@astryxdesign/cli 0.6.5 → 0.6.6

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 (217) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +16 -15
  3. package/api/build/_adapter.d.mts +50 -2
  4. package/api/build/_adapter.mjs +98 -10
  5. package/api/build/build.doc.mjs +2 -2
  6. package/api/build/build.test.mjs +111 -2
  7. package/api/build/kit/kit.mjs +98 -22
  8. package/api/build/kit/rank.d.mts +32 -8
  9. package/api/build/kit/rank.mjs +291 -97
  10. package/api/build/kit/rank.test.mjs +231 -48
  11. package/api/build/kit/weights.d.mts +82 -0
  12. package/api/build/kit/weights.json +1 -0
  13. package/api/build/kit/weights.mjs +305 -0
  14. package/api/build/kit/weights.test.mjs +190 -0
  15. package/api/docs/docs.d.mts +6 -0
  16. package/api/docs/docs.depth.test.mjs +132 -0
  17. package/api/docs/docs.doc.mjs +31 -2
  18. package/api/docs/docs.mjs +44 -1
  19. package/api/docs/docs.test.mjs +279 -0
  20. package/api/docs/docs.type.d.mts +38 -1
  21. package/api/docs/docs.type.mjs +18 -1
  22. package/api/docs/integration-tree.test.mjs +572 -0
  23. package/api/docs/integrationDocs.test.mjs +336 -0
  24. package/api/docs/node/node.d.mts +28 -3
  25. package/api/docs/node/node.mjs +146 -23
  26. package/api/error.d.mts +22 -0
  27. package/api/error.mjs +42 -0
  28. package/api/gap-report/gap-report.d.mts +3 -1
  29. package/api/gap-report/gap-report.mjs +12 -2
  30. package/api/gap-report/gap-report.test.mjs +106 -0
  31. package/api/hook/list/list.d.mts +1 -1
  32. package/api/integration/add-contribution.d.mts +2 -1
  33. package/api/integration/add-contribution.mjs +7 -3
  34. package/api/integration/add-contribution.test.mjs +3 -3
  35. package/api/integration/add-theme.mjs +338 -26
  36. package/api/integration/add-theme.test.mjs +314 -1
  37. package/api/integration/authoring-checks.mjs +10 -7
  38. package/api/integration/authoring-checks.type.d.mts +8 -0
  39. package/api/integration/authoring-checks.type.mjs +7 -3
  40. package/api/integration/integration-authoring.type.d.mts +4 -1
  41. package/api/integration/integration-authoring.type.mjs +6 -1
  42. package/api/integration/integrationAdd.doc.mjs +6 -0
  43. package/api/integration/integrationAddTheme.doc.mjs +10 -0
  44. package/api/integration/integrationComponentConflicts.doc.mjs +1 -1
  45. package/api/integration/integrationDocConflicts.doc.mjs +1 -1
  46. package/api/integration/integrationTemplateConflicts.doc.mjs +1 -1
  47. package/api/integration/pack-check.mjs +12 -3
  48. package/api/integration/pack-check.test.mjs +52 -3
  49. package/api/integration/validate-integration.d.mts +4 -2
  50. package/api/integration/validate-integration.mjs +7 -2
  51. package/api/integration/validate-integration.test.mjs +55 -0
  52. package/api/integration/validate-integration.type.d.mts +5 -0
  53. package/api/integration/validate-integration.type.mjs +5 -1
  54. package/api/integration/validateIntegration.doc.mjs +1 -1
  55. package/api/layout/expand/expand.mjs +12 -7
  56. package/api/layout/expand/expand.receipt.test.mjs +74 -0
  57. package/api/layout/layout.type.d.mts +1 -0
  58. package/api/layout/layout.type.mjs +1 -0
  59. package/api/layout/layoutExpand.doc.mjs +1 -1
  60. package/api/search/search.d.mts +36 -5
  61. package/api/search/search.doc.mjs +4 -4
  62. package/api/search/search.mjs +194 -54
  63. package/api/search/search.test.mjs +825 -0
  64. package/api/search/search.type.d.mts +5 -5
  65. package/api/search/search.type.mjs +5 -5
  66. package/api/swizzle/copy/copy.mjs +66 -3
  67. package/api/swizzle/swizzle.doc.mjs +4 -0
  68. package/api/template/copy/copy.mjs +14 -8
  69. package/api/template/copy/copy.receipt.test.mjs +77 -0
  70. package/api/template/show/show.mjs +15 -4
  71. package/api/template/show/show.test.mjs +76 -0
  72. package/api/template/template-integration.test.mjs +14 -0
  73. package/api/template/template.d.mts +1 -1
  74. package/api/template/template.doc.mjs +6 -2
  75. package/api/template/template.mjs +1 -0
  76. package/api/template/template.type.d.mts +2 -0
  77. package/api/template/template.type.mjs +2 -0
  78. package/api/theme/build/build.d.mts +24 -0
  79. package/api/theme/build/build.icon-lineage.test.mjs +117 -0
  80. package/api/theme/build/build.icon-preservation.test.mjs +639 -0
  81. package/api/theme/build/build.mjs +381 -77
  82. package/api/theme/build/build.project-core.test.mjs +165 -0
  83. package/api/theme/build/build.test.mjs +190 -1
  84. package/api/theme/build/icon-imports.d.mts +47 -0
  85. package/api/theme/build/icon-imports.mjs +691 -0
  86. package/api/theme/themeBuild.doc.d.mts +4 -1
  87. package/api/theme/themeBuild.doc.mjs +14 -3
  88. package/api/upgrade/run/run.mjs +20 -3
  89. package/api/upgrade/run/run.test.mjs +45 -1
  90. package/api/upgrade/upgrade.doc.mjs +1 -1
  91. package/api/upgrade/upgrade.type.d.mts +1 -0
  92. package/api/upgrade/upgrade.type.mjs +1 -0
  93. package/assets/docs/icons.doc.mjs +1 -0
  94. package/assets/docs/theme.doc.mjs +3 -2
  95. package/assets/docs/tokens.doc.mjs +3 -3
  96. package/assets/docs/tree/add-a-theme.doc.mjs +4 -0
  97. package/assets/docs/tree/add-a-topic.doc.mjs +1 -1
  98. package/assets/docs/tree/check-your-docs.doc.mjs +2 -2
  99. package/assets/docs/tree/checks.doc.mjs +1 -1
  100. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +1 -1
  101. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  102. package/assets/docs/tree/sections-and-placement.doc.mjs +1 -1
  103. package/assets/docs/tree/template-doc-overview.doc.mjs +13 -1
  104. package/assets/docs/tree/troubleshooting.doc.mjs +9 -5
  105. package/assets/docs/tree/versioning.doc.mjs +7 -6
  106. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.doc.mjs +15 -0
  107. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupShowcase.tsx +38 -0
  108. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.doc.mjs +20 -0
  109. package/assets/templates/blocks/components/DropdownMenuGroup/DropdownMenuGroupWithSelectable.tsx +48 -0
  110. package/assets/templates/pages/ai-chat/template.doc.mjs +16 -1
  111. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +9 -1
  112. package/assets/templates/pages/blank/template.doc.mjs +3 -1
  113. package/assets/templates/pages/canvas-editor/template.doc.mjs +9 -1
  114. package/assets/templates/pages/centered-hero/template.doc.mjs +3 -1
  115. package/assets/templates/pages/checkout-wizard/template.doc.mjs +1 -0
  116. package/assets/templates/pages/classic-gallery/template.doc.mjs +3 -1
  117. package/assets/templates/pages/contact-form/template.doc.mjs +16 -1
  118. package/assets/templates/pages/dashboard/template.doc.mjs +15 -1
  119. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +23 -1
  120. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +10 -1
  121. package/assets/templates/pages/dashboard-comparison/template.doc.mjs +9 -1
  122. package/assets/templates/pages/dashboard-composition/template.doc.mjs +10 -1
  123. package/assets/templates/pages/dashboard-progress/template.doc.mjs +17 -1
  124. package/assets/templates/pages/dashboard-scorecard/template.doc.mjs +2 -1
  125. package/assets/templates/pages/detail-page/template.doc.mjs +8 -0
  126. package/assets/templates/pages/documentation/template.doc.mjs +10 -1
  127. package/assets/templates/pages/documentation-design/template.doc.mjs +10 -1
  128. package/assets/templates/pages/documentation-technical/template.doc.mjs +10 -1
  129. package/assets/templates/pages/editor/template.doc.mjs +9 -1
  130. package/assets/templates/pages/file-explorer/template.doc.mjs +3 -1
  131. package/assets/templates/pages/form-two-column/template.doc.mjs +17 -1
  132. package/assets/templates/pages/form-wizard/template.doc.mjs +14 -1
  133. package/assets/templates/pages/form-wizard-dialog/template.doc.mjs +1 -0
  134. package/assets/templates/pages/gallery-hero/template.doc.mjs +10 -1
  135. package/assets/templates/pages/ide/template.doc.mjs +9 -1
  136. package/assets/templates/pages/incident-console/template.doc.mjs +10 -1
  137. package/assets/templates/pages/kanban-board/template.doc.mjs +11 -1
  138. package/assets/templates/pages/library/template.doc.mjs +15 -1
  139. package/assets/templates/pages/login/template.doc.mjs +10 -1
  140. package/assets/templates/pages/login-card/template.doc.mjs +11 -1
  141. package/assets/templates/pages/login-split/template.doc.mjs +10 -1
  142. package/assets/templates/pages/login-sso/template.doc.mjs +10 -1
  143. package/assets/templates/pages/messaging-shell/template.doc.mjs +11 -1
  144. package/assets/templates/pages/mixed-gallery/template.doc.mjs +10 -1
  145. package/assets/templates/pages/payment-form/template.doc.mjs +3 -1
  146. package/assets/templates/pages/product-detail/template.doc.mjs +9 -1
  147. package/assets/templates/pages/product-gallery/template.doc.mjs +10 -1
  148. package/assets/templates/pages/settings/template.doc.mjs +3 -1
  149. package/assets/templates/pages/settings-dialog/template.doc.mjs +9 -1
  150. package/assets/templates/pages/settings-sidebar/template.doc.mjs +9 -1
  151. package/assets/templates/pages/shell-nav/template.doc.mjs +10 -1
  152. package/assets/templates/pages/shell-side-nav/template.doc.mjs +14 -1
  153. package/assets/templates/pages/shell-top-nav/template.doc.mjs +11 -1
  154. package/assets/templates/pages/side-gallery/template.doc.mjs +3 -1
  155. package/assets/templates/pages/table/template.doc.mjs +11 -1
  156. package/assets/templates/pages/table-filter/template.doc.mjs +21 -1
  157. package/assets/templates/pages/table-grouped/template.doc.mjs +15 -1
  158. package/assets/templates/pages/table-inbox/template.doc.mjs +18 -6
  159. package/assets/templates/pages/table-page/template.doc.mjs +20 -1
  160. package/assets/templates/pages/table-tree/template.doc.mjs +14 -1
  161. package/assets/templates/pages/theme-showcase/template.doc.mjs +10 -1
  162. package/assets/templates/pages/work-item-detail/template.doc.mjs +10 -0
  163. package/assets/templates/themes/butter/icons.tsx +2 -0
  164. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  165. package/assets/templates/themes/gothic/icons.tsx +2 -0
  166. package/assets/templates/themes/matcha/icons.tsx +2 -0
  167. package/assets/templates/themes/neutral/icons.tsx +2 -0
  168. package/assets/templates/themes/stone/icons.tsx +2 -0
  169. package/assets/templates/themes/y2k/icons.tsx +2 -0
  170. package/authoring/doctypes/template/parse.d.mts +2 -0
  171. package/authoring/doctypes/template/parse.mjs +1 -0
  172. package/authoring/doctypes/template/parse.test.mjs +21 -0
  173. package/authoring/doctypes/template/template.doc.mjs +6 -0
  174. package/authoring/doctypes/template/type.ts +10 -0
  175. package/clients/cli/commands/build-theme.mjs +8 -2
  176. package/clients/cli/commands/discover.mjs +29 -1
  177. package/clients/cli/commands/discover.no-source.test.mjs +75 -0
  178. package/clients/cli/commands/docs.depth.test.mjs +219 -0
  179. package/clients/cli/commands/docs.doc.mjs +15 -2
  180. package/clients/cli/commands/docs.mjs +222 -5
  181. package/clients/cli/commands/docs.test.mjs +383 -0
  182. package/clients/cli/commands/doctor.mjs +4 -4
  183. package/clients/cli/commands/gap-report.mjs +12 -0
  184. package/clients/cli/commands/gap-report.test.mjs +63 -0
  185. package/clients/cli/commands/integration-add.doc.mjs +10 -0
  186. package/clients/cli/commands/integration-authoring.test.mjs +12 -2
  187. package/clients/cli/commands/integration.mjs +3 -1
  188. package/clients/cli/commands/layout-expand.doc.mjs +3 -1
  189. package/clients/cli/commands/layout.expand-receipt.test.mjs +94 -0
  190. package/clients/cli/commands/layout.mjs +16 -0
  191. package/clients/cli/commands/search.doc.mjs +5 -4
  192. package/clients/cli/commands/search.mjs +30 -6
  193. package/clients/cli/commands/search.test.mjs +60 -16
  194. package/clients/cli/commands/template.copy-receipt.test.mjs +60 -0
  195. package/clients/cli/commands/template.mjs +19 -5
  196. package/clients/cli/commands/template.show-media.test.mjs +62 -0
  197. package/clients/cli/commands/theme-list.behavior.test.mjs +41 -0
  198. package/clients/cli/commands/upgrade.ascii-output.test.mjs +14 -0
  199. package/clients/cli/commands/write-failure.test.mjs +175 -0
  200. package/clients/cli/lib/manifest.mjs +44 -165
  201. package/clients/cli/lib/manifest.test.mjs +98 -7
  202. package/foundation/agent-docs/agent-docs.mjs +2 -1
  203. package/foundation/agent-docs/agent-docs.test.mjs +1168 -0
  204. package/foundation/discovery/template-adapter.d.mts +14 -0
  205. package/foundation/discovery/template-adapter.fixture-refs.test.mjs +37 -1
  206. package/foundation/discovery/template-adapter.mjs +21 -1
  207. package/foundation/discovery/theme-discovery.d.mts +6 -0
  208. package/foundation/discovery/theme-discovery.mjs +9 -0
  209. package/foundation/doc-compiler/doc-loads.test.mjs +3 -3
  210. package/foundation/doc-compiler/inputs.test.mjs +0 -1
  211. package/foundation/doc-compiler/tree.test.mjs +649 -0
  212. package/foundation/integrations/cli-requirement.d.mts +57 -13
  213. package/foundation/integrations/cli-requirement.mjs +84 -22
  214. package/foundation/integrations/cli-requirement.test.mjs +135 -8
  215. package/foundation/response/response-types.doc.d.mts +5 -5
  216. package/foundation/response/response-types.doc.mjs +13 -13
  217. package/package.json +1 -1
