@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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 (203) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -23,6 +23,7 @@ import {Project} from '../../foundation/config/project.mjs';
23
23
  import {
24
24
  BUNDLED_THEME_PACKAGE,
25
25
  THEMES_DIR,
26
+ THEME_SLUG_RE,
26
27
  discoverBundledThemes,
27
28
  discoverIntegrationThemes,
28
29
  discoverUnmigratedThemeCopies,
@@ -51,8 +52,13 @@ import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';
51
52
  import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';
52
53
  import {importThemeArtifact} from '../../foundation/fs/module-loader.mjs';
53
54
  import {applyWrites} from '../integration/add-helpers.mjs';
54
- import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
55
+ import {forkFileNames, renamedEntry} from './_fork.mjs';
56
+ import {
57
+ formatCliCommand,
58
+ quoteCommandArgument,
59
+ } from '../../foundation/env/package-manager.mjs';
55
60
  import {fsErrorMessage} from '../../foundation/fs/fs-error.mjs';
61
+ import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
56
62
  import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';
57
63
 
58
64
  export {BUNDLED_THEME_PACKAGE, THEMES_DIR};
@@ -65,6 +71,20 @@ export function themeRecordOwner(theme) {
65
71
  return themeImportPackage(theme);
66
72
  }
67
73
 
74
+ /**
75
+ * Whether `--package <name>` selects a theme. It takes either name the CLI
76
+ * shows for it: the package that provides it (`@astryxdesign/cli` for a
77
+ * bundled theme) or the package the app imports it from, which the record
78
+ * holds (`@astryxdesign/theme-butter`).
79
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
80
+ * @param {string | undefined} name
81
+ */
82
+ export function themeInPackage(theme, name) {
83
+ return (
84
+ name == null || theme.package === name || themeImportPackage(theme) === name
85
+ );
86
+ }
87
+
68
88
  /**
69
89
  * A bundled theme entry kept for the historical public `listThemes()` helper.
70
90
  * @typedef {Pick<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme, 'slug' | 'displayName' | 'description' | 'maintained' | 'entry' | 'exportName' | 'files'>} BundledTheme
@@ -168,11 +188,60 @@ const skippedLocalThemesOf = new WeakMap();
168
188
  function brokenLocalThemeError(broken) {
169
189
  return new AstryxError(
170
190
  `Local theme "${broken.slug}" in ${broken.path} is broken: ${broken.reason}`,
171
- undefined,
191
+ [
192
+ {
193
+ name: formatCliCommand('theme list'),
194
+ reason: 'the themes that load, and the broken folders it skips',
195
+ },
196
+ ],
172
197
  ERROR_CODES.ERR_THEME_INVALID,
173
198
  );
174
199
  }
175
200
 
201
+ /**
202
+ * A slug that is not in the app's record. When a theme by that name is
203
+ * available, the refusal names `theme add`; otherwise `theme list`, since
204
+ * adding it would fail too.
205
+ * @param {string} slug
206
+ * @param {{projectDir: string}} state
207
+ */
208
+ async function notAddedError(slug, state) {
209
+ let match;
210
+ try {
211
+ match = await findTheme(slug, {cwd: state.projectDir});
212
+ } catch (error) {
213
+ // More than one package provides the slug: adding it names one.
214
+ if (
215
+ error instanceof AstryxError &&
216
+ error.code === ERROR_CODES.ERR_AMBIGUOUS_THEME
217
+ ) {
218
+ return new AstryxError(
219
+ `Theme "${slug}" is not added, and more than one package provides it. Add it from one of them with --package first.`,
220
+ error.suggestions,
221
+ ERROR_CODES.ERR_UNKNOWN_THEME,
222
+ );
223
+ }
224
+ throw error;
225
+ }
226
+ const list = {
227
+ name: formatCliCommand('theme list', state.projectDir),
228
+ reason: 'the themes you can add',
229
+ };
230
+ if (!match) {
231
+ return new AstryxError(
232
+ `Theme "${slug}" is not added, and no theme by that name is available. Run \`${list.name}\` for the themes you can add.`,
233
+ [list],
234
+ ERROR_CODES.ERR_UNKNOWN_THEME,
235
+ );
236
+ }
237
+ const add = formatCliCommand(`theme add ${match.slug}`, state.projectDir);
238
+ return new AstryxError(
239
+ `Theme "${slug}" is not added. Run \`${add}\` first.`,
240
+ [{name: add, reason: 'add it to the app'}],
241
+ ERROR_CODES.ERR_UNKNOWN_THEME,
242
+ );
243
+ }
244
+
176
245
  /** @param {unknown} error */
177
246
  function isMissingThemeArtifact(error) {
178
247
  return (
@@ -381,12 +450,14 @@ function scaffoldContents(bytes) {
381
450
  /**
382
451
  * Describe an ejected theme as a new, unmaintained local fork.
383
452
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
453
+ * @param {string} [name] the fork's name: the folder it takes in the local
454
+ * themes root, which discovery reads as the theme's name
384
455
  */
385
- function localThemeDescriptor(theme) {
456
+ function localThemeDescriptor(theme, name = theme.slug) {
386
457
  return `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */
387
458
  export default {
388
459
  type: 'theme',
389
- name: ${JSON.stringify(theme.slug)},
460
+ name: ${JSON.stringify(name)},
390
461
  displayName: ${JSON.stringify(theme.displayName)},
391
462
  description: ${JSON.stringify(theme.description)},
392
463
  maintained: false,
@@ -403,8 +474,10 @@ export default {
403
474
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
404
475
  * @param {string} dir
405
476
  * @param {string} cwd
477
+ * @param {string} projectDir the project root the default target is in
478
+ * @param {string[]} [forkNames] the fork's own file names, when they differ
406
479
  */
407
- function assertEjectTargetFree(theme, dir, cwd) {
480
+ function assertEjectTargetFree(theme, dir, cwd, projectDir, forkNames = []) {
408
481
  /** @type {string[]} */
409
482
  let entries;
410
483
  try {
@@ -415,7 +488,8 @@ function assertEjectTargetFree(theme, dir, cwd) {
415
488
  }
416
489
  const rel = path.relative(cwd, dir) || '.';
417
490
  const isDefault =
418
- path.resolve(cwd, defaultEjectTarget(theme.slug)) === path.resolve(dir);
491
+ path.resolve(projectDir, defaultEjectTarget(theme.slug)) ===
492
+ path.resolve(dir);
419
493
  const suggestion = isDefault
420
494
  ? undefined
421
495
  : [
@@ -432,7 +506,9 @@ function assertEjectTargetFree(theme, dir, cwd) {
432
506
  ERROR_CODES.ERR_FILE_EXISTS,
433
507
  );
434
508
  }
435
- const ownFiles = new Set(theme.files.map(name => path.basename(name)));
509
+ const ownFiles = new Set(
510
+ [...theme.files, ...forkNames].map(name => path.basename(name)),
511
+ );
436
512
  for (const name of entries) {
437
513
  const otherDescriptor =
438
514
  name.endsWith('.doc.mjs') && !ownFiles.has(name)
@@ -440,7 +516,13 @@ function assertEjectTargetFree(theme, dir, cwd) {
440
516
  : null;
441
517
  const otherEntry =
442
518
  /Theme\.(?:ts|tsx|mts)$/.test(name) && !ownFiles.has(name);
443
- if ((otherDescriptor && otherDescriptor !== theme.slug) || otherEntry) {
519
+ // A fork in the local themes root carries its folder's name.
520
+ if (
521
+ (otherDescriptor &&
522
+ otherDescriptor !== theme.slug &&
523
+ otherDescriptor !== path.basename(dir)) ||
524
+ otherEntry
525
+ ) {
444
526
  throw new AstryxError(
445
527
  `${rel} holds another theme (${name}). Eject does not mix two themes in one folder, even with --overwrite.`,
446
528
  suggestion,
@@ -450,6 +532,98 @@ function assertEjectTargetFree(theme, dir, cwd) {
450
532
  }
451
533
  }
452
534
 
535
+ /**
536
+ * Refuse a fork target that `theme list` and `theme add` would then misread:
537
+ * the local themes folder itself, where every theme has its own folder, or a
538
+ * folder in it named after another theme the project can use.
539
+ * @param {string} slug
540
+ * @param {string} dir absolute target
541
+ * @param {string} projectDir
542
+ * @param {string} cwd
543
+ * @param {Set<string>} takenSlugs the slugs of the themes the project can use
544
+ * @param {boolean} [sameFork] whether the folder holds no fork or a fork of
545
+ * this theme
546
+ */
547
+ function assertEjectTargetPlace(
548
+ slug,
549
+ dir,
550
+ projectDir,
551
+ cwd,
552
+ takenSlugs,
553
+ sameFork = true,
554
+ ) {
555
+ const themesRoot = path.resolve(projectDir, LOCAL_THEME_ROOT);
556
+ const resolved = path.resolve(dir);
557
+ const own = defaultEjectTarget(slug).split(path.sep).join('/');
558
+ const suggestion = [
559
+ {
560
+ name: formatCliCommand(`theme eject ${slug}`, cwd),
561
+ reason: `fork into ${own}`,
562
+ },
563
+ ];
564
+ if (resolved === themesRoot) {
565
+ throw new AstryxError(
566
+ `${path.relative(cwd, dir) || '.'} is the folder that holds the local themes, each in its own folder. Fork ${slug} into ${own}.`,
567
+ suggestion,
568
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
569
+ );
570
+ }
571
+ // A fork may take a new name; only another theme's name is refused.
572
+ const name = path.basename(resolved);
573
+ // The theme of that name may be the one in this very folder (a re-fork,
574
+ // which the folder checks decide).
575
+ const ownFolder = () => {
576
+ try {
577
+ return fs
578
+ .readdirSync(resolved)
579
+ .some(
580
+ file =>
581
+ file.endsWith('.doc.mjs') &&
582
+ themeDescriptorName(path.join(resolved, file)) === name,
583
+ );
584
+ } catch {
585
+ return false;
586
+ }
587
+ };
588
+ if (
589
+ path.dirname(resolved) === themesRoot &&
590
+ name !== slug &&
591
+ takenSlugs.has(name) &&
592
+ !(sameFork && ownFolder())
593
+ ) {
594
+ throw new AstryxError(
595
+ `${path.relative(cwd, dir)} is named after the theme ${name}, and a local theme's folder carries its name. Fork ${slug} into ${own}, or into a folder with a new name.`,
596
+ suggestion,
597
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
598
+ );
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Whether a folder holds no fork, or a fork of `theme`: its descriptor
604
+ * carries the theme's display name, as eject writes it.
605
+ * @param {string} dir
606
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
607
+ */
608
+ function holdsForkOf(dir, theme) {
609
+ let docs;
610
+ try {
611
+ docs = fs.readdirSync(dir).filter(file => file.endsWith('.doc.mjs'));
612
+ } catch {
613
+ return true;
614
+ }
615
+ return docs.every(file => {
616
+ try {
617
+ const text = fs.readFileSync(path.join(dir, file), 'utf-8');
618
+ return (
619
+ /\bdisplayName:\s*(['"])(.*?)\1/.exec(text)?.[2] === theme.displayName
620
+ );
621
+ } catch {
622
+ return false;
623
+ }
624
+ });
625
+ }
626
+
453
627
  /**
454
628
  * The `name` of a theme descriptor, read as text so a broken file cannot run.
455
629
  * @param {string} file
@@ -468,35 +642,78 @@ function themeDescriptorName(file) {
468
642
  /**
469
643
  * Publish one theme's complete source inventory as an atomic local fork.
470
644
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
471
- * @param {{cwd: string, targetPath?: string, overwrite?: boolean}} options
472
- * @returns {string} project-relative output directory
645
+ * @param {{cwd: string, targetPath?: string, overwrite?: boolean, takenSlugs?: Set<string>}} options
646
+ * `takenSlugs`: the slugs of the themes the project can use, which a fork's
647
+ * new folder name may not take
648
+ * @returns {{outputDir: string, files: string[]}} the project-relative output
649
+ * directory and the files written, named as the fork names them
473
650
  */
474
- export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
651
+ export function ejectThemeFiles(
652
+ theme,
653
+ {cwd, targetPath: typedPath, overwrite = false, takenSlugs = new Set()},
654
+ ) {
655
+ // The fork lands in the project, as list and add read it: the default root
656
+ // is the project's, and a relative [path] is read from the working folder
657
+ // but must stay inside the project.
658
+ const projectDir = findPackageRoot(cwd) ?? path.resolve(cwd);
659
+ // A Windows-style path names the same folders on every platform, as
660
+ // compile reads it; a folder name with a backslash in it is never meant.
661
+ const targetPath = typedPath?.replace(/\\/g, '/');
662
+ const target = !targetPath
663
+ ? defaultEjectTarget(theme.slug)
664
+ : path.isAbsolute(targetPath)
665
+ ? targetPath
666
+ : path.relative(projectDir, path.resolve(cwd, targetPath)) || '.';
475
667
  let resolvedDir;
476
668
  try {
477
- resolvedDir = assertWithin(
478
- targetPath || defaultEjectTarget(theme.slug),
479
- cwd,
480
- {label: 'theme target path'},
481
- );
669
+ resolvedDir = assertWithin(target, projectDir, {
670
+ label: 'theme target path',
671
+ });
482
672
  } catch (error) {
483
673
  if (error instanceof PathSafetyError) {
484
674
  throw new AstryxError(
485
- error.message,
486
- undefined,
675
+ targetPath
676
+ ? error.message.replace(`"${target}"`, `"${targetPath}"`)
677
+ : error.message,
678
+ [
679
+ {
680
+ name: formatCliCommand(`theme eject ${theme.slug}`, cwd),
681
+ reason: `fork into ${defaultEjectTarget(theme.slug).split(path.sep).join('/')}`,
682
+ },
683
+ ],
487
684
  ERROR_CODES.ERR_PATH_TRAVERSAL,
488
685
  );
489
686
  }
490
687
  throw error;
491
688
  }
492
689
 
690
+ // A fork in the local themes root is named after its folder, as `theme
691
+ // list` and `theme add` read it; elsewhere it keeps the theme's name.
692
+ const inThemesRoot =
693
+ path.dirname(path.resolve(resolvedDir)) ===
694
+ path.resolve(projectDir, LOCAL_THEME_ROOT);
695
+ const forkName = inThemesRoot ? path.basename(resolvedDir) : theme.slug;
696
+ if (inThemesRoot && !THEME_SLUG_RE.test(forkName)) {
697
+ throw new AstryxError(
698
+ `A local theme's folder is its name, which is lowercase kebab-case starting with a letter; ${forkName} is not.`,
699
+ [
700
+ {
701
+ name: formatCliCommand(`theme eject ${theme.slug}`, cwd),
702
+ reason: `fork into ${defaultEjectTarget(theme.slug).split(path.sep).join('/')}`,
703
+ },
704
+ ],
705
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
706
+ );
707
+ }
708
+
709
+ const names = forkFileNames(theme, forkName);
493
710
  let writes;
494
711
  try {
495
- writes = theme.files.map(name => ({
496
- name,
497
- src: path.join(theme.sourceDir, name),
498
- dest: assertWithin(name, resolvedDir, {
499
- label: `theme destination for ${name}`,
712
+ writes = theme.files.map((src, index) => ({
713
+ name: names[index],
714
+ src: path.join(theme.sourceDir, src),
715
+ dest: assertWithin(names[index], resolvedDir, {
716
+ label: `theme destination for ${names[index]}`,
500
717
  }),
501
718
  }));
502
719
  } catch (error) {
@@ -521,8 +738,24 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
521
738
  }
522
739
  }
523
740
 
524
- assertEjectTargetFree(theme, resolvedDir, cwd);
525
-
741
+ // The fork's own names count as its files only in a folder that holds
742
+ // no fork or a fork of this theme.
743
+ const sameFork = holdsForkOf(resolvedDir, theme);
744
+ assertEjectTargetFree(
745
+ theme,
746
+ resolvedDir,
747
+ cwd,
748
+ projectDir,
749
+ sameFork ? names : [],
750
+ );
751
+ assertEjectTargetPlace(
752
+ theme.slug,
753
+ resolvedDir,
754
+ projectDir,
755
+ cwd,
756
+ takenSlugs,
757
+ sameFork,
758
+ );
526
759
  if (!overwrite) {
527
760
  const existing = writes.find(write => fs.existsSync(write.dest));
528
761
  if (existing) {
@@ -530,12 +763,39 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
530
763
  throw new AstryxError(
531
764
  `Refusing to overwrite existing file ${rel}. ` +
532
765
  'Re-run with --overwrite (or -f) to replace it.',
533
- undefined,
766
+ [
767
+ {
768
+ name: formatCliCommand(
769
+ [
770
+ 'theme eject',
771
+ theme.slug,
772
+ ...(targetPath ? [quoteCommandArgument(targetPath)] : []),
773
+ ...(theme.source === 'bundled'
774
+ ? []
775
+ : ['--package', quoteCommandArgument(theme.package)]),
776
+ '--overwrite',
777
+ ].join(' '),
778
+ cwd,
779
+ ),
780
+ reason: 'replace the earlier fork of this theme',
781
+ },
782
+ ],
534
783
  ERROR_CODES.ERR_FILE_EXISTS,
535
784
  );
536
785
  }
537
786
  }
538
787
 
788
+ // A fork under another name renames its entry first, so an entry that
789
+ // names no theme is refused before any folder is made.
790
+ const entrySrc = path.resolve(theme.sourceDir, theme.files[0]);
791
+ const renamed =
792
+ forkName !== theme.slug
793
+ ? renamedEntry(
794
+ String(scaffoldContents(fs.readFileSync(entrySrc))),
795
+ theme,
796
+ forkName,
797
+ )
798
+ : null;
539
799
  try {
540
800
  fs.mkdirSync(resolvedDir, {recursive: true});
541
801
  const plans = writes.map(write => {
@@ -547,8 +807,10 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
547
807
  path: dest,
548
808
  contents:
549
809
  path.resolve(write.src) === path.resolve(theme.docPath)
550
- ? localThemeDescriptor(theme)
551
- : scaffoldContents(fs.readFileSync(write.src)),
810
+ ? localThemeDescriptor(theme, forkName)
811
+ : renamed != null && path.resolve(write.src) === entrySrc
812
+ ? renamed
813
+ : scaffoldContents(fs.readFileSync(write.src)),
552
814
  createOnly: !overwrite,
553
815
  };
554
816
  });
@@ -568,7 +830,7 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
568
830
  throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
569
831
  }
570
832
 
571
- return path.relative(cwd, resolvedDir) || '.';
833
+ return {outputDir: path.relative(cwd, resolvedDir) || '.', files: names};
572
834
  }
573
835
 
574
836
  /**
@@ -606,7 +868,11 @@ function asThemeError(error) {
606
868
  message.startsWith('Refusing to replace')
607
869
  ? ERROR_CODES.ERR_FILE_EXISTS
608
870
  : ERROR_CODES.ERR_THEME_INVALID;
609
- return new AstryxError(message, undefined, code);
871
+ const suggestions =
872
+ error instanceof ThemeStateError || error instanceof ThemeImportError
873
+ ? error.suggestions
874
+ : undefined;
875
+ return new AstryxError(message, suggestions, code);
610
876
  }
611
877
 
612
878
  /**
@@ -614,7 +880,9 @@ function asThemeError(error) {
614
880
  * Without an explicit package, a local theme shadows package themes that share
615
881
  * its slug. Other duplicate slugs fail closed until the caller selects an owner.
616
882
  * @param {string} [slug]
617
- * @param {{cwd?: string, package?: string, includeLocal?: boolean}} [options]
883
+ * @param {{cwd?: string, package?: string, includeLocal?: boolean, command?: string}} [options]
884
+ * `command`: the command a refusal suggests running with `--package`,
885
+ * `theme add` by default
618
886
  * @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined>}
619
887
  */
620
888
  export async function findTheme(slug, options = {}) {
@@ -627,7 +895,7 @@ export async function findTheme(slug, options = {}) {
627
895
  const matches = themes.filter(
628
896
  theme =>
629
897
  theme.slug.toLowerCase() === normalized &&
630
- (options.package == null || theme.package === options.package),
898
+ themeInPackage(theme, options.package),
631
899
  );
632
900
  const broken = skipped.find(entry => entry.slug.toLowerCase() === normalized);
633
901
  if (
@@ -657,7 +925,10 @@ export async function findTheme(slug, options = {}) {
657
925
  throw new AstryxError(
658
926
  `Theme "${slug}" is provided by more than one package. Select one with --package.`,
659
927
  matches.map(theme => ({
660
- name: `${theme.slug} --package ${theme.package}`,
928
+ name: formatCliCommand(
929
+ `${options.command ?? 'theme add'} ${theme.slug} --package ${quoteCommandArgument(theme.package)}`,
930
+ options.cwd ?? process.cwd(),
931
+ ),
661
932
  reason:
662
933
  theme.source === 'bundled'
663
934
  ? 'bundled theme'
@@ -671,6 +942,36 @@ export async function findTheme(slug, options = {}) {
671
942
  return matches[0];
672
943
  }
673
944
 
945
+ /**
946
+ * Runnable `<command> <slug>` suggestions for an unknown slug, closest names
947
+ * first; `--package` is named only where packages share a slug.
948
+ * @param {string} command such as `theme add`
949
+ * @param {string} slug what the person typed
950
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available
951
+ * @param {string} cwd
952
+ * @returns {Array<{theme: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme, name: string}>}
953
+ */
954
+ export function themeCommandsFor(command, slug, available, cwd) {
955
+ const needle = String(slug).toLowerCase();
956
+ const shared = (/** @type {string} */ other) =>
957
+ available.filter(theme => theme.slug === other).length > 1;
958
+ return [...available]
959
+ .sort(
960
+ (a, b) =>
961
+ levenshteinDistance(needle, a.slug.toLowerCase()) -
962
+ levenshteinDistance(needle, b.slug.toLowerCase()) ||
963
+ a.slug.localeCompare(b.slug),
964
+ )
965
+ .slice(0, 5)
966
+ .map(theme => ({
967
+ theme,
968
+ name: formatCliCommand(
969
+ `${command} ${theme.slug}${shared(theme.slug) ? ` --package ${quoteCommandArgument(theme.package)}` : ''}`,
970
+ cwd,
971
+ ),
972
+ }));
973
+ }
974
+
674
975
  /**
675
976
  * Read the generated module's app-theme record with stable CLI errors.
676
977
  * @param {string} [cwd]
@@ -730,7 +1031,12 @@ export function resolveRecordedThemes(state, available) {
730
1031
  if (!theme) {
731
1032
  throw new AstryxError(
732
1033
  `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, or drop it with \`${formatCliCommand(`theme remove ${slug}`, state.projectDir)}\`.`,
733
- undefined,
1034
+ [
1035
+ {
1036
+ name: formatCliCommand(`theme remove ${slug}`, state.projectDir),
1037
+ reason: 'drop it from the app',
1038
+ },
1039
+ ],
734
1040
  ERROR_CODES.ERR_UNKNOWN_THEME,
735
1041
  );
736
1042
  }
@@ -985,15 +1291,17 @@ async function addThemeToAppLocked(slug, cwd, options) {
985
1291
  const available = await listAvailableThemes(cwd);
986
1292
  throw new AstryxError(
987
1293
  `Unknown theme "${slug}"${options.package ? ` in package "${options.package}"` : ''}.`,
988
- available.map(theme => ({
989
- name: `${theme.slug} --package ${theme.package}`,
990
- reason:
991
- theme.source === 'bundled'
992
- ? 'bundled theme'
993
- : theme.source === 'local'
994
- ? 'local theme'
995
- : `provided by ${theme.package}`,
996
- })),
1294
+ themeCommandsFor('theme add', slug, available, cwd).map(
1295
+ ({theme, name}) => ({
1296
+ name,
1297
+ reason:
1298
+ theme.source === 'bundled'
1299
+ ? 'bundled theme'
1300
+ : theme.source === 'local'
1301
+ ? 'local theme'
1302
+ : `provided by ${theme.package}`,
1303
+ }),
1304
+ ),
997
1305
  ERROR_CODES.ERR_UNKNOWN_THEME,
998
1306
  );
999
1307
  }
@@ -1066,16 +1374,28 @@ async function removeThemeFromAppLocked(slug, cwd) {
1066
1374
  const state = readAppThemeState(cwd);
1067
1375
  const recordedSlug = recordedThemeSlug(state, slug);
1068
1376
  if (!state.configured || recordedSlug == null) {
1069
- throw new AstryxError(
1070
- `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,
1071
- undefined,
1072
- ERROR_CODES.ERR_UNKNOWN_THEME,
1073
- );
1377
+ throw await notAddedError(slug, state);
1074
1378
  }
1075
1379
  if (state.defaultSlug === recordedSlug) {
1380
+ const others = Object.keys(state.themes).filter(
1381
+ other => other !== recordedSlug,
1382
+ );
1383
+ const uses = others.slice(0, 3).map(other => ({
1384
+ name: formatCliCommand(`theme use ${other}`, state.projectDir),
1385
+ reason: `make ${other} the default`,
1386
+ }));
1076
1387
  throw new AstryxError(
1077
- `Theme "${recordedSlug}" is the default. Run \`${formatCliCommand('theme use <other-slug>', state.projectDir)}\` before removing it.`,
1078
- undefined,
1388
+ uses.length > 0
1389
+ ? `Theme "${recordedSlug}" is the default. Run \`${uses[0].name}\` before removing it.`
1390
+ : `Theme "${recordedSlug}" is the default and the only added theme. Add another theme and make it the default before removing it.`,
1391
+ uses.length > 0
1392
+ ? uses
1393
+ : [
1394
+ {
1395
+ name: formatCliCommand('theme list', state.projectDir),
1396
+ reason: 'the themes you can add',
1397
+ },
1398
+ ],
1079
1399
  ERROR_CODES.ERR_THEME_INVALID,
1080
1400
  );
1081
1401
  }
@@ -1083,8 +1403,16 @@ async function removeThemeFromAppLocked(slug, cwd) {
1083
1403
  delete themes[recordedSlug];
1084
1404
  if (state.defaultSlug == null) {
1085
1405
  throw new AstryxError(
1086
- `The generated theme module has no default theme. Run \`${formatCliCommand('theme use <slug>', state.projectDir)}\` first.`,
1087
- undefined,
1406
+ `The generated theme module has no default theme. Run \`${formatCliCommand(`theme use ${Object.keys(themes)[0] ?? recordedSlug}`, state.projectDir)}\` first.`,
1407
+ [
1408
+ {
1409
+ name: formatCliCommand(
1410
+ `theme use ${Object.keys(themes)[0] ?? recordedSlug}`,
1411
+ state.projectDir,
1412
+ ),
1413
+ reason: 'choose a default',
1414
+ },
1415
+ ],
1088
1416
  ERROR_CODES.ERR_THEME_INVALID,
1089
1417
  );
1090
1418
  }
@@ -1116,11 +1444,7 @@ async function useThemeInAppLocked(slug, cwd) {
1116
1444
  const state = readAppThemeState(cwd);
1117
1445
  const recordedSlug = recordedThemeSlug(state, slug);
1118
1446
  if (!state.configured || recordedSlug == null) {
1119
- throw new AstryxError(
1120
- `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,
1121
- undefined,
1122
- ERROR_CODES.ERR_UNKNOWN_THEME,
1123
- );
1447
+ throw await notAddedError(slug, state);
1124
1448
  }
1125
1449
  const available = await listAvailableThemes(state.projectDir);
1126
1450
  return writeThemeApp(