@astryxdesign/cli 0.7.15-canary.gbe99721 → 0.7.15-canary.gbef2f83

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 (69) hide show
  1. package/README.md +2 -1
  2. package/api/integration/validate-integration.mjs +1 -1
  3. package/api/theme/_adapter.mjs +12 -9
  4. package/api/theme/build/build.d.mts +1 -21
  5. package/api/theme/build/build.mjs +105 -29
  6. package/api/theme/template/template.d.mts +2 -0
  7. package/api/theme/template/template.mjs +41 -12
  8. package/api/theme/theme.type.d.mts +4 -0
  9. package/api/theme/theme.type.mjs +2 -1
  10. package/api/theme/themeBuild.doc.mjs +3 -3
  11. package/api/theme/themeTemplate.doc.mjs +9 -3
  12. package/api/theme-edit/_adapter.d.mts +10 -0
  13. package/api/theme-edit/_adapter.mjs +76 -5
  14. package/api/theme-edit/_check.mjs +181 -50
  15. package/api/theme-edit/_color.d.mts +2 -8
  16. package/api/theme-edit/_color.mjs +126 -55
  17. package/api/theme-edit/_compiler.d.mts +1 -0
  18. package/api/theme-edit/_compiler.mjs +3 -0
  19. package/api/theme-edit/_context.d.mts +7 -0
  20. package/api/theme-edit/_context.mjs +34 -1
  21. package/api/theme-edit/_css.d.mts +21 -1
  22. package/api/theme-edit/_css.mjs +172 -13
  23. package/api/theme-edit/_edit.d.mts +9 -0
  24. package/api/theme-edit/_edit.mjs +377 -48
  25. package/api/theme-edit/_how-commands.d.mts +7 -26
  26. package/api/theme-edit/_how-commands.mjs +27 -1
  27. package/api/theme-edit/_how-question.mjs +330 -12
  28. package/api/theme-edit/_how.mjs +68 -26
  29. package/api/theme-edit/_palette.mjs +10 -0
  30. package/api/theme-edit/_parts.d.mts +16 -0
  31. package/api/theme-edit/_parts.mjs +49 -1
  32. package/api/theme-edit/_preview-app.mjs +176 -9
  33. package/api/theme-edit/_preview.mjs +7 -3
  34. package/api/theme-edit/_project.d.mts +11 -0
  35. package/api/theme-edit/_project.mjs +35 -9
  36. package/api/theme-edit/_settings.d.mts +46 -5
  37. package/api/theme-edit/_settings.mjs +217 -25
  38. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  39. package/api/theme-edit/theme-edit.type.mjs +1 -1
  40. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  41. package/api/theme-edit/themeEditShow.doc.mjs +1 -1
  42. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  43. package/assets/docs.generated.json +2 -2
  44. package/assets/preview-app/next.config.mjs +7 -1
  45. package/assets/self-audit.generated.json +1 -1
  46. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  47. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  48. package/assets/templates/components.generated.json +1 -1
  49. package/clients/cli/build-id.generated.json +1 -1
  50. package/clients/cli/commands/experimental/theme.mjs +113 -34
  51. package/clients/cli/commands/experimental-theme-compile.doc.mjs +1 -1
  52. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  53. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  54. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  55. package/clients/cli/commands/experimental-theme-template.doc.mjs +1 -1
  56. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  57. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  58. package/clients/cli/commands/theme.mjs +82 -5
  59. package/clients/cli/manifest.generated.json +1 -1
  60. package/foundation/config/project.mjs +50 -14
  61. package/foundation/fs/gather-cache.mjs +4 -3
  62. package/foundation/fs/paths.d.mts +16 -0
  63. package/foundation/fs/paths.mjs +25 -0
  64. package/foundation/response/error-codes.d.mts +2 -1
  65. package/foundation/response/error-codes.d.ts +1 -0
  66. package/foundation/response/error-codes.doc.mjs +5 -0
  67. package/foundation/response/error-codes.mjs +3 -0
  68. package/foundation/response/response-types.doc.mjs +1 -1
  69. package/package.json +7 -6
