@astryxdesign/cli 0.7.14 → 0.7.15-canary.g061b2fa

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