@astryxdesign/cli 0.6.5-canary.3646c6d → 0.6.5-canary.3f1bee4

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 (81) hide show
  1. package/README.md +13 -14
  2. package/api/error.d.mts +0 -22
  3. package/api/error.mjs +0 -42
  4. package/api/integration/add-contribution.d.mts +1 -2
  5. package/api/integration/add-contribution.mjs +3 -7
  6. package/api/integration/add-contribution.test.mjs +3 -3
  7. package/api/integration/add-theme.mjs +22 -243
  8. package/api/integration/add-theme.test.mjs +0 -213
  9. package/api/integration/authoring-checks.mjs +7 -10
  10. package/api/integration/authoring-checks.type.d.mts +0 -8
  11. package/api/integration/authoring-checks.type.mjs +3 -7
  12. package/api/integration/integration-authoring.type.d.mts +1 -4
  13. package/api/integration/integration-authoring.type.mjs +1 -6
  14. package/api/integration/integrationAdd.doc.mjs +0 -6
  15. package/api/integration/integrationAddTheme.doc.mjs +0 -10
  16. package/api/integration/integrationComponentConflicts.doc.mjs +1 -1
  17. package/api/integration/integrationDocConflicts.doc.mjs +1 -1
  18. package/api/integration/integrationTemplateConflicts.doc.mjs +1 -1
  19. package/api/integration/pack-check.test.mjs +1 -7
  20. package/api/integration/validate-integration.d.mts +2 -4
  21. package/api/integration/validate-integration.mjs +2 -7
  22. package/api/integration/validate-integration.test.mjs +0 -55
  23. package/api/integration/validate-integration.type.d.mts +0 -5
  24. package/api/integration/validate-integration.type.mjs +1 -5
  25. package/api/integration/validateIntegration.doc.mjs +1 -1
  26. package/api/layout/expand/expand.mjs +7 -12
  27. package/api/layout/layout.type.d.mts +0 -1
  28. package/api/layout/layout.type.mjs +0 -1
  29. package/api/layout/layoutExpand.doc.mjs +1 -1
  30. package/api/swizzle/copy/copy.mjs +3 -66
  31. package/api/swizzle/swizzle.doc.mjs +0 -4
  32. package/api/template/copy/copy.mjs +8 -14
  33. package/api/template/show/show.mjs +4 -15
  34. package/api/template/template.d.mts +1 -1
  35. package/api/template/template.doc.mjs +2 -6
  36. package/api/template/template.mjs +0 -1
  37. package/api/template/template.type.d.mts +0 -2
  38. package/api/template/template.type.mjs +0 -2
  39. package/api/upgrade/run/run.mjs +3 -20
  40. package/api/upgrade/run/run.test.mjs +1 -45
  41. package/api/upgrade/upgrade.doc.mjs +1 -1
  42. package/api/upgrade/upgrade.type.d.mts +0 -1
  43. package/api/upgrade/upgrade.type.mjs +0 -1
  44. package/assets/docs/tree/check-your-docs.doc.mjs +2 -2
  45. package/assets/docs/tree/checks.doc.mjs +1 -1
  46. package/assets/docs/tree/sections-and-placement.doc.mjs +1 -1
  47. package/assets/docs/tree/troubleshooting.doc.mjs +4 -4
  48. package/assets/docs/tree/versioning.doc.mjs +4 -4
  49. package/clients/cli/commands/doctor.mjs +4 -4
  50. package/clients/cli/commands/integration-add.doc.mjs +0 -10
  51. package/clients/cli/commands/integration-authoring.test.mjs +2 -12
  52. package/clients/cli/commands/integration.mjs +1 -3
  53. package/clients/cli/commands/layout-expand.doc.mjs +1 -3
  54. package/clients/cli/commands/layout.mjs +0 -16
  55. package/clients/cli/commands/template.mjs +5 -19
  56. package/clients/cli/commands/upgrade.ascii-output.test.mjs +0 -14
  57. package/clients/cli/lib/manifest.mjs +165 -44
  58. package/clients/cli/lib/manifest.test.mjs +7 -98
  59. package/foundation/discovery/template-adapter.d.mts +0 -13
  60. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +1 -37
  61. package/foundation/discovery/template-adapter.mjs +1 -16
  62. package/foundation/integrations/cli-requirement.d.mts +11 -14
  63. package/foundation/integrations/cli-requirement.mjs +19 -24
  64. package/foundation/integrations/cli-requirement.test.mjs +16 -60
  65. package/foundation/response/response-types.doc.d.mts +5 -5
  66. package/foundation/response/response-types.doc.mjs +13 -13
  67. package/package.json +9 -9
  68. package/api/docs/docs.test.mjs +0 -279
  69. package/api/docs/integration-tree.test.mjs +0 -572
  70. package/api/docs/integrationDocs.test.mjs +0 -336
  71. package/api/layout/expand/expand.receipt.test.mjs +0 -74
  72. package/api/search/search.test.mjs +0 -710
  73. package/api/template/copy/copy.receipt.test.mjs +0 -77
  74. package/api/template/show/show.test.mjs +0 -76
  75. package/clients/cli/commands/docs.test.mjs +0 -383
  76. package/clients/cli/commands/layout.expand-receipt.test.mjs +0 -94
  77. package/clients/cli/commands/template.copy-receipt.test.mjs +0 -60
  78. package/clients/cli/commands/template.show-media.test.mjs +0 -62
  79. package/clients/cli/commands/write-failure.test.mjs +0 -175
  80. package/foundation/agent-docs/agent-docs.test.mjs +0 -1160
  81. package/foundation/doc-compiler/tree.test.mjs +0 -649
