@kurvball/rehearse 1.12.2 → 1.13.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 (52) hide show
  1. package/README.md +1 -0
  2. package/dist/commands/drive.js +16 -7
  3. package/dist/commands/index.js +2 -0
  4. package/dist/commands/record.d.ts +2 -0
  5. package/dist/commands/record.js +146 -0
  6. package/dist/drive/browser.d.ts +12 -1
  7. package/dist/drive/browser.js +64 -5
  8. package/dist/drive/daemon.js +91 -90
  9. package/dist/drive/grammar.d.ts +1 -0
  10. package/dist/drive/grammar.js +3 -1
  11. package/dist/drive/index.d.ts +9 -5
  12. package/dist/drive/index.js +9 -5
  13. package/dist/drive/log.d.ts +19 -0
  14. package/dist/drive/log.js +75 -0
  15. package/dist/drive/names.d.ts +2 -0
  16. package/dist/drive/names.js +4 -0
  17. package/dist/drive/open.d.ts +25 -0
  18. package/dist/drive/open.js +95 -0
  19. package/dist/drive/secrets.d.ts +3 -0
  20. package/dist/drive/secrets.js +31 -21
  21. package/dist/drive/state.d.ts +2 -0
  22. package/dist/drive/state.js +11 -0
  23. package/dist/drive/walk.d.ts +39 -0
  24. package/dist/drive/walk.js +112 -0
  25. package/dist/drive/watcher.d.ts +28 -0
  26. package/dist/drive/watcher.js +255 -0
  27. package/dist/kinds/flow/kind.js +2 -2
  28. package/dist/manifest/index.d.ts +1 -1
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/types.d.ts +1 -0
  31. package/dist/record/flow.d.ts +38 -0
  32. package/dist/record/flow.js +88 -0
  33. package/dist/record/index.d.ts +6 -0
  34. package/dist/record/index.js +5 -0
  35. package/dist/record/keys.d.ts +24 -0
  36. package/dist/record/keys.js +92 -0
  37. package/dist/record/page.d.ts +47 -0
  38. package/dist/record/page.js +188 -0
  39. package/dist/record/person.d.ts +22 -0
  40. package/dist/record/person.js +286 -0
  41. package/dist/record/taking.d.ts +39 -0
  42. package/dist/record/taking.js +214 -0
  43. package/dist/record/walked.d.ts +10 -0
  44. package/dist/record/walked.js +59 -0
  45. package/dist/schema.d.ts +1 -1
  46. package/dist/schema.js +1 -0
  47. package/llms.txt +3 -2
  48. package/package.json +1 -1
  49. package/schema/v1/flow.schema.json +4 -0
  50. package/schema/v1/record.schema.json +64 -0
  51. package/schema/v1/samples/record.json +20 -0
  52. package/skill/rehearse/SKILL.md +14 -1
package/README.md CHANGED
@@ -68,6 +68,7 @@ Scenarios use formats agents already write:
68
68
  | `rehearse compare [--base <ref>]` | Every scenario on the base and the head, compared |
69
69
  | `rehearse announce [--draft]` | What the change announces, or a draft to rewrite |
70
70
  | `rehearse drive <step>` | One step for an agent: click, fill, snapshot… |
71
+ | `rehearse record <file> [--from-drive]` | Writes a flow from a click-through or a drive |
71
72
  | `rehearse clean` | Removes old base checkouts, runs and comparisons |
72
73
  | `rehearse validate <schema> [file]` | Checks a file or stdin against a schema in v1 |
73
74
  | `rehearse mcp` | Serves list, compare, drive, announce over MCP |
@@ -3,7 +3,7 @@ import { closeSync, mkdirSync, openSync, readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { checkoutOf, manifestOf, said } from './command.js';
6
- import { failed, driveArgv, exitOf, parseDrive, resultText, VERBS, forgetDriving, readDriving, writeDriving, } from '../drive/index.js';
6
+ import { addToWalk, beginWalk, failed, driveArgv, exitOf, parseDrive, resultText, VERBS, forgetDriving, readDriving, walked, writeDriving, } from '../drive/index.js';
7
7
  import { sh, tail } from '../exec.js';
8
8
  import { fillEnv } from '../manifest/index.js';
9
9
  import { applyWorld, baseVars } from '../run/index.js';
@@ -82,12 +82,16 @@ Each answers in the drive result shape (schema/v1/drive.schema.json): 0 done, 1
82
82
  if (world)
83
83
  await applyWorld(m, world, 'add', checkout, baseVars(m, checkout, running));
84
84
  }
