@astryxdesign/cli 0.7.16 → 0.7.17-canary.gb36275e

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 (239) hide show
  1. package/README.md +13 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +59 -12
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +42 -0
  14. package/api/build/kit/words.mjs +82 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +46 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +531 -192
  34. package/api/render/render.doc.mjs +11 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +47 -0
  46. package/api/theme/build/build.mjs +147 -25
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +48 -0
  50. package/api/theme-edit/_adapter.mjs +675 -42
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1481 -252
  53. package/api/theme-edit/_color.d.mts +9 -0
  54. package/api/theme-edit/_color.mjs +41 -1
  55. package/api/theme-edit/_compiler.mjs +9 -0
  56. package/api/theme-edit/_context.mjs +60 -3
  57. package/api/theme-edit/_css.mjs +21 -1
  58. package/api/theme-edit/_edit.d.mts +22 -0
  59. package/api/theme-edit/_edit.mjs +1196 -88
  60. package/api/theme-edit/_how-commands.d.mts +57 -0
  61. package/api/theme-edit/_how-commands.mjs +536 -1
  62. package/api/theme-edit/_how-question.d.mts +65 -0
  63. package/api/theme-edit/_how-question.mjs +4401 -225
  64. package/api/theme-edit/_how.mjs +104 -4
  65. package/api/theme-edit/_marks.d.mts +31 -5
  66. package/api/theme-edit/_marks.mjs +57 -5
  67. package/api/theme-edit/_normal.d.mts +153 -0
  68. package/api/theme-edit/_normal.mjs +661 -0
  69. package/api/theme-edit/_palette.mjs +10 -4
  70. package/api/theme-edit/_parts.d.mts +8 -0
  71. package/api/theme-edit/_parts.mjs +103 -2
  72. package/api/theme-edit/_preview-app.d.mts +7 -1
  73. package/api/theme-edit/_preview-app.mjs +205 -17
  74. package/api/theme-edit/_preview.d.mts +64 -8
  75. package/api/theme-edit/_preview.mjs +447 -89
  76. package/api/theme-edit/_settings.d.mts +176 -5
  77. package/api/theme-edit/_settings.mjs +1936 -128
  78. package/api/theme-edit/_tables.d.mts +6 -0
  79. package/api/theme-edit/_tables.mjs +32 -1
  80. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  81. package/api/theme-edit/theme-edit.type.mjs +4 -1
  82. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  83. package/assets/codemods/run-codemod.mjs +73 -6
  84. package/assets/codemods/transforms/next/index.mjs +11 -1
  85. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  86. package/assets/docs/author-a-theme.doc.mjs +1 -0
  87. package/assets/docs/theme.doc.dense.mjs +2 -2
  88. package/assets/docs/theme.doc.mjs +1 -1
  89. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  90. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  91. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  92. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  93. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  94. package/assets/docs/use-a-theme.doc.mjs +1 -1
  95. package/assets/docs.generated.json +2 -2
  96. package/assets/self-audit.generated.json +1 -1
  97. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  99. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  100. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  101. package/assets/templates/components.generated.json +1 -1
  102. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  103. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  104. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  105. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  106. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  107. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  108. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  110. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  111. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  112. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  113. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  114. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  115. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  116. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  117. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  118. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  119. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  120. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  121. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  122. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  123. package/assets/templates/pages/ide/page.tsx +24 -2
  124. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  125. package/assets/templates/pages/library/template.doc.mjs +4 -1
  126. package/assets/templates/pages/login/template.doc.mjs +2 -1
  127. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  128. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  129. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  130. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  131. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  132. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  133. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  134. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  135. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  136. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  137. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  138. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  139. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  140. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  141. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  142. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  143. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  144. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  145. package/authoring/debug/parse.d.mts +3 -3
  146. package/authoring/doctypes/_schema.d.mts +3 -3
  147. package/authoring/doctypes/command/command.doc.mjs +1 -1
  148. package/authoring/doctypes/template/template.doc.mjs +1 -1
  149. package/authoring/doctypes/template/type.ts +9 -0
  150. package/clients/cli/bin/astryx.mjs +6 -9
  151. package/clients/cli/build-id.generated.json +1 -1
  152. package/clients/cli/commands/component.doc.mjs +1 -1
  153. package/clients/cli/commands/component.mjs +20 -2
  154. package/clients/cli/commands/docs.doc.mjs +7 -1
  155. package/clients/cli/commands/docs.mjs +3 -1
  156. package/clients/cli/commands/doctor.mjs +22 -14
  157. package/clients/cli/commands/experimental/render.mjs +32 -1
  158. package/clients/cli/commands/experimental/theme.mjs +65 -14
  159. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  160. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  161. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  162. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  163. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  164. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  165. package/clients/cli/commands/search.doc.mjs +2 -1
  166. package/clients/cli/commands/search.mjs +6 -1
  167. package/clients/cli/commands/template.mjs +4 -2
  168. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  169. package/clients/cli/commands/theme.doc.mjs +1 -1
  170. package/clients/cli/commands/theme.mjs +153 -5
  171. package/clients/cli/commands/upgrade.mjs +42 -7
  172. package/clients/cli/index.mjs +1 -1
  173. package/clients/cli/lib/component-format.mjs +205 -98
  174. package/clients/cli/lib/hook-format.mjs +9 -19
  175. package/clients/cli/manifest.generated.json +1 -1
  176. package/foundation/agent-docs/agent-docs.mjs +1 -1
  177. package/foundation/config/theme-state.d.mts +13 -1
  178. package/foundation/config/theme-state.mjs +47 -7
  179. package/foundation/discovery/component-discovery.d.mts +11 -0
  180. package/foundation/discovery/component-discovery.mjs +27 -2
  181. package/foundation/discovery/component-replacement.mjs +130 -1
  182. package/foundation/discovery/entry-name-files.d.mts +43 -0
  183. package/foundation/discovery/entry-name-files.mjs +264 -0
  184. package/foundation/discovery/hook-discovery.d.mts +8 -2
  185. package/foundation/discovery/hook-discovery.mjs +20 -7
  186. package/foundation/discovery/package-exports.d.mts +10 -0
  187. package/foundation/discovery/package-exports.mjs +56 -3
  188. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  189. package/foundation/discovery/runner-allowlist.mjs +2 -0
  190. package/foundation/discovery/template-adapter.d.mts +52 -0
  191. package/foundation/discovery/template-adapter.mjs +173 -10
  192. package/foundation/discovery/theme-imports.d.mts +14 -0
  193. package/foundation/discovery/theme-imports.mjs +43 -1
  194. package/foundation/doc-compiler/import.mjs +7 -1
  195. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  196. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  197. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  198. package/foundation/fs/cache-eviction.d.mts +21 -0
  199. package/foundation/fs/cache-eviction.mjs +73 -0
  200. package/foundation/fs/gather-cache.d.mts +25 -4
  201. package/foundation/fs/gather-cache.mjs +163 -53
  202. package/foundation/fs/jiti-cache.d.mts +19 -1
  203. package/foundation/fs/jiti-cache.mjs +130 -6
  204. package/foundation/fs/kept-tree.d.mts +60 -0
  205. package/foundation/fs/kept-tree.mjs +154 -0
  206. package/foundation/fs/module-loader.d.mts +18 -2
  207. package/foundation/fs/module-loader.mjs +92 -20
  208. package/foundation/identity/provider-identity.d.mts +6 -0
  209. package/foundation/identity/provider-identity.mjs +10 -1
  210. package/foundation/render/embedded-imports.d.mts +5 -4
  211. package/foundation/render/embedded-imports.mjs +7 -16
  212. package/foundation/render/file-header.d.mts +66 -0
  213. package/foundation/render/file-header.mjs +118 -0
  214. package/foundation/render/host-answer.d.mts +18 -0
  215. package/foundation/render/host-answer.mjs +46 -0
  216. package/foundation/render/host-exit.d.mts +1 -0
  217. package/foundation/render/host-exit.mjs +6 -1
  218. package/foundation/render/html-reader.d.mts +55 -2
  219. package/foundation/render/html-reader.mjs +145 -26
  220. package/foundation/render/markup-edits.d.mts +57 -0
  221. package/foundation/render/markup-edits.mjs +182 -0
  222. package/foundation/render/page-host.mjs +29 -12
  223. package/foundation/render/page-worker.mjs +83 -13
  224. package/foundation/render/render-page.d.mts +34 -2
  225. package/foundation/render/render-page.mjs +210 -29
  226. package/foundation/render/source-block.d.mts +73 -6
  227. package/foundation/render/source-block.mjs +170 -19
  228. package/foundation/render/ts-paths.d.mts +53 -6
  229. package/foundation/render/ts-paths.mjs +286 -41
  230. package/foundation/response/error-codes.d.mts +3 -1
  231. package/foundation/response/error-codes.d.ts +1 -0
  232. package/foundation/response/error-codes.doc.mjs +12 -1
  233. package/foundation/response/error-codes.mjs +10 -0
  234. package/foundation/text/string-utils.d.mts +3 -2
  235. package/foundation/text/string-utils.mjs +16 -3
  236. package/foundation/text/suggest-order.d.mts +9 -0
  237. package/foundation/text/suggest-order.mjs +13 -0
  238. package/host/index.mjs +8 -6
  239. package/package.json +6 -6