package/README.md CHANGED
@@ -303,12 +303,11 @@ Shape:
303
303
  ```
304
304
 
305
305
  The manifest is **derived from Commander metadata** (commands, arguments, options)
306
- so it can't drift from the real command definitions. The facts Commander doesn't
307
- track come from each command's docs: examples from its CommandDoc, and emitted
308
- response types from the returns of the FunctionDoc it wraps (plus the few
309
- envelopes the CLI layer builds itself). `--json` support comes from the
310
- `JSON_SUPPORTED` allowlist. Drift tests (`manifest.test.mjs`) fail CI when a
311
- command is added without describing it.
306
+ so it can't drift from the real command definitions. The two facts Commander
307
+ doesn't track (`--json` support and emitted response types) are layered on from
308
+ the `JSON_SUPPORTED` allowlist and a small declarative `RESPONSE_TYPES` map in
309
+ `src/lib/manifest.mjs`, guarded by a drift test (`manifest.test.mjs`) so adding a
310
+ command without describing it fails CI.
312
311
 
313
312
  **Backwards-compat:** the bare `astryx --json` envelope keeps `type: "help"` and its
314
313
  original shallow fields (`name`, `version`, `commands` as a `string[]` of names,
@@ -451,9 +450,9 @@ Every response has a `type` discriminant. The full set is below (generated from
451
450
  | `gap-report.categories` | The fixed gap category values and human-readable labels. |
452
451
  | `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |
453
452
  | `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
454
- | `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
453
+ | `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |
455
454
  | `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
456
- | `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
455
+ | `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
457
456
  | `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
458
457
  | `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
459
458
  | `hook.detail` | One hook's full authored HookDoc. |
@@ -469,18 +468,18 @@ Every response has a `type` discriminant. The full set is below (generated from
469
468
  | `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
470
469
  | `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
471
470
  | `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
472
- | `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
471
+ | `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
473
472
  | `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
474
473
  | `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
475
474
  | `version` | The CLI version, for `astryx --version --json`: {version}. |
476
475
  | `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. |
477
476
  | `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. |
478
477
  | `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message}]. |
479
- | `integration.validate` | The validation result: validated (false when no integration manifest was found, so nothing was checked and the empty issues list proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
480
- | `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
481
- | `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
482
- | `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
483
- | `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). |
478
+ | `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
479
+ | `integration.template-conflicts` | The integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
480
+ | `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
481
+ | `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
482
+ | `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |
484
483
  | `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |
485
484
  | `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |
486
485
 