85
- writeDriving(m.dir, {
85
+ const since = new Date().toISOString();
86
+ writeDriving(m.dir, { driver: 'service', service: svc.name, checkout, started: !already, since });
87
+ beginWalk(m.dir, {
86
88
  driver: 'service',
87
89
  service: svc.name,
88
- checkout,
89
- started: !already,
90
- since: new Date().toISOString(),
90
+ piece: null,
91
+ world,
92
+ person: null,
93
+ start: null,
94
+ since,
91
95
  });
92
96
  const person = options.as ?? null;
93
97
  return answer({
@@ -202,8 +206,13 @@ Each answers in the drive result shape (schema/v1/drive.schema.json): 0 done, 1
202
206
  timeoutMs: 120_000,
203
207
  });
204
208
  try {
205
- const r = JSON.parse(ran.stdout.trim().split('\n').at(-1) ?? '');
206
- return answer({ v: 1, driver: 'service', ...r });
209
+ const r = {
210
+ v: 1,
211
+ driver: 'service',
212
+ ...JSON.parse(ran.stdout.trim().split('\n').at(-1) ?? ''),
213
+ };
214
+ addToWalk(m.dir, walked(command, r.ok === true, 'unseen'));
215
+ return answer(r);
207
216
  }
208
217
  catch {
209
218
  return answer(failed(command.command, at, 'crashed', `\`${svc.drive}\` answered with no JSON: ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`, 'service'));
@@ -6,6 +6,7 @@ import { drive } from './drive.js';
6
6
  import { list } from './list.js';
7
7
  import { mcp } from './mcp.js';
8
8
  import { open } from './open.js';
9
+ import { record } from './record.js';
9
10
  import { run } from './run.js';
10
11
  import { down, up } from './up.js';
11
12
  import { init } from './init.js';
@@ -32,6 +33,7 @@ export const COMMANDS = [
32
33
  compare,
33
34
  announce,
34
35
  drive,
36
+ record,
35
37
  stage,
36
38
  open,
37
39
  clean,
@@ -0,0 +1,2 @@
1
+ import type { Command } from './command.ts';
2
+ export declare const record: Command;
@@ -0,0 +1,146 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { checkoutOf, manifestOf, said } from './command.js';
4
+ import { one } from '../args.js';
5
+ import { flushDriving, readWalk } from '../drive/index.js';
6
+ import { RehearseError, usage } from '../errors.js';
7
+ import { flowOf, fromTheWalk, nameFromFile, interruptsUntilWritten, recordAPerson, } from '../record/index.js';
8
+ import { readScenarios } from '../scenarios/index.js';
9
+ const CDP_PORT = 'REHEARSE_RECORD_CDP_PORT';
10
+ const MOST_WORDS = 120;
11
+ const TAKEN_FROM_THE_DRIVE = ['service', 'world', 'as', 'start'];
12
+ function portOf(env) {
13
+ const given = env[CDP_PORT];
14
+ if (!given)
15
+ return null;
16
+ const port = Number(given);
17
+ if (!Number.isInteger(port) || port < 1 || port > 65_535)
18
+ throw usage(`$${CDP_PORT} is a port, from 1 to 65535, not “${given}”.`);
19
+ return port;
20
+ }
21
+ const counted = (n, single, plural) => `${n} ${n === 1 ? single : plural}`;
22
+ async function fromTheDrive(m) {
23
+ await flushDriving(m.dir);
24
+ const walk = readWalk(m.dir);
25
+ if (!walk)
26
+ throw new RehearseError('no_steps', 'No drive has run here to record: walk the product with `rehearse drive start` and its steps first.');
27
+ const from = fromTheWalk(walk);
28
+ const left = [
29
+ from.failed ? counted(from.failed, 'failed step', 'failed steps') : '',
30
+ from.looks ? counted(from.looks, 'look', 'looks') : '',
31
+ ].filter(Boolean);
32
+ return {
33
+ from: 'drive',
34
+ head: from.head,
35
+ taken: from.taken,
36
+ notes: from.notes,
37
+ left: left.length ? `Left out ${left.join(' and ')}.` : null,
38
+ nothing: `The latest drive, begun ${walk.began.since}, took no step a flow keeps: a click, fill, type, key, or a snapshot of a named element that worked.`,
39
+ };
40
+ }
41
+ async function fromAPerson(m, args, ctx, interrupts) {
42
+ const watched = await recordAPerson(m, checkoutOf(m, null, ctx.cwd), {
43
+ service: one(args, 'service'),
44
+ world: one(args, 'world'),
45
+ as: one(args, 'as'),
46
+ start: one(args, 'start'),
47
+ devtoolsPort: portOf(ctx.env),
48
+ interrupts,
49
+ progress: ctx.progress,
50
+ });
51
+ return {
52
+ from: 'person',
53
+ ...watched,
54
+ left: null,
55
+ nothing: 'Nothing was recorded: the window closed before a click, a fill or a key Rehearse could name.',
56
+ };
57
+ }
58
+ function warningText(file, w) {
59
+ return `${w.line === null ? file : `${file}:${w.line}`}: ${w.says}`;
60
+ }
61
+ export const record = {
62
+ name: 'record',
63
+ summary: 'Writes a flow from a click-through, every step by accessible name: the steps a drive took, or what you do in a browser window.',
64
+ usage: `rehearse record <file> [--from-drive | --service <name> [--world <name>] [--as <person>] [--start <path>]] [--name <words>] [--force] [--json]
65
+
66
+ --from-drive writes the steps the current or latest \`rehearse drive\` took.
67
+ Otherwise it brings the service up as \`rehearse drive start\` does, opens it in a Chromium window and records
68
+ each click, fill, choice and key you make there, until you close the window or press Ctrl-C.
69
+ Either way it writes <file> as a flow, prints it, and says what to check in it.`,
70
+ spec: { valued: ['service', 'world', 'as', 'start', 'name'], bare: ['from-drive', 'force'] },
71
+ async run(args, ctx) {
72
+ const [file, ...more] = args.positional;
73
+ if (!file)
74
+ throw usage('Name the flow file to write, such as flows/sign-in.flow.yaml.');
75
+ if (more.length)
76
+ throw usage(`rehearse record writes one file, not “${more[0]}” too.`);
77
+ if (!/\.ya?ml$/i.test(file))
78
+ throw usage("rehearse record writes YAML: end the file's name in .flow.yaml, such as flows/sign-in.flow.yaml.");
79
+ const fromDrive = args.flags.has('from-drive');
80
+ const both = TAKEN_FROM_THE_DRIVE.find((flag) => args.values.has(flag));
81
+ if (fromDrive && both)
82
+ throw usage(`--from-drive takes the service, world, person and start the drive began with, so it takes no --${both}.`);
83
+ const name = one(args, 'name') ?? nameFromFile(file);
84
+ if (name.length > MOST_WORDS)
85
+ throw usage(`--name takes up to ${MOST_WORDS} characters.`);
86
+ const m = manifestOf(ctx);
87
+ const abs = path.resolve(ctx.cwd, file);
88
+ const force = args.flags.has('force');
89
+ const there = existsSync(abs);
90
+ if (there && !force)
91
+ throw new RehearseError('exists', `${file} is already there. Give --force to replace it.`);
92
+ const interrupts = interruptsUntilWritten();
93
+ try {
94
+ const recorded = fromDrive ? await fromTheDrive(m) : await fromAPerson(m, args, ctx, interrupts);
95
+ return await writeTheFlow(m, ctx, { file, abs, name, force, there }, recorded);
96
+ }
97
+ finally {
98
+ interrupts.release();
99
+ }
100
+ },
101
+ };
102
+ async function writeTheFlow(m, ctx, { file, abs, name, force, there }, recorded) {
103
+ const written = flowOf({ name, ...recorded.head }, recorded.taken, recorded.notes);
104
+ if (!written)
105
+ throw new RehearseError('no_steps', `${recorded.nothing} Rehearse wrote no file.`);
106
+ mkdirSync(path.dirname(abs), { recursive: true });
107
+ try {
108
+ writeFileSync(abs, written.text, { flag: force ? 'w' : 'wx' });
109
+ }
110
+ catch (error) {
111
+ if (error.code === 'EEXIST')
112
+ throw new RehearseError('exists', `${file} appeared while Rehearse recorded. Give --force to replace it.`);
113
+ throw error;
114
+ }
115
+ const checkout = checkoutOf(m, null, ctx.cwd);
116
+ const read = await readScenarios(m, checkout, ['flow']);
117
+ const scenario = read.scenarios.find((s) => path.resolve(s.abs) === abs);
118
+ const warnings = [
119
+ ...written.warnings,
120
+ ...(scenario
121
+ ? []
122
+ : [
123
+ {
124
+ line: null,
125
+ step: null,
126
+ says: `rehearse.yaml's scenarios.flows doesn't list ${path.relative(checkout, abs)}, so \`rehearse run\` won't find it: add a glob that matches it, such as 'flows/*.flow.yaml'.`,
127
+ },
128
+ ]),
129
+ ];
130
+ const shown = path.relative(ctx.cwd, abs) || abs;
131
+ const out = {
132
+ v: 1,
133
+ file: abs,
134
+ from: recorded.from,
135
+ replaced: there,
136
+ steps: written.steps,
137
+ warnings,
138
+ };
139
+ const after = [
140
+ ...(recorded.left ? [recorded.left] : []),
141
+ ...warnings.map((w) => warningText(shown, w)),
142
+ ...(scenario ? [`Run it: rehearse run ${scenario.id}`] : []),
143
+ ];
144
+ const text = [`Wrote ${shown}:`, '', written.text.trimEnd(), ...(after.length ? ['', ...after] : [])];
145
+ return said(out, `${text.join('\n')}\n`);
146
+ }
@@ -1,9 +1,15 @@
1
1
  import type { Browser, BrowserContext, Page } from 'playwright-core';
2
2
  import { type Manifest } from '../manifest/index.ts';
3
3
  import { type Command, type DriveResult, type Failure, type Step, type Verb } from './grammar.ts';
4
+ import { type Picked } from './names.ts';
5
+ import { type BecameSecret, type Looked } from './watcher.ts';
4
6
  export declare const ACT_MS = 5000;
5
7
  export declare const FIXED_TIME: Date;
6
- export declare function launch(): Promise<Browser>;
8
+ export interface Launching {
9
+ headless?: boolean;
10
+ args?: readonly string[];
11
+ }
12
+ export declare function launch(how?: Launching): Promise<Browser>;
7
13
  export declare class Stopped extends Error {
8
14
  name: string;
9
15
  readonly failure: Exclude<Failure, 'usage'>;
@@ -13,6 +19,11 @@ export declare class Stopped extends Error {
13
19
  export declare const treeOf: (page: Page) => Promise<string>;
14
20
  export declare const seenTree: (page: Page) => Promise<string>;
15
21
  export declare function calm(page: Page): Promise<string>;
22
+ export declare function picks(page: Page, name: string, role: string | null): Promise<Picked>;
23
+ export declare function focusedNow(page: Page): Promise<Looked>;
24
+ export declare function fieldNow(page: Page, name: string, role: string | null): Promise<Looked>;
25
+ export declare function secretValueOf(page: Page, key: string): Promise<string | null>;
26
+ export declare function recheckNow(page: Page, keys: readonly string[]): Promise<BecameSecret[]>;
16
27
  export declare const failed: (command: Verb | null, at: number, failure: Failure, says: string, driver?: string | null) => DriveResult;
17
28
  export declare function act(page: Page, command: Command, at?: number): Promise<DriveResult>;
18
29
  export interface SignIn {
@@ -3,8 +3,9 @@ import path from 'node:path';
3
3
  import { RehearseError } from '../errors.js';
4
4
  import { fill, fillEnv } from '../manifest/index.js';
5
5
  import { FAILURE_WORDS, stepCommand, } from './grammar.js';
6
- import { ambiguousWords, findNamed, namedIn, notFoundWords, sameWords } from './names.js';
6
+ import { ambiguousWords, findNamed, namedIn, notFoundWords, sameWords, } from './names.js';
7
7
  import { noteSecretsOn, rememberSecretFields, secretsHidden, secretsHiddenInWords } from './secrets.js';
8
+ import { SECRETS } from './watcher.js';
8
9
  export const ACT_MS = 5_000;
9
10
  const CALM_MS = 120;
10
11
  const CALM_LIMIT_MS = 4_000;
@@ -21,10 +22,13 @@ async function playwright() {
21
22
  throw new RehearseError('no_browser', 'Rehearse drives a browser with playwright-core, which isn’t installed. Install Rehearse with its optional dependencies, then `npx playwright-core install chromium`.');
22
23
  }
23
24
  }
24
- export async function launch() {
25
+ export async function launch(how = {}) {
25
26
  const pw = await playwright();
26
27
  try {
27
- return await pw.chromium.launch({ headless: true, args: ['--disable-dev-shm-usage'] });
28
+ return await pw.chromium.launch({
29
+ headless: how.headless ?? true,
30
+ args: ['--disable-dev-shm-usage', ...(how.args ?? [])],
31
+ });
28
32
  }
29
33
  catch (error) {
30
34
  const said = error.message.split('\n')[0] ?? '';
@@ -73,6 +77,55 @@ async function theOne(page, name, role) {
73
77
  const lines = await Promise.all((await at.all()).map(async (each) => (await secretsHidden(each, () => each.ariaSnapshot())).split('\n')[0].trim()));
74
78
  throw new Stopped('ambiguous', sameWords(one, lines));
75
79
  }
80
+ const optionsOf = (target) => target.evaluate((el) => (el instanceof HTMLSelectElement ? [...el.options].map((o) => o.label) : null), undefined, { timeout: ACT_MS });
81
+ const noOptionWords = (field, wanted, options) => `“${field}” has no option “${wanted}”. It has ${options.map((o) => `“${o}”`).join(', ') || 'none'}.`;
82
+ export async function picks(page, name, role) {
83
+ try {
84
+ await theOne(page, name, role);
85
+ return 'one';
86
+ }
87
+ catch (error) {
88
+ return error instanceof Stopped && error.failure === 'ambiguous' ? 'many' : 'none';
89
+ }
90
+ }
91
+ const NOTHING_SEEN = { key: null, typed: 'unseen', identities: [], choice: false };
92
+ export async function focusedNow(page) {
93
+ try {
94
+ const looked = await page.evaluate((key) => window[Symbol.for(key)]?.focused() ?? null, SECRETS);
95
+ return looked ?? NOTHING_SEEN;
96
+ }
97
+ catch {
98
+ return NOTHING_SEEN;
99
+ }
100
+ }
101
+ export async function fieldNow(page, name, role) {
102
+ try {
103
+ const { at } = await theOne(page, name, role);
104
+ const looked = await at.evaluate((el, key) => window[Symbol.for(key)]?.lookAt(el) ?? null, SECRETS);
105
+ return looked ?? NOTHING_SEEN;
106
+ }
107
+ catch {
108
+ return NOTHING_SEEN;
109
+ }
110
+ }
111
+ export async function secretValueOf(page, key) {
112
+ try {
113
+ return await page.evaluate(({ secrets, wanted }) => window[Symbol.for(secrets)]?.secretValueOf(wanted) ?? null, { secrets: SECRETS, wanted: key });
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ }
119
+ export async function recheckNow(page, keys) {
120
+ if (keys.length === 0)
121
+ return [];
122
+ const each = await Promise.all(page
123
+ .frames()
124
+ .map((frame) => frame
125
+ .evaluate(({ key, wanted }) => window[Symbol.for(key)]?.recheck(wanted) ?? [], { key: SECRETS, wanted: [...keys] })
126
+ .catch(() => [])));
127
+ return each.flat();
128
+ }
76
129
  const timedOut = (error) => error instanceof Error && error.name === 'TimeoutError';
77
130
  const done = (command, at, extra = {}) => ({
78
131
  v: 1,
@@ -120,7 +173,13 @@ async function acted(page, command, at) {
120
173
  case 'fill': {
121
174
  const { named, at: target } = await theOne(page, command.name, command.role);
122
175
  try {
123
- await target.fill(command.text, { timeout: ACT_MS });
176
+ const options = await optionsOf(target);
177
+ if (options === null)
178
+ await target.fill(command.text, { timeout: ACT_MS });
179
+ else if (options.includes(command.text))
180
+ await target.selectOption({ label: command.text }, { timeout: ACT_MS });
181
+ else
182
+ throw new Stopped('not_found', await secretsHiddenInWords(page, noOptionWords(named.name, command.text, options)));
124
183
  }
125
184
  catch (error) {
126
185
  if (timedOut(error))
@@ -212,7 +271,7 @@ export function signInOf(m, person, tokens) {
212
271
  }),
213
272
  steps: (p.browser.steps ?? []).map((st) => ({
214
273
  ...st,
215
- ...(st.with !== undefined && { with: fill(st.with, vars) }),
274
+ ...(st.with !== undefined && !st.literal && { with: fill(st.with, vars) }),
216
275
  })),
217
276
  };
218
277
  }
@@ -1,18 +1,17 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { createServer } from 'node:http';
3
- import path from 'node:path';
4
3
  import { parseArgs } from 'node:util';
5
4
  import { errorText } from '../errors.js';
6
- import { fill, loadManifest } from '../manifest/index.js';
7
- import { scrub, scrubDeep, signIn } from '../people/index.js';
8
- import { startPieceServer } from '../kinds/index.js';
9
- import { applyWorld, baseVars } from '../run/index.js';
10
- import { runningServices, bringDown, bringUp, freePort, stateDir } from '../services/index.js';
11
- import { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
12
- import { noteSecretsOn } from './secrets.js';
5
+ import { loadManifest } from '../manifest/index.js';
6
+ import { scrubDeep } from '../people/index.js';
7
+ import { freePort } from '../services/index.js';
8
+ import { act, failed, fieldNow, focusedNow, recheckNow } from './browser.js';
13
9
  import { driveArgv, parseDrive } from './grammar.js';
14
- import { forgetDriving, writeDriving } from './state.js';
15
- import { readScenarios } from '../scenarios/index.js';
10
+ import { StepLog } from './log.js';
11
+ import { openPage } from './open.js';
12
+ import { SECRETS } from './watcher.js';
13
+ import { FLUSH, forgetDriving, writeDriving } from './state.js';
14
+ import { beginWalk, startWithoutTokens } from './walk.js';
16
15
  const { values } = parseArgs({
17
16
  options: {
18
17
  manifest: { type: 'string' },
@@ -28,82 +27,38 @@ const { values } = parseArgs({
28
27
  });
29
28
  const m = loadManifest(values.manifest);
30
29
  const checkout = values.on;
31
- const world = values.world ?? m.defaults.world;
32
- const started = [];
33
- let browser = null;
34
- let context = null;
35
- let pieces = null;
36
- let page;
37
- let errors = [];
38
- let tokens = {};
39
30
  const secret = randomBytes(24).toString('hex');
40
- async function open() {
41
- let url;
42
- if (values.piece) {
43
- const piece = (await readScenarios(m, checkout, ['piece'])).scenarios.find((p) => p.id === values.piece);
44
- const spec = piece?.spec;
45
- if (!piece || !spec?.packageDir)
46
- throw new Error(`There is no piece ${values.piece} in ${checkout}.`);
47
- pieces = await startPieceServer({
48
- dir: spec.packageDir,
49
- state: stateDir(m.dir),
50
- preview: m.scenarios.pieces.preview ?? null,
51
- styles: m.scenarios.pieces.styles ?? null,
52
- config: m.scenarios.pieces.config ?? null,
53
- pieces: [{ file: spec.inPackage, exportName: spec.exportName }],
54
- });
55
- url = pieces.canvas(spec.inPackage, spec.exportName);
56
- }
57
- else {
58
- const name = values.service ?? m.scenarios.flows.service ?? m.defaults.service;
59
- const svc = name ? m.services[name] : undefined;
60
- if (!svc)
61
- throw new Error(`There is no service to drive: name one with --service.`);
62
- let running = runningServices(m.dir).filter((r) => path.resolve(r.checkout) === path.resolve(checkout));
63
- let mine = running.find((r) => r.name === svc.name);
64
- if (!mine) {
65
- if (world)
66
- await applyWorld(m, world, 'before', checkout, baseVars(m, checkout, running));
67
- mine = await bringUp(m, svc, checkout, {
68
- world,
69
- real: new Set(),
70
- vars: baseVars(m, checkout, running),
71
- });
72
- started.push(mine);
73
- running = [...running, mine];
74
- if (world)
75
- await applyWorld(m, world, 'add', checkout, baseVars(m, checkout, running));
76
- }
77
- if (!mine.url)
78
- throw new Error(`${svc.name} has no URL to open.`);
79
- url = new URL(values.start ?? '/', mine.url).href;
80
- if (m.signIn || Object.values(m.people).some((p) => p.token)) {
81
- const v = baseVars(m, checkout, running);
82
- tokens = (await signIn(m, { cwd: checkout, env: {}, fill: (t) => fill(t, v) })).tokens;
83
- }
84
- }
85
- const person = values.as ?? m.defaults.person;
86
- const signedIn = signInOf(m, person, tokens);
87
- browser = await launch();
88
- context = await contextFor(browser, url, signedIn, values.scheme === 'dark' ? 'dark' : 'light');
89
- page = await context.newPage();
90
- await page.clock.setFixedTime(FIXED_TIME);
91
- errors = errorsOf(page);
92
- if (signedIn?.steps.length && !values.piece) {
93
- const stopped = await signInBySteps(page, new URL(url).origin, signedIn.steps);
94
- if (stopped)
95
- throw new Error(scrub(stopped, tokens));
96
- }
97
- await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
98
- await calm(page);
99
- await noteSecretsOn(page);
31
+ const person = values.as ?? m.defaults.person;
32
+ const SAID_SECRET = '__rehearseSaidSecret';
33
+ let opened = null;
34
+ let log = null;
35
+ const toldBeforeTheLog = [];
36
+ function tellWhenSecret({ binding, secrets }) {
37
+ const api = window[Symbol.for(secrets)];
38
+ api?.onSecret((became) => {
39
+ const call = window[binding];
40
+ void call?.(became);
41
+ });
42
+ }
43
+ const isBecameSecret = (v) => Boolean(v) &&
44
+ typeof v.key === 'string' &&
45
+ Array.isArray(v.identities) &&
46
+ v.identities.every((i) => typeof i === 'string');
47
+ function heard(became) {
48
+ if (!isBecameSecret(became))
49
+ return;
50
+ if (log)
51
+ log.became([became]);
52
+ else
53
+ toldBeforeTheLog.push(became);
54
+ }
55
+ async function lookAgain(now, steps) {
56
+ steps.settle(await recheckNow(now.page, steps.keys()));
100
57
  }
101
58
  async function stop() {
102
- await context?.close().catch(() => undefined);
103
- await browser?.close().catch(() => undefined);
104
- await pieces?.close().catch(() => undefined);
105
- for (const r of started.toReversed())
106
- await bringDown(m, r).catch(() => undefined);
59
+ if (opened && log)
60
+ await lookAgain(opened, log).catch(() => undefined);
61
+ await opened?.close().catch(() => undefined);
107
62
  forgetDriving(m.dir);
108
63
  }
109
64
  function onlyWhatTheGrammarAllows(given) {
@@ -112,9 +67,52 @@ function onlyWhatTheGrammarAllows(given) {
112
67
  throw new Error(readAgainAsWords.says);
113
68
  return readAgainAsWords.command;
114
69
  }
70
+ async function step(now, steps, command, at) {
71
+ await lookAgain(now, steps);
72
+ if (command.command === 'stop')
73
+ return { v: 1, ok: true, command: 'stop', ms: 0, file: null, tree: null, driver: 'browser' };
74
+ const before = command.command === 'fill'
75
+ ? await fieldNow(now.page, command.name, command.role)
76
+ : command.command === 'type'
77
+ ? await focusedNow(now.page)
78
+ : null;
79
+ const result = await act(now.page, command, at).catch((e) => failed(command.command, at, 'crashed', errorText(e)));
80
+ const after = before ? await focusedNow(now.page) : null;
81
+ steps.took(command, result.ok, before && after ? steps.typedOf(command, before, after) : 'shown', before);
82
+ return result;
83
+ }
115
84
  async function main() {
85
+ let now;
86
+ let steps;
116
87
  try {
117
- await open();
88
+ now = await openPage(m, checkout, {
89
+ service: values.service,
90
+ piece: values.piece,
91
+ world: values.world ?? m.defaults.world,
92
+ as: values.as,
93
+ start: values.start,
94
+ scheme: values.scheme,
95
+ }, {
96
+ prepare: async (context) => {
97
+ await context.exposeBinding(SAID_SECRET, (_source, became) => heard(became));
98
+ await context.addInitScript(tellWhenSecret, { binding: SAID_SECRET, secrets: SECRETS });
99
+ },
100
+ });
101
+ opened = now;
102
+ steps = new StepLog(m.dir, now.tokens, person);
103
+ log = steps;
104
+ steps.became(toldBeforeTheLog.splice(0));
105
+ const start = values.start ? startWithoutTokens(values.start, now.tokens) : null;
106
+ beginWalk(m.dir, {
107
+ driver: 'browser',
108
+ service: values.piece ? null : now.service,
109
+ piece: values.piece ?? null,
110
+ world: values.world ?? m.defaults.world,
111
+ person,
112
+ start: start?.start ?? null,
113
+ since: new Date().toISOString(),
114
+ ...(start?.trimmed && { trimmed: true }),
115
+ });
118
116
  }
119
117
  catch (error) {
120
118
  process.stderr.write(`${errorText(error)}\n`);
@@ -132,6 +130,11 @@ async function main() {
132
130
  res.writeHead(403).end();
133
131
  return;
134
132
  }
133
+ if (req.url === FLUSH) {
134
+ await lookAgain(now, steps);
135
+ res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
136
+ return;
137
+ }
135
138
  let command;
136
139
  try {
137
140
  command = onlyWhatTheGrammarAllows(JSON.parse(body));
@@ -141,12 +144,10 @@ async function main() {
141
144
  res.end(JSON.stringify(failed(null, at, 'usage', errorText(error))));
142
145
  return;
143
146
  }
144
- const seen = errors.length;
145
- const result = command.command === 'stop'
146
- ? { v: 1, ok: true, command: 'stop', ms: 0, file: null, tree: null, driver: 'browser' }
147
- : await act(page, command, at).catch((e) => failed(command.command, at, 'crashed', errorText(e)));
148
- const fresh = errors.slice(seen);
149
- const answer = scrubDeep(result.ok && fresh.length ? { ...result, errors: fresh } : result, tokens);
147
+ const seen = now.errors.length;
148
+ const result = await step(now, steps, command, at);
149
+ const fresh = now.errors.slice(seen);
150
+ const answer = scrubDeep(result.ok && fresh.length ? { ...result, errors: fresh } : result, now.tokens);
150
151
  res.writeHead(200, { 'content-type': 'application/json' });
151
152
  res.end(JSON.stringify(answer), () => {
152
153
  if (command.command === 'stop')
@@ -9,6 +9,7 @@ export interface Step {
9
9
  snapshot?: string;
10
10
  fill?: string;
11
11
  with?: string;
12
+ literal?: boolean;
12
13
  role?: string;
13
14
  }
14
15
  export declare const VERBS: readonly ['start', 'click', 'type', 'key', 'fill', 'snapshot', 'screenshot', 'record', 'stop'];
@@ -156,9 +156,11 @@ export function stepOf(v, n) {
156
156
  throw new Error(`Step ${n}'s ${verb} needs words.`);
157
157
  if (s.role !== undefined && !isRole(s.role))
158
158
  throw new Error(`Step ${n} names a role Rehearse doesn't know: ${String(s.role)}.`);
159
+ if (s.literal !== undefined && (verb !== 'fill' || typeof s.literal !== 'boolean'))
160
+ throw new Error(`Step ${n}'s literal is true or false, on a fill step.`);
159
161
  if (verb === 'key' && !isKey(s.key))
160
162
  throw new Error(`Step ${n} presses a key Rehearse doesn't know: name it as Playwright does, such as Enter or Meta+k.`);
161
- const extra = Object.keys(s).filter((k) => k !== verb && k !== 'role' && !(verb === 'fill' && k === 'with'));
163
+ const extra = Object.keys(s).filter((k) => k !== verb && k !== 'role' && !(verb === 'fill' && (k === 'with' || k === 'literal')));
162
164
  if (extra.length)
163
165
  throw new Error(`Step ${n} has more than its ${verb}: ${extra.join(', ')}.`);
164
166
  return s;
@@ -1,5 +1,9 @@
1
- export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, seenTree, signInBySteps, signInOf, type SignIn, } from './browser.ts';
2
- export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, type DriveResult, type Step, type Verb, } from './grammar.ts';
3
- export { findNamed, namedIn } from './names.ts';
4
- export { HIDDEN_VALUE, secretsHidden, TREE_WITHHELD, withValuesHidden } from './secrets.ts';
5
- export { forgetDriving, readDriving, writeDriving } from './state.ts';
1
+ export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, picks, seenTree, signInBySteps, signInOf, fieldNow, focusedNow, recheckNow, secretValueOf, treeOf, type Launching, type SignIn, } from './browser.ts';
2
+ export { driveArgv, exitOf, isKey, isRole, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, type DriveResult, type Role, type Step, type Verb, } from './grammar.ts';
3
+ export { findNamed, namedIn, pickedIn, type Picked } from './names.ts';
4
+ export { openPage, type OpenedPage, type Opening, type Showing } from './open.ts';
5
+ export { HIDDEN_VALUE, hiddenInWords, secretsHidden, secretsHiddenInWords, secretValuesNow, TREE_WITHHELD, withValuesHidden, } from './secrets.ts';
6
+ export { StepLog } from './log.ts';
7
+ export { SECRETS, watchForSecrets, type BecameSecret, type Looked, type SecretsInPage, type Typed, } from './watcher.ts';
8
+ export { flushDriving, forgetDriving, readDriving, writeDriving } from './state.ts';
9
+ export { addToWalk, beginWalk, holdsAToken, keptText, readWalk, rewriteWalk, startWithoutTokens, walked, walkFileOf, type Hidden, type Kept, type Walk, type WalkBegan, type Walked, } from './walk.ts';
@@ -1,5 +1,9 @@
1
- export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, seenTree, signInBySteps, signInOf, } from './browser.js';
2
- export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, } from './grammar.js';
3
- export { findNamed, namedIn } from './names.js';
4
- export { HIDDEN_VALUE, secretsHidden, TREE_WITHHELD, withValuesHidden } from './secrets.js';
5
- export { forgetDriving, readDriving, writeDriving } from './state.js';
1
+ export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, picks, seenTree, signInBySteps, signInOf, fieldNow, focusedNow, recheckNow, secretValueOf, treeOf, } from './browser.js';
2
+ export { driveArgv, exitOf, isKey, isRole, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, } from './grammar.js';
3
+ export { findNamed, namedIn, pickedIn } from './names.js';
4
+ export { openPage } from './open.js';
5
+ export { HIDDEN_VALUE, hiddenInWords, secretsHidden, secretsHiddenInWords, secretValuesNow, TREE_WITHHELD, withValuesHidden, } from './secrets.js';
6
+ export { StepLog } from './log.js';
7
+ export { SECRETS, watchForSecrets, } from './watcher.js';
8
+ export { flushDriving, forgetDriving, readDriving, writeDriving } from './state.js';
9
+ export { addToWalk, beginWalk, holdsAToken, keptText, readWalk, rewriteWalk, startWithoutTokens, walked, walkFileOf, } from './walk.js';