@astryxdesign/cli 0.7.16 → 0.7.17-canary.g9a957aa

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 (229) hide show
  1. package/README.md +12 -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 +47 -9
  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 +32 -0
  14. package/api/build/kit/words.mjs +49 -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 +48 -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 +491 -186
  34. package/api/render/render.doc.mjs +10 -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 +38 -0
  46. package/api/theme/build/build.mjs +144 -24
  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 +35 -0
  50. package/api/theme-edit/_adapter.mjs +477 -41
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1077 -200
  53. package/api/theme-edit/_compiler.mjs +9 -0
  54. package/api/theme-edit/_context.mjs +60 -3
  55. package/api/theme-edit/_css.mjs +21 -1
  56. package/api/theme-edit/_edit.d.mts +22 -0
  57. package/api/theme-edit/_edit.mjs +932 -82
  58. package/api/theme-edit/_how-commands.d.mts +49 -0
  59. package/api/theme-edit/_how-commands.mjs +386 -1
  60. package/api/theme-edit/_how-question.d.mts +56 -0
  61. package/api/theme-edit/_how-question.mjs +3509 -168
  62. package/api/theme-edit/_how.mjs +104 -4
  63. package/api/theme-edit/_marks.d.mts +31 -5
  64. package/api/theme-edit/_marks.mjs +57 -5
  65. package/api/theme-edit/_normal.d.mts +137 -0
  66. package/api/theme-edit/_normal.mjs +612 -0
  67. package/api/theme-edit/_palette.mjs +10 -4
  68. package/api/theme-edit/_parts.d.mts +4 -0
  69. package/api/theme-edit/_parts.mjs +28 -2
  70. package/api/theme-edit/_preview-app.d.mts +7 -1
  71. package/api/theme-edit/_preview-app.mjs +191 -15
  72. package/api/theme-edit/_preview.d.mts +64 -8
  73. package/api/theme-edit/_preview.mjs +401 -83
  74. package/api/theme-edit/_settings.d.mts +139 -5
  75. package/api/theme-edit/_settings.mjs +1659 -112
  76. package/api/theme-edit/_tables.mjs +17 -1
  77. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  78. package/api/theme-edit/theme-edit.type.mjs +4 -1
  79. package/api/theme-edit/themeEditPreviewApp.doc.mjs +2 -2
  80. package/assets/codemods/run-codemod.mjs +73 -6
  81. package/assets/codemods/transforms/next/index.mjs +11 -1
  82. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  83. package/assets/docs/author-a-theme.doc.mjs +1 -0
  84. package/assets/docs/theme.doc.dense.mjs +2 -2
  85. package/assets/docs/theme.doc.mjs +1 -1
  86. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  87. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  88. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  89. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  90. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  91. package/assets/docs/use-a-theme.doc.mjs +1 -1
  92. package/assets/docs.generated.json +2 -2
  93. package/assets/self-audit.generated.json +1 -1
  94. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  95. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  96. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  97. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  98. package/assets/templates/components.generated.json +1 -1
  99. package/assets/templates/pages/ai-chat/template.doc.mjs +8 -4
  100. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  101. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  102. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  103. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  104. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  105. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  106. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  107. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  108. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  110. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  111. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  112. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  113. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  114. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  115. package/assets/templates/pages/editor/template.doc.mjs +1 -7
  116. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  117. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  118. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  119. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  120. package/assets/templates/pages/ide/page.tsx +24 -2
  121. package/assets/templates/pages/library/template.doc.mjs +4 -1
  122. package/assets/templates/pages/login/template.doc.mjs +2 -1
  123. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  124. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  125. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  126. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  127. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  128. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  129. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  130. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  131. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  132. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  133. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  134. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  135. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  136. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  137. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  138. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  139. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -1
  140. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  141. package/authoring/debug/parse.d.mts +3 -3
  142. package/authoring/doctypes/_schema.d.mts +3 -3
  143. package/authoring/doctypes/command/command.doc.mjs +1 -1
  144. package/authoring/doctypes/template/template.doc.mjs +1 -1
  145. package/authoring/doctypes/template/type.ts +9 -0
  146. package/clients/cli/bin/astryx.mjs +6 -9
  147. package/clients/cli/build-id.generated.json +1 -1
  148. package/clients/cli/commands/component.doc.mjs +1 -1
  149. package/clients/cli/commands/component.mjs +20 -2
  150. package/clients/cli/commands/docs.doc.mjs +7 -1
  151. package/clients/cli/commands/docs.mjs +3 -1
  152. package/clients/cli/commands/doctor.mjs +22 -14
  153. package/clients/cli/commands/experimental/render.mjs +32 -1
  154. package/clients/cli/commands/experimental/theme.mjs +27 -2
  155. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  156. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  157. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  158. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  159. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  160. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  161. package/clients/cli/commands/search.doc.mjs +2 -1
  162. package/clients/cli/commands/search.mjs +6 -1
  163. package/clients/cli/commands/template.mjs +4 -2
  164. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  165. package/clients/cli/commands/theme.doc.mjs +1 -1
  166. package/clients/cli/commands/theme.mjs +138 -3
  167. package/clients/cli/commands/upgrade.mjs +42 -7
  168. package/clients/cli/index.mjs +1 -1
  169. package/clients/cli/lib/component-format.mjs +205 -98
  170. package/clients/cli/lib/hook-format.mjs +9 -19
  171. package/clients/cli/manifest.generated.json +1 -1
  172. package/foundation/agent-docs/agent-docs.mjs +1 -1
  173. package/foundation/config/theme-state.d.mts +13 -1
  174. package/foundation/config/theme-state.mjs +47 -7
  175. package/foundation/discovery/component-discovery.d.mts +11 -0
  176. package/foundation/discovery/component-discovery.mjs +27 -2
  177. package/foundation/discovery/component-replacement.mjs +130 -1
  178. package/foundation/discovery/entry-name-files.d.mts +43 -0
  179. package/foundation/discovery/entry-name-files.mjs +264 -0
  180. package/foundation/discovery/hook-discovery.d.mts +8 -2
  181. package/foundation/discovery/hook-discovery.mjs +20 -7
  182. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  183. package/foundation/discovery/runner-allowlist.mjs +2 -0
  184. package/foundation/discovery/template-adapter.d.mts +52 -0
  185. package/foundation/discovery/template-adapter.mjs +169 -0
  186. package/foundation/discovery/theme-imports.d.mts +14 -0
  187. package/foundation/discovery/theme-imports.mjs +43 -1
  188. package/foundation/doc-compiler/import.mjs +7 -1
  189. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  190. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  191. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  192. package/foundation/fs/cache-eviction.d.mts +21 -0
  193. package/foundation/fs/cache-eviction.mjs +73 -0
  194. package/foundation/fs/gather-cache.d.mts +25 -4
  195. package/foundation/fs/gather-cache.mjs +138 -52
  196. package/foundation/fs/jiti-cache.d.mts +19 -1
  197. package/foundation/fs/jiti-cache.mjs +130 -6
  198. package/foundation/fs/kept-tree.d.mts +60 -0
  199. package/foundation/fs/kept-tree.mjs +154 -0
  200. package/foundation/fs/module-loader.d.mts +18 -2
  201. package/foundation/fs/module-loader.mjs +92 -20
  202. package/foundation/identity/provider-identity.d.mts +6 -0
  203. package/foundation/identity/provider-identity.mjs +10 -1
  204. package/foundation/render/file-header.d.mts +66 -0
  205. package/foundation/render/file-header.mjs +118 -0
  206. package/foundation/render/host-answer.d.mts +18 -0
  207. package/foundation/render/host-answer.mjs +46 -0
  208. package/foundation/render/host-exit.d.mts +1 -0
  209. package/foundation/render/host-exit.mjs +6 -1
  210. package/foundation/render/html-reader.d.mts +55 -2
  211. package/foundation/render/html-reader.mjs +145 -26
  212. package/foundation/render/markup-edits.d.mts +57 -0
  213. package/foundation/render/markup-edits.mjs +182 -0
  214. package/foundation/render/page-host.mjs +29 -12
  215. package/foundation/render/page-worker.mjs +79 -10
  216. package/foundation/render/render-page.d.mts +34 -2
  217. package/foundation/render/render-page.mjs +210 -29
  218. package/foundation/render/source-block.d.mts +73 -6
  219. package/foundation/render/source-block.mjs +170 -19
  220. package/foundation/render/ts-paths.d.mts +4 -1
  221. package/foundation/render/ts-paths.mjs +7 -3
  222. package/foundation/response/error-codes.d.mts +2 -1
  223. package/foundation/response/error-codes.doc.mjs +7 -1
  224. package/foundation/response/error-codes.mjs +7 -0
  225. package/foundation/text/string-utils.d.mts +3 -2
  226. package/foundation/text/string-utils.mjs +16 -3
  227. package/foundation/text/suggest-order.d.mts +9 -0
  228. package/foundation/text/suggest-order.mjs +13 -0
  229. package/package.json +6 -6