package/api/error.d.mts CHANGED
@@ -1,28 +1,6 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
- /**
5
- * The error for a write that failed on the filesystem: no permission, a
6
- * read-only mount, a full disk, a path component that is not a directory.
7
- *
8
- * A raw Node errno error reached the envelope as
9
- * `{"error": "EACCES: permission denied, open '/home/you/p/readonly/x.tsx'",
10
- * "code": "ERR_UNKNOWN"}` — the wrong code (ERR_WRITE_FAILED is in the frozen
11
- * registry for exactly this) and an absolute host path in the message. This
12
- * keeps the errno, which is the part that tells you what to fix, and reports
13
- * the target the way every other Astryx message does: relative to the project.
14
- *
15
- * A caller that wrote files before the failure must undo them first and pass
16
- * the ones it could not restore as `unrestored`, so the message never says
17
- * nothing was written when something was.
18
- *
19
- * @param {string} target absolute path the write was aimed at
20
- * @param {string} cwd project root, for the relative form
21
- * @param {unknown} cause the error the filesystem call threw
22
- * @param {string[]} [unrestored] absolute paths an undo could not put back
23
- * @returns {AstryxError}
24
- */
25
- export function writeFailed(target: string, cwd: string, cause: unknown, unrestored?: string[]): AstryxError;
26
4
  export class AstryxError extends Error {
27
5
  /**
28
6
  * @param {string} message
package/api/error.mjs CHANGED
@@ -12,7 +12,6 @@
12
12
  */
13
13
 
14
14
  import {ERROR_CODES} from '../foundation/response/error-codes.mjs';
15
- import * as path from 'node:path';
16
15
 
17
16
  export class AstryxError extends Error {
18
17
  /** @type {import('../foundation/response/base').Suggestion[] | undefined} */
@@ -37,44 +36,3 @@ export class AstryxError extends Error {
37
36
  if (Array.isArray(suggestions) && suggestions.length) this.suggestions = suggestions;
38
37
  }
39
38
  }
40
-
41
- /**
42
- * The error for a write that failed on the filesystem: no permission, a
43
- * read-only mount, a full disk, a path component that is not a directory.
44
- *
45
- * A raw Node errno error reached the envelope as
46
- * `{"error": "EACCES: permission denied, open '/home/you/p/readonly/x.tsx'",
47
- * "code": "ERR_UNKNOWN"}` — the wrong code (ERR_WRITE_FAILED is in the frozen
48
- * registry for exactly this) and an absolute host path in the message. This
49
- * keeps the errno, which is the part that tells you what to fix, and reports
50
- * the target the way every other Astryx message does: relative to the project.
51
- *
52
- * A caller that wrote files before the failure must undo them first and pass
53
- * the ones it could not restore as `unrestored`, so the message never says
54
- * nothing was written when something was.
55
- *
56
- * @param {string} target absolute path the write was aimed at
57
- * @param {string} cwd project root, for the relative form
58
- * @param {unknown} cause the error the filesystem call threw
59
- * @param {string[]} [unrestored] absolute paths an undo could not put back
60
- * @returns {AstryxError}
61
- */
62
- export function writeFailed(target, cwd, cause, unrestored = []) {
63
- const rel = path.relative(cwd, target) || target;
64
- const errno =
65
- typeof (/** @type {any} */ (cause)?.code) === 'string'
66
- ? /** @type {any} */ (cause).code
67
- : null;
68
- const why = errno === 'EACCES' || errno === 'EPERM' ? ' (no permission)' : '';
69
- const outcome =
70
- unrestored.length === 0
71
- ? 'Nothing was written.'
72
- : `Earlier writes could not all be undone: ${unrestored
73
- .map(file => path.relative(cwd, file) || file)
74
- .join(', ')}.`;
75
- return new AstryxError(
76
- `Could not write ${rel}${errno ? `: ${errno}` : ''}${why}. ${outcome}`,
77
- undefined,
78
- ERROR_CODES.ERR_WRITE_FAILED,
79
- );
80
- }
@@ -31,7 +31,7 @@ export function integrationAddAgentDoc(line: string, options?: import("./integra
31
31
  *
32
32
  * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
33
33
  * @param {string} name
34
- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]
34
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string}} [options]
35
35
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
36
36
  */
