@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
package/README.md CHANGED
@@ -60,6 +60,10 @@ Unless overridden, its required URL metadata uses obvious, schema-valid
60
60
  `https://TODO.invalid/...` placeholders that must also be replaced before
61
61
  publishing.
62
62
 
63
+ Set `minimumCliVersion` in `system.emulsify.json` to declare the earliest CLI
64
+ version your system supports. See the adoption rule for `npmDependencies` in the
65
+ [system configuration guide](./docs/systems.md#system-repository-shape).
66
+
63
67
  Add `--dry-run` to preview the normalized target, every generated file, and
64
68
  whether Git would be initialized without changing the filesystem.
65
69
 
@@ -116,9 +120,12 @@ emulsify system detach --yes
116
120
  ```
117
121
 
118
122
  For component installation, provide either a component name or `--all`, and use
119
- `--force` when an existing destination should be replaced. For component
120
- creation, provide the positional name plus `--type` and `--directory`, and use
121
- `--force` when an existing generated component should be replaced. The existing
123
+ `--force` when an existing destination should be replaced. Use `--skip-npm` with
124
+ `component install` or `system install` to report the
125
+ [npm packages](./docs/components.md#npm-packages) and install them later.
126
+ For component creation, provide the positional name plus `--type` and
127
+ `--directory`, and use `--force` when an existing generated component should be
128
+ replaced. The existing
122
129
  `-y, --yes` form remains available as a compatibility alias. Explicit
123
130
  `--type` values are honored even when project detection would hide that choice
124
131
  from the wizard. The deprecated `--format default` and `--format sdc` forms
@@ -2,7 +2,7 @@ import { promises as fs } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { CACHE_DIR } from '../lib/constants.js';
4
4
  import CliError from '../lib/CliError.js';
5
- import log from '../lib/log.js';
5
+ import { markSessionMayHaveChanges } from '../lib/session.js';
6
6
  function isMissingPathError(error) {
7
7
  return (error !== null &&
8
8
  typeof error === 'object' &&
@@ -45,18 +45,17 @@ async function inspectCache() {
45
45
  export default async function cacheClear({ dryRun = false, } = {}) {
46
46
  const stats = await inspectCache();
47
47
  if (!stats.exists) {
48
- log('info', 'The Emulsify cache is already empty: 0 buckets and 0 entries.');
49
- return;
48
+ return 'The Emulsify cache is already empty: 0 buckets and 0 entries.';
50
49
  }
51
50
  if (dryRun) {
52
- log('info', `Dry run: the Emulsify cache contains ${stats.bucketCount} buckets and ${stats.entryCount} entries. No files were removed.`);
53
- return;
51
+ return `Dry run: the Emulsify cache contains ${stats.bucketCount} buckets and ${stats.entryCount} entries. No files were removed.`;
54
52
  }
55
53
  try {
54
+ markSessionMayHaveChanges();
56
55
  await fs.rm(CACHE_DIR, { recursive: true, force: true });
57
56
  }
58
57
  catch (error) {
59
58
  throw new CliError(`Unable to clear the Emulsify cache at "${CACHE_DIR}": ${getErrorMessage(error)}`);
60
59
  }
61
- log('success', `Cleared the Emulsify cache: removed ${stats.bucketCount} buckets and ${stats.entryCount} entries.`);
60
+ return `Cleared the Emulsify cache: removed ${stats.bucketCount} buckets and ${stats.entryCount} entries.`;
62
61
  }
@@ -1,15 +1,15 @@
1
- import { input } from '@inquirer/prompts';
1
+ import { text } from '@clack/prompts';
2
2
  import generateComponent from '../util/project/generateComponent.js';
3
3
  import { withEmulsifySystem } from './hofs/withEmulsifySystem.js';
4
4
  import CliError from '../lib/CliError.js';
5
5
  import deriveComponentNames from '../util/deriveComponentNames.js';
6
- import { isExitPromptError, requireInteractiveTerminal, runPrompt, } from '../util/prompt/index.js';
6
+ import { isPromptCancelledError, requireInteractiveTerminal, runPrompt, } from '../util/prompt/index.js';
7
7
  import { MISSING_COMPONENT_DIRECTORY_ERROR, MISSING_COMPONENT_TYPE_ERROR, } from '../util/project/componentTypes.js';
8
8
  const MISSING_COMPONENT_NAME_ERROR = 'Please specify a name for the new component.';
9
9
  function validateComponentName(name) {
10
10
  try {
11
- deriveComponentNames(name);
12
- return true;
11
+ deriveComponentNames(name ?? '');
12
+ return undefined;
13
13
  }
14
14
  catch (error) {
15
15
  return error.message;
@@ -31,17 +31,17 @@ export default async function componentCreate(name, options = {}) {
31
31
  });
32
32
  const componentName = providedComponentName ??
33
33
  (await runPrompt({
34
- prompt: () => input({
35
- message: 'Component name:',
34
+ prompt: () => text({
35
+ message: 'Component name',
36
36
  validate: validateComponentName,
37
37
  }),
38
38
  nonInteractive: { error: MISSING_COMPONENT_NAME_ERROR },
39
39
  }));
40
40
  try {
41
- await generateComponent(variantConf, emulsifyConfig, componentName, options);
41
+ return await generateComponent(variantConf, emulsifyConfig, componentName, options);
42
42
  }
43
43
  catch (e) {
44
- if (isExitPromptError(e)) {
44
+ if (isPromptCancelledError(e)) {
45
45
  throw e;
46
46
  }
47
47
  const msg = e instanceof Error ? e.message : String(e);
@@ -1,4 +1,4 @@
1
- import { checkbox } from '@inquirer/prompts';
1
+ import { multiselect } from '@clack/prompts';
2
2
  import { randomUUID } from 'crypto';
3
3
  import { constants as fsConstants, promises as fs } from 'fs';
4
4
  import { basename, dirname, join } from 'path';
@@ -6,6 +6,7 @@ import { pathExists } from 'fs-extra';
6
6
  import CliError from '../lib/CliError.js';
7
7
  import { EMULSIFY_PROJECT_CONFIG_FILE, EMULSIFY_PROJECT_TEMPLATES_FOLDER, } from '../lib/constants.js';
8
8
  import log from '../lib/log.js';
9
+ import { markSessionMayHaveChanges, note } from '../lib/session.js';
9
10
  import findFileInCurrentPath from '../util/fs/findFileInCurrentPath.js';
10
11
  import safeResolveWithin from '../util/fs/safeResolveWithin.js';
11
12
  import { COMPONENT_TYPES, normalizeComponentType, } from '../util/project/componentTypes.js';
@@ -13,26 +14,26 @@ import { buildEjectableComponentTemplates } from '../util/project/componentTempl
13
14
  import { requireInteractiveTerminal, runPrompt } from '../util/prompt/index.js';
14
15
  export const MISSING_TEMPLATE_TYPE_ERROR = 'Component template selection is required in non-interactive mode. Pass the [type] positional argument (twig, twig-sdc, react, or web-component), or pass --all.';
15
16
  export const CONFLICTING_TEMPLATE_TYPE_ERROR = 'Pass either the [type] positional argument or --all, not both.';
16
- const TYPE_CHOICES = [
17
+ const TYPE_OPTIONS = [
17
18
  {
18
- name: 'Twig',
19
19
  value: 'twig',
20
- description: 'Twig markup, SCSS, YAML data, and a Storybook story',
20
+ label: 'Twig',
21
+ hint: 'Twig markup, SCSS, YAML data, and a Storybook story',
21
22
  },
22
23
  {
23
- name: 'Twig SDC',
24
24
  value: 'twig-sdc',
25
- description: 'Drupal Single Directory Component templates',
25
+ label: 'Twig SDC',
26
+ hint: 'Drupal Single Directory Component templates',
26
27
  },
27
28
  {
28
- name: 'React',
29
29
  value: 'react',
30
- description: 'React JSX, SCSS, and a standard Storybook story',
30
+ label: 'React',
31
+ hint: 'React JSX, SCSS, and a standard Storybook story',
31
32
  },
32
33
  {
33
- name: 'Web Component',
34
34
  value: 'web-component',
35
- description: 'Custom element, SCSS, and an Emulsify Core story',
35
+ label: 'Web Component',
36
+ hint: 'Custom element, SCSS, and an Emulsify Core story',
36
37
  },
37
38
  ];
38
39
  export function buildComponentTemplateEjectionPlan(projectRoot, types) {
@@ -72,17 +73,16 @@ function getDryRunAction(exists, force) {
72
73
  return 'would replace';
73
74
  return 'conflict; a real run requires --force';
74
75
  }
75
- function logDryRun(types, plan, force) {
76
+ function noteDryRun(types, plan, force) {
76
77
  const destinations = plan
77
78
  .map(({ destination, exists }) => ` - ${destination} (${getDryRunAction(exists, force)})`)
78
79
  .join('\n');
79
- log('info', [
80
- 'Dry run: component eject-templates',
80
+ note([
81
81
  `Types: ${types.join(', ')}`,
82
82
  'Template files:',
83
83
  destinations,
84
84
  'No files were written or replaced.',
85
- ].join('\n'));
85
+ ].join('\n'), 'Dry run: component eject-templates');
86
86
  }
87
87
  function formatConflictError(conflicts) {
88
88
  const paths = conflicts
@@ -246,6 +246,7 @@ function formatInstallError(item, error, force, rollbackFailures, cleanupFailure
246
246
  }
247
247
  async function executeTransaction(plan, force) {
248
248
  const transactionPlan = buildTransactionPlan(plan);
249
+ markSessionMayHaveChanges();
249
250
  await stageTransaction(transactionPlan);
250
251
  for (const item of transactionPlan) {
251
252
  try {
@@ -287,10 +288,10 @@ export default async function componentEjectTemplates(type, { all = false, force
287
288
  }
288
289
  else {
289
290
  selectedTypes = await runPrompt({
290
- prompt: () => checkbox({
291
+ prompt: () => multiselect({
291
292
  message: 'Which component template types should be ejected?',
292
- choices: TYPE_CHOICES,
293
- validate: (values) => values.length > 0 || 'Select at least one component type.',
293
+ options: TYPE_OPTIONS,
294
+ required: false,
294
295
  }),
295
296
  nonInteractive: { error: MISSING_TEMPLATE_TYPE_ERROR },
296
297
  });
@@ -302,8 +303,8 @@ export default async function componentEjectTemplates(type, { all = false, force
302
303
  const inspectedPlan = await inspectPlan(buildComponentTemplateEjectionPlan(projectRoot, canonicalTypes));
303
304
  const conflicts = inspectedPlan.filter(({ exists }) => exists);
304
305
  if (dryRun) {
305
- logDryRun(canonicalTypes, inspectedPlan, force);
306
- return;
306
+ noteDryRun(canonicalTypes, inspectedPlan, force);
307
+ return 'Dry run complete';
307
308
  }
308
309
  if (conflicts.length > 0 && !force) {
309
310
  throw new CliError(formatConflictError(conflicts));
@@ -312,6 +313,7 @@ export default async function componentEjectTemplates(type, { all = false, force
312
313
  const paths = inspectedPlan
313
314
  .map(({ destination }) => ` - ${destination}`)
314
315
  .join('\n');
315
- log('success', `Ejected ${inspectedPlan.length} built-in component templates:\n${paths}`);
316
+ note(paths, 'Ejected');
316
317
  log('info', 'Edit these files to customize component create. Delete an override to restore its built-in template.');
318
+ return `Ejected ${inspectedPlan.length} built-in component templates`;
317
319
  }
@@ -1,10 +1,12 @@
1
1
  import { pathExists } from 'fs-extra';
2
- import { confirm, select } from '@inquirer/prompts';
2
+ import { confirm, select } from '@clack/prompts';
3
3
  import log from '../lib/log.js';
4
+ import { markSessionMayHaveChanges, note } from '../lib/session.js';
4
5
  import { EMULSIFY_PROJECT_CONFIG_FILE } from '../lib/constants.js';
5
6
  import CliError from '../lib/CliError.js';
6
7
  import installComponentFromCache, { getComponentDestination, } from '../util/project/installComponentFromCache.js';
7
8
  import buildComponentDependencyList from '../util/project/buildComponentDependencyList.js';
9
+ import { applyComponentNpmInstall, confirmComponentNpmInstall, formatAddedNpmPackages, formatComponentNpmInstall, prepareComponentNpmInstall, } from '../util/project/installComponentNpmDependencies.js';
8
10
  import catchLater from '../util/catchLater.js';
9
11
  import findFileInCurrentPath from '../util/fs/findFileInCurrentPath.js';
10
12
  import { requireInteractiveTerminal, runPrompt } from '../util/prompt/index.js';
@@ -20,8 +22,7 @@ function getDryRunInstallAction(exists, force) {
20
22
  }
21
23
  return 'prompt before replacing or skipping';
22
24
  }
23
- async function buildComponentInstallPlan(variant, componentNames, rootComponentName, force) {
24
- const projectConfigPath = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
25
+ async function buildComponentInstallPlan(variant, componentNames, rootComponentName, force, projectConfigPath) {
25
26
  if (!projectConfigPath) {
26
27
  throw new CliError('Unable to find an Emulsify project to preview component installation into.');
27
28
  }
@@ -39,7 +40,7 @@ async function buildComponentInstallPlan(variant, componentNames, rootComponentN
39
40
  }
40
41
  return plan;
41
42
  }
42
- function logComponentInstallDryRun(targetLabel, dependencies, plan) {
43
+ function logComponentInstallDryRun(targetLabel, dependencies, plan, npmPackages) {
43
44
  const dependencyList = dependencies.length > 0
44
45
  ? dependencies.map((dependency) => ` - ${dependency}`).join('\n')
45
46
  : ' - none';
@@ -57,30 +58,34 @@ function logComponentInstallDryRun(targetLabel, dependencies, plan) {
57
58
  dependencyList,
58
59
  'Planned component installs:',
59
60
  plannedInstalls,
61
+ 'npm packages:',
62
+ npmPackages,
60
63
  'No files were copied, removed, or overwritten.',
61
64
  ].join('\n'));
62
65
  }
63
- export default async function componentInstall(name, { force, all, dryRun, refresh }) {
66
+ export default async function componentInstall(name, { force, all, dryRun, refresh, skipNpm = false, yes = false, }) {
64
67
  let selectedName = name;
65
68
  let installAll = all === true;
66
69
  const needsSelection = !selectedName?.trim() && !installAll;
67
70
  if (needsSelection) {
71
+ if (dryRun)
72
+ throw new CliError(MISSING_COMPONENT_INSTALL_TARGET_ERROR);
68
73
  requireInteractiveTerminal(MISSING_COMPONENT_INSTALL_TARGET_ERROR);
69
74
  }
70
75
  const { systemConf, variantConf } = await withEmulsifySystem('install components', { refresh });
71
76
  if (needsSelection) {
72
77
  const selection = await runPrompt({
73
78
  prompt: () => select({
74
- message: 'Choose a component to install:',
75
- choices: [
79
+ message: 'Choose a component to install',
80
+ options: [
76
81
  ...variantConf.components.map((component) => ({
77
- name: component.name,
78
82
  value: component.name,
79
- description: component.description,
83
+ label: component.name,
84
+ hint: component.structure,
80
85
  })),
81
86
  {
82
- name: 'Install all available components',
83
87
  value: INSTALL_ALL_COMPONENTS,
88
+ label: 'Install all available components',
84
89
  },
85
90
  ],
86
91
  }),
@@ -93,68 +98,65 @@ export default async function componentInstall(name, { force, all, dryRun, refre
93
98
  selectedName = selection;
94
99
  }
95
100
  }
96
- const components = [];
97
- if (installAll) {
98
- const componentNames = variantConf.components.map((component) => component.name);
99
- if (dryRun) {
100
- const plan = await buildComponentInstallPlan(variantConf, componentNames, undefined, true);
101
- logComponentInstallDryRun('all components', [], plan);
102
- return;
103
- }
104
- components.push(...componentNames.map((component) => [
105
- component,
106
- false,
107
- catchLater(installComponentFromCache(systemConf, variantConf, component, true)),
108
- ]));
101
+ const rootComponentName = installAll ? undefined : selectedName || '';
102
+ const componentNames = installAll
103
+ ? variantConf.components.map(({ name }) => name)
104
+ : buildComponentDependencyList(variantConf.components, rootComponentName);
105
+ if (!installAll && componentNames.length === 0) {
106
+ throw new CliError(`Cannot find the definition for component "${rootComponentName}".\n\nRun "emulsify component list" to see the full list.`);
109
107
  }
110
- else {
111
- const rootComponentName = selectedName;
112
- const componentsWithDependencies = buildComponentDependencyList(variantConf.components, rootComponentName);
113
- if (componentsWithDependencies.length === 0) {
114
- throw new CliError(`Cannot find the definition for component "${rootComponentName}".\n\nRun "emulsify component list" to see the full list.`);
115
- }
116
- if (dryRun) {
117
- const dependencies = componentsWithDependencies.filter((dependencyName) => dependencyName !== rootComponentName);
118
- const plan = await buildComponentInstallPlan(variantConf, componentsWithDependencies, rootComponentName, Boolean(force));
119
- logComponentInstallDryRun(rootComponentName, dependencies, plan);
120
- return;
121
- }
122
- const projectConfigPath = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
123
- for (const componentName of componentsWithDependencies) {
124
- const isDependency = componentName !== rootComponentName;
125
- let currentForce = force;
126
- const destination = projectConfigPath
127
- ? getComponentDestination(variantConf, componentName, projectConfigPath)
128
- : undefined;
129
- if (destination && (await pathExists(destination)) && !force) {
130
- const dependencyNote = isDependency
131
- ? ` (required by "${rootComponentName}")`
132
- : '';
133
- const overwriteMessage = `The component "${componentName}"${dependencyNote} already exists.`;
134
- const result = await runPrompt({
135
- prompt: () => confirm({
136
- message: `${overwriteMessage} Would you like to replace it?`,
137
- default: false,
138
- }),
139
- nonInteractive: {
140
- error: `${overwriteMessage} Pass --force to replace existing components in non-interactive mode.`,
141
- },
142
- });
143
- if (result) {
144
- currentForce = true;
145
- }
146
- else {
147
- log('info', `Skipping installation of component "${componentName}".`);
148
- continue;
149
- }
108
+ const projectConfigPath = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
109
+ const plan = [];
110
+ for (const componentName of componentNames) {
111
+ const isDependency = !installAll && componentName !== rootComponentName;
112
+ let currentForce = installAll || Boolean(force);
113
+ const destination = !dryRun && !installAll && projectConfigPath
114
+ ? getComponentDestination(variantConf, componentName, projectConfigPath)
115
+ : undefined;
116
+ if (destination && (await pathExists(destination)) && !currentForce) {
117
+ const dependencyNote = isDependency
118
+ ? ` (required by "${rootComponentName}")`
119
+ : '';
120
+ const overwriteMessage = `The component "${componentName}"${dependencyNote} already exists.`;
121
+ currentForce = await runPrompt({
122
+ prompt: () => confirm({
123
+ message: `${overwriteMessage} Would you like to replace it?`,
124
+ initialValue: false,
125
+ }),
126
+ nonInteractive: {
127
+ error: `${overwriteMessage} Pass --force to replace existing components in non-interactive mode.`,
128
+ },
129
+ });
130
+ if (!currentForce) {
131
+ log('info', `Skipping installation of component "${componentName}".`);
132
+ continue;
150
133
  }
151
- components.push([
152
- componentName,
153
- isDependency,
154
- catchLater(installComponentFromCache(systemConf, variantConf, componentName, currentForce)),
155
- ]);
156
134
  }
135
+ plan.push({ componentName, isDependency, force: currentForce });
136
+ }
137
+ const selectedComponents = installAll
138
+ ? variantConf.components
139
+ : plan.map(({ componentName }) => variantConf.components.find(({ name }) => name === componentName));
140
+ const npmPlan = await prepareComponentNpmInstall(systemConf.name, selectedComponents, projectConfigPath, Boolean(dryRun || skipNpm));
141
+ if (dryRun) {
142
+ const dependencies = installAll
143
+ ? []
144
+ : componentNames.filter((dependency) => dependency !== rootComponentName);
145
+ const preview = await buildComponentInstallPlan(variantConf, componentNames, rootComponentName, Boolean(installAll || force), projectConfigPath);
146
+ logComponentInstallDryRun(rootComponentName ?? 'all components', dependencies, preview, formatComponentNpmInstall(npmPlan, skipNpm ? 'skip' : 'preview'));
147
+ return 'Dry run complete';
157
148
  }
149
+ if (plan.length === 0)
150
+ return 'No components were installed';
151
+ const acceptedNpm = await confirmComponentNpmInstall(npmPlan, skipNpm, yes, plan.some(({ componentName }) => componentName === rootComponentName)
152
+ ? `The ${JSON.stringify(rootComponentName)} component`
153
+ : 'This component install');
154
+ markSessionMayHaveChanges();
155
+ const components = plan.map(({ componentName, isDependency, force }) => [
156
+ componentName,
157
+ isDependency,
158
+ catchLater(installComponentFromCache(systemConf, variantConf, componentName, force)),
159
+ ]);
158
160
  const installedDeps = [];
159
161
  const failedDeps = [];
160
162
  const failureMessages = [];
@@ -178,7 +180,7 @@ export default async function componentInstall(name, { force, all, dryRun, refre
178
180
  }
179
181
  if (installedDeps.length > 0) {
180
182
  const depList = installedDeps.map((d) => ` → ${d}`).join('\n');
181
- log('info', `The following dependencies were also installed:\n${depList}`);
183
+ note(depList, 'Also installed');
182
184
  }
183
185
  if (failedDeps.length > 0) {
184
186
  const failList = failedDeps.map((d) => ` → ${d}`).join('\n');
@@ -187,4 +189,7 @@ export default async function componentInstall(name, { force, all, dryRun, refre
187
189
  if (failureMessages.length > 0) {
188
190
  throw new CliError(failureMessages.join('\n'));
189
191
  }
192
+ const added = await applyComponentNpmInstall(npmPlan, acceptedNpm);
193
+ const summary = `Installed ${plan.length} component${plan.length === 1 ? '' : 's'}`;
194
+ return added ? `${summary} · ${formatAddedNpmPackages(added)}` : summary;
190
195
  }
@@ -1,10 +1,57 @@
1
- import log from '../lib/log.js';
1
+ import { note } from '../lib/session.js';
2
2
  import { withEmulsifySystem } from './hofs/withEmulsifySystem.js';
3
+ function pluralize(count, singular) {
4
+ return `${count} ${count === 1 ? singular : `${singular}s`}`;
5
+ }
6
+ function groupByStructure(components) {
7
+ const groups = new Map();
8
+ for (const component of components) {
9
+ const group = groups.get(component.structure);
10
+ if (group) {
11
+ group.push(component);
12
+ continue;
13
+ }
14
+ groups.set(component.structure, [component]);
15
+ }
16
+ return groups;
17
+ }
18
+ export function formatComponentList(components) {
19
+ if (components.length === 0) {
20
+ return 'This variant offers no components.';
21
+ }
22
+ const nameWidth = Math.max(...components.map(({ name }) => name.length));
23
+ const lines = [];
24
+ for (const [structure, group] of groupByStructure(components)) {
25
+ const requiredCount = group.filter(({ required }) => required).length;
26
+ const heading = [
27
+ structure,
28
+ pluralize(group.length, 'component'),
29
+ ...(requiredCount > 0 ? [`${requiredCount} required`] : []),
30
+ ].join(' · ');
31
+ if (lines.length > 0) {
32
+ lines.push('');
33
+ }
34
+ lines.push(heading);
35
+ for (const { name, required, dependency, npmDependencies } of group) {
36
+ const packageNames = Object.keys(npmDependencies ?? {});
37
+ const notes = [
38
+ ...(required ? ['required'] : []),
39
+ ...(dependency && dependency.length > 0
40
+ ? [`needs ${dependency.join(', ')}`]
41
+ : []),
42
+ ...(packageNames.length > 0 ? [`npm ${packageNames.join(', ')}`] : []),
43
+ ];
44
+ lines.push(` ${name.padEnd(nameWidth)} ${notes.join(' · ')}`.trimEnd());
45
+ }
46
+ }
47
+ return lines.join('\n');
48
+ }
3
49
  export default async function componentList({ refresh, } = {}) {
4
50
  const { variantConf } = await withEmulsifySystem('list components', {
5
51
  refresh,
6
52
  });
7
- variantConf.components.map(({ name, structure }) => {
8
- log('info', `${structure} -> ${name}`);
9
- });
53
+ const { components } = variantConf;
54
+ note(formatComponentList(components), 'Available components');
55
+ const structureCount = groupByStructure(components).size;
56
+ return `${pluralize(components.length, 'component')} across ${pluralize(structureCount, 'structure')}`;
10
57
  }
@@ -63,7 +63,9 @@ export async function withEmulsifySystem(actionLabel, { refresh = false } = {})
63
63
  try {
64
64
  await cloneIntoCache('systems', [systemName], { refresh })(systemReference);
65
65
  }
66
- catch {
66
+ catch (error) {
67
+ if (error instanceof CliError)
68
+ throw error;
67
69
  throw new EmulsifySystemError('The system specified in your project configuration is not clone-able, or has an invalid checkout value.');
68
70
  }
69
71
  const loadedSystemConf = await getJsonFromCachedFile({
@@ -0,0 +1,8 @@
1
+ import { finishSession, startSession } from '../../lib/session.js';
2
+ export default function withSession(title, action) {
3
+ return async (...args) => {
4
+ startSession(title);
5
+ const summary = await action(...args);
6
+ finishSession(typeof summary === 'string' ? summary : undefined);
7
+ };
8
+ }