@astryxdesign/cli 0.7.15 → 0.7.16-canary.g22213fd

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 (222) hide show
  1. package/README.md +6 -4
  2. package/api/build/_adapter.d.mts +10 -0
  3. package/api/build/_adapter.mjs +24 -0
  4. package/api/build/blocks/blocks.d.mts +1 -0
  5. package/api/build/blocks/blocks.mjs +18 -1
  6. package/api/build/kit/shell.weights.json +1 -0
  7. package/api/build/kit/shellcall.d.mts +26 -0
  8. package/api/build/kit/shellcall.mjs +87 -0
  9. package/api/build/kit/start.mjs +67 -4
  10. package/api/build/kit/weights.d.mts +15 -0
  11. package/api/build/kit/weights.mjs +27 -0
  12. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  13. package/api/component/_adapter.d.mts +1 -1
  14. package/api/component/_adapter.mjs +28 -1
  15. package/api/doctor/_adapter.d.mts +38 -2
  16. package/api/doctor/_adapter.mjs +76 -1
  17. package/api/doctor/built-checks.mjs +1 -1
  18. package/api/doctor/doctor.d.mts +26 -0
  19. package/api/doctor/doctor.doc.mjs +1 -1
  20. package/api/doctor/doctor.mjs +156 -11
  21. package/api/doctor/theme-checks.mjs +163 -18
  22. package/api/icon/_adapter.d.mts +7 -3
  23. package/api/icon/_adapter.mjs +12 -3
  24. package/api/icon/icon.type.d.mts +15 -0
  25. package/api/icon/icon.type.mjs +10 -3
  26. package/api/icon/iconUse.doc.mjs +19 -5
  27. package/api/icon/list/list.mjs +7 -1
  28. package/api/icon/use/use.d.mts +8 -5
  29. package/api/icon/use/use.mjs +95 -13
  30. package/api/init/run/run.mjs +1 -0
  31. package/api/integration/add-contribution.mjs +3 -3
  32. package/api/integration/pack-check.mjs +14 -8
  33. package/api/integration/validate-integration.mjs +1 -1
  34. package/api/search/_adapter.mjs +15 -16
  35. package/api/search/_entries.d.mts +2 -1
  36. package/api/search/_entries.mjs +28 -1
  37. package/api/swizzle/_moduleGraph.mjs +1 -1
  38. package/api/template/template.type.d.mts +6 -2
  39. package/api/template/template.type.mjs +2 -1
  40. package/api/theme/_adapter.d.mts +5 -2
  41. package/api/theme/_adapter.mjs +59 -14
  42. package/api/theme/_fork.mjs +1 -1
  43. package/api/theme/build/build.d.mts +120 -32
  44. package/api/theme/build/build.mjs +471 -111
  45. package/api/theme/eject/eject.mjs +22 -1
  46. package/api/theme/generateTonalPalette.doc.mjs +2 -2
  47. package/api/theme/palette/generate/generator.mjs +141 -2
  48. package/api/theme/template/template.d.mts +19 -0
  49. package/api/theme/template/template.mjs +102 -25
  50. package/api/theme/theme.type.d.mts +44 -1
  51. package/api/theme/theme.type.mjs +23 -1
  52. package/api/theme/themeBuild.doc.mjs +4 -4
  53. package/api/theme/themeEject.doc.mjs +1 -1
  54. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  55. package/api/theme/themeTemplate.doc.mjs +9 -3
  56. package/api/theme-edit/_adapter.d.mts +33 -2
  57. package/api/theme-edit/_adapter.mjs +276 -41
  58. package/api/theme-edit/_check.d.mts +93 -4
  59. package/api/theme-edit/_check.mjs +1712 -223
  60. package/api/theme-edit/_color.d.mts +2 -8
  61. package/api/theme-edit/_color.mjs +292 -219
  62. package/api/theme-edit/_compiler.d.mts +1 -0
  63. package/api/theme-edit/_compiler.mjs +20 -1
  64. package/api/theme-edit/_context.d.mts +31 -1
  65. package/api/theme-edit/_context.mjs +445 -41
  66. package/api/theme-edit/_css.d.mts +60 -1
  67. package/api/theme-edit/_css.mjs +404 -28
  68. package/api/theme-edit/_edit.d.mts +25 -0
  69. package/api/theme-edit/_edit.mjs +1620 -154
  70. package/api/theme-edit/_how-commands.d.mts +11 -26
  71. package/api/theme-edit/_how-commands.mjs +30 -2
  72. package/api/theme-edit/_how-question.d.mts +15 -0
  73. package/api/theme-edit/_how-question.mjs +1469 -194
  74. package/api/theme-edit/_how.mjs +144 -30
  75. package/api/theme-edit/_marks.d.mts +13 -0
  76. package/api/theme-edit/_marks.mjs +15 -0
  77. package/api/theme-edit/_overview.mjs +2 -0
  78. package/api/theme-edit/_palette.d.mts +38 -0
  79. package/api/theme-edit/_palette.mjs +306 -73
  80. package/api/theme-edit/_parts.d.mts +33 -0
  81. package/api/theme-edit/_parts.mjs +138 -9
  82. package/api/theme-edit/_png.d.mts +18 -0
  83. package/api/theme-edit/_png.mjs +95 -14
  84. package/api/theme-edit/_preview-app.d.mts +55 -1
  85. package/api/theme-edit/_preview-app.mjs +1552 -101
  86. package/api/theme-edit/_preview.d.mts +71 -3
  87. package/api/theme-edit/_preview.mjs +565 -35
  88. package/api/theme-edit/_project.d.mts +15 -0
  89. package/api/theme-edit/_project.mjs +68 -13
  90. package/api/theme-edit/_settings.d.mts +299 -5
  91. package/api/theme-edit/_settings.mjs +2806 -158
  92. package/api/theme-edit/_tables.d.mts +24 -0
  93. package/api/theme-edit/_tables.mjs +212 -150
  94. package/api/theme-edit/_vet.d.mts +42 -0
  95. package/api/theme-edit/_vet.mjs +144 -0
  96. package/api/theme-edit/theme-edit.type.d.mts +31 -2
  97. package/api/theme-edit/theme-edit.type.mjs +10 -2
  98. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  99. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  100. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  101. package/api/upgrade/registry/registry.mjs +6 -1
  102. package/assets/codemods/parse.mjs +2 -2
  103. package/assets/docs/author-a-theme.doc.mjs +1 -1
  104. package/assets/docs/theme.doc.dense.mjs +1 -1
  105. package/assets/docs/theme.doc.mjs +1 -1
  106. package/assets/docs/theme.doc.zh.mjs +4 -3
  107. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  108. package/assets/docs/tree/icon-sets.doc.mjs +63 -8
  109. package/assets/docs/tree/single-component.doc.mjs +11 -2
  110. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  111. package/assets/docs.generated.json +2 -2
  112. package/assets/preview-app/next.config.mjs +7 -1
  113. package/assets/preview-app/package.json +1 -0
  114. package/assets/preview-app/src/app/globals.css +1 -0
  115. package/assets/self-audit.generated.json +1 -1
  116. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.doc.mjs +21 -0
  117. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.tsx +62 -0
  118. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  119. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  120. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  121. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  122. package/assets/templates/components.generated.json +1 -1
  123. package/assets/templates/pages/ai-chat/page.tsx +20 -2
  124. package/assets/templates/pages/dashboard/page.tsx +1 -1
  125. package/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json +2 -0
  126. package/authoring/config/config.doc.mjs +8 -0
  127. package/authoring/config/parse.d.mts +1 -0
  128. package/authoring/config/parse.mjs +12 -0
  129. package/authoring/config/type.ts +8 -0
  130. package/authoring/doctypes/_schema.d.mts +52 -5
  131. package/authoring/doctypes/_schema.mjs +62 -7
  132. package/authoring/doctypes/base/type.ts +10 -0
  133. package/authoring/doctypes/component/component.doc.mjs +1 -1
  134. package/authoring/doctypes/function/function.doc.mjs +6 -0
  135. package/authoring/doctypes/function/type.ts +3 -0
  136. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +3 -3
  137. package/authoring/doctypes/legacy.mjs +5 -1
  138. package/authoring/index.d.ts +1 -0
  139. package/authoring/shadcn/source-variants.d.mts +1 -1
  140. package/authoring/shadcn/source-variants.mjs +32 -10
  141. package/clients/cli/build-id.generated.json +1 -1
  142. package/clients/cli/commands/doctor.doc.mjs +2 -2
  143. package/clients/cli/commands/experimental/icon.mjs +61 -6
  144. package/clients/cli/commands/experimental/theme.mjs +244 -45
  145. package/clients/cli/commands/experimental-icon-use.doc.mjs +12 -5
  146. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  147. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  148. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  149. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  150. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  151. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  152. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  153. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  154. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  155. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  156. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  157. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  158. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  159. package/clients/cli/commands/theme.doc.mjs +7 -2
  160. package/clients/cli/commands/theme.mjs +222 -55
  161. package/clients/cli/commands.generated.json +1 -1
  162. package/clients/cli/formatters/index.mjs +7 -4
  163. package/clients/cli/index.mjs +25 -5
  164. package/clients/cli/lib/cli-error.mjs +9 -3
  165. package/clients/cli/lib/component-format.mjs +27 -9
  166. package/clients/cli/lib/json-shim.mjs +72 -2
  167. package/clients/cli/manifest.generated.json +1 -1
  168. package/clients/cli/run.mjs +49 -0
  169. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  170. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  171. package/foundation/agent-docs/agent-docs.mjs +4 -3
  172. package/foundation/config/config-writer.d.mts +23 -0
  173. package/foundation/config/config-writer.mjs +152 -58
  174. package/foundation/config/project.mjs +103 -16
  175. package/foundation/discovery/component-discovery.mjs +11 -22
  176. package/foundation/discovery/icon-set-checks.mjs +164 -48
  177. package/foundation/discovery/icon-set-discovery.d.mts +38 -5
  178. package/foundation/discovery/icon-set-discovery.mjs +50 -6
  179. package/foundation/discovery/icon-set-theme-maps.d.mts +59 -0
  180. package/foundation/discovery/icon-set-theme-maps.mjs +95 -0
  181. package/foundation/discovery/icon-set-writer.d.mts +2 -3
  182. package/foundation/discovery/icon-set-writer.mjs +58 -17
  183. package/foundation/discovery/module-exports.mjs +1 -15
  184. package/foundation/discovery/template-adapter.mjs +44 -19
  185. package/foundation/discovery/template-icons.d.mts +27 -10
  186. package/foundation/discovery/template-icons.mjs +142 -26
  187. package/foundation/discovery/template-source-tree.mjs +3 -16
  188. package/foundation/discovery/theme-discovery.d.mts +30 -1
  189. package/foundation/discovery/theme-discovery.mjs +109 -50
  190. package/foundation/fs/exact-codec.d.mts +35 -0
  191. package/foundation/fs/exact-codec.mjs +148 -0
  192. package/foundation/fs/gather-cache.d.mts +15 -5
  193. package/foundation/fs/gather-cache.mjs +129 -31
  194. package/foundation/fs/paths.d.mts +39 -0
  195. package/foundation/fs/paths.mjs +44 -11
  196. package/foundation/fs/read-record.mjs +11 -1
  197. package/foundation/integrations/autolink.d.mts +4 -2
  198. package/foundation/integrations/autolink.mjs +4 -2
  199. package/foundation/integrations/cli-requirement.d.mts +16 -5
  200. package/foundation/integrations/cli-requirement.mjs +27 -6
  201. package/foundation/integrations/contribution-fixes.mjs +1 -16
  202. package/foundation/integrations/may-have-integrations.mjs +7 -3
  203. package/foundation/integrations/missing-dependency.d.mts +9 -0
  204. package/foundation/integrations/missing-dependency.mjs +100 -0
  205. package/foundation/integrations/public-imports.mjs +1 -1
  206. package/foundation/render/embedded-imports.mjs +1 -1
  207. package/foundation/render/host-exit.d.mts +8 -0
  208. package/foundation/render/host-exit.mjs +11 -0
  209. package/foundation/render/page-host.mjs +56 -10
  210. package/foundation/render/page-worker.mjs +14 -0
  211. package/foundation/render/render-page.mjs +37 -2
  212. package/foundation/response/error-codes.d.mts +2 -1
  213. package/foundation/response/error-codes.d.ts +1 -0
  214. package/foundation/response/error-codes.doc.mjs +5 -0
  215. package/foundation/response/error-codes.mjs +3 -0
  216. package/foundation/response/json.d.mts +15 -0
  217. package/foundation/response/json.mjs +52 -1
  218. package/foundation/response/response-types.doc.mjs +1 -1
  219. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  220. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  221. package/foundation/xle/browser.d.mts +2 -2
  222. package/package.json +7 -6