@@ -18,7 +18,7 @@
18
18
  * so the server render sets them aside and draws them after it with React
19
19
  * DOM in a small document (charts.mjs).
20
20
  *
21
- * @input workerData {entry, root, served, withoutSegmenter}
21
+ * @input workerData {entry, root, scope, served, withoutSegmenter}
22
22
  * @output one message: {ok: true, markup, css, files, texts, logs} or
23
23
  * {ok: false, error: {code, message, detail?}}
24
24
  * @position foundation/render — started by page-host.mjs
@@ -31,17 +31,18 @@ import {pathToFileURL} from 'node:url';
31
31
  import {format} from 'node:util';
32
32
  import {parentPort, workerData} from 'node:worker_threads';
33
33
  import {transformSync} from '@babel/core';
34
- import {matchPath, readPathsIn, resolvePath} from './ts-paths.mjs';
34
+ import {LOAD_EXTENSIONS, existingFile, matchPath, pathsFor, resolvePath} from './ts-paths.mjs';
35
35
  import {createJiti} from 'jiti';
36
36
  import {assetDataUri, isAssetPath} from './assets.mjs';
37
- import {SINGLE_COPY, isServedPackage, packageOf} from './served-packages.mjs';
37
+ import {SINGLE_COPY, isServedPackage, packageOf, resolveServed} from './served-packages.mjs';
38
38
  import {findNodeModulesPackage} from '../fs/paths.mjs';
