@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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 (203) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -0,0 +1,783 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A gathered catalog kept between runs, so a run whose inputs are
5
+ * unchanged skips gathering.
6
+ *
7
+ * @input `recordRunFor(argv, run)` around a whole run; `persistedGather(key,
8
+ * load, codec)` around one gather inside it.
9
+ * @output The value the gather returns. A run that asks again with the same
10
+ * key gets the stored value only when every file and folder the first run
11
+ * read (from its start to the end of its gather), every module it loaded,
12
+ * and every environment variable it read are as they were; otherwise it
13
+ * gathers fresh and stores that.
14
+ * @position Used by search's adapter (api/search/_adapter.mjs) for the
15
+ * catalog `search` and `build` rank, and by the project
16
+ * (foundation/config/project.mjs) for each integration's contribution-check
17
+ * results, which `component`, `template`, `theme`, `discover` and `search`
18
+ * report. Gathers are kept only once the folder exists: the first such run
19
+ * on a machine just makes it, so a one-off run pays nothing to store one. Only a published CLI stores anything:
20
+ * its build id (clients/cli/build-id.generated.json, written at `prepack`)
21
+ * names its exact code, so a checkout, whose code may change between runs
22
+ * under the same version, always gathers.
23
+ *
24
+ * The folder is `catalogs` in the user's cache folder (userCacheDir):
25
+ * created 0700, used only while it is a real folder owned by the user and
26
+ * closed to others (isPrivateDir; never on a system with no user ids), each file written 0600 by a rename, oldest first evicted past
27
+ * CACHE_LIMIT_BYTES. Any failure to read, check, parse or write is silent
28
+ * and the run gathers fresh, as it would with no cache.
29
+ */
30
+
31
+ import {createHash} from 'node:crypto';
32
+ import * as fs from 'node:fs';
33
+ import * as nodeModule from 'node:module';
34
+ import * as os from 'node:os';
35
+ import * as path from 'node:path';
36
+ import {fileURLToPath} from 'node:url';
37
+ import {isDeepStrictEqual} from 'node:util';
38
+ import {CLI_ROOT} from './paths.mjs';
39
+ import {mayHaveIntegrations} from '../integrations/may-have-integrations.mjs';
40
+ import {currentUid, isPrivateDir} from '../env/private-dir.mjs';
41
+ import {userCacheDir} from '../env/user-dirs.mjs';
42
+ import {jitiCacheDir} from './jiti-cache.mjs';
43
+ import {
44
+ fileStamp,
45
+ recordReads,
46
+ recordStates,
47
+ stillInState,
48
+ withoutRecording,
49
+ } from './read-record.mjs';
50
+
51
+ /**
52
+ * The kept commands whose only kept gather is their integrations' check
53
+ * results: a project with no integration records none of them.
54
+ */
55
+ const INTEGRATION_COMMANDS = new Set([
56
+ 'component',
57
+ 'template',
58
+ 'theme',
59
+ 'discover',
60
+ ]);
61
+
62
+ /** The run's commands whose gathers are kept. */
63
+ const KEPT_COMMANDS = new Set([
64
+ 'search',
65
+ 'build',
66
+ 'component',
67
+ 'template',
68
+ 'theme',
69
+ 'discover',
70
+ ]);
71
+
72
+ /** Where `prepack` writes the id of the package's exact contents. */
73
+ export const BUILD_ID_FILE = path.join(
74
+ CLI_ROOT,
75
+ 'clients',
76
+ 'cli',
77
+ 'build-id.generated.json',
78
+ );
79
+
80
+ /** The most the folder holds; the oldest entries go first past it. */
81
+ export const CACHE_LIMIT_BYTES = 64 * 1024 * 1024;
82
+
83
+ /** The stored format; a different one is a miss. */
84
+ const FORMAT = 1;
85
+
86
+ /** A variable the run read that was unset, as stored. */
87
+ const UNSET = null;
88
+
89
+ /**
90
+ * What the running command has read since it started: files and folders with
91
+ * their states, modules it loaded with theirs, and environment variables with
92
+ * their values. Files and folders are recorded for the whole run; modules and
93
+ * variables only while the run is armed: from its start to the end of its
94
+ * first gather, and during each later gather. Null outside a recorded run.
95
+ * @type {{reads: Map<string, string>, env: Map<string, string | null>, arm: () => boolean, disarm: () => void} | null}
96
+ */
97
+ let run = null;
98
+
99
+ /**
100
+ * The running recorded run's reads and variables, for tests: null outside one.
101
+ * @returns {{reads: Map<string, string>, env: Map<string, string | null>} | null}
102
+ */
103
+ export function recordedRun() {
104
+ return run && {reads: run.reads, env: run.env};
105
+ }
106
+
107
+ /** Why the last persisted gather in this process hit or missed. */
108
+ /** @type {{hit: boolean, reason: string} | null} */
109
+ let lastOutcome = null;
110
+
111
+ /**
112
+ * The states of the CLI's own files that the run's kept gather depends on:
113
+ * those it was stored with and that a hit has just found unchanged, or those
114
+ * a fresh gather was stored with. A derived value keys on them, so an edit to
115
+ * the CLI's code in an installed copy, which misses the gather, misses the
116
+ * derived value too. Null before any kept gather in the run.
117
+ * @type {[string, string][] | null}
118
+ */
119
+ let gatherCode = null;
120
+
121
+ /** How many persistedGather calls are running, nested inside one another. */
122
+ let gatherDepth = 0;
123
+
124
+ /**
125
+ * The outcome of the last kept gather in this process: whether it was a hit,
126
+ * and why it missed. Null when no kept gather ran.
127
+ * @returns {{hit: boolean, reason: string} | null}
128
+ */
129
+ export function gatherCacheOutcome() {
130
+ return lastOutcome;
131
+ }
132
+
133
+ /**
134
+ * Whether a path is in jiti's transpile cache, where the first load of each
135
+ * TypeScript integration file writes its compiled copy. That copy follows its
136
+ * source, whose content is a stamp of its own, so the cache never decides an
137
+ * answer; stamping it would only make the run after a cache fill miss.
138
+ * @param {string} file
139
+ * @returns {boolean}
140
+ */
141
+ function inJitiCache(file) {
142
+ jitiRoots ??= jitiCacheRoots();
143
+ return jitiRoots.some(
144
+ root => file === root || file.startsWith(root + path.sep),
145
+ );
146
+ }
147
+
148
+ /** jiti's cache folders, worked out once per process (inJitiCache). */
149
+ /** @type {string[] | undefined} */
150
+ let jitiRoots;
151
+
152
+ /**
153
+ * Where jiti may keep transpiled code: the system temp folder's `jiti`, the
154
+ * per-user folder (jiti-cache.mjs), and a set JITI_FS_CACHE.
155
+ * @returns {string[]}
156
+ */
157
+ function jitiCacheRoots() {
158
+ const env = process.env.JITI_FS_CACHE;
159
+ const roots = [path.join(os.tmpdir(), 'jiti'), jitiCacheDir()];
160
+ if (env && env !== 'false' && env !== 'true' && env !== '0' && env !== '1') {
161
+ roots.push(path.resolve(env));
162
+ }
163
+ return roots;
164
+ }
165
+
166
+ /**
167
+ * The published package's build id, or null in a checkout.
168
+ * @returns {string | null}
169
+ */
170
+ function buildId() {
171
+ // Only an installed package keeps catalogs: one in a node_modules folder,
172
+ // where its files stay as published. A checkout's code changes as it is
173
+ // edited, and a build id a local pack left there would not follow.
174
+ if (!CLI_ROOT.split(path.sep).includes('node_modules')) return null;
175
+ try {
176
+ const id = JSON.parse(fs.readFileSync(BUILD_ID_FILE, 'utf-8')).id;
177
+ return typeof id === 'string' && id.length > 0 ? id : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Where the kept catalogs live: a folder of their own in the user's cache
185
+ * folder.
186
+ * @returns {string}
187
+ */
188
+ function cacheDirPath() {
189
+ return path.join(userCacheDir(), 'catalogs');
190
+ }
191
+
192
+ /**
193
+ * The kept catalogs' folder, or null when it is missing or cannot be used:
194
+ * not a real folder, owned by someone else, open to others, or on a system
195
+ * with no user ids, where ownership cannot be checked (see isPrivateDir).
196
+ * @returns {string | null}
197
+ */
198
+ export function gatherCacheDir() {
199
+ const dir = cacheDirPath();
200
+ return isPrivateDir(dir) ? dir : null;
201
+ }
202
+
203
+ /**
204
+ * The run's first operand: the command a run of these arguments asks for.
205
+ * @param {string[]} argv
206
+ * @returns {string | undefined}
207
+ */
208
+ function commandOf(argv) {
209
+ return argv.find(arg => !arg.startsWith('-'));
210
+ }
211
+
212
+ /**
213
+ * Run `fn`, recording what it reads, when the arguments ask for a command
214
+ * whose gather is kept and the CLI can keep one. Otherwise run it as is.
215
+ * @template T
216
+ * @param {string[]} argv
217
+ * @param {() => Promise<T>} fn
218
+ * @returns {Promise<T>}
219
+ */
220
+ export async function recordRunFor(argv, fn) {
221
+ const command = commandOf(argv);
222
+ // Under Yarn Plug'n'Play, Node's module hooks hand PnP's resolver options
223
+ // it refuses, so the run keeps no catalogs and installs no hook; nor where
224
+ // the system has no user ids, as the folder's owner cannot be checked.
225
+ if (
226
+ !command ||
227
+ !KEPT_COMMANDS.has(command) ||
228
+ runsUnderPnp() ||
229
+ currentUid() == null ||
230
+ withoutRecording(buildId) == null ||
231
+ // Last, being a few file checks: those commands keep only their
232
+ // integrations' check results, so a project with none records nothing.
233
+ (INTEGRATION_COMMANDS.has(command) &&
234
+ !withoutRecording(() => mayHaveIntegrations(process.cwd())))
235
+ ) {
236
+ return fn();
237
+ }
238
+ // Gathers are kept only once the folder exists: the first recorded run on a
239
+ // machine (search, build, component, template, theme or discover) just makes
240
+ // it, so a one-off run never pays to store one.
241
+ const dir = cacheDirPath();
242
+ if (!withoutRecording(() => fs.existsSync(dir))) {
243
+ try {
244
+ withoutRecording(() => fs.mkdirSync(dir, {recursive: true, mode: 0o700}));
245
+ } catch {
246
+ // A folder that cannot be made keeps no catalogs; nothing more.
247
+ }
248
+ return fn();
249
+ }
250
+ // A folder the cache would refuse (not the user's own, open to others, a
251
+ // link) leaves the run exactly as without the cache: no hook is installed.
252
+ if (withoutRecording(gatherCacheDir) == null) return fn();
253
+ return recordRun(fn);
254
+ }
255
+
256
+ /**
257
+ * Run `fn` as a recorded run (see `run`), armed from its start. Exported for
258
+ * tests; `recordRunFor` decides which runs are recorded.
259
+ * @template T
260
+ * @param {() => Promise<T>} fn
261
+ * @returns {Promise<T>}
262
+ */
263
+ export async function recordRun(fn) {
264
+ const registerHooks = /** @type {any} */ (nodeModule).registerHooks;
265
+ if (typeof registerHooks !== 'function' || run != null) return fn();
266
+ /** @type {Map<string, string>} */
267
+ const reads = new Map();
268
+ /** @type {Map<string, string | null>} */
269
+ const env = new Map();
270
+ const realEnv = process.env;
271
+ /** @type {{deregister: () => void} | null} */
272
+ let hooks = null;
273
+ /** @param {string | symbol} name */
274
+ const noteEnv = name => {
275
+ if (typeof name === 'string' && !env.has(name)) {
276
+ env.set(name, envState(realEnv[name]));
277
+ }
278
+ };
279
+ const proxy = new Proxy(realEnv, {
280
+ get(target, name) {
281
+ noteEnv(name);
282
+ return Reflect.get(target, name);
283
+ },
284
+ has(target, name) {
285
+ noteEnv(name);
286
+ return Reflect.has(target, name);
287
+ },
288
+ getOwnPropertyDescriptor(target, name) {
289
+ noteEnv(name);
290
+ return Reflect.getOwnPropertyDescriptor(target, name);
291
+ },
292
+ ownKeys(target) {
293
+ if (!env.has('\0names')) env.set('\0names', envState(namesOf(target)));
294
+ return Reflect.ownKeys(target);
295
+ },
296
+ });
297
+ const disarm = () => {
298
+ try {
299
+ hooks?.deregister();
300
+ } catch {
301
+ // A hook that cannot be removed is inert: it only notes modules.
302
+ }
303
+ hooks = null;
304
+ if (process.env === proxy) process.env = realEnv;
305
+ };
306
+ const arm = () => {
307
+ if (hooks) return true;
308
+ try {
309
+ hooks = registerHooks({
310
+ /**
311
+ * @param {string} url
312
+ * @param {any} context
313
+ * @param {(url: string, context: any) => any} next
314
+ */
315
+ /**
316
+ * @param {string} specifier
317
+ * @param {any} context
318
+ * @param {(specifier: string, context: any) => any} next
319
+ */
320
+ resolve(specifier, context, next) {
321
+ if (hooks) noteLookups(specifier, context?.parentURL, reads);
322
+ return next(specifier, context);
323
+ },
324
+ /**
325
+ * @param {string} url
326
+ * @param {any} context
327
+ * @param {(url: string, context: any) => any} next
328
+ */
329
+ load(url, context, next) {
330
+ if (hooks && url.startsWith('file:')) {
331
+ try {
332
+ const file = fileURLToPath(url);
333
+ if (!reads.has(file)) reads.set(file, fileStamp(file));
334
+ } catch {
335
+ // A URL with no file path holds nothing to check.
336
+ }
337
+ }
338
+ return next(url, context);
339
+ },
340
+ });
341
+ process.env = proxy;
342
+ return true;
343
+ } catch {
344
+ disarm();
345
+ return false;
346
+ }
347
+ };
348
+ if (!arm()) return fn();
349
+ run = {reads, env, arm, disarm};
350
+ try {
351
+ return await recordReads(reads, fn, {exact: true});
352
+ } finally {
353
+ disarm();
354
+ run = null;
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Note where Node looks for a bare import, as it looks: `node_modules/<name>`
360
+ * in the importing file's folder and in each folder above it, each with its
361
+ * state now (absent included), so a package added to or removed from any of
362
+ * them later is a change.
363
+ * @param {string} specifier
364
+ * @param {string | undefined} parentURL
365
+ * @param {Map<string, string>} reads
366
+ */
367
+ function noteLookups(specifier, parentURL, reads) {
368
+ if (
369
+ !parentURL?.startsWith('file:') ||
370
+ /^(?:\.|\/|[a-z][a-z0-9+.-]*:)/i.test(specifier) ||
371
+ nodeModule.isBuiltin(specifier)
372
+ ) {
373
+ return;
374
+ }
375
+ const parts = specifier.split('/');
376
+ const name = specifier.startsWith('@')
377
+ ? parts.slice(0, 2).join('/')
378
+ : parts[0];
379
+ try {
380
+ let dir = path.dirname(fileURLToPath(parentURL));
381
+ for (;;) {
382
+ if (path.basename(dir) !== 'node_modules') {
383
+ const candidate = path.join(dir, 'node_modules', name);
384
+ if (!reads.has(candidate)) reads.set(candidate, lookupStamp(candidate));
385
+ }
386
+ const up = path.dirname(dir);
387
+ if (up === dir) break;
388
+ dir = up;
389
+ }
390
+ } catch {
391
+ // A parent with no file path has nothing to look up.
392
+ }
393
+ }
394
+
395
+ /**
396
+ * A looked-up package folder's state: its identity when it is there, as a
397
+ * probe records it (see read-record.mjs), or absent.
398
+ * @param {string} folder
399
+ * @returns {string}
400
+ */
401
+ function lookupStamp(folder) {
402
+ try {
403
+ const stat = fs.statSync(folder, {throwIfNoEntry: false});
404
+ return stat ? `dir:${stat.ino}` : '-';
405
+ } catch {
406
+ return '-';
407
+ }
408
+ }
409
+
410
+ /**
411
+ * How an environment variable the run read is kept: a digest of its value,
412
+ * never the value (it can be a token), or UNSET when it was not set.
413
+ * @param {unknown} value
414
+ * @returns {string | null}
415
+ */
416
+ function envState(value) {
417
+ // Only a set variable has a value; a name such as `toString` reads a
418
+ // function from Object.prototype, which is no variable.
419
+ if (typeof value !== 'string') return UNSET;
420
+ return createHash('sha256').update(value).digest('hex').slice(0, 32);
421
+ }
422
+
423
+ /**
424
+ * Every environment variable's name, sorted and joined, standing for a read of
425
+ * the whole environment.
426
+ * @param {NodeJS.ProcessEnv} env
427
+ * @returns {string}
428
+ */
429
+ function namesOf(env) {
430
+ return Object.keys(env).sort().join('\0');
431
+ }
432
+
433
+ /**
434
+ * The entry's file in the folder, for a key.
435
+ * @param {string} dir
436
+ * @param {unknown[]} key
437
+ * @param {string} id
438
+ * @returns {string}
439
+ */
440
+ function entryFile(dir, key, id) {
441
+ const hash = createHash('sha256')
442
+ .update(entryKey(key, id))
443
+ .digest('hex')
444
+ .slice(0, 40);
445
+ return path.join(dir, `gather-${hash}.json`);
446
+ }
447
+
448
+ /**
449
+ * Everything an entry is for, as text: stored in the entry and compared on
450
+ * every read, so an entry copied under another entry's name is not used.
451
+ * @param {unknown[]} key
452
+ * @param {string} id
453
+ * @returns {string}
454
+ */
455
+ function entryKey(key, id) {
456
+ return JSON.stringify([
457
+ FORMAT,
458
+ id,
459
+ process.version,
460
+ process.platform,
461
+ process.arch,
462
+ ...key,
463
+ ]);
464
+ }
465
+
466
+ /**
467
+ * Whether every stored state still holds: files, folders and modules, and the
468
+ * environment.
469
+ * @param {[string, string][]} stamps
470
+ * @param {[string, string | null][]} env
471
+ * @returns {string | null} why not, or null when all hold
472
+ */
473
+ function staleReason(stamps, env) {
474
+ for (const [name, value] of env) {
475
+ const current = envState(
476
+ name === '\0names' ? namesOf(process.env) : process.env[name],
477
+ );
478
+ if (current !== value) {
479
+ return name === '\0names'
480
+ ? 'the environment has other variables'
481
+ : 'an environment variable it read changed';
482
+ }
483
+ }
484
+ for (const [file, state] of stamps) {
485
+ if (!stillInState(file, state)) return 'a file or folder it read changed';
486
+ }
487
+ return null;
488
+ }
489
+
490
+ /**
491
+ * The gather `load` returns, or the one a run with the same key stored while
492
+ * every input it read is unchanged (see the file header).
493
+ * @template T, E
494
+ * @param {unknown[]} key - What else decides the gather: its folder (a real
495
+ * path) and options.
496
+ * @param {() => Promise<T>} load
497
+ * @param {{encode: (value: T) => E, decode: (stored: E) => T}} codec - A
498
+ * plain-JSON form of the value and back.
499
+ * @param {(value: T) => boolean} [keep] whether a fresh gather may be
500
+ * stored: one that depends on something its stamps cannot see (a retry
501
+ * that waits on time) is used for this run only
502
+ * @returns {Promise<T>}
503
+ */
504
+ export async function persistedGather(key, load, codec, keep = () => true) {
505
+ // A gather inside another (an integration's checks inside search's catalog
506
+ // gather) leaves the run's recording to the outermost: only it disarms, so
507
+ // what the outer gather reads after the inner one is still stamped.
508
+ gatherDepth++;
509
+ try {
510
+ return await gatherAt(key, load, codec, keep);
511
+ } finally {
512
+ if (--gatherDepth === 0) run?.disarm();
513
+ }
514
+ }
515
+
516
+ /**
517
+ * persistedGather's body; the caller disarms the run's recording once the
518
+ * outermost gather is done.
519
+ * @template T, E
520
+ * @param {unknown[]} key
521
+ * @param {() => Promise<T>} load
522
+ * @param {{encode: (value: T) => E, decode: (stored: E) => T}} codec
523
+ * @param {(value: T) => boolean} keep
524
+ * @returns {Promise<T>}
525
+ */
526
+ async function gatherAt(key, load, codec, keep) {
527
+ const id = withoutRecording(buildId);
528
+ // A run under Yarn Plug'n'Play's loader neither keeps nor reads catalogs:
529
+ // its modules resolve through PnP, which a catalog's stamps do not follow.
530
+ const dir =
531
+ id == null || runsUnderPnp() ? null : withoutRecording(gatherCacheDir);
532
+ if (id == null || dir == null) {
533
+ lastOutcome = {
534
+ hit: false,
535
+ reason:
536
+ id == null
537
+ ? 'this CLI has no build id'
538
+ : runsUnderPnp()
539
+ ? "a run under Yarn Plug'n'Play's loader"
540
+ : 'no usable cache folder',
541
+ };
542
+ return await load();
543
+ }
544
+ const file = entryFile(dir, key, id);
545
+ let reason = 'no entry';
546
+ try {
547
+ const stored = JSON.parse(
548
+ withoutRecording(() => fs.readFileSync(file, 'utf-8')),
549
+ );
550
+ if (stored?.format !== FORMAT) {
551
+ reason = 'another format';
552
+ } else if (stored.key !== entryKey(key, id)) {
553
+ reason = 'an entry for other inputs';
554
+ } else {
555
+ const stale = staleReason(stored.stamps, stored.env);
556
+ if (stale == null) {
557
+ const value = codec.decode(stored.value);
558
+ recordStates(stored.stamps);
559
+ gatherCode = cliStates(stored.stamps);
560
+ lastOutcome = {hit: true, reason: 'unchanged'};
561
+ try {
562
+ const now = new Date();
563
+ withoutRecording(() => fs.utimesSync(file, now, now));
564
+ } catch {
565
+ // An entry that cannot be touched is evicted sooner; nothing more.
566
+ }
567
+ return value;
568
+ }
569
+ reason = stale;
570
+ }
571
+ } catch (error) {
572
+ if (/** @type {any} */ (error)?.code !== 'ENOENT')
573
+ reason = 'unreadable entry';
574
+ }
575
+ lastOutcome = {hit: false, reason};
576
+ // A later gather in the run records its modules and variables again.
577
+ const armed = run?.arm() ?? false;
578
+ const value = await load();
579
+ if (run && armed && keep(value)) {
580
+ withoutRecording(() => store(dir, file, entryKey(key, id), value, codec));
581
+ }
582
+ return value;
583
+ }
584
+
585
+ /**
586
+ * The CLI's own files among a gather's stamps: the modules it loaded and the
587
+ * files it read under the CLI's folder.
588
+ * @param {[string, string][]} stamps
589
+ * @returns {[string, string][]}
590
+ */
591
+ function cliStates(stamps) {
592
+ const root = CLI_ROOT + path.sep;
593
+ return stamps.filter(([file]) => file.startsWith(root));
594
+ }
595
+
596
+ /**
597
+ * The state of the code a derived value depends on: the CLI's own files the
598
+ * kept gather depends on (gatherCode), and each of `inputs` by its stamp now,
599
+ * in one digest.
600
+ * @param {[string, string][]} code
601
+ * @param {string[]} inputs
602
+ * @returns {string}
603
+ */
604
+ function codeStamp(code, inputs) {
605
+ const states = [...code];
606
+ for (const file of inputs) {
607
+ states.push([file, withoutRecording(() => fileStamp(file))]);
608
+ }
609
+ states.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
610
+ return createHash('sha256').update(JSON.stringify(states)).digest('hex');
611
+ }
612
+
613
+ /**
614
+ * A value derived from what a kept gather holds, kept beside the gather: it
615
+ * is a function of `key`, of the CLI's code and of `inputs` (with this CLI
616
+ * build), so a stored value is used as it is. The code is the CLI's own files
617
+ * the run's kept gather depends on (each by its stamp, so an edit misses the
618
+ * gather and the value alike), with `inputs`: the files the computation reads
619
+ * that the gather may not have, such as its own module and its weights. An
620
+ * edit to any of them in an installed copy, where the build id stays the
621
+ * same, is a new key. Kept only after a kept gather in the run (a search or
622
+ * build of an installed CLI whose cache folder exists); anywhere else, or on
623
+ * any read or write error, `compute` runs as before.
624
+ * @template T, E
625
+ * @param {unknown[]} key - Everything the value is computed from.
626
+ * @param {() => T} compute
627
+ * @param {{encode: (value: T) => E, decode: (stored: E) => T}} codec
628
+ * @param {string[]} [inputs] - Files the computation reads, by path.
629
+ * @returns {T}
630
+ */
631
+ export function persistedDerived(key, compute, codec, inputs = []) {
632
+ if (!run || gatherCode == null) return compute();
633
+ const id = withoutRecording(buildId);
634
+ const dir = id == null ? null : withoutRecording(gatherCacheDir);
635
+ if (id == null || dir == null) return compute();
636
+ const derivedKey = ['derived', ...key, codeStamp(gatherCode, inputs)];
637
+ const file = entryFile(dir, derivedKey, id);
638
+ const entry = entryKey(derivedKey, id);
639
+ try {
640
+ const stored = JSON.parse(
641
+ withoutRecording(() => fs.readFileSync(file, 'utf-8')),
642
+ );
643
+ if (
644
+ stored?.format === FORMAT &&
645
+ stored.derived === true &&
646
+ stored.key === entry
647
+ ) {
648
+ const value = codec.decode(stored.value);
649
+ try {
650
+ const now = new Date();
651
+ withoutRecording(() => fs.utimesSync(file, now, now));
652
+ } catch {
653
+ // An entry that cannot be touched is evicted sooner; nothing more.
654
+ }
655
+ return value;
656
+ }
657
+ } catch {
658
+ // No usable entry: computed below.
659
+ }
660
+ const value = compute();
661
+ withoutRecording(() => {
662
+ try {
663
+ const encoded = codec.encode(value);
664
+ const text = JSON.stringify({
665
+ format: FORMAT,
666
+ derived: true,
667
+ key: entry,
668
+ value: encoded,
669
+ });
670
+ if (!isDeepStrictEqual(JSON.parse(text).value, encoded)) return;
671
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
672
+ fs.writeFileSync(temp, text, {mode: 0o600, flag: 'wx'});
673
+ fs.renameSync(temp, file);
674
+ evict(dir);
675
+ } catch {
676
+ // A value that cannot be stored is computed again next time.
677
+ }
678
+ });
679
+ return value;
680
+ }
681
+
682
+ /**
683
+ * Store a fresh gather with what the run read, unless its plain form does not
684
+ * read back as the same value. Silent on any failure.
685
+ * @template T, E
686
+ * @param {string} dir
687
+ * @param {string} file
688
+ * @param {string} entry - The entry's key (entryKey).
689
+ * @param {T} value
690
+ * @param {{encode: (value: T) => E, decode: (stored: E) => T}} codec
691
+ */
692
+ function store(dir, file, entry, value, codec) {
693
+ if (!run) return;
694
+ try {
695
+ const encoded = codec.encode(value);
696
+ const stamps = [...run.reads].filter(([file]) => !inJitiCache(file));
697
+ gatherCode = cliStates(stamps);
698
+ const text = JSON.stringify({
699
+ format: FORMAT,
700
+ key: entry,
701
+ stamps,
702
+ env: [...run.env],
703
+ value: encoded,
704
+ });
705
+ if (!isDeepStrictEqual(JSON.parse(text).value, encoded)) return;
706
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
707
+ fs.writeFileSync(temp, text, {mode: 0o600, flag: 'wx'});
708
+ fs.renameSync(temp, file);
709
+ evict(dir);
710
+ } catch {
711
+ // A gather that cannot be stored is gathered again next time.
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Delete the oldest entries until the folder holds at most CACHE_LIMIT_BYTES.
717
+ * @param {string} dir
718
+ */
719
+ function evict(dir) {
720
+ const entries = fs
721
+ .readdirSync(dir)
722
+ .filter(name => name.startsWith('gather-'))
723
+ .map(name => {
724
+ const entry = path.join(dir, name);
725
+ try {
726
+ const {size, mtimeMs} = fs.statSync(entry);
727
+ return {entry, size, mtimeMs};
728
+ } catch {
729
+ return null;
730
+ }
731
+ })
732
+ .filter(e => e != null)
733
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
734
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
735
+ for (const {entry, size} of entries) {
736
+ if (total <= CACHE_LIMIT_BYTES) break;
737
+ try {
738
+ fs.unlinkSync(entry);
739
+ total -= size;
740
+ } catch {
741
+ // Another run removed it.
742
+ }
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Whether this run is under Yarn Plug'n'Play's loader (`yarn astryx` in a PnP
748
+ * project): Node's module hooks hand PnP's resolver options it refuses, so
749
+ * such a run keeps and uses no catalogs. The plain `astryx` command in the
750
+ * same project keeps them.
751
+ * @returns {boolean}
752
+ */
753
+ export function runsUnderPnp() {
754
+ return Boolean(process.versions.pnp);
755
+ }
756
+
757
+ /**
758
+ * The cache folder and how much it holds, for `doctor`: null when the CLI
759
+ * keeps no gathers (a checkout) or has no usable folder.
760
+ * @returns {{dir: string, bytes: number, entries: number, pnp: boolean} | null}
761
+ * `pnp`: whether this run is under Yarn Plug'n'Play's loader (runsUnderPnp)
762
+ */
763
+ export function gatherCacheSummary() {
764
+ if (buildId() == null) return null;
765
+ const dir = gatherCacheDir();
766
+ if (dir == null) return null;
767
+ let bytes = 0;
768
+ let entries = 0;
769
+ try {
770
+ for (const name of fs.readdirSync(dir)) {
771
+ if (!name.startsWith('gather-') || name.endsWith('.tmp')) continue;
772
+ try {
773
+ bytes += fs.statSync(path.join(dir, name)).size;
774
+ entries++;
775
+ } catch {
776
+ // Removed meanwhile.
777
+ }
778
+ }
779
+ } catch {
780
+ return null;
781
+ }
782
+ return {dir, bytes, entries, pnp: runsUnderPnp()};
783
+ }