@kurvball/rehearse 1.8.0 → 1.10.0

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 (74) hide show
  1. package/README.md +3 -2
  2. package/dist/commands/init.js +52 -7
  3. package/dist/commands/stage.js +19 -3
  4. package/dist/detect/detect.d.ts +6 -0
  5. package/dist/detect/detect.js +48 -0
  6. package/dist/detect/finding.d.ts +18 -0
  7. package/dist/detect/finding.js +4 -0
  8. package/dist/detect/globs.d.ts +10 -0
  9. package/dist/detect/globs.js +43 -0
  10. package/dist/detect/index.d.ts +2 -0
  11. package/dist/detect/index.js +2 -0
  12. package/dist/detect/lockfiles.d.ts +15 -0
  13. package/dist/detect/lockfiles.js +64 -0
  14. package/dist/detect/paths.d.ts +5 -0
  15. package/dist/detect/paths.js +39 -0
  16. package/dist/detect/pieces.d.ts +14 -0
  17. package/dist/detect/pieces.js +119 -0
  18. package/dist/detect/prepare.d.ts +14 -0
  19. package/dist/detect/prepare.js +78 -0
  20. package/dist/detect/repository.d.ts +33 -0
  21. package/dist/detect/repository.js +166 -0
  22. package/dist/detect/scenarios.d.ts +26 -0
  23. package/dist/detect/scenarios.js +170 -0
  24. package/dist/detect/scripts.d.ts +46 -0
  25. package/dist/detect/scripts.js +233 -0
  26. package/dist/detect/services.d.ts +16 -0
  27. package/dist/detect/services.js +171 -0
  28. package/dist/detect/write.d.ts +18 -0
  29. package/dist/detect/write.js +115 -0
  30. package/dist/manifest/index.d.ts +1 -1
  31. package/dist/manifest/index.js +1 -1
  32. package/dist/manifest/init.d.ts +47 -1
  33. package/dist/manifest/init.js +19 -16
  34. package/dist/scenarios/glob.d.ts +1 -0
  35. package/dist/scenarios/glob.js +10 -3
  36. package/dist/scenarios/index.d.ts +1 -1
  37. package/dist/scenarios/index.js +1 -1
  38. package/dist/schema.d.ts +1 -1
  39. package/dist/schema.js +1 -0
  40. package/dist/stage/client/client/api.js +4 -1
  41. package/dist/stage/client/client/index.js +1 -0
  42. package/dist/stage/client/client/static.js +28 -0
  43. package/dist/stage/client/features/canvas/call.js +12 -3
  44. package/dist/stage/client/features/canvas/file.js +4 -2
  45. package/dist/stage/client/features/canvas/piece.js +12 -2
  46. package/dist/stage/client/features/list/list.js +6 -1
  47. package/dist/stage/client/features/scenario/heading.js +3 -2
  48. package/dist/stage/client/features/scenario/scenario.js +8 -4
  49. package/dist/stage/client/main.js +7 -3
  50. package/dist/stage/client/stage.css +11 -0
  51. package/dist/stage/compared.d.ts +7 -1
  52. package/dist/stage/compared.js +16 -4
  53. package/dist/stage/files.d.ts +1 -0
  54. package/dist/stage/files.js +6 -4
  55. package/dist/stage/index.d.ts +1 -0
  56. package/dist/stage/index.js +1 -0
  57. package/dist/stage/public.d.ts +9 -0
  58. package/dist/stage/public.js +107 -0
  59. package/dist/stage/server.js +2 -2
  60. package/dist/stage/static.d.ts +22 -0
  61. package/dist/stage/static.js +241 -0
  62. package/llms.txt +3 -2
  63. package/package.json +1 -1
  64. package/schema/v1/init.schema.json +69 -1
  65. package/schema/v1/samples/init.json +46 -1
  66. package/schema/v1/samples/static.json +21 -0
  67. package/schema/v1/static.schema.json +34 -0
  68. package/schema/vendor/acta/LICENSE +21 -0
  69. package/schema/vendor/acta/README.md +12 -0
  70. package/schema/vendor/acta/v1/canonical.schema.json +818 -0
  71. package/schema/vendor/acta/v1/check.schema.json +35 -0
  72. package/schema/vendor/acta/v1/record.schema.json +1443 -0
  73. package/schema/vendor/acta/v1/run-model.schema.json +1074 -0
  74. package/skill/rehearse/SKILL.md +6 -0
@@ -1,4 +1,4 @@
1
- import { api } from '../../client/index.js';
1
+ import { api, fileUrl, staticCopy } from '../../client/index.js';
2
2
  import { h } from '../../primitives/index.js';
3
3
  import { differencesOrCompare, sideObs } from './parts.js';