@@ -189,7 +189,9 @@ async function selectTarget(project, component, packageName) {
189
189
  /**
190
190
  * Collect the effective handler set in delivery order: project config first,
191
191
  * then integrations in config order. Valid handlers dedupe by handle identity;
192
- * malformed integration exports retain their position as failed deliveries.
192
+ * malformed integration exports and integrations that failed to load retain
193
+ * their position as failed deliveries. An unloadable integration may export a
194
+ * handler, so it never counts as an empty set that enables the fallback.
193
195
  *
194
196
  * @param {Project} project
195
197
  * @returns {HandlerEntry[]}
@@ -214,7 +216,15 @@ export function collectGapReportHandlers(project) {
214
216
  }
215
217
 
216
218
  for (const integration of project.loadedIntegrations) {
217
- if (integration.__loadError) continue;
219
+ if (integration.__loadError) {
220
+ entries.push({
221
+ kind: 'malformed',
222
+ handlerType: 'integration',
223
+ handlerName: integration.name,
224
+ error: `Integration failed to load, so it could not receive this report: ${integration.__loadError}. Fix the package or remove it from integrations in astryx.config, then rerun.`,
225
+ });
226
+ continue;
227
+ }
218
228
  if (integration.__gapReportError) {
219
229
  entries.push({
220
230
  kind: 'malformed',
@@ -105,6 +105,45 @@ function addIntegration({
105
105
  return {dir};
106
106
  }
107
107
 
108
+ /**
109
+ * Add an integration whose module throws on import, so it never loads.
110
+ * @param {string} name
111
+ */
112
+ function addBrokenIntegration(name) {
113
+ const dir = packageDir(name);
114
+ fs.mkdirSync(dir, {recursive: true});
115
+ fs.writeFileSync(
116
+ path.join(dir, 'package.json'),
117
+ JSON.stringify({name, version: '1.0.0', type: 'module'}),
118
+ );
119
+ fs.writeFileSync(
120
+ path.join(dir, 'astryx.integration.mjs'),
121
+ "throw new Error('intentional integration load failure');\n",
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Put a fake `gh` first on PATH that records its arguments if it is called.
127
+ * @returns {string} the file the fake writes when invoked
128
+ */
129
+ function stubGh() {
130
+ const binDir = path.join(projectDir, 'bin');
131
+ const argsFile = path.join(projectDir, 'gh-args.json');
132
+ fs.mkdirSync(binDir, {recursive: true});
133
+ fs.writeFileSync(
134
+ path.join(binDir, 'gh'),
135
+ `#!/usr/bin/env node
136
+ import fs from 'node:fs';
137
+ fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));
138
+ console.log('https://github.com/acme/core/issues/42');
139
+ `,
140
+ {mode: 0o755},
141
+ );
142
+ fs.chmodSync(path.join(binDir, 'gh'), 0o755);
143
+ vi.stubEnv('PATH', `${binDir}${path.delimiter}${process.env.PATH ?? ''}`);
144
+ return argsFile;
145
+ }
146
+
108
147
  const reportOptions = {
109
148
  category: 'missing_variant',
110
149
  reason: 'Need a compact size',
@@ -681,6 +720,73 @@ describe('gapReport handler isolation', () => {
681
720
  });
682
721
  });
683
722
 
723
+ it('an integration that fails to load is a failed delivery, not a missing handler', async () => {
724
+ addBrokenIntegration('@test/broken');
725
+ configure(['@test/broken'], {
726
+ issuesUrl: 'https://github.com/acme/core/issues/new',
727
+ });
728
+
729
+ const result = await gapReport('General', {
730
+ ...reportOptions,
731
+ cwd: projectDir,
732
+ });
733
+
734
+ expect(result.data.status).toBe('failed');
735
+ expect(result.data.deliveries).toEqual([
736
+ {
737
+ handlerType: 'integration',
738
+ handler: '@test/broken',
739
+ audience: null,
740
+ status: 'failed',
741
+ url: null,
742
+ message: expect.stringContaining(
743
+ 'intentional integration load failure',
744
+ ),
745
+ },
746
+ ]);
747
+ });
748
+
749
+ it('an integration that fails to load keeps the public fallback off, even with consent', async () => {
750
+ addBrokenIntegration('@test/broken');
751
+ configure(['@test/broken'], {
752
+ issuesUrl: 'https://github.com/acme/core/issues/new',
753
+ });
754
+ const argsFile = stubGh();
755
+
756
+ const result = await gapReport('General', {
757
+ ...reportOptions,
758
+ confirmPublic: true,
759
+ cwd: projectDir,
760
+ });
761
+
762
+ expect(result.data.status).toBe('failed');
763
+ expect(result.data.deliveries.map(d => d.handlerType)).toEqual([
764
+ 'integration',
765
+ ]);
766
+ expect(fs.existsSync(argsFile)).toBe(false);
767
+ });
768
+
769
+ it('an integration that fails to load keeps its place beside working handlers', async () => {
770
+ addBrokenIntegration('@test/broken');
771
+ addIntegration({
772
+ name: '@test/valid',
773
+ audience: 'internal',
774
+ handleBody: "return {status: 'filed', message: 'ok'};",
775
+ });
776
+ configure(['@test/broken', '@test/valid']);
777
+
778
+ const result = await gapReport('General', {
779
+ ...reportOptions,
780
+ cwd: projectDir,
781
+ });
782
+
783
+ expect(result.data.status).toBe('partial');
784
+ expect(result.data.deliveries.map(d => [d.handler, d.status])).toEqual([
785
+ ['@test/broken', 'failed'],
786
+ ['@test/valid', 'filed'],
787
+ ]);
788
+ });
789
+
684
790
  it('invalid handler receipt is recorded as failed delivery', async () => {
685
791
  addIntegration({
686
792
  name: '@test/bad-receipt',
@@ -13,7 +13,7 @@
13
13
  export function list({ cwd, category, detail, zh, lang, }?: {
14
14
  cwd?: string | undefined;
15
15
  category?: string | undefined;
16
- detail?: "compact" | "full" | "names" | "brief" | undefined;
16
+ detail?: "compact" | "full" | "brief" | "names" | undefined;
17
17
  zh?: boolean | undefined;
18
18
  lang?: string | null | undefined;
19
19
  }): Promise<import("../hook.type.mjs").HookListResponse>;
@@ -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}} [options]
34
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: 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,4 +42,5 @@ export function integrationAdd(kind: "component" | "doc" | "template" | "codemod
42
42
  replaces?: string;
43
43
  extends?: string;
44
44
  parent?: string;
45
+ from?: string;
45
46
  }): 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']),
1214
+ theme: new Set(['cwd', 'dryRun', 'from']),
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}} [options]
1241
+ * @param {{cwd?: string, dryRun?: boolean, templateType?: 'page'|'block', to?: string, replaces?: string, extends?: string, parent?: string, from?: string}} [options]
1242
1242
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
1243
1243
  */
1244
1244
  export async function integrationAdd(kind, name, options = {}) {
@@ -1270,6 +1270,10 @@ 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, options);
1273
+ return integrationAddTheme(name, {
1274
+ cwd: options.cwd,
1275
+ dryRun: options.dryRun,
1276
+ from: options.from,
1277
+ });
1274
1278
  }
