@kurvball/rehearse 1.12.1 → 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 (53) 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/compare/gate.js +22 -2
  7. package/dist/drive/browser.d.ts +12 -1
  8. package/dist/drive/browser.js +64 -5
  9. package/dist/drive/daemon.js +91 -90
  10. package/dist/drive/grammar.d.ts +1 -0
  11. package/dist/drive/grammar.js +3 -1
  12. package/dist/drive/index.d.ts +9 -5
  13. package/dist/drive/index.js +9 -5
  14. package/dist/drive/log.d.ts +19 -0
  15. package/dist/drive/log.js +75 -0
  16. package/dist/drive/names.d.ts +2 -0
  17. package/dist/drive/names.js +4 -0
  18. package/dist/drive/open.d.ts +25 -0
  19. package/dist/drive/open.js +95 -0
  20. package/dist/drive/secrets.d.ts +3 -0
  21. package/dist/drive/secrets.js +31 -21
  22. package/dist/drive/state.d.ts +2 -0
  23. package/dist/drive/state.js +11 -0
  24. package/dist/drive/walk.d.ts +39 -0
  25. package/dist/drive/walk.js +112 -0
  26. package/dist/drive/watcher.d.ts +28 -0
  27. package/dist/drive/watcher.js +255 -0
  28. package/dist/kinds/flow/kind.js +2 -2
  29. package/dist/manifest/index.d.ts +1 -1
  30. package/dist/manifest/index.js +1 -1
  31. package/dist/manifest/types.d.ts +1 -0
  32. package/dist/record/flow.d.ts +38 -0
  33. package/dist/record/flow.js +88 -0
  34. package/dist/record/index.d.ts +6 -0
  35. package/dist/record/index.js +5 -0
  36. package/dist/record/keys.d.ts +24 -0
  37. package/dist/record/keys.js +92 -0
  38. package/dist/record/page.d.ts +47 -0
  39. package/dist/record/page.js +188 -0
  40. package/dist/record/person.d.ts +22 -0
  41. package/dist/record/person.js +286 -0
  42. package/dist/record/taking.d.ts +39 -0
  43. package/dist/record/taking.js +214 -0
  44. package/dist/record/walked.d.ts +10 -0
  45. package/dist/record/walked.js +59 -0
  46. package/dist/schema.d.ts +1 -1
  47. package/dist/schema.js +1 -0
  48. package/llms.txt +3 -2
  49. package/package.json +1 -1
  50. package/schema/v1/flow.schema.json +4 -0
  51. package/schema/v1/record.schema.json +64 -0
  52. package/schema/v1/samples/record.json +20 -0
  53. package/skill/rehearse/SKILL.md +14 -1