package/README.md CHANGED
@@ -223,6 +223,7 @@ if (isError(result)) {
223
223
  | `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
224
224
  | `ERR_THEME_INVALID` | A theme definition or contributed theme descriptor is invalid. |
225
225
  | `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |
226
+ | `ERR_THEME_STALE` | `theme build --check` found stale or missing outputs: exit 1, in the check result (`code`), not an error. |
226
227
  | `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |
227
228
  | `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
228
229
  | `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
@@ -511,7 +512,7 @@ Every response has a `type` discriminant. The full set is below (generated from
511
512
  | `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
512
513
  | `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
513
514
  | `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, cssDts, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
514
- | `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
515
+ | `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), the full list of checked paths, and, when any is stale or missing, code ERR_THEME_STALE. Writes nothing. |
515
516
  | `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
516
517
  | `theme.list` | Every bundled, installed package, and local theme as a ThemeListEntry[]. Each entry has slug, displayName, description, maintained, owner package or local root, source, added, and default fields. Optional meta.unmigratedCopies names earlier descriptor-less copies, their missing descriptor, and the upgrade command; those copies are not data entries. |
517
518
  | `theme.app` | The app theme record after add, remove, or use. It includes every added theme and its built imports, the default slug, generated module path, and the command change. After add, the envelope package names the npm package that owns the added theme; a local theme has none. |
@@ -293,7 +293,7 @@ async function findUnreachableContributionIssues(
293
293
  issues.push(
294
294
  warning(
295
295
  'unreachable_contribution',
296
- `Found contribution metadata "${path.relative(packageDir, full)}" outside every declared integration root, so it contributes nothing. ${unreachableFix(context, full, stamp)}`,
296
+ `Found contribution metadata "${path.relative(packageDir, full).split(path.sep).join('/')}" outside every declared integration root, so it contributes nothing. ${unreachableFix(context, full, stamp)}`,
297
297
  ),
298
298
  );
299
299
  }
@@ -16,6 +16,7 @@ import {createRequire} from 'node:module';
16
16
  import {
17
17
  findCarriedCoreDir,
18
18
  findPackageRoot,
19
+ projectWritePath,
19
20
  requireCoreDir,
20
21
  } from '../../foundation/fs/paths.mjs';
21
22
  import {tryLock, userCacheDir} from '../../foundation/release/cache.mjs';
@@ -655,15 +656,17 @@ export function ejectThemeFiles(
655
656
  // The fork lands in the project, as list and add read it: the default root
656
657
  // is the project's, and a relative [path] is read from the working folder
657
658
  // 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)) || '.';
659
+ // Read as every theme command reads a path it writes; a backslash
660
+ // separates folders on every platform.
661
+ const {
662
+ projectDir,
663
+ typed: targetPath,
664
+ relative: target,
665
+ } = projectWritePath(
666
+ cwd,
667
+ typedPath || undefined,
668
+ defaultEjectTarget(theme.slug),
669
+ );
667
670
  let resolvedDir;
668
671
  try {
669
672
  resolvedDir = assertWithin(target, projectDir, {
@@ -190,24 +190,7 @@ export function themeBuildFamily(files: string[], options: {
190
190
  };
191
191
  }, { cwd }?: {
192
192
  cwd?: string;
193
- }): Promise<{
194
- type: string;
195
- data: {
196
- name: any;
197
- upToDate: boolean;
198
- stale: {
199
- path: string;
200
- reason: "missing" | "outdated";
201
- }[];
202
- checked: string[];
203
- tokenCount?: undefined;
204
- componentCount?: undefined;
205
- sizeKB?: undefined;
206
- outputs?: undefined;
207
- warnings?: undefined;
208
- notices?: undefined;
209
- };
210
- } | {
193
+ }): Promise<import("../theme.type.mjs").ThemeBuildCheckResponse | {
211
194
  type: string;
212
195
  data: {
213
196
  name: any;
@@ -222,9 +205,6 @@ export function themeBuildFamily(files: string[], options: {
222
205
  };
223
206
  warnings: any[];
224
207
  notices: string[];
225
- upToDate?: undefined;
226
- stale?: undefined;
227
- checked?: undefined;
228
208
  };
229
209
  }>;
230
210
  /**
@@ -84,6 +84,7 @@ import {
84
84
  PathSafetyError,
85
85
  } from '../../../foundation/fs/path-safety.mjs';
86
86
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
87
+ import {editorThemeRecord} from '../../../foundation/config/theme-state.mjs';
87
88
  import {validatePrivateVars} from '../../../foundation/config/theme-private-vars.mjs';
88
89
  import {AstryxError} from '../../error.mjs';
89
90
  import {applyWrites} from '../../integration/add-helpers.mjs';
@@ -1069,21 +1070,48 @@ function assertThemeSourceFile(filePath, cwd) {
1069
1070
  * @param {Array<{dest: string}>} writes
1070
1071
  * @param {string} filePath the theme source
1071
1072
  * @param {string} cwd
1072
- * @param {{claimed?: Map<string, string>, rerun?: string, refuseUnmarked?: boolean, elsewhere?: string}} [options]
1073
+ * @param {{claimed?: Map<string, string>, rerun?: (out: string | null) => string, refuseUnmarked?: boolean, elsewhere?: string, onEditorFolder?: (warning: string) => void}} [options]
1073
1074
  * `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