1275
1279
  }
@@ -12,7 +12,7 @@ import {
12
12
  integrationAddTemplate,
13
13
  } from './add-contribution.mjs';
14
14
  import {validateLocalIntegration} from './validate-integration.mjs';
15
- import {DOCS_TREE_CLI} from '../../foundation/integrations/cli-requirement.mjs';
15
+ import {NAMESPACE_DOCS_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': `>=${DOCS_TREE_CLI}`});
358
+ expect(pkg.peerDependencies).toEqual({'@astryxdesign/cli': '>=0.6.4'});
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': `>=${DOCS_TREE_CLI}`,
432
+ '@astryxdesign/cli': `>=${NAMESPACE_DOCS_CLI}`,
433
433
  });
434
434
  write('^9.1.0');
435
435
  await integrationAdd('doc', 'upgrading', {cwd: tmpDir, parent: 'acme'});
@@ -4,18 +4,27 @@
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.
7
10
  */
8
11
 
9
12
  import * as fs from 'node:fs';
13
+ import {isBuiltin} from 'node:module';
10
14
  import * as path from 'node:path';
11
15
  import {AstryxError} from '../error.mjs';
16
+ import {CLI_ROOT} from '../../foundation/fs/paths.mjs';
12
17
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
13
18
  import {
14
19
  assertWithin,
15
20
  PathSafetyError,
16
21
  sanitizeName,
17
22
  } from '../../foundation/fs/path-safety.mjs';
