@emulsify/cli 2.3.0 → 2.4.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 (43) hide show
  1. package/README.md +96 -16
  2. package/dist/handlers/componentCreate.js +34 -5
  3. package/dist/handlers/componentEjectTemplates.js +317 -0
  4. package/dist/handlers/componentInstall.js +54 -14
  5. package/dist/handlers/hofs/withEmulsifySystem.js +1 -1
  6. package/dist/handlers/init.js +26 -22
  7. package/dist/handlers/systemCreate.js +222 -0
  8. package/dist/handlers/systemDetach.js +50 -0
  9. package/dist/handlers/systemInstall.js +341 -101
  10. package/dist/index.js +66 -110
  11. package/dist/lib/log.js +12 -9
  12. package/dist/lib/rootHelp.js +321 -0
  13. package/dist/lib/terminalColors.js +10 -0
  14. package/dist/schemas/emulsifyProjectConfig.json +59 -0
  15. package/dist/util/cache/cloneIntoCache.js +2 -4
  16. package/dist/util/deriveComponentNames.js +5 -0
  17. package/dist/util/deriveCustomElementTagName.js +25 -0
  18. package/dist/util/fs/writeToJsonFile.js +21 -5
  19. package/dist/util/getGitRepoNameFromUrl.js +47 -3
  20. package/dist/util/getNonInteractiveGitEnvironment.js +7 -0
  21. package/dist/util/getRepositoryLatestTag.js +17 -2
  22. package/dist/util/platform/platformCompatibility.js +18 -7
  23. package/dist/util/project/componentTemplates/buildComponentArtifacts.js +121 -0
  24. package/dist/util/project/componentTemplates/index.js +5 -0
  25. package/dist/util/project/componentTemplates/react.js +20 -0
  26. package/dist/util/project/componentTemplates/reactStories.js +18 -0
  27. package/dist/util/project/componentTemplates/scss.js +2 -3
  28. package/dist/util/project/componentTemplates/sdcStories.js +2 -2
  29. package/dist/util/project/componentTemplates/stories.js +2 -2
  30. package/dist/util/project/componentTemplates/twig.js +2 -3
  31. package/dist/util/project/componentTemplates/webComponent.js +49 -0
  32. package/dist/util/project/componentTemplates/webComponentStories.js +19 -0
  33. package/dist/util/project/componentTypes.js +71 -0
  34. package/dist/util/project/generateComponent.js +139 -101
  35. package/dist/util/project/getEmulsifyConfig.js +4 -0
  36. package/dist/util/project/renderTemplate.js +24 -4
  37. package/dist/util/project/resolveComponentTemplate.js +24 -11
  38. package/dist/util/project/unsetEmulsifyConfig.js +16 -0
  39. package/dist/util/prompt/index.js +25 -0
  40. package/dist/util/system/buildSystemInstallPlan.js +46 -0
  41. package/dist/util/system/buildSystemScaffold.js +99 -0
  42. package/dist/util/system/getAvailableSystems.js +4 -0
  43. package/package.json +2 -2
@@ -13,6 +13,7 @@ import getInitSuccessMessageForPlatform from '../util/platform/getInitSuccessMes
13
13
  import log from '../lib/log.js';
14
14
  import CliError from '../lib/CliError.js';
15
15
  import { isPlatform } from '../util/platform/platformCompatibility.js';
16
+ import { runPrompt } from '../util/prompt/index.js';
16
17
  const git = simpleGit();
17
18
  export const DIRECTORY = 1;
18
19
  const DEFAULT_PROJECT_NAME = 'emulsifyTheme';