@@ -15,7 +15,7 @@
15
15
  import * as fs from 'node:fs';
16
16
  import * as path from 'node:path';
17
17
  import {findInstalledPackage} from '../fs/paths.mjs';
18
- import {moduleExportsName} from './module-exports.mjs';
18
+ import {moduleExportSource, moduleExportsName} from './module-exports.mjs';
19
19
  import {inspectPackageExport} from './package-exports.mjs';
20
20
  import {themeImportPackage} from './theme-discovery.mjs';
21
21
  import {isLocalThemeOwner, projectPath} from '../config/theme-state.mjs';
@@ -101,6 +101,7 @@ function resolveLocalTheme(theme, cwd) {
101
101
  stylesheetFile,
102
102
  ...(fs.existsSync(fontStylesheetFile) ? {fontStylesheetFile} : {}),
103
103
  source: /** @type {const} */ ('local'),
104
+ ...builtColorMode(moduleFile, theme.exportName),
104
105
  };
105
106
  }
106
107
 
@@ -228,9 +229,50 @@ function resolvePackageTheme(theme, cwd, ownerThemeCount) {
228
229
  /** @type {any} */ (theme).source === 'bundled' || theme.bundled
229
230
  ? /** @type {const} */ ('bundled')
230
231
  : /** @type {const} */ ('package'),
232
+ ...builtColorMode(selected.module.target, theme.exportName),
231
233
  };