@@ -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';
@@ -0,0 +1,19 @@
1
+ import type { Command } from './grammar.ts';
2
+ import type { BecameSecret, Looked, Typed } from './watcher.ts';
3
+ export declare class StepLog {
4
+ private lines;
5
+ private texts;
6
+ private readonly secretKeys;
7
+ private readonly secret;
8
+ private readonly manifestDir;
9
+ private readonly tokens;
10
+ private readonly person;
11
+ constructor(manifestDir: string, tokens: Readonly<Record<string, string>>, person: string | null);
12
+ private known;
13
+ typedOf(command: Command, before: Looked, after: Looked): Typed;
14
+ took(command: Command, ok: boolean, typed: Typed, looked: Looked | null): void;
15
+ private isSecret;
16
+ became(all: readonly BecameSecret[]): void;
17
+ settle(rechecked: readonly BecameSecret[]): void;
18
+ keys(): string[];
19
+ }
@@ -0,0 +1,75 @@
1
+ import { scrubDeep } from '../people/index.js';
2
+ import { addToWalk, rewriteWalk, walked } from './walk.js';
3
+ export class StepLog {
4
+ lines = 0;
5
+ texts = [];
6
+ secretKeys = new Set();
7
+ secret = new Set();
8
+ manifestDir;
9
+ tokens;
10
+ person;
11
+ constructor(manifestDir, tokens, person) {
12
+ this.manifestDir = manifestDir;
13
+ this.tokens = tokens;
14
+ this.person = person;
15
+ }
16
+ known(looked) {
17
+ return (looked.typed === 'password' ||
18
+ (looked.key !== null && this.secretKeys.has(looked.key)) ||
19
+ looked.identities.some((i) => this.secret.has(i)));
20
+ }
21
+ typedOf(command, before, after) {
22
+ if (this.known(before))
23
+ return 'password';
24
+ if (command.command === 'fill' && before.choice)
25
+ return before.typed;
26
+ if (this.known(after))
27
+ return 'password';
28
+ if (before.typed !== 'shown' || before.key === null || before.key !== after.key)
29
+ return 'unseen';
30
+ return command.command === 'fill' || (!before.choice && after.typed === 'shown') ? 'shown' : 'unseen';
31
+ }
32
+ took(command, ok, typed, looked) {
33
+ const step = scrubDeep(walked(command, ok, typed, this.tokens, this.person), this.tokens);
34
+ const holdsText = (command.command === 'fill' || command.command === 'type') && ok && !step.hid;
35
+ if (holdsText && looked) {
36
+ addToWalk(this.manifestDir, walked(command, ok, 'pending'));
37
+ this.texts.push({
38
+ line: this.lines,
39
+ command,
40
+ step,
41
+ key: looked.key,
42
+ identities: looked.identities,
43
+ written: false,
44
+ });
45
+ }
46
+ else
47
+ addToWalk(this.manifestDir, holdsText ? walked(command, ok, 'unseen') : step);
48
+ this.lines += 1;
49
+ }
50
+ isSecret(t) {
51
+ return (t.key !== null && this.secretKeys.has(t.key)) || t.identities.some((i) => this.secret.has(i));
52
+ }
53
+ became(all) {
54
+ for (const b of all) {
55
+ this.secretKeys.add(b.key);
56
+ for (const i of b.identities)
57
+ this.secret.add(i);
58
+ }
59
+ const now = this.texts.filter((t) => this.isSecret(t));
60
+ for (const t of now)
61
+ rewriteWalk(this.manifestDir, t.line, walked(t.command, true, 'password'));
62
+ this.texts = this.texts.filter((t) => !now.includes(t));
63
+ }
64
+ settle(rechecked) {
65
+ this.became(rechecked);
66
+ for (const t of this.texts)
67
+ if (!t.written) {
68
+ rewriteWalk(this.manifestDir, t.line, t.step);
69
+ t.written = true;
70
+ }
71
+ }
72
+ keys() {
73
+ return this.texts.flatMap((t) => (t.key === null ? [] : [t.key]));
74
+ }
75
+ }
@@ -6,6 +6,8 @@ export interface Named {
6
6
  }
7
7
  export declare const said: (role: string, name: string) => string;
8
8
  export declare function namedIn(snapshot: string): Named[];
9
+ export type Picked = 'one' | 'none' | 'many';
10
+ export declare function pickedIn(tree: string, name: string, role: string | null): Picked;
9
11
  export type Found = {
10
12
  found: 'one';
11
13
  one: Named;
@@ -25,6 +25,10 @@ export function namedIn(snapshot) {
25
25
  }
26
26
  return named;
27
27
  }
28
+ export function pickedIn(tree, name, role) {
29
+ const { found } = findNamed(namedIn(tree), name, role);
30
+ return found;
31
+ }
28
32
  const NEAR = 5;
29
33
  function distance(a, b) {
30
34
  const row = Array.from({ length: b.length + 1 }, (_, j) => j);
@@ -0,0 +1,25 @@
1
+ import type { Browser, BrowserContext, Page } from 'playwright-core';
2
+ import { type Manifest } from '../manifest/index.ts';
3
+ import { type Launching } from './browser.ts';
4
+ export interface Opening {
5
+ service?: string | undefined;
6
+ piece?: string | undefined;
7
+ world: string | null;
8
+ as?: string | undefined;
9
+ start?: string | undefined;
10
+ scheme?: string | undefined;
11
+ }
12
+ export interface Showing extends Launching {
13
+ prepare?: (context: BrowserContext) => Promise<void>;
14
+ progress?: (line: string) => void;
15
+ }
16
+ export interface OpenedPage {
17
+ page: Page;
18
+ browser: Browser;
19
+ url: string;
20
+ service: string | null;
21
+ tokens: Record<string, string>;
22
+ errors: string[];
23
+ close(): Promise<void>;
24
+ }
25
+ export declare function openPage(m: Manifest, checkout: string, o: Opening, showing?: Showing): Promise<OpenedPage>;
@@ -0,0 +1,95 @@
1
+ import path from 'node:path';
2
+ import { fill } from '../manifest/index.js';
3
+ import { scrub, signIn } from '../people/index.js';
4
+ import { startPieceServer } from '../kinds/index.js';
5
+ import { applyWorld, baseVars } from '../run/index.js';
6
+ import { bringDown, bringUp, runningServices, stateDir } from '../services/index.js';
7
+ import { readScenarios } from '../scenarios/index.js';
8
+ import { calm, contextFor, errorsOf, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
9
+ import { noteSecretsOn, SECRET_AUTOCOMPLETE } from './secrets.js';
10
+ import { SECRETS, watchForSecrets } from './watcher.js';
11
+ export async function openPage(m, checkout, o, showing = {}) {
12
+ const started = [];
13
+ let browser = null;
14
+ let context = null;
15
+ let pieces = null;
16
+ const close = async () => {
17
+ await context?.close().catch(() => undefined);
18
+ await browser?.close().catch(() => undefined);
19
+ await pieces?.close().catch(() => undefined);
20
+ for (const r of started.toReversed())
21
+ await bringDown(m, r, showing.progress).catch(() => undefined);
22
+ };
23
+ try {
24
+ let url;
25
+ let service = null;
26
+ let tokens = {};
27
+ if (o.piece) {
28
+ const piece = (await readScenarios(m, checkout, ['piece'])).scenarios.find((p) => p.id === o.piece);
29
+ const spec = piece?.spec;
30
+ if (!piece || !spec?.packageDir)
31
+ throw new Error(`There is no piece ${o.piece} in ${checkout}.`);
32
+ pieces = await startPieceServer({
33
+ dir: spec.packageDir,
34
+ state: stateDir(m.dir),
35
+ preview: m.scenarios.pieces.preview ?? null,
36
+ styles: m.scenarios.pieces.styles ?? null,
37
+ config: m.scenarios.pieces.config ?? null,
38
+ pieces: [{ file: spec.inPackage, exportName: spec.exportName }],
39
+ });
40
+ url = pieces.canvas(spec.inPackage, spec.exportName);
41
+ }
42
+ else {
43
+ const name = o.service ?? m.scenarios.flows.service ?? m.defaults.service;
44
+ const svc = name ? m.services[name] : undefined;
45
+ if (!svc)
46
+ throw new Error(`There is no service to drive: name one with --service.`);
47
+ service = svc.name;
48
+ let running = runningServices(m.dir).filter((r) => path.resolve(r.checkout) === path.resolve(checkout));
49
+ let mine = running.find((r) => r.name === svc.name);
50
+ if (!mine) {
51
+ if (o.world)
52
+ await applyWorld(m, o.world, 'before', checkout, baseVars(m, checkout, running));
53
+ mine = await bringUp(m, svc, checkout, {
54
+ world: o.world,
55
+ real: new Set(),
56
+ vars: baseVars(m, checkout, running),
57
+ ...(showing.progress && { progress: showing.progress }),
58
+ });
59
+ started.push(mine);
60
+ running = [...running, mine];
61
+ if (o.world)
62
+ await applyWorld(m, o.world, 'add', checkout, baseVars(m, checkout, running));
63
+ }
64
+ if (!mine.url)
65
+ throw new Error(`${svc.name} has no URL to open.`);
66
+ url = new URL(o.start ?? '/', mine.url).href;
67
+ if (m.signIn || Object.values(m.people).some((p) => p.token)) {
68
+ const v = baseVars(m, checkout, running);
69
+ tokens = (await signIn(m, { cwd: checkout, env: {}, fill: (t) => fill(t, v) })).tokens;
70
+ }
71
+ }
72
+ const person = o.as ?? m.defaults.person;
73
+ const signedIn = signInOf(m, person, tokens);
74
+ browser = await launch(showing);
75
+ context = await contextFor(browser, url, signedIn, o.scheme === 'dark' ? 'dark' : 'light');
76
+ await context.addInitScript(watchForSecrets, { key: SECRETS, autocomplete: [...SECRET_AUTOCOMPLETE] });
77
+ await showing.prepare?.(context);
78
+ const page = await context.newPage();
79
+ await page.clock.setFixedTime(FIXED_TIME);
80
+ const errors = errorsOf(page);
81
+ if (signedIn?.steps.length && !o.piece) {
82
+ const stopped = await signInBySteps(page, new URL(url).origin, signedIn.steps);
83
+ if (stopped)
84
+ throw new Error(scrub(stopped, tokens));
85
+ }
86
+ await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
87
+ await calm(page);
88
+ await noteSecretsOn(page);
89
+ return { page, browser, url, service, tokens, errors, close };
90
+ }
91
+ catch (error) {
92
+ await close();
93
+ throw error;
94
+ }
95
+ }
@@ -1,8 +1,11 @@
1
1
  import type { BrowserContext, Locator, Page } from 'playwright-core';
2
2
  export declare const HIDDEN_VALUE = "\u2039secret\u203A";
3
3
  export declare const TREE_WITHHELD = "\u2039withheld: Rehearse could not read which fields hold secrets on this page\u203A";
4
+ export declare const SECRET_AUTOCOMPLETE: readonly string[];
4
5
  export declare const rememberSecretFields: (context: BrowserContext) => Promise<void>;
5
6
  export declare function withValuesHidden(tree: string, values: readonly string[]): string;
6
7
  export declare function secretsHidden<T extends string | null>(scope: Locator, take: () => Promise<T>): Promise<T>;
7
8
  export declare function noteSecretsOn(page: Page): Promise<void>;
9
+ export declare const secretValuesNow: (page: Page) => Promise<string[] | null>;
10
+ export declare const hiddenInWords: (words: string, values: readonly string[]) => string;
8
11
  export declare function secretsHiddenInWords(page: Page, words: string): Promise<string>;
@@ -1,6 +1,6 @@
1
1
  export const HIDDEN_VALUE = '‹secret›';
2
2
  export const TREE_WITHHELD = '‹withheld: Rehearse could not read which fields hold secrets on this page›';
3
- const SECRET_AUTOCOMPLETE = [
3
+ export const SECRET_AUTOCOMPLETE = [
4
4
  'current-password',
5
5
  'new-password',
6
6
  'one-time-code',
@@ -22,33 +22,38 @@ const holdsControl = (value) => [...value].some((ch) => {
22
22
  const WORDS_APART = '(?:\\s|\\\\n|\\\\t|\\\\r)+';
23
23
  const remembered = new WeakMap();
24
24
  export const rememberSecretFields = async (context) => {
25
- await context.addInitScript(() => {
25
+ await context.addInitScript((secretTokens) => {
26
26
  const memory = window;
27
27
  const seen = new WeakSet();
28
28
  const values = new Set();
29
+ const latest = new Map();
29
30
  memory.rehearseWasSecret = seen;
30
31
  memory.rehearseSecretValues = values;
32
+ memory.rehearseLatestSecretValues = latest;
31
33
  const isPassword = (el) => el instanceof HTMLInputElement && el.type === 'password';
32
- const secretTokens = [
33
- 'current-password',
34
- 'new-password',
35
- 'one-time-code',
36
- 'cc-number',
37
- 'cc-csc',
38
- 'cc-exp',
39
- 'cc-exp-month',
40
- 'cc-exp-year',
41
- ];
42
- const keep = (event) => {
34
+ const secretField = (event) => {
43
35
  const target = event.composedPath()[0];
44
- if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) || !target.value)
45
- return;
36
+ if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement))
37
+ return null;
46
38
  const tokens = (target.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/);
47
- if (isPassword(target) || tokens.some((t) => secretTokens.includes(t)))
48
- values.add(target.value);
39
+ return isPassword(target) || tokens.some((t) => secretTokens.includes(t)) ? target : null;
49
40
  };
50
- document.addEventListener('input', keep, true);
51
- document.addEventListener('change', keep, true);
41
+ document.addEventListener('input', (event) => {
42
+ const field = secretField(event);
43
+ if (!field)
44
+ return;
45
+ if (field.value)
46
+ latest.set(field, field.value);
47
+ else
48
+ latest.delete(field);
49
+ }, true);
50
+ document.addEventListener('change', (event) => {
51
+ const field = secretField(event);
52
+ if (!field?.value)
53
+ return;
54
+ values.add(field.value);
55
+ latest.set(field, field.value);
56
+ }, true);
52
57
  new MutationObserver((records) => {
53
58
  for (const r of records)
54
59
  if (r.type === 'attributes' && (r.oldValue ?? '').toLowerCase() === 'password') {
@@ -63,7 +68,7 @@ export const rememberSecretFields = async (context) => {
63
68
  attributeFilter: ['type'],
64
69
  attributeOldValue: true,
65
70
  });
66
- });
71
+ }, SECRET_AUTOCOMPLETE);
67
72
  };
68
73
  async function secretValuesOn(page) {
69
74
  try {
@@ -79,7 +84,10 @@ async function secretValuesOn(page) {
79
84
  }
80
85
  };
81
86
  visit(document);
82
- const values = [...(memory.rehearseSecretValues ?? [])];
87
+ const values = [
88
+ ...(memory.rehearseSecretValues ?? []),
89
+ ...(memory.rehearseLatestSecretValues?.values() ?? []),
90
+ ];
83
91
  for (const el of fields) {
84
92
  const style = getComputedStyle(el);
85
93
  const tokens = (el.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/);
@@ -193,6 +201,8 @@ export async function secretsHidden(scope, take) {
193
201
  export async function noteSecretsOn(page) {
194
202
  await valuesKnownOn(page);
195
203
  }
204
+ export const secretValuesNow = (page) => secretValuesOn(page);
205
+ export const hiddenInWords = (words, values) => values.some(holdsControl) ? TREE_WITHHELD : hiddenIn(words, patternsOf(values));
196
206
  export async function secretsHiddenInWords(page, words) {
197
207
  const values = await valuesKnownOn(page);
198
208
  if (values === null || values.some(holdsControl))
@@ -11,3 +11,5 @@ export interface Driving {
11
11
  export declare function readDriving(manifestDir: string): Driving | null;
12
12
  export declare function writeDriving(manifestDir: string, d: Driving): void;
13
13
  export declare const forgetDriving: (manifestDir: string) => void;
14
+ export declare const FLUSH = "/flush";
15
+ export declare function flushDriving(manifestDir: string): Promise<void>;
@@ -26,3 +26,14 @@ export function writeDriving(manifestDir, d) {
26
26
  });
27
27
  }
28
28
  export const forgetDriving = (manifestDir) => rmSync(fileOf(manifestDir), { force: true });
29
+ export const FLUSH = '/flush';
30
+ export async function flushDriving(manifestDir) {
31
+ const d = readDriving(manifestDir);
32
+ if (d?.driver !== 'browser' || !d.port)
33
+ return;
34
+ await fetch(`http://127.0.0.1:${d.port}${FLUSH}`, {
35
+ method: 'POST',
36
+ headers: { 'x-rehearse-drive': d.secret ?? '' },
37
+ signal: AbortSignal.timeout(30_000),
38
+ }).catch(() => undefined);
39
+ }
@@ -0,0 +1,39 @@
1
+ import type { Command } from './grammar.ts';
2
+ import type { Typed } from './watcher.ts';
3
+ export interface WalkBegan {
4
+ driver: 'service' | 'browser';
5
+ service: string | null;
6
+ piece: string | null;
7
+ world: string | null;
8
+ person: string | null;
9
+ start: string | null;
10
+ since: string;
11
+ trimmed?: true;
12
+ }
13
+ export type Hidden = 'password' | 'unseen' | 'token' | 'pending';
14
+ export interface Walked {
15
+ command: Command;
16
+ ok: boolean;
17
+ hid?: Hidden;
18
+ fillsIn?: true;
19
+ }
20
+ export interface Walk {
21
+ began: WalkBegan;
22
+ steps: Walked[];
23
+ }
24
+ export interface Kept {
25
+ text: string;
26
+ fillsIn: boolean;
27
+ }
28
+ export declare const walkFileOf: (manifestDir: string) => string;
29
+ export declare function beginWalk(manifestDir: string, began: WalkBegan): void;
30
+ export declare const holdsAToken: (text: string, tokens: Readonly<Record<string, string>>) => boolean;
31
+ export declare function keptText(text: string, tokens: Readonly<Record<string, string>>, person: string | null, fillsIn: boolean): Kept | null;
32
+ export declare function startWithoutTokens(start: string, tokens: Readonly<Record<string, string>>): {
33
+ start: string;
34
+ trimmed: boolean;
35
+ };
36
+ export declare function walked(command: Command, ok: boolean, typed: Typed | 'pending', tokens?: Readonly<Record<string, string>>, person?: string | null): Walked;
37
+ export declare function addToWalk(manifestDir: string, step: Walked): void;
38
+ export declare function rewriteWalk(manifestDir: string, index: number, step: Walked): void;
39
+ export declare function readWalk(manifestDir: string): Walk | null;
@@ -0,0 +1,112 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { placeholdersIn } from '../manifest/index.js';
4
+ import { stateDir } from '../services/index.js';
5
+ const ONLY_THIS_USER_READS_IT = 0o600;
6
+ const SHORTEST_TOKEN = 6;
7
+ const SHORTEST_PART = 12;
8
+ const SHORTEST_BASE64 = 8;
9
+ export const walkFileOf = (manifestDir) => path.join(stateDir(manifestDir), 'drive-steps.jsonl');
10
+ export function beginWalk(manifestDir, began) {
11
+ mkdirSync(stateDir(manifestDir), { recursive: true });
12
+ writeFileSync(walkFileOf(manifestDir), `${JSON.stringify({ began })}\n`, { mode: ONLY_THIS_USER_READS_IT });
13
+ }
14
+ function base64Within(token) {
15
+ const bytes = Buffer.from(token, 'utf8');
16
+ const unsettledAtFirst = [0, 2, 3];
17
+ return [0, 1, 2].flatMap((before) => {
18
+ const all = Buffer.concat([Buffer.alloc(before), bytes]).toString('base64');
19
+ const settled = all.slice(unsettledAtFirst[before], Math.floor(((before + bytes.length) * 8) / 6));
20
+ return settled.length >= SHORTEST_BASE64
21
+ ? [settled, settled.replace(/\+/g, '-').replace(/\//g, '_')]
22
+ : [];
23
+ });
24
+ }
25
+ function holds(text, token) {
26
+ const lower = text.toLowerCase();
27
+ const wanted = token.toLowerCase();
28
+ if (lower.includes(wanted) || lower.includes(encodeURIComponent(token).toLowerCase()))
29
+ return true;
30
+ if (base64Within(token).some((b) => text.includes(b)))
31
+ return true;
32
+ for (let at = 0; at + SHORTEST_PART <= wanted.length; at += 1)
33
+ if (lower.includes(wanted.slice(at, at + SHORTEST_PART)))
34
+ return true;
35
+ return false;
36
+ }
37
+ export const holdsAToken = (text, tokens) => Object.values(tokens).some((t) => t.length >= SHORTEST_TOKEN && holds(text, t));
38
+ export function keptText(text, tokens, person, fillsIn) {
39
+ const own = person ? tokens[person] : undefined;
40
+ const ownHere = own !== undefined && own.length >= SHORTEST_TOKEN && text.includes(own);
41
+ const rest = ownHere ? text.split(own).join('\0') : text;
42
+ if (holdsAToken(rest, tokens))
43
+ return null;
44
+ if (!ownHere)
45
+ return { text, fillsIn: false };
46
+ if (!fillsIn || placeholdersIn(text).length > 0)
47
+ return null;
48
+ return { text: text.split(own).join('{{token}}'), fillsIn: true };
49
+ }
50
+ export function startWithoutTokens(start, tokens) {
51
+ if (!holdsAToken(start, tokens))
52
+ return { start, trimmed: false };
53
+ const where = start.replace(/[?#].*$/, '') || '/';
54
+ return { start: holdsAToken(where, tokens) ? '/' : where, trimmed: true };
55
+ }
56
+ export function walked(command, ok, typed, tokens = {}, person = null) {
57
+ if (command.command !== 'fill' && command.command !== 'type')
58
+ return { command, ok };
59
+ const without = { ...command, text: '' };
60
+ if (!ok)
61
+ return { command: without, ok };
62
+ if (typed !== 'shown')
63
+ return { command: without, ok, hid: typed };
64
+ const kept = keptText(command.text, tokens, person, command.command === 'fill');
65
+ if (!kept)
66
+ return { command: without, ok, hid: 'token' };
67
+ return { command: { ...command, text: kept.text }, ok, ...(kept.fillsIn && { fillsIn: true }) };
68
+ }
69
+ export function addToWalk(manifestDir, step) {
70
+ const file = walkFileOf(manifestDir);
71
+ if (existsSync(file))
72
+ appendFileSync(file, `${JSON.stringify(step)}\n`);
73
+ }
74
+ export function rewriteWalk(manifestDir, index, step) {
75
+ let lines;
76
+ try {
77
+ lines = readFileSync(walkFileOf(manifestDir), 'utf8').split('\n');
78
+ }
79
+ catch {
80
+ return;
81
+ }
82
+ if (!lines[index + 1])
83
+ return;
84
+ lines[index + 1] = JSON.stringify(step);
85
+ writeFileSync(walkFileOf(manifestDir), lines.join('\n'));
86
+ }
87
+ const readLine = (line) => {
88
+ try {
89
+ return JSON.parse(line);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ };
95
+ const isWalked = (v) => Boolean(v) &&
96
+ typeof v === 'object' &&
97
+ typeof v.ok === 'boolean' &&
98
+ typeof v.command?.command === 'string';
99
+ export function readWalk(manifestDir) {
100
+ let text;
101
+ try {
102
+ text = readFileSync(walkFileOf(manifestDir), 'utf8');
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ const [first, ...rest] = text.split('\n').filter(Boolean).map(readLine);
108
+ const began = first?.began;
109
+ if (!began || typeof began !== 'object')
110
+ return null;
111
+ return { began, steps: rest.filter(isWalked) };
112
+ }
@@ -0,0 +1,28 @@
1
+ export declare const SECRETS = "rehearse.secrets";
2
+ export type Typed = 'shown' | 'password' | 'unseen';
3
+ export interface Looked {
4
+ key: string | null;
5
+ typed: Typed;
6
+ identities: string[];
7
+ choice: boolean;
8
+ }
9
+ export interface BecameSecret {
10
+ key: string;
11
+ identities: string[];
12
+ }
13
+ export interface SecretsInPage {
14
+ isSecret(el: Element): boolean;
15
+ isPlain(el: Element): boolean;
16
+ keyOf(el: Element): string;
17
+ identitiesOf(el: Element): string[];
18
+ lookAt(el: Element): Looked;
19
+ focused(): Looked;
20
+ recheck(keys: readonly string[]): BecameSecret[];
21
+ secretValueOf(key: string): string | null;
22
+ onSecret(listener: (became: BecameSecret) => void): void;
23
+ }
24
+ export interface Watching {
25
+ key: string;
26
+ autocomplete: readonly string[];
27
+ }
28
+ export declare function watchForSecrets({ key, autocomplete }: Watching): void;