-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdw-json.ts
More file actions
568 lines (516 loc) · 16.8 KB
/
dw-json.ts
File metadata and controls
568 lines (516 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
* Copyright (c) 2025, Salesforce, Inc.
* SPDX-License-Identifier: Apache-2
* For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0
*/
/**
* dw.json configuration file loading.
*
* This module provides utilities for loading B2C Commerce configuration from
* dw.json files, the standard configuration format used by B2C development tools.
*
* @module config
*/
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import type {AuthMethod} from '../auth/types.js';
import {getLogger} from '../logging/logger.js';
import {normalizeConfigKeys} from './mapping.js';
/**
* Configuration structure for dw.json after key normalization.
*
* All keys are normalized to camelCase by `normalizeConfigKeys()` when loading.
* Both camelCase and kebab-case are accepted in the raw file; the interface
* documents the canonical (post-normalization) field names.
*
* Legacy aliases (e.g., `server`, `secureHostname`, `passphrase`, `selfsigned`,
* `cloudOrigin`, `scapi-shortcode`) are also accepted and mapped to their
* canonical names during normalization.
*/
export interface DwJsonConfig {
/** Instance name (for multi-config files) */
name?: string;
/** Whether this config is active (for multi-config files) */
active?: boolean;
/** B2C instance hostname */
hostname?: string;
/** Code version for deployments */
codeVersion?: string;
/** Username for Basic auth (WebDAV) */
username?: string;
/** Password/access-key for Basic auth (WebDAV) */
password?: string;
/** OAuth client ID */
clientId?: string;
/** OAuth client secret */
clientSecret?: string;
/** OAuth scopes */
oauthScopes?: string[];
/** SLAS client ID for shopper authentication */
slasClientId?: string;
/** SLAS client secret for private shopper clients */
slasClientSecret?: string;
/** B2C Commerce site/channel ID */
siteId?: string;
/** SCAPI short code */
shortCode?: string;
/** Alternate hostname for WebDAV (if different from main hostname) */
webdavHostname?: string;
/** Allowed authentication methods in priority order */
authMethods?: AuthMethod[];
/** Account Manager hostname for OAuth */
accountManagerHost?: string;
/** MRT project slug */
mrtProject?: string;
/** MRT environment name (e.g., staging, production) */
mrtEnvironment?: string;
/** MRT API key */
mrtApiKey?: string;
/** MRT cloud origin URL */
mrtOrigin?: string;
/** Tenant/Organization ID for SCAPI */
tenantId?: string;
/** ODS API hostname */
sandboxApiHost?: string;
/** Default ODS realm for sandbox operations */
realm?: string;
/** Whether to auto-start code upload/sync in IDE extensions */
autoUpload?: boolean;
/** Cartridge names to include in deploy/watch (string with colon/comma separators, or array) */
cartridges?: string | string[];
/** Default content library ID for content export/list commands */
contentLibrary?: string;
/** Catalog IDs for WebDAV browsing */
catalogs?: string[];
/** Library IDs for WebDAV browsing */
libraries?: string[];
/** Optional CIP analytics host override */
cipHost?: string;
/** Path to PKCS12 certificate file for mTLS (two-factor auth) */
certificate?: string;
/** Passphrase for the certificate */
certificatePassphrase?: string;
/** Whether to skip SSL/TLS certificate verification (self-signed certs) */
selfSigned?: boolean;
/**
* Safety configuration for this instance.
*
* @example
* ```json
* {
* "safety": {
* "level": "NO_UPDATE",
* "confirm": true,
* "rules": [
* { "job": "sfcc-site-archive-export", "action": "allow" },
* { "command": "sandbox:*", "action": "confirm" }
* ]
* }
* }
* ```
*/
safety?: {
level?: string;
confirm?: boolean;
rules?: Array<{
method?: string;
path?: string;
job?: string;
command?: string;
action: string;
}>;
};
}
/**
* dw.json with multi-config support (configs array).
*/
export interface DwJsonMultiConfig extends DwJsonConfig {
/** Array of named instance configurations */
configs?: DwJsonConfig[];
}
/**
* Options for loading dw.json.
*/
export interface LoadDwJsonOptions {
/** Named instance to select from configs array */
instance?: string;
/** Explicit path to dw.json (skips searching if provided) */
path?: string;
/** Starting directory for search (defaults to cwd) */
projectDirectory?: string;
/** @deprecated Use projectDirectory instead */
workingDirectory?: string;
}
/**
* Result of loading dw.json configuration.
*/
export interface LoadDwJsonResult {
/** The parsed configuration */
config: DwJsonConfig;
/** The path to the dw.json file that was loaded */
path: string;
}
/**
* Finds dw.json by searching upward from the starting directory.
*
* @param projectDirectory - Directory to start searching from (defaults to cwd)
* @returns Path to dw.json if found, undefined otherwise
*
* @example
* const dwPath = findDwJson();
* if (dwPath) {
* console.log(`Found dw.json at ${dwPath}`);
* }
*/
export async function findDwJson(projectDirectory: string = process.cwd()): Promise<string | undefined> {
let dir = projectDirectory;
const root = path.parse(dir).root;
while (dir !== root) {
const dwJsonPath = path.join(dir, 'dw.json');
try {
await fsp.access(dwJsonPath);
return dwJsonPath;
} catch {
// File doesn't exist, continue searching
}
dir = path.dirname(dir);
}
return undefined;
}
/**
* Selects the appropriate config from a multi-config dw.json.
*
* Selection priority:
* 1. Named instance (if `instance` option provided)
* 2. Config marked as `active: true`
* 3. Root-level config
*/
function selectConfig(json: DwJsonMultiConfig, instanceName?: string): DwJsonConfig | undefined {
const logger = getLogger();
// Single config or no configs array
if (!Array.isArray(json.configs) || json.configs.length === 0) {
logger.trace(
{selection: 'root', instanceName: json.name},
`[DwJsonSource] Selected config "${json.name ?? 'root'}" (single config)`,
);
return json;
}
// Find by instance name
if (instanceName) {
// Check root first
if (json.name === instanceName) {
logger.trace(
{selection: 'named', instanceName},
`[DwJsonSource] Selected config "${instanceName}" by name (root)`,
);
return json;
}
// Then check configs array
const found = json.configs.find((c) => c.name === instanceName);
if (found) {
logger.trace({selection: 'named', instanceName}, `[DwJsonSource] Selected config "${instanceName}" by name`);
return found;
}
// Instance explicitly requested but not found - return undefined
logger.trace({requestedInstance: instanceName}, `[DwJsonSource] Named instance "${instanceName}" not found`);
return undefined;
}
// Find active config
if (json.active === false) {
// Root is inactive, look for active in configs
const activeConfig = json.configs.find((c) => c.active === true);
if (activeConfig) {
logger.trace(
{selection: 'active', instanceName: activeConfig.name},
`[DwJsonSource] Selected config "${activeConfig.name}" by active flag`,
);
return activeConfig;
}
}
// Default to root config
logger.trace(
{selection: 'root', instanceName: json.name},
`[DwJsonSource] Selected config "${json.name ?? 'root'}" (default to root)`,
);
return json;
}
/**
* Load the raw dw.json file without selecting a specific instance.
*
* This is useful for instance management operations that need to work
* with the full configs array.
*
* @param options - Loading options
* @returns The raw multi-config structure and path, or undefined if not found
*/
export async function loadFullDwJson(
options: LoadDwJsonOptions = {},
): Promise<{config: DwJsonMultiConfig; path: string} | undefined> {
const logger = getLogger();
const dwJsonPath =
options.path ?? path.join(options.projectDirectory ?? options.workingDirectory ?? process.cwd(), 'dw.json');
logger.trace({path: dwJsonPath}, '[DwJsonSource] Checking for config file');
try {
await fsp.access(dwJsonPath);
} catch {
logger.trace({path: dwJsonPath}, '[DwJsonSource] No config file found');
return undefined;
}
try {
const content = await fsp.readFile(dwJsonPath, 'utf8');
const json = JSON.parse(content) as DwJsonMultiConfig;
return {config: json, path: dwJsonPath};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logger.trace({path: dwJsonPath, error: message}, '[DwJsonSource] Failed to parse config file');
throw error;
}
}
/**
* Save a dw.json configuration to disk.
*
* @param config - The configuration to save
* @param filePath - Path to save to
*/
export async function saveDwJson(config: DwJsonMultiConfig, filePath: string): Promise<void> {
const content = JSON.stringify(config, null, 2) + '\n';
await fsp.writeFile(filePath, content, 'utf8');
}
/**
* Options for adding an instance.
*/
export interface AddInstanceOptions {
/** Path to dw.json (defaults to ./dw.json) */
path?: string;
/** Starting directory for search */
projectDirectory?: string;
/** @deprecated Use projectDirectory instead */
workingDirectory?: string;
/** Whether to set as active instance */
setActive?: boolean;
}
/**
* Add a new instance to dw.json.
*
* If dw.json doesn't exist, creates a new one. If an instance with the same
* name already exists, throws an error.
*
* @param instance - The instance configuration to add
* @param options - Options for adding
* @throws Error if instance with same name already exists
*/
export async function addInstance(instance: DwJsonConfig, options: AddInstanceOptions = {}): Promise<void> {
const dwJsonPath =
options.path ?? path.join(options.projectDirectory || options.workingDirectory || process.cwd(), 'dw.json');
let existing: DwJsonMultiConfig = {};
try {
const content = await fsp.readFile(dwJsonPath, 'utf8');
existing = JSON.parse(content) as DwJsonMultiConfig;
} catch (error) {
// File doesn't exist - start with empty config
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error;
}
}
// Check if instance name already exists
const instanceName = instance.name;
if (!instanceName) {
throw new Error('Instance must have a name');
}
// Check root config
if (existing.name === instanceName) {
throw new Error(`Instance "${instanceName}" already exists`);
}
// Check configs array
if (existing.configs?.some((c) => c.name === instanceName)) {
throw new Error(`Instance "${instanceName}" already exists`);
}
// Handle setActive - clear other active flags
if (options.setActive) {
instance.active = true;
// Clear active on root if it has it
if (existing.active !== undefined) {
existing.active = false;
}
// Clear active on all other configs
if (existing.configs) {
for (const c of existing.configs) {
if (c.active !== undefined) {
c.active = false;
}
}
}
}
// Initialize configs array if needed
if (!existing.configs) {
existing.configs = [];
}
// Add the new instance
existing.configs.push(instance);
await saveDwJson(existing, dwJsonPath);
}
/**
* Options for removing an instance.
*/
export interface RemoveInstanceOptions {
/** Path to dw.json */
path?: string;
/** Starting directory for search */
projectDirectory?: string;
/** @deprecated Use projectDirectory instead */
workingDirectory?: string;
}
/**
* Remove an instance from dw.json.
*
* @param name - Name of the instance to remove
* @param options - Options for removal
* @throws Error if instance not found or dw.json doesn't exist
*/
export async function removeInstance(name: string, options: RemoveInstanceOptions = {}): Promise<void> {
const dwJsonPath =
options.path ?? path.join(options.projectDirectory || options.workingDirectory || process.cwd(), 'dw.json');
let content: string;
try {
content = await fsp.readFile(dwJsonPath, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error('No dw.json file found');
}
throw error;
}
const existing = JSON.parse(content) as DwJsonMultiConfig;
// Check if trying to remove root config
if (existing.name === name) {
throw new Error(`Cannot remove root instance "${name}". Edit dw.json manually to remove root config.`);
}
// Find and remove from configs array
if (!existing.configs || !existing.configs.some((c) => c.name === name)) {
throw new Error(`Instance "${name}" not found`);
}
existing.configs = existing.configs.filter((c) => c.name !== name);
await saveDwJson(existing, dwJsonPath);
}
/**
* Options for setting active instance.
*/
export interface SetActiveInstanceOptions {
/** Path to dw.json */
path?: string;
/** Starting directory for search */
projectDirectory?: string;
/** @deprecated Use projectDirectory instead */
workingDirectory?: string;
}
/**
* Set an instance as the active default.
*
* @param name - Name of the instance to set as active
* @param options - Options
* @throws Error if instance not found or dw.json doesn't exist
*/
export async function setActiveInstance(name: string, options: SetActiveInstanceOptions = {}): Promise<void> {
const dwJsonPath =
options.path ?? path.join(options.projectDirectory || options.workingDirectory || process.cwd(), 'dw.json');
let content: string;
try {
content = await fsp.readFile(dwJsonPath, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error('No dw.json file found');
}
throw error;
}
const existing = JSON.parse(content) as DwJsonMultiConfig;
// Find the target instance
let found = false;
// Check root config
if (existing.name === name) {
found = true;
existing.active = true;
} else if (existing.active !== undefined) {
existing.active = false;
}
// Check and update configs array
if (existing.configs) {
for (const c of existing.configs) {
if (c.name === name) {
found = true;
c.active = true;
} else if (c.active !== undefined) {
c.active = false;
}
}
}
if (!found) {
throw new Error(`Instance "${name}" not found`);
}
await saveDwJson(existing, dwJsonPath);
}
/**
* Loads configuration from a dw.json file.
*
* If an explicit path is provided, uses that file. Otherwise, looks for dw.json
* in the projectDirectory (or cwd). Does NOT search parent directories.
*
* Use `findDwJson()` if you need to search upward through parent directories.
*
* @param options - Loading options
* @returns The parsed config with its path, or undefined if no dw.json found
*
* @example
* // Load from ./dw.json (current directory)
* const result = loadDwJson();
* if (result) {
* console.log(`Loaded from ${result.path}`);
* console.log(result.config.hostname);
* }
*
* // Load from specific directory
* const result = loadDwJson({ projectDirectory: '/path/to/project' });
*
* // Use named instance
* const result = loadDwJson({ instance: 'staging' });
*
* // Explicit path
* const result = loadDwJson({ path: './config/dw.json' });
*/
export async function loadDwJson(options: LoadDwJsonOptions = {}): Promise<LoadDwJsonResult | undefined> {
const logger = getLogger();
// If explicit path provided, use it. Otherwise default to ./dw.json (no upward search)
const dwJsonPath =
options.path ?? path.join(options.projectDirectory || options.workingDirectory || process.cwd(), 'dw.json');
logger.trace({path: dwJsonPath}, '[DwJsonSource] Checking for config file');
try {
await fsp.access(dwJsonPath);
} catch {
logger.trace({path: dwJsonPath}, '[DwJsonSource] No config file found');
return undefined;
}
try {
const content = await fsp.readFile(dwJsonPath, 'utf8');
const raw = JSON.parse(content) as Record<string, unknown>;
// Normalize root-level keys to camelCase
const normalized = normalizeConfigKeys(raw) as DwJsonMultiConfig;
// Normalize keys in each configs[] item
if (Array.isArray(normalized.configs)) {
normalized.configs = normalized.configs.map(
(item) => normalizeConfigKeys(item as Record<string, unknown>) as DwJsonConfig,
);
}
const config = selectConfig(normalized, options.instance);
if (!config) {
return undefined;
}
return {
config,
path: dwJsonPath,
};
} catch (error) {
// Invalid JSON or read error - log at trace level and re-throw
// The resolver will catch this and create a SOURCE_ERROR warning
const message = error instanceof Error ? error.message : String(error);
logger.trace({path: dwJsonPath, error: message}, '[DwJsonSource] Failed to parse config file');
throw error;
}
}