232
234
  }
233
235
 
236
+ /**
237
+ * `{mode}` for a built theme module that exports one color mode
238
+ * (`export const colorModes = ["light"];`, which `theme build` writes beside
239
+ * the theme export), read without running it; nothing for a module with
240
+ * both modes, which exports none.
241
+ * @param {string | null | undefined} moduleFile
242
+ * @param {string} [exportName] the theme's export: a module that re-exports
243
+ * only the theme by name (`export {oceanTheme} from './ocean.js'`) is
244
+ * read where the theme is declared
245
+ * @returns {{mode?: 'light' | 'dark'}}
246
+ */
247
+ export function builtColorMode(moduleFile, exportName) {
248
+ if (!moduleFile) return {};
249
+ // The file that declares it: the module, or the built module it re-exports
250
+ // (`export * from './ocean.js'`); else the built module that declares the
251
+ // theme the module re-exports by name.
252
+ const declaring =
253
+ moduleExportSource(moduleFile, 'colorModes') ??
254
+ (exportName
255
+ ? (() => {
256
+ const theme = moduleExportSource(moduleFile, exportName);
257
+ return theme && theme !== moduleFile
258
+ ? moduleExportSource(theme, 'colorModes')
259
+ : null;
260
+ })()
261
+ : null);
262
+ if (!declaring) return {};
263
+ let text;
264
+ try {
265
+ text = fs.readFileSync(declaring, 'utf8');
266
+ } catch {
267
+ return {};
268
+ }
269
+ const m =
270
+ /^export const colorModes = \[\s*["'](light|dark)["']\s*\];?\s*$/m.exec(
271
+ text,
272
+ );
273
+ return m ? {mode: /** @type {'light' | 'dark'} */ (m[1])} : {};
274
+ }
275
+
234
276
  /**
235
277
  * Resolve a discovered theme to app imports.
236
278
  * @param {import('./theme-discovery.mjs').DiscoveredTheme} theme
@@ -35,7 +35,12 @@ import {
35
35
  readInTurn,
36
36
  } from '../fs/module-loader.mjs';
37
37
  import {fileStamp, recordContentRead} from '../fs/read-record.mjs';
38
- import {readStore, storedKey, STORED_DOCS_FILE} from './stored-docs.mjs';
38
+ import {
39
+ noteStoredExport,
40
+ readStore,
41
+ storedKey,
42
+ STORED_DOCS_FILE,
43
+ } from './stored-docs.mjs';
39
44
 
40
45
  const requireFromHere = createRequire(import.meta.url);
41
46
 
@@ -132,6 +137,7 @@ function storedModule(file) {
132
137
  enumerable: true,
133
138
  writable: true,
134
139
  });
140
+ noteStoredExport(exports[name], key, name);
135
141
  }
136
142
  Object.defineProperty(module, Symbol.toStringTag, {value: 'Module'});
137
143
  Object.preventExtensions(module);
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import {parseDoc} from '../../authoring/doctypes/parse.mjs';
14
+ import {storedParse} from './stored-docs.mjs';
14
15
 
15
16
  /**
16
17
  * @param {unknown} input
@@ -25,5 +26,7 @@ export function parseReadableDoc(input, label = 'doc') {
25
26
  if (type === 'theme') {
26
27
  throw new Error(`${label} has unsupported type ${JSON.stringify(type)}.`);
27
28
  }
28
- return parseDoc(input, label);
29
+ // A doc Astryx ships was parsed at publish (scripts/generate-stored-docs.mjs):
30
+ // its stored parse is what parsing it gives.
31
+ return storedParse(input) ?? parseDoc(input, label);
29
32
  }
@@ -21,6 +21,28 @@ export function storedKey(text: string | Buffer): string;
21
21
  export function readStore(file: string): {
22
22
  get: (key: string) => any;
23
23
  };
24
+ /**
25
+ * Note that `value` is the `name` export of the stored doc `key`.
26
+ * @param {unknown} value
27
+ * @param {string} key
28
+ * @param {string} name
29
+ */
30
+ export function noteStoredExport(value: unknown, key: string, name: string): void;
31
+ /**
32
+ * Where a stored doc's export, as the readers parse it, is stored at publish.
33
+ * @param {string} key the doc's key
34
+ * @param {string} name the export's name
35
+ * @returns {string}
36
+ */
37
+ export function storedParseKey(key: string, name: string): string;
38
+ /**
39
+ * The parse of `value`, read from the store, when `value` is a stored doc's
40
+ * export whose parse was stored at publish: a fresh value, as a parse gives.
41
+ * Undefined otherwise, or when the store cannot be read.
42
+ * @param {unknown} value
43
+ * @returns {any}
44
+ */
45
+ export function storedParse(value: unknown): any;
24
46
  /**
25
47
  * Where the exports of the doc files Astryx ships (the CLI's and Core's) are
26
48
  * stored: each doc that imports nothing, reads nothing of where it sits, and
@@ -96,3 +96,52 @@ function openStore(file) {
96
96
  return new Map();
97
97
  }
98
98
  }
99
+
100
+ /**
101
+ * Each export value of a stored doc's module (./import.mjs), with the doc's
102
+ * key and the export's name, so its parse can be answered from the store
103
+ * ({@link storedParse}).
104
+ * @type {WeakMap<object, {key: string, name: string}>}
105
+ */
106
+ const storedExports = new WeakMap();
107
+
108
+ /**
109
+ * Note that `value` is the `name` export of the stored doc `key`.
110
+ * @param {unknown} value
111
+ * @param {string} key
112
+ * @param {string} name
113
+ */
114
+ export function noteStoredExport(value, key, name) {
115
+ if (value && typeof value === 'object') storedExports.set(value, {key, name});
116
+ }
117
+
118
+ /**
119
+ * Where a stored doc's export, as the readers parse it, is stored at publish.
120
+ * @param {string} key the doc's key
121
+ * @param {string} name the export's name
122
+ * @returns {string}
123
+ */
124
+ export function storedParseKey(key, name) {
125
+ return `parsed:${name}:${key}`;
126
+ }
127
+
128
+ /**
129
+ * The parse of `value`, read from the store, when `value` is a stored doc's
130
+ * export whose parse was stored at publish: a fresh value, as a parse gives.
131
+ * Undefined otherwise, or when the store cannot be read.
132
+ * @param {unknown} value
133
+ * @returns {any}
134
+ */
135
+ export function storedParse(value) {
136
+ if (!value || typeof value !== 'object') return undefined;
137
+ const at = storedExports.get(value);
138
+ if (!at) return undefined;
139
+ try {
140
+ const parsed = readStore(STORED_DOCS_FILE).get(
141
+ storedParseKey(at.key, at.name),
142
+ );
143
+ return parsed != null && typeof parsed === 'object' ? parsed : undefined;
144
+ } catch {
145
+ return undefined;
146
+ }
147
+ }
@@ -0,0 +1,21 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Delete the folder's counted files, least recently used first, until they
6
+ * hold at most `limit` bytes. A file used at `keepUsedSince` or later is kept,
7
+ * even while the folder holds more. Only regular files directly in the
8
+ * folder count: never a link, a folder, or anything inside one. A file
9
+ * another run removes first is left to that run.
10
+ * @param {string} dir
11
+ * @param {(name: string) => boolean} counts - whether a file name counts
12
+ * @param {{limit?: number, keepUsedSince?: number, lastUse?: (stat: fs.Stats) => number}} [options]
13
+ */
14
+ export function evictOldest(dir: string, counts: (name: string) => boolean, { limit, keepUsedSince, lastUse, }?: {
15
+ limit?: number;
16
+ keepUsedSince?: number;
17
+ lastUse?: (stat: fs.Stats) => number;
18
+ }): void;
19
+ /** The most a cache folder holds; the oldest files go first past it. */
20
+ export const CACHE_LIMIT_BYTES: number;
21
+ import * as fs from 'node:fs';
@@ -0,0 +1,73 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Keeps a per-user cache folder within its size limit: the oldest files
5
+ * go first.
6
+ * @input A cache folder, and which of its files count.
7
+ * @output `CACHE_LIMIT_BYTES`, the most a cache folder holds, and
8
+ * `evictOldest(dir, counts)`, which deletes the folder's oldest counted
9
+ * files until it holds at most that.
10
+ * @position Used by gather-cache.mjs for the kept catalogs and by
11
+ * jiti-cache.mjs for jiti's transpiled code. Each folder has its own limit
12
+ * of this size.
13
+ */
14
+
15
+ import * as fs from 'node:fs';
16
+ import * as path from 'node:path';
17
+
18
+ /** The most a cache folder holds; the oldest files go first past it. */
19
+ export const CACHE_LIMIT_BYTES = 64 * 1024 * 1024;
20
+
21
+ /**
22
+ * When a file was last used, by default its last write (a kept catalog is
23
+ * written again when it is read back).
24
+ * @param {fs.Stats} stat
25
+ * @returns {number}
26
+ */
27
+ const lastWrite = stat => stat.mtimeMs;
28
+
29
+ /**
30
+ * Delete the folder's counted files, least recently used first, until they
31
+ * hold at most `limit` bytes. A file used at `keepUsedSince` or later is kept,
32
+ * even while the folder holds more. Only regular files directly in the
33
+ * folder count: never a link, a folder, or anything inside one. A file
34
+ * another run removes first is left to that run.
35
+ * @param {string} dir
36
+ * @param {(name: string) => boolean} counts - whether a file name counts
37
+ * @param {{limit?: number, keepUsedSince?: number, lastUse?: (stat: fs.Stats) => number}} [options]
38
+ */
39
+ export function evictOldest(
40
+ dir,
41
+ counts,
42
+ {
43
+ limit = CACHE_LIMIT_BYTES,
44
+ keepUsedSince = Infinity,
45
+ lastUse = lastWrite,
46
+ } = {},
47
+ ) {
48
+ const entries = fs
49
+ .readdirSync(dir)
50
+ .filter(counts)
51
+ .map(name => {
52
+ const entry = path.join(dir, name);
53
+ try {
54
+ const stat = fs.lstatSync(entry);
55
+ if (!stat.isFile()) return null;
56
+ return {entry, size: stat.size, used: lastUse(stat)};
57
+ } catch {
58
+ return null;
59
+ }
60
+ })
61
+ .filter(e => e != null)
62
+ .sort((a, b) => a.used - b.used);
63
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
64
+ for (const {entry, size, used} of entries) {
65
+ if (total <= limit || used >= keepUsedSince) break;
66
+ try {
67
+ fs.unlinkSync(entry);
68
+ total -= size;
69
+ } catch {
70
+ // Another run removed it.
71
+ }
72
+ }
73
+ }
@@ -92,6 +92,26 @@ export function persistedDerived<T, E>(key: unknown[], compute: () => T, codec:
92
92
  decode: (stored: E) => T;
93
93
  valid?: (value: T) => boolean;
94
94
  }, inputs?: string[]): T;
