esa-cli 0.0.2-beta.2 → 0.0.2-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/commands/commit/index.js +48 -115
  2. package/dist/commands/commit/prodBuild.js +2 -3
  3. package/dist/commands/common/constant.js +0 -19
  4. package/dist/commands/common/utils.js +416 -0
  5. package/dist/commands/config.js +1 -1
  6. package/dist/commands/deploy/helper.js +51 -72
  7. package/dist/commands/deploy/index.js +50 -188
  8. package/dist/commands/deployments/delete.js +32 -22
  9. package/dist/commands/deployments/index.js +2 -2
  10. package/dist/commands/deployments/list.js +22 -38
  11. package/dist/commands/dev/build.js +3 -3
  12. package/dist/commands/dev/doProcess.js +5 -5
  13. package/dist/commands/dev/ew2/cacheService.js +33 -0
  14. package/dist/commands/dev/ew2/devEntry.js +2 -1
  15. package/dist/commands/dev/ew2/devPack.js +39 -43
  16. package/dist/commands/dev/ew2/kvService.js +27 -0
  17. package/dist/commands/dev/ew2/mock/cache.js +99 -15
  18. package/dist/commands/dev/ew2/mock/kv.js +142 -21
  19. package/dist/commands/dev/ew2/server.js +165 -29
  20. package/dist/commands/dev/index.js +17 -17
  21. package/dist/commands/dev/mockWorker/devPack.js +35 -24
  22. package/dist/commands/dev/mockWorker/server.js +7 -6
  23. package/dist/commands/domain/add.js +2 -2
  24. package/dist/commands/domain/delete.js +7 -7
  25. package/dist/commands/domain/index.js +2 -2
  26. package/dist/commands/domain/list.js +10 -10
  27. package/dist/commands/init/helper.js +759 -0
  28. package/dist/commands/init/index.js +88 -220
  29. package/dist/commands/init/snippets/nextjs/next.config.mjs +6 -0
  30. package/dist/commands/init/snippets/nextjs/next.config.ts +7 -0
  31. package/dist/commands/init/snippets/react-router/react-router.config.ts +7 -0
  32. package/dist/commands/init/template.jsonc +84 -0
  33. package/dist/commands/init/types.js +1 -0
  34. package/dist/commands/lang.js +2 -2
  35. package/dist/commands/login/index.js +74 -34
  36. package/dist/commands/logout.js +5 -5
  37. package/dist/commands/route/add.js +105 -49
  38. package/dist/commands/route/delete.js +33 -27
  39. package/dist/commands/route/helper.js +123 -0
  40. package/dist/commands/route/index.js +2 -2
  41. package/dist/commands/route/list.js +56 -17
  42. package/dist/commands/routine/delete.js +2 -2
  43. package/dist/commands/routine/index.js +2 -2
  44. package/dist/commands/routine/list.js +43 -37
  45. package/dist/commands/site/index.js +1 -1
  46. package/dist/commands/site/list.js +6 -7
  47. package/dist/commands/utils.js +59 -23
  48. package/dist/components/descriptionInput.js +1 -1
  49. package/dist/components/filterSelector.js +1 -1
  50. package/dist/components/mutiLevelSelect.js +43 -55
  51. package/dist/components/mutiSelectTable.js +1 -1
  52. package/dist/components/routeBuilder.js +68 -0
  53. package/dist/components/selectInput.js +2 -3
  54. package/dist/components/selectItem.js +1 -1
  55. package/dist/docs/Commands_en.md +142 -131
  56. package/dist/docs/Commands_zh_CN.md +139 -127
  57. package/dist/i18n/index.js +2 -2
  58. package/dist/i18n/locales.json +435 -23
  59. package/dist/index.js +27 -20
  60. package/dist/libs/api.js +32 -9
  61. package/dist/libs/apiService.js +267 -88
  62. package/dist/libs/git/index.js +86 -9
  63. package/dist/libs/interface.js +0 -1
  64. package/dist/libs/logger.js +162 -10
  65. package/dist/libs/service.js +2 -2
  66. package/dist/libs/templates/index.js +3 -2
  67. package/dist/utils/checkAssetsExist.js +80 -0
  68. package/dist/utils/checkDevPort.js +3 -17
  69. package/dist/utils/checkEntryFileExist.js +10 -0
  70. package/dist/utils/checkIsRoutineCreated.js +28 -27
  71. package/dist/utils/checkVersion.js +119 -1
  72. package/dist/utils/command.js +149 -0
  73. package/dist/utils/compress.js +136 -0
  74. package/dist/utils/download.js +182 -0
  75. package/dist/utils/fileMd5.js +1 -1
  76. package/dist/utils/fileUtils/base.js +1 -1
  77. package/dist/utils/fileUtils/index.js +136 -44
  78. package/dist/utils/installDeno.js +8 -8
  79. package/dist/utils/installEw2.js +7 -7
  80. package/dist/utils/openInBrowser.js +1 -1
  81. package/dist/utils/prompt.js +97 -0
  82. package/package.json +19 -12
