@emulsify/cli 2.4.2 → 2.5.0

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 (35) hide show
  1. package/README.md +10 -3
  2. package/dist/handlers/cacheClear.js +5 -6
  3. package/dist/handlers/componentCreate.js +8 -8
  4. package/dist/handlers/componentEjectTemplates.js +22 -20
  5. package/dist/handlers/componentInstall.js +74 -69
  6. package/dist/handlers/componentList.js +51 -4
  7. package/dist/handlers/hofs/withEmulsifySystem.js +3 -1
  8. package/dist/handlers/hofs/withSession.js +8 -0
  9. package/dist/handlers/init.js +144 -132
  10. package/dist/handlers/systemCreate.js +31 -25
  11. package/dist/handlers/systemDetach.js +5 -5
  12. package/dist/handlers/systemInstall.js +57 -53
  13. package/dist/handlers/systemList.js +13 -2
  14. package/dist/index.js +57 -34
  15. package/dist/lib/log.js +21 -24
  16. package/dist/lib/rootHelp.js +30 -5
  17. package/dist/lib/session.js +141 -0
  18. package/dist/schemas/system.json +1 -0
  19. package/dist/schemas/variant.json +8 -0
  20. package/dist/util/cache/cloneIntoCache.js +25 -8
  21. package/dist/util/cache/getCachedItemPath.js +3 -1
  22. package/dist/util/fs/writeToJsonFile.js +4 -1
  23. package/dist/util/getGitRepoNameFromUrl.js +21 -10
  24. package/dist/util/getNonInteractiveGitEnvironment.js +1 -1
  25. package/dist/util/platform/getInitSuccessMessageForPlatform.js +15 -9
  26. package/dist/util/project/componentNpmDependencies.js +169 -0
  27. package/dist/util/project/componentNpmManifest.js +164 -0
  28. package/dist/util/project/generateComponent.js +98 -39
  29. package/dist/util/project/installComponentNpmDependencies.js +197 -0
  30. package/dist/util/project/installDependencies.js +10 -3
  31. package/dist/util/project/resolveComponentTemplate.js +11 -1
  32. package/dist/util/prompt/index.js +21 -6
  33. package/dist/util/system/validateSystemConfig.js +13 -27
  34. package/package.json +16 -18
  35. package/dist/handlers/hofs/withProgressBar.js +0 -10