37
37
  export function integrationAdd(kind: "component" | "doc" | "template" | "codemod" | "agent-doc" | "theme", name: string, options?: {
@@ -42,5 +42,4 @@ export function integrationAdd(kind: "component" | "doc" | "template" | "codemod
42
42
  replaces?: string;
43
43
  extends?: string;
44
44
  parent?: string;
45
- from?: string;
46
45
  }): Promise<import("./integration-authoring.type.mjs").IntegrationAddResponse>;
@@ -1211,7 +1211,7 @@ const KIND_OPTIONS = {
1211
1211
  template: new Set(['cwd', 'dryRun', 'templateType']),
1212
1212
  codemod: new Set(['cwd', 'dryRun', 'to']),
1213
1213
  'agent-doc': new Set(['cwd', 'dryRun']),
1214
- theme: new Set(['cwd', 'dryRun', 'from']),
1214
+ theme: new Set(['cwd', 'dryRun']),
1215
1215
  };
1216
1216
 
1217
1217
  /**
@@ -1238,7 +1238,7 @@ function validateKindOptions(kind, options) {
1238
1238
  *
1239
1239
  * @param {'component'|'doc'|'template'|'codemod'|'agent-doc'|'theme'} kind
1240
1240
  * @param {string} name
1241
- * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]
1241
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string}} [options]
1242
1242
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
1243
1243
  */
1244
1244
  export async function integrationAdd(kind, name, options = {}) {
@@ -1270,10 +1270,6 @@ export async function integrationAdd(kind, name, options = {}) {
1270
1270
  case 'agent-doc':
1271
1271
  return integrationAddAgentDoc(name, options);
1272
1272
  case 'theme':
1273
- return integrationAddTheme(name, {
1274
- cwd: options.cwd,
1275
- dryRun: options.dryRun,
1276
- from: options.from,
1277
- });
1273
+ return integrationAddTheme(name, options);
1278
1274
  }
1279
1275
  }
@@ -12,7 +12,7 @@ import {
12
12
  integrationAddTemplate,
13
13
  } from './add-contribution.mjs';
14
14
  import {validateLocalIntegration} from './validate-integration.mjs';
15
- import {NAMESPACE_DOCS_CLI} from '../../foundation/integrations/cli-requirement.mjs';
15
+ import {DOCS_TREE_CLI} from '../../foundation/integrations/cli-requirement.mjs';
16
16
 
17
17
  let tmpDir;
18
18
 
@@ -355,7 +355,7 @@ describe('integrationAdd doc', () => {
355
355
 
356
356
  // The namespace doc needs a CLI that reads it, declared as an optional peer.
357
357
  const pkg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'));
358
- expect(pkg.peerDependencies).toEqual({'@astryxdesign/cli': '>=0.6.4'});
358
+ expect(pkg.peerDependencies).toEqual({'@astryxdesign/cli': `>=${DOCS_TREE_CLI}`});
359
359
  expect(pkg.peerDependenciesMeta).toEqual({'@astryxdesign/cli': {optional: true}});
360
360
 
361
361
  const second = await integrationAdd('doc', 'upgrading', {
@@ -429,7 +429,7 @@ describe('integrationAdd doc', () => {
429
429
  write('^0.6.0');
430
430
  await integrationAdd('doc', 'deploying', {cwd: tmpDir, parent: 'acme'});
431
431
  expect(JSON.parse(fs.readFileSync(file, 'utf-8')).peerDependencies).toEqual({
432
- '@astryxdesign/cli': `>=${NAMESPACE_DOCS_CLI}`,
432
+ '@astryxdesign/cli': `>=${DOCS_TREE_CLI}`,
433
433
  });
434
434
  write('^9.1.0');
435
435
  await integrationAdd('doc', 'upgrading', {cwd: tmpDir, parent: 'acme'});
@@ -4,9 +4,6 @@
4
4
  * @file `astryx integration add theme` — scaffold one strongly typed,
5
5
  * same-stem source/descriptor pair into an integration package and declare the
6
6
  * themes root on first use.
7
- *
8
- * `--from <base>` forks an existing theme's source files as the starting point
9
- * instead of writing a blank `defineTheme` skeleton.
10
7
  */
11
8
 
12
9
  import * as fs from 'node:fs';
@@ -18,10 +15,7 @@ import {
18
15
  PathSafetyError,
19
16
  sanitizeName,
20
17
  } from '../../foundation/fs/path-safety.mjs';
21
- import {
22
- discoverBundledThemes,
23
- discoverThemeDirectory,
24
- } from '../../foundation/discovery/theme-discovery.mjs';
18
+ import {discoverThemeDirectory} from '../../foundation/discovery/theme-discovery.mjs';
25
19
  import {
26
20
  findLocalIntegrationManifestOrNull,
27
21
  IntegrationRootConflictError,
@@ -35,7 +29,6 @@ import {
35
29
  themesCliProblem,
36
30
  withCliPeer,
37
31
  } from '../../foundation/integrations/cli-requirement.mjs';
38
- import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';
39
32
  import {
40
33
  applyWrites,
41
34
  findPackageDir,
@@ -77,7 +70,6 @@ function themeIdentity(slug) {
77
70
  .join(' ');
78
71
  return {
79
72
  slug,
80
- identifier,
81
73
  displayName,
82
74
  exportName: `${identifier}Theme`,
83
75
  entry: `${identifier}Theme.ts`,
@@ -101,182 +93,6 @@ function themeDescriptor(identity) {
101
93
  });
102
94
  }
103
95
 
104
- // ── --from: resolve and fork a base theme ───────────────────────────
105
-
106
- /**
107
- * Resolve a theme slug to its discovered record, searching the bundled themes
108
- * and the package's own themes root (when it has one).
109
- * @param {string} slug
110
- * @param {string} packageDir
111
- * @param {string} owner
112
- * @param {string | undefined} themesRoot resolved absolute themes root, if any
113
- * @returns {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme}
114
- */
115
- function resolveBaseTheme(slug, packageDir, owner, themesRoot) {
116
- const normalized = slug.toLowerCase();
117
-
118
- /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} */
119
- let candidates = [];
120
- try {
121
- candidates = discoverBundledThemes();
122
- } catch {
123
- // Bundled themes unavailable — not fatal, package themes may suffice.
124
- }
125
-
126
- // Also check the package's own themes root.
127
- if (themesRoot && fs.existsSync(themesRoot)) {
128
- try {
129
- candidates = [...candidates, ...discoverThemeDirectory(themesRoot, owner)];
130
- } catch {
131
- // A broken local root is not the caller's problem here.
132
- }
133
- }
134
-
135
- const match = candidates.find(t => t.slug.toLowerCase() === normalized);
136
- if (!match) {
137
- throw new AstryxError(
138
- `Unknown base theme "${slug}". Available themes: ${candidates.map(t => t.slug).join(', ') || '(none)'}.`,
139
- candidates.map(t => ({
140
- name: t.slug,
141
- reason: t.bundled ? 'bundled theme' : `provided by ${t.package}`,
142
- })),
143
- ERROR_CODES.ERR_UNKNOWN_THEME,
144
- );
145
- }
146
- return match;
147
- }
148
-
149
- /**
150
- * Rename a file from the base theme's namespace to the new theme's namespace.
151
- * Files whose name starts with the base identifier get the new identifier;
152
- * others keep their name as-is.
153
- * @param {string} file POSIX relative path inside the theme directory
154
- * @param {string} baseIdentifier
155
- * @param {string} newIdentifier
156
- * @returns {string}
157
- */
158
- function renameThemeFile(file, baseIdentifier, newIdentifier) {
159
- const basename = path.posix.basename(file);
160
- const dir = path.posix.dirname(file);
161
- if (!basename.startsWith(baseIdentifier)) return file;
162
- const renamed = newIdentifier + basename.slice(baseIdentifier.length);
163
- return dir === '.' ? renamed : `${dir}/${renamed}`;
164
- }
165
-
166
- /**
167
- * Rewrite a source file's contents from the base theme's names to the new
168
- * theme's names. This replaces:
169
- * 1. Identifier prefixes (camelCase variables, import paths): baseIdentifier
170
- * followed by an uppercase letter.
171
- * 2. The theme slug in string literals: 'baseSlug' → 'newSlug' and
172
- * 'astryx-baseSlug' → 'astryx-newSlug'.
173
- * 3. CSS custom properties scoped to the theme: --astryx-theme-baseSlug-.
174
- * @param {string} source
175
- * @param {string} baseSlug
176
- * @param {string} baseIdentifier
177
- * @param {string} newSlug
178
- * @param {string} newIdentifier
179
- * @returns {string}
180
- */
181
- function rewriteThemeSource(
182
- source,
183
- baseSlug,
184
- baseIdentifier,
185
- newSlug,
186
- newIdentifier,
187
- ) {
188
- let result = source;
189
- // 1. Identifier prefixes: neutralPalettes → oceanPalettes, neutralTheme → oceanTheme
190
- const identRe = new RegExp(`${escapeRegExp(baseIdentifier)}(?=[A-Z])`, 'gu');
191
- result = result.replace(identRe, newIdentifier);
192
- // 2. String-literal theme names
193
- result = result.replace(
194
- new RegExp(`'astryx-${escapeRegExp(baseSlug)}'`, 'gu'),
195
- `'astryx-${newSlug}'`,
196
- );
197
- result = result.replace(
198
- new RegExp(`'${escapeRegExp(baseSlug)}'`, 'gu'),
199
- `'${newSlug}'`,
200
- );
201
- // 3. CSS custom properties scoped to the base theme
202
- result = result.replace(
203
- new RegExp(
204
- `--astryx-theme-${escapeRegExp(baseSlug)}-`,
205
- 'gu',
206
- ),
207
- `--astryx-theme-${newSlug}-`,
208
- );
209
- return result;
210
- }
211
-
212
- /** @param {string} s */
213
- function escapeRegExp(s) {
214
- return s.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
215
- }
216
-
217
- /**
218
- * Build the write plans for a forked theme.
219
- * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
220
- * @param {ReturnType<typeof themeIdentity>} identity new theme identity
221
- * @param {string} themeDir absolute target directory
222
- * @returns {import('./add-helpers.mjs').WritePlan[]}
223
- */
224
- function forkThemePlans(base, identity, themeDir) {
225
- const baseIdentity = themeIdentity(base.slug);
226
- /** @type {import('./add-helpers.mjs').WritePlan[]} */
227
- const plans = [];
228
-
229
- // Copy every file the base theme ships (entry first, then the rest), except
230
- // the descriptor — we write a fresh one.
231
- const filesToCopy = base.files.filter(
232
- file => path.posix.basename(file) !== `${baseIdentity.exportName}.doc.mjs`,
233
- );
234
-
235
- for (const file of filesToCopy) {
236
- const srcPath = path.join(base.sourceDir, file);
237
- const newFileName = renameThemeFile(
238
- file,
239
- baseIdentity.identifier,
240
- identity.identifier,
241
- );
242
- const destPath = assertWithin(newFileName, themeDir, {
243
- label: `forked theme file "${newFileName}"`,
244
- });
245
-
246
- // Read source bytes; for text, strip copyright and rewrite identifiers.
247
- const bytes = fs.readFileSync(srcPath);
248
- const text = bytes.toString('utf-8');
249
- const isText = Buffer.from(text, 'utf-8').equals(bytes);
250
-
251
- /** @type {string | Buffer} */
252
- let contents;
253
- if (isText) {
254
- contents = rewriteThemeSource(
255
- stripCopyrightHeader(text),
256
- base.slug,
257
- baseIdentity.identifier,
258
- identity.slug,
259
- identity.identifier,
260
- );
261
- } else {
262
- contents = bytes;
263
- }
264
- plans.push({path: destPath, contents, createOnly: true});
265
- }
266
-
267
- // Write a fresh descriptor — the fork is a new theme, not a derivative.
268
- const descriptorPath = assertWithin(identity.descriptor, themeDir, {
269
- label: 'theme descriptor file',
270
- });
271
- plans.push({
272
- path: descriptorPath,
273
- contents: themeDescriptor(identity),
274
- createOnly: true,
275
- });
276
-
277
- return plans;
278
- }
279
-
280
96
  /**
281
97
  * Read bytes back through the same discovery seam Project uses. A write is not
282
98
  * successful until the requested slug resolves.
@@ -314,7 +130,7 @@ async function verifyThemeContribution(packageDir, manifestFile, owner, slug) {
314
130
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
315
131
  */
316
132
  export async function integrationAddTheme(name, options = {}) {
317
- const {cwd = process.cwd(), dryRun = false, from} = options;
133
+ const {cwd = process.cwd(), dryRun = false} = options;
318
134
  const packageDir = findPackageDir(cwd);
319
135
  const packageFile = path.join(packageDir, 'package.json');
320
136
  let pkg;
@@ -396,64 +212,32 @@ export async function integrationAddTheme(name, options = {}) {
396
212
  const themeDir = assertWithin(identity.slug, root, {
397
213
  label: 'theme directory',
398
214
  });
399
-
400
- // Resolve the base theme when --from is given, before writing anything.
401
- /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined} */
402
- let baseTheme;
403
- if (from != null) {
404
- if (from === name) {
215
+ const sourceFile = assertWithin(identity.entry, themeDir, {
216
+ label: 'theme source file',
217
+ });
218
+ const descriptorFile = assertWithin(identity.descriptor, themeDir, {
219
+ label: 'theme descriptor file',
220
+ });
221
+ // An existing folder is filled; only a file this would write is refused.
222
+ for (const file of [sourceFile, descriptorFile]) {
223
+ if (fs.existsSync(file)) {
405
224
  throw new AstryxError(
406
- `Cannot fork theme "${from}" into itself.`,
225
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
407
226
  undefined,
408
- ERROR_CODES.ERR_INVALID_ARGUMENT,
227
+ ERROR_CODES.ERR_FILE_EXISTS,
409
228
  );
410
229
  }
411
- baseTheme = resolveBaseTheme(from, packageDir, owner, root);
412
230
  }
413
231
 
414
232
  /** @type {import('./add-helpers.mjs').WritePlan[]} */
415
- let plans;
416
-
417
- if (baseTheme) {
418
- // Fork: copy the base theme's files, renamed and rewritten.
419
- plans = forkThemePlans(baseTheme, identity, themeDir);
420
- // Check that no target file already exists.
421
- for (const plan of plans) {
422
- if (fs.existsSync(plan.path)) {
423
- throw new AstryxError(
424
- `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, plan.path))}.`,
425
- undefined,
426
- ERROR_CODES.ERR_FILE_EXISTS,
427
- );
428
- }
429
- }
430
- } else {
431
- // Blank scaffold.
432
- const sourceFile = assertWithin(identity.entry, themeDir, {
433
- label: 'theme source file',
434
- });
435
- const descriptorFile = assertWithin(identity.descriptor, themeDir, {
436
- label: 'theme descriptor file',
437
- });
438
- for (const file of [sourceFile, descriptorFile]) {
439
- if (fs.existsSync(file)) {
440
- throw new AstryxError(
441
- `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
442
- undefined,
443
- ERROR_CODES.ERR_FILE_EXISTS,
444
- );
445
- }
446
- }
447
- plans = [
448
- {path: sourceFile, contents: themeSource(identity), createOnly: true},
449
- {
450
- path: descriptorFile,
451
- contents: themeDescriptor(identity),
452
- createOnly: true,
453
- },
454
- ];
455
- }
456
-
233
+ const plans = [
234
+ {path: sourceFile, contents: themeSource(identity), createOnly: true},
235
+ {
236
+ path: descriptorFile,
237
+ contents: themeDescriptor(identity),
238
+ createOnly: true,
239
+ },
240
+ ];
457
241
  let packageUpdate = packageJsonUpdate(
458
242
  packageFile,
459
243
  rootPath,
@@ -525,8 +309,7 @@ export async function integrationAddTheme(name, options = {}) {
525
309
  writtenFiles.push(manifestPath);
526
310
  }
527
311
 
528
- /** @type {import('./integration-authoring.type.mjs').IntegrationAddResponse} */
529
- const response = {
312
+ return {
530
313
  type: 'integration.add',
531
314
  data: {
532
315
  kind: 'theme',
@@ -538,8 +321,4 @@ export async function integrationAddTheme(name, options = {}) {
538
321
  dryRun,
539
322
  },
540
323
  };
541
- if (from != null) {
542
- response.data.from = from;
543
- }
544
- return response;
545
324
  }