39
+ import {importSpecifiers} from './embedded-imports.mjs';
39
40
  import {CHART_GLOBAL, CHART_ROOTS, chartDocument, chartSize, markLegends} from './charts.mjs';
40
41
 
41
42
  /** @typedef {{level: string, text: string}} PageLog */
42
43
 
43
- /** @type {{entry: string, root: string, served: {dir: string, integrations: string[]} | null, withoutSegmenter?: boolean}} */
44
- const {entry, root} = workerData;
44
+ /** @type {{entry: string, root: string, scope: string, served: {dir: string, integrations: string[]} | null, withoutSegmenter?: boolean}} */
45
+ const {entry, root, scope} = workerData;
45
46
 
46
47
  // Some Node builds crash in Intl.Segmenter. Without it, Core splits text by
47
48
  // code points, so a joined emoji can count as several characters.
@@ -49,7 +50,8 @@ if (workerData.withoutSegmenter) delete (/** @type {any} */ (Intl)).Segmenter;
49
50
 
50
51
  /** The package set, for a page outside a project whose folder has no Core of its own. */
51
52
  const served = workerData.served && findNodeModulesPackage(path.dirname(entry), '@astryxdesign/core') === null ? workerData.served : null;
52
- const ROOT_PREFIX = root.endsWith(path.sep) ? root : root + path.sep;
53
+ /** The folder whose modules the page carries (see render-page.mjs `carryScopeOf`). */
54
+ const SCOPE_PREFIX = scope.endsWith(path.sep) ? scope : scope + path.sep;
53
55
 
54
56
  /** @type {PageLog[]} */
55
57
  const logs = [];
@@ -143,10 +145,10 @@ const fnKey = p => {
143
145
 
144
146
  const NODE_MODULES = `${path.sep}node_modules${path.sep}`;
145
147
 
146
- /** A module of the project itself: inside its folder, not a package.
148
+ /** A module of the page's own: inside the folder whose modules it carries, not a package.
147
149
  * @param {string} file */
148
150
  const isLocal = file =>
149
- !file.includes(NODE_MODULES) && (file === entry || file.startsWith(ROOT_PREFIX));
151
+ !file.includes(NODE_MODULES) && (file === entry || file.startsWith(SCOPE_PREFIX));
150
152
 
151
153
  /** Charts the server render set aside, drawn after it. @type {any[]} */
152
154
  const charts = [];
@@ -579,10 +581,11 @@ function pagePlugin(filename) {
579
581
  }
580
582
 
581
583
  /**
582
- * The project's path aliases (`compilerOptions.paths` in tsconfig.json or
583
- * jsconfig.json), matched by TypeScript's rules (see ts-paths.mjs).
584
+ * The page's path aliases (`compilerOptions.paths` in the tsconfig.json or
585
+ * jsconfig.json that TypeScript reads for the page), matched by TypeScript's
586
+ * rules (see ts-paths.mjs).
584
587
  */
585
- const PATHS = readPathsIn(root) ?? [];
588
+ const PATHS = pathsFor(path.resolve(entry));
586
589
 
587
590
  /** @param {string} spec whether a specifier goes through a project alias */
588
591
  const isAliased = spec => resolvePath(PATHS, spec) !== null;
@@ -607,6 +610,20 @@ const namesAlias = spec => {
607
610
  */
608
611
  const resolveAlias = spec => resolvePath(PATHS, spec) ?? spec;
609
612
 
613
+ /**
614
+ * The file a relative or aliased import names, found the way the render
615
+ * loads it, or null for a package import or a file that does not exist.
616
+ * @param {string} spec
617
+ * @param {string} from the importing file
618
+ * @returns {string | null}
619
+ */
620
+ function importedFile(spec, from) {
621
+ const raw = spec.split('?')[0];
622
+ if (raw.startsWith('.')) return existingFile(path.resolve(path.dirname(from), raw), LOAD_EXTENSIONS);
623
+ // An alias resolves by TypeScript's rules, as the import rewrite loads it.
624
+ return isAliased(raw) ? resolveAlias(raw) : null;
625
+ }
626
+
610
627
  /** Packages the page took from the package set, by name: their folders. */
611
628
  /** @type {Map<string, string>} */
612
629
  const fromSet = new Map();
@@ -698,18 +715,47 @@ if (servedParent && Object.keys(SINGLE_COPY_ALIASES).length > 0) {
698
715
  });
699
716
  }
