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