@@ -26,34 +27,36 @@ export default function init(progress) {
26
27
  return async (name, targetDirectory, options) => {
27
28
  const { name: autoPlatformName, emulsifyParentDirectory } = (await getPlatformInfo()) || {};
28
29
  const isDetectedDrupalProject = autoPlatformName === 'drupal';
29
- const canPrompt = process.stdin.isTTY === true;
30
30
  const acceptDefaults = options?.yes === true;
31
31
  let projectName = name || options?.machineName;
32
32
  if (!projectName) {
33
- if (acceptDefaults) {
34
- projectName = DEFAULT_PROJECT_NAME;
35
- }
36
- else if (canPrompt) {
37
- projectName = await input({
33
+ projectName = await runPrompt({
34
+ prompt: () => input({
38
35
  message: 'Project name:',
39
36
  default: DEFAULT_PROJECT_NAME,
40
- });
41
- }
37
+ }),
38
+ nonInteractive: {
39
+ error: 'Unable to determine the project name. Please provide a valid project name.',
40
+ },
41
+ accept: {
42
+ when: acceptDefaults,
43
+ value: DEFAULT_PROJECT_NAME,
44
+ },
45
+ });
42
46
  }
43
47
  if (!projectName) {
44
48
  throw new CliError('Unable to determine the project name. Please provide a valid project name.');
45
49
  }
46
50
  let targetParent = targetDirectory || emulsifyParentDirectory;
47
51
  if (!targetParent) {
48
- if (acceptDefaults) {
49
- targetParent = './';
50
- }
51
- else if (canPrompt) {
52
- targetParent = await input({
52
+ targetParent = await runPrompt({
53
+ prompt: () => input({
53
54
  message: 'Target directory:',
54
55
  default: './',
55
- });
56
- }
56
+ }),
57
+ nonInteractive: { value: undefined },
58
+ accept: { when: acceptDefaults, value: './' },
59
+ });
57
60
  }
58
61
  const requestedPlatformName = options?.platform || autoPlatformName;
59
62
  let platformName = isPlatform(requestedPlatformName)
@@ -63,16 +66,17 @@ export default function init(progress) {
63
66
  throw new CliError(`Unsupported platform "${requestedPlatformName}". Supported platforms are "none", "drupal", and "wordpress".`);
64
67
  }
65
68
  if (!platformName) {
66
- if (acceptDefaults) {
67
- platformName = DEFAULT_PLATFORM;
68
- }
69
- else if (canPrompt) {
70
- platformName = await select({
69
+ platformName = await runPrompt({
70
+ prompt: () => select({
71
71
  message: 'Platform:',
72
72
  choices: PLATFORM_CHOICES,
73
73
  default: DEFAULT_PLATFORM,
74
- });
75
- }
74
+ }),
75
+ nonInteractive: {
76
+ error: 'Unable to determine which platform you are installing Emulsify within. Please specify a platform (such as "drupal" or "wordpress") by passing a -p or --platform flag with your init command.',
77
+ },
78
+ accept: { when: acceptDefaults, value: DEFAULT_PLATFORM },
79
+ });
76
80
  }
77
81
  if (!platformName) {
78
82
  throw new CliError('Unable to determine which platform you are installing Emulsify within. Please specify a platform (such as "drupal" or "wordpress") by passing a -p or --platform flag with your init command.');
@@ -0,0 +1,222 @@
1
+ import { checkbox, confirm, input } from '@inquirer/prompts';
2
+ import { existsSync, promises as fs } from 'fs';
3
+ import { dirname, join, resolve } from 'path';
4
+ import { simpleGit } from 'simple-git';
5
+ import CliError from '../lib/CliError.js';
6
+ import log from '../lib/log.js';
7
+ import { EMULSIFY_SYSTEM_CONFIG_FILE } from '../lib/constants.js';
8
+ import strToMachineName from '../util/strToMachineName.js';
9
+ import safeResolveWithin from '../util/fs/safeResolveWithin.js';
10
+ import writeToJsonFile from '../util/fs/writeToJsonFile.js';
11
+ import { normalizePlatformExpression } from '../util/platform/platformCompatibility.js';
12
+ import { runPrompt } from '../util/prompt/index.js';
13
+ import buildSystemScaffold from '../util/system/buildSystemScaffold.js';
14
+ import validateSystemConfig from '../util/system/validateSystemConfig.js';
15
+ const DEFAULT_SYSTEM_NAME = 'custom-system';
16
+ const DEFAULT_TARGET_DIRECTORY = './';
17
+ const DEFAULT_PLATFORM = 'none';
18
+ const PLATFORM_CHOICES = [
19
+ {
20
+ name: 'Generic / no platform',
21
+ value: 'none',
22
+ checked: true,
23
+ },
24
+ { name: 'Drupal', value: 'drupal' },
25
+ { name: 'WordPress', value: 'wordpress' },
26
+ ];
27
+ export function normalizeSystemName(name) {
28
+ const trimmedName = name?.trim() || '';
29
+ const machineName = strToMachineName(trimmedName.replace(/([a-z\d])([A-Z])/g, '$1 $2').replace(/[-_]+/g, ' '));
30
+ if (machineName.length < 3) {
31
+ throw new CliError('System name must contain at least three letters or numbers. Pass the [name] positional argument or use --yes for the default.');
32
+ }
33
+ return machineName;
34
+ }
35
+ function validatePromptedSystemName(name) {
36
+ try {
37
+ normalizeSystemName(name);
38
+ return true;
39
+ }
40
+ catch (error) {
41
+ return error instanceof Error ? error.message : String(error);
42
+ }
43
+ }
44
+ function normalizeRequestedPlatform(platform) {
45
+ try {
46
+ return normalizePlatformExpression(platform);
47
+ }
48
+ catch {
49
+ throw new CliError(`Unsupported platform expression "${platform}". Pass --platform with none, drupal, wordpress, or a supported expression such as "drupal || wordpress".`);
50
+ }
51
+ }
52
+ function formatValidationErrors(errors) {
53
+ return (errors
54
+ ?.map(({ instancePath, message }) => `${instancePath || '/'} ${message || 'is invalid'}`)
55
+ .join('; ') || 'unknown schema validation error');
56
+ }
57
+ function getErrorMessage(error) {
58
+ return error instanceof Error ? error.message : String(error);
59
+ }
60
+ function isAlreadyExistsError(error) {
61
+ return (error !== null &&
62
+ typeof error === 'object' &&
63
+ 'code' in error &&
64
+ error.code === 'EEXIST');
65
+ }
66
+ function logDryRun(target, targetExists, platform, initializeGit, files) {
67
+ const plannedFiles = files
68
+ .map((destination) => ` - ${destination}`)
69
+ .join('\n');
70
+ const realRunAction = targetExists
71
+ ? 'refuse because the target is already occupied'
72
+ : 'create the system scaffold';
73
+ const gitAction = initializeGit
74
+ ? 'would initialize a repository on branch main'
75
+ : 'would not initialize a repository';
76
+ log('info', [
77
+ 'Dry run: system create',
78
+ `Target: ${target} (${targetExists ? 'exists' : 'would be created'})`,
79
+ `Platform: ${platform}`,
80
+ `Git: ${gitAction}`,
81
+ `Real run would: ${realRunAction}`,
82
+ 'Generated files:',
83
+ plannedFiles,
84
+ 'No directories or files were written, and Git was not initialized.',
85
+ ].join('\n'));
86
+ }
87
+ async function writeExclusiveSystemFile({ destination, contents, }) {
88
+ try {
89
+ await fs.mkdir(dirname(destination), { recursive: true });
90
+ await fs.writeFile(destination, contents, {
91
+ encoding: 'utf-8',
92
+ flag: 'wx',
93
+ flush: true,
94
+ });
95
+ }
96
+ catch (error) {
97
+ if (isAlreadyExistsError(error)) {
98
+ throw new CliError(`System scaffold file "${destination}" appeared during creation and was not replaced. The target may contain a partial scaffold; remove it before retrying.`);
99
+ }
100
+ throw error;
101
+ }
102
+ }
103
+ export default async function systemCreate(name, options = {}) {
104
+ const acceptDefaults = options.yes === true;
105
+ const dryRun = options.dryRun === true;
106
+ let requestedName = name?.trim();
107
+ if (!requestedName) {
108
+ requestedName = await runPrompt({
109
+ prompt: () => input({
110
+ message: 'System name:',
111
+ default: DEFAULT_SYSTEM_NAME,
112
+ validate: validatePromptedSystemName,
113
+ }),
114
+ nonInteractive: {
115
+ error: 'System name is required in non-interactive mode. Pass the [name] positional argument or use --yes.',
116
+ },
117
+ accept: { when: acceptDefaults, value: DEFAULT_SYSTEM_NAME },
118
+ });
119
+ }
120
+ const systemName = normalizeSystemName(requestedName);
121
+ let targetParent = options.directory?.trim();
122
+ if (!targetParent) {
123
+ targetParent = await runPrompt({
124
+ prompt: () => input({
125
+ message: 'Target directory:',
126
+ default: DEFAULT_TARGET_DIRECTORY,
127
+ validate: (value) => value.trim().length > 0 || 'Target directory cannot be empty.',
128
+ }),
129
+ nonInteractive: {
130
+ error: 'Target directory is required in non-interactive mode. Pass --directory <directory> or use --yes.',
131
+ },
132
+ accept: { when: acceptDefaults, value: DEFAULT_TARGET_DIRECTORY },
133
+ });
134
+ }
135
+ let platform = options.platform
136
+ ? normalizeRequestedPlatform(options.platform)
137
+ : undefined;
138
+ if (!platform) {
139
+ const platforms = await runPrompt({
140
+ prompt: () => checkbox({
141
+ message: 'Platform targets:',
142
+ choices: PLATFORM_CHOICES,
143
+ validate: (values) => values.length > 0 || 'Select at least one platform target.',
144
+ }),
145
+ nonInteractive: {
146
+ error: 'A platform target is required in non-interactive mode. Pass --platform <platform-expression> or use --yes.',
147
+ },
148
+ accept: { when: acceptDefaults, value: [DEFAULT_PLATFORM] },
149
+ });
150
+ platform = normalizeRequestedPlatform(platforms.join(' || '));
151
+ }
152
+ let initializeGit = options.git;
153
+ if (initializeGit === undefined) {
154
+ initializeGit = await runPrompt({
155
+ prompt: () => confirm({
156
+ message: 'Initialize a Git repository?',
157
+ default: true,
158
+ }),
159
+ nonInteractive: {
160
+ error: 'Git initialization choice is required in non-interactive mode. Pass --git or --no-git, or use --yes.',
161
+ },
162
+ accept: { when: acceptDefaults, value: true },
163
+ });
164
+ }
165
+ const target = join(resolve(targetParent), systemName);
166
+ const targetExists = existsSync(target);
167
+ if (targetExists && !dryRun) {
168
+ throw new CliError(`The system target is already occupied: ${target}. Choose another parent directory with --directory.`);
169
+ }
170
+ const scaffold = buildSystemScaffold({
171
+ name: systemName,
172
+ platform,
173
+ homepage: options.homepage || `https://TODO.invalid/${systemName}`,
174
+ repository: options.repository || `https://TODO.invalid/${systemName}.git`,
175
+ });
176
+ const validation = await validateSystemConfig(scaffold.systemConfig);
177
+ if (!validation.valid) {
178
+ throw new CliError(`Unable to create an invalid system scaffold: ${formatValidationErrors(validation.errors)}`);
179
+ }
180
+ const systemConfigDestination = safeResolveWithin(target, EMULSIFY_SYSTEM_CONFIG_FILE, 'System scaffold file');
181
+ const plannedArtifactFiles = scaffold.files.map(({ path, contents }) => ({
182
+ destination: safeResolveWithin(target, path, 'System scaffold file'),
183
+ contents,
184
+ }));
185
+ const plannedDestinations = [
186
+ systemConfigDestination,
187
+ ...plannedArtifactFiles.map(({ destination }) => destination),
188
+ ];
189
+ if (dryRun) {
190
+ logDryRun(target, targetExists, platform, initializeGit, plannedDestinations);
191
+ return;
192
+ }
193
+ try {
194
+ await fs.mkdir(dirname(target), { recursive: true });
195
+ try {
196
+ await fs.mkdir(target, { recursive: false });
197
+ }
198
+ catch (error) {
199
+ if (isAlreadyExistsError(error)) {
200
+ throw new CliError(`The system target became occupied during creation: ${target}. No existing files were replaced.`);
201
+ }
202
+ throw error;
203
+ }
204
+ await Promise.all([
205
+ writeToJsonFile(systemConfigDestination, scaffold.systemConfig),
206
+ ...plannedArtifactFiles.map(writeExclusiveSystemFile),
207
+ ]);
208
+ if (initializeGit) {
209
+ await simpleGit(target).init(false, { '--initial-branch': 'main' });
210
+ }
211
+ }
212
+ catch (error) {
213
+ if (error instanceof CliError) {
214
+ throw error;
215
+ }
216
+ throw new CliError(`Unable to create the system in ${target}: ${getErrorMessage(error)}`);
217
+ }
218
+ log('success', `Created the ${systemName} system in ${target}.`);
219
+ if (initializeGit) {
220
+ log('info', 'Git was initialized on branch main. Review the generated metadata, then commit the scaffold before installing it.');
221
+ }
222
+ }
@@ -0,0 +1,50 @@
1
+ import { confirm } from '@inquirer/prompts';
2
+ import CliError from '../lib/CliError.js';
3
+ import log from '../lib/log.js';
4
+ import getGitRepoNameFromUrl from '../util/getGitRepoNameFromUrl.js';
5
+ import getEmulsifyConfig from '../util/project/getEmulsifyConfig.js';
6
+ import unsetEmulsifyConfig from '../util/project/unsetEmulsifyConfig.js';
7
+ import { runPrompt } from '../util/prompt/index.js';
8
+ const CONFIGURED_SYSTEM_LABEL = 'configured component system';
9
+ function getSystemLabel(repository) {
10
+ try {
11
+ const name = getGitRepoNameFromUrl(repository);
12
+ return name ? `${name} system` : CONFIGURED_SYSTEM_LABEL;
13
+ }
14
+ catch {
15
+ return CONFIGURED_SYSTEM_LABEL;
16
+ }
17
+ }
18
+ export default async function systemDetach({ yes = false, } = {}) {
19
+ const projectConfig = await getEmulsifyConfig();
20
+ if (!projectConfig) {
21
+ throw new CliError('No Emulsify project detected. Run this command within an existing Emulsify project.');
22
+ }
23
+ if (!projectConfig.system) {
24
+ throw new CliError('No component system is configured for this Emulsify project.');
25
+ }
26
+ const systemLabel = getSystemLabel(projectConfig.system.repository);
27
+ const systemReference = `${systemLabel} at ${projectConfig.system.checkout}`;
28
+ const confirmed = await runPrompt({
29
+ prompt: () => confirm({
30
+ message: `Detach the ${systemReference} from this project? Component files will be left in place.`,
31
+ default: false,
32
+ }),
33
+ nonInteractive: {
34
+ error: 'System detachment requires confirmation in non-interactive mode. Pass --yes to detach the configured system.',
35
+ },
36
+ accept: { when: yes, value: true },
37
+ });
38
+ if (!confirmed) {
39
+ log('info', 'System detach cancelled. No project files were changed.');
40
+ return;
41
+ }
42
+ try {
43
+ await unsetEmulsifyConfig('system', 'variant');
44
+ }
45
+ catch {
46
+ throw new CliError('Unable to detach the configured system from project.emulsify.json.');
47
+ }
48
+ log('success', `Detached the ${systemReference}. All component files were left in place.`);
49
+ log('info', 'Next: run "emulsify system create" to scaffold your own system repository, then replace its example content with the components preserved in this project.');
50
+ }