1075
+ * them; `rerun`: this build's command with another --out, or without one;
1076
+ * `elsewhere`: the option that moves the outputs; `onEditorFolder`: takes
1077
+ * the editor-folder warning instead of the logger (a watcher prints it once)
1076
1078
  */
1077
1079
  function assertOutputsReplaceable(
1078
1080
  writes,
1079
1081
  filePath,
1080
1082
  cwd,
1081
- {claimed, rerun, refuseUnmarked = false, elsewhere = '--out'} = {},
1083
+ {
1084
+ claimed,
1085
+ rerun,
1086
+ refuseUnmarked = false,
1087
+ elsewhere = '--out',
1088
+ onEditorFolder,
1089
+ } = {},
1082
1090
  ) {
1083
1091
  const rel = (/** @type {string} */ file) => path.relative(cwd, file);
1084
1092
  const sourceKey = outputKey(filePath);
1085
1093
  const seen = new Set();
1086
1094
  let warnedOtherSource = false;
1095
+ // The same build without --out, with its other options.
1096
+ const beside = {
1097
+ name: rerun
1098
+ ? rerun(null)
1099
+ : formatCliCommand(`theme build ${shellWord(rel(filePath))}`, cwd),
1100
+ reason: 'write the outputs beside this source',
1101
+ };
1102
+ // A folder the theme editor made holds that theme's outputs only: another
1103
+ // source's outputs there would sit beside its settings as if they were
1104
+ // its own. A source inside the folder builds there as always; one outside
1105
+ // it writes there too, with a warning.
1106
+ let editorFolder = false;
1107
+ if (refuseUnmarked && writes.length) {
1108
+ const dir = path.resolve(path.dirname(writes[0].dest));
1109
+ const record = editorThemeRecord(dir);
1110
+ const fromDir = path.relative(dir, path.resolve(filePath));
1111
+ // On Windows a source on another drive has an absolute relative path.
1112
+ const inside = !fromDir.startsWith('..') && !path.isAbsolute(fromDir);
1113
+ if (record && !inside) editorFolder = true;
1114
+ }
1087
1115
  for (const write of writes) {
1088
1116
  const key = outputKey(write.dest);
1089
1117
  if (key === sourceKey) {
@@ -1147,15 +1175,7 @@ function assertOutputsReplaceable(
1147
1175
  } else if (otherSource) {
1148
1176
  throw new AstryxError(
1149
1177
  `${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
- ],
1178
+ [beside],
1159
1179
  ERROR_CODES.ERR_FILE_EXISTS,
1160
1180
  );
1161
1181
  }
@@ -1166,20 +1186,70 @@ function assertOutputsReplaceable(
1166
1186
  stat.size > 0 &&
1167
1187
  !fileHead(write.dest).includes(GENERATED_MARKER)
1168
1188
  ) {
1189
+ // Never advice to delete it: it may be the person's file (a settings
1190
+ // file, app source). A path that takes every output instead.
1191
+ const free = freeOutPath(writes);
1169
1192
  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,
1193
+ `${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}.`,
1194
+ [
1195
+ ...(free && rerun
1196
+ ? [
1197
+ {
1198
+ name: rerun(rel(free)),
1199
+ reason: 'a path where no output of this build exists yet',
1200
+ },
1201
+ ]
1202
+ : []),
1203
+ beside,
1204
+ ],
1179
1205
  ERROR_CODES.ERR_FILE_EXISTS,
1180
1206
  );
1181
1207
  }
1182
1208
  }
1209
+ // Warned only once nothing refuses the build, so it names a write that
1210
+ // happens.
1211
+ if (editorFolder) {
1212
+ const dir = path.dirname(writes[0].dest);
1213
+ 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.`;
1214
+ if (onEditorFolder) onEditorFolder(warning);
1215
+ else logger.warn(warning);
1216
+ }
1217
+ }
1218
+
1219
+ /**
1220
+ * An --out path where no output of this build exists yet, or null. The
1221
+ * stylesheet and its `.css.d.ts` follow the name --out gives; the module and
1222
+ * its types are named after the theme, so a new name beside them (`brand-2.css`)
1223
+ * helps only when those are free, else a new folder (`brand-2/brand.css`).
1224
+ * @param {Array<{dest: string}>} writes the stylesheet first
1225
+ * @returns {string | null}
1226
+ */
1227
+ function freeOutPath(writes) {
1228
+ const css = writes[0]?.dest;
1229
+ if (!css) return null;
1230
+ const dir = path.dirname(css);
1231
+ const stem = path.basename(css).replace(/\.css$/i, '');
1232
+ /** Whether a write set (each output moved by `move`) touches any file. */
1233
+ const blocked = (/** @type {(dest: string) => string} */ move) =>
1234
+ writes.some(w => fs.existsSync(move(w.dest)));
1235
+ for (let n = 2; n < 100; n += 1) {
1236
+ const next = `${stem}-${n}`;
1237
+ // Only the stylesheet and its types follow --out's name.
1238
+ // The exact names a build with `--out <next>.css` writes, also when
1239
+ // --out did not end in .css (`o.txt` suggests `o.txt-2.css`).
1240
+ const renamed = (/** @type {string} */ dest) =>
1241
+ dest === css
1242
+ ? path.join(dir, `${next}.css`)
1243
+ : dest === `${css}.d.ts`
1244
+ ? path.join(dir, `${next}.css.d.ts`)
1245
+ : dest;
1246
+ if (!blocked(renamed)) return path.join(dir, `${next}.css`);
1247
+ const folder = (/** @type {string} */ dest) =>
1248
+ path.join(dir, next, path.basename(dest));
1249
+ if (!fs.existsSync(path.join(dir, next)) && !blocked(folder))
1250
+ return path.join(dir, next, path.basename(css));
1251
+ }
1252
+ return null;
1183
1253
  }
1184
1254
 
1185
1255
  /**
@@ -3504,13 +3574,14 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
3504
3574
  * `logger` (silent by default).
3505
3575
  *
3506
3576
  * @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] -
3577
+ * @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}, __onEditorFolder?: (warning: string) => void}} [options] -
3508
3578
  * `out` overrides the output CSS path, or names the folder for it; `check` compares against on-disk outputs
3509
3579
  * instead of writing. `__claimedOutputs` records the outputs earlier builds
3510
3580
  * in one run wrote, so a later theme cannot replace them; with
3511
3581
  * `__deferredWrites` the build adds its outputs to that list instead of
3512
3582
  * 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
3583
+ * output must stay inside, for a CLI-internal scratch build. `__onEditorFolder`
3584
+ * takes the editor-folder warning instead of the logger. `iconsSpecifier` overrides the icon registry import
3514
3585
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
3515
3586
  * direct registry specifiers from the theme source are emitted unchanged.
3516
3587
  * @param {{cwd?: string, projectCore?: boolean}} [ctx] `projectCore`: only the
@@ -4223,7 +4294,7 @@ async function themeBuildInternal(
4223
4294
  if (!options.check) {
4224
4295
  confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);
4225
4296
  // 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);
4297
+ const rerun = (/** @type {string | null} */ out) => formatCliCommand(['theme', 'build', path.relative(cwd, filePath), ...(out == null ? [] : ['--out', out]), ...(options.iconsSpecifier ? ['--icons-specifier', options.iconsSpecifier] : [])].map(shellWord).join(' '), cwd);
4227
4298
  // A header-less file at the default paths beside the source is an output
4228
4299
  // of a CLI before 0.6.7, which the build has always replaced. A path that
4229
4300
  // --out names may hold anything, so there only build outputs are replaced.
@@ -4231,6 +4302,7 @@ async function themeBuildInternal(
4231
4302
  claimed: options.__claimedOutputs,
4232
4303
  rerun,
4233
4304
  refuseUnmarked: Boolean(options.out),
4305
+ onEditorFolder: options.__onEditorFolder,
4234
4306
  });
4235
4307
  }