@@ -62,11 +62,12 @@ import * as fs from 'node:fs';
62
62
  import * as path from 'node:path';
63
63
  import {createRequire, isBuiltin} from 'node:module';
64
64
  import {fileURLToPath, pathToFileURL} from 'node:url';
65
- import {parse} from '@babel/parser';
65
+ import {babelParse as parse} from '../../../foundation/runtime/lazy-dependencies.mjs';
66
66
  import {createJiti} from 'jiti';
67
67
  import {
68
68
  formatCliCommand,
69
69
  getCliInvocation,
70
+ quoteCommandArgument,
70
71
  } from '../../../foundation/env/package-manager.mjs';
71
72
  import {
72
73
  CLI_ROOT,
@@ -84,6 +85,7 @@ import {
84
85
  PathSafetyError,
85
86
  } from '../../../foundation/fs/path-safety.mjs';
86
87
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
88
+ import {editorThemeRecord} from '../../../foundation/config/theme-state.mjs';
87
89
  import {validatePrivateVars} from '../../../foundation/config/theme-private-vars.mjs';
88
90
  import {AstryxError} from '../../error.mjs';
89
91
  import {applyWrites} from '../../integration/add-helpers.mjs';
@@ -710,16 +712,21 @@ export function normalizeThemeBuildForCompare(content) {
710
712
  .join('\n');
711
713
  }
712
714
 
713
- /** @param {Array<{dest: string, content: string, allowMissingInCheck?: boolean}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */
715
+ /**
716
+ * The outputs that are missing or differ from what the build would write. A
717
+ * missing `.css.d.ts` stylesheet type stub (a write marked `warnWhenMissing`)
718
+ * is not stale: projects that ignore it in version control run the check in
719
+ * CI, so the check warns about it instead (missingDeclarations). Every other
720
+ * missing output, the module's `.d.ts` too, is stale.
721
+ * @param {Array<{dest: string, content: string, warnWhenMissing?: boolean}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>}
722
+ */
714
723
  function staleBuildOutputs(writes, cwd) {
715
724
  /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */
716
725
  const stale = [];
717
726
  for (const write of writes) {
718
727
  const rel = path.relative(cwd, write.dest);
719
728
  if (!fs.existsSync(write.dest)) {
720
- if (!write.allowMissingInCheck) {
721
- stale.push({path: rel, reason: 'missing'});
722
- }
729
+ if (!write.warnWhenMissing) stale.push({path: rel, reason: 'missing'});
723
730
  continue;
724
731
  }
725
732
  const onDisk = fs.readFileSync(write.dest, 'utf8');
@@ -733,13 +740,42 @@ function staleBuildOutputs(writes, cwd) {
733
740
  return stale;
734
741
  }
735
742
 
736
- /** @param {Array<{dest: string, allowMissingInCheck?: boolean}>} writes @param {string} cwd */
743
+ /**
744
+ * Every output the build writes, from the same write list the build and the
745
+ * stale comparison use. A missing output makes the check stale, except the
746
+ * `.css.d.ts` stub, which it warns about (missingDeclarations).
747
+ * @param {Array<{dest: string}>} writes @param {string} cwd
748
+ */
737
749
  function checkedBuildOutputs(writes, cwd) {
750
+ return writes.map(write => path.relative(cwd, write.dest));
751
+ }
752
+
753
+ /**
754
+ * The `.css.d.ts` stylesheet type stubs the build writes that are missing,
755
+ * which the check names as checked and warns about in text mode without
756
+ * failing.
757
+ * @param {Array<{dest: string, warnWhenMissing?: boolean}>} writes @param {string} cwd
758
+ * @returns {string[]}
759
+ */
760
+ function missingDeclarations(writes, cwd) {
738
761
  return writes
739
- .filter(write => !write.allowMissingInCheck || fs.existsSync(write.dest))
762
+ .filter(write => write.warnWhenMissing && !fs.existsSync(write.dest))
740
763
  .map(write => path.relative(cwd, write.dest));
741
764
  }
742
765
 
766
+ /**
767
+ * The one text-mode warning line for missing stylesheet type stubs, or
768
+ * nothing when none is missing. The logger is silent under --json.
769
+ * @param {Array<{dest: string, warnWhenMissing?: boolean}>} writes @param {string} cwd
770
+ */
771
+ function warnMissingDeclarations(writes, cwd) {
772
+ const missing = missingDeclarations(writes, cwd);
773
+ if (missing.length === 0) return;
774
+ logger.warn(
775
+ ` Warning: stylesheet type declaration file${missing.length === 1 ? '' : 's'} not found: ${missing.join(', ')}. The check does not fail on ${missing.length === 1 ? 'it' : 'them'}; a build writes ${missing.length === 1 ? 'it' : 'them'}.`,
776
+ );
777
+ }
778
+
743
779
  /** Remedies that end a confinement error, by where the output path came from. */
744
780
  const OUT_REMEDY = 'Pass an --out path inside it.';
745
781
  const SOURCE_REMEDY =
@@ -862,7 +898,23 @@ function outsideCheckRemedy(writes, sources, root, args) {
862
898
  }
863
899
 
864
900
  /** The first words of every file a build writes. */
865
- const GENERATED_MARKER = '@generated by `astryx theme build`';
901
+ export const GENERATED_MARKER = '@generated by `astryx theme build`';
902
+
903
+ /** Marks the refusal of a theme that sets a private var. */
904
+ const PRIVATE_VAR_REFUSAL = Symbol('astryx.theme.privateVarRefusal');
905
+
906
+ /**
907
+ * Whether `error` is a build's refusal of a theme that sets a private var
908
+ * (which `doctor` reports in its own check, not as a stale output).
909
+ * CLI-internal.
910
+ * @param {unknown} error
911
+ * @returns {boolean}
912
+ */
913
+ export function isPrivateVarRefusal(error) {
914
+ return Boolean(
915
+ error && /** @type {any} */ (error)[PRIVATE_VAR_REFUSAL] === true,
916
+ );
917
+ }
866
918
 
867
919
  /** @param {string} file @returns {boolean} */
868
920
  function isDirectorySync(file) {
@@ -1005,8 +1057,10 @@ export function themeSourceGuesses(file, cwd) {
1005
1057
  * source has, such as `.css` or `.json` (THEME_SOURCE_EXTENSIONS).
1006
1058
  * @param {string} filePath
1007
1059
  * @param {string} cwd
1060
+ * @param {BuildMode} [mode] the caller's --check and --out, kept in every
1061
+ * build a refusal suggests
1008
1062
  */
1009
- function assertThemeSourceFile(filePath, cwd) {
1063
+ function assertThemeSourceFile(filePath, cwd, mode = {}) {
1010
1064
  const rel = (/** @type {string} */ file) => path.relative(cwd, file);
1011
1065
  const sourceHead = fileHead(filePath);
1012
1066
  if (sourceHead.includes(GENERATED_MARKER)) {
@@ -1023,16 +1077,16 @@ function assertThemeSourceFile(filePath, cwd) {
1023
1077
  const familyKey = /Command: .*--family-key (\S+)/.exec(sourceHead)?.[1];
1024
1078
  const build =
1025
1079
  sources.length > 1 && familyKey
1026
- ? `theme build --family ${sources.map(shellWord).join(' ')} --family-key ${shellWord(familyKey)}`
1080
+ ? buildSuggestion(sources, mode, cwd, undefined, {familyKey})
1027
1081
  : sources.length > 0
1028
- ? `theme build ${shellWord(sources[0])}`
1082
+ ? buildSuggestion(sources[0], mode, cwd)
1029
1083
  : null;
1030
1084
  throw new AstryxError(
1031
1085
  `${rel(filePath)} is an output of \`theme build\`, not a theme source.${sources.length > 0 ? ` It was built from ${sources.join(', ')}.` : ''}`,
1032
1086
  build
1033
1087
  ? [
1034
1088
  {
1035
- name: formatCliCommand(build, cwd),
1089
+ name: build,
1036
1090
  reason: 'build the theme source',
1037
1091
  },
1038
1092
  ]
@@ -1044,12 +1098,11 @@ function assertThemeSourceFile(filePath, cwd) {
1044
1098
  throw new AstryxError(
1045
1099
  `${rel(filePath)} is not a theme module. A theme source is a ${THEME_SOURCE_EXTENSIONS.join(', ')} file that exports defineTheme(...).`,
1046
1100
  themeFilesIn(path.dirname(filePath)).map(name => ({
1047
- name: formatCliCommand(
1048
- `theme build ${shellWord(
1049
- rel(path.join(path.dirname(filePath), name))
1050
- .split(path.sep)
1051
- .join('/'),
1052
- )}`,
1101
+ name: buildSuggestion(
1102
+ rel(path.join(path.dirname(filePath), name))
1103
+ .split(path.sep)
1104
+ .join('/'),
1105
+ mode,
1053
1106
  cwd,
1054
1107
  ),
1055
1108
  reason: 'a theme source in that folder',
@@ -1059,6 +1112,96 @@ function assertThemeSourceFile(filePath, cwd) {
1059
1112
  }
1060
1113
  }
1061
1114
 
1115
+ /**
1116
+ * What the CLI hands a build beyond themeBuild's options. CLI-internal, never
1117
+ * a themeBuild option: `claimedOutputs` records the outputs earlier builds in
1118
+ * one run wrote, so a later theme cannot replace them; with `deferredWrites`
1119
+ * the build adds its outputs to that list instead of writing them, for
1120
+ * writeDeferredBuildOutputs; `writeRoot` replaces `cwd` as the directory every
1121
+ * output must stay inside, for a scratch build; `commandWords` names the
1122
+ * command in the rebuild hint; `prepareFamily`, `familyLoader`, and
1123
+ * `familyInterception` make the build a family member's plan.
1124
+ * @typedef {{prepareFamily?: boolean, familyLoader?: any, familyInterception?: any, writeRoot?: string, claimedOutputs?: Map<string, string>, deferredWrites?: Array<Array<{dest: string, content: string}>>, commandWords?: {group: string, build: string}}} ThemeBuildHandOff
1125
+ */
1126
+
1127
+ /**
1128
+ * Who takes the theme editor warnings (an editor folder, an editor-made
1129
+ * theme) instead of the logger: the watcher's child build hands each to its
1130
+ * parent, which prints it once per session. Set
1131
+ * only by the CLI (not part of the public API), and never by an option of
1132
+ * themeBuild.
1133
+ * @type {((warning: string) => void) | null}
1134
+ */
1135
+ let editorFolderListener = null;
1136
+
1137
+ /**
1138
+ * Hand the theme editor warnings of the builds in this process to
1139
+ * `listener` instead of the logger. CLI-internal: the watch child's
1140
+ * hand-off to its parent.
1141
+ * @param {((warning: string) => void) | null} listener
1142
+ */
1143
+ export function setEditorFolderListener(listener) {
1144
+ editorFolderListener = listener;
1145
+ }
1146
+
1147
+ /**
1148
+ * A build's mode flags: what it does (`--check` compares, never writes) and
1149
+ * where (`--out`), carried into every build command a refusal suggests.
1150
+ * @typedef {{check?: boolean, out?: string, iconsSpecifier?: string}} BuildMode
1151
+ */
1152
+
1153
+ /**
1154
+ * How a suggested build writes its source: `glob` leaves a pattern as typed
1155
+ * (unquoted, so the shell expands it); `family` makes it a --family run,
1156
+ * and `familyKey` names its key (a family run never takes --out).
1157
+ * @typedef {{glob?: boolean, family?: boolean, familyKey?: string}} SuggestionShape
1158
+ */
1159
+
1160
+ /**
1161
+ * The `theme build` command for `source` with the caller's mode flags, so a
1162
+ * suggestion never turns a check into a write or moves the outputs.
1163
+ * @param {string | string[]} source as the user types it, from cwd; several
1164
+ * for a family (with `shape.familyKey`)
1165
+ * @param {BuildMode} mode
1166
+ * @param {string} cwd
1167
+ * @param {{group: string, build: string}} [words] the command's own words
1168
+ * (`experimental theme compile`), else `theme build`
1169
+ * @param {SuggestionShape} [shape]
1170
+ * @returns {string}
1171
+ */
1172
+ export function buildSuggestion(source, mode, cwd, words, shape = {}) {
1173
+ /** @param {string[]} ws quoted for the shell the command runs in (PowerShell too) */
1174
+ const quoted = ws => ws.map(w => quoteCommandArgument(w));
1175
+ // A glob stays as typed: the shell expands it.
1176
+ const src = (Array.isArray(source) ? source : [source])
1177
+ .map(one =>
1178
+ shape.glob ? one.replace(/['"]/g, '') : quoteCommandArgument(one),
1179
+ )
1180
+ .join(' ');
1181
+ return formatCliCommand(
1182
+ [
1183
+ ...quoted([
1184
+ ...(words ? words.group.split(' ') : ['theme']),
1185
+ words?.build ?? 'build',
1186
+ ]),
1187
+ ...(shape.family || shape.familyKey ? ['--family'] : []),
1188
+ src,
1189
+ ...quoted([
1190
+ ...(shape.familyKey ? ['--family-key', shape.familyKey] : []),
1191
+ // A family run refuses --out.
1192
+ ...(mode.out && !shape.family && !shape.familyKey
1193
+ ? ['--out', mode.out]
1194
+ : []),
1195
+ ...(mode.iconsSpecifier
1196
+ ? ['--icons-specifier', mode.iconsSpecifier]
1197
+ : []),
1198
+ ...(mode.check ? ['--check'] : []),
1199
+ ]),
1200
+ ].join(' '),
1201
+ cwd,
1202
+ );
1203
+ }
1204
+
1062
1205
  /**
1063
1206
  * Refuse a build that would replace a file it does not own. A build never
1064
1207
  * writes over its input, two of its own outputs at one path, or an output
@@ -1069,21 +1212,47 @@ function assertThemeSourceFile(filePath, cwd) {
1069
1212
  * @param {Array<{dest: string}>} writes
1070
1213
  * @param {string} filePath the theme source
1071
1214
  * @param {string} cwd
1072
- * @param {{claimed?: Map<string, string>, rerun?: string, refuseUnmarked?: boolean, elsewhere?: string}} [options]
1215
+ * @param {{claimed?: Map<string, string>, rerun?: (out: string | null) => string, refuseUnmarked?: boolean, elsewhere?: string, onEditorFolder?: (warning: string) => void}} [options]
1073
1216
  * `claimed`: outputs written earlier in this run, by the source that wrote
1074
- * them; `rerun`: this build's command, to run again once the file is gone;
1075
- * `elsewhere`: the option that moves the outputs
1217
+ * them; `rerun`: this build's command with another --out, or without one;
1218
+ * `elsewhere`: the option that moves the outputs; `onEditorFolder`: takes
1219
+ * the editor-folder warning instead of the logger (a watcher prints it once)
1076
1220
  */
1077
1221
  function assertOutputsReplaceable(
1078
1222
  writes,
1079
1223
  filePath,
1080
1224
  cwd,
1081
- {claimed, rerun, refuseUnmarked = false, elsewhere = '--out'} = {},
1225
+ {
1226
+ claimed,
1227
+ rerun,
1228
+ refuseUnmarked = false,
1229
+ elsewhere = '--out',
1230
+ onEditorFolder,
1231
+ } = {},
1082
1232
  ) {
1083
1233
  const rel = (/** @type {string} */ file) => path.relative(cwd, file);
1084
1234
  const sourceKey = outputKey(filePath);
1085
1235
  const seen = new Set();
1236
+ /** @type {string | false} */
1086
1237
  let warnedOtherSource = false;
1238
+ // The same build without --out, with its other options.
1239
+ const beside = {
1240
+ name: rerun ? rerun(null) : buildSuggestion(rel(filePath), {}, cwd),
1241
+ reason: 'write the outputs beside this source',
1242
+ };
1243
+ // A folder the theme editor made holds that theme's outputs only: another
1244
+ // source's outputs there would sit beside its settings as if they were
1245
+ // its own. A source inside the folder builds there as always; one outside
1246
+ // it writes there too, with a warning.
1247
+ let editorFolder = false;
1248
+ if (refuseUnmarked && writes.length) {
1249
+ const dir = path.resolve(path.dirname(writes[0].dest));
1250
+ const record = editorThemeRecord(dir);
1251
+ const fromDir = path.relative(dir, path.resolve(filePath));
1252
+ // On Windows a source on another drive has an absolute relative path.
1253
+ const inside = !fromDir.startsWith('..') && !path.isAbsolute(fromDir);
1254
+ if (record && !inside) editorFolder = true;
1255
+ }
1087
1256
  for (const write of writes) {
1088
1257
  const key = outputKey(write.dest);
1089
1258
  if (key === sourceKey) {
@@ -1091,10 +1260,8 @@ function assertOutputsReplaceable(
1091
1260
  `The output ${rel(write.dest)} is the theme source itself. Pick another --out.`,
1092
1261
  [
1093
1262
  {
1094
- name: formatCliCommand(
1095
- `theme build ${shellWord(rel(filePath))}`,
1096
- cwd,
1097
- ),
1263
+ // The same build without --out (its --icons-specifier kept).
1264
+ name: beside.name,
1098
1265
  reason: 'write the outputs beside the source',
1099
1266
  },
1100
1267
  ],
@@ -1139,23 +1306,14 @@ function assertOutputsReplaceable(
1139
1306
  : null;
1140
1307
  if (otherSource && !OUT_REFUSES_OTHER_SOURCE) {
1141
1308
  // One warning per build: every output of that source goes together.
1309
+ // It is printed after every output passes, so it names a replacement
1310
+ // that happens.
1142
1311
  if (warnedOtherSource) continue;
1143
- warnedOtherSource = true;
1144
- logger.warn(
1145
- `Warning: ${rel(write.dest)} was built from ${otherSource}; this build of ${rel(filePath)} replaces it.`,
1146
- );
1312
+ warnedOtherSource = `Warning: ${rel(write.dest)} was built from ${otherSource}; this build of ${rel(filePath)} replaces it.`;
1147
1313
  } else if (otherSource) {
1148
1314
  throw new AstryxError(
1149
1315
  `${rel(write.dest)} is the build output of another theme source, ${otherSource}, so this build does not replace it. Pick another ${elsewhere}.`,
1150
- [
1151
- {
1152
- name: formatCliCommand(
1153
- `theme build ${shellWord(rel(filePath))}`,
1154
- cwd,
1155
- ),
1156
- reason: 'write the outputs beside this source',
1157
- },
1158
- ],
1316
+ [beside],
1159
1317
  ERROR_CODES.ERR_FILE_EXISTS,
1160
1318
  );
1161
1319
  }
@@ -1166,20 +1324,71 @@ function assertOutputsReplaceable(
1166
1324
  stat.size > 0 &&
1167
1325
  !fileHead(write.dest).includes(GENERATED_MARKER)
1168
1326
  ) {
1327
+ // Never advice to delete it: it may be the person's file (a settings
1328
+ // file, app source). A path that takes every output instead.
1329
+ const free = freeOutPath(writes);
1169
1330
  throw new AstryxError(
1170
- `${rel(write.dest)} was written by an older CLI (before 0.6.7) or by hand, so the build does not replace it. Delete that file and run the same build again, or pick another ${elsewhere}.`,
1171
- rerun
1172
- ? [
1173
- {
1174
- name: rerun,
1175
- reason: 'run the same build again once the file is deleted',
1176
- },
1177
- ]
1178
- : undefined,
1331
+ `${rel(write.dest)} is a file this build did not write (it has no build header: your own file, another tool's, or an output from a CLI before 0.6.7), so the build does not replace it. Pick another ${elsewhere}.`,
1332
+ [
1333
+ ...(free && rerun
1334
+ ? [
1335
+ {
1336
+ name: rerun(rel(free)),
1337
+ reason: 'a path where no output of this build exists yet',
1338
+ },
1339
+ ]
1340
+ : []),
1341
+ beside,
1342
+ ],
1179
1343
  ERROR_CODES.ERR_FILE_EXISTS,
1180
1344
  );
1181
1345
  }
1182
1346
  }
1347
+ // Warned only once nothing refuses the build, so it names a write that
1348
+ // happens.
1349
+ if (warnedOtherSource) logger.warn(warnedOtherSource);
1350
+ if (editorFolder) {
1351
+ const dir = path.dirname(writes[0].dest);
1352
+ const warning = `Warning: ${rel(dir) || '.'} is a folder the theme editor made, and ${rel(filePath)} is outside it; the build writes there anyway. Build beside the source, or pick another ${elsewhere}, to keep the editor's folder to its own theme.`;
1353
+ if (onEditorFolder) onEditorFolder(warning);
1354
+ else logger.warn(warning);
1355
+ }
1356
+ }
1357
+
1358
+ /**
1359
+ * An --out path where no output of this build exists yet, or null. The
1360
+ * stylesheet and its `.css.d.ts` follow the name --out gives; the module and
1361
+ * its types are named after the theme, so a new name beside them (`brand-2.css`)
1362
+ * helps only when those are free, else a new folder (`brand-2/brand.css`).
1363
+ * @param {Array<{dest: string}>} writes the stylesheet first
1364
+ * @returns {string | null}
1365
+ */
1366
+ function freeOutPath(writes) {
1367
+ const css = writes[0]?.dest;
1368
+ if (!css) return null;
1369
+ const dir = path.dirname(css);
1370
+ const stem = path.basename(css).replace(/\.css$/i, '');
1371
+ /** Whether a write set (each output moved by `move`) touches any file. */
1372
+ const blocked = (/** @type {(dest: string) => string} */ move) =>
1373
+ writes.some(w => fs.existsSync(move(w.dest)));
1374
+ for (let n = 2; n < 100; n += 1) {
1375
+ const next = `${stem}-${n}`;
1376
+ // Only the stylesheet and its types follow --out's name.
1377
+ // The exact names a build with `--out <next>.css` writes, also when
1378
+ // --out did not end in .css (`o.txt` suggests `o.txt-2.css`).
1379
+ const renamed = (/** @type {string} */ dest) =>
1380
+ dest === css
1381
+ ? path.join(dir, `${next}.css`)
1382
+ : dest === `${css}.d.ts`
1383
+ ? path.join(dir, `${next}.css.d.ts`)
1384
+ : dest;
1385
+ if (!blocked(renamed)) return path.join(dir, `${next}.css`);
1386
+ const folder = (/** @type {string} */ dest) =>
1387
+ path.join(dir, next, path.basename(dest));
1388
+ if (!fs.existsSync(path.join(dir, next)) && !blocked(folder))
1389
+ return path.join(dir, next, path.basename(css));
1390
+ }
1391
+ return null;
1183
1392
  }
1184
1393
 
1185
1394
  /**
@@ -1274,18 +1483,25 @@ function toIdentifier(name) {
1274
1483
  }
1275
1484
 
1276
1485
  /**
1277
- * Import specifier for install/scaffold instructions. Drops a leading `src/`
1278
- * from the cwd-relative dir (most consumers import from a file under src/) but
1279
- * keeps the rest of the path (e.g. `themes/gothic`). Callers note the path is
1280
- * relative to the consumer's file.
1281
- * @param {string} relDir
1486
+ * Import specifier for install/scaffold instructions, from a file directly
1487
+ * in the project's src/ (the file the printed snippet says it is relative
1488
+ * to; callers pass the output folder from the outputs' project root): an output
1489
+ * under src/ is `./themes/gothic/gothic`, one beside src/ is
1490
+ * `../themes/gothic/gothic`.
1491
+ * @param {string} relDir the output folder, relative to the outputs' project root
1282
1492
  * @param {string} base
1283
1493
  * @returns {string}
1284
1494
  */
1285
1495
  export function importSpecifier(relDir, base) {
1286
- const normalized = relDir === '.' ? '' : relDir;
1287
- const withinSrc = normalized.replace(/^src\/?/, '').replace(/\/+$/, '');
1288
- return withinSrc ? `./${withinSrc}/${base}` : `./${base}`;
1496
+ // An import specifier always uses `/`. On Windows the cwd-relative dir comes
1497
+ // from path.relative with `\`, which would print `./\themes\ocean/ocean`.
1498
+ const normalized = relDir === '.' ? '.' : relDir.split(path.sep).join('/');
1499
+ const fromSrc = path.posix.relative('src', normalized.replace(/\/+$/, ''));
1500
+ if (!fromSrc) return `./${base}`;
1501
+ // Only a parent step (`..` or `../…`), never a folder named like `..cache`.
1502
+ return fromSrc === '..' || fromSrc.startsWith('../')
1503
+ ? `${fromSrc}/${base}`
1504
+ : `./${fromSrc}/${base}`;
1289
1505
  }
1290
1506
 
1291
1507
  /**
@@ -2642,7 +2858,7 @@ class ThemeShapeError extends Error {}
2642
2858
  * @param {string} cwd
2643
2859
  * @returns {import('../../../foundation/response/base').Suggestion[]}
2644
2860
  */
2645
- function themeLoadSuggestions(error, shown, cwd) {
2861
+ function themeLoadSuggestions(error, shown, cwd, mode = {}) {
2646
2862
  const missing = missingThemePackage(error.cause ?? error);
2647
2863
  if (missing) {
2648
2864
  const {installCommand} = installCommandFor(
@@ -2661,7 +2877,7 @@ function themeLoadSuggestions(error, shown, cwd) {
2661
2877
  if (/changed while it was loading/.test(error.message)) {
2662
2878
  return [
2663
2879
  {
2664
- name: formatCliCommand(`theme build ${shellWord(shown)}`, cwd),
2880
+ name: buildSuggestion(shown, mode, cwd),
2665
2881
  reason: 'build again once the file is saved',
2666
2882
  },
2667
2883
  ];
@@ -3504,44 +3720,68 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
3504
3720
  * `logger` (silent by default).
3505
3721
  *
3506
3722
  * @param {string} file - Theme file path, resolved against `cwd`.
3507
- * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string, __claimedOutputs?: Map<string, string>, __deferredWrites?: Array<Array<{dest: string, content: string}>>, __commandWords?: {group: string, build: string}}} [options] -
3723
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] -
3508
3724
  * `out` overrides the output CSS path, or names the folder for it; `check` compares against on-disk outputs
3509
- * instead of writing. `__claimedOutputs` records the outputs earlier builds
3510
- * in one run wrote, so a later theme cannot replace them; with
3511
- * `__deferredWrites` the build adds its outputs to that list instead of
3512
- * writing them, for writeDeferredBuildOutputs. `__writeRoot` replaces `cwd` as the directory every
3513
- * output must stay inside, for a CLI-internal scratch build. `iconsSpecifier` overrides the icon registry import
3725
+ * instead of writing. `iconsSpecifier` overrides the icon registry import
3514
3726
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
3515
3727
  * direct registry specifiers from the theme source are emitted unchanged.
3516
3728
  * @param {{cwd?: string, projectCore?: boolean}} [ctx] `projectCore`: only the
3517
3729
  * project's installed Core (spec AST-081 FR3)
3730
+ * @param {{compact?: boolean, trailers?: ThemeBuildTrailer[]}} [report]
3731
+ * @param {ThemeBuildHandOff} [handOff] - what the CLI's batch, family, and
3732
+ * scratch builds hand a build; never an option of the public themeBuild.
3518
3733
  * @returns {Promise<any>}
3519
3734
  */
3520
3735
  async function themeBuildInternal(
3521
3736
  file,
3522
3737
  options = {},
3523
3738
  {cwd = process.cwd(), projectCore = false} = {},
3524
- /** @type {{compact?: boolean, trailers?: ThemeBuildTrailer[]}} */ report = {},
3739
+ report = {},
3740
+ handOff = {},
3525
3741
  ) {
3742
+ // A backslash in --out separates folders on every platform, as it does in
3743
+ // the other theme paths (a Windows path copied into a POSIX shell).
3744
+ if (typeof options.out === 'string' && options.out.includes('\\'))
3745
+ options = {...options, out: options.out.replace(/\\/g, '/')};
3526
3746
  const filePath = path.resolve(cwd, file);
3527
3747
 
3528
3748
  if (!fs.existsSync(filePath)) {
3529
3749
  throw new AstryxError(
3530
3750
  `File not found: ${filePath}`,
3531
3751
  themeSourceGuesses(file, cwd).map(guess => ({
3532
- name: formatCliCommand(`theme build ${shellWord(guess)}`, cwd),
3752
+ name: buildSuggestion(guess, options, cwd),
3533
3753
  reason: 'a theme source that exists',
3534
3754
  })),
3535
3755
  ERROR_CODES.ERR_FILE_NOT_FOUND,
3536
3756
  );
3537
3757
  }
3538
3758
 
3759
+ // A theme the theme editor made is built from its settings by the editor;
3760
+ // a plain build reads its settings module as last written (released CLIs
3761
+ // built it, so it still does, and says so).
3762
+ {
3763
+ const dir = path.dirname(filePath);
3764
+ const slug = path.basename(dir);
3765
+ if (
3766
+ (!handOff.commandWords || handOff.commandWords.group === 'theme') &&
3767
+ path.basename(filePath) === `${slug}.theme.ts` &&
3768
+ editorThemeRecord(dir)
3769
+ )
3770
+ (editorFolderListener ?? (w => logger.warn(w)))(
3771
+ `Warning: ${path.relative(cwd, filePath)} is a theme the theme editor made (${slug}.settings.json is beside it). This build reads ${slug}.settings.ts as last written; to build it from its settings, run ${formatCliCommand(`experimental theme editor show ${shellWord(slug)}`, cwd)}.`,
3772
+ );
3773
+ }
3774
+
3539
3775
  if (fs.statSync(filePath).isDirectory()) {
3540
3776
  throw new AstryxError(
3541
3777
  `${path.relative(cwd, filePath) || '.'} is a folder. Pass the theme file inside it.`,
3542
3778
  themeFilesIn(filePath).map(name => ({
3543
- name: formatCliCommand(
3544
- `theme build ${shellWord(path.relative(cwd, path.join(filePath, name)).split(path.sep).join('/'))}`,
3779
+ name: buildSuggestion(
3780
+ path
3781
+ .relative(cwd, path.join(filePath, name))
3782
+ .split(path.sep)
3783
+ .join('/'),
3784
+ options,
3545
3785
  cwd,
3546
3786
  ),
3547
3787
  reason: 'a theme source in that folder',
@@ -3550,7 +3790,7 @@ async function themeBuildInternal(
3550
3790
  );
3551
3791
  }
3552
3792
 
3553
- assertThemeSourceFile(filePath, cwd);
3793
+ assertThemeSourceFile(filePath, cwd, options);
3554
3794
 
3555
3795
  if (!report.compact) {
3556
3796
  logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
@@ -3574,7 +3814,7 @@ async function themeBuildInternal(
3574
3814
  // shared loader so exact authored parent identity stays CLI-private instead
3575
3815
  // of becoming a public DefinedTheme field.
3576
3816
  const interception =
3577
- options.__familyInterception ??
3817
+ handOff.familyInterception ??
3578
3818
  (_generateAdaptationCSS && themeFolderResolvesCore(filePath)
3579
3819
  ? undefined
3580
3820
  : interceptCore(_coreThemeModule, _coreRootModule));
@@ -3599,7 +3839,7 @@ async function themeBuildInternal(
3599
3839
  const loaded = await extractThemeDefinition(
3600
3840
  filePath,
3601
3841
  interception,
3602
- options.__familyLoader,
3842
+ handOff.familyLoader,
3603
3843
  );
3604
3844
  const after = fs.readFileSync(filePath, 'utf8');
3605
3845
  if (before !== after || before === '') {
@@ -3614,9 +3854,62 @@ async function themeBuildInternal(
3614
3854
  } catch (e) {
3615
3855
  const err = /** @type {Error} */ (e);
3616
3856
  const shown = path.relative(cwd, filePath) || filePath;
3857
+ // A theme file that is a link and does not load: named with the file it
3858
+ // points to (some loaders read its relative imports from the link's
3859
+ // folder, others from the file's own), never with Node's require stack.
3860
+ // Only an unresolved relative import is about the link; any other
3861
+ // failure (a package not installed) keeps its own remedy.
3862
+ let link = null;
3863
+ try {
3864
+ if (
3865
+ fs.lstatSync(filePath).isSymbolicLink() &&
3866
+ /Cannot find (?:module|package) '\.\.?\//.test(err.message)
3867
+ )
3868
+ link = fs.realpathSync(filePath);
3869
+ } catch {
3870
+ link = null;
3871
+ }
3872
+ const message = err.message
3873
+ .replace(/\n+Require stack:(?:\n- [^\n]*)*/, '')
3874
+ .split(filePath)
3875
+ .join(shown);
3617
3876
  throw new AstryxError(
3618
- err.message.split(filePath).join(shown),
3619
- themeLoadSuggestions(err, shown, cwd),
3877
+ link
3878
+ ? `${shown} is a link to ${path.relative(cwd, link) || link}, and it could not be loaded (a relative import may be read from the link's folder or from the file's own, depending on the loader); build the file itself: ${message}`
3879
+ : message,
3880
+ link
3881
+ ? [
3882
+ {
3883
+ // The file itself, with its outputs kept inside the working
3884
+ // folder (beside the link) when the file is outside it.
3885
+ name: buildSuggestion(
3886
+ path.relative(cwd, link) || link,
3887
+ {
3888
+ ...options,
3889
+ // The caller's --out, else beside the link when the file
3890
+ // is outside the working folder.
3891
+ out:
3892
+ options.out ??
3893
+ (path.relative(cwd, link).startsWith('..') ||
3894
+ path.isAbsolute(path.relative(cwd, link))
3895
+ ? path
3896
+ .relative(
3897
+ cwd,
3898
+ path.join(
3899
+ path.dirname(filePath),
3900
+ `${path.basename(filePath).replace(/\.[^.]+$/, '')}.css`,
3901
+ ),
3902
+ )
3903
+ .split(path.sep)
3904
+ .join('/')
3905
+ : undefined),
3906
+ },
3907
+ cwd,
3908
+ ),
3909
+ reason: 'build the file itself',
3910
+ },
3911
+ ]
3912
+ : themeLoadSuggestions(err, shown, cwd, options),
3620
3913
  ERROR_CODES.ERR_THEME_LOAD,
3621
3914
  );
3622
3915
  }
@@ -3626,13 +3919,13 @@ async function themeBuildInternal(
3626
3919
  // JSON.stringify and Object.keys, so it could not reach output regardless.)
3627
3920
  // Both reads happen BEFORE the strip, which is what removes the evidence.
3628
3921
  const ancestryObserved =
3629
- !options.__prepareFamily ||
3922
+ !handOff.prepareFamily ||
3630
3923
  !interception ||
3631
3924
  interception.observed(themeDef) ||
3632
3925
  Object.hasOwn(themeDef, 'extends');
3633
- if (options.__prepareFamily && interception) interception.retain(themeDef);
3926
+ if (handOff.prepareFamily && interception) interception.retain(themeDef);
3634
3927
  const sourceParent =
3635
- options.__prepareFamily && interception
3928
+ handOff.prepareFamily && interception
3636
3929
  ? interception.parentOf(themeDef)
3637
3930
  : undefined;
3638
3931
  const adaptationLineage = interception
@@ -3653,7 +3946,7 @@ async function themeBuildInternal(
3653
3946
  `Theme "${themeDef.name ?? path.basename(filePath)}" in ${shown} is a plain object, so a family build cannot see which theme it extends. A family member is made with defineTheme(...) from @astryxdesign/core/theme; build a plain-object theme on its own.`,
3654
3947
  [
3655
3948
  {
3656
- name: formatCliCommand(`theme build ${shellWord(shown)}`, cwd),
3949
+ name: buildSuggestion(shown, options, cwd),
3657
3950
  reason: 'build this theme on its own',
3658
3951
  },
3659
3952
  ],
@@ -3691,7 +3984,7 @@ async function themeBuildInternal(
3691
3984
  // generation so neither the no-CSS return nor --check can bypass the error.
3692
3985
  // Family preparation keeps its own named-import registry contract, which
3693
3986
  // themeBuildFamily checks against the selected members' graph.
3694
- const standaloneIcons = !options.__prepareFamily;
3987
+ const standaloneIcons = !handOff.prepareFamily;
3695
3988
  // Function icon entries stay functions in the built module, beside a node
3696
3989
  // view bound to `<theme>IconNodes` and computed from `<theme>IconEntries`.
3697
3990
  const functionEntries =
@@ -3743,17 +4036,20 @@ async function themeBuildInternal(
3743
4036
  logger.warn(` [warn] ${source}${w}`);
3744
4037
  }
3745
4038
 
3746
- // Validate no private vars are set directly
4039
+ // A theme that sets a private var directly is refused before anything is
4040
+ // written (a --check too): it is not a theme the build accepts, so no
4041
+ // output, receipt or success may say otherwise.
4042
+ // The message names no file: a batch and a family name the one it is
4043
+ // about, and a single build is about the file it was given.
3747
4044
  const privateVarErrors = validatePrivateVars(themeDef);
3748
- for (const e of privateVarErrors) {
3749
- warningMessages.push(e);
3750
- logger.error(` [error] ${source}${e}`);
3751
- }
3752
4045
  if (privateVarErrors.length > 0) {
3753
- options.__onPrivateVarError?.();
3754
- logger.error(
3755
- `\n ${source}${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`,
4046
+ const refusal = new AstryxError(
4047
+ `${privateVarErrors.join('\n')}\n${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`,
4048
+ undefined,
4049
+ ERROR_CODES.ERR_THEME_INVALID,
3756
4050
  );
4051
+ Object.defineProperty(refusal, PRIVATE_VAR_REFUSAL, {value: true});
4052
+ throw refusal;
3757
4053
  }
3758
4054
 
3759
4055
  const customHeadingErrors = validateCustomHeadingTypes(themeDef);
@@ -4067,7 +4363,20 @@ async function themeBuildInternal(
4067
4363
  // Source path relative to cwd — used in @generated headers
4068
4364
  const sourceRelative = path.relative(cwd, filePath);
4069
4365
  // What `--check` prints to rebuild, from the working folder.
4070
- const rebuildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(cwd, path.resolve(cwd, options.out)) : ''}`;
4366
+ // The project's own invocation, each path quoted for the shell.
4367
+ const rebuildCommand = formatCliCommand(
4368
+ [
4369
+ 'theme',
4370
+ 'build',
4371
+ sourceRelative,
4372
+ ...(options.out
4373
+ ? ['--out', path.relative(cwd, path.resolve(cwd, options.out))]
4374
+ : []),
4375
+ ]
4376
+ .map(shellWord)
4377
+ .join(' '),
4378
+ cwd,
4379
+ );
4071
4380
  // Stable provenance recorded in @generated headers — versions, not a
4072
4381
  // timestamp, so identical inputs produce byte-identical output.
4073
4382
  const versions = resolveToolVersions(cwd);
@@ -4077,7 +4386,7 @@ async function themeBuildInternal(
4077
4386
  const baseName = themeDef.name;
4078
4387
  // Every write stays inside cwd. A CLI-internal caller that renders into a
4079
4388
  // scratch directory it creates and removes names that directory instead.
4080
- const writeRoot = options.__writeRoot ?? cwd;
4389
+ const writeRoot = handOff.writeRoot ?? cwd;
4081
4390
  let outPath;
4082
4391
  if (options.out) {
4083
4392
  outPath = path.resolve(cwd, options.out);
@@ -4157,7 +4466,7 @@ async function themeBuildInternal(
4157
4466
  'export {};\n';
4158
4467
  // A family member's module is generated by themeBuildFamily, which carries
4159
4468
  // its registries and slot functions through the family's own imports.
4160
- const jsContent = options.__prepareFamily
4469
+ const jsContent = handOff.prepareFamily
4161
4470
  ? ''
4162
4471
  : generatedHeader(headerSource, 'js', buildCommand, versions) +
4163
4472
  generateBuiltModule(
@@ -4187,7 +4496,7 @@ async function themeBuildInternal(
4187
4496
  ]),
4188
4497
  ];
4189
4498
 
4190
- if (options.__prepareFamily) {
4499
+ if (handOff.prepareFamily) {
4191
4500
  return {
4192
4501
  filePath,
4193
4502
  sourceRelative: sourceRelative.split(path.sep).join('/'),
@@ -4209,7 +4518,7 @@ async function themeBuildInternal(
4209
4518
 
4210
4519
  const writes = [
4211
4520
  {dest: outPath, content: cssContent},
4212
- {dest: cssDtsPath, content: cssDtsContent, allowMissingInCheck: true},
4521
+ {dest: cssDtsPath, content: cssDtsContent, warnWhenMissing: true},
4213
4522
  {dest: jsPath, content: jsContent},
4214
4523
  {dest: dtsPath, content: dtsContent},
4215
4524
  ];
@@ -4222,15 +4531,22 @@ async function themeBuildInternal(
4222
4531
  // outside cwd read-only.
4223
4532
  if (!options.check) {
4224
4533
  confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);
4225
- // prettier-ignore
4226
- const rerun = formatCliCommand(['theme', 'build', path.relative(cwd, filePath), ...(options.out ? ['--out', options.out] : []), ...(options.iconsSpecifier ? ['--icons-specifier', options.iconsSpecifier] : [])].map(shellWord).join(' '), cwd);
4534
+ // This write build with another --out, or none: its --icons-specifier
4535
+ // kept, quoted for the shell.
4536
+ const rerun = (/** @type {string | null} */ out) =>
4537
+ buildSuggestion(
4538
+ path.relative(cwd, filePath),
4539
+ {iconsSpecifier: options.iconsSpecifier, out: out ?? undefined},
4540
+ cwd,
4541
+ );
4227
4542
  // A header-less file at the default paths beside the source is an output
4228
4543
  // of a CLI before 0.6.7, which the build has always replaced. A path that
4229
4544
  // --out names may hold anything, so there only build outputs are replaced.
4230
4545
  assertOutputsReplaceable(writes, filePath, cwd, {
4231
- claimed: options.__claimedOutputs,
4546
+ claimed: handOff.claimedOutputs,
4232
4547
  rerun,
4233
4548
  refuseUnmarked: Boolean(options.out),
4549
+ onEditorFolder: editorFolderListener ?? undefined,
4234
4550
  });
4235
4551
  }
4236
4552
 
@@ -4260,26 +4576,29 @@ async function themeBuildInternal(
4260
4576
  if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
4261
4577
  else
4262
4578
  logger.error(
4263
- `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
4579
+ `\n Rebuild with: ${rebuildLine(rebuildCommand, handOff.commandWords)}`,
4264
4580
  );
4265
4581
  }
4266
- return {
4582
+ warnMissingDeclarations(writes, cwd);
4583
+ return /** @type {import('../theme.type.mjs').ThemeBuildCheckResponse} */ ({
4267
4584
  type: 'theme.build.check',
4268
4585
  data: {
4269
4586
  name: themeDef.name,
4270
4587
  upToDate,
4271
4588
  stale,
4272
4589
  checked: checkedBuildOutputs(writes, cwd),
4590
+ // The code a stale check exits 1 with, for --json callers.
4591
+ ...(upToDate ? {} : {code: ERROR_CODES.ERR_THEME_STALE}),
4273
4592
  },
4274
- };
4593
+ });
4275
4594
  }
4276
4595
 
4277
4596
  // A batch publishes every theme's outputs after all of them are built, so
4278
4597
  // two themes that build the same files are refused before either writes.
4279
- if (options.__deferredWrites) options.__deferredWrites.push(writes);
4598
+ if (handOff.deferredWrites) handOff.deferredWrites.push(writes);
4280
4599
  else writeBuildOutputs(writes);
4281
4600
  for (const write of writes) {
4282
- options.__claimedOutputs?.set(outputKey(write.dest), sourceRelative);
4601
+ handOff.claimedOutputs?.set(outputKey(write.dest), sourceRelative);
4283
4602
  }
4284
4603
 
4285
4604
  if (!report.compact) {
@@ -4299,7 +4618,9 @@ async function themeBuildInternal(
4299
4618
  }
4300
4619
  }
4301
4620
 
4302
- const relOutDir = path.relative(cwd, outDir) || '.';
4621
+ // From the outputs' project root, whatever folder the build ran in: the
4622
+ // snippet is relative to a file in that project's src/.
4623
+ const relOutDir = path.relative(headerRoot(outDir, cwd), outDir) || '.';
4303
4624
  const jsImport = importSpecifier(relOutDir, baseName);
4304
4625
  const cssImport = importSpecifier(relOutDir, path.basename(outPath));
4305
4626
  const exportName = `${toIdentifier(baseName)}Theme`;
@@ -4503,6 +4824,7 @@ function groupUnloadedFonts(trailers) {
4503
4824
  * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options]
4504
4825
  * @param {{cwd?: string}} [ctx]
4505
4826
  * @param {{compact?: boolean}} [report]
4827
+ * @param {ThemeBuildHandOff} [handOff]
4506
4828
  * @returns {Promise<{receipt: import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null, trailer: ThemeBuildTrailer | null}>}
4507
4829
  */
4508
4830
  export async function themeBuildForReport(
@@ -4510,18 +4832,38 @@ export async function themeBuildForReport(
4510
4832
  options = {},
4511
4833
  ctx = {},
4512
4834
  {compact = false} = {},
4835
+ handOff = {},
4513
4836
  ) {
4514
4837
  /** @type {ThemeBuildTrailer[]} */
4515
4838
  const trailers = [];
4516
4839
  const receipt = /** @type {any} */ (
4517
- await themeBuildInternal(file, options, ctx, {compact, trailers})
4840
+ await themeBuildInternal(file, options, ctx, {compact, trailers}, handOff)
4518
4841
  );
4519
4842
  return {receipt, trailer: trailers[0] ?? null};
4520
4843
  }
4521
4844
 
4522
4845
  /** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string, projectCore?: boolean}} [ctx] `projectCore`: read only the project's installed Core, never the carried one (doctor; spec AST-081 FR3) @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */
4523
4846
  export async function themeBuild(file, options = {}, ctx = {}) {
4524
- return /** @type {any} */ (themeBuildInternal(file, options, ctx));
4847
+ const {out, check, iconsSpecifier} = options;
4848
+ return /** @type {any} */ (
4849
+ themeBuildInternal(file, {out, check, iconsSpecifier}, ctx)
4850
+ );
4851
+ }
4852
+
4853
+ /**
4854
+ * {@link themeBuild} with the CLI's hand-off: the same build, outputs, and
4855
+ * receipt, plus what only the CLI's batch and scratch builds pass.
4856
+ * CLI-internal: not exported from the API entry.
4857
+ * @param {string} file
4858
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} options
4859
+ * @param {{cwd?: string, projectCore?: boolean}} ctx
4860
+ * @param {ThemeBuildHandOff} handOff
4861
+ * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>}
4862
+ */
4863
+ export async function themeBuildWithHandOff(file, options, ctx, handOff) {
4864
+ return /** @type {any} */ (
4865
+ themeBuildInternal(file, options, ctx, {}, handOff)
4866
+ );
4525
4867
  }
4526
4868
  /** @param {string} name */
4527
4869
  // prettier-ignore
@@ -4660,11 +5002,12 @@ async function preloadFamilySource(filePath, loader, interception) {
4660
5002
  finally { patch.undo(); }
4661
5003
  }
4662
5004
 
4663
- /** @param {string[]} files @param {{familyKey: string, check?: boolean, iconsSpecifier?: string, __onPrivateVarError?: () => void, __commandWords?: {group: string, build: string}}} options @param {{cwd?: string}} [ctx] */
5005
+ /** @param {string[]} files @param {{familyKey: string, check?: boolean, iconsSpecifier?: string}} options @param {{cwd?: string}} [ctx] @param {{commandWords?: {group: string, build: string}}} [handOff] - the CLI's words for the rebuild hint */
4664
5006
  export async function themeBuildFamily(
4665
5007
  files,
4666
5008
  options,
4667
5009
  {cwd = process.cwd()} = {},
5010
+ handOff = {},
4668
5011
  ) {
4669
5012
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options?.familyKey ?? '')) {
4670
5013
  throw new AstryxError(
@@ -4696,8 +5039,20 @@ export async function themeBuildFamily(
4696
5039
  continue;
4697
5040
  }
4698
5041
  const file = source.file;
4699
- // prettier-ignore
4700
- const member = await themeBuildInternal(file, {iconsSpecifier: options.iconsSpecifier, __prepareFamily: true, __familyLoader: familyLoader, __familyInterception: familyInterception, __onPrivateVarError: options.__onPrivateVarError}, {cwd});
5042
+ /** @type {any} */
5043
+ let member;
5044
+ try {
5045
+ // `check` rides along for the suggestions a member's refusal makes; a
5046
+ // prepared member writes nothing either way.
5047
+ // prettier-ignore
5048
+ member = await themeBuildInternal(file, {iconsSpecifier: options.iconsSpecifier, check: options.check}, {cwd}, {}, {prepareFamily: true, familyLoader, familyInterception});
5049
+ } catch (error) {
5050
+ // A member's refusal names the member.
5051
+ if (isPrivateVarRefusal(error))
5052
+ /** @type {Error} */ (error).message =
5053
+ `${file}: ${/** @type {Error} */ (error).message}`;
5054
+ throw error;
5055
+ }
4701
5056
  if (!member || member.type) {
4702
5057
  throw new AstryxError(
4703
5058
  `Theme family member "${file}" did not produce a complete build plan.`,
@@ -4871,7 +5226,7 @@ export async function themeBuildFamily(
4871
5226
  },
4872
5227
  {
4873
5228
  dest: cssDtsPath,
4874
- allowMissingInCheck: true,
5229
+ warnWhenMissing: true,
4875
5230
  content:
4876
5231
  generatedHeader(headerSource, 'ts', buildCommand, root.versions) +
4877
5232
  'export {};\n',
@@ -4928,27 +5283,32 @@ export async function themeBuildFamily(
4928
5283
  if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
4929
5284
  else
4930
5285
  logger.error(
4931
- `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
5286
+ `\n Rebuild with: ${rebuildLine(rebuildCommand, handOff.commandWords)}`,
4932
5287
  );
4933
5288
  }
4934
- return {
5289
+ warnMissingDeclarations(writes, cwd);
5290
+ return /** @type {import('../theme.type.mjs').ThemeBuildCheckResponse} */ ({
4935
5291
  type: 'theme.build.check',
4936
5292
  data: {
4937
5293
  name: root.theme.name,
4938
5294
  upToDate,
4939
5295
  stale,
4940
5296
  checked: checkedBuildOutputs(writes, cwd),
5297
+ // The code a stale check exits 1 with, for --json callers.
5298
+ ...(upToDate ? {} : {code: ERROR_CODES.ERR_THEME_STALE}),
4941
5299
  },
4942
- };
5300
+ });
4943
5301
  }
4944
5302
  writeBuildOutputs(writes);
4945
5303
  for (const output of Object.values(outputs)) logger.log(`[ok] ${output}`);
4946
5304
  const themeBindings = members.map(member => bindings.get(member.theme.name));
4947
- const relOutDir = path.relative(cwd, outDir) || '.';
5305
+ // From the outputs' project root, whatever folder the build ran in: the
5306
+ // snippet is relative to a file in that project's src/.
5307
+ const relOutDir = path.relative(headerRoot(outDir, cwd), outDir) || '.';
4948
5308
  const jsImport = importSpecifier(relOutDir, baseName);
4949
5309
  const cssImport = `${jsImport}.css`;
4950
5310
  logger.log(`
4951
- Load the family CSS once, then select any member by theme identity:
5311
+ Load the family CSS once, then select any member by theme identity (paths are relative to a file in src/; adjust if yours lives elsewhere):
4952
5312
  import { ${themeBindings.join(', ')} } from '${jsImport}';
4953
5313
  import '${cssImport}';
4954
5314
  Or load the same stylesheet natively: