@yaks/testing 0.0.0-stage → 0.2.36

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 (93) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +427 -2
  3. package/_dist/assert.d.ts +40 -0
  4. package/_dist/assert.d.ts.map +1 -0
  5. package/_dist/choose.d.ts +39 -0
  6. package/_dist/choose.d.ts.map +1 -0
  7. package/_dist/clock.d.ts +8 -0
  8. package/_dist/clock.d.ts.map +1 -0
  9. package/_dist/deps.d.ts +113 -0
  10. package/_dist/deps.d.ts.map +1 -0
  11. package/_dist/examples.d.ts +69 -0
  12. package/_dist/examples.d.ts.map +1 -0
  13. package/_dist/find.d.ts +23 -0
  14. package/_dist/find.d.ts.map +1 -0
  15. package/_dist/kept.d.ts +27 -0
  16. package/_dist/kept.d.ts.map +1 -0
  17. package/_dist/lend.d.ts +15 -0
  18. package/_dist/lend.d.ts.map +1 -0
  19. package/_dist/main.d.ts +2 -0
  20. package/_dist/main.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +45 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/names.d.ts +31 -0
  24. package/_dist/names.d.ts.map +1 -0
  25. package/_dist/own.d.ts +25 -0
  26. package/_dist/own.d.ts.map +1 -0
  27. package/_dist/reads.d.ts +8 -0
  28. package/_dist/reads.d.ts.map +1 -0
  29. package/_dist/suite.d.ts +82 -0
  30. package/_dist/suite.d.ts.map +1 -0
  31. package/_dist/typist.d.ts +24 -0
  32. package/_dist/typist.d.ts.map +1 -0
  33. package/_dist/wait.d.ts +21 -0
  34. package/_dist/wait.d.ts.map +1 -0
  35. package/assert.js +114 -0
  36. package/assert.js.map +1 -0
  37. package/assert.ts +143 -0
  38. package/choose.js +197 -0
  39. package/choose.js.map +1 -0
  40. package/choose.ts +327 -0
  41. package/clock.js +45 -0
  42. package/clock.js.map +1 -0
  43. package/clock.ts +60 -0
  44. package/deno.json +1 -0
  45. package/deps.js +868 -0
  46. package/deps.js.map +1 -0
  47. package/deps.ts +1004 -0
  48. package/drive.js +43 -0
  49. package/drive.js.map +1 -0
  50. package/drive.ts +41 -0
  51. package/examples.js +279 -0
  52. package/examples.js.map +1 -0
  53. package/examples.ts +380 -0
  54. package/find.js +86 -0
  55. package/find.js.map +1 -0
  56. package/find.ts +102 -0
  57. package/kept.js +128 -0
  58. package/kept.js.map +1 -0
  59. package/kept.ts +146 -0
  60. package/lend.js +30 -0
  61. package/lend.js.map +1 -0
  62. package/lend.ts +31 -0
  63. package/load.js +106 -0
  64. package/load.js.map +1 -0
  65. package/load.ts +139 -0
  66. package/main.js +214 -0
  67. package/main.js.map +1 -0
  68. package/main.ts +217 -0
  69. package/mod.js +45 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +55 -0
  72. package/names.js +209 -0
  73. package/names.js.map +1 -0
  74. package/names.ts +204 -0
  75. package/own.js +109 -0
  76. package/own.js.map +1 -0
  77. package/own.ts +136 -0
  78. package/package.json +56 -4
  79. package/reads.js +88 -0
  80. package/reads.js.map +1 -0
  81. package/reads.ts +98 -0
  82. package/run.js +306 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +405 -0
  85. package/suite.js +191 -0
  86. package/suite.js.map +1 -0
  87. package/suite.ts +224 -0
  88. package/typist.js +74 -0
  89. package/typist.js.map +1 -0
  90. package/typist.ts +79 -0
  91. package/wait.js +34 -0
  92. package/wait.js.map +1 -0
  93. package/wait.ts +60 -0
package/deps.ts ADDED
@@ -0,0 +1,1004 @@
1
+ import * as io from '@yaks/file/io'
2
+ import * as system from '@yaks/process/system'
3
+ import { type Info, modules } from '@yaks/process/modules'
4
+ // Which files a run can leave out: one whose tests all passed, when nothing
5
+ // it depends on has changed since. Before it runs, a file depends on its
6
+ // module graph, as `deno info` resolves it (a dynamic import of a literal
7
+ // specifier included); on every file a module in that graph names beside
8
+ // itself (`new URL('./fixture.json', import.meta.url)`); and on what every
9
+ // file shares: the runner, the config and lock it runs under, the runtime,
10
+ // and whatever the caller adds. A directory a module names is a place (a
11
+ // root, a working directory), not what lies in it. That is the file's key.
12
+ //
13
+ // As it runs, a file reads what no graph can say: a directory it walks, a
14
+ // file at a path it computes, a module it imports by a computed specifier
15
+ // (./reads.ts says how the runner sees them). Each is a dependency too: a
16
+ // file's bytes, a directory's listing, a module's whole graph. A pass is kept
17
+ // by its proof, the file's key with what each of those holds; a run that
18
+ // could not see them keeps the key alone. The passes are kept in a file every
19
+ // checkout on the machine shares, so the same sources passing in one worktree
20
+ // count in another, and what each file read as it last passed in a file
21
+ // beside it.
22
+ import { createHash } from 'node:crypto'
23
+ import { dirname, resolve } from 'node:path'
24
+ import { pathToFileURL } from 'node:url'
25
+ import { written } from './find.js'
26
+ import {
27
+ append,
28
+ byStatus,
29
+ cache,
30
+ load,
31
+ put,
32
+ seed,
33
+ stores,
34
+ write,
35
+ } from './kept.js'
36
+
37
+ export type { Info }
38
+
39
+ let hex = (data: string | Uint8Array): string =>
40
+ createHash('sha256').update(data).digest('hex')
41
+
42
+ /** A checkout's paths: its directory, its `file://` base, a path's URL and a
43
+ * specifier's checkout path. */
44
+ export type Location = {
45
+ cwd: string
46
+ base: string
47
+ url: (path: string) => string
48
+ rel: (specifier: string) => string
49
+ }
50
+
51
+ // A lookup uses one checkout context; later lookups can use another. Paths
52
+ // recur throughout selection and source planning, so normalize each once.
53
+ export let location = (cwd: string = system.cwd()): Location => {
54
+ let base = `file://${cwd}/`
55
+ let urls = new Map<string, string>(), paths = new Map<string, string>()
56
+ return {
57
+ cwd,
58
+ base,
59
+ url: (path: string) => {
60
+ if (!urls.has(path)) urls.set(path, new URL(path, base).href)
61
+ return urls.get(path)!
62
+ },
63
+ // A checkout file is relative, an outside file absolute; any other
64
+ // specifier keeps its name.
65
+ rel: (specifier: string) => {
66
+ if (!paths.has(specifier)) {
67
+ paths.set(
68
+ specifier,
69
+ specifier.startsWith(base)
70
+ ? decodeURIComponent(specifier.slice(base.length))
71
+ : specifier.startsWith('file:')
72
+ ? decodeURIComponent(new URL(specifier).pathname)
73
+ : specifier,
74
+ )
75
+ }
76
+ return paths.get(specifier)!
77
+ },
78
+ }
79
+ }
80
+ let code = (path: string) => /\.[mc]?[jt]sx?$/.test(path)
81
+
82
+ /** The module graph reached from `roots`, checkout paths or URLs, or
83
+ * undefined when deno cannot say (@yaks/process/modules). */
84
+ export let graph = (roots: string[]): Promise<Info | undefined> => {
85
+ let { cwd, url } = location()
86
+ return modules(roots.map(url), cwd)
87
+ }
88
+
89
+ /** What a graph's caller can say of a path: what it holds now (`digest`). */
90
+ export type Bytes = (path: string) => Promise<string>
91
+
92
+ // The tokens that can bring a module a dependency: a static, dynamic or
93
+ // CommonJS import, a re-export, and the compiler's pragmas.
94
+ let IMPORTING = /^.*(?:\b(?:import|from|require)\b|<reference|@ts-|@jsx).*$/gm
95
+ let SPECIFIER = /\b(?:import|from|require)\s*\(?\s*(['"`])[^'"`]*\1/g
96
+
97
+ /// importing("import a from './a.ts'\nlet x = 1") == importing("import a from './a.ts'\nlet x = 2") -> true
98
+ /// importing("import a from './a.ts'") == importing("import a from './b.ts'") -> false
99
+ /// importing("await import(\n './a.ts',\n)") == importing("await import(\n './b.ts',\n)") -> false
100
+ /// importing("import {\n a,\n} from './a.ts'") == importing("import {\n a,\n b,\n} from './a.ts'") -> true
101
+ /** What in a module's source decides what deno says it imports: each line
102
+ * holding an import, a re-export, a `require` or a compiler pragma, and each
103
+ * specifier one of those names, however the lines around it break. Two
104
+ * versions of a module alike in these resolve alike. */
105
+ export let importing = (source: string): string =>
106
+ [
107
+ ...source.match(IMPORTING) ?? [],
108
+ '',
109
+ ...source.match(SPECIFIER)?.map((m) => m.replace(/\s+/g, '')) ?? [],
110
+ ].join('\n')
111
+
112
+ /** What decides what deno says `path` imports, now: a module's
113
+ * `importing`, any other file's bytes. */
114
+ export let said: Bytes = (path) =>
115
+ Promise.try(() => {
116
+ if (!code(path)) return digest(path)
117
+ try {
118
+ return hex(importing(io.readTextFileSync(path)))
119
+ } catch {
120
+ return 'absent'
121
+ }
122
+ })
123
+
124
+ /** Where what deno said each module imports is kept, by what decides it. */
125
+ export let GRAPH: string = `${stores()}/graph.json`
126
+
127
+ // The configuration a whole graph is resolved under, whose change has every
128
+ // module asked of deno again (`remembered`).
129
+ let ROOT = [
130
+ 'deno.json',
131
+ 'deno.lock',
132
+ 'package.json',
133
+ 'node_modules/.pnpm/lock.yaml',
134
+ ]
135
+
136
+ /** What a checkout's graph starts from: the one any checkout under the same
137
+ * root configuration wrote last. A checkout of another revision keeps its
138
+ * own, so checkouts of main and of a branch changing deno.json, run at once,
139
+ * never each find the other's and resolve every module again. */
140
+ export let graphSeed = (cwd: string = system.cwd()): string =>
141
+ seed(
142
+ 'graphs',
143
+ ROOT.map((f) => {
144
+ try {
145
+ return hex(io.readFileSync(`${cwd}/${f}`))
146
+ } catch {
147
+ return 'absent'
148
+ }
149
+ }).join('\n'),
150
+ )
151
+
152
+ /** Where what each file of the checkout held, as last read, is kept by the
153
+ * file's status (`survey`). */
154
+ export let FACTS: string = `${stores()}/facts-v3.json`
155
+
156
+ // What the store keeps of a module: what `Info` reads, without the source
157
+ // spans and sizes deno says beside it, by what decides its imports (`said`).
158
+ let VERSION = 2
159
+ type Module = Info['modules'][number]
160
+ type Kept = {
161
+ version: number
162
+ deno: string
163
+ configs: Record<string, string>
164
+ modules: Record<string, { digest: string; module: Module }>
165
+ redirects: Record<string, string>
166
+ npmPackages: NonNullable<Info['npmPackages']>
167
+ }
168
+
169
+ let empty = (): Kept => ({
170
+ version: VERSION,
171
+ deno: system.runtimeVersion,
172
+ configs: {},
173
+ modules: {},
174
+ redirects: {},
175
+ npmPackages: {},
176
+ })
177
+
178
+ let configuration = async (kept: Kept, bytes: Bytes) =>
179
+ (await Promise.all(
180
+ Object.entries(kept.configs).sort().map(
181
+ async ([path, was]) => {
182
+ let now = await bytes(path)
183
+ return now == was ? [] : [[path, now]]
184
+ },
185
+ ),
186
+ )).flat()
187
+
188
+ let current = (kept: Kept) =>
189
+ kept.version == VERSION && kept.deno == system.runtimeVersion
190
+
191
+ let slim = (m: Module): Module => ({
192
+ specifier: m.specifier,
193
+ ...m.local && { local: m.local },
194
+ ...m.kind && { kind: m.kind },
195
+ ...m.mediaType && { mediaType: m.mediaType },
196
+ ...m.npmPackage && { npmPackage: m.npmPackage },
197
+ ...m.dependencies && {
198
+ dependencies: m.dependencies.map((d) => ({
199
+ ...d.specifier && { specifier: d.specifier },
200
+ ...d.code?.specifier && { code: { specifier: d.code.specifier } },
201
+ ...d.type?.specifier && { type: { specifier: d.type.specifier } },
202
+ ...d.isDynamic && { isDynamic: true },
203
+ })),
204
+ },
205
+ })
206
+
207
+ /** What may resolve the modules at `paths`: the lock, the npm tree's (what
208
+ * pnpm last installed, or absent before it has: a workspace package then
209
+ * resolves outside the checkout), and each config (`deno.json`, `deno.jsonc`,
210
+ * `package.json`) in their directories and those above them, up to the
211
+ * checkout's, whether there or not. */
212
+ let configs = (paths: string[]) => {
213
+ let dirs = new Set<string>(['.'])
214
+ for (let p of paths) {
215
+ if (p.startsWith('/')) continue
216
+ for (let at = p.lastIndexOf('/'); at > 0; at = p.lastIndexOf('/', at - 1)) {
217
+ if (dirs.has(p.slice(0, at))) break
218
+ dirs.add(p.slice(0, at))
219
+ }
220
+ }
221
+ return [
222
+ 'deno.lock',
223
+ 'node_modules/.pnpm/lock.yaml',
224
+ ...[...dirs].flatMap((d) =>
225
+ ['deno.json', 'deno.jsonc', 'package.json'].map((f) =>
226
+ d == '.' ? f : `${d}/${f}`
227
+ )
228
+ ),
229
+ ]
230
+ }
231
+
232
+ // Selection and source checks may consult one cache together. A following
233
+ // lookup reads after publication, then validates its own context and bytes;
234
+ // no resolved graph is kept in process or substituted for that validation.
235
+ let refreshing = new Map<string, Promise<void>>()
236
+ let refresh = async <T>(key: string, read: () => Promise<T>): Promise<T> => {
237
+ let before = refreshing.get(key)
238
+ let turn = Promise.withResolvers<void>()
239
+ refreshing.set(key, turn.promise)
240
+ try {
241
+ await before
242
+ return await read()
243
+ } finally {
244
+ turn.resolve()
245
+ if (refreshing.get(key) === turn.promise) refreshing.delete(key)
246
+ }
247
+ }
248
+
249
+ /**
250
+ * `info` (`deno info`), asked only of what changed: each module deno said
251
+ * before is kept by what decides what it imports (`said`: its import lines,
252
+ * not the rest of its bytes), and while those and the configs and lock
253
+ * resolving it hold, what it imports is what deno said then. A module whose
254
+ * imports changed, or never seen, is asked again, with what it reaches. The
255
+ * store names a checkout's files from the checkout, and the examples a
256
+ * process writes beside a page (./load.ts `beside`) without its pid, so
257
+ * every checkout and run shares it; the checkout's store is written once,
258
+ * and the seed is the same file.
259
+ */
260
+ export let remembered = (
261
+ info: (roots: string[]) => Promise<Info | undefined> = graph,
262
+ store = GRAPH,
263
+ seed?: string,
264
+ ) =>
265
+ async (roots: string[], bytes: Bytes = said): Promise<Info | undefined> => {
266
+ let { cwd, base, url, rel } = location()
267
+ return await refresh(`${base} ${url(store)}`, async () => {
268
+ let here = `${cwd}/`, pid = `.${system.pid}.example.`
269
+ let load = (from: string): Kept | undefined => {
270
+ try {
271
+ return JSON.parse(
272
+ io.readTextFileSync(from).replaceAll('<checkout>/', here)
273
+ .replaceAll('.<pid>.example.', pid),
274
+ )
275
+ } catch { /* none kept */ }
276
+ }
277
+ let saved = load(store)
278
+ let whole = !saved || !current(saved) ||
279
+ (await configuration(saved, bytes)).length > 0
280
+ let shared = seed
281
+ if (whole && seed) {
282
+ let base = load(seed)
283
+ if (base && current(base)) {
284
+ let changes = await configuration(base, bytes)
285
+ // Two worktrees can share lockfiles while a member's package.json
286
+ // differs. Share each resolution separately so they keep their graphs.
287
+ if (changes.length) {
288
+ shared = `${seed}.${hex(JSON.stringify(changes)).slice(0, 16)}.json`
289
+ saved = load(shared)
290
+ whole = !saved || !current(saved) ||
291
+ (await configuration(saved, bytes)).length > 0
292
+ } else {
293
+ saved = base
294
+ whole = false
295
+ }
296
+ }
297
+ } else if (!whole) {
298
+ // A warm checkout can update its own graph without replacing a shared
299
+ // graph built under another checkout's configuration.
300
+ shared = undefined
301
+ }
302
+ let kept = saved ?? empty()
303
+ let file = (s: string) => s.startsWith('file:')
304
+ let now = (s: string) => file(s) ? bytes(rel(s)) : Promise.resolve('')
305
+ let at = (s: string) => kept.redirects[s] ?? s
306
+ // Walked a wave at a time, each wave's bytes read together.
307
+ let reached = new Map<string, Module>()
308
+ let seen = new Set<string>(), stale = new Set<string>()
309
+ let wave = whole ? [] : roots.map((r) => at(url(r)))
310
+ while (wave.length) {
311
+ wave = [...new Set(wave)].filter((s) => !seen.has(s))
312
+ for (let s of wave) seen.add(s)
313
+ let digests = await Promise.all(wave.map(now))
314
+ let next: string[] = []
315
+ for (let [i, s] of wave.entries()) {
316
+ let k = kept.modules[s]
317
+ if (!k && !file(s)) whole = true
318
+ if (!k || k.digest != digests[i]) {
319
+ stale.add(rel(s))
320
+ continue
321
+ }
322
+ reached.set(s, k.module)
323
+ for (let d of k.module.dependencies ?? []) {
324
+ for (let to of [d.code?.specifier, d.type?.specifier]) {
325
+ if (to) next.push(at(to))
326
+ }
327
+ }
328
+ }
329
+ wave = next
330
+ }
331
+ if (whole) {
332
+ kept = empty()
333
+ stale = new Set(roots)
334
+ }
335
+ if (stale.size) {
336
+ let fresh = await info([...stale])
337
+ if (!fresh) return undefined
338
+ let digests = await Promise.all(
339
+ fresh.modules.map((m) => now(m.specifier)),
340
+ )
341
+ for (let [i, m] of fresh.modules.entries()) {
342
+ reached.set(m.specifier, m)
343
+ kept.modules[m.specifier] = { digest: digests[i], module: slim(m) }
344
+ }
345
+ Object.assign(kept.redirects, fresh.redirects)
346
+ Object.assign(kept.npmPackages, fresh.npmPackages)
347
+ let local = fresh.modules.map((m) => m.specifier).filter(file).map(rel)
348
+ let unseen = configs(local).filter((c) => !(c in kept.configs))
349
+ let found = await Promise.all(unseen.map(bytes))
350
+ for (let [i, c] of unseen.entries()) kept.configs[c] = found[i]
351
+ let text = JSON.stringify(kept).replaceAll(here, '<checkout>/')
352
+ .replaceAll(pid, '.<pid>.example.')
353
+ put(text, store, shared)
354
+ }
355
+ let modules = new Map<string, Module>()
356
+ let visit = roots.map((r) => at(url(r)))
357
+ while (visit.length) {
358
+ let s = visit.pop()!
359
+ if (modules.has(s)) continue
360
+ let m = reached.get(s)
361
+ if (!m) continue
362
+ modules.set(s, m)
363
+ for (let d of m.dependencies ?? []) {
364
+ for (let to of [d.code?.specifier, d.type?.specifier]) {
365
+ if (to) visit.push(at(to))
366
+ }
367
+ }
368
+ }
369
+ // Deno's npm table is the lock's resolution context, including packages
370
+ // outside these modules. Keep it whole, as Deno reports it.
371
+ return {
372
+ modules: [...modules.values()],
373
+ redirects: kept.redirects,
374
+ npmPackages: kept.npmPackages,
375
+ }
376
+ })
377
+ }
378
+
379
+ /// named("new URL('./a.json', import.meta.url)", 'x/t_test.ts') -> ['x/a.json']
380
+ /// named("new URL('../', import.meta.url)", 'x/y/t_test.ts') -> ['x']
381
+ /// named("new URL('../..', import.meta.url)", 'x/y/t_test.ts') -> ['.']
382
+ /// named("// new URL('./a.json', import.meta.url)", 'x/t_test.ts') -> []
383
+ /// named("Deno.readTextFileSync('fixtures/a.json')", 'x/t_test.ts') -> ['fixtures/a.json']
384
+ /** Files a module names with a module-relative URL or a literal Deno read
385
+ * path. Computed paths are observed in the runtime. */
386
+ export let named = (
387
+ source: string,
388
+ path: string,
389
+ { cwd, url, rel }: Location = location(),
390
+ ): string[] => {
391
+ let text = source.replace(/^\s*(\/\/|\/\*|\*).*$/gm, '')
392
+ let urls = text.matchAll(
393
+ /new URL\(\s*(['"])([^'"]+)\1,\s*import\.meta\.url\s*\)/g,
394
+ )
395
+ let reads = text.matchAll(
396
+ /\bDeno\.(?:read(?:Text)?File|open)(?:Sync)?\(\s*(['"])([^'"\\\n]+)\1\s*[,)]/g,
397
+ )
398
+ return [
399
+ ...new Set([
400
+ ...Array.from(urls, ([, , name]) => new URL(name, url(path)).href),
401
+ ...Array.from(
402
+ reads,
403
+ ([, , name]) => pathToFileURL(resolve(cwd, name)).href,
404
+ ),
405
+ ].map((at) => rel(at).replace(/\/$/, '') || '.')),
406
+ ]
407
+ }
408
+
409
+ /** What a path holds now: a file's bytes, a directory's listing (each entry's
410
+ * name, a directory's ending in `/`, but for what the runner writes beside a
411
+ * page while it is keyed or loads), or nothing. A directory a module only
412
+ * names is a `place`, whatever lies in it. */
413
+ export let digest = (path: string, place = false): Promise<string> =>
414
+ Promise.try(() => {
415
+ let info
416
+ try {
417
+ info = io.statSync(path)
418
+ } catch {
419
+ return 'absent'
420
+ }
421
+ if (info.isFile) return hex(io.readFileSync(path))
422
+ if (place) return 'place'
423
+ let names: string[] = []
424
+ for (let e of io.readDirSync(path)) {
425
+ if (!written(e.name)) names.push(e.isDirectory ? `${e.name}/` : e.name)
426
+ }
427
+ return hex(names.sort().join('\n'))
428
+ })
429
+
430
+ /// let next = new Map([['a', ['b']], ['b', ['a']], ['c', ['a']], ['d', []]])
431
+ /// let s = seal(next, (n) => n)
432
+ /// s.get('a') == s.get('b') -> true
433
+ /// s.get('c') == s.get('a') -> false
434
+ /// s.get('c') == seal(next, (n) => n == 'b' ? 'B' : n).get('c') -> false
435
+ /// s.get('d') == seal(next, (n) => n == 'b' ? 'B' : n).get('d') -> true
436
+ /**
437
+ * Each node's seal: a digest of what it is (`own`) and of every node it
438
+ * reaches through `next`, so a change to any of those changes it. Nodes in a
439
+ * cycle reach each other, and share one; a seal is made of the seals of the
440
+ * cycles a node's own reaches (Tarjan's strongly connected components, which
441
+ * come last first), so a graph is sealed in one pass however many roots
442
+ * share it.
443
+ */
444
+ export let seal = (
445
+ next: Map<string, string[]>,
446
+ own: (node: string) => string,
447
+ ): Map<string, string> => {
448
+ let index = new Map<string, number>(), low = new Map<string, number>()
449
+ let stack: string[] = [], on = new Set<string>()
450
+ let sealed = new Map<string, string>()
451
+ let enter = (v: string) => {
452
+ index.set(v, index.size)
453
+ low.set(v, index.get(v)!)
454
+ stack.push(v)
455
+ on.add(v)
456
+ }
457
+ // A cycle closed at `v`: everything above it on the stack.
458
+ let close = (v: string) => {
459
+ let members: string[] = []
460
+ let w
461
+ do {
462
+ w = stack.pop()!
463
+ on.delete(w)
464
+ members.push(w)
465
+ } while (w != v)
466
+ let inside = new Set(members)
467
+ let beyond = new Set(
468
+ members.flatMap((m) => next.get(m) ?? []).filter((n) => !inside.has(n))
469
+ .map((n) => sealed.get(n)!),
470
+ )
471
+ let s = hex([...members.map(own).sort(), '', ...[...beyond].sort()].join(
472
+ '\n',
473
+ ))
474
+ for (let m of members) sealed.set(m, s)
475
+ }
476
+ for (let start of next.keys()) {
477
+ if (index.has(start)) continue
478
+ enter(start)
479
+ let work: [string, number][] = [[start, 0]]
480
+ while (work.length) {
481
+ let top = work.at(-1)!
482
+ let [v, i] = top
483
+ let out = next.get(v) ?? []
484
+ if (i < out.length) {
485
+ top[1]++
486
+ let w = out[i]
487
+ if (!index.has(w)) {
488
+ enter(w)
489
+ work.push([w, 0])
490
+ } else if (on.has(w)) low.set(v, Math.min(low.get(v)!, index.get(w)!))
491
+ continue
492
+ }
493
+ work.pop()
494
+ let up = work.at(-1)?.[0]
495
+ if (up) low.set(up, Math.min(low.get(up)!, low.get(v)!))
496
+ if (low.get(v) == index.get(v)) close(v)
497
+ }
498
+ }
499
+ return sealed
500
+ }
501
+
502
+ /** What a run knows of some paths and everything they reach, each file read
503
+ * once: what a path holds now (`of`: a code module's seal, else its `digest`,
504
+ * a directory its listing), what a module is with only what loads with it
505
+ * (`loads`: its seal without what it imports only when it asks, by a literal
506
+ * `import('…')`), and the seals of what a module imports (`next`). A file of
507
+ * data is its bytes whether or not a module there imports it (a config read
508
+ * as JSON), so it holds the same in every survey. A file's `distance` from a
509
+ * change is the imports between them, never through a module wider than
510
+ * `WIDE`; given each path's package (`owner`), a file of a changed package
511
+ * is 0 when changes in that package reach it, and 1 otherwise. A file
512
+ * importing a changed package from another is at most 1. `distance` follows
513
+ * runtime imports by default; `false` includes type-only imports. */
514
+ export type Survey = {
515
+ // Exact resolution metadata from this snapshot. Inputs regenerated after
516
+ // it was taken must still hold; unknown roots need a fresh resolution.
517
+ info: (roots: string[], refreshed?: string[]) => Promise<Info | undefined>
518
+ // What a path holds as the survey read it (`digest`), read now if it
519
+ // never did.
520
+ bytes: Bytes
521
+ // What decides what deno says a path imports (`said`), as the survey read
522
+ // it.
523
+ said: Bytes
524
+ of: (path: string, runtime?: boolean) => Promise<string>
525
+ loads: (path: string) => Promise<string>
526
+ next: (path: string, runtime?: boolean) => string[]
527
+ reaches: (
528
+ roots: string[],
529
+ changed: string[],
530
+ loaded?: boolean,
531
+ runtime?: boolean,
532
+ ) => boolean
533
+ distance: (
534
+ changed: string[],
535
+ owner?: (path: string) => string | undefined,
536
+ runtime?: boolean,
537
+ ) => (root: string) => number
538
+ }
539
+
540
+ /** How many modules a module may load and still say something about what its
541
+ * importers depend on. Past it, a module composes a whole platform (a kernel,
542
+ * a test fixture over one): nearly every change reaches its importers, so that
543
+ * path does not make them relevant to the change. */
544
+ export const WIDE = 200
545
+
546
+ // What `survey` keeps of a file: its digest, the files it names, and what
547
+ // decides its imports (`said`).
548
+ type Fact = { digest: string; names: string[]; imports: string }
549
+
550
+ /** The survey of `paths`, their modules' graph from `info` (`deno info`), or
551
+ * undefined when it cannot say what they import. Given a `store`, what each
552
+ * file among them and their modules held is kept there by the file's status
553
+ * (./kept.ts `byStatus`). */
554
+ export let survey = async (
555
+ paths: string[],
556
+ info: (roots: string[], bytes: Bytes) => Promise<Info | undefined> =
557
+ remembered(graph, GRAPH, graphSeed()),
558
+ store?: string,
559
+ ): Promise<Survey | undefined> => {
560
+ let where = location(), { url, rel } = where
561
+ let known = byStatus<Fact>(store)
562
+ let aliases = new Map<string, string[]>()
563
+ let link = (path: string) => {
564
+ let target = rel(
565
+ pathToFileURL(resolve(dirname(path), io.readLinkSync(path))).href,
566
+ )
567
+ let names = aliases.get(target) ?? []
568
+ names.push(path)
569
+ aliases.set(target, names)
570
+ }
571
+ let look = (path: string): Promise<Fact> => {
572
+ let s
573
+ try {
574
+ s = io.lstatSync(path)
575
+ if (s.isSymlink) {
576
+ link(path)
577
+ s = io.statSync(path)
578
+ }
579
+ } catch {
580
+ return Promise.resolve({ digest: 'absent', names: [], imports: 'absent' })
581
+ }
582
+ if (!s.isFile) {
583
+ return Promise.resolve({ digest: 'place', names: [], imports: 'place' })
584
+ }
585
+ return Promise.resolve(known.of(path, s, () => {
586
+ let bytes = io.readFileSync(path)
587
+ let digest = hex(bytes)
588
+ if (!code(path)) return { digest, names: [], imports: digest }
589
+ let text = new TextDecoder().decode(bytes)
590
+ return {
591
+ digest,
592
+ names: named(text, path, where),
593
+ imports: hex(importing(text)),
594
+ }
595
+ }))
596
+ }
597
+ // What each file is and names: read once for the lot.
598
+ let facts = new Map<string, Promise<Fact>>()
599
+ let fact = (path: string) => {
600
+ if (!facts.has(path)) facts.set(path, look(path))
601
+ return facts.get(path)!
602
+ }
603
+ await Promise.all(paths.map(fact))
604
+ let roots = [...new Set(paths.filter(code))]
605
+ let found = roots.length
606
+ ? await info(roots, async (p) => (await fact(p)).imports)
607
+ : { modules: [], redirects: {} }
608
+ if (!found) return undefined
609
+ let { redirects } = found
610
+ let at = (s: string) => redirects[s] ?? s
611
+ let modules = new Map(found.modules.map((m) => [m.specifier, m]))
612
+ let local = found.modules.filter((m) => m.specifier.startsWith('file:'))
613
+ await Promise.all(local.map((m) => fact(rel(m.specifier))))
614
+ // A node is a module, by its specifier, or a file a module names that is
615
+ // none, by its path. A remote module is its versioned specifier.
616
+ let next = new Map<string, string[]>()
617
+ let still = new Map<string, string[]>()
618
+ let runtime = new Map<string, string[]>()
619
+ let own = new Map<string, string>()
620
+ for (let m of local) {
621
+ let path = rel(m.specifier)
622
+ let { digest: d, names } = await fact(path)
623
+ own.set(m.specifier, `${path} ${d}`)
624
+ let deps = (m.dependencies ?? []).flatMap((d) =>
625
+ [d.code?.specifier, d.type?.specifier].flatMap((specifier) =>
626
+ specifier
627
+ ? [{
628
+ to: at(specifier),
629
+ asked: d.isDynamic,
630
+ typed: specifier != d.code?.specifier,
631
+ }]
632
+ : []
633
+ )
634
+ )
635
+ // A literal file reference depends on the named bytes. Keep this edge
636
+ // even when another root imports that same file as a module.
637
+ for (let n of names) {
638
+ own.set(n, `${n} ${(await fact(n)).digest}`)
639
+ next.set(n, [])
640
+ }
641
+ next.set(m.specifier, [...deps.map((d) => d.to), ...names])
642
+ runtime.set(m.specifier, [
643
+ ...deps.flatMap((d) => d.typed ? [] : [d.to]),
644
+ ...names,
645
+ ])
646
+ still.set(m.specifier, [
647
+ ...deps.flatMap((d) => d.asked || d.typed ? [] : [d.to]),
648
+ ...names,
649
+ ])
650
+ }
651
+ for (let m of found.modules) {
652
+ if (!next.has(m.specifier)) next.set(m.specifier, [])
653
+ }
654
+ for (let targets of [...next.values()]) {
655
+ for (let t of targets) if (!next.has(t)) next.set(t, [])
656
+ }
657
+ // Reads and imports may name a symlink while Git names the changed target.
658
+ let changedNodes = (changed: string[]) => {
659
+ let paths = new Set(changed)
660
+ for (let p of paths) {
661
+ for (let alias of aliases.get(p) ?? []) paths.add(alias)
662
+ }
663
+ return [...paths].flatMap((p) => [p, at(url(p))])
664
+ }
665
+ known.save((path) => !facts.has(path))
666
+ let mine = (n: string) => own.get(n) ?? n
667
+ let seals = seal(next, mine)
668
+ let executed = seal(
669
+ new Map([...next].map(([n]) => [n, runtime.get(n) ?? []])),
670
+ mine,
671
+ )
672
+ let held = new Map<string, Promise<string>>()
673
+ let reverse = new Map<Map<string, string[]>, Map<string, string[]>>()
674
+ let incoming = (edges: Map<string, string[]>) => {
675
+ if (!reverse.has(edges)) {
676
+ let back = new Map<string, string[]>()
677
+ for (let [from, targets] of edges) {
678
+ for (let to of targets) {
679
+ let parents = back.get(to) ?? []
680
+ parents.push(from)
681
+ back.set(to, parents)
682
+ }
683
+ }
684
+ reverse.set(edges, back)
685
+ }
686
+ return reverse.get(edges)!
687
+ }
688
+ let closures = new Map<string, Set<string>>()
689
+ // Whether a module loads more than `WIDE` others. The walk stops past
690
+ // `WIDE`: a whole platform is thousands of modules, and its importers are
691
+ // hundreds, each asking.
692
+ let wides = new Map<string, boolean>()
693
+ let wide = (node: string, run: boolean) => {
694
+ let key = `${run} ${node}`, edges = run ? runtime : next
695
+ if (!wides.has(key)) {
696
+ let seen = new Set([node])
697
+ let go = [node]
698
+ while (go.length && seen.size <= WIDE) {
699
+ for (let n of edges.get(go.pop()!) ?? []) {
700
+ if (seen.has(n)) continue
701
+ seen.add(n)
702
+ go.push(n)
703
+ }
704
+ }
705
+ wides.set(key, seen.size > WIDE)
706
+ }
707
+ return wides.get(key)!
708
+ }
709
+ return {
710
+ info: async (roots, refreshed = []) => {
711
+ let reached = new Map<string, Module>()
712
+ let visit = roots.map((r) => at(url(r)))
713
+ while (visit.length) {
714
+ let s = visit.pop()!
715
+ if (reached.has(s)) continue
716
+ let m = modules.get(s)
717
+ if (!m) return undefined
718
+ reached.set(s, m)
719
+ for (let d of m.dependencies ?? []) {
720
+ for (let to of [d.code?.specifier, d.type?.specifier]) {
721
+ if (to) visit.push(at(to))
722
+ }
723
+ }
724
+ }
725
+ for (let path of refreshed) {
726
+ if (!reached.has(url(path))) continue
727
+ if (
728
+ await facts.get(path)?.then((f) => f.digest) !=
729
+ await digest(path, true)
730
+ ) {
731
+ return undefined
732
+ }
733
+ }
734
+ return {
735
+ modules: [...reached.values()],
736
+ redirects,
737
+ npmPackages: found.npmPackages,
738
+ }
739
+ },
740
+ bytes: (path) =>
741
+ fact(path).then((f) => f.digest == 'place' ? digest(path) : f.digest),
742
+ said: (path) =>
743
+ fact(path).then((f) => f.digest == 'place' ? digest(path) : f.imports),
744
+ of: (path, run = false) => {
745
+ let key = `${run} ${path}`
746
+ if (!held.has(key)) {
747
+ let s = code(path) && (run ? executed : seals).get(at(url(path)))
748
+ // A file surveyed is as it was read; a directory, its listing now.
749
+ held.set(
750
+ key,
751
+ s ? Promise.resolve(s) : (facts.get(path) ?? Promise.resolve())
752
+ .then((f) => f && f.digest != 'place' ? f.digest : digest(path)),
753
+ )
754
+ }
755
+ return held.get(key)!
756
+ },
757
+ loads: (path) => {
758
+ let root = at(url(path))
759
+ if (!code(path) || !seals.has(root)) return digest(path)
760
+ let reached = new Set<string>()
761
+ let go = [root]
762
+ while (go.length) {
763
+ let n = go.pop()!
764
+ if (reached.has(n)) continue
765
+ reached.add(n)
766
+ go.push(...still.get(n) ?? [])
767
+ }
768
+ return Promise.resolve(hex([...reached].map(mine).sort().join('\n')))
769
+ },
770
+ reaches: (roots, changed, loaded = false, run = false) => {
771
+ let cache = JSON.stringify([loaded, run, changed])
772
+ if (!closures.has(cache)) {
773
+ let edges = incoming(loaded ? still : run ? runtime : next)
774
+ let seen = new Set<string>()
775
+ let visit = changedNodes(changed)
776
+ while (visit.length) {
777
+ let node = visit.pop()!
778
+ if (seen.has(node)) continue
779
+ seen.add(node)
780
+ visit.push(...edges.get(node) ?? [])
781
+ }
782
+ closures.set(cache, seen)
783
+ }
784
+ let reached = closures.get(cache)!
785
+ return roots.some((p) => reached.has(p) || reached.has(at(url(p))))
786
+ },
787
+ distance: (changed, owner = () => undefined, run = true) => {
788
+ let deps = run ? runtime : next, edges = incoming(deps)
789
+ let walk = (paths: string[]) => {
790
+ let far = new Map<string, number>()
791
+ for (let p of changedNodes(paths)) far.set(p, 0)
792
+ for (let node of far.keys()) {
793
+ let d = far.get(node)!
794
+ if (d && wide(node, run)) continue
795
+ for (let from of edges.get(node) ?? []) {
796
+ if (!far.has(from)) far.set(from, d + 1)
797
+ }
798
+ }
799
+ return far
800
+ }
801
+ let far = walk(changed)
802
+ let homes = [...new Set(changed.map(owner).filter(Boolean))]
803
+ let mine = new Map(
804
+ homes.map((
805
+ home,
806
+ ) => [home, walk(changed.filter((p) => owner(p) == home))]),
807
+ )
808
+ return (root) => {
809
+ let d = Math.min(
810
+ far.get(root) ?? Infinity,
811
+ far.get(at(url(root))) ?? Infinity,
812
+ )
813
+ let home = owner(root)
814
+ let own = home && mine.get(home)
815
+ if (own) return own.has(root) || own.has(at(url(root))) ? 0 : 1
816
+ let uses = (deps.get(at(url(root))) ?? []).some((n) => {
817
+ let to = owner(rel(n))
818
+ return to && to != home && mine.has(to)
819
+ })
820
+ return uses ? Math.min(d, 1) : d
821
+ }
822
+ },
823
+ next: (
824
+ path,
825
+ run = false,
826
+ ) => (((run ? runtime : next).get(at(url(path))) ?? []).map((n) =>
827
+ (run ? executed : seals).get(n)!
828
+ )),
829
+ }
830
+ }
831
+
832
+ /** What every file of a kind shares: `salt`, the runtime's version, what
833
+ * each of `also` holds, and the modules of the `runner` running them, each
834
+ * with what loads with it: the modules it imports only when it asks, for
835
+ * some other file's sake, are that file's to depend on. */
836
+ export let shared = async (
837
+ s: Survey,
838
+ also: string[],
839
+ salt = '',
840
+ runner: string[] = [],
841
+ ): Promise<string> =>
842
+ hex(
843
+ [
844
+ `${system.runtimeVersion} ${salt}`,
845
+ ...(await Promise.all([
846
+ ...also.map(async (p) => `${p} ${await s.of(p)}`),
847
+ ...runner.map(async (p) => `${p} loads ${await s.loads(p)}`),
848
+ ])).sort(),
849
+ ].join('\n'),
850
+ )
851
+
852
+ /** A file's key: `common` (what it shares with its kind), its name, and what
853
+ * it is and reaches. A root standing for another file, `name` (an example
854
+ * page's plan module stands for the page), is that file's: what the root
855
+ * imports, and the page, not the root itself. */
856
+ export let key = async (
857
+ s: Survey,
858
+ common: string,
859
+ root: string,
860
+ name = root,
861
+ runtime = false,
862
+ ): Promise<string> =>
863
+ hex(
864
+ [
865
+ common,
866
+ name,
867
+ ...name == root
868
+ ? [await s.of(root, runtime)]
869
+ : [...s.next(root, runtime), await s.of(name, runtime)].sort(),
870
+ ].join('\n'),
871
+ )
872
+
873
+ /** The pass a file is kept by: its key, and what each path it read as it ran
874
+ * holds now. A run that could not see what it read keeps the key alone,
875
+ * which no proof of a run that could ever matches. */
876
+ export let proof = async (
877
+ s: Survey,
878
+ key: string,
879
+ reads?: string[],
880
+ runtime = false,
881
+ ): Promise<string> =>
882
+ reads
883
+ ? hex(
884
+ [
885
+ key,
886
+ ...(await Promise.all(
887
+ reads.map(async (p) => `${p} ${await s.of(p, runtime)}`),
888
+ )).sort(),
889
+ ].join('\n'),
890
+ )
891
+ : key
892
+
893
+ /** Where passes are kept, by proof, for every checkout on this machine: a
894
+ * proof a line, the newest last. */
895
+ export let STORE: string = `${cache}/yak/tests-passed.log`
896
+
897
+ /** Where what each file read as it last passed is kept, beside them. */
898
+ export let READS: string = `${cache}/yak/tests-reads.json`
899
+
900
+ // Enough passes for every file of many checkouts; the oldest go first.
901
+ let KEEP = 100_000
902
+ // A proof's line: a digest in hex, and its end.
903
+ let LINE = 65
904
+
905
+ let proofs = (store: string): string[] => {
906
+ try {
907
+ return io.readTextFileSync(store).split('\n').filter(Boolean)
908
+ } catch {
909
+ return []
910
+ }
911
+ }
912
+
913
+ /** The passes kept. */
914
+ export let passed = (store = STORE): Set<string> => new Set(proofs(store))
915
+
916
+ /** Adds passes made now to what the store holds. A run appends only its
917
+ * own, so runs adding at once keep each other's; a store grown past twice
918
+ * `keep` lines is cut to the newest `keep`. */
919
+ export let remember = (
920
+ made: string[],
921
+ store = STORE,
922
+ keep = KEEP,
923
+ ): void => {
924
+ if (!made.length) return
925
+ append(made.map((k) => `${k}\n`).join(''), store)
926
+ if (io.statSync(store).size > 2 * keep * LINE) {
927
+ save([...new Set(proofs(store).reverse())].slice(0, keep).reverse(), store)
928
+ }
929
+ }
930
+
931
+ // The reads store names each path once, and each file's reads by their
932
+ // place in that list: files share most of what they read. A file's key as it
933
+ // passed is kept beside its reads, where its run knew it.
934
+ type Reads = {
935
+ paths?: string[]
936
+ files?: Record<string, number[]>
937
+ keys?: Record<string, string>
938
+ }
939
+
940
+ /** What each file read as it last passed, in any checkout. A proof holds
941
+ * the file's key, so reads kept from another version of it match only a
942
+ * pass of that version that read the same. */
943
+ export let recall = (store = READS): Record<string, string[]> => {
944
+ let { paths = [], files = {} } = load(store) as Reads
945
+ return Object.fromEntries(
946
+ Object.entries(files).map(([f, at]) => [f, at.map((i) => paths[i])]),
947
+ )
948
+ }
949
+
950
+ /** The key each file had as it last passed, where its run knew it: the
951
+ * version of it its reads (`recall`) are what. */
952
+ export let versions = (store = READS): Record<string, string> =>
953
+ (load(store) as Reads).keys ?? {}
954
+
955
+ /** Adds what each file read as it passed now, nothing included: a file kept
956
+ * as reading nothing is known to, where one with no entry is unknown. `keys`
957
+ * says which version of each file read it. */
958
+ export let note = (
959
+ reads: Record<string, string[]>,
960
+ store = READS,
961
+ keys: Record<string, string> = {},
962
+ ): void => {
963
+ if (!Object.keys(reads).length) return
964
+ let all = recall(store)
965
+ let known = versions(store)
966
+ for (let [f, paths] of Object.entries(reads)) {
967
+ delete all[f]
968
+ all[f] = paths
969
+ if (keys[f]) known[f] = keys[f]
970
+ else delete known[f]
971
+ }
972
+ let index = new Map<string, number>()
973
+ let at = (p: string) => index.get(p) ?? index.set(p, index.size).get(p)!
974
+ let kept = Object.entries(all).slice(-KEEP)
975
+ let files = Object.fromEntries(kept.map(([f, paths]) => [f, paths.map(at)]))
976
+ let had = kept.flatMap(([f]) => known[f] ? [[f, known[f]]] : [])
977
+ write(
978
+ { paths: [...index.keys()], files, keys: Object.fromEntries(had) },
979
+ store,
980
+ )
981
+ }
982
+
983
+ /** Where what each file last took to load and run is kept, beside them. */
984
+ export let TOOK: string = `${cache}/yak/tests-took.json`
985
+
986
+ /** What each file last took to load and run here, in milliseconds. */
987
+ export let took = (store = TOOK): Record<string, number> => load(store)
988
+
989
+ /** Adds what files took now to what the store holds. */
990
+ export let tally = (times: Record<string, number>, store = TOOK): void => {
991
+ if (Object.keys(times).length) write({ ...took(store), ...times }, store)
992
+ }
993
+
994
+ /** Takes passes back out of what the store holds: those that a caller
995
+ * holding the run to more than passing (bin/test-budget.ts) does not grant. */
996
+ export let forget = (taken: string[], store = STORE): void => {
997
+ if (!taken.length) return
998
+ let gone = new Set(taken)
999
+ save(proofs(store).filter((k) => !gone.has(k)), store)
1000
+ }
1001
+
1002
+ // The store holding `all`, oldest first, written whole.
1003
+ let save = (all: string[], store: string) =>
1004
+ put(all.map((k) => `${k}\n`).join(''), store)