forked from forcedotcom/salesforcedx-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectGenerator.ts
More file actions
680 lines (617 loc) · 19.1 KB
/
Copy pathprojectGenerator.ts
File metadata and controls
680 lines (617 loc) · 19.1 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import * as path from 'path';
import { CreateUtil } from '../utils';
import { GeneratorContext, ProjectOptions } from '../utils/types';
import {
BUILT_IN_FULL_TEMPLATES,
FULL_TEMPLATE_DEFAULT_NAMES,
generateBuiltInFullTemplate,
renderEjsFile,
} from '../utils/uiBundleTemplateUtils';
import { BaseGenerator } from './baseGenerator';
const VALID_PROJECT_TEMPLATES = [
'standard',
'empty',
'analytics',
'reactinternalapp',
'reactexternalapp',
'angularinternalapp',
'angularexternalapp',
'agent',
'nativemobile',
] as const;
const GITIGNORE = 'gitignore';
const HUSKY_FOLDER = '.husky';
const huskyhookarray = ['pre-commit'];
const vscodearray = ['extensions', 'launch', 'settings'];
const standardfolderarray = [
'applications',
'aura',
'classes',
'contentassets',
'flexipages',
'layouts',
'lwc',
'objects',
'permissionsets',
'staticresources',
'tabs',
'triggers',
];
const filestocopy = [
'.forceignore',
GITIGNORE,
'.prettierignore',
'.prettierrc',
'jest.config.js',
'package.json',
];
const agentFilesToCopy = [
'.forceignore',
GITIGNORE,
'.prettierignore',
'.prettierrc',
'package.json',
];
const emptyfolderarray = ['aura', 'lwc'];
const analyticsfolderarray = ['aura', 'classes', 'lwc', 'waveTemplates'];
const analyticsVscodeExt = 'salesforce.analyticsdx-vscode';
const agentfolderarray = [
'aiAuthoringBundles',
'bots',
'classes',
'flows',
'genAiPlannerBundles',
'genAiPromptTemplates',
'permissionsetgroups',
'permissionsets',
];
const agentMetadataMap: Array<{ src: string; destDir: string }> = [
{
src: 'aab/Local_Info_Agent.bundle-meta.xml',
destDir: 'aiAuthoringBundles/Local_Info_Agent',
},
{
src: 'aab/Local_Info_Agent.agent',
destDir: 'aiAuthoringBundles/Local_Info_Agent',
},
{ src: 'apex/CheckWeather.cls', destDir: 'classes' },
{ src: 'apex/CheckWeather.cls-meta.xml', destDir: 'classes' },
{ src: 'apex/CurrentDate.cls', destDir: 'classes' },
{ src: 'apex/CurrentDate.cls-meta.xml', destDir: 'classes' },
{ src: 'apex/CurrentDateTest.cls', destDir: 'classes' },
{ src: 'apex/CurrentDateTest.cls-meta.xml', destDir: 'classes' },
{ src: 'apex/WeatherService.cls', destDir: 'classes' },
{ src: 'apex/WeatherService.cls-meta.xml', destDir: 'classes' },
{ src: 'apex/WeatherServiceTest.cls', destDir: 'classes' },
{ src: 'apex/WeatherServiceTest.cls-meta.xml', destDir: 'classes' },
{ src: 'flow/Get_Resort_Hours.flow-meta.xml', destDir: 'flows' },
{
src: 'gapt/Get_Event_Info.genAiPromptTemplate-meta.xml',
destDir: 'genAiPromptTemplates',
},
{ src: 'ps/Resort_Agent.permissionset-meta.xml', destDir: 'permissionsets' },
{ src: 'ps/Resort_Admin.permissionset-meta.xml', destDir: 'permissionsets' },
{
src: 'psg/AFDX_Agent_Perms.permissionsetgroup-meta.xml',
destDir: 'permissionsetgroups',
},
{
src: 'psg/AFDX_User_Perms.permissionsetgroup-meta.xml',
destDir: 'permissionsetgroups',
},
];
export default class ProjectGenerator extends BaseGenerator<ProjectOptions> {
constructor(
options: ProjectOptions,
context?: GeneratorContext,
cwd?: string
) {
super(options, context, cwd);
this.sourceRootWithPartialPath('project');
}
private async extendJSON(
filepath: string,
replacer?: (this: any, key: string, value: any) => any
) {
const originalContent = JSON.parse(
await this._fs.promises.readFile(filepath, 'utf8').catch(() => '{}')
);
const newContent = JSON.stringify(originalContent, replacer, 2);
await this._fs.promises.writeFile(filepath, newContent);
}
/**
* Returns template path for primary; if it doesn't exist, returns fallback path.
* Used so reactinternalapp/reactexternalapp can omit shared files and fall back to standard.
*/
private templatePathWithFallback(primary: string, fallback: string): string {
const primaryPath = this.templatePath(primary);
return this._fs.existsSync(primaryPath)
? primaryPath
: this.templatePath(fallback);
}
/**
* Returns the appropriate template path based on whether TypeScript is enabled.
* TypeScript-specific templates are organized in a typescript/ subdirectory.
* Only files that have TypeScript-specific variants are looked up there.
*/
private getTemplatePath(
file: string,
isTypeScript: boolean
): string {
// Files that have TypeScript-specific variants
const tsSpecificFiles = [
'package.json',
'.forceignore',
GITIGNORE,
'project.eslint.config.js',
'settings.json'
];
const hasTypescriptVariant = tsSpecificFiles.includes(file);
const subdir = isTypeScript && hasTypescriptVariant ? 'typescript' : '';
return this.templatePath(subdir, file);
}
/**
* Generates TypeScript configuration file if TypeScript is enabled.
*/
private async generateTypeScriptConfig(
isTypeScript: boolean,
projectname: string,
defaultpackagedir: string
): Promise<void> {
if (isTypeScript) {
await this.render(
this.templatePath('tsconfig.json'),
this.destinationPath(
path.join(this.outputdir, projectname, 'tsconfig.json')
),
{ defaultpackagedir }
);
}
}
/**
* Generates ESLint configuration file with appropriate template for JS or TS.
*/
private async generateEslintConfig(
isTypeScript: boolean,
projectname: string
): Promise<void> {
await this.render(
this.getTemplatePath('project.eslint.config.js', isTypeScript),
this.destinationPath(
path.join(this.outputdir, projectname, 'eslint.config.js')
),
{}
);
}
/**
* Generates VSCode settings with TypeScript-specific configuration if needed.
*/
private async generateVSCodeSettings(
isTypeScript: boolean,
projectname: string
): Promise<void> {
for (const file of vscodearray) {
const templateFile = `${file}.json`;
// Use TypeScript directory for settings file when TypeScript is enabled
const templatePath = isTypeScript && file === 'settings'
? this.getTemplatePath(templateFile, true)
: this.templatePath(templateFile);
await this.render(
templatePath,
this.destinationPath(
path.join(this.outputdir, projectname, '.vscode', `${file}.json`)
),
{}
);
}
}
/**
* Copies project root level files with TypeScript-specific variants when applicable.
*/
private async copyProjectFiles(
isTypeScript: boolean,
projectname: string
): Promise<void> {
for (const file of filestocopy) {
const out = file === GITIGNORE ? `.${file}` : file;
await this.render(
this.getTemplatePath(file, isTypeScript),
this.destinationPath(path.join(this.outputdir, projectname, out)),
{}
);
}
}
public validateOptions(): void {
CreateUtil.checkInputs(this.options.template);
if (
!VALID_PROJECT_TEMPLATES.includes(
this.options.template as (typeof VALID_PROJECT_TEMPLATES)[number]
)
) {
throw new Error(
`Invalid project template: ${
this.options.template
}. Valid options: ${VALID_PROJECT_TEMPLATES.join(', ')}`
);
}
// Validate lwcLanguage if provided
if (
this.options.lwcLanguage &&
!['javascript', 'typescript'].includes(this.options.lwcLanguage)
) {
throw new Error(
`Invalid lwcLanguage value: '${this.options.lwcLanguage}'. Must be 'javascript' or 'typescript'.`
);
}
}
public async generate(): Promise<void> {
// Re-apply source root so customTemplatesRootPath (set in run()) is used when provided
this.sourceRootWithPartialPath('project');
const {
projectname,
template,
defaultpackagedir,
manifest,
ns,
loginurl,
lwcLanguage,
} = this.options;
const isTypeScript = lwcLanguage === 'typescript';
const folderlayout = [
this.outputdir,
projectname,
defaultpackagedir,
'main',
'default',
];
const scratchDefFile = `${template}/ScratchDef.json`;
const manifestFile = `${template}/Manifest.xml`;
const soqlQueryFile = 'account.soql';
const anonApexFile = 'hello.apex';
await this.render(
this.templatePathWithFallback(scratchDefFile, 'standard/ScratchDef.json'),
this.destinationPath(
path.join(
this.outputdir,
projectname,
'config',
'project-scratch-def.json'
)
),
{ company: (process.env.USER || 'Demo') + ' company' }
);
await this.render(
this.templatePathWithFallback(
`${template}/README.md`,
'standard/README.md'
),
this.destinationPath(path.join(this.outputdir, projectname, 'README.md')),
{ projectname }
);
await this.render(
this.templatePath('sfdx-project.json'),
this.destinationPath(
path.join(this.outputdir, projectname, 'sfdx-project.json')
),
{
defaultpackagedir,
namespace: ns,
loginurl,
apiversion: this.apiversion,
name: projectname,
lwcLanguage,
}
);
if (manifest === true) {
await this.render(
this.templatePathWithFallback(manifestFile, 'standard/Manifest.xml'),
this.destinationPath(
path.join(this.outputdir, projectname, 'manifest', 'package.xml')
),
{ apiversion: this.apiversion }
);
}
if (template === 'standard') {
await this.makeEmptyFolders(folderlayout, standardfolderarray);
// Add Husky directory and hooks
this._createHuskyConfig(path.join(this.outputdir, projectname));
// VSCode config files
await this.generateVSCodeSettings(isTypeScript, projectname);
// ESLint config
await this.generateEslintConfig(isTypeScript, projectname);
// SOQL sample file
await this.render(
this.templatePath(path.join(template, soqlQueryFile)),
this.destinationPath(
path.join(
this.outputdir,
projectname,
'scripts',
'soql',
soqlQueryFile
)
),
{}
);
// Apex sample script
await this.render(
this.templatePath(path.join(template, anonApexFile)),
this.destinationPath(
path.join(
this.outputdir,
projectname,
'scripts',
'apex',
anonApexFile
)
),
{}
);
// Copy project root level files
await this.copyProjectFiles(isTypeScript, projectname);
// Generate TypeScript configuration files if TypeScript is selected
await this.generateTypeScriptConfig(isTypeScript, projectname, defaultpackagedir);
}
if (template === 'empty') {
await this.makeEmptyFolders(folderlayout, emptyfolderarray);
// For TypeScript projects, generate full toolchain
if (isTypeScript) {
// Add Husky directory and hooks
this._createHuskyConfig(path.join(this.outputdir, projectname));
// VSCode config files
await this.generateVSCodeSettings(isTypeScript, projectname);
// ESLint config
await this.generateEslintConfig(isTypeScript, projectname);
// Copy project root level files (includes package.json, .gitignore, etc.)
await this.copyProjectFiles(isTypeScript, projectname);
// Generate TypeScript configuration
await this.generateTypeScriptConfig(isTypeScript, projectname, defaultpackagedir);
} else {
// For JavaScript projects, just copy .forceignore
await this.render(
this.templatePath('.forceignore'),
this.destinationPath(
path.join(this.outputdir, projectname, '.forceignore')
),
{}
);
}
}
if (template === 'nativemobile') {
await this.makeEmptyFolders(folderlayout, emptyfolderarray);
await this.render(
this.templatePath('.forceignore'),
this.destinationPath(
path.join(this.outputdir, projectname, '.forceignore')
),
{}
);
// Derive a camelCase app name from the project name for CAMA metadata
const appName =
projectname.charAt(0).toLowerCase() +
projectname.slice(1).replace(/[^a-zA-Z0-9]/g, '');
// Human-readable label: insert spaces before uppercase runs and digits
const appLabel = projectname
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([a-zA-Z])(\d)/g, '$1 $2')
.replace(/[_-]/g, ' ')
.trim()
.toLowerCase();
const camaData = { appName, appLabel, projectname };
const ecBase = path.join(
...folderlayout,
'digitalExperiences',
'experiencecontainer',
appName
);
// DigitalExperienceBundle meta XML
await this.render(
this.templatePath('nativemobile/digitalExperience-meta.xml'),
this.destinationPath(
path.join(ecBase, `${appName}.digitalExperience-meta.xml`)
),
camaData
);
// EC Definition
await this.render(
this.templatePath('nativemobile/ecDefinition-meta.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaECDefinition',
appName,
'_meta.json'
)
),
camaData
);
await this.render(
this.templatePath('nativemobile/ecDefinition-content.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaECDefinition',
appName,
'content.json'
)
),
camaData
);
// App Metadata
await this.render(
this.templatePath('nativemobile/appMetadata-meta.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaAppMetadata',
'appMetadata',
'_meta.json'
)
),
camaData
);
await this.render(
this.templatePath('nativemobile/appMetadata-content.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaAppMetadata',
'appMetadata',
'content.json'
)
),
camaData
);
// Build Metadata
await this.render(
this.templatePath('nativemobile/buildMetadata-meta.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaBuildMetadata',
'buildMetadata',
'_meta.json'
)
),
camaData
);
await this.render(
this.templatePath('nativemobile/buildMetadata-content.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaBuildMetadata',
'buildMetadata',
'content.json'
)
),
camaData
);
// Home Screen
await this.render(
this.templatePath('nativemobile/homeScreen-meta.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaScreen',
'homeScreen',
'_meta.json'
)
),
camaData
);
await this.render(
this.templatePath('nativemobile/homeScreen-content.json'),
this.destinationPath(
path.join(
ecBase,
'experience__camaScreen',
'homeScreen',
'content.json'
)
),
camaData
);
}
if (template === 'analytics') {
await this.makeEmptyFolders(folderlayout, analyticsfolderarray);
// Add Husky directory and hooks
this._createHuskyConfig(path.join(this.outputdir, projectname));
// VSCode config files
await this.generateVSCodeSettings(isTypeScript, projectname);
// add the analytics vscode extension to the recommendations
await this.extendJSON(
path.join(this.outputdir, projectname, '.vscode', 'extensions.json'),
(key: string, value: unknown) => {
if (
key === 'recommendations' &&
Array.isArray(value) &&
!value.some((n) => n === analyticsVscodeExt)
) {
value.push(analyticsVscodeExt);
}
return value;
}
);
// ESLint config
await this.generateEslintConfig(isTypeScript, projectname);
// Copy project root level files
await this.copyProjectFiles(isTypeScript, projectname);
// Generate TypeScript configuration files if TypeScript is selected
await this.generateTypeScriptConfig(isTypeScript, projectname, defaultpackagedir);
}
if (template === 'agent') {
await this.makeEmptyFolders(folderlayout, agentfolderarray);
for (const file of vscodearray) {
await this.render(
this.templatePath(`${file}.json`),
this.destinationPath(
path.join(this.outputdir, projectname, '.vscode', `${file}.json`)
),
{}
);
}
for (const file of agentFilesToCopy) {
const out = file === GITIGNORE ? `.${file}` : file;
await this.render(
this.templatePathWithFallback(path.join(template, file), file),
this.destinationPath(path.join(this.outputdir, projectname, out)),
{}
);
}
for (const { src, destDir } of agentMetadataMap) {
const fileName = path.basename(src);
await this.render(
this.templatePath(path.join('agent', 'md', src)),
this.destinationPath(path.join(...folderlayout, destDir, fileName)),
{}
);
}
}
if (BUILT_IN_FULL_TEMPLATES.has(template)) {
await generateBuiltInFullTemplate(template, projectname, {
templateDir: this.templatePath(FULL_TEMPLATE_DEFAULT_NAMES[template]?.base ?? template),
projectDir: path.join(this.outputdir, projectname),
defaultpackagedir,
ns,
loginurl,
apiversion: this.apiversion,
renderEjs: renderEjsFile,
onFileCreated: (destPath) => this.registerChange(destPath),
});
}
}
private registerChange(destPath: string): void {
const relativePath = path.relative(process.cwd(), destPath);
this.changes.created.push(relativePath);
}
private async _createHuskyConfig(projectRootDir: string) {
const huskyDirPath = path.join(projectRootDir, HUSKY_FOLDER);
if (!this._fs.existsSync(huskyDirPath)) {
this._fs.mkdirSync(huskyDirPath);
}
for (const file of huskyhookarray) {
await this.render(
this.templatePath(path.join(HUSKY_FOLDER, file)),
this.destinationPath(path.join(huskyDirPath, file)),
{}
);
}
}
private async makeEmptyFolders(
toplevelfolders: string[],
metadatafolders: string[]
) {
for (const folder of metadatafolders) {
await this._fs.promises.mkdir(path.join(...toplevelfolders, folder), {
recursive: true,
});
}
}
}