@kurvball/rehearse 1.8.0 → 1.9.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 (36) hide show
  1. package/dist/commands/stage.js +19 -3
  2. package/dist/schema.d.ts +1 -1
  3. package/dist/schema.js +1 -0
  4. package/dist/stage/client/client/api.js +4 -1
  5. package/dist/stage/client/client/index.js +1 -0
  6. package/dist/stage/client/client/static.js +28 -0
  7. package/dist/stage/client/features/canvas/call.js +12 -3
  8. package/dist/stage/client/features/canvas/file.js +4 -2
  9. package/dist/stage/client/features/canvas/piece.js +12 -2
  10. package/dist/stage/client/features/list/list.js +6 -1
  11. package/dist/stage/client/features/scenario/heading.js +3 -2
  12. package/dist/stage/client/features/scenario/scenario.js +8 -4
  13. package/dist/stage/client/main.js +7 -3
  14. package/dist/stage/client/stage.css +11 -0
  15. package/dist/stage/compared.d.ts +7 -1
  16. package/dist/stage/compared.js +16 -4
  17. package/dist/stage/files.d.ts +1 -0
  18. package/dist/stage/files.js +6 -4
  19. package/dist/stage/index.d.ts +1 -0
  20. package/dist/stage/index.js +1 -0
  21. package/dist/stage/public.d.ts +9 -0
  22. package/dist/stage/public.js +107 -0
  23. package/dist/stage/server.js +2 -2
  24. package/dist/stage/static.d.ts +22 -0
  25. package/dist/stage/static.js +241 -0
  26. package/llms.txt +2 -1
  27. package/package.json +1 -1
  28. package/schema/v1/samples/static.json +21 -0
  29. package/schema/v1/static.schema.json +34 -0
  30. package/schema/vendor/acta/LICENSE +21 -0
  31. package/schema/vendor/acta/README.md +12 -0
  32. package/schema/vendor/acta/v1/canonical.schema.json +818 -0
  33. package/schema/vendor/acta/v1/check.schema.json +35 -0
  34. package/schema/vendor/acta/v1/record.schema.json +1443 -0
  35. package/schema/vendor/acta/v1/run-model.schema.json +1074 -0
  36. package/skill/rehearse/SKILL.md +1 -0
@@ -2,8 +2,21 @@ import path from 'node:path';
2
2
  import { announceFromOf, checkoutOf, manifestOf, said } from './command.js';
3
3
  import { many, one } from '../args.js';
4
4
  import { errorText, usage } from '../errors.js';
5
- import { startStage } from '../stage/index.js';
5
+ import { baseWords, headWords, startStage, writeStaticCopy } from '../stage/index.js';
6
6
  export const DEFAULT_STAGE_PORT = 4400;