95
+ /**
96
+ * A summary of files and folders, made at once, kept as an entry beside the
97
+ * gathers, in or out of a recorded run: the stored value while every path
98
+ * `make` stamped has the stamp it was stored with, else the one `make` gives
99
+ * now, which is stored unless a stamp is younger than
100
+ * {@link SUMMARY_SETTLE_MS}. The folder, the build id, the Yarn Plug'n'Play
101
+ * rule, the 0600 rename write and the eviction are those of a kept gather;
102
+ * anywhere a gather is not kept, or on any read or write error, `make` runs
103
+ * as before.
104
+ * @template T
105
+ * @param {unknown[]} key - Everything else the summary depends on.
106
+ * @param {() => {value: T, stamps: [string, string][]}} make - The summary,
107
+ * with the stamp ({@link fileStamp}) of each path it depends on, each taken
108
+ * before the path was read.
109
+ * @returns {T}
110
+ */
111
+ export function persistedSummary<T>(key: unknown[], make: () => {
112
+ value: T;
113
+ stamps: [string, string][];
114
+ }): T;
95
115
  /**
96
116
  * Whether this run is under Yarn Plug'n'Play's loader (`yarn astryx` in a PnP
97
117
  * project): Node's module hooks hand PnP's resolver options it refuses, so
@@ -103,16 +123,17 @@ export function runsUnderPnp(): boolean;
103
123
  /**
104
124
  * The cache folder and how much it holds, for `doctor`: null when the CLI
105
125
  * keeps no gathers (a checkout) or has no usable folder.
106
- * @returns {{dir: string, bytes: number, entries: number, pnp: boolean} | null}
107
- * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp)
126
+ * @returns {{dir: string, bytes: number, entries: number, pnp: boolean, limitBytes: number, jitiDir: string} | null}
127
+ * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp);
128
+ * `limitBytes`: the most the folder, and jiti's folder `jitiDir`, holds
108
129
  */
