@emulsify/cli 2.4.0 → 2.4.2

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.
@@ -16,15 +16,10 @@ function validateComponentName(name) {
16
16
  }
17
17
  }
18
18
  export default async function componentCreate(name, options = {}) {
19
- const componentName = name?.trim()
20
- ? name
21
- : await runPrompt({
22
- prompt: () => input({
23
- message: 'Component name:',
24
- validate: validateComponentName,
25
- }),
26
- nonInteractive: { error: MISSING_COMPONENT_NAME_ERROR },
27
- });
19
+ const providedComponentName = name?.trim() ? name : undefined;
20
+ if (!providedComponentName) {
21
+ requireInteractiveTerminal(MISSING_COMPONENT_NAME_ERROR);
22
+ }
28
23
  if (!options.type && !options.format) {
29
24
  requireInteractiveTerminal(MISSING_COMPONENT_TYPE_ERROR);
30
25
  }
@@ -34,6 +29,14 @@ export default async function componentCreate(name, options = {}) {
34
29
  const { emulsifyConfig, variantConf } = await withEmulsifySystem('create components', {
35
30
  refresh: options.refresh,
36
31
  });
32
+ const componentName = providedComponentName ??
33
+ (await runPrompt({
34
+ prompt: () => input({
35
+ message: 'Component name:',
36
+ validate: validateComponentName,
37
+ }),
38
+ nonInteractive: { error: MISSING_COMPONENT_NAME_ERROR },
39
+ }));
37
40
  try {
38
41
  await generateComponent(variantConf, emulsifyConfig, componentName, options);
39
42
  }
@@ -5,6 +5,7 @@ import { input, select } from '@inquirer/prompts';
5
5
  import { EMULSIFY_PROJECT_CONFIG_FILE, EMULSIFY_PROJECT_HOOK_INIT, EMULSIFY_PROJECT_HOOK_FOLDER, } from '../lib/constants.js';
6
6
  import getPlatformInfo from '../util/platform/getPlatformInfo.js';
7
7
  import getAvailableStarters from '../util/getAvailableStarters.js';
8
+ import loadJsonFile from '../util/fs/loadJsonFile.js';
8
9
  import writeToJsonFile from '../util/fs/writeToJsonFile.js';
9
10
  import strToMachineName from '../util/strToMachineName.js';
10
11
  import installDependencies from '../util/project/installDependencies.js';
@@ -23,6 +24,22 @@ const PLATFORM_CHOICES = [
23
24
  'wordpress',
24
25
  'none',
25
26
  ];
27
+ function isAlreadyExistsError(error) {
28
+ return (error !== null &&
29
+ typeof error === 'object' &&
30
+ 'code' in error &&
31
+ error.code === 'EEXIST');
32
+ }
33
+ async function rollbackFailedInitialization(target, phase, error) {
34
+ const failure = `Unable to initialize project while ${phase}: ${String(error)}`;
35
+ try {
36
+ await fs.rm(target, { recursive: true, force: true });
37
+ return new CliError(`${failure}. Removed the incomplete target "${target}".`);
38
+ }
39
+ catch (cleanupError) {
40
+ return new CliError(`${failure}. Automatic cleanup of the incomplete target "${target}" also failed: ${String(cleanupError)}. Remove it manually before retrying.`);
41
+ }
42
+ }
26
43
  export default function init(progress) {
27
44
  return async (name, targetDirectory, options) => {
28
45
  const { name: autoPlatformName, emulsifyParentDirectory } = (await getPlatformInfo()) || {};
@@ -99,6 +116,16 @@ export default function init(progress) {
99
116
  if (existsSync(target)) {
100
117
  throw new CliError(`The intended target is already occupied: ${target}`);
101
118
  }
119
+ try {
120
+ await fs.mkdir(target);
121
+ }
122
+ catch (error) {
123
+ if (isAlreadyExistsError(error)) {
124
+ throw new CliError(`The intended target is already occupied: ${target}`);
125
+ }
126
+ throw new CliError(`Unable to initialize project while creating the target directory "${target}": ${String(error)}`);
127
+ }
128
+ let phase = 'cloning the starter';
102
129
  try {
103
130
  progress.tick(10, { message: 'validation complete, cloning starter' });
104
131
  await git.clone(repository, target, checkout
@@ -106,36 +133,48 @@ export default function init(progress) {
106
133
  '--branch': checkout,
107
134
  }
108
135
  : {});
109
- await writeToJsonFile(join(target, EMULSIFY_PROJECT_CONFIG_FILE), {
136
+ phase = 'reading the starter project configuration';
137
+ const configPath = join(target, EMULSIFY_PROJECT_CONFIG_FILE);
138
+ const starterConfig = await loadJsonFile(configPath);
139
+ phase = 'writing the project configuration';
140
+ await writeToJsonFile(configPath, {
141
+ ...starterConfig,
110
142
  project: {
143
+ ...starterConfig?.project,
111
144
  platform: platformName,
112
145
  name: projectName,
113
146
  machineName,
114
147
  },
115
- starter: { repository },
148
+ starter: {
149
+ ...starterConfig?.starter,
150
+ repository,
151
+ },
116
152
  });
117
153
  progress.tick(30, {
118
154
  message: 'starter cloned, installing dependencies (this will take a moment)',
119
155
  });
156
+ phase = 'installing dependencies';
120
157
  await installDependencies(target);
121
158
  progress.tick(40, {
122
159
  message: 'dependencies installed, executing init script',
123
160
  });
124
161
  const initPath = join(target, EMULSIFY_PROJECT_HOOK_FOLDER, EMULSIFY_PROJECT_HOOK_INIT);
125
162
  if (existsSync(initPath)) {
163
+ phase = 'executing the starter init hook';
126
164
  await executeScript(initPath);
127
165
  }
166
+ phase = 'removing the starter Git metadata';
128
167
  await fs.rm(join(target, '.git'), { recursive: true });
129
- progress.tick(10, {
130
- message: 'init script executed, initialization complete',
131
- });
132
- log('success', `Created an Emulsify project in ${target}.`);
133
- getInitSuccessMessageForPlatform(platformName, target, {
134
- includeDrupalInstallReminder: isDetectedDrupalProject && platformName === 'drupal',
135
- }).map(({ method, message }) => log(method, message));
136
168
  }
137
169
  catch (e) {
138
- throw new CliError(`Unable to pull down ${repository}: ${String(e)}`);
170
+ throw await rollbackFailedInitialization(target, phase, e);
139
171
  }
172
+ progress.tick(10, {
173
+ message: 'init script executed, initialization complete',
174
+ });
175
+ log('success', `Created an Emulsify project in ${target}.`);
176
+ getInitSuccessMessageForPlatform(platformName, target, {
177
+ includeDrupalInstallReminder: isDetectedDrupalProject && platformName === 'drupal',
178
+ }).map(({ method, message }) => log(method, message));
140
179
  };
141
180
  }
@@ -19,7 +19,7 @@ import executeScript from '../util/fs/executeScript.js';
19
19
  import validateSystemConfig from '../util/system/validateSystemConfig.js';
20
20
  import { getVariantPlatformExpressions, isPlatform, parsePlatformExpression, rankPlatformVariants, selectCompatiblePlatformVariant, selectExactPlatformVariant, } from '../util/platform/platformCompatibility.js';
21
21
  import { runPrompt } from '../util/prompt/index.js';
22
- import buildSystemInstallPlan from '../util/system/buildSystemInstallPlan.js';
22
+ import buildSystemInstallPlan, { selectSystemComponents, } from '../util/system/buildSystemInstallPlan.js';
23
23
  const MISSING_SYSTEM_SOURCE_ERROR = 'No component system source was provided. Pass a built-in system name as the positional argument, or pass both --repository <repository> and --checkout <branch, tag, or commit>.';
24
24
  const INVALID_SYSTEM_SOURCE_ERROR = 'Unable to resolve the requested component system source. Pass a valid built-in system name as the positional argument, or pass both --repository <repository> and --checkout <branch, tag, or commit>.';
25
25
  const WIZARD_TITLE = 'Install a component system';
@@ -409,6 +409,8 @@ export default async function systemInstall(name, options) {
409
409
  }
410
410
  }
411
411
  catch (e) {
412
+ if (e instanceof CliError)
413
+ throw e;
412
414
  console.error('System configuration errors:', e);
413
415
  throw new CliError(`The system install failed due to the validation errors reported above. Please fix the errors in the "${systemConf.name}" configuration and try again.`);
414
416
  }
@@ -448,9 +450,7 @@ export default async function systemInstall(name, options) {
448
450
  const installAll = guidedInstall && !options.all
449
451
  ? await promptForInstallScope(variantConf, ++wizardStep, wizardTotalSteps)
450
452
  : options.all === true;
451
- let componentsToInstall = installAll
452
- ? variantConf.components
453
- : variantConf.components.filter(({ required }) => required === true);
453
+ let componentsToInstall = selectSystemComponents(variantConf, installAll);
454
454
  if (guidedInstall) {
455
455
  const projectConfigPath = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
456
456
  if (!projectConfigPath) {
package/dist/index.js CHANGED
@@ -73,6 +73,7 @@ system
73
73
  .action(systemDetach);
74
74
  const component = program
75
75
  .command('component')
76
+ .alias('components')
76
77
  .description('List, install, create, or customize components');
77
78
  component
78
79
  .command('list')
@@ -19,6 +19,10 @@
19
19
  "format": "uri",
20
20
  "description": "Git URL to the repository containing the system"
21
21
  },
22
+ "minimumCliVersion": {
23
+ "type": "string",
24
+ "description": "Minimum Emulsify CLI version required to use this system"
25
+ },
22
26
  "structure": {
23
27
  "type": "array",
24
28
  "description": "Objects that describe the structure of the system. Each structural item depicts a category within the system, such as a component folder, and MUST be implemented within each of the system's variants",
@@ -62,13 +66,11 @@
62
66
  "$ref": "variant.json#/definitions/files"
63
67
  }
64
68
  },
65
- "additionalProperties": false,
66
69
  "required": ["platform", "structureImplementations", "components"]
67
70
  }
68
71
  ]
69
72
  }
70
73
  }
71
74
  },