4236
4308
 
@@ -4263,15 +4335,17 @@ async function themeBuildInternal(
4263
4335
  `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
4264
4336
  );
4265
4337
  }
4266
- return {
4338
+ return /** @type {import('../theme.type.mjs').ThemeBuildCheckResponse} */ ({
4267
4339
  type: 'theme.build.check',
4268
4340
  data: {
4269
4341
  name: themeDef.name,
4270
4342
  upToDate,
4271
4343
  stale,
4272
4344
  checked: checkedBuildOutputs(writes, cwd),
4345
+ // The code a stale check exits 1 with, for --json callers.
4346
+ ...(upToDate ? {} : {code: ERROR_CODES.ERR_THEME_STALE}),
4273
4347
  },
4274
- };
4348
+ });
4275
4349
  }
4276
4350
 
4277
4351
  // A batch publishes every theme's outputs after all of them are built, so
@@ -4931,15 +5005,17 @@ export async function themeBuildFamily(
4931
5005
  `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
4932
5006
  );
4933
5007
  }
4934
- return {
5008
+ return /** @type {import('../theme.type.mjs').ThemeBuildCheckResponse} */ ({
4935
5009
  type: 'theme.build.check',
4936
5010
  data: {
4937
5011
  name: root.theme.name,
4938
5012
  upToDate,
4939
5013
  stale,
4940
5014
  checked: checkedBuildOutputs(writes, cwd),
5015
+ // The code a stale check exits 1 with, for --json callers.
5016
+ ...(upToDate ? {} : {code: ERROR_CODES.ERR_THEME_STALE}),
4941
5017
  },
4942
- };
5018
+ });
4943
5019
  }