109
130
  export function gatherCacheSummary(): {
110
131
  dir: string;
111
132
  bytes: number;
112
133
  entries: number;
113
134
  pnp: boolean;
135
+ limitBytes: number;
136
+ jitiDir: string;
114
137
  } | null;
115
138
  /** Where `prepack` writes the id of the package's exact contents. */
116
139
  export const BUILD_ID_FILE: string;
117
- /** The most the folder holds; the oldest entries go first past it. */
118
- export const CACHE_LIMIT_BYTES: number;
@@ -17,13 +17,21 @@
17
17
  * integration's contribution-check results and the whole list (with the
18
18
  * template and component replacement passes), which `component`,
19
19
  * `template`, `theme`, `discover` and `search` report, by template
20
- * discovery (foundation/discovery/template-adapter.mjs) for its records, by theme discovery
21
- * (foundation/discovery/theme-discovery.mjs) for each integration's themes,
22
- * and by `doctor` (api/doctor/_adapter.mjs) for its file-only docs checks,
23
- * in a run that records modules and variables to its end. The commands
24
- * whose runs keep these entries are `search`, `build`, `component`,
25
- * `template`, `theme`, `discover`, `docs` and `doctor`. Gathers are kept only once the folder exists: the first such run
26
- * on a machine just makes it, so a one-off run pays nothing to store one. Only a published CLI stores anything:
20
+ * discovery (foundation/discovery/template-adapter.mjs) for its records, by
21
+ * the component list (api/component/list/list.mjs) and component
22
+ * replacement (foundation/discovery/component-replacement.mjs), by theme
23
+ * discovery (foundation/discovery/theme-discovery.mjs) for each
24
+ * integration's themes,
25
+ * by `doctor` (api/doctor/_adapter.mjs) for its file-only docs checks and
26
+ * its theme-wiring scan,
27
+ * in a run that records modules and variables to its end, and, through
28
+ * `persistedSummary`, by kept-tree.mjs for the docs not-found hint's
29
+ * summaries of folder trees, each kept while every path it stamped is
30
+ * unchanged, in any command. The commands whose runs keep the other
31
+ * entries are `search`, `build`, `component`, `template`, `theme`,
32
+ * `discover`, `docs` and `doctor`. The first such run on a machine makes the
33
+ * folder and keeps its gathers at once, so the next run (most often the same
34
+ * session's next command) uses them; doctor never makes it. Only a published CLI stores anything:
27
35
  * its build id (clients/cli/build-id.generated.json, written at `prepack`)
28
36
  * names its exact code, so a checkout, whose code may change between runs
29
37
  * under the same version, always gathers.
@@ -31,7 +39,7 @@
31
39
  * The folder is `catalogs` in the user's cache folder (userCacheDir):
32
40
  * created 0700, used only while it is a real folder owned by the user and
33
41
  * closed to others (isPrivateDir; never on a system with no user ids), each file written 0600 by a rename, oldest first evicted past
34
- * CACHE_LIMIT_BYTES. Any failure to read, check, parse or write is silent
42
+ * CACHE_LIMIT_BYTES (cache-eviction.mjs). Any failure to read, check, parse or write is silent
35
43
  * and the run gathers fresh, as it would with no cache.
36
44
  */
37
45
 
@@ -47,6 +55,7 @@ import {mayHaveIntegrations} from '../integrations/may-have-integrations.mjs';
47
55
  import {currentUid, isPrivateDir} from '../env/private-dir.mjs';
48
56
  import {userCacheDir} from '../env/user-dirs.mjs';
49
57
  import {jitiCacheDir} from './jiti-cache.mjs';
58
+ import {CACHE_LIMIT_BYTES, evictOldest} from './cache-eviction.mjs';
50
59
  import {
51
60
  fileStamp,
52
61
  recordReads,
@@ -78,7 +87,8 @@ const KEPT_COMMANDS = new Set([
78
87
  'theme',
79
88
  'discover',
80
89
  'docs',
81
- // The project check alone (no subcommand): its docs checks are kept.
90
+ // The project check alone (no subcommand): its docs checks and theme-wiring
91
+ // scan are kept.
82
92
  'doctor',
83
93
  ]);
84
94
 
@@ -90,8 +100,12 @@ export const BUILD_ID_FILE = path.join(
90
100
  'build-id.generated.json',
91
101
  );
92
102
 
93
- /** The most the folder holds; the oldest entries go first past it. */
94
- export const CACHE_LIMIT_BYTES = 64 * 1024 * 1024;
103
+ /**
104
+ * Whether a file in the folder is a kept entry, which eviction counts.
105
+ * @param {string} name
106
+ * @returns {boolean}
107
+ */
108
+ const isEntry = name => name.startsWith('gather-');
95
109
 
96
110
  /** The stored format; a different one is a miss. */
97
111
  const FORMAT = 1;
@@ -254,9 +268,8 @@ export async function recordRunFor(argv, fn) {
254
268
  ) {
255
269
  return fn();
256
270
  }
257
- // Gathers are kept only once the folder exists: the first recorded run on a
258
- // machine (search, build, component, template, theme, discover or docs) just makes
259
- // it, so a one-off run never pays to store one.
271
+ // The first recorded run on a machine (search, build, component, template,
272
+ // theme, discover or docs) makes the folder and keeps its gathers at once.
260
273
  const dir = cacheDirPath();
261
274
  if (!withoutRecording(() => fs.existsSync(dir))) {
262
275
  // Once the per-user cache folder exists doctor uses it; it never makes
@@ -267,8 +280,8 @@ export async function recordRunFor(argv, fn) {
267
280
  withoutRecording(() => fs.mkdirSync(dir, {recursive: true, mode: 0o700}));
268
281
  } catch {
269
282
  // A folder that cannot be made keeps no catalogs; nothing more.
283
+ return fn();
270
284
  }
271
- return fn();
272
285
  }
273
286
  // A folder the cache would refuse (not the user's own, open to others, a
274
287
  // link) leaves the run exactly as without the cache: no hook is installed.
@@ -744,7 +757,7 @@ export function persistedDerived(key, compute, codec, inputs = []) {
744
757
  const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
745
758
  fs.writeFileSync(temp, text, {mode: 0o600, flag: 'wx'});
746
759
  fs.renameSync(temp, file);
747
- evict(dir);
760
+ evictOldest(dir, isEntry);
748
761
  } catch {
749
762
  // A value that cannot be stored is computed again next time.
750
763
  }
@@ -752,6 +765,102 @@ export function persistedDerived(key, compute, codec, inputs = []) {
752
765
  return value;
753
766
  }
754
767
 
768
+ /**
769
+ * How old every stamped time must be before a summary is stored. A file
770
+ * system can store times as coarsely as 2 s, so a change within one tick of
771
+ * the last can leave a stamp as it was.
772
+ */
773
+ const SUMMARY_SETTLE_MS = 2000;
774
+
775
+ /**
776
+ * Whether every stamp in `stamps` was taken longer than
777
+ * {@link SUMMARY_SETTLE_MS} ago, by its modification and change times.
778
+ * @param {[string, string][]} stamps
779
+ * @returns {boolean}
780
+ */
781
+ function settled(stamps) {
782
+ const limit = Date.now() - SUMMARY_SETTLE_MS;
783
+ return stamps.every(([, stamp]) => {
784
+ if (stamp === '-') return true;
785
+ const [, mtime, ctime] = stamp.split(':').map(Number);
786
+ return mtime < limit && ctime < limit;
787
+ });
788
+ }
789
+
790
+ /**
791
+ * A summary of files and folders, made at once, kept as an entry beside the
792
+ * gathers, in or out of a recorded run: the stored value while every path
793
+ * `make` stamped has the stamp it was stored with, else the one `make` gives
794
+ * now, which is stored unless a stamp is younger than
795
+ * {@link SUMMARY_SETTLE_MS}. The folder, the build id, the Yarn Plug'n'Play
796
+ * rule, the 0600 rename write and the eviction are those of a kept gather;
797
+ * anywhere a gather is not kept, or on any read or write error, `make` runs
798
+ * as before.
799
+ * @template T
800
+ * @param {unknown[]} key - Everything else the summary depends on.
801
+ * @param {() => {value: T, stamps: [string, string][]}} make - The summary,
802
+ * with the stamp ({@link fileStamp}) of each path it depends on, each taken
803
+ * before the path was read.
804
+ * @returns {T}
805
+ */
806
+ export function persistedSummary(key, make) {
807
+ const id = withoutRecording(buildId);
808
+ const dir =
809
+ id == null || runsUnderPnp() ? null : withoutRecording(gatherCacheDir);
810
+ if (id == null || dir == null) return make().value;
811
+ const summaryKey = ['summary', ...key];
812
+ const file = entryFile(dir, summaryKey, id);
813
+ const entry = entryKey(summaryKey, id);
814
+ try {
815
+ const stored = JSON.parse(
816
+ withoutRecording(() => fs.readFileSync(file, 'utf-8')),
817
+ );
818
+ if (
819
+ stored?.format === FORMAT &&
820
+ stored.summary === true &&
821
+ stored.key === entry &&
822
+ Object.hasOwn(stored, 'value') &&
823
+ Array.isArray(stored.stamps) &&
824
+ stored.stamps.every(
825
+ (/** @type {[string, string]} */ [at, stamp]) =>
826
+ typeof at === 'string' && fileStamp(at) === stamp,
827
+ )
828
+ ) {
829
+ try {
830
+ const now = new Date();
831
+ withoutRecording(() => fs.utimesSync(file, now, now));
832
+ } catch {
833
+ // An entry that cannot be touched is evicted sooner; nothing more.
834
+ }
835
+ return stored.value;
836
+ }
837
+ } catch {
838
+ // No usable entry: made below.
839
+ }
840
+ const {value, stamps} = make();
841
+ if (settled(stamps)) {
842
+ withoutRecording(() => {
843
+ try {
844
+ const text = JSON.stringify({
845
+ format: FORMAT,
846
+ summary: true,
847
+ key: entry,
848
+ stamps,
849
+ value,
850
+ });
851
+ if (!isDeepStrictEqual(JSON.parse(text).value, value)) return;
852
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
853
+ fs.writeFileSync(temp, text, {mode: 0o600, flag: 'wx'});
854
+ fs.renameSync(temp, file);
855
+ evictOldest(dir, isEntry);
856
+ } catch {
857
+ // A summary that cannot be stored is made again next time.
858
+ }
859
+ });
860
+ }
861
+ return value;
862
+ }
863
+
755
864
  /**
756
865
  * A stored entry's value, decoded, or undefined when it has none, its decode
757
866
  * throws, or the decoded value fails the codec's shape check (`valid`): such
@@ -798,43 +907,12 @@ function store(dir, file, entry, value, codec) {
798
907
  const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
799
908
  fs.writeFileSync(temp, text, {mode: 0o600, flag: 'wx'});
800
909
  fs.renameSync(temp, file);
801
- evict(dir);
910
+ evictOldest(dir, isEntry);
802
911
  } catch {
803
912
  // A gather that cannot be stored is gathered again next time.
804
913
  }
805
914
  }
806
915
 
807
- /**
808
- * Delete the oldest entries until the folder holds at most CACHE_LIMIT_BYTES.
809
- * @param {string} dir
810
- */
811
- function evict(dir) {
812
- const entries = fs
813
- .readdirSync(dir)
814
- .filter(name => name.startsWith('gather-'))
815
- .map(name => {
816
- const entry = path.join(dir, name);
817
- try {
818
- const {size, mtimeMs} = fs.statSync(entry);
819
- return {entry, size, mtimeMs};
820
- } catch {
821
- return null;
822
- }
823
- })
824
- .filter(e => e != null)
825
- .sort((a, b) => a.mtimeMs - b.mtimeMs);
826
- let total = entries.reduce((sum, e) => sum + e.size, 0);
827
- for (const {entry, size} of entries) {
828
- if (total <= CACHE_LIMIT_BYTES) break;
829
- try {
830
- fs.unlinkSync(entry);
831
- total -= size;
832
- } catch {
833
- // Another run removed it.
834
- }
835
- }
836
- }
837
-
838
916
  /**
839
917
  * Whether this run is under Yarn Plug'n'Play's loader (`yarn astryx` in a PnP
840
918
  * project): Node's module hooks hand PnP's resolver options it refuses, so
@@ -849,15 +927,16 @@ export function runsUnderPnp() {
849
927
  /**
850
928
  * The cache folder and how much it holds, for `doctor`: null when the CLI
851
929
  * keeps no gathers (a checkout) or has no usable folder.
852
- * @returns {{dir: string, bytes: number, entries: number, pnp: boolean} | null}
853
- * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp)
930
+ * @returns {{dir: string, bytes: number, entries: number, pnp: boolean, limitBytes: number, jitiDir: string} | null}
931
+ * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp);
932
+ * `limitBytes`: the most the folder, and jiti's folder `jitiDir`, holds
854
933
  */
855
934
  export function gatherCacheSummary() {
856
935
  // The cache's own bookkeeping, never an input of what it keeps.
857
936
  return withoutRecording(summarize);
858
937
  }
859
938
 
860
- /** @returns {{dir: string, bytes: number, entries: number, pnp: boolean} | null} */
939
+ /** @returns {{dir: string, bytes: number, entries: number, pnp: boolean, limitBytes: number, jitiDir: string} | null} */
861
940
  function summarize() {
862
941
  if (buildId() == null) return null;
863
942
  const dir = gatherCacheDir();
@@ -877,5 +956,12 @@ function summarize() {
877
956
  } catch {
878
957
  return null;
879
958
  }
880
- return {dir, bytes, entries, pnp: runsUnderPnp()};
959
+ return {
960
+ dir,
961
+ bytes,
962
+ entries,
963
+ pnp: runsUnderPnp(),
964
+ limitBytes: CACHE_LIMIT_BYTES,
965
+ jitiDir: jitiCacheDir(),
966
+ };
881
967
  }
@@ -9,7 +9,8 @@ export function jitiCacheDir(): string;
9
9
  /**
10
10
  * The `fsCache` option for a jiti loader: the per-user folder, made (0700)
11
11
  * on first use and used at once, while it is a real folder the user owns and
12
- * no one else can reach (the kept catalogs' check). A folder that fails the
12
+ * no one else can reach (the kept catalogs' check), kept within its size
13
+ * limit (keepWithinLimit). A folder that fails the
13
14
  * check, or cannot be made, is not used and nothing is cached on disk. Where
14
15
  * the system has no user ids (Windows) ownership cannot be checked, and jiti
15
16
  * keeps its default, the user's own temp folder there. Worked out once per
@@ -19,3 +20,20 @@ export function jitiCacheDir(): string;
19
20
  export function jitiCacheOptions(): {
20
21
  fsCache?: string | false;
21
22
  };
23
+ /**
24
+ * Whether a file in the folder is a copy jiti wrote, the only files the size
25
+ * limit removes.
26
+ * @param {string} name
27
+ * @returns {boolean}
28
+ */
29
+ export function isTranspiledCopy(name: string): boolean;
30
+ /**
31
+ * Keep the folder within `limit` bytes, least recently used copies first,
32
+ * never one used within RECENT_USE_MS. The folder's time moves only when a
33
+ * file is made or removed, which is the only way the folder grows (jiti
34
+ * writes an edited source's code over its old file), so a run whose folder
35
+ * time matches the last check reads no more than that.
36
+ * @param {string} dir
37
+ * @param {number} [limit]
38
+ */
39
+ export function keepWithinLimit(dir: string, limit?: number): void;