72
- "additionalProperties": false,
73
75
  "required": ["name", "homepage", "repository", "structure"]
74
76
  }
@@ -49,7 +49,6 @@
49
49
  "description": "Relative path to the folder that will hold all of the assets, components, and files related to the structure"
50
50
  }
51
51
  },
52
- "additionalProperties": false,
53
52
  "required": ["name", "directory"]
54
53
  }
55
54
  },
@@ -83,7 +82,6 @@
83
82
  }
84
83
  }
85
84
  },
86
- "additionalProperties": false,
87
85
  "required": ["name", "structure"]
88
86
  }
89
87
  },
@@ -110,7 +108,6 @@
110
108
  "description": "Text describing the intended purpose of the folder"
111
109
  }
112
110
  },
113
- "additionalProperties": false,
114
111
  "required": ["name", "path", "destinationPath"]
115
112
  }
116
113
  },
@@ -137,7 +134,6 @@
137
134
  "description": "Text describing the intended purpose of the file"
138
135
  }
139
136
  },
140
- "additionalProperties": false,
141
137
  "required": ["name", "path", "destinationPath"]
142
138
  }
143
139
  }
@@ -159,7 +155,6 @@
159
155
  "$ref": "#/definitions/files"
160
156
  }
161
157
  },
162
- "additionalProperties": false,
163
158
  "required": [
164
159
  "platform",
165
160
  "structureImplementations",
@@ -1,5 +1,6 @@
1
1
  import { dirname, relative, sep } from 'path';
2
2
  import safeResolveWithin from '../fs/safeResolveWithin.js';
3
+ import buildComponentDependencyList from '../project/buildComponentDependencyList.js';
3
4
  import { getComponentDestination } from '../project/installComponentFromCache.js';
4
5
  function toProjectRelativeDisplayPath(projectRoot, destination) {
5
6
  const displayPath = relative(projectRoot, destination).split(sep).join('/');
@@ -8,6 +9,14 @@ function toProjectRelativeDisplayPath(projectRoot, destination) {
8
9
  function uniqueInOrder(values) {
9
10
  return [...new Set(values)];
10
11
  }
12
+ export function selectSystemComponents(variantConf, installAll) {
13
+ if (installAll) {
14
+ return [...variantConf.components];
15
+ }
16
+ const requiredComponents = variantConf.components.filter(({ required }) => required === true);
17
+ const selectedNames = uniqueInOrder(requiredComponents.flatMap(({ name }) => buildComponentDependencyList(variantConf.components, name)));
18
+ return selectedNames.map((name) => variantConf.components.find((component) => component.name === name));
19
+ }
11
20
  function assertSystemStructure(systemConf, component) {
12
21
  if (!systemConf.structure.some(({ name }) => name === component.structure)) {
13
22
  throw new Error(`The structure (${component.structure}) specified within the component ${component.name} is invalid.`);
@@ -16,9 +25,7 @@ function assertSystemStructure(systemConf, component) {
16
25
  export default function buildSystemInstallPlan(systemConf, variantConf, installAll, projectConfigPath) {
17
26
  const projectRoot = dirname(projectConfigPath);
18
27
  const requiredComponents = variantConf.components.filter(({ required }) => required === true);
19
- const components = installAll
20
- ? [...variantConf.components]
21
- : requiredComponents;
28
+ const components = selectSystemComponents(variantConf, installAll);
22
29
  const componentParentDestinations = uniqueInOrder(components.map((component) => {
23
30
  assertSystemStructure(systemConf, component);
24
31
  return toProjectRelativeDisplayPath(projectRoot, dirname(getComponentDestination(variantConf, component.name, projectConfigPath)));
@@ -1,5 +1,8 @@
1
1
  import { Ajv } from 'ajv';
2
2
  import addFormats from 'ajv-formats';
3
+ import CliError from '../../lib/CliError.js';
4
+ import log from '../../lib/log.js';
5
+ const upgradeCommand = 'npm i -g @emulsify/cli@latest';
3
6
  async function loadSchemas() {
4
7
  const [{ default: systemSchema }, { default: variantSchema }] = await Promise.all([
5
8
  import('../../schemas/system.json', { with: { type: 'json' } }),
@@ -7,21 +10,70 @@ async function loadSchemas() {
7
10
  ]);
8
11
  return { systemSchema, variantSchema };
9
12
  }
13
+ async function createValidator() {
14
+ const [schemas, { default: packageInfo }] = await Promise.all([
15
+ loadSchemas(),
16
+ import('../../../package.json', { with: { type: 'json' } }),
17
+ ]);
18
+ const ajv = new Ajv();
19
+ addFormats(ajv, ['uri']);
20
+ ajv.addSchema(schemas.variantSchema, 'variant.json');
21
+ return {
22
+ validate: ajv.compile(schemas.systemSchema),
23
+ schemas,
24
+ runningVersion: packageInfo.version,
25
+ };
26
+ }
10
27
  let validatorPromise;
11
- async function getValidator() {
12
- if (!validatorPromise) {
13
- validatorPromise = loadSchemas().then(({ systemSchema, variantSchema }) => {
14
- const ajv = new Ajv();
15
- addFormats(ajv, ['uri']);
16
- ajv.addSchema(variantSchema, 'variant.json');
17
- return ajv.compile(systemSchema);
18
- });
28
+ function checkMinimumCliVersion({ name, minimumCliVersion }, runningVersion) {
29
+ if (minimumCliVersion === undefined)
30
+ return;
31
+ const minimum = minimumCliVersion.match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].+)?$/);
32
+ if (!minimum) {
33
+ throw new CliError(`The ${JSON.stringify(name)} system has an invalid minimumCliVersion ${JSON.stringify(minimumCliVersion)}. Use a version such as "2.5.0".`);
34
+ }
35
+ const running = runningVersion.split(/[.+-]/, 3).map(Number);
36
+ const required = minimum.slice(1).map(Number);
37
+ const index = required.findIndex((part, i) => part !== running[i]);
38
+ if (index !== -1 && running[index] < required[index]) {
39
+ throw new CliError(`The ${JSON.stringify(name)} system requires Emulsify CLI ${minimumCliVersion} or newer. You are running ${runningVersion}. Upgrade with: ${upgradeCommand}`);
40
+ }
41
+ }
42
+ function warnUnknownProperties(systemConfig, { systemSchema, variantSchema }) {
43
+ const unknown = [];
44
+ const collect = (value, properties, location) => {
45
+ const keys = Object.keys(value).filter((key) => !Object.hasOwn(properties, key));
46
+ if (keys.length > 0) {
47
+ unknown.push(`${location}: ${keys.join(', ')}`);
48
+ }
49
+ };
50
+ collect(systemConfig, systemSchema.properties, 'system');
51
+ const variantProperties = systemSchema.properties.variants.items.anyOf[0].properties;
52
+ const items = [
53
+ ['structureImplementations', 'structure implementation'],
54
+ ['components', 'component'],
55
+ ['directories', 'directory'],
56
+ ['files', 'file'],
57
+ ];
58
+ for (const [index, variant] of (systemConfig.variants ?? []).entries()) {
59
+ const location = `variant[${index}] (${JSON.stringify(variant.platform)})`;
60
+ collect(variant, variantProperties, location);
61
+ for (const [key, label] of items) {
62
+ for (const item of variant[key] ?? []) {
63
+ collect(item, variantSchema.definitions[key].items.properties, `${location} ${label} ${JSON.stringify(item.name)}`);
64
+ }
65
+ }
66
+ }
67
+ if (unknown.length > 0) {
68
+ log('warn', `This system uses configuration this version of Emulsify CLI does not understand (${unknown.join('; ')}). Upgrade with \`${upgradeCommand}\` if the system is not behaving as documented.`);
19
69
  }
20
- return validatorPromise;
21
70
  }
22
71
  export default async function validateSystemConfig(systemConfig) {
23
- const validate = await getValidator();
72
+ const { validate, schemas, runningVersion } = await (validatorPromise ??=
73
+ createValidator());
24
74
  if (validate(systemConfig)) {
75
+ checkMinimumCliVersion(systemConfig, runningVersion);
76
+ warnUnknownProperties(systemConfig, schemas);
25
77
  return { valid: true, systemConfig };
26
78
  }
27
79
  return { valid: false, errors: validate.errors };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@emulsify/cli",
3
3
  "productName": "Emulsify CLI",
4
- "version": "2.4.0",
4
+ "version": "2.4.2",
5
5
  "description": "Build and use component systems in Drupal, WordPress, or standalone front ends.",
6
6
  "repository": "git@github.com:emulsify-ds/emulsify-cli.git",
7
7
  "author": "Patrick Coffey <patrickcoffey48@gmail.com>",
@@ -80,6 +80,6 @@
80
80
  "consola": "^3.4.2",
81
81
  "fs-extra": "^11.4.0",
82
82
  "progress": "^2.0.3",
83
- "simple-git": "^3.36.0"
83
+ "simple-git": "^4.0.2"
84
84
  }
85
85
  }