4944
5020
  writeBuildOutputs(writes);
4945
5021
  for (const output of Object.values(outputs)) logger.log(`[ok] ${output}`);
@@ -17,5 +17,7 @@ export function themeTemplate(options?: {
17
17
  }): import("../theme.type.mjs").ThemeTemplateResponse;
18
18
  /** The annotated `defineTheme` reference that ships with the CLI. */
19
19
  export const THEME_TEMPLATE_SRC: string;
20
+ /** The warning the CLI prints when it writes the template outside a project. */
21
+ export const OUTSIDE_PROJECT_WARNING: "Warning: no package.json is in this folder or above it, so the template is written here. Run it inside a project, or run `npm init -y` here first, to write it at a project root.";
20
22
  /** Where it lands when the caller does not say. */
21
23
  export const THEME_TEMPLATE_DEFAULT_PATH: "theme.template.ts";
@@ -15,8 +15,11 @@
15
15
 
16
16
  import * as fs from 'node:fs';
17
17
  import * as path from 'node:path';
18
- import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
19
- import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
18
+ import {CLI_ROOT, projectWritePath} from '../../../foundation/fs/paths.mjs';
19
+ import {
20
+ assertWithin,
21
+ PathSafetyError,
22
+ } from '../../../foundation/fs/path-safety.mjs';
20
23
  import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
21
24
  import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';
22
25
  import {fsErrorMessage} from '../../../foundation/fs/fs-error.mjs';
@@ -25,7 +28,15 @@ import {AstryxError} from '../../error.mjs';
25
28
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
26
29
 
27
30
  /** The annotated `defineTheme` reference that ships with the CLI. */
28
- export const THEME_TEMPLATE_SRC = path.join(CLI_ROOT, 'assets', 'theme.template.ts');
31
+ export const THEME_TEMPLATE_SRC = path.join(
32
+ CLI_ROOT,
33
+ 'assets',
34
+ 'theme.template.ts',
35
+ );
36
+
37
+ /** The warning the CLI prints when it writes the template outside a project. */
38
+ export const OUTSIDE_PROJECT_WARNING =
39
+ 'Warning: no package.json is in this folder or above it, so the template is written here. Run it inside a project, or run `npm init -y` here first, to write it at a project root.';
29
40
 
30
41
  /** Where it lands when the caller does not say. */
31
42
  export const THEME_TEMPLATE_DEFAULT_PATH = 'theme.template.ts';