18
- import {discoverThemeDirectory} from '../../foundation/discovery/theme-discovery.mjs';
23
+ import {
24
+ discoverBundledThemes,
25
+ discoverThemeDirectory,
26
+ themeFileImports,
27
+ } from '../../foundation/discovery/theme-discovery.mjs';
19
28
  import {
20
29
  findLocalIntegrationManifestOrNull,
21
30
  IntegrationRootConflictError,
@@ -25,9 +34,11 @@ import {loadManifestObject} from '../../foundation/integrations/integrations.mjs
25
34
  import {themeDescriptorSource} from '../../foundation/integrations/theme-descriptor.mjs';
26
35
  import {assertContributionVisible} from '../../foundation/integrations/contribution-inventory.mjs';
27
36
  import {
37
+ THEMES_CLI,
28
38
  themesCliProblem,
29
- withDocsTreeCli,
39
+ withCliPeer,
30
40
  } from '../../foundation/integrations/cli-requirement.mjs';
41
+ import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';
31
42
  import {
32
43
  applyWrites,
33
44
  findPackageDir,
@@ -69,6 +80,7 @@ function themeIdentity(slug) {
69
80
  .join(' ');
70
81
  return {
71
82
  slug,
83
+ identifier,
72
84
  displayName,
73
85
  exportName: `${identifier}Theme`,
74
86
  entry: `${identifier}Theme.ts`,
@@ -92,6 +104,253 @@ function themeDescriptor(identity) {
92
104
  });
93
105
  }
94
106
 
107
+ // ── --from: resolve and fork a base theme ───────────────────────────
108
+
109
+ /**
110
+ * Resolve a theme slug to its discovered record, searching the bundled themes
111
+ * and the package's own themes root (when it has one).
112
+ * @param {string} slug
113
+ * @param {string} packageDir
114
+ * @param {string} owner
115
+ * @param {string | undefined} themesRoot resolved absolute themes root, if any
116
+ * @returns {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme}
117
+ */
118
+ function resolveBaseTheme(slug, packageDir, owner, themesRoot) {
119
+ const normalized = slug.toLowerCase();
120
+
121
+ /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} */
122
+ let candidates = [];
123
+ try {
124
+ candidates = discoverBundledThemes();
125
+ } catch {
126
+ // Bundled themes unavailable — not fatal, package themes may suffice.
127
+ }
128
+
129
+ // Also check the package's own themes root.
130
+ if (themesRoot && fs.existsSync(themesRoot)) {
131
+ try {
132
+ candidates = [...candidates, ...discoverThemeDirectory(themesRoot, owner)];
133
+ } catch {
134
+ // A broken local root is not the caller's problem here.
135
+ }
136
+ }
137
+
138
+ const match = candidates.find(t => t.slug.toLowerCase() === normalized);
139
+ if (!match) {
140
+ throw new AstryxError(
141
+ `Unknown base theme "${slug}". Available themes: ${candidates.map(t => t.slug).join(', ') || '(none)'}.`,
142
+ candidates.map(t => ({
143
+ name: t.slug,
144
+ reason: t.bundled ? 'bundled theme' : `provided by ${t.package}`,
145
+ })),
146
+ ERROR_CODES.ERR_UNKNOWN_THEME,
147
+ );
148
+ }
149
+ return match;
150
+ }
151
+
152
+ /**
153
+ * Rename a file from the base theme's namespace to the new theme's namespace.
154
+ * Files whose name starts with the base identifier get the new identifier;
155
+ * others keep their name as-is.
156
+ * @param {string} file POSIX relative path inside the theme directory
157
+ * @param {string} baseIdentifier
158
+ * @param {string} newIdentifier
159
+ * @returns {string}
160
+ */
161
+ function renameThemeFile(file, baseIdentifier, newIdentifier) {
162
+ const basename = path.posix.basename(file);
163
+ const dir = path.posix.dirname(file);
164
+ if (!basename.startsWith(baseIdentifier)) return file;
165
+ const renamed = newIdentifier + basename.slice(baseIdentifier.length);
166
+ return dir === '.' ? renamed : `${dir}/${renamed}`;
167
+ }
168
+
169
+ /**
170
+ * Rewrite a source file's contents from the base theme's names to the new
171
+ * theme's names. This replaces:
172
+ * 1. Identifier prefixes (camelCase variables, import paths): baseIdentifier
173
+ * followed by an uppercase letter.
174
+ * 2. The theme slug in string literals: 'baseSlug' → 'newSlug' and
175
+ * 'astryx-baseSlug' → 'astryx-newSlug'.
176
+ * 3. CSS custom properties scoped to the theme: --astryx-theme-baseSlug-.
177
+ * @param {string} source
178
+ * @param {string} baseSlug
179
+ * @param {string} baseIdentifier
180
+ * @param {string} newSlug
181
+ * @param {string} newIdentifier
182
+ * @returns {string}
183
+ */
184
+ function rewriteThemeSource(
185
+ source,
186
+ baseSlug,
187
+ baseIdentifier,
188
+ newSlug,
189
+ newIdentifier,
190
+ ) {
191
+ let result = source;
192
+ // 1. Identifier prefixes: neutralPalettes → oceanPalettes, neutralTheme → oceanTheme
193
+ const identRe = new RegExp(`${escapeRegExp(baseIdentifier)}(?=[A-Z])`, 'gu');
194
+ result = result.replace(identRe, newIdentifier);
195
+ // 2. String-literal theme names
196
+ result = result.replace(
197
+ new RegExp(`'astryx-${escapeRegExp(baseSlug)}'`, 'gu'),
198
+ `'astryx-${newSlug}'`,
199
+ );
200
+ result = result.replace(
201
+ new RegExp(`'${escapeRegExp(baseSlug)}'`, 'gu'),
202
+ `'${newSlug}'`,
203
+ );
204
+ // 3. CSS custom properties scoped to the base theme
205
+ result = result.replace(
206
+ new RegExp(
207
+ `--astryx-theme-${escapeRegExp(baseSlug)}-`,
208
+ 'gu',
209
+ ),
210
+ `--astryx-theme-${newSlug}-`,
211
+ );
212
+ return result;
213
+ }
214
+
215
+ /** @param {string} s */
216
+ function escapeRegExp(s) {
217
+ return s.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
218
+ }
219
+
220
+ /** What every app that uses Astryx already has: Core, and React through Core's peers. */
221
+ const APP_PROVIDED = new Set(['@astryxdesign/core', 'react', 'react-dom']);
222
+
223
+ /**
224
+ * The npm package a module specifier names, or null for a relative path, an
225
+ * absolute path, or a Node built-in.
226
+ * @param {string} specifier
227
+ * @returns {string | null}
228
+ */
229
+ function packageOfSpecifier(specifier) {
230
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
231
+ if (isBuiltin(specifier)) return null;
232
+ const parts = specifier.split('/');
233
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
234
+ }
235
+
236
+ /**
237
+ * The npm packages a fork's copied files import that its package does not
238
+ * declare yet, each at the range the bundled themes are built against (the
239
+ * CLI's own package.json). The fork depends on them at runtime, so an app that
240
+ * installs the package needs them too. Derived from the imports, not copied
241
+ * from a base's whole dependency list. Core and React are left out, since every
242
+ * Astryx app has them; so is a fork of the package's own theme, whose imports
243
+ * the package already resolves.
244
+ *
245
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
246
+ * @param {Record<string, any>} pkg - The package's package.json.
247
+ * @returns {Record<string, string>} package name to range
248
+ */
249
+ function forkDependencies(base, pkg) {
250
+ if (!base.bundled) return {};
251
+ /** @type {Record<string, any>} */
252
+ let cli;
253
+ try {
254
+ cli = JSON.parse(
255
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),
256
+ );
257
+ } catch {
258
+ return {};
259
+ }
260
+ /** @type {Record<string, string>} */
261
+ const ranges = {
262
+ ...cli.devDependencies,
263
+ ...cli.peerDependencies,
264
+ ...cli.dependencies,
265
+ };
266
+ const declared = {
267
+ ...pkg.devDependencies,
268
+ ...pkg.peerDependencies,
269
+ ...pkg.dependencies,
270
+ };
271
+ /** @type {Record<string, string>} */
272
+ const needed = {};
273
+ for (const file of base.files) {
274
+ const code = /\.(?:[cm]?[jt]sx?)$/u.test(file);
275
+ if (!code || file.endsWith('.doc.mjs')) continue;
276
+ let specifiers;
277
+ try {
278
+ specifiers = themeFileImports(path.join(base.sourceDir, file));
279
+ } catch {
280
+ continue; // discovery already refuses a theme whose source does not parse
281
+ }
282
+ for (const specifier of specifiers) {
283
+ const name = packageOfSpecifier(specifier);
284
+ if (name == null || APP_PROVIDED.has(name) || name in declared) continue;
285
+ if (typeof ranges[name] === 'string') needed[name] = ranges[name];
286
+ }
287
+ }
288
+ return needed;
289
+ }
290
+
291
+ /**
292
+ * Build the write plans for a forked theme.
293
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} base
294
+ * @param {ReturnType<typeof themeIdentity>} identity new theme identity
295
+ * @param {string} themeDir absolute target directory
296
+ * @returns {import('./add-helpers.mjs').WritePlan[]}
297
+ */
298
+ function forkThemePlans(base, identity, themeDir) {
299
+ const baseIdentity = themeIdentity(base.slug);
300
+ /** @type {import('./add-helpers.mjs').WritePlan[]} */
301
+ const plans = [];
302
+
303
+ // Copy every file the base theme ships (entry first, then the rest), except
304
+ // the descriptor — we write a fresh one.
305
+ const filesToCopy = base.files.filter(
306
+ file => path.posix.basename(file) !== `${baseIdentity.exportName}.doc.mjs`,
307
+ );
308
+
309
+ for (const file of filesToCopy) {
310
+ const srcPath = path.join(base.sourceDir, file);
311
+ const newFileName = renameThemeFile(
312
+ file,
313
+ baseIdentity.identifier,
314
+ identity.identifier,
315
+ );
316
+ const destPath = assertWithin(newFileName, themeDir, {
317
+ label: `forked theme file "${newFileName}"`,
318
+ });
319
+
320
+ // Read source bytes; for text, strip copyright and rewrite identifiers.
321
+ const bytes = fs.readFileSync(srcPath);
322
+ const text = bytes.toString('utf-8');
323
+ const isText = Buffer.from(text, 'utf-8').equals(bytes);
324
+
325
+ /** @type {string | Buffer} */
326
+ let contents;
327
+ if (isText) {
328
+ contents = rewriteThemeSource(
329
+ stripCopyrightHeader(text),
330
+ base.slug,
331
+ baseIdentity.identifier,
332
+ identity.slug,
333
+ identity.identifier,
334
+ );
335
+ } else {
336
+ contents = bytes;
337
+ }
338
+ plans.push({path: destPath, contents, createOnly: true});
339
+ }
340
+
341
+ // Write a fresh descriptor — the fork is a new theme, not a derivative.
342
+ const descriptorPath = assertWithin(identity.descriptor, themeDir, {
343
+ label: 'theme descriptor file',
344
+ });
345
+ plans.push({
346
+ path: descriptorPath,
347
+ contents: themeDescriptor(identity),
348
+ createOnly: true,
349
+ });
350
+
351
+ return plans;
352
+ }
353
+
95
354
  /**
96
355
  * Read bytes back through the same discovery seam Project uses. A write is not
97
356
  * successful until the requested slug resolves.
@@ -129,7 +388,7 @@ async function verifyThemeContribution(packageDir, manifestFile, owner, slug) {
129
388
  * @returns {Promise<import('./integration-authoring.type.mjs').IntegrationAddResponse>}
130
389
  */