700
717
 
718
+ /** What the StyleX compiler reads as a theme or constants file, by name. */
719
+ const STYLEX_THEME_FILE = /\.(?:stylex(?:\.const)?|transformed)(?:\.(?:js|ts|tsx|jsx|mjs|cjs))?$/;
720
+
721
+ /**
722
+ * Outside a project, the file the page loads for each StyleX theme file a
723
+ * module imports from a package, for the StyleX compiler. The compiler finds
724
+ * a theme import from the folder of the file that imports it, which outside
725
+ * a project holds no copy of the packages the set serves, so it is given the
726
+ * file the page loads. Its own rules still name that file for the variables'
727
+ * names, so they match the package's stylesheet.
728
+ * @param {string} source
729
+ * @param {string} filename
730
+ * @returns {Record<string, string[]> | null}
731
+ */
732
+ function servedThemeFiles(source, filename) {
733
+ if (!served) return null;
734
+ /** @type {Record<string, string[]>} */
735
+ const files = {};
736
+ for (const spec of importSpecifiers(source, filename)) {
737
+ if (spec.startsWith('.') || path.isAbsolute(spec) || !STYLEX_THEME_FILE.test(spec)) continue;
738
+ const file = resolveServed(spec, filename, served);
739
+ if (file) files[spec] = [file];
740
+ }
741
+ return Object.keys(files).length > 0 ? files : null;
742
+ }
743
+
701
744
  const plain = createJiti(entry, {fsCache: false, jsx: {runtime: 'automatic'}});
702
745
 