@@ -100,20 +111,33 @@ export function themeTemplate(options = {}) {
100
111
  );
101
112
  }
102
113
 
114
+ // The project the folder belongs to bounds the path, as for other theme
115
+ // commands: a path given is read from the current folder, and no path
116
+ // means the project root.
117
+ // With no package.json at or above the folder it writes here, and the CLI
118
+ // prints OUTSIDE_PROJECT_WARNING.
119
+ // Read as every theme command reads a path it writes; a backslash
120
+ // separates folders on every platform.
121
+ const {projectDir, relative: fromRoot} = projectWritePath(
122
+ cwd,
123
+ options.targetPath == null ? undefined : String(targetPath),
124
+ THEME_TEMPLATE_DEFAULT_PATH,
125
+ );
103
126
  let resolved;
104
127
  try {
105
- resolved = assertWithin(targetPath, cwd, {label: 'theme template path'});
128
+ resolved = assertWithin(fromRoot, projectDir, {
129
+ label: 'theme template path',
130
+ });
106
131
  } catch (err) {
107
132
  if (err instanceof PathSafetyError) {
108
133
  throw new AstryxError(
109
- err.message,
134
+ // The path as typed, not as read from the project root.
135
+ err.message.replace(`"${fromRoot}"`, `"${targetPath}"`),
110
136
  [
111
137
  {
112
- name: formatCliCommand(
113
- `theme template ${THEME_TEMPLATE_DEFAULT_PATH}`,
114
- cwd,
115
- ),
116
- reason: 'write the template in this project',
138
+ // No path: the template at the project root.
139
+ name: formatCliCommand('theme template', cwd),
140
+ reason: 'write the template at the project root',
117
141
  },
118
142
  ],
119
143
  ERROR_CODES.ERR_PATH_TRAVERSAL,
@@ -212,7 +236,9 @@ export function themeTemplate(options = {}) {
212
236
  }
213
237
 
214
238
  // Our repo header has no business in someone else's source tree.
215
- const contents = stripCopyrightHeader(fs.readFileSync(THEME_TEMPLATE_SRC, 'utf-8'));
239
+ const contents = stripCopyrightHeader(
240
+ fs.readFileSync(THEME_TEMPLATE_SRC, 'utf-8'),
241
+ );
216
242
  try {
217
243
  fs.mkdirSync(path.dirname(resolved), {recursive: true});
218
244
  fs.writeFileSync(resolved, contents);
@@ -223,7 +249,10 @@ export function themeTemplate(options = {}) {
223
249
  throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
224
250
  }
225
251
 
226
- return {type: 'theme.template', data: {path: relative, written: true, reason: null}};
252
+ return {
253
+ type: 'theme.template',
254
+ data: {path: relative, written: true, reason: null},
255
+ };
227
256
  }
228
257
 
229
258
  /** @param {string} file */
@@ -32,6 +32,9 @@ export type ThemeBuildResponse = {
32
32
  */
33
33
  export type ThemeBuildCheckResponse = {
34
34
  type: "theme.build.check";
35
+ /**
36
+ * `code` is set when the outputs are stale or missing (exit 1).
37
+ */
35
38
  data: {
36
39
  name: string;
37
40
  upToDate: boolean;
@@ -40,6 +43,7 @@ export type ThemeBuildCheckResponse = {
40
43
  reason: "missing" | "outdated";
41
44
  }>;
42
45
  checked: string[];
46
+ code?: "ERR_THEME_STALE";
43
47
  };
44
48
  };
45
49
  /**
@@ -38,7 +38,8 @@
38
38
  * astryx --json theme build <file> --check
39
39
  * @typedef {object} ThemeBuildCheckResponse
40
40
  * @property {'theme.build.check'} type
41
- * @property {{name: string, upToDate: boolean, stale: Array<{path: string, reason: 'missing' | 'outdated'}>, checked: string[]}} data
41
+ * @property {{name: string, upToDate: boolean, stale: Array<{path: string, reason: 'missing' | 'outdated'}>, checked: string[], code?: 'ERR_THEME_STALE'}} data
42
+ * `code` is set when the outputs are stale or missing (exit 1).
42
43
  */
43
44
 
44
45
  /**
@@ -58,7 +58,7 @@ export const doc = {
58
58
  name: 'options.out',
59
59
  type: 'string',
60
60
  description:
61
- 'Override the output CSS path, relative or absolute; a build refuses a path outside cwd, and check mode refuses only a relative path that escapes cwd. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file. An existing folder, or a path that ends in a separator, names the folder: the CSS is written there as <name>.css. A file path should end in .css; another name still builds, with a warning, and the import line it prints names the file as written.',
61
+ 'Override the output CSS path, relative or absolute; a build refuses a path outside cwd, and check mode refuses only a relative path that escapes cwd. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file. An existing folder, or a path that ends in a separator, names the folder: the CSS is written there as <name>.css. A file path should end in .css; another name still builds, with a warning, and the import line it prints names the file as written. A path in a folder the theme editor made (folder <slug>/ holds <slug>.settings.json) takes the outputs of a source outside that folder too, and the CLI warns; to keep the editor folder to its own theme, build beside the source, or pick an out path outside it.',
62
62
  },
63
63
  {
64
64
  name: 'options.check',
@@ -90,7 +90,7 @@ export const doc = {
90
90
  {
91
91
  type: 'theme.build.check',
92
92
  description:
93
- 'The {check: true} receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: "missing" | "outdated"}), and the full list of checked paths. Writes nothing. Resolves to null, like a normal build, when the theme produces no CSS.',
93
+ 'The {check: true} receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: "missing" | "outdated"}), the full list of checked paths, and, when stale, code ERR_THEME_STALE. Writes nothing. Resolves to null, like a normal build, when the theme produces no CSS.',
94
94
  },
95
95
  ],
96
96
  throws: [
@@ -108,7 +108,7 @@ export const doc = {
108
108
  },
109
109
  {
110
110
  code: 'ERR_FILE_EXISTS',
111
- when: 'a path that out names holds a non-empty file without the generated header, such as package.json, app source, or an output from a CLI before 0.6.7; nothing is written. Delete the file and run the same build again (the suggestion), or pick another out path. At the default paths beside the source, and at family output paths, a header-less file is an output of a CLI before 0.6.7 and is replaced',
111
+ when: 'a path that out names holds a non-empty file without the generated header, such as package.json, app source, or an output from a CLI before 0.6.7; nothing is written. The suggestions name a free out path beside it and the build beside the source; the file is left as it is. At the default paths beside the source, and at family output paths, a header-less file is an output of a CLI before 0.6.7 and is replaced',
112
112
  },
113
113
  {
114
114
  code: 'ERR_INVALID_ARGUMENT',
@@ -22,7 +22,9 @@ export const doc = {
22
22
  'Read it, copy what you need into your own theme file, delete it. Use `theme add` to ' +
23
23
  'use an installed built theme, extend that theme for ordinary customization, or use ' +
24
24
  '`theme eject` for a complete source fork. This command starts a new blank theme. Refuses to overwrite without ' +
25
- '`overwrite`, so it is safe to re-run.',
25
+ '`overwrite`, so it is safe to re-run. With no package.json at or above cwd, it writes in cwd ' +
26
+ 'and the CLI warns; pass a cwd inside a project, or run `npm init -y` in that folder first, to ' +
27
+ 'write it at a project root.',
26
28
  importPath: '@astryxdesign/cli/api',
27
29
  signature:
28
30
  'themeTemplate(options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): ThemeTemplateResponse',
@@ -31,7 +33,8 @@ export const doc = {
31
33
  {
32
34
  name: 'options.targetPath',
33
35
  type: 'string',
34
- description: 'Destination file. Must resolve within cwd.',
36
+ description:
37
+ 'Destination file, read from cwd. Must resolve within the project root: the nearest folder at or above cwd with a package.json. Left out, the template is written at the project root.',
35
38
  default: "'theme.template.ts'",
36
39
  },
37
40
  {
@@ -55,7 +58,10 @@ export const doc = {
55
58
  },
56
59
  ],
57
60
  throws: [
58
- {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},
61
+ {
62
+ code: 'ERR_PATH_TRAVERSAL',
63
+ when: 'the target path escapes the project root (the nearest folder at or above cwd with a package.json)',
64
+ },
59
65
  {
60
66
  code: 'ERR_INVALID_ARGUMENT',
61
67
  when: 'the target path is blank, names a folder, or is not a .ts file (with or without overwrite)',