4
4
  function live(ctx, side) {
@@ -16,15 +16,25 @@ function live(ctx, side) {
16
16
  .catch((e) => box.replaceChildren(h('h3', {}, side), h('p', { class: 'error' }, e.message)));
17
17
  return box;
18
18
  }
19
+ const screenshotIn = (o, scheme) => o?.artifacts?.find((a) => a.kind === 'screenshot' && a.label === scheme)?.path ?? null;
20
+ function keptScreenshot(o, scheme) {
21
+ const shot = staticCopy ? screenshotIn(o, scheme) : null;
22
+ return shot ? h('img', { class: 'shot', src: fileUrl(shot), alt: `What Rehearse saw, ${scheme}` }) : null;
23
+ }
19
24
  function seen(o) {
20
25
  const schemes = o?.observed?.schemes;
21
26
  if (!schemes)
22
27
  return null;
23
28
  return h('div', {}, Object.entries(schemes).map(([scheme, s]) => h('div', {}, h('h3', {}, `What Rehearse saw, ${scheme}`), s.threw ? h('p', { class: 'error' }, `It threw: ${s.threw}`) : h('pre', {}, s.tree ?? ''), s.violations.length
24
29
  ? h('ul', { class: 'diffs' }, s.violations.map((v) => h('li', {}, h('span', { class: 'path' }, v.id), v.help)))
25
- : null, s.errors.length ? h('pre', { class: 'error' }, s.errors.join('\n')) : null)));
30
+ : null, s.errors.length ? h('pre', { class: 'error' }, s.errors.join('\n')) : null, keptScreenshot(o, scheme))));
26
31
  }