131
390
  export async function integrationAddTheme(name, options = {}) {
132
- const {cwd = process.cwd(), dryRun = false} = options;
391
+ const {cwd = process.cwd(), dryRun = false, from} = options;
133
392
  const packageDir = findPackageDir(cwd);
134
393
  const packageFile = path.join(packageDir, 'package.json');
135
394
  let pkg;
@@ -211,32 +470,64 @@ export async function integrationAddTheme(name, options = {}) {
211
470
  const themeDir = assertWithin(identity.slug, root, {
212
471
  label: 'theme directory',
213
472
  });
214
- const sourceFile = assertWithin(identity.entry, themeDir, {
215
- label: 'theme source file',
216
- });
217
- const descriptorFile = assertWithin(identity.descriptor, themeDir, {
218
- label: 'theme descriptor file',
219
- });
220
- // An existing folder is filled; only a file this would write is refused.
221
- for (const file of [sourceFile, descriptorFile]) {
222
- if (fs.existsSync(file)) {
473
+
474
+ // Resolve the base theme when --from is given, before writing anything.
475
+ /** @type {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined} */
476
+ let baseTheme;
477
+ if (from != null) {
478
+ if (from === name) {
223
479
  throw new AstryxError(
224
- `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
480
+ `Cannot fork theme "${from}" into itself.`,
225
481
  undefined,
226
- ERROR_CODES.ERR_FILE_EXISTS,
482
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
227
483
  );
228
484
  }
485
+ baseTheme = resolveBaseTheme(from, packageDir, owner, root);
229
486
  }
230
487
 
231
488
  /** @type {import('./add-helpers.mjs').WritePlan[]} */
232
- const plans = [
233
- {path: sourceFile, contents: themeSource(identity), createOnly: true},
234
- {
235
- path: descriptorFile,
236
- contents: themeDescriptor(identity),
237
- createOnly: true,
238
- },
239
- ];
489
+ let plans;
490
+
491
+ if (baseTheme) {
492
+ // Fork: copy the base theme's files, renamed and rewritten.
493
+ plans = forkThemePlans(baseTheme, identity, themeDir);
494
+ // Check that no target file already exists.
495
+ for (const plan of plans) {
496
+ if (fs.existsSync(plan.path)) {
497
+ throw new AstryxError(
498
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, plan.path))}.`,
499
+ undefined,
500
+ ERROR_CODES.ERR_FILE_EXISTS,
501
+ );
502
+ }
503
+ }
504
+ } else {
505
+ // Blank scaffold.
506
+ const sourceFile = assertWithin(identity.entry, themeDir, {
507
+ label: 'theme source file',
508
+ });
509
+ const descriptorFile = assertWithin(identity.descriptor, themeDir, {
510
+ label: 'theme descriptor file',
511
+ });
512
+ for (const file of [sourceFile, descriptorFile]) {
513
+ if (fs.existsSync(file)) {
514
+ throw new AstryxError(
515
+ `Refusing to overwrite existing file ${projectPath(path.relative(packageDir, file))}.`,
516
+ undefined,
517
+ ERROR_CODES.ERR_FILE_EXISTS,
518
+ );
519
+ }
520
+ }
521
+ plans = [
522
+ {path: sourceFile, contents: themeSource(identity), createOnly: true},
523
+ {
524
+ path: descriptorFile,
525
+ contents: themeDescriptor(identity),
526
+ createOnly: true,
527
+ },
528
+ ];
529
+ }
530
+
240
531
  let packageUpdate = packageJsonUpdate(
241
532
  packageFile,
242
533
  rootPath,
@@ -250,11 +541,27 @@ export async function integrationAddTheme(name, options = {}) {
250
541
  packageUpdate?.expectedOriginal ?? fs.readFileSync(packageFile);
251
542
  const text = packageUpdate?.contents ?? expectedOriginal.toString('utf-8');
252
543
  const current = JSON.parse(text);
253
- if (themesCliProblem(current) != null) {
544
+ let next =
545
+ themesCliProblem(current) != null
546
+ ? withCliPeer(current, THEMES_CLI)
547
+ : current;
548
+ // A fork runs the base's imports: declare the packages they come from.
549
+ const forked = baseTheme ? forkDependencies(baseTheme, next) : {};
550
+ if (Object.keys(forked).length > 0) {
551
+ const dependencies = {...next.dependencies, ...forked};
552
+ next = {
553
+ ...next,
554
+ dependencies: Object.fromEntries(
555
+ Object.keys(dependencies)
556
+ .sort()
557
+ .map(name => [name, dependencies[name]]),
558
+ ),
559
+ };
560
+ }
561
+ if (next !== current) {
254
562
  packageUpdate = {
255
563
  contents:
256
- JSON.stringify(withDocsTreeCli(current), null, 2) +
257
- (text.endsWith('\n') ? '\n' : ''),
564
+ JSON.stringify(next, null, 2) + (text.endsWith('\n') ? '\n' : ''),
258
565
  expectedOriginal,
259
566
  };
260
567
  }
@@ -308,7 +615,8 @@ export async function integrationAddTheme(name, options = {}) {
308
615
  writtenFiles.push(manifestPath);
309
616
  }
310
617
 
311
- return {
618
+ /** @type {import('./integration-authoring.type.mjs').IntegrationAddResponse} */
619
+ const response = {
312
620
  type: 'integration.add',
313
621
  data: {
314
622
  kind: 'theme',
@@ -320,4 +628,8 @@ export async function integrationAddTheme(name, options = {}) {
320
628
  dryRun,
321
629
  },
322
630
  };
631
+ if (from != null) {
632
+ response.data.from = from;
633
+ }
634
+ return response;
323
635
  }