@@ -0,0 +1,164 @@
1
+ import { existsSync, promises as fs } from 'fs';
2
+ import { dirname, join } from 'path';
3
+ import CliError from '../../lib/CliError.js';
4
+ const lockfiles = [
5
+ ['pnpm-lock.yaml', 'pnpm'],
6
+ ['yarn.lock', 'yarn'],
7
+ ['bun.lock', 'bun'],
8
+ ['bun.lockb', 'bun'],
9
+ ['package-lock.json', 'npm'],
10
+ ['npm-shrinkwrap.json', 'npm'],
11
+ ];
12
+ function isObject(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ export async function readComponentNpmManifest(projectRoot) {
16
+ const path = join(projectRoot, 'package.json');
17
+ let source;
18
+ try {
19
+ source = await fs.readFile(path, 'utf8');
20
+ }
21
+ catch (error) {
22
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
23
+ return { status: 'missing', path, reason: 'does not exist' };
24
+ }
25
+ return { status: 'unreadable', path, reason: 'could not be read' };
26
+ }
27
+ let json;
28
+ try {
29
+ json = JSON.parse(source);
30
+ }
31
+ catch {
32
+ return { status: 'invalid', path, reason: 'does not contain valid JSON' };
33
+ }
34
+ if (!isObject(json)) {
35
+ return {
36
+ status: 'invalid',
37
+ path,
38
+ reason: 'does not contain a JSON object',
39
+ };
40
+ }
41
+ if (Object.hasOwn(json, 'dependencies') && !isObject(json.dependencies)) {
42
+ return {
43
+ status: 'invalid',
44
+ path,
45
+ reason: 'has a dependencies field that is not an object',
46
+ };
47
+ }
48
+ return { status: 'ready', path, source, json };
49
+ }
50
+ export function detectComponentPackageManager(projectRoot, packageManager) {
51
+ if (typeof packageManager === 'string' && packageManager.trim()) {
52
+ const name = packageManager.split('@')[0];
53
+ if (name === 'npm' ||
54
+ name === 'pnpm' ||
55
+ name === 'yarn' ||
56
+ name === 'bun') {
57
+ return name;
58
+ }
59
+ return 'unsupported';
60
+ }
61
+ return (lockfiles.find(([file]) => existsSync(join(projectRoot, file)))?.[1] ??
62
+ 'npm');
63
+ }
64
+ function findDependenciesObject(source) {
65
+ let depth = 0;
66
+ let isDependenciesProperty = false;
67
+ let start;
68
+ let result;
69
+ for (const token of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}\[\]]/g)) {
70
+ const [value, key, colon] = token;
71
+ if (depth === 1 && colon) {
72
+ isDependenciesProperty = JSON.parse(key) === 'dependencies';
73
+ }
74
+ else if (value === '{' || value === '[') {
75
+ if (depth === 1 && isDependenciesProperty) {
76
+ start = token.index;
77
+ }
78
+ depth++;
79
+ }
80
+ else if (value === '}' || value === ']') {
81
+ depth--;
82
+ if (depth === 1 && start !== undefined) {
83
+ result = { start, end: token.index + 1 };
84
+ start = undefined;
85
+ }
86
+ }
87
+ }
88
+ return result;
89
+ }
90
+ function updateSource({ source, json }, dependencies) {
91
+ const newline = source.includes('\r\n') ? '\r\n' : '\n';
92
+ const multiline = source.trim().includes('\n');
93
+ const indent = source.match(/^([ \t]+)"/m)?.[1] ?? ' ';
94
+ const entries = [...dependencies.keys()].sort().map((name) => {
95
+ const value = dependencies.get(name);
96
+ if (!multiline) {
97
+ return `${JSON.stringify(name)}:${JSON.stringify(value)}`;
98
+ }
99
+ const formattedValue = JSON.stringify(value, null, indent).replaceAll('\n', `${newline}${indent}${indent}`);
100
+ return `${indent}${indent}${JSON.stringify(name)}: ${formattedValue}`;
101
+ });
102
+ const object = multiline
103
+ ? `{${newline}${entries.join(`,${newline}`)}${newline}${indent}}`
104
+ : `{${entries.join(',')}}`;
105
+ const previous = findDependenciesObject(source);
106
+ if (previous) {
107
+ return (source.slice(0, previous.start) + object + source.slice(previous.end));
108
+ }
109
+ const end = source.slice(0, source.lastIndexOf('}')).trimEnd().length;
110
+ const comma = Object.keys(json).length > 0 ? ',' : '';
111
+ const property = multiline
112
+ ? `${newline}${indent}"dependencies": ${object}`
113
+ : `"dependencies":${object}`;
114
+ return source.slice(0, end) + comma + property + source.slice(end);
115
+ }
116
+ export async function writeComponentNpmManifest(manifest, additions) {
117
+ const { path, source, json } = manifest;
118
+ const dependencies = new Map(Object.entries(isObject(json.dependencies) ? json.dependencies : {}));
119
+ const previousCount = dependencies.size;
120
+ for (const [name, range] of additions) {
121
+ if (!dependencies.has(name)) {
122
+ dependencies.set(name, range);
123
+ }
124
+ }
125
+ if (dependencies.size === previousCount) {
126
+ return;
127
+ }
128
+ const temporaryPath = join(dirname(path), '.package.json.emulsify.tmp');
129
+ let temporaryFile;
130
+ try {
131
+ temporaryFile = await fs.open(temporaryPath, 'wx', 0o600);
132
+ }
133
+ catch (error) {
134
+ if (error instanceof Error && 'code' in error && error.code === 'EEXIST') {
135
+ throw new CliError(`A package.json update is already staged at ${temporaryPath}. Wait for any running Emulsify installs to finish. If the file remains once they have finished, remove it and retry.`);
136
+ }
137
+ throw new CliError(`Unable to create ${temporaryPath}: ${String(error)}.`);
138
+ }
139
+ try {
140
+ try {
141
+ const mode = (await fs.stat(path)).mode & 0o7777;
142
+ await temporaryFile.writeFile(updateSource(manifest, dependencies), 'utf8');
143
+ await temporaryFile.chmod(mode);
144
+ await temporaryFile.sync();
145
+ }
146
+ finally {
147
+ await temporaryFile.close();
148
+ }
149
+ if ((await fs.readFile(path, 'utf8')) !== source) {
150
+ throw new CliError(`${path} changed during installation. Re-run the command to apply the npm packages.`);
151
+ }
152
+ await fs.rename(temporaryPath, path);
153
+ }
154
+ catch (error) {
155
+ let cleanup = '';
156
+ try {
157
+ await fs.rm(temporaryPath, { force: true });
158
+ }
159
+ catch (cleanupError) {
160
+ cleanup = ` Temporary-file cleanup also failed: ${String(cleanupError)}`;
161
+ }
162
+ throw new CliError(`Unable to update ${path}: ${String(error)}.${cleanup}`);
163
+ }
164
+ }
@@ -1,18 +1,19 @@
1
- import { confirm, input, select } from '@inquirer/prompts';
1
+ import { confirm, select, text } from '@clack/prompts';
2
2
  import { promises as fs } from 'fs';
3
- import { dirname } from 'path';
4
- import { pathExists, remove } from 'fs-extra';
3
+ import { dirname, join } from 'path';
4
+ import { pathExists } from 'fs-extra';
5
+ import CliError from '../../lib/CliError.js';
5
6
  import log from '../../lib/log.js';
6
- import getTerminalColors from '../../lib/terminalColors.js';
7
+ import { markSessionMayHaveChanges, note } from '../../lib/session.js';
7
8
  import findFileInCurrentPath from '../fs/findFileInCurrentPath.js';
8
9
  import safeResolveWithin from '../fs/safeResolveWithin.js';
9
10
  import { EMULSIFY_PROJECT_CONFIG_FILE } from '../../lib/constants.js';
10
11
  import deriveComponentNames from '../deriveComponentNames.js';
11
12
  import { assertValidCustomElementTagName, deriveCustomElementTagName, } from '../deriveCustomElementTagName.js';
12
- import { isInteractiveTerminal, runPrompt } from '../prompt/index.js';
13
+ import { isInteractiveTerminal, runPrompt, } from '../prompt/index.js';
13
14
  import { componentTypeFromLegacyFormat, getAvailableComponentTypes, getComponentFormatLabel, getCompatibleFormatToken, MISSING_COMPONENT_DIRECTORY_ERROR, MISSING_COMPONENT_TYPE_ERROR, normalizeComponentType, projectDeclaresEmulsifyCore, } from './componentTypes.js';
14
15
  import resolveComponentTemplate from './resolveComponentTemplate.js';
15
- import { buildComponentArtifacts } from './componentTemplates/index.js';
16
+ import { buildComponentArtifacts, } from './componentTemplates/index.js';
16
17
  const TYPE_LABELS = {
17
18
  twig: 'Twig',
18
19
  'twig-sdc': 'Twig SDC',
@@ -33,7 +34,7 @@ function resolveProvidedComponentType(options) {
33
34
  log('warn', `The --format option is deprecated; use --type ${type} instead.`);
34
35
  return type;
35
36
  }
36
- async function promptForComponentType(projectRoot, platform, bold, cyan) {
37
+ async function promptForComponentType(projectRoot, platform) {
37
38
  const hasEmulsifyCore = await projectDeclaresEmulsifyCore(projectRoot);
38
39
  const availableTypes = getAvailableComponentTypes(platform, hasEmulsifyCore);
39
40
  if (platform !== 'drupal') {
@@ -53,25 +54,65 @@ async function promptForComponentType(projectRoot, platform, bold, cyan) {
53
54
  'web-component': 'Custom element rendered by @emulsify/core',
54
55
  };
55
56
  return select({
56
- message: cyan('Choose the component type:'),
57
- choices: availableTypes.map((type) => ({
58
- name: bold(TYPE_LABELS[type]),
57
+ message: 'Choose the component type',
58
+ options: availableTypes.map((type) => ({
59
59
  value: type,
60
- description: descriptions[type],
60
+ label: TYPE_LABELS[type],
61
+ hint: descriptions[type],
61
62
  })),
62
63
  });
63
64
  }
64
65
  function validateCustomElementTagName(value) {
65
66
  try {
66
- assertValidCustomElementTagName(value.trim());
67
- return true;
67
+ assertValidCustomElementTagName((value ?? '').trim());
68
+ return undefined;
68
69
  }
69
70
  catch (error) {
70
71
  return error.message;
71
72
  }
72
73
  }
74
+ async function writeComponentFiles(directory, artifacts) {
75
+ for (const { destinationName, contents } of artifacts) {
76
+ await fs.writeFile(join(directory, destinationName), contents);
77
+ }
78
+ }
79
+ async function cleanUpComponentDirectory(directory) {
80
+ try {
81
+ await fs.rm(directory, { recursive: true, force: true });
82
+ }
83
+ catch (error) {
84
+ log('warn', `Unable to clean up component directory "${directory}": ${String(error)}`);
85
+ }
86
+ }
87
+ async function replaceComponentDirectory(destination, artifacts) {
88
+ const transaction = await fs.mkdtemp(join(dirname(destination), '.emulsify-component-'));
89
+ const staged = join(transaction, 'staged');
90
+ const backup = join(transaction, 'original');
91
+ let keepBackup = false;
92
+ try {
93
+ await fs.mkdir(staged);
94
+ await writeComponentFiles(staged, artifacts);
95
+ await fs.rename(destination, backup);
96
+ try {
97
+ await fs.rename(staged, destination);
98
+ }
99
+ catch (error) {
100
+ try {
101
+ await fs.rename(backup, destination);
102
+ }
103
+ catch (restoreError) {
104
+ keepBackup = true;
105
+ throw new CliError(`Unable to replace component "${destination}": ${String(error)}. Restore the original component from "${backup}". Automatic restoration failed: ${String(restoreError)}.`);
106
+ }
107
+ throw error;
108
+ }
109
+ }
110
+ finally {
111
+ if (!keepBackup)
112
+ await cleanUpComponentDirectory(transaction);
113
+ }
114
+ }
73
115
  export default async function generateComponent(variant, projectConfig, componentName, options = {}) {
74
- const { bold, cyan, green, yellow } = getTerminalColors();
75
116
  const { filename, className, camelName, pascalName, snakeName, humanName } = deriveComponentNames(componentName);
76
117
  const providedType = resolveProvidedComponentType(options);
77
118
  const force = options.force === true || options.yes === true;
@@ -84,7 +125,7 @@ export default async function generateComponent(variant, projectConfig, componen
84
125
  const type = providedType
85
126
  ? providedType
86
127
  : await runPrompt({
87
- prompt: () => promptForComponentType(projectRoot, projectConfig.project.platform, bold, cyan),
128
+ prompt: () => promptForComponentType(projectRoot, projectConfig.project.platform),
88
129
  nonInteractive: { error: MISSING_COMPONENT_TYPE_ERROR },
89
130
  });
90
131
  if (options.tagName !== undefined && type !== 'web-component') {
@@ -103,9 +144,10 @@ export default async function generateComponent(variant, projectConfig, componen
103
144
  else {
104
145
  const derivedTagName = deriveCustomElementTagName(filename, projectConfig.project.machineName);
105
146
  tagName = (await runPrompt({
106
- prompt: () => input({
107
- message: cyan('Custom element tag name:'),
108
- default: derivedTagName,
147
+ prompt: () => text({
148
+ message: 'Custom element tag name',
149
+ placeholder: derivedTagName,
150
+ defaultValue: derivedTagName,
109
151
  validate: validateCustomElementTagName,
110
152
  }),
111
153
  nonInteractive: { value: derivedTagName },
@@ -124,10 +166,10 @@ export default async function generateComponent(variant, projectConfig, componen
124
166
  if (!directory) {
125
167
  directory = await runPrompt({
126
168
  prompt: () => select({
127
- message: cyan('Choose a directory for the new component:'),
128
- choices: variant.structureImplementations.map((structure) => ({
129
- name: structure.name,
169
+ message: 'Choose a directory for the new component',
170
+ options: variant.structureImplementations.map((structure) => ({
130
171
  value: structure.name,
172
+ label: structure.name,
131
173
  })),
132
174
  }),
133
175
  nonInteractive: {
@@ -165,13 +207,14 @@ export default async function generateComponent(variant, projectConfig, componen
165
207
  const realRunAction = componentExists
166
208
  ? force
167
209
  ? 'replace the existing component directory'
168
- : 'prompt before replacing the existing component directory'
210
+ : isInteractiveTerminal()
211
+ ? 'prompt before replacing the existing component directory'
212
+ : 'fail unless --force is passed to replace the existing component directory'
169
213
  : 'create the component directory';
170
214
  const generatedFiles = artifactDestinations
171
215
  .map((filePath) => ` - ${filePath}`)
172
216
  .join('\n');
173
- return log('info', [
174
- `Dry run: component create "${filename}"`,
217
+ note([
175
218
  `Type: ${type}`,
176
219
  `Directory: ${directory}`,
177
220
  `Structure path: ${structure.directory}`,
@@ -182,30 +225,46 @@ export default async function generateComponent(variant, projectConfig, componen
182
225
  'Generated files:',
183
226
  generatedFiles,
184
227
  'No files were written, removed, or created.',
185
- ].join('\n'));
186
- }
187
- if (!parentExists) {
188
- await fs.mkdir(parentPath, { recursive: true });
228
+ ].join('\n'), `Dry run: component create "${filename}"`);
229
+ return 'Dry run complete; no files were changed';
189
230
  }
190
231
  if (componentExists) {
191
232
  const shouldReplace = await runPrompt({
192
233
  prompt: () => confirm({
193
- message: yellow(`The component "${humanName}" already exists in ${structure.directory}. Would you like to replace it?`),
194
- default: false,
234
+ message: `The component "${humanName}" already exists in ${structure.directory}. Would you like to replace it?`,
235
+ initialValue: false,
195
236
  }),
196
- nonInteractive: { value: false },
237
+ nonInteractive: {
238
+ error: `The component "${humanName}" already exists in ${structure.directory}. Pass --force to replace it in non-interactive mode.`,
239
+ },
197
240
  accept: { when: force, value: true },
198
241
  });
199
242
  if (!shouldReplace) {
200
- return log('info', `Component creation canceled.`);
243
+ log('info', `Component creation canceled.`);
244
+ return `Canceled; the existing ${componentName} component was kept`;
201
245
  }
202
- await remove(destination);
203
246
  }
204
- await fs.mkdir(destination, { recursive: true });
205
- for (const [index, artifact] of artifacts.entries()) {
206
- const templateFile = (await resolveComponentTemplate(projectRoot, type, artifact.logicalName, templateVars)) ?? artifact.contents;
207
- const artifactDestination = artifactDestinations[index];
208
- await fs.writeFile(artifactDestination, templateFile);
247
+ for (const artifact of artifacts) {
248
+ artifact.contents =
249
+ (await resolveComponentTemplate(projectRoot, type, artifact.logicalName, templateVars)) ?? artifact.contents;
250
+ }
251
+ markSessionMayHaveChanges();
252
+ if (!parentExists) {
253
+ await fs.mkdir(parentPath, { recursive: true });
254
+ }
255
+ if (componentExists) {
256
+ await replaceComponentDirectory(destination, artifacts);
257
+ }
258
+ else {
259
+ await fs.mkdir(destination);
260
+ try {
261
+ await writeComponentFiles(destination, artifacts);
262
+ }
263
+ catch (error) {
264
+ await cleanUpComponentDirectory(destination);
265
+ throw error;
266
+ }
209
267
  }
210
- return log('success', `${bold(green('Success!'))} The ${bold(cyan(componentName))} component (${yellow(TYPE_LABELS[type].toUpperCase())}) has been created in ${bold(directory)}.`);
268
+ log('success', `Success! The ${componentName} component (${TYPE_LABELS[type].toUpperCase()}) has been created in ${directory}.`);
269
+ return `Created the ${componentName} component in ${directory}`;
211
270
  }
@@ -0,0 +1,197 @@
1
+ import { dirname } from 'path';
2
+ import { writeSync } from 'fs';
3
+ import { confirm } from '@clack/prompts';
4
+ import CliError from '../../lib/CliError.js';
5
+ import log from '../../lib/log.js';
6
+ import { note, onAbort, spinner } from '../../lib/session.js';
7
+ import { runPrompt } from '../prompt/index.js';
8
+ import { classifyComponentNpmDependencies, collectComponentNpmDependencies, } from './componentNpmDependencies.js';
9
+ import { detectComponentPackageManager, readComponentNpmManifest, writeComponentNpmManifest, } from './componentNpmManifest.js';
10
+ import installDependencies from './installDependencies.js';
11
+ function formatSpec({ name, range }) {
12
+ const displayRange = range.trim().replace(/\s+/gu, ' ') || '*';
13
+ return `${name}@${displayRange}`;
14
+ }
15
+ function formatAddCommand(manager, packages) {
16
+ if (manager === 'unsupported')
17
+ return;
18
+ const command = manager === 'npm' ? 'npm install' : `${manager} add`;
19
+ return `${command} ${packages.map((pkg) => `"${formatSpec(pkg)}"`).join(' ')}`;
20
+ }
21
+ export function formatAddedNpmPackages(count) {
22
+ return `added ${count} npm package${count === 1 ? '' : 's'}`;
23
+ }
24
+ export async function prepareComponentNpmInstall(system, components, projectConfigPath, reportOnly) {
25
+ const requirements = collectComponentNpmDependencies(system, components, reportOnly
26
+ ? (error) => log('warn', `${error.message} Ignoring this npm declaration.`)
27
+ : undefined);
28
+ if (requirements.length === 0)
29
+ return;
30
+ if (!projectConfigPath) {
31
+ throw new CliError('Unable to locate the Emulsify project for npm packages.');
32
+ }
33
+ const root = dirname(projectConfigPath);
34
+ const manifest = await readComponentNpmManifest(root);
35
+ const json = manifest.status === 'ready' ? manifest.json : {};
36
+ let manifestProblem;
37
+ if (manifest.status !== 'ready') {
38
+ const names = [...new Set(requirements.flatMap((pkg) => pkg.components))];
39
+ const specs = requirements.map(formatSpec).join(', ');
40
+ const instruction = manifest.status === 'missing'
41
+ ? 'Create it (for example with npm init -y)'
42
+ : 'Provide a valid package.json';
43
+ manifestProblem = `${names.join(', ')} ${names.length === 1 ? 'needs' : 'need'} npm packages (${specs}), but ${manifest.path} ${manifest.reason}. ${instruction} or re-run with --skip-npm.`;
44
+ if (!reportOnly)
45
+ throw new CliError(manifestProblem);
46
+ }
47
+ const packages = classifyComponentNpmDependencies(requirements, json);
48
+ for (const pkg of packages) {
49
+ if (pkg.nonSatisfyingSections?.includes('peerDependencies')) {
50
+ log('warn', `${pkg.name} is declared in peerDependencies. Only dependencies or devDependencies satisfy ${formatSpec(pkg)}.`);
51
+ }
52
+ if (pkg.nonSatisfyingSections?.includes('optionalDependencies')) {
53
+ log('warn', `${pkg.name} is declared in optionalDependencies, which can override dependencies. Move the entry to dependencies or devDependencies with a range that satisfies ${formatSpec(pkg)}.`);
54
+ }
55
+ }
56
+ return {
57
+ root,
58
+ manifest,
59
+ manager: detectComponentPackageManager(root, json.packageManager),
60
+ packages,
61
+ manifestProblem,
62
+ };
63
+ }
64
+ export function getComponentNpmInstallReview(plan, skipNpm) {
65
+ if (!plan || skipNpm || plan.manifest.status !== 'ready')
66
+ return;
67
+ const missing = plan.packages.filter((pkg) => pkg.status === 'missing');
68
+ if (missing.length === 0)
69
+ return;
70
+ const manager = plan.manager === 'npm'
71
+ ? 'npm install --ignore-scripts'
72
+ : plan.manager === 'unsupported'
73
+ ? 'use the manager declared in package.json to install manually'
74
+ : `${plan.manager} (install manually)`;
75
+ return {
76
+ specs: missing.map(formatSpec).join(', '),
77
+ lines: [
78
+ ...missing.map((pkg) => `${formatSpec(pkg)} (needed by ${pkg.components.join(', ')})`),
79
+ `Package manager: ${manager}`,
80
+ ],
81
+ };
82
+ }
83
+ export async function confirmComponentNpmInstall(plan, skipNpm, yes, subject) {
84
+ if (skipNpm)
85
+ return false;
86
+ const review = getComponentNpmInstallReview(plan, skipNpm);
87
+ if (!review)
88
+ return true;
89
+ note(review.lines.join('\n'), 'npm package review');
90
+ return runPrompt({
91
+ prompt: () => confirm({ message: 'Add these npm packages?', initialValue: false }),
92
+ nonInteractive: {
93
+ error: `${subject} requires npm packages (${review.specs}). Pass --yes to install them or --skip-npm to continue without them.`,
94
+ },
95
+ accept: { when: yes, value: true },
96
+ });
97
+ }
98
+ export function formatComponentNpmInstall(plan, mode) {
99
+ if (!plan)
100
+ return ' - none';
101
+ const lines = plan.packages.map((pkg) => {
102
+ const description = `needed by ${pkg.components.join(', ')}`;
103
+ let status;
104
+ switch (pkg.status) {
105
+ case 'satisfied':
106
+ status =
107
+ mode === 'preview' ? 'already satisfied' : 'already in package.json';
108
+ break;
109
+ case 'needs-attention':
110
+ status = pkg.nonSatisfyingSections?.includes('optionalDependencies')
111
+ ? 'needs attention (declared in optionalDependencies)'
112
+ : `needs attention (package.json has ${JSON.stringify(pkg.declaredRange)})`;
113
+ break;
114
+ case 'missing':
115
+ status =
116
+ plan.manifest.status !== 'ready'
117
+ ? `package.json ${plan.manifest.status}`
118
+ : mode === 'install'
119
+ ? 'added'
120
+ : mode === 'preview'
121
+ ? 'would add'
122
+ : 'would add (skipped)';
123
+ break;
124
+ }
125
+ return ` - ${formatSpec(pkg)} · ${status} · ${description}`;
126
+ });
127
+ if (plan.manifestProblem)
128
+ lines.push(plan.manifestProblem);
129
+ if (mode === 'skip') {
130
+ const missing = plan.packages.filter((pkg) => pkg.status === 'missing');
131
+ if (missing.length) {
132
+ const command = formatAddCommand(plan.manager, missing);
133
+ lines.push(command
134
+ ? `From ${plan.root}, run: ${command}`
135
+ : 'Use the package manager declared in package.json to add these packages.');
136
+ }
137
+ }
138
+ return lines.join('\n');
139
+ }
140
+ export async function applyComponentNpmInstall(plan, accepted) {
141
+ if (!plan)
142
+ return 0;
143
+ if (!accepted || plan.manifest.status !== 'ready') {
144
+ note(formatComponentNpmInstall(plan, 'skip'), 'npm packages');
145
+ return 0;
146
+ }
147
+ const additions = new Map(plan.packages
148
+ .filter((pkg) => pkg.status === 'missing')
149
+ .map(({ name, range }) => [name, range]));
150
+ if (additions.size) {
151
+ await writeComponentNpmManifest(plan.manifest, additions);
152
+ }
153
+ else {
154
+ const current = await readComponentNpmManifest(plan.root);
155
+ if (current.status !== 'ready' || current.source !== plan.manifest.source) {
156
+ throw new CliError(`${plan.manifest.path} changed during installation. Run component install to check the packages against the current manifest.`);
157
+ }
158
+ }
159
+ note(formatComponentNpmInstall(plan, 'install'), 'npm packages');
160
+ for (const pkg of plan.packages) {
161
+ if (pkg.status !== 'needs-attention' ||
162
+ pkg.nonSatisfyingSections?.includes('optionalDependencies')) {
163
+ continue;
164
+ }
165
+ const command = formatAddCommand(plan.manager, [pkg]);
166
+ log('warn', `${pkg.name} is in package.json as ${JSON.stringify(pkg.declaredRange)}, but ${pkg.components.join(', ')} ${pkg.components.length === 1 ? 'needs' : 'need'} "${pkg.range}". ${command ? `To change the declaration, run: ${command}` : 'Review the declaration using your project’s package manager.'}`);
167
+ }
168
+ if (additions.size === 0)
169
+ return 0;
170
+ if (plan.manager !== 'npm') {
171
+ const instructions = plan.manager === 'unsupported'
172
+ ? 'Use the package manager declared in package.json to install these packages.'
173
+ : `From ${plan.root}, run: ${plan.manager} install`;
174
+ log('info', instructions);
175
+ return additions.size;
176
+ }
177
+ const progress = spinner();
178
+ const retry = `Run npm install --ignore-scripts in ${plan.root} to finish installing the packages.`;
179
+ const unregisterAbort = onAbort(() => {
180
+ writeSync(process.stderr.fd, `${retry}\n`);
181
+ });
182
+ try {
183
+ progress.start('Installing npm packages');
184
+ await installDependencies(plan.root, { ignoreScripts: true });
185
+ }
186
+ catch (error) {
187
+ progress.error('Unable to install npm packages');
188
+ const output = (error instanceof Error ? error.message : String(error)).trim();
189
+ throw new CliError(`npm install failed:\n${output}\nThe new dependencies remain in package.json.\n${retry}`);
190
+ }
191
+ finally {
192
+ unregisterAbort();
193
+ }
194
+ progress.stop(`Installed ${additions.size} npm package${additions.size === 1 ? '' : 's'} with npm`);
195
+ log('info', 'Lifecycle scripts were not run. If a package needs them, run: npm rebuild');
196
+ return additions.size;
197
+ }
@@ -1,8 +1,15 @@
1
- import { exec } from 'child_process';
2
- export default async function installDependencies(directory) {
1
+ import { execFile } from 'child_process';
2
+ const NPM_INSTALL_TIMEOUT_MS = 10 * 60 * 1_000;
3
+ export default async function installDependencies(directory, { ignoreScripts = false } = {}) {
4
+ const args = ignoreScripts ? ['install', '--ignore-scripts'] : ['install'];
5
+ const shell = process.platform === 'win32';
6
+ const command = shell ? ['npm', ...args].join(' ') : 'npm';
3
7
  return new Promise((resolve, reject) => {
4
- exec('npm install', {
8
+ execFile(command, shell ? [] : args, {
5
9
  cwd: directory,
10
+ maxBuffer: Infinity,
11
+ timeout: NPM_INSTALL_TIMEOUT_MS,
12
+ shell,
6
13
  }, (error, stdout, stderr) => {
7
14
  if (error) {
8
15
  return reject(error);
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { pathExists } from 'fs-extra';
4
+ import CliError from '../../lib/CliError.js';
4
5
  import log from '../../lib/log.js';
5
6
  import { EMULSIFY_PROJECT_TEMPLATES_FOLDER } from '../../lib/constants.js';
6
7
  import renderTemplate, { renderLegacyTemplate, } from './renderTemplate.js';
@@ -18,7 +19,16 @@ export default async function resolveComponentTemplate(projectRoot, type, logica
18
19
  if (!(await pathExists(templatePath))) {
19
20
  continue;
20
21
  }
21
- const template = await fs.readFile(templatePath, 'utf8');
22
+ let template;
23
+ try {
24
+ template = await fs.readFile(templatePath, 'utf8');
25
+ }
26
+ catch (error) {
27
+ const message = error instanceof Error ? error.message : String(error);
28
+ const readError = new CliError(`Unable to read component template override "${templatePath}": ${message}`);
29
+ readError.cause = error;
30
+ throw readError;
31
+ }
22
32
  if (template.trim() === '') {
23
33
  log('warn', `Component template override "${templatePath}" is empty; using the built-in template instead.`);
24
34
  return null;