@astryxdesign/cli 0.7.14 → 0.7.15-canary.g79b95eb

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