@@ -0,0 +1,759 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { execSync } from 'child_process';
11
+ import path from 'path';
12
+ import { exit } from 'process';
13
+ import { confirm as clackConfirm, isCancel, log, outro } from '@clack/prompts';
14
+ import chalk from 'chalk';
15
+ import fs from 'fs-extra';
16
+ import Haikunator from 'haikunator';
17
+ import t from '../../i18n/index.js';
18
+ import logger from '../../libs/logger.js';
19
+ import Template from '../../libs/templates/index.js';
20
+ import { execCommand } from '../../utils/command.js';
21
+ import { getDirName } from '../../utils/fileUtils/base.js';
22
+ import { generateConfigFile, getCliConfig, getProjectConfig, getTemplatesConfig, templateHubPath, updateProjectConfigFile } from '../../utils/fileUtils/index.js';
23
+ import promptParameter from '../../utils/prompt.js';
24
+ import { commitAndDeployVersion } from '../common/utils.js';
25
+ export const getTemplateInstances = (templateHubPath) => {
26
+ return fs
27
+ .readdirSync(templateHubPath)
28
+ .filter((item) => {
29
+ const itemPath = path.join(templateHubPath, item);
30
+ return (fs.statSync(itemPath).isDirectory() &&
31
+ !['.git', 'node_modules', 'lib'].includes(item));
32
+ })
33
+ .map((item) => {
34
+ var _a;
35
+ const projectPath = path.join(templateHubPath, item);
36
+ const projectConfig = getProjectConfig(projectPath);
37
+ const templateName = (_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _a !== void 0 ? _a : '';
38
+ return new Template(projectPath, templateName);
39
+ });
40
+ };
41
+ export const transferTemplatesToSelectItem = (configs, templateInstanceList, lang) => {
42
+ if (!configs)
43
+ return [];
44
+ return configs.map((config) => {
45
+ var _a, _b;
46
+ const title = config.Title_EN;
47
+ const value = (_b = (_a = templateInstanceList.find((template) => {
48
+ return title === template.title;
49
+ })) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : '';
50
+ const children = transferTemplatesToSelectItem(config.children, templateInstanceList, lang);
51
+ return {
52
+ label: lang === 'en' ? config.Title_EN : config.Title_ZH,
53
+ value: value,
54
+ hint: lang === 'en' ? config.Desc_EN : config.Desc_ZH,
55
+ children
56
+ };
57
+ });
58
+ };
59
+ export const preInstallDependencies = (targetPath) => __awaiter(void 0, void 0, void 0, function* () {
60
+ const packageJsonPath = path.join(targetPath, 'package.json');
61
+ if (fs.existsSync(packageJsonPath)) {
62
+ logger.log(t('init_install_dependence').d('⌛️ Installing dependencies...'));
63
+ execSync('npm install', { stdio: 'inherit', cwd: targetPath });
64
+ logger.success(t('init_install_dependencies_success').d('Dependencies installed successfully.'));
65
+ // Read and parse package.json to check for build script
66
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
67
+ if (packageJson.scripts && packageJson.scripts.build) {
68
+ logger.log(t('init_build_project').d('⌛️ Building project...'));
69
+ execSync('npm run build', { stdio: 'inherit', cwd: targetPath });
70
+ logger.success(t('init_build_project_success').d('Project built successfully.'));
71
+ }
72
+ else {
73
+ logger.log(t('no_build_script').d('No build script found in package.json, skipping build step.'));
74
+ }
75
+ // After build, try to infer assets directory if not explicitly known
76
+ try {
77
+ const candidates = ['dist', 'build', 'out'];
78
+ for (const dir of candidates) {
79
+ const abs = path.join(targetPath, dir);
80
+ if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
81
+ // Update config file if present and assets not set
82
+ const projectConfig = getProjectConfig(targetPath);
83
+ if (projectConfig) {
84
+ const { updateProjectConfigFile } = yield import('../../utils/fileUtils/index.js');
85
+ if (!projectConfig.assets || !projectConfig.assets.directory) {
86
+ yield updateProjectConfigFile({ assets: { directory: dir } }, targetPath);
87
+ logger.success(`Detected build output "${dir}" and updated assets.directory`);
88
+ }
89
+ }
90
+ break;
91
+ }
92
+ }
93
+ }
94
+ catch (_a) { }
95
+ }
96
+ });
97
+ export function checkAndUpdatePackage(packageName) {
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ try {
100
+ const spinner = logger.ora;
101
+ spinner.text = t('checking_template_update').d('Checking esa-template updates...');
102
+ spinner.start();
103
+ // Get currently installed version
104
+ const __dirname = getDirName(import.meta.url);
105
+ const packageJsonPath = path.join(__dirname, '../../../');
106
+ let versionInfo;
107
+ try {
108
+ versionInfo = execSync(`npm list ${packageName}`, {
109
+ cwd: packageJsonPath
110
+ }).toString();
111
+ }
112
+ catch (e) {
113
+ spinner.text = t('template_updating').d('Updating templates to latest...');
114
+ execSync(`rm -rf node_modules/${packageName}`, {
115
+ cwd: packageJsonPath
116
+ });
117
+ execSync(`npm install ${packageName}@latest`, {
118
+ cwd: packageJsonPath,
119
+ stdio: 'inherit'
120
+ });
121
+ spinner.stop();
122
+ logger.log(`├ ${t('template_updated_to_latest').d('Templates updated to latest.')}`);
123
+ return;
124
+ }
125
+ const match = versionInfo.match(new RegExp(`(${packageName})@([0-9.]+)`));
126
+ const currentVersion = match ? match[2] : '';
127
+ // Get latest version
128
+ const latestVersion = execSync(`npm view ${packageName} version`, {
129
+ cwd: packageJsonPath
130
+ })
131
+ .toString()
132
+ .trim();
133
+ if (currentVersion !== latestVersion) {
134
+ spinner.stop();
135
+ logger.log(t('display_current_esa_template_version').d(`Current esa-template version:`) +
136
+ chalk.green(currentVersion) +
137
+ ' ' +
138
+ t('display_latest_esa_template_version').d(`Latest esa-template version:`) +
139
+ chalk.green(latestVersion));
140
+ logger.stopSpinner();
141
+ const isUpdate = yield clackConfirm({
142
+ message: t('is_update_to_latest_version').d('Do you want to update templates to latest version?')
143
+ });
144
+ if (!isCancel(isUpdate) && isUpdate) {
145
+ spinner.start(t('template_updating').d('Updating templates to latest...'));
146
+ execSync(`rm -rf node_modules/${packageName}`, {
147
+ cwd: packageJsonPath
148
+ });
149
+ execSync(`rm -rf package-lock.json`, {
150
+ cwd: packageJsonPath
151
+ });
152
+ execSync(`npm install ${packageName}@latest`, {
153
+ cwd: packageJsonPath,
154
+ stdio: 'inherit'
155
+ });
156
+ spinner.stop();
157
+ logger.log(`├ ${t('updated_esa_template_to_latest_version', { packageName }).d(`${packageName} updated successfully`)}`);
158
+ }
159
+ }
160
+ else {
161
+ spinner.stop();
162
+ logger.log(` ${t('checking_esa_template_finished').d(`Checking esa-template finished.`)}`);
163
+ t('esa_template_is_latest_version', { packageName }).d(`${packageName} is latest.`);
164
+ logger.divider();
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.log(error);
169
+ if (error instanceof Error) {
170
+ logger.ora.fail(t('check_and_update_package_error').d('Error: An error occurred while checking and updating the package, skipping template update'));
171
+ }
172
+ }
173
+ });
174
+ }
175
+ export const getFrameworkConfig = (framework) => {
176
+ // Read template.jsonc from init directory
177
+ const templatePath = path.join(getDirName(import.meta.url), 'template.jsonc');
178
+ const jsonc = fs.readFileSync(templatePath, 'utf-8');
179
+ const json = JSON.parse(jsonc);
180
+ return json[framework];
181
+ };
182
+ /**
183
+ * 获取框架全部配置
184
+ * @returns 框架全部配置
185
+ */
186
+ export const getAllFrameworkConfig = () => {
187
+ // Read template.jsonc from init directory
188
+ const templatePath = path.join(getDirName(import.meta.url), 'template.jsonc');
189
+ const jsonc = fs.readFileSync(templatePath, 'utf-8');
190
+ const json = JSON.parse(jsonc);
191
+ return json;
192
+ };
193
+ export function getInitParamsFromArgv(argv) {
194
+ const a = argv;
195
+ const HaikunatorCtor = Haikunator;
196
+ const haikunator = new HaikunatorCtor();
197
+ const params = {
198
+ name: ''
199
+ };
200
+ if (a.yes) {
201
+ params.name = haikunator.haikunate();
202
+ params.git = true;
203
+ params.deploy = true;
204
+ params.template = 'Hello World';
205
+ params.framework = undefined;
206
+ params.language = undefined;
207
+ params.yes = true;
208
+ }
209
+ if (typeof a.name === 'string')
210
+ params.name = a.name;
211
+ if (typeof a.template === 'string' && a.template) {
212
+ params.template = a.template;
213
+ params.framework = undefined;
214
+ params.language = undefined;
215
+ params.category = 'template';
216
+ }
217
+ else {
218
+ const fw = a.framework;
219
+ const lang = a.language;
220
+ if (fw) {
221
+ params.framework = fw;
222
+ params.category = 'framework';
223
+ }
224
+ if (lang) {
225
+ params.language = lang;
226
+ }
227
+ }
228
+ if (typeof a.git === 'boolean')
229
+ params.git = Boolean(a.git);
230
+ if (typeof a.deploy === 'boolean')
231
+ params.deploy = Boolean(a.deploy);
232
+ return params;
233
+ }
234
+ // Configure project name
235
+ export const configProjectName = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
236
+ if (initParams.name) {
237
+ log.step(`Project name configured ${initParams.name}`);
238
+ return;
239
+ }
240
+ const HaikunatorCtor = Haikunator;
241
+ const haikunator = new HaikunatorCtor();
242
+ const defaultName = haikunator.haikunate();
243
+ const name = (yield promptParameter({
244
+ type: 'text',
245
+ question: `${t('init_input_name').d('Enter the name of edgeRoutine:')}`,
246
+ label: 'Project name',
247
+ defaultValue: defaultName,
248
+ validate: (input) => {
249
+ if (input === '' || input === undefined) {
250
+ initParams.name = defaultName;
251
+ return true;
252
+ }
253
+ const regex = /^[a-z0-9-]{2,}$/;
254
+ if (!regex.test(input)) {
255
+ return t('init_name_error').d('Error: The project name must be at least 2 characters long and can only contain lowercase letters, numbers, and hyphens.');
256
+ }
257
+ return true;
258
+ }
259
+ }));
260
+ initParams.name = name;
261
+ });
262
+ export const configCategory = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
263
+ if (initParams.category || initParams.framework || initParams.template) {
264
+ return;
265
+ }
266
+ const initMode = (yield promptParameter({
267
+ type: 'select',
268
+ question: 'How would you like to initialize the project?',
269
+ label: 'Init mode',
270
+ choices: [
271
+ { name: 'Framework Starter', value: 'framework' },
272
+ {
273
+ name: 'Function Template',
274
+ value: 'template'
275
+ }
276
+ ]
277
+ }));
278
+ initParams.category = initMode;
279
+ });
280
+ /*
281
+ 选择模板
282
+ 如果选择的是framework,则选择具体的模版 vue /react等
283
+ 如果选择的是template,则选择具体的模版 esa template
284
+ */
285
+ export const configTemplate = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
286
+ if (initParams.template) {
287
+ log.step(`Template configured ${initParams.template}`);
288
+ return;
289
+ }
290
+ if (initParams.framework) {
291
+ log.step(`Framework configured ${initParams.framework}`);
292
+ return;
293
+ }
294
+ if (initParams.category === 'template') {
295
+ const templateItems = prepareTemplateItems();
296
+ const selectedTemplatePath = yield promptParameter({
297
+ type: 'multiLevelSelect',
298
+ question: 'Select a template:',
299
+ treeItems: templateItems
300
+ });
301
+ if (!selectedTemplatePath)
302
+ return null;
303
+ // TODO
304
+ initParams.template = selectedTemplatePath;
305
+ }
306
+ else {
307
+ const allFrameworkConfig = getAllFrameworkConfig();
308
+ const fw = (yield promptParameter({
309
+ type: 'select',
310
+ question: 'Select a framework',
311
+ label: 'Framework',
312
+ choices: Object.keys(allFrameworkConfig).map((fw) => {
313
+ var _a;
314
+ return ({
315
+ name: allFrameworkConfig[fw].label,
316
+ value: fw,
317
+ hint: (_a = allFrameworkConfig[fw]) === null || _a === void 0 ? void 0 : _a.hint
318
+ });
319
+ })
320
+ }));
321
+ initParams.framework = fw;
322
+ }
323
+ });
324
+ export const configLanguage = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
325
+ if (initParams.language) {
326
+ log.info(`Language configured ${initParams.language}`);
327
+ return;
328
+ }
329
+ const framework = initParams.framework;
330
+ if (!framework) {
331
+ log.info('Framework config not configured, language skipped');
332
+ return;
333
+ }
334
+ const frameworkConfig = getFrameworkConfig(framework);
335
+ if (frameworkConfig.language) {
336
+ const language = (yield promptParameter({
337
+ type: 'select',
338
+ question: t('init_language_select').d('Select programming language:'),
339
+ label: 'Language',
340
+ choices: [
341
+ {
342
+ name: t('init_language_typescript').d('TypeScript (.ts) - Type-safe JavaScript, recommended'),
343
+ value: 'typescript'
344
+ },
345
+ {
346
+ name: t('init_language_javascript').d('JavaScript (.js) - Traditional JavaScript'),
347
+ value: 'javascript'
348
+ }
349
+ ],
350
+ defaultValue: 'typescript'
351
+ }));
352
+ initParams.language = language;
353
+ }
354
+ });
355
+ export const createProject = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
356
+ var _a;
357
+ if (initParams.template) {
358
+ // resolve template value: it may be a filesystem path or a template title
359
+ let selectedTemplatePath = initParams.template;
360
+ if (!path.isAbsolute(selectedTemplatePath) ||
361
+ !fs.existsSync(selectedTemplatePath)) {
362
+ const instances = getTemplateInstances(templateHubPath);
363
+ const matched = instances.find((it) => it.title === initParams.template);
364
+ if (matched) {
365
+ selectedTemplatePath = matched.path;
366
+ }
367
+ }
368
+ if (!fs.existsSync(selectedTemplatePath)) {
369
+ outro(`Project creation failed: cannot resolve template "${initParams.template}"`);
370
+ exit(1);
371
+ }
372
+ const res = yield initializeProject(selectedTemplatePath, initParams.name);
373
+ if (!res) {
374
+ outro(`Project creation failed`);
375
+ exit(1);
376
+ }
377
+ }
378
+ if (initParams.framework) {
379
+ const framework = initParams.framework;
380
+ const frameworkConfig = getFrameworkConfig(framework);
381
+ const command = frameworkConfig.command;
382
+ const templateFlag = ((_a = frameworkConfig.language) === null || _a === void 0 ? void 0 : _a[initParams.language || 'typescript']) || '';
383
+ const extraParams = frameworkConfig.params || '';
384
+ const full = `${command} ${initParams.name} ${templateFlag} ${extraParams}`.trim();
385
+ const res = yield execCommand(['sh', '-lc', full], {
386
+ interactive: true,
387
+ startText: `Starting to execute framework command ${chalk.gray(full)}`,
388
+ doneText: `Framework command executed ${chalk.gray(full)}`
389
+ });
390
+ if (!res.success) {
391
+ outro(`Framework command execution failed`);
392
+ exit(1);
393
+ }
394
+ }
395
+ });
396
+ export const installDependencies = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
397
+ if (initParams.template) {
398
+ return;
399
+ }
400
+ const targetPath = path.join(process.cwd(), initParams.name);
401
+ const res = yield execCommand(['npm', 'install'], {
402
+ cwd: targetPath,
403
+ useSpinner: true,
404
+ silent: true,
405
+ startText: 'Installing dependencies',
406
+ doneText: 'Dependencies installed'
407
+ });
408
+ if (!res.success) {
409
+ outro(`Dependencies installation failed`);
410
+ exit(1);
411
+ }
412
+ });
413
+ /**
414
+ * Apply configured file edits (方式1: overwrite) after project scaffold
415
+ */
416
+ export const applyFileEdits = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
417
+ var _a;
418
+ if (!initParams.framework) {
419
+ return true;
420
+ }
421
+ const frameworkConfig = getFrameworkConfig(initParams.framework || '');
422
+ const edits = frameworkConfig.fileEdits || [];
423
+ if (!edits.length)
424
+ return true;
425
+ logger.startSubStep(`Applying file edits`);
426
+ const __dirname = getDirName(import.meta.url);
427
+ try {
428
+ const toRegexFromGlob = (pattern) => {
429
+ // Very small glob subset: *, ?, {a,b,c}
430
+ let escaped = pattern
431
+ .replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&') // escape regex specials first
432
+ .replace(/\\\*/g, '.*')
433
+ .replace(/\\\?/g, '.');
434
+ // restore and convert {a,b} to (a|b)
435
+ escaped = escaped.replace(/\\\{([^}]+)\\\}/g, (_, inner) => {
436
+ const parts = inner.split(',').map((s) => s.trim());
437
+ return `(${parts.join('|')})`;
438
+ });
439
+ return new RegExp('^' + escaped + '$');
440
+ };
441
+ const targetPath = path.join(process.cwd(), initParams.name);
442
+ const listRootFiles = () => {
443
+ try {
444
+ return fs.readdirSync(targetPath);
445
+ }
446
+ catch (_a) {
447
+ return [];
448
+ }
449
+ };
450
+ for (const edit of edits) {
451
+ if (((_a = edit.when) === null || _a === void 0 ? void 0 : _a.language) && initParams.language) {
452
+ if (edit.when.language !== initParams.language)
453
+ continue;
454
+ }
455
+ const createIfMissing = edit.createIfMissing !== false;
456
+ let matchedFiles = [];
457
+ if (edit.matchType === 'exact') {
458
+ matchedFiles = [edit.match];
459
+ }
460
+ else if (edit.matchType === 'glob') {
461
+ const regex = toRegexFromGlob(edit.match);
462
+ matchedFiles = listRootFiles().filter((name) => regex.test(name));
463
+ }
464
+ else if (edit.matchType === 'regex') {
465
+ const regex = new RegExp(edit.match);
466
+ matchedFiles = listRootFiles().filter((name) => regex.test(name));
467
+ }
468
+ // if no matched files and allowed to create, provide a reasonable default for common patterns
469
+ if (!matchedFiles.length && createIfMissing) {
470
+ if (edit.matchType === 'exact') {
471
+ matchedFiles = [edit.match];
472
+ }
473
+ else if (edit.matchType === 'glob' &&
474
+ /next\.config\.\{.*\}/.test(edit.match)) {
475
+ matchedFiles = ['next.config.ts'];
476
+ }
477
+ }
478
+ if (!matchedFiles.length)
479
+ continue;
480
+ // resolve content
481
+ let payload = null;
482
+ if (edit.fromFile) {
483
+ const absFrom = path.isAbsolute(edit.fromFile)
484
+ ? edit.fromFile
485
+ : path.join(__dirname, edit.fromFile);
486
+ payload = fs.readFileSync(absFrom, 'utf-8');
487
+ }
488
+ else if (typeof edit.content === 'string') {
489
+ payload = edit.content;
490
+ }
491
+ for (const rel of matchedFiles) {
492
+ const abs = path.join(targetPath, rel);
493
+ if (payload == null)
494
+ continue;
495
+ fs.ensureDirSync(path.dirname(abs));
496
+ fs.writeFileSync(abs, payload, 'utf-8');
497
+ }
498
+ }
499
+ logger.endSubStep('File edits applied');
500
+ return true;
501
+ }
502
+ catch (_b) {
503
+ outro(`File edits application failed`);
504
+ exit(1);
505
+ }
506
+ });
507
+ export const installESACli = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
508
+ const targetPath = path.join(process.cwd(), initParams.name);
509
+ const res = yield execCommand(['npm', 'install', '-D', 'esa-cli'], {
510
+ cwd: targetPath,
511
+ useSpinner: true,
512
+ silent: true,
513
+ startText: 'Installing ESA CLI',
514
+ doneText: 'ESA CLI installed in the project'
515
+ });
516
+ if (!res.success) {
517
+ outro(`ESA CLI installation failed`);
518
+ exit(1);
519
+ }
520
+ });
521
+ export const updateConfigFile = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
522
+ var _a, _b;
523
+ const targetPath = path.join(process.cwd(), initParams.name);
524
+ const configFormat = 'jsonc';
525
+ logger.startSubStep(`Updating config file`);
526
+ try {
527
+ if (initParams.framework) {
528
+ const frameworkConfig = getFrameworkConfig(initParams.framework);
529
+ const assetsDirectory = (_a = frameworkConfig.assets) === null || _a === void 0 ? void 0 : _a.directory;
530
+ const notFoundStrategy = (_b = frameworkConfig.assets) === null || _b === void 0 ? void 0 : _b.notFoundStrategy;
531
+ yield generateConfigFile(initParams.name, {
532
+ assets: assetsDirectory ? { directory: assetsDirectory } : undefined
533
+ }, targetPath, configFormat, notFoundStrategy);
534
+ }
535
+ else {
536
+ // TODO revise template config file later
537
+ // console.log(
538
+ // 'test:',
539
+ // initParams.name,
540
+ // undefined,
541
+ // targetPath,
542
+ // configFormat
543
+ // );
544
+ // logger.startSubStep(`Updating config file`);
545
+ // await generateConfigFile(initParams.name, undefined, targetPath, 'toml');
546
+ }
547
+ logger.endSubStep('Config file updated');
548
+ }
549
+ catch (_c) {
550
+ outro(`Config file update failed`);
551
+ exit(1);
552
+ }
553
+ });
554
+ export const initGit = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
555
+ var _a;
556
+ const frameworkConfig = getFrameworkConfig(initParams.framework || '');
557
+ if ((frameworkConfig === null || frameworkConfig === void 0 ? void 0 : frameworkConfig.useGit) === false) {
558
+ log.step('Git skipped');
559
+ return true;
560
+ }
561
+ const gitInstalled = yield isGitInstalled();
562
+ if (!gitInstalled) {
563
+ log.step('You have not installed Git, Git skipped');
564
+ return true;
565
+ }
566
+ if (!initParams.git) {
567
+ const initGit = (yield promptParameter({
568
+ type: 'confirm',
569
+ question: t('init_git').d('Do you want to init git in your project?'),
570
+ label: 'Init git',
571
+ defaultValue: false
572
+ }));
573
+ initParams.git = initGit;
574
+ }
575
+ if (initParams.git) {
576
+ const targetPath = path.join(process.cwd(), initParams.name);
577
+ const res = yield execCommand(['git', 'init'], {
578
+ cwd: targetPath,
579
+ silent: true,
580
+ startText: 'Initializing git',
581
+ doneText: 'Git initialized'
582
+ });
583
+ if (!res.success) {
584
+ outro(`Git initialization failed`);
585
+ exit(1);
586
+ }
587
+ // Ensure .gitignore exists and has sensible defaults
588
+ yield ensureGitignore(targetPath, (_a = frameworkConfig === null || frameworkConfig === void 0 ? void 0 : frameworkConfig.assets) === null || _a === void 0 ? void 0 : _a.directory);
589
+ }
590
+ return true;
591
+ });
592
+ export function getGitVersion() {
593
+ return __awaiter(this, void 0, void 0, function* () {
594
+ try {
595
+ let stdout = yield execCommand(['git', '--version'], {
596
+ useSpinner: false,
597
+ silent: true,
598
+ captureOutput: true
599
+ });
600
+ const gitVersion = stdout.stdout.replace(/^git\s+version\s+/, '');
601
+ return gitVersion;
602
+ }
603
+ catch (_a) {
604
+ log.error('Failed to get Git version');
605
+ return null;
606
+ }
607
+ });
608
+ }
609
+ export function isGitInstalled() {
610
+ return __awaiter(this, void 0, void 0, function* () {
611
+ return (yield getGitVersion()) !== '' && (yield getGitVersion()) !== null;
612
+ });
613
+ }
614
+ /**
615
+ * Create or update .gitignore in project root with sensible defaults.
616
+ * - Preserves existing entries and comments
617
+ * - Avoids duplicates
618
+ * - Adds framework assets directory if provided
619
+ */
620
+ function ensureGitignore(projectRoot, assetsDirectory) {
621
+ return __awaiter(this, void 0, void 0, function* () {
622
+ try {
623
+ const gitignorePath = path.join(projectRoot, '.gitignore');
624
+ const defaults = [
625
+ '# Logs',
626
+ 'logs',
627
+ '*.log',
628
+ 'npm-debug.log*',
629
+ 'yarn-debug.log*',
630
+ 'yarn-error.log*',
631
+ 'pnpm-debug.log*',
632
+ '',
633
+ '# Node modules',
634
+ 'node_modules/',
635
+ '',
636
+ '# Build output',
637
+ 'dist/',
638
+ 'build/',
639
+ 'out/',
640
+ '.next/',
641
+ '.nuxt/',
642
+ 'coverage/',
643
+ '.vite/',
644
+ '',
645
+ '# Env files',
646
+ '.env',
647
+ '.env.local',
648
+ '.env.development.local',
649
+ '.env.test.local',
650
+ '.env.production.local',
651
+ '',
652
+ '# IDE/editor',
653
+ '.DS_Store',
654
+ '.idea/',
655
+ '.vscode/',
656
+ '',
657
+ '# Misc caches',
658
+ '.eslintcache',
659
+ '.parcel-cache/',
660
+ '.turbo/',
661
+ '.cache/'
662
+ ];
663
+ // Include assets directory if provided and not a common default
664
+ if (assetsDirectory &&
665
+ !['dist', 'build', 'out'].includes(assetsDirectory.replace(/\/$/, ''))) {
666
+ defaults.push('', '# Project assets output', `${assetsDirectory}/`);
667
+ }
668
+ let existingContent = '';
669
+ if (fs.existsSync(gitignorePath)) {
670
+ existingContent = fs.readFileSync(gitignorePath, 'utf-8');
671
+ }
672
+ const existingLines = new Set(existingContent.split(/\r?\n/).map((l) => l.trimEnd()));
673
+ const toAppend = [];
674
+ for (const line of defaults) {
675
+ if (!existingLines.has(line)) {
676
+ toAppend.push(line);
677
+ existingLines.add(line);
678
+ }
679
+ }
680
+ // If nothing to add, keep as is
681
+ if (!toAppend.length)
682
+ return;
683
+ const newContent = existingContent
684
+ ? `${existingContent.replace(/\n$/, '')}\n${toAppend.join('\n')}\n`
685
+ : `${toAppend.join('\n')}\n`;
686
+ fs.writeFileSync(gitignorePath, newContent, 'utf-8');
687
+ }
688
+ catch (_a) {
689
+ // Do not fail init due to .gitignore issues
690
+ }
691
+ });
692
+ }
693
+ export const buildProject = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
694
+ if (initParams.template) {
695
+ return;
696
+ }
697
+ const targetPath = path.join(process.cwd(), initParams.name);
698
+ const res = yield execCommand(['npm', 'run', 'build'], {
699
+ useSpinner: true,
700
+ silent: true,
701
+ startText: 'Building project',
702
+ doneText: 'Project built',
703
+ cwd: targetPath
704
+ });
705
+ if (!res.success) {
706
+ outro(`Build project failed`);
707
+ exit(1);
708
+ }
709
+ });
710
+ export function prepareTemplateItems() {
711
+ var _a;
712
+ const templateInstanceList = getTemplateInstances(templateHubPath);
713
+ const templateConfig = getTemplatesConfig();
714
+ const cliConfig = getCliConfig();
715
+ const lang = (_a = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.lang) !== null && _a !== void 0 ? _a : 'en';
716
+ return transferTemplatesToSelectItem(templateConfig, templateInstanceList, lang);
717
+ }
718
+ export const deployProject = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
719
+ if (!initParams.deploy) {
720
+ log.step('Deploy project skipped');
721
+ return;
722
+ }
723
+ const targetPath = path.join(process.cwd(), initParams.name);
724
+ const res = yield commitAndDeployVersion(initParams.name, undefined, undefined, 'Init project', targetPath, 'all');
725
+ if (!res) {
726
+ outro(`Deploy project failed`);
727
+ exit(1);
728
+ }
729
+ });
730
+ export function initializeProject(selectedTemplatePath, name) {
731
+ return __awaiter(this, void 0, void 0, function* () {
732
+ const selectTemplate = new Template(selectedTemplatePath, name);
733
+ const projectConfig = getProjectConfig(selectedTemplatePath);
734
+ if (!projectConfig) {
735
+ logger.notInProject();
736
+ return null;
737
+ }
738
+ const targetPath = path.join(process.cwd(), name);
739
+ if (fs.existsSync(targetPath)) {
740
+ logger.block();
741
+ logger.tree([
742
+ `${chalk.bgRed(' ERROR ')} ${chalk.bold.red(t('init_abort').d('Initialization aborted'))}`,
743
+ `${chalk.gray(t('reason').d('Reason:'))} ${chalk.red(t('dir_already_exists').d('Target directory already exists'))}`,
744
+ `${chalk.gray(t('path').d('Path:'))} ${chalk.cyan(targetPath)}`,
745
+ chalk.gray(t('try').d('Try one of the following:')),
746
+ `- ${chalk.white(t('try_diff_name').d('Choose a different project name'))}`,
747
+ `- ${chalk.white(t('try_remove').d('Remove the directory:'))} ${chalk.yellow(`rm -rf "${name}”`)}`,
748
+ `- ${chalk.white(t('try_another_dir').d('Run the command in another directory'))}`
749
+ ]);
750
+ logger.block();
751
+ return null;
752
+ }
753
+ yield fs.copy(selectedTemplatePath, targetPath);
754
+ projectConfig.name = name;
755
+ yield updateProjectConfigFile(projectConfig, targetPath);
756
+ yield preInstallDependencies(targetPath);
757
+ return { template: selectTemplate, targetPath };
758
+ });
759
+ }