703
746
  const jiti = createJiti(entry, {
704
747
  fsCache: false,
705
748
  tryNative: false,
706
- extensions: ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.mts', '.cts', '.json'],
749
+ extensions: [...LOAD_EXTENSIONS],
707
750
  moduleCache: true,
708
751
  interopDefault: true,
709
752
  alias: SINGLE_COPY_ALIASES,
710
753
  jsx: {runtime: 'automatic'},
711
754
  transform(opts) {
712
- const filename = opts.filename ?? '';
755
+ // jiti names the file with forward slashes on Windows (`C:/...`), while
756
+ // `entry`, `root` and the node_modules test use the platform separator.
757
+ // Without this, no file reads as local there and none is transformed.
758
+ const filename = opts.filename ? path.normalize(opts.filename) : '';
713
759
  let source = opts.source;
714
760
  if (filename && isLocal(filename) && /\.json$/i.test(filename) && !localFiles.includes(filename)) {
715
761
  localFiles.push(filename);
@@ -717,6 +763,7 @@ const jiti = createJiti(entry, {
717
763
  if (filename && isLocal(filename) && /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/.test(filename)) {
718
764
  if (!localFiles.includes(filename)) localFiles.push(filename);
719
765
  const ts = /\.(tsx?|mts|cts)$/.test(filename);
766
+ const themeFiles = source.includes('stylex') ? servedThemeFiles(source, filename) : null;
720
767
  const result = transformSync(source, {
721
768
  filename,
722
769
  babelrc: false,
@@ -737,6 +784,7 @@ const jiti = createJiti(entry, {
737
784
  runtimeInjection: false,
738
785
  treeshakeCompensation: true,
739
786
  unstable_moduleResolution: {type: 'commonJS', rootDir: root},
787
+ ...(themeFiles ? {aliases: themeFiles} : {}),
740
788
  },
741
789
  ],
742
790
  ]
@@ -909,6 +957,28 @@ try {
909
957
  reach('compiling styles');
910
958
  css = stylexPlugin.processStylexRules(stylexRules, {useLayers: false});
911
959
  }
960
+ // Node loads some local modules itself (jiti hands it a plain ES module,
961
+ // such as a built theme), so they never pass the transform that records
962
+ // local files. Follow the imports of every local module instead, so the
963
+ // file carries each module the page reaches, as --reverse expects.
964
+ for (let i = 0; i < localFiles.length; i++) {
965
+ const file = localFiles[i];
966
+ if (!/\.[cm]?[jt]sx?$/.test(file)) continue;
967
+ let source;
968
+ try {
969
+ source = fs.readFileSync(file, 'utf8');
970
+ } catch {
971
+ continue;
972
+ }
973
+ for (const spec of importSpecifiers(source, file)) {
974
+ const target = importedFile(spec, file);
975
+ // Modules and JSON only: the transform already carries the stylesheets
976
+ // and images a module imports, and a Sass file is never carried.
977
+ if (target && /\.([cm]?[jt]sx?|json)$/i.test(target) && isLocal(target) && !localFiles.includes(target)) {
978
+ localFiles.push(target);
979
+ }
980
+ }
981
+ }
912
982
  parentPort?.postMessage({
913
983
  ok: true,
914
984
  markup,
@@ -1,6 +1,30 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * Run `use` with a state file for one host in a new folder under the system's
6
+ * temporary folder, never in the project, and remove the folder after. The
7
+ * state file only explains a failure: without a temporary folder, `use` gets
8
+ * none and the render runs without it.
9
+ * @template T
10
+ * @param {(stateFile: string | undefined) => Promise<T>} use
11
+ * @param {{makeTempDir?: (prefix: string) => string}} [options]
12
+ * @returns {Promise<T>}
13
+ */
14
+ export function withHostStateFile<T>(use: (stateFile: string | undefined) => Promise<T>, { makeTempDir }?: {
15
+ makeTempDir?: (prefix: string) => string;
16
+ }): Promise<T>;
17
+ /**
18
+ * The page's answer from its host process, or the reason it has none.
19
+ * @param {import('node:child_process').ChildProcess} host
20
+ * @param {{timeoutMs: number, withoutSegmenter: boolean, stateFile?: string}} options
21
+ * @returns {Promise<any>}
22
+ */
23
+ export function awaitHost(host: import("node:child_process").ChildProcess, { timeoutMs, withoutSegmenter, stateFile }: {
24
+ timeoutMs: number;
25
+ withoutSegmenter: boolean;
26
+ stateFile?: string;
27
+ }): Promise<any>;
4
28
  /**
5
29
  * The warning for a page rendered without Intl.Segmenter.
6
30
  * @returns {RenderWarning}
@@ -9,9 +33,15 @@ export function segmenterWarning(): RenderWarning;
9
33
  /**
10
34
  * Render a page module to one self-contained HTML file.
11
35
  * @param {string} entry absolute path of the page module
12
- * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null}} [options]
36
+ * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null, output?: string, cwd?: string}} [options]
13
37
  * `served`: the Core of the package set the CLI runs from, for the packages
14
- * the page's folder has no copy of
38
+ * the page's folder has no copy of; `output`: the file the HTML goes to;
39
+ * `cwd`: the current folder, whose files are the page's own outside a
40
+ * project.
41
+ * With `output`, the file describes itself: notes at its top and end name
42
+ * what made it and the commands that give the page back and render it
43
+ * again, and its embedded source records the CLI version, the packages
44
+ * the page rendered with, and the markup as rendered.
15
45
  * @returns {Promise<RenderedPage>}
16
46
  */
17
47
  export function renderPage(entry: string, options?: {
@@ -19,6 +49,8 @@ export function renderPage(entry: string, options?: {
19
49
  timeoutMs?: number;
20
50
  version?: string;
21
51
  served?: ServedSet | null;
52
+ output?: string;
53
+ cwd?: string;
22
54
  }): Promise<RenderedPage>;
23
55
  /** How long one page may take to render before it is stopped. */
24
56
  export const RENDER_TIMEOUT_MS: 60000;
@@ -17,17 +17,22 @@
17
17
  */
18
18
 
19
19
  import * as fs from 'node:fs';
20
+ import * as os from 'node:os';
20
21
  import * as path from 'node:path';
21
22
  import {fork, spawnSync} from 'node:child_process';
23
+ import {builtinModules} from 'node:module';
22
24
  import {fileURLToPath} from 'node:url';
23
25
  import postcss from 'postcss';
24
26
  import {assetDataUri, isAssetBytes, isAssetPath, RenderAssetError} from './assets.mjs';
25
27
  import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';
26
- import {sourceBlock} from './source-block.mjs';
28
+ import {RENDER_FORMAT, asParsed, sha256, sourceBlock} from './source-block.mjs';
27
29
  import {embeddedPathProblem} from './embedded-files.mjs';
28
- import {resolveServed} from './served-packages.mjs';
30
+ import {isServedPackage, resolveServed} from './served-packages.mjs';
29
31
  import {CHART_CSS} from './charts.mjs';
30
32
  import {HOST_EXIT} from './host-exit.mjs';
33
+ import {endNote, headerNote} from './file-header.mjs';
34
+ import {textRuns} from './markup-edits.mjs';
35
+ import {findNodeModulesPackage} from '../fs/paths.mjs';
31
36
 
32
37
  /** How long one page may take to render before it is stopped. */
33
38
  export const RENDER_TIMEOUT_MS = 60_000;
@@ -68,19 +73,33 @@ export class RenderError extends Error {
68
73
  }
69
74
 
70
75
  /**
71
- * The nearest folder at or above `dir` with a package.json, else `dir`.
76
+ * The nearest folder at or above `dir` with a package.json, or null outside
77
+ * a project.
72
78
  * @param {string} dir
79
+ * @returns {string | null}
73
80
  */
74
- function projectRootOf(dir) {
75
- let d = dir;
76
- for (;;) {
81
+ function projectOf(dir) {
82
+ for (let d = dir; ; d = path.dirname(d)) {
77
83
  if (fs.existsSync(path.join(d, 'package.json'))) return d;
78
- const up = path.dirname(d);
79
- if (up === d) return dir;
80
- d = up;
84
+ if (path.dirname(d) === d) return null;
81
85
  }
82
86
  }
83
87
 
88
+ /**
89
+ * The folder whose modules the page carries: its project's. Outside a
90
+ * project, the current folder when it holds the page, so a page with
91
+ * neighbours above its own folder (as a restore lays them out) carries them;
92
+ * else the page's folder.
93
+ * @param {string} dir
94
+ * @param {string} [cwd]
95
+ */
96
+ function carryScopeOf(dir, cwd) {
97
+ const project = projectOf(dir);
98
+ if (project) return project;
99
+ const fromCwd = cwd ? path.relative(cwd, dir) : '..';
100
+ return fromCwd.startsWith('..') || path.isAbsolute(fromCwd) ? dir : /** @type {string} */ (cwd);
101
+ }
102
+
84
103
  /** @param {string} s */
85
104
  const escapeHtml = s =>
86
105
  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -305,24 +324,61 @@ function hostEndError(/** @type {number | null} */ code) {
305
324
  if (code === HOST_EXIT.timeout) {
306
325
  return new RenderError('ERR_RENDER_TIMEOUT', "The page's process stopped at its own time limit before this process read an answer.", {reason: 'host-timeout', exit: code});
307
326
  }
327
+ if (code === HOST_EXIT.sendFailed) {
328
+ return new RenderError('ERR_RENDER_FAILED', "The page's process could not send its answer to this process.", {reason: 'send-failed', exit: code});
329
+ }
308
330
  return new RenderError('ERR_RENDER_FAILED', `The page's process ended without an answer (exit ${code}).`, {reason: 'host-ended', exit: code});
309
331
  }
310
332
 
333
+ /**
334
+ * The error for a host that ended with no answer reaching this process, from
335
+ * the state it left in its per-run file: an answer it sent that never
336
+ * arrived, or the stage it ended in.
337
+ * @param {number | null} code
338
+ * @param {string | undefined} stateFile
339
+ */
340
+ function noMessageError(code, stateFile) {
341
+ if (code !== 0 && code !== null && Object.values(HOST_EXIT).includes(code)) return hostEndError(code);
342
+ /** @type {any} */
343
+ let saved = null;
344
+ try {
345
+ saved = stateFile ? JSON.parse(fs.readFileSync(stateFile, 'utf8')) : null;
346
+ } catch {
347
+ // No readable state: fall back to the bare message below.
348
+ }
349
+ if (!saved) return hostEndError(code);
350
+ const detail = {exit: code, stage: saved.stage, elapsedMs: saved.elapsedMs, rssMb: saved.rssMb, freeMb: saved.freeMb, ...(saved.stderrTail ? {stderrTail: saved.stderrTail} : {})};
351
+ if (saved.answered === 'sent') {
352
+ return new RenderError('ERR_RENDER_FAILED', `The page's process sent its answer, but this process did not receive it (exit ${code}).`, {reason: 'answer-lost', ...detail});
353
+ }
354
+ if (saved.answered === 'sending') {
355
+ return new RenderError('ERR_RENDER_FAILED', `The page's process ended while it sent its answer (exit ${code}).`, {reason: 'ended-while-sending', ...detail});
356
+ }
357
+ const seconds = Math.round((saved.elapsedMs ?? 0) / 1000);
358
+ const last = saved.stderrTail ? ` Its last output: ${String(saved.stderrTail).split('\n').at(-1)}` : '';
359
+ return new RenderError(
360
+ 'ERR_RENDER_FAILED',
361
+ `The page's process ended without an answer (exit ${code}) while ${saved.stage}, after ${seconds} seconds, with ${saved.freeMb} MB of memory free.${last}`,
362
+ {reason: 'host-ended', ...detail},
363
+ );
364
+ }
365
+
311
366
  /**
312
367
  * Run the page in a host process (page-host.mjs), stopping it after
313
368
  * `timeoutMs`. The host runs the page in a worker thread, and it exits when
314
369
  * this process goes away.
315
- * @param {{entry: string, root: string, served: ServedSet | null, withoutSegmenter: boolean}} input
370
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null, withoutSegmenter: boolean}} input
316
371
  * @param {number} timeoutMs
317
372
  * @returns {Promise<any>} the page's answer, or `{crashed: how}` when a
318
373
  * native crash ended the host
319
374
  */
320
375
  function runWorker(input, timeoutMs) {
321
- return new Promise((resolve, reject) => {
376
+ return withHostStateFile(stateFile => {
322
377
  const data = {
323
378
  ...input,
324
379
  served: input.served ? {dir: input.served.dir, integrations: [...input.served.integrations]} : null,
325
380
  timeoutMs,
381
+ stateFile,
326
382
  };
327
383
  const host = fork(fileURLToPath(new URL('./page-host.mjs', import.meta.url)), [JSON.stringify(data)], {
328
384
  // Never the CLI's own flags (such as --input-type).
@@ -330,6 +386,52 @@ function runWorker(input, timeoutMs) {
330
386
  stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
331
387
  serialization: 'advanced',
332
388
  });
389
+ return awaitHost(host, {timeoutMs, withoutSegmenter: input.withoutSegmenter, stateFile});
390
+ });
391
+ }
392
+
393
+ /**
394
+ * Run `use` with a state file for one host in a new folder under the system's
395
+ * temporary folder, never in the project, and remove the folder after. The
396
+ * state file only explains a failure: without a temporary folder, `use` gets
397
+ * none and the render runs without it.
398
+ * @template T
399
+ * @param {(stateFile: string | undefined) => Promise<T>} use
400
+ * @param {{makeTempDir?: (prefix: string) => string}} [options]
401
+ * @returns {Promise<T>}
402
+ */
403
+ export async function withHostStateFile(
404
+ use,
405
+ {makeTempDir = prefix => fs.mkdtempSync(prefix)} = {},
406
+ ) {
407
+ /** @type {string} */
408
+ let dir;
409
+ try {
410
+ dir = makeTempDir(path.join(os.tmpdir(), 'astryx-render-'));
411
+ } catch {
412
+ // No temporary folder (missing or read-only): render without the state file.
413
+ return use(undefined);
414
+ }
415
+ try {
416
+ return await use(path.join(dir, 'host-state.json'));
417
+ } finally {
418
+ try {
419
+ fs.rmSync(dir, {recursive: true, force: true, maxRetries: 3});
420
+ } catch {
421
+ // Best effort: a removal that fails (a file still held open) never
422
+ // replaces the render's own result.
423
+ }
424
+ }
425
+ }
426
+
427
+ /**
428
+ * The page's answer from its host process, or the reason it has none.
429
+ * @param {import('node:child_process').ChildProcess} host
430
+ * @param {{timeoutMs: number, withoutSegmenter: boolean, stateFile?: string}} options
431
+ * @returns {Promise<any>}
432
+ */
433
+ export function awaitHost(host, {timeoutMs, withoutSegmenter, stateFile}) {
434
+ return new Promise((resolve, reject) => {
333
435
  let settled = false;
334
436
  /** @param {() => void} settle */
335
437
  const finish = settle => {
@@ -369,12 +471,14 @@ function runWorker(input, timeoutMs) {
369
471
  host.once('error', error => {
370
472
  finish(() => reject(new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`)));
371
473
  });
372
- host.once('exit', (code, signal) => {
474
+ // 'close' comes after the IPC channel drains, so an answer the host sent
475
+ // just before it exited still wins; 'exit' can come first under load.
476
+ host.once('close', (code, signal) => {
373
477
  finish(() => {
374
478
  const crash = crashOf(code, signal);
375
479
  if (crash) resolve({crashed: crash});
376
- else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter: input.withoutSegmenter}));
377
- else reject(hostEndError(code));
480
+ else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter}));
481
+ else reject(noMessageError(code, stateFile));
378
482
  });
379
483
  });
380
484
  });
@@ -383,7 +487,7 @@ function runWorker(input, timeoutMs) {
383
487
  /**
384
488
  * Run the page. When this Node crashes in Intl.Segmenter, run it once more
385
489
  * without Intl.Segmenter and say so in a warning.
386
- * @param {{entry: string, root: string, served: ServedSet | null}} input
490
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null}} input
387
491
  * @param {number} timeoutMs
388
492
  * @param {RenderWarning[]} warnings
389
493
  */
@@ -484,6 +588,26 @@ function inlineAssets(text, kind, ctx) {
484
588
  });
485
589
  }
486
590
 
591
+ /**
592
+ * The version of a package the page rendered with: the package set's copy
593
+ * when the page took it from there, else the copy Node's resolver finds from
594
+ * the page's folder.
595
+ * @param {string} name
596
+ * @param {string} dir the page's folder
597
+ * @param {Map<string, string>} setDirs the packages the page took from the package set: their folders
598
+ * @returns {string | null}
599
+ */
600
+ function installedVersion(name, dir, setDirs) {
601
+ const packageDir = setDirs.get(name) ?? findNodeModulesPackage(dir, name)?.packageDir;
602
+ if (!packageDir) return null;
603
+ try {
604
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
605
+ return pkg?.name === name && typeof pkg.version === 'string' ? pkg.version : null;
606
+ } catch {
607
+ return null;
608
+ }
609
+ }
610
+
487
611
  /** The light and dark switch every rendered page carries. */
488
612
  const SCHEME_CSS =
489
613
  ':root{color-scheme:light dark}:root[data-theme="light"]{color-scheme:light}:root[data-theme="dark"]{color-scheme:dark}';
@@ -491,18 +615,27 @@ const SCHEME_CSS =
491
615
  /**
492
616
  * Render a page module to one self-contained HTML file.
493
617
  * @param {string} entry absolute path of the page module
494
- * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null}} [options]
618
+ * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null, output?: string, cwd?: string}} [options]
495
619
  * `served`: the Core of the package set the CLI runs from, for the packages
496
- * the page's folder has no copy of
620
+ * the page's folder has no copy of; `output`: the file the HTML goes to;
621
+ * `cwd`: the current folder, whose files are the page's own outside a
622
+ * project.
623
+ * With `output`, the file describes itself: notes at its top and end name
624
+ * what made it and the commands that give the page back and render it
625
+ * again, and its embedded source records the CLI version, the packages
626
+ * the page rendered with, and the markup as rendered.
497
627
  * @returns {Promise<RenderedPage>}
498
628
  */
499
629
  export async function renderPage(entry, options = {}) {
500
630
  const dir = path.dirname(entry);
501
- const root = projectRootOf(dir);
631
+ // The project's folder, else the page's: where its tsconfig.json and
632
+ // public/ images are read.
633
+ const root = projectOf(dir) ?? dir;
634
+ const scope = carryScopeOf(dir, options.cwd);
502
635
  const served = options.served ?? null;
503
636
  /** @type {RenderWarning[]} */
504
637
  const warnings = [];
505
- const message = await runPage({entry, root, served}, options.timeoutMs ?? RENDER_TIMEOUT_MS, warnings);
638
+ const message = await runPage({entry, root, scope, served}, options.timeoutMs ?? RENDER_TIMEOUT_MS, warnings);
506
639
  if (!message.ok) {
507
640
  throw new RenderError(message.error.code, message.error.message, message.error.detail);
508
641
  }
@@ -696,12 +829,12 @@ export async function renderPage(entry, options = {}) {
696
829
  // (`<img src="./logo.png">`, `url(./bg.png)`) are carried too, so the page
697
830
  // comes back with them; a package's own files are not.
698
831
  for (const sheet of carriedCss) {
699
- const rel = path.relative(root, sheet);
832
+ const rel = path.relative(scope, sheet);
700
833
  if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
701
834
  if (!files.includes(sheet)) files.push(sheet);
702
835
  }
703
836
  for (const asset of ctx.localAssets) {
704
- const rel = path.relative(root, asset);
837
+ const rel = path.relative(scope, asset);
705
838
  if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
706
839
  if (files.includes(asset)) continue;
707
840
  // Carried only when its bytes are a known image, font or media format,
@@ -739,14 +872,62 @@ export async function renderPage(entry, options = {}) {
739
872
  }
740
873
  const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(markup)?.[1]?.replace(/<[^>]*>/g, '').trim();
741
874
  const title = options.title ?? (heading ? decodeAttr(heading) : path.basename(entry).replace(/\.[^.]+$/, ''));
742
- const html =
743
- '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
744
- '<meta name="viewport" content="width=device-width,initial-scale=1">' +
745
- '<meta name="color-scheme" content="light dark">' +
746
- `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">` +
747
- `<title>${escapeHtml(title)}</title>` +
748
- `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style></head><body>${markup}` +
749
- `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
875
+ const generator = `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">`;
876
+ const style = `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style>`;
877
+ let html;
878
+ if (options.output) {
879
+ // The charset and generator metas come first: a browser reads the
880
+ // charset only from the first 1024 bytes, and a CLI decides whether a
881
+ // render wrote a file from its first 4096.
882
+ const setDirs = new Map(/** @type {{name: string, dir: string}[]} */ (message.fromSet ?? []).map(p => [p.name, p.dir]));
883
+ const names = new Set([...(message.packages ?? []), ...setDirs.keys(), 'react', 'react-dom']);
884
+ if (hasCore) names.add('@astryxdesign/core');
885
+ /** @type {Record<string, string>} */
886
+ const packages = {};
887
+ for (const name of [...names].sort()) {
888
+ if (name.startsWith('node:') || builtinModules.includes(name)) continue;
889
+ const version = installedVersion(name, dir, setDirs);
890
+ if (version) packages[name] = version;
891
+ }
892
+ const file = path.basename(options.output);
893
+ const facts = {
894
+ cli: options.version ?? null,
895
+ format: RENDER_FORMAT,
896
+ file,
897
+ page: path.relative(root, entry).split(path.sep).join('/'),
898
+ restored: `${file.replace(/\.[^.]+$/, '')}-restored/${embedded[0].path}`,
899
+ files: embedded.map(f => f.path),
900
+ packages,
901
+ install: Object.entries(packages)
902
+ .filter(([name]) => !isServedPackage(name, []))
903
+ .map(([name, version]) => `${name}@${version}`),
904
+ ...(options.title === undefined ? {} : {title: options.title}),
905
+ };
906
+ const record = {
907
+ ...(facts.cli ? {cli: facts.cli} : {}),
908
+ page: facts.page,
909
+ ...(options.title === undefined ? {} : {title: options.title}),
910
+ packages,
911
+ markup: {
912
+ sha256: sha256(asParsed(markup)),
913
+ style: sha256(asParsed(style)),
914
+ text: Buffer.from(JSON.stringify({title, runs: textRuns(markup)})).toString('base64'),
915
+ },
916
+ };
917
+ html =
918
+ `<!doctype html><html lang="en"><head><meta charset="utf-8">${generator}\n${headerNote(facts)}\n` +
919
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
920
+ '<meta name="color-scheme" content="light dark">' +
921
+ `<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
922
+ `${sourceBlock(path.basename(entry), embedded, record)}\n${endNote(facts)}\n</body></html>\n`;
923
+ } else {
924
+ html =
925
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
926
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
927
+ '<meta name="color-scheme" content="light dark">' +
928
+ `${generator}<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
929
+ `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
930
+ }
750
931
  return {
751
932
  html,
752
933
  files: embedded.map(f => f.path),