7
+ const ONLY_FOR_A_LIVE_STAGE = ['head', 'port', 'announce', 'announce-from', 'said'];
8
+ function staticCopy(dir, args, ctx) {
9
+ const live = ONLY_FOR_A_LIVE_STAGE.find((flag) => args.values.has(flag));
10
+ if (live)
11
+ throw usage(`--static copies the latest comparison as it is and starts no stage, so it takes no --${live}.`);
12
+ const m = manifestOf(ctx);
13
+ const copy = writeStaticCopy(m, path.resolve(ctx.cwd, dir), {
14
+ head: checkoutOf(m, null, ctx.cwd),
15
+ base: one(args, 'base') ?? m.base,
16
+ cwd: ctx.cwd,
17
+ });
18
+ return said(copy, `Wrote a static copy of the comparison of ${headWords(copy.head)} with ${baseWords(copy.base)} to ${copy.dir}: ${copy.scenarios} scenario${copy.scenarios === 1 ? '' : 's'}.\nServe the folder with any static file server; a browser won't run it opened from disk.\n`);
19
+ }
7
20
  export function portOf(given) {
8
21
  if (given === null)
9
22
  return { port: DEFAULT_STAGE_PORT, anyPort: true };
@@ -15,9 +28,12 @@ export function portOf(given) {
15
28
  export const stage = {
16
29
  name: 'stage',
17
30
  summary: "Serves the stage: every scenario on one page, in Base, Head and Diff, with Works, Doesn't and a note.",
18
- usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--port <port>] [--announce <file>] [--announce-from changesets] [--said <scenario>]…\n\nIt runs until you stop it (Ctrl-C), and stops the services it brought up.\nCompare on the stage reads the announcement as rehearse compare does.',
19
- spec: { valued: ['base', 'head', 'port', 'announce', 'announce-from', 'said'], bare: [] },
31
+ usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--port <port>] [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--static <dir>]\n\nIt runs until you stop it (Ctrl-C), and stops the services it brought up.\nCompare on the stage reads the announcement as rehearse compare does.\nWith --static <dir>, it writes the stage of the latest comparison into <dir> as plain files, for any static host, and exits.',
32
+ spec: { valued: ['base', 'head', 'port', 'announce', 'announce-from', 'said', 'static'], bare: [] },
20
33
  async run(args, ctx) {
34
+ const dir = one(args, 'static');
35
+ if (dir !== null)
36
+ return staticCopy(dir, args, ctx);
21
37
  const m = manifestOf(ctx);
22
38
  const { port, anyPort } = portOf(one(args, 'port'));
23
39
  const announce = one(args, 'announce');
package/dist/schema.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js';
2
2
  export declare const SCHEMA_DIR: string;
3
- export declare const SCHEMAS: readonly ['manifest', 'flow', 'file-scenario', 'announce', 'services', 'people', 'worlds', 'list', 'observation', 'comparison', 'drive', 'open', 'stage', 'try', 'error', 'dependents', 'check', 'init', 'validate', 'up', 'clean'];
3
+ export declare const SCHEMAS: readonly ['manifest', 'flow', 'file-scenario', 'announce', 'services', 'people', 'worlds', 'list', 'observation', 'comparison', 'drive', 'open', 'stage', 'static', 'try', 'error', 'dependents', 'check', 'init', 'validate', 'up', 'clean'];
4
4
  export type SchemaName = (typeof SCHEMAS)[number];
5
5
  export declare const schemaId: (name: SchemaName | 'common') => string;
6
6
  export declare function validatorOf(name: SchemaName): ValidateFunction;
package/dist/schema.js CHANGED
@@ -17,6 +17,7 @@ export const SCHEMAS = [
17
17
  'drive',
18
18
  'open',
19
19
  'stage',
20
+ 'static',
20
21
  'try',
21
22
  'error',
22
23
  'dependents',
@@ -1,5 +1,8 @@
1
+ import { fileInTheCopy, fromTheCopy, staticCopy } from './static.js';
1
2
  const refusedByTheStage = (answer) => answer.ok === false && answer.error !== undefined;
2
3
  export async function api(path, body) {
4
+ if (staticCopy)
5
+ return fromTheCopy(path, body);
3
6
  const r = await fetch(path, body === undefined
4
7
  ? {}
5
8
  : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
@@ -8,4 +11,4 @@ export async function api(path, body) {
8
11
  throw new Error(json.error?.says ?? `The stage answered ${r.status}.`);
9
12
  return json;
10
13
  }
11
- export const fileUrl = (file) => `/files?path=${encodeURIComponent(file)}`;
14
+ export const fileUrl = (file) => staticCopy ? fileInTheCopy(file) : `/files?path=${encodeURIComponent(file)}`;
@@ -1 +1,2 @@
1
1
  export { api, fileUrl } from './api.js';
2
+ export { staticCopy } from './static.js';
@@ -0,0 +1,28 @@
1
+ export const staticCopy = document.documentElement.dataset.stage === 'static';
2
+ const NEEDS_THE_STAGE = 'This is a static copy of a comparison: rehearse stage runs it live.';
3
+ let copiedIndex = null;
4
+ async function copied(file) {
5
+ const r = await fetch(file);
6
+ if (!r.ok)
7
+ throw new Error(`This static copy has no ${file} (${r.status}).`);
8
+ return (await r.json());
9
+ }
10
+ const indexOfTheCopy = () => (copiedIndex ??= copied('data/index.json'));
11
+ export async function fromTheCopy(asked, body) {
12
+ if (body !== undefined)
13
+ throw new Error(NEEDS_THE_STAGE);
14
+ const url = new URL(asked, 'http://stage.invalid');
15
+ if (url.pathname === '/api/index')
16
+ return (await indexOfTheCopy());
17
+ if (url.pathname === '/api/scenario') {
18
+ const id = url.searchParams.get('id') ?? '';
19
+ const row = (await indexOfTheCopy()).scenarios.find((s) => s.id === id);
20
+ if (!row)
21
+ throw new Error(`This static copy has no scenario “${id}”.`);
22
+ return copied(row.data);
23
+ }
24
+ if (url.pathname === '/api/tries')
25
+ return { v: 1, tries: [] };
26
+ throw new Error(NEEDS_THE_STAGE);
27
+ }
28
+ export const fileInTheCopy = (file) => file.split('/').map(encodeURIComponent).join('/');
@@ -1,18 +1,27 @@
1
- import { api } from '../../client/index.js';
2
- import { disableKeepingFocus, enableAgain, h, say, state } from '../../primitives/index.js';
1
+ import { api, staticCopy } from '../../client/index.js';
2
+ import { disableKeepingFocus, enableAgain, h, say, state, } from '../../primitives/index.js';
3
3
  import { differencesOrCompare, failuresOf, pretty, sideObs } from './parts.js';
4
4
  const callEditsKeptAcrossDraws = new Map();
5
5
  function answerOf(ctx, o, title) {
6
6
  const seen = o?.observed;
7
7
  if (!o || !seen)
8
- return h('div', {}, h('h3', {}, title), o ? (failuresOf(o) ?? ctx.notRunYet('head')) : h('p', { class: 'note' }, 'Not run yet.'));
8
+ return h('div', {}, h('h3', {}, title), o
9
+ ? (failuresOf(o) ?? ctx.notRunYet('head'))
10
+ : h('p', { class: 'note' }, staticCopy ? 'Not run in this comparison.' : 'Not run yet.'));
9
11
  const ok = typeof seen.status === 'number' && seen.status < 400;
10
12
  return h('div', {}, h('h3', {}, title), h('div', { class: 'answer-head' }, h('span', { class: `code-badge ${ok ? 'ok' : 'bad'}` }, String(seen.status ?? '—')), h('span', {}, seen.contentType ?? ''), h('span', { class: 'note' }, seen.who ? `as ${seen.who}` : '')), h('pre', {}, pretty(seen.body)), failuresOf(o));
11
13
  }
14
+ function asCompared(ctx, side) {
15
+ const o = sideObs(ctx, side);
16
+ const request = o?.observed?.request;
17
+ return h('div', { class: 'split' }, h('div', {}, h('h3', {}, 'Request'), h('pre', {}, request ?? '—')), answerOf(ctx, o, side === 'base' ? 'On the base' : 'On the head'));
18
+ }
12
19
  export const callView = (ctx) => {
13
20
  if (ctx.mode === 'diff')
14
21
  return h('div', {}, differencesOrCompare(ctx), h('div', { class: 'split' }, answerOf(ctx, ctx.detail.base, 'On the base'), answerOf(ctx, ctx.detail.head, 'On the head')));
15
22
  const side = ctx.mode;
23
+ if (staticCopy)
24
+ return asCompared(ctx, side);
16
25
  const id = ctx.detail.scenario.id;
17
26
  const editor = h('textarea', {
18
27
  class: 'code',
@@ -1,4 +1,4 @@
1
- import { fileUrl } from '../../client/index.js';
1
+ import { fileUrl, staticCopy } from '../../client/index.js';
2
2
  import { h } from '../../primitives/index.js';
3
3
  import { differencesOrCompare, failuresOf, markLinesNotIn, pretty, sideObs } from './parts.js';
4
4
  function outputView(o, other) {
@@ -31,6 +31,8 @@ export const fileView = (ctx) => {
31
31
  const theirs = ctx.mode === 'diff' ? outputsOf(ctx.detail.base) : null;
32
32
  const input = o.artifacts?.find((a) => a.kind === 'input');
33
33
  return h('div', {}, ctx.mode === 'diff' ? differencesOrCompare(ctx) : null, input
34
- ? h('p', { class: 'note' }, 'Input: ', h('a', { href: fileUrl(input.path), target: '_blank' }, input.path.split('/').at(-1) ?? input.path))
34
+ ? h('p', { class: 'note' }, 'Input: ', staticCopy
35
+ ? h('a', { href: fileUrl(input.path), type: 'text/plain', rel: 'noopener' }, input.name ?? input.path.split('/').at(-1) ?? input.path)
36
+ : h('a', { href: fileUrl(input.path), target: '_blank' }, input.path.split('/').at(-1) ?? input.path))
35
37
  : null, failuresOf(o), outputsOf(o).map((out) => h('div', {}, h('h3', {}, ctx.mode === 'diff' ? `${out.file}, on the head, against the base` : out.file), outputView(out, theirs ? (theirs.find((x) => x.file === out.file) ?? null) : null))));
36
38
  };
@@ -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;