32
+ const asCompared = (ctx, side) => h('div', {}, h('h3', {}, side === 'base' ? 'On the base' : 'On the head'), seen(sideObs(ctx, side)) ?? ctx.notRunYet(side));
27
33
  export const pieceView = (ctx) => {
34
+ if (staticCopy)
35
+ return ctx.mode === 'diff'
36
+ ? h('div', {}, differencesOrCompare(ctx), h('div', { class: 'split' }, asCompared(ctx, 'base'), asCompared(ctx, 'head')))
37
+ : asCompared(ctx, ctx.mode);
28
38
  if (ctx.mode === 'diff')
29
39
  return h('div', {}, differencesOrCompare(ctx), h('div', { class: 'split' }, live(ctx, 'base'), live(ctx, 'head')), h('div', { class: 'split' }, seen(ctx.detail.base) ?? h('span'), seen(ctx.detail.head) ?? h('span')));
30
40
  return h('div', {}, live(ctx, ctx.mode), seen(sideObs(ctx, ctx.mode)));
@@ -1,3 +1,4 @@
1
+ import { staticCopy } from '../../client/index.js';
1
2
  import { h, redrawKeepingFocus, state, verdictWords } from '../../primitives/index.js';
2
3
  const typingIn = (el) => el?.tagName === 'INPUT' || el?.tagName === 'TEXTAREA';
3
4
  export function createList(choose) {
@@ -31,7 +32,11 @@ export function createList(choose) {
31
32
  areas.set(r.area, [...(areas.get(r.area) ?? []), r]);
32
33
  redrawKeepingFocus(groups, () => groups.replaceChildren(...(rows.length === 0
33
34
  ? [
34
- h('p', { class: 'note', style: 'padding: 0 14px' }, q ? `Nothing matches “${query}”.` : 'This repository has no scenarios yet.'),
35
+ h('p', { class: 'note', style: 'padding: 0 14px' }, q
36
+ ? `Nothing matches “${query}”.`
37
+ : staticCopy
38
+ ? 'This comparison holds no scenario.'
39
+ : 'This repository has no scenarios yet.'),
35
40
  ]
36
41
  : []), ...[...areas].map(([area, items]) => h('section', { class: 'group' }, h('h2', {}, area), items.map((r) => {
37
42
  const verdict = r.verdict ? verdictWords(r.verdict) : 'Not compared';
@@ -1,14 +1,15 @@
1
+ import { staticCopy } from '../../client/index.js';
1
2
  import { h, verdictWords } from '../../primitives/index.js';
2
3
  export function heading(d) {
3
4
  const c = d.comparison;
4
5
  return h('section', { class: 'head' }, h('h1', {}, d.scenario.name), h('div', { class: 'where' }, `${d.scenario.kind} · ${d.scenario.file}${d.scenario.line ? `:${d.scenario.line}` : ''}`), h('div', { class: 'row' }, c
5
6
  ? h('span', { class: `verdict ${c.verdict}` }, h('span', { class: `dot ${c.verdict}` }), verdictWords(c.verdict))
6
- : h('span', { class: 'verdict' }, 'Not compared yet'), c?.said === 'announced' && c.why
7
+ : h('span', { class: 'verdict' }, staticCopy ? 'Not compared' : 'Not compared yet'), c?.said === 'announced' && c.why
7
8
  ? h('span', { class: 'why' }, `Announced: ${c.why}`)
8
9
  : c?.said === 'edited'
9
10
  ? h('span', { class: 'why' }, 'Its own definition was edited.')
10
11
  : null, c?.verdict === 'fails' && c.failsOnBase
11
12
  ? h('span', { class: 'why' }, 'It fails on the base too: not this change’s doing.')
12
- : null));
13
+ : null, (d.notRun ?? []).map((n) => h('span', { class: 'why' }, `It didn't run on the ${n.side} (${n.step}): ${n.says}`))));
13
14
  }
14
15
  export const problem = (text) => h('p', { class: 'error', role: 'alert' }, text);
@@ -1,4 +1,4 @@
1
- import { api } from '../../client/index.js';
1
+ import { api, staticCopy } from '../../client/index.js';
2
2
  import { disableKeepingFocus, h, redrawKeepingFocus, rememberInUrl, say, state, verdictWords, } from '../../primitives/index.js';
3
3
  import { viewOf } from '../canvas/index.js';
4
4
  import { tryPanel } from '../try/index.js';
@@ -19,8 +19,12 @@ export function createScenario(hooks) {
19
19
  let latestAsk = 0;
20
20
  let modeShown = null;
21
21
  const render = () => redrawKeepingFocus(element, draw, () => modeShown);
22
- const notRunYet = (side) => h('p', { class: 'note' }, `Not run on the ${side} yet. `, h('button', { class: 'btn', type: 'button', 'data-key': `run ${side}`, onclick: () => void run(side) }, `Run on the ${side}`));
23
- const notComparedYet = () => h('p', { class: 'note' }, 'Not compared yet. ', h('button', { class: 'btn', type: 'button', 'data-key': 'compare', onclick: () => void compare() }, 'Compare'));
22
+ const notRunYet = (side) => staticCopy
23
+ ? h('p', { class: 'note' }, `Not run on the ${side} in this comparison.`)
24
+ : h('p', { class: 'note' }, `Not run on the ${side} yet. `, h('button', { class: 'btn', type: 'button', 'data-key': `run ${side}`, onclick: () => void run(side) }, `Run on the ${side}`));
25
+ const notComparedYet = () => staticCopy
26
+ ? h('p', { class: 'note' }, 'Not compared in this comparison.')
27
+ : h('p', { class: 'note' }, 'Not compared yet. ', h('button', { class: 'btn', type: 'button', 'data-key': 'compare', onclick: () => void compare() }, 'Compare'));
24
28
  function draw() {
25
29
  modeShown = null;
26
30
  const d = state.detail;
@@ -57,7 +61,7 @@ export function createScenario(hooks) {
57
61
  if (doing)
58
62
  disableKeepingFocus(go);
59
63
  const view = viewOf(d.scenario.kind)({ detail: d, mode, notRunYet, notComparedYet });
60
- element.replaceChildren(heading(d), ...(state.errorUntilNextAction ? [problem(state.errorUntilNextAction)] : []), h('div', { class: 'bar' }, chooser('World', 'world', state.index?.worlds ?? [], state.world, (v) => (state.world = v)), chooser('As', 'as', state.index?.people ?? [], state.person, (v) => (state.person = v)), modes, h('span', { class: 'spacer' }), go), h('section', { class: 'canvas', 'aria-label': 'Canvas' }, view), tryPanel(d, mode));
64
+ element.replaceChildren(heading(d), ...(state.errorUntilNextAction ? [problem(state.errorUntilNextAction)] : []), h('div', { class: 'bar' }, chooser('World', 'world', state.index?.worlds ?? [], state.world, (v) => (state.world = v)), chooser('As', 'as', state.index?.people ?? [], state.person, (v) => (state.person = v)), modes, ...(staticCopy ? [] : [h('span', { class: 'spacer' }), go])), h('section', { class: 'canvas', 'aria-label': 'Canvas' }, view), ...(staticCopy ? [] : [tryPanel(d, mode)]));
61
65
  }
62
66
  async function select(id) {
63
67
  const ask = ++latestAsk;
@@ -1,15 +1,19 @@
1
- import { api } from './client/index.js';
1
+ import { api, staticCopy } from './client/index.js';
2
2
  import { createList } from './features/list/index.js';
3
3
  import { createScenario } from './features/scenario/index.js';
4
4
  import { h, liveRegion, state } from './primitives/index.js';
5
5
  const sides = h('span', { class: 'sides', id: 'sides' });
6
6
  const line = h('span', { class: 'line', id: 'line' });
7
+ const copyNotice = staticCopy ? h('p', { class: 'copy', role: 'note' }) : null;
8
+ const baseWords = (i) => `${i.base.ref ?? 'a folder'}${i.base.commit ? `@${i.base.commit.slice(0, 8)}` : ''}`;
9
+ const headWords = (i) => `${i.head.commit ? i.head.commit.slice(0, 8) : (i.head.ref ?? i.head.path)}${i.head.dirty ? ' + changes' : ''}`;
7
10
  function renderTop() {
8
11
  const i = state.index;
9
12
  if (!i)
10
13
  return;
11
- sides.replaceChildren('base ', h('code', {}, `${i.base.ref}${i.base.commit ? `@${i.base.commit.slice(0, 8)}` : ''}`), ' · head ', h('code', {}, `${i.head.commit ? i.head.commit.slice(0, 8) : i.head.path}${i.head.dirty ? ' + changes' : ''}`));
14
+ sides.replaceChildren('base ', h('code', {}, baseWords(i)), ' · head ', h('code', {}, headWords(i)));
12
15
  line.textContent = i.line ?? 'Not compared yet: rehearse compare, or Compare on a scenario.';
16
+ copyNotice?.replaceChildren('A static copy of the comparison of ', h('code', {}, headWords(i)), ' with ', h('code', {}, baseWords(i)), '. ', h('code', {}, 'rehearse stage'), ' runs it live.');
13
17
  }
14
18
  async function loadIndex() {
15
19
  state.index = await api('/api/index');
@@ -18,7 +22,7 @@ async function loadIndex() {
18
22
  }
19
23
  const list = createList((id) => void scenario.select(id));
20
24
  const scenario = createScenario({ chosen: () => list.render(), compared: loadIndex });
21
- document.body.append(h('header', { class: 'top' }, h('span', { class: 'brand' }, 'Rehearse'), sides, line), h('div', { class: 'body' }, list.element, scenario.element), liveRegion);
25
+ document.body.append(h('header', { class: 'top' }, h('span', { class: 'brand' }, 'Rehearse'), sides, line), ...(copyNotice ? [copyNotice] : []), h('div', { class: 'body' }, list.element, scenario.element), liveRegion);
22
26
  await loadIndex().catch((e) => list.showError(e.message));
23
27
  if (state.id)
24
28
  await scenario.select(state.id);
@@ -91,6 +91,17 @@ textarea {
91
91
  font-size: 13px;
92
92
  text-align: right;
93
93
  }
94
+ .copy {
95
+ margin: 0;
96
+ padding: 6px 18px;
97
+ border-bottom: 1px solid var(--line);
98
+ background: var(--accent-soft);
99
+ font-size: 13px;
100
+ }
101
+ .copy code {
102
+ font-family: var(--mono);
103
+ font-size: 12px;
104
+ }
94
105
 
95
106
  .body {
96
107
  flex: 1;
@@ -17,4 +17,10 @@ export interface LastCompared {
17
17
  newerEntryOf(id: string): Compared | null;
18
18
  someComparedOnItsOwnSince(at: number): boolean;
19
19
  }
20
- export declare function lastCompared(compareDir: string, head: string, baseRef: string): LastCompared;
20
+ export interface BaseAsked {
21
+ ref: string;
22
+ folder: string | null;
23
+ }
24
+ export declare function baseAsked(repo: string, ref: string, cwd: string): BaseAsked;
25
+ export declare const ofThisHeadAndBase: (c: Comparison, head: string, base: BaseAsked) => boolean;
26
+ export declare function lastCompared(compareDir: string, head: string, base: BaseAsked): LastCompared;
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { locate } from '../git/index.js';
3
4
  const modifiedAt = (file) => {
4
5
  try {
5
6
  return statSync(file).mtimeMs;
@@ -8,13 +9,24 @@ const modifiedAt = (file) => {
8
9
  return -1;
9
10
  }
10
11
  };
11
- export function lastCompared(compareDir, head, baseRef) {
12
+ export function baseAsked(repo, ref, cwd) {
13
+ try {
14
+ const found = locate(repo, ref, cwd);
15
+ return { ref, folder: 'folder' in found ? found.folder : null };
16
+ }
17
+ catch {
18
+ return { ref, folder: null };
19
+ }
20
+ }
21
+ export const ofThisHeadAndBase = (c, head, base) => path.resolve(c.head.checkout.path) === path.resolve(head) &&
22
+ (base.folder === null
23
+ ? c.base.checkout.ref === base.ref
24
+ : c.base.checkout.ref === null && path.resolve(c.base.checkout.path) === path.resolve(base.folder));
25
+ export function lastCompared(compareDir, head, base) {
12
26
  const readIfOfThisHeadAndBase = (file) => {
13
27
  try {
14
28
  const c = JSON.parse(readFileSync(file, 'utf8'));
15
- return path.resolve(c.head.checkout.path) === path.resolve(head) && c.base.checkout.ref === baseRef
16
- ? c
17
- : null;
29
+ return ofThisHeadAndBase(c, head, base) ? c : null;
18
30
  }
19
31
  catch {
20
32
  return null;
@@ -1,4 +1,5 @@
1
1
  import type { ServerResponse } from 'node:http';
2
+ export declare const BUILT_PAGE: string;
2
3
  export declare function fileThePageMayShow(file: string, keptOrCompared: readonly string[]): string | null;
3
4
  export declare function serveFile(res: ServerResponse, wanted: string, keptOrCompared: readonly string[]): void;
4
5
  export declare function servePage(res: ServerResponse, pathname: string): void;
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { PACKAGE_ROOT } from '../version.js';
4
4
  import { fail } from './http.js';
5
- const CLIENT = path.join(PACKAGE_ROOT, 'dist', 'stage', 'client');
5
+ export const BUILT_PAGE = path.join(PACKAGE_ROOT, 'dist', 'stage', 'client');
6
6
  const TYPES = {
7
7
  '.html': 'text/html; charset=utf-8',
8
8
  '.css': 'text/css; charset=utf-8',
@@ -45,10 +45,12 @@ export function serveFile(res, wanted, keptOrCompared) {
45
45
  }
46
46
  export function servePage(res, pathname) {
47
47
  const name = pathname === '/' ? 'index.html' : pathname.slice(1);
48
- const file = path.join(CLIENT, name);
49
- if (!file.startsWith(CLIENT + path.sep) || !existsSync(file) || !statSync(file).isFile()) {
48
+ const file = path.join(BUILT_PAGE, name);
49
+ if (!file.startsWith(BUILT_PAGE + path.sep) || !existsSync(file) || !statSync(file).isFile()) {
50
50
  res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
51
- res.end(existsSync(CLIENT) ? 'Not found\n' : 'The stage’s page isn’t built: run `pnpm build` in Rehearse.\n');
51
+ res.end(existsSync(BUILT_PAGE)
52
+ ? 'Not found\n'
53
+ : 'The stage’s page isn’t built: run `pnpm build` in Rehearse.\n');
52
54
  return;
53
55
  }
54
56
  res.writeHead(200, {
@@ -1 +1,2 @@
1
1
  export { runningStage, startStage, type Stage } from './server.ts';
2
+ export { baseWords, headWords, writeStaticCopy, type StaticCopy, type StaticOptions } from './static.ts';
@@ -1 +1,2 @@
1
1
  export { runningStage, startStage } from './server.js';
2
+ export { baseWords, headWords, writeStaticCopy } from './static.js';
@@ -0,0 +1,9 @@
1
+ export declare function placeholdersFor(folders: readonly (readonly [string, string])[]): <T>(value: T) => T;
2
+ export declare function manifestPlaceholder(manifestDir: string, head: string): string;
3
+ export declare const anImage: (name: string, real: string) => boolean;
4
+ export declare const asPlainText: (name: string) => string;
5
+ export declare function textScrubbed(bytes: Buffer, placed: (text: string) => string): Buffer;
6
+ export declare function publishableFrom(o: {
7
+ state: string;
8
+ checkouts: readonly string[];
9
+ }): (file: string) => string | null;
@@ -0,0 +1,107 @@
1
+ import { accessSync, closeSync, constants, openSync, readSync, realpathSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { gitOr } from '../git/index.js';
5
+ const SEPARATOR = String.raw `(?:\\?\/|\\\\?|%2f)`;
6
+ const ENDS_A_NAME = String.raw `\/\\\s'"\x60:;,()<>\[\]{}|&`;
7
+ const NAME = String.raw `(?:(?!%2f)[^${ENDS_A_NAME}])+`;
8
+ const ANYONES_HOME = new RegExp([
9
+ String.raw `(?:[a-z]:|(?:${SEPARATOR}mnt)?${SEPARATOR}[a-z])?${SEPARATOR}users${SEPARATOR}${NAME}`,
10
+ String.raw `(?:${SEPARATOR}(?:var|export|data))?${SEPARATOR}home${SEPARATOR}${NAME}`,
11
+ String.raw `${SEPARATOR}root(?=${SEPARATOR}|$|[${ENDS_A_NAME}])`,
12
+ ].join('|'), 'gi');
13
+ const IMAGE_NAMES = /\.(png|jpe?g|webp|gif)$/i;
14
+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
15
+ const asItReallyIs = (dir) => {
16
+ try {
17
+ return realpathSync(dir);
18
+ }
19
+ catch {
20
+ return path.resolve(dir);
21
+ }
22
+ };
23
+ const spellingsOf = (dir) => {
24
+ const forward = dir.replaceAll('\\', '/');
25
+ return [
26
+ dir,
27
+ forward,
28
+ forward.replaceAll('/', '\\/'),
29
+ dir.replaceAll('\\', '\\\\'),
30
+ encodeURIComponent(forward),
31
+ ];
32
+ };
33
+ const wholeFolder = (spelled) => new RegExp(`${spelled.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replaceAll('%2F', '%2[Ff]')}(?!\\w|[.-]\\w)`, 'g');
34
+ export function placeholdersFor(folders) {
35
+ const each = [...folders, [homedir(), '~']].flatMap(([dir, name]) => [path.resolve(dir), asItReallyIs(dir)].flatMap(spellingsOf).map((spelled) => [spelled, name]));
36
+ const longestFirst = [...new Map(each)]
37
+ .filter(([spelled]) => spelled.length > 1)
38
+ .sort(([a], [b]) => b.length - a.length)
39
+ .map(([spelled, name]) => [wholeFolder(spelled), name]);
40
+ const text = (s) => longestFirst.reduce((t, [dir, name]) => t.replace(dir, () => name), s).replace(ANYONES_HOME, '~');
41
+ const walk = (v) => typeof v === 'string'
42
+ ? text(v)
43
+ : Array.isArray(v)
44
+ ? v.map(walk)
45
+ : v && typeof v === 'object'
46
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [text(k), walk(x)]))
47
+ : v;
48
+ return (value) => walk(value);
49
+ }
50
+ export function manifestPlaceholder(manifestDir, head) {
51
+ const inside = path.relative(asItReallyIs(head), asItReallyIs(manifestDir));
52
+ if (inside.startsWith('..') || path.isAbsolute(inside))
53
+ return '{{manifest}}';
54
+ return inside ? `{{checkout}}/${inside.split(path.sep).join('/')}` : '{{checkout}}';
55
+ }
56
+ function startsLikeAnImage(file) {
57
+ const start = Buffer.alloc(12);
58
+ const fd = openSync(file, 'r');
59
+ try {
60
+ readSync(fd, start, 0, 12, 0);
61
+ }
62
+ finally {
63
+ closeSync(fd);
64
+ }
65
+ return (start.subarray(0, 8).equals(PNG) ||
66
+ (start[0] === 0xff && start[1] === 0xd8 && start[2] === 0xff) ||
67
+ start.toString('latin1', 0, 4) === 'GIF8' ||
68
+ (start.toString('latin1', 0, 4) === 'RIFF' && start.toString('latin1', 8, 12) === 'WEBP'));
69
+ }
70
+ export const anImage = (name, real) => IMAGE_NAMES.test(name) && startsLikeAnImage(real);
71
+ export const asPlainText = (name) => (/\.txt$/i.test(name) ? name : `${name}.txt`);
72
+ export function textScrubbed(bytes, placed) {
73
+ const asUtf8 = bytes.toString('utf8');
74
+ const encoding = Buffer.from(asUtf8, 'utf8').equals(bytes) ? 'utf8' : 'latin1';
75
+ return Buffer.from(placed(bytes.toString(encoding)), encoding);
76
+ }
77
+ function unchangedSinceItsCommit(checkout, inside) {
78
+ const committed = gitOr(checkout, ['rev-parse', '--verify', '--quiet', `HEAD:./${inside}`]);
79
+ return (committed !== null &&
80
+ gitOr(checkout, ['hash-object', '--', inside]) === committed &&
81
+ gitOr(checkout, ['diff', '--quiet', 'HEAD', '--', inside]) !== null &&
82
+ gitOr(checkout, ['diff', '--quiet', '--cached', 'HEAD', '--', inside]) !== null);
83
+ }
84
+ export function publishableFrom(o) {
85
+ const runs = asItReallyIs(path.join(o.state, 'runs')) + path.sep;
86
+ const checkouts = [...new Set(o.checkouts.map(asItReallyIs))].sort((a, b) => b.length - a.length);
87
+ return (file) => {
88
+ let real;
89
+ try {
90
+ real = realpathSync(file);
91
+ if (!statSync(real).isFile())
92
+ return null;
93
+ accessSync(real, constants.R_OK);
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ if (real.startsWith(runs))
99
+ return real;
100
+ const checkout = checkouts.find((c) => real.startsWith(c + path.sep));
101
+ if (!checkout)
102
+ return null;
103
+ return unchangedSinceItsCommit(checkout, path.relative(checkout, real).split(path.sep).join('/'))
104
+ ? real
105
+ : null;
106
+ };
107
+ }
@@ -9,7 +9,7 @@ import { scrubDeep } from '../people/index.js';
9
9
  import { readScenarios } from '../scenarios/index.js';
10
10
  import { alive, stateDir } from '../services/index.js';
11
11
  import { apiOf } from './api.js';
12
- import { lastCompared } from './compared.js';
12
+ import { baseAsked, lastCompared } from './compared.js';
13
13
  import { serveFile, servePage } from './files.js';
14
14
  import { refusalOf, STAGE_HOST } from './guard.js';
15
15
  import { answer, bodyOf, fail, personIn, sideOf, str, worldIn } from './http.js';
@@ -84,7 +84,7 @@ export async function startStage(o) {
84
84
  checkoutOf,
85
85
  scenarioOn,
86
86
  runs: new Map(),
87
- compared: lastCompared(path.join(stateDir(m.dir), 'compare'), head.path, baseRef),
87
+ compared: lastCompared(path.join(stateDir(m.dir), 'compare'), head.path, baseAsked(head.path, baseRef, o.cwd)),
88
88
  sending,
89
89
  triesFile: path.join(stateDir(m.dir), 'tries.jsonl'),
90
90
  }),
@@ -0,0 +1,22 @@
1
+ import type { Manifest } from '../manifest/index.ts';
2
+ import type { CheckoutInfo } from '../run/index.ts';
3
+ export interface StaticCopy {
4
+ v: 1;
5
+ dir: string;
6
+ comparison: 'whole' | 'partial';
7
+ comparedAt: string;
8
+ base: CheckoutInfo;
9
+ head: CheckoutInfo;
10
+ line: string;
11
+ scenarios: number;
12
+ artifacts: number;
13
+ }
14
+ export interface StaticOptions {
15
+ head: string;
16
+ base: string;
17
+ cwd: string;
18
+ page?: string;
19
+ }
20
+ export declare const headWords: (head: CheckoutInfo) => string;
21
+ export declare const baseWords: (base: CheckoutInfo) => string;
22
+ export declare function writeStaticCopy(m: Manifest, dir: string, o: StaticOptions): StaticCopy;
@@ -0,0 +1,241 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { RehearseError } from '../errors.js';
5
+ import { validate } from '../schema.js';
6
+ import { stateDir } from '../services/index.js';
7
+ import { baseAsked, ofThisHeadAndBase } from './compared.js';
8
+ import { BUILT_PAGE } from './files.js';
9
+ import { anImage, asPlainText, manifestPlaceholder, placeholdersFor, publishableFrom, textScrubbed, } from './public.js';
10
+ const MARKED_AS_A_STATIC_COPY = 'data-stage="static"';
11
+ const WRITTEN_BY_AN_EARLIER_COPY = ['index.html', 'page', 'data'];
12
+ const ARTIFACTS_THE_PAGE_SHOWS = new Set(['screenshot', 'input']);
13
+ const COMPARISONS = [
14
+ ['whole', 'latest.json'],
15
+ ['partial', 'latest-partial.json'],
16
+ ];
17
+ const shortHash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 16);
18
+ export const headWords = (head) => `${head.commit ? head.commit.slice(0, 8) : (head.ref ?? path.basename(head.path))}${head.dirty ? ' + changes' : ''}`;
19
+ export const baseWords = (base) => `${base.ref ?? base.path}${base.commit ? `@${base.commit.slice(0, 8)}` : ''}`;
20
+ function chosenComparison(m, head, base) {
21
+ const found = [];
22
+ let unreadable = null;
23
+ let ofAnother = false;
24
+ for (const [kind, name] of COMPARISONS) {
25
+ const file = path.join(stateDir(m.dir), 'compare', name);
26
+ if (!existsSync(file))
27
+ continue;
28
+ let read;
29
+ try {
30
+ read = JSON.parse(readFileSync(file, 'utf8'));
31
+ }
32
+ catch {
33
+ unreadable ??= `${file} isn't JSON`;
34
+ continue;
35
+ }
36
+ const invalid = validate('comparison', read);
37
+ if (invalid.length > 0) {
38
+ unreadable ??= `${file} isn't a comparison Rehearse can read (${invalid[0].says})`;
39
+ continue;
40
+ }
41
+ if (!ofThisHeadAndBase(read, head, base)) {
42
+ ofAnother = true;
43
+ continue;
44
+ }
45
+ found.push({ kind, at: statSync(file).mtime, comparison: read });
46
+ }
47
+ const newest = found.sort((a, b) => b.at.getTime() - a.at.getTime())[0];
48
+ if (newest)
49
+ return newest;
50
+ throw new RehearseError('no_comparison', unreadable
51
+ ? `${unreadable}: run rehearse compare again.`
52
+ : ofAnother
53
+ ? `The latest comparison isn't of this checkout with ${base.ref}: run rehearse compare --base ${base.ref} here, or give --static the --base it compared with.`
54
+ : 'There is no comparison to copy yet: run rehearse compare first, then rehearse stage --static again.');
55
+ }
56
+ function builtPage(page) {
57
+ const html = path.join(page, 'index.html');
58
+ if (!existsSync(path.join(page, 'main.js')) || !existsSync(html))
59
+ throw new RehearseError('stage', "The stage's page isn't built: run pnpm build in Rehearse.");
60
+ return readFileSync(html, 'utf8')
61
+ .replace('<html ', `<html ${MARKED_AS_A_STATIC_COPY} `)
62
+ .replace(/\b(href|src)="(?![a-z]+:)/g, '$1="page/');
63
+ }
64
+ const anEarlierCopy = (dir) => {
65
+ try {
66
+ return readFileSync(path.join(dir, 'index.html'), 'utf8').includes(MARKED_AS_A_STATIC_COPY);
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ };
72
+ function readiedFolder(dir) {
73
+ if (!existsSync(dir)) {
74
+ mkdirSync(dir, { recursive: true });
75
+ return;
76
+ }
77
+ if (!statSync(dir).isDirectory())
78
+ throw new RehearseError('exists', `${dir} is a file: give a folder for the static copy.`);
79
+ if (readdirSync(dir).length === 0)
80
+ return;
81
+ if (!anEarlierCopy(dir))
82
+ throw new RehearseError('exists', `${dir} holds other files: give an empty folder, or one an earlier rehearse stage --static wrote.`);
83
+ for (const own of WRITTEN_BY_AN_EARLIER_COPY)
84
+ rmSync(path.join(dir, own), { recursive: true, force: true });
85
+ }
86
+ function artifactsToPublish(m, c, placed) {
87
+ const publishable = publishableFrom({
88
+ state: stateDir(m.dir),
89
+ checkouts: [c.head.checkout.path, c.base.checkout.path],
90
+ });
91
+ const copies = new Map();
92
+ const published = (a) => {
93
+ if (!ARTIFACTS_THE_PAGE_SHOWS.has(a.kind))
94
+ return [];
95
+ const real = publishable(a.path);
96
+ if (!real)
97
+ return [];
98
+ const name = path.basename(a.path);
99
+ const image = anImage(name, real);
100
+ if (a.kind === 'screenshot' && !image)
101
+ return [];
102
+ let copy = copies.get(real);
103
+ if (!copy) {
104
+ const bytes = image ? null : textScrubbed(readFileSync(real), placed);
105
+ copy = {
106
+ to: `data/files/${shortHash(bytes ?? readFileSync(real))}/${image ? name : asPlainText(name)}`,
107
+ bytes,
108
+ };
109
+ copies.set(real, copy);
110
+ }
111
+ return [{ ...a, path: copy.to, ...(!image && { name }) }];
112
+ };
113
+ return { published, copies };
114
+ }
115
+ function readObservation(file) {
116
+ if (!file || !existsSync(file))
117
+ return null;
118
+ let read;
119
+ try {
120
+ read = JSON.parse(readFileSync(file, 'utf8'));
121
+ }
122
+ catch {
123
+ throw new RehearseError('no_comparison', `${file} isn't JSON: run rehearse compare again.`);
124
+ }
125
+ const invalid = validate('observation', read);
126
+ if (invalid.length > 0)
127
+ throw new RehearseError('no_comparison', `${file} isn't an observation Rehearse can read (${invalid[0].says}): run rehearse compare again.`);
128
+ return read;
129
+ }
130
+ const shownRef = (s) => ({
131
+ id: s.id,
132
+ kind: s.kind,
133
+ name: s.name,
134
+ file: s.file,
135
+ ...(s.line !== undefined && { line: s.line }),
136
+ area: s.area,
137
+ });
138
+ const shownComparison = (e) => ({
139
+ verdict: e.verdict,
140
+ changed: e.changed,
141
+ said: e.said,
142
+ why: e.why,
143
+ failsOnBase: e.failsOnBase,
144
+ failsOnHead: e.failsOnHead,
145
+ differences: e.differences,
146
+ setAside: e.setAside,
147
+ });
148
+ export function writeStaticCopy(m, dir, o) {
149
+ const { kind, at, comparison: c } = chosenComparison(m, o.head, baseAsked(o.head, o.base, o.cwd));
150
+ const page = o.page ?? BUILT_PAGE;
151
+ const html = builtPage(page);
152
+ const placed = placeholdersFor([
153
+ [m.dir, manifestPlaceholder(m.dir, c.head.checkout.path)],
154
+ [c.base.checkout.path, '{{checkout}}'],
155
+ [c.head.checkout.path, '{{checkout}}'],
156
+ ]);
157
+ const { published, copies } = artifactsToPublish(m, c, placed);
158
+ const shown = (ob) => ob && {
159
+ ok: ob.ok,
160
+ failures: ob.failures,
161
+ broke: ob.broke ?? null,
162
+ observed: ob.observed,
163
+ artifacts: (ob.artifacts ?? []).flatMap(published),
164
+ };
165
+ const notRun = new Map();
166
+ for (const n of c.notRun) {
167
+ const seen = notRun.get(n.scenario.id) ?? { scenario: n.scenario, sides: [] };
168
+ seen.sides.push({ side: n.side, step: n.step, says: n.says });
169
+ notRun.set(n.scenario.id, seen);
170
+ }
171
+ const each = [
172
+ ...c.scenarios.map((e) => ({ scenario: e.scenario, entry: e, sides: [] })),
173
+ ...[...notRun.values()].map((n) => ({ scenario: n.scenario, entry: null, sides: n.sides })),
174
+ ];
175
+ const details = each.map(({ scenario, entry, sides }) => {
176
+ const base = readObservation(entry?.observations?.base);
177
+ const head = readObservation(entry?.observations?.head);
178
+ return {
179
+ data: `data/scenarios/${shortHash(scenario.id)}.json`,
180
+ row: { ...shownRef(scenario), verdict: entry?.verdict ?? null },
181
+ detail: {
182
+ v: 1,
183
+ scenario: { ...shownRef(scenario), world: head?.world ?? null, person: head?.person ?? null },
184
+ spec: null,
185
+ ...placed({
186
+ comparison: entry && shownComparison(entry),
187
+ base: shown(base),
188
+ head: shown(head),
189
+ notRun: sides,
190
+ }),
191
+ tries: [],
192
+ },
193
+ };
194
+ });
195
+ const index = {
196
+ v: 1,
197
+ head: {
198
+ path: '{{checkout}}',
199
+ ref: c.head.checkout.ref,
200
+ commit: c.head.checkout.commit,
201
+ dirty: c.head.checkout.dirty,
202
+ },
203
+ base: { ref: c.base.checkout.ref, commit: c.base.checkout.commit },
204
+ line: placed(c.line),
205
+ comparedAt: at.toISOString(),
206
+ comparison: kind,
207
+ scenarios: details.map((d) => ({ ...d.row, data: d.data })),
208
+ people: [],
209
+ person: null,
210
+ worlds: [],
211
+ world: null,
212
+ };
213
+ readiedFolder(dir);
214
+ cpSync(page, path.join(dir, 'page'), {
215
+ recursive: true,
216
+ filter: (from) => from !== path.join(page, 'index.html'),
217
+ });
218
+ writeFileSync(path.join(dir, 'index.html'), html);
219
+ mkdirSync(path.join(dir, 'data', 'scenarios'), { recursive: true });
220
+ for (const d of details)
221
+ writeFileSync(path.join(dir, d.data), `${JSON.stringify(d.detail)}\n`);
222
+ writeFileSync(path.join(dir, 'data', 'index.json'), `${JSON.stringify(index)}\n`);
223
+ for (const [real, copy] of copies) {
224
+ mkdirSync(path.dirname(path.join(dir, copy.to)), { recursive: true });
225
+ if (copy.bytes)
226
+ writeFileSync(path.join(dir, copy.to), copy.bytes);
227
+ else
228
+ copyFileSync(real, path.join(dir, copy.to));
229
+ }
230
+ return {
231
+ v: 1,
232
+ dir,
233
+ comparison: kind,
234
+ comparedAt: at.toISOString(),
235
+ base: c.base.checkout,
236
+ head: c.head.checkout,
237
+ line: c.line,
238
+ scenarios: details.length,
239
+ artifacts: copies.size,
240
+ };
241
+ }