@nifrajs/e2e 0.0.0-placeholder → 5.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 (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +128 -0
  4. package/dist/agent.d.ts +119 -0
  5. package/dist/agent.d.ts.map +1 -0
  6. package/dist/agent.js +315 -0
  7. package/dist/agent.js.map +1 -0
  8. package/dist/cache.d.ts +84 -0
  9. package/dist/cache.d.ts.map +1 -0
  10. package/dist/cache.js +166 -0
  11. package/dist/cache.js.map +1 -0
  12. package/dist/decision.d.ts +54 -0
  13. package/dist/decision.d.ts.map +1 -0
  14. package/dist/decision.js +122 -0
  15. package/dist/decision.js.map +1 -0
  16. package/dist/engine.d.ts +75 -0
  17. package/dist/engine.d.ts.map +1 -0
  18. package/dist/engine.js +13 -0
  19. package/dist/engine.js.map +1 -0
  20. package/dist/evidence.d.ts +14 -0
  21. package/dist/evidence.d.ts.map +1 -0
  22. package/dist/evidence.js +52 -0
  23. package/dist/evidence.js.map +1 -0
  24. package/dist/expect.d.ts +28 -0
  25. package/dist/expect.d.ts.map +1 -0
  26. package/dist/expect.js +88 -0
  27. package/dist/expect.js.map +1 -0
  28. package/dist/fake.d.ts +35 -0
  29. package/dist/fake.d.ts.map +1 -0
  30. package/dist/fake.js +129 -0
  31. package/dist/fake.js.map +1 -0
  32. package/dist/index.d.ts +11 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +8 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/internal/record.d.ts +3 -0
  37. package/dist/internal/record.d.ts.map +1 -0
  38. package/dist/internal/record.js +6 -0
  39. package/dist/internal/record.js.map +1 -0
  40. package/dist/locator.d.ts +53 -0
  41. package/dist/locator.d.ts.map +1 -0
  42. package/dist/locator.js +103 -0
  43. package/dist/locator.js.map +1 -0
  44. package/dist/params.d.ts +44 -0
  45. package/dist/params.d.ts.map +1 -0
  46. package/dist/params.js +108 -0
  47. package/dist/params.js.map +1 -0
  48. package/dist/playwright.d.ts +72 -0
  49. package/dist/playwright.d.ts.map +1 -0
  50. package/dist/playwright.js +169 -0
  51. package/dist/playwright.js.map +1 -0
  52. package/dist/replay.d.ts +34 -0
  53. package/dist/replay.d.ts.map +1 -0
  54. package/dist/replay.js +111 -0
  55. package/dist/replay.js.map +1 -0
  56. package/dist/route.d.ts +7 -0
  57. package/dist/route.d.ts.map +1 -0
  58. package/dist/route.js +26 -0
  59. package/dist/route.js.map +1 -0
  60. package/dist/session.d.ts +62 -0
  61. package/dist/session.d.ts.map +1 -0
  62. package/dist/session.js +105 -0
  63. package/dist/session.js.map +1 -0
  64. package/dist/snapshot.d.ts +8 -0
  65. package/dist/snapshot.d.ts.map +1 -0
  66. package/dist/snapshot.js +49 -0
  67. package/dist/snapshot.js.map +1 -0
  68. package/package.json +75 -1
  69. package/src/agent.ts +525 -0
  70. package/src/cache.ts +229 -0
  71. package/src/decision.ts +152 -0
  72. package/src/engine.ts +92 -0
  73. package/src/evidence.ts +58 -0
  74. package/src/expect.ts +171 -0
  75. package/src/fake.ts +185 -0
  76. package/src/index.ts +64 -0
  77. package/src/internal/record.ts +5 -0
  78. package/src/locator.ts +157 -0
  79. package/src/params.ts +128 -0
  80. package/src/playwright.ts +236 -0
  81. package/src/replay.ts +153 -0
  82. package/src/route.ts +26 -0
  83. package/src/session.ts +178 -0
  84. package/src/snapshot.ts +46 -0
package/src/cache.ts ADDED
@@ -0,0 +1,229 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { type PerformedDecision, parseActDecision, type Target } from "./decision.ts"
5
+ import { isRecord } from "./internal/record.ts"
6
+ import { keyParams, type Params } from "./params.ts"
7
+
8
+ /**
9
+ * `read-write` replays and records; `read-only` replays and hands off but never writes or deletes (CI);
10
+ * `strict` replays only, and a missing or stale recording fails; `off` ignores the cache.
11
+ */
12
+ export type CacheMode = "read-write" | "read-only" | "strict" | "off"
13
+
14
+ /** One action as it was taken. A fill's value and a goto's path keep their `{name}` placeholders. */
15
+ export type RecordedAction =
16
+ | { readonly kind: "tap"; readonly target: Target; readonly matches: number }
17
+ | {
18
+ readonly kind: "fill"
19
+ readonly target: Target
20
+ readonly matches: number
21
+ readonly value: string
22
+ }
23
+ | {
24
+ readonly kind: "press"
25
+ readonly target: Target
26
+ readonly matches: number
27
+ readonly key: string
28
+ }
29
+ | { readonly kind: "goto"; readonly path: string }
30
+
31
+ export interface CacheEntry {
32
+ readonly version: 1
33
+ readonly instruction: string
34
+ readonly startRoute: string
35
+ readonly actions: readonly RecordedAction[]
36
+ readonly end: {
37
+ readonly route: string
38
+ readonly appeared: readonly string[]
39
+ readonly disappeared: readonly string[]
40
+ }
41
+ }
42
+
43
+ export interface CacheStore {
44
+ read(key: string): Promise<CacheEntry | undefined>
45
+ write(key: string, entry: CacheEntry): Promise<void>
46
+ delete(key: string): Promise<void>
47
+ }
48
+
49
+ function parseAction(raw: unknown): RecordedAction | undefined {
50
+ const parsed = parseActDecision(raw)
51
+ if (!parsed.ok || !isRecord(raw)) return undefined
52
+ const decision = parsed.value
53
+ if (decision.kind === "goto") return decision
54
+ if (decision.kind === "done" || decision.kind === "fail") return undefined
55
+ const { matches } = raw
56
+ if (typeof matches !== "number" || !Number.isInteger(matches) || matches < 1) return undefined
57
+ return { ...decision, matches }
58
+ }
59
+
60
+ function strings(raw: unknown): string[] | undefined {
61
+ return Array.isArray(raw) && raw.every((item) => typeof item === "string") ? raw : undefined
62
+ }
63
+
64
+ /** A stored value read back as an entry, or `undefined` when it is not one (a corrupt file is a miss). */
65
+ export function parseEntry(raw: unknown): CacheEntry | undefined {
66
+ if (!isRecord(raw) || raw.version !== 1 || !isRecord(raw.end)) return undefined
67
+ const { instruction, startRoute } = raw
68
+ const { route } = raw.end
69
+ const appeared = strings(raw.end.appeared)
70
+ const disappeared = strings(raw.end.disappeared)
71
+ if (typeof instruction !== "string" || typeof startRoute !== "string") return undefined
72
+ if (typeof route !== "string" || appeared === undefined || disappeared === undefined) {
73
+ return undefined
74
+ }
75
+ if (!Array.isArray(raw.actions) || raw.actions.length === 0) return undefined
76
+ const actions: RecordedAction[] = []
77
+ for (const item of raw.actions) {
78
+ const action = parseAction(item)
79
+ if (action === undefined) return undefined
80
+ actions.push(action)
81
+ }
82
+ return { version: 1, instruction, startRoute, actions, end: { route, appeared, disappeared } }
83
+ }
84
+
85
+ /** What a recorded action asked the page to do, without the bookkeeping. */
86
+ export function performedOf(action: RecordedAction): PerformedDecision {
87
+ if (action.kind === "goto") return action
88
+ if (action.kind === "tap") return { kind: "tap", target: action.target }
89
+ if (action.kind === "fill") return { kind: "fill", target: action.target, value: action.value }
90
+ return { kind: "press", target: action.target, key: action.key }
91
+ }
92
+
93
+ /** Entries as files under `dir`, one JSON per key: small, diffable and meant to be committed. */
94
+ export function fileCacheStore(dir: string): CacheStore {
95
+ const file = (key: string): string => join(dir, `${key}.json`)
96
+ return {
97
+ async read(key) {
98
+ try {
99
+ return parseEntry(JSON.parse(await readFile(file(key), "utf8")))
100
+ } catch {
101
+ return undefined
102
+ }
103
+ },
104
+ async write(key, entry) {
105
+ await mkdir(dir, { recursive: true })
106
+ const temp = `${file(key)}.${process.pid}.tmp`
107
+ await writeFile(temp, `${JSON.stringify(entry, null, 2)}\n`)
108
+ await rename(temp, file(key))
109
+ },
110
+ async delete(key) {
111
+ await rm(file(key), { force: true })
112
+ },
113
+ }
114
+ }
115
+
116
+ /** Entries in memory, for tests of code built on this package. */
117
+ export function memoryCacheStore(): CacheStore & { readonly entries: Map<string, CacheEntry> } {
118
+ const entries = new Map<string, CacheEntry>()
119
+ return {
120
+ entries,
121
+ read: async (key) => entries.get(key),
122
+ write: async (key, entry) => {
123
+ entries.set(key, entry)
124
+ },
125
+ delete: async (key) => {
126
+ entries.delete(key)
127
+ },
128
+ }
129
+ }
130
+
131
+ export interface CacheOptions {
132
+ readonly mode?: CacheMode
133
+ /** Where entries live. Default `.nifra/e2e-cache` under the working directory. */
134
+ readonly dir?: string
135
+ /** Replaces the file store. */
136
+ readonly store?: CacheStore
137
+ /** Names the test, so two tests that say the same thing do not share a recording. Pass it: the default is empty. */
138
+ readonly testId?: string
139
+ /** Anything that should invalidate every recording when it changes, such as the app's version. */
140
+ readonly appIdentity?: string
141
+ }
142
+
143
+ export interface Cache {
144
+ readonly mode: CacheMode
145
+ /** Whether this run may write and delete entries. */
146
+ readonly canWrite: boolean
147
+ /** The key for the next `act` with this instruction; asking again counts as another occurrence. */
148
+ key(instruction: string, params: Params, context: string | undefined): string
149
+ read(key: string): Promise<CacheEntry | undefined>
150
+ /** Holds a new recording until a later check passes. */
151
+ stage(key: string, entry: CacheEntry): void
152
+ /** Notes that a recording was replayed, so a later failing check removes it. */
153
+ replayed(key: string): void
154
+ /** Removes a recording now: a hand-off the agent could not finish. */
155
+ discard(key: string): Promise<void>
156
+ /** A locator assertion or `agent.assert` finished: a pass writes what was staged, a failure deletes what it rested on. */
157
+ onCheck(passed: boolean): Promise<void>
158
+ /** Writes and deletes that the store refused; the cache is best effort and never fails a test. */
159
+ readonly failures: number
160
+ }
161
+
162
+ export function defaultCacheMode(): CacheMode {
163
+ return typeof process !== "undefined" && process.env.CI !== undefined && process.env.CI !== ""
164
+ ? "read-only"
165
+ : "read-write"
166
+ }
167
+
168
+ export function createCache(options: CacheOptions = {}): Cache {
169
+ const mode = options.mode ?? defaultCacheMode()
170
+ const store = options.store ?? fileCacheStore(options.dir ?? join(".nifra", "e2e-cache"))
171
+ const testId = options.testId ?? ""
172
+ const canWrite = mode === "read-write"
173
+ const occurrences = new Map<string, number>()
174
+ const staged = new Map<string, CacheEntry>()
175
+ const used = new Set<string>()
176
+ let failures = 0
177
+
178
+ const guarded = async (work: Promise<void>): Promise<void> => {
179
+ try {
180
+ await work
181
+ } catch {
182
+ failures += 1
183
+ }
184
+ }
185
+
186
+ return {
187
+ mode,
188
+ canWrite,
189
+ get failures() {
190
+ return failures
191
+ },
192
+ key(instruction, params, context) {
193
+ const material = JSON.stringify([
194
+ testId,
195
+ instruction,
196
+ keyParams(params),
197
+ context ?? "",
198
+ options.appIdentity ?? "",
199
+ ])
200
+ const seen = occurrences.get(material) ?? 0
201
+ occurrences.set(material, seen + 1)
202
+ return createHash("sha256").update(`${material}#${seen}`).digest("hex").slice(0, 32)
203
+ },
204
+ read: (key) => store.read(key),
205
+ stage(key, entry) {
206
+ staged.set(key, entry)
207
+ },
208
+ replayed(key) {
209
+ used.add(key)
210
+ },
211
+ async discard(key) {
212
+ staged.delete(key)
213
+ used.delete(key)
214
+ if (canWrite) await guarded(store.delete(key))
215
+ },
216
+ async onCheck(passed) {
217
+ const writes = [...staged]
218
+ const deletes = new Set([...staged.keys(), ...used])
219
+ staged.clear()
220
+ used.clear()
221
+ if (!canWrite) return
222
+ if (passed) {
223
+ for (const [key, entry] of writes) await guarded(store.write(key, entry))
224
+ } else {
225
+ for (const key of deletes) await guarded(store.delete(key))
226
+ }
227
+ },
228
+ }
229
+ }
@@ -0,0 +1,152 @@
1
+ import type { Selector, Step } from "./engine.ts"
2
+ import { isRecord } from "./internal/record.ts"
3
+
4
+ /** Which control a step means: exactly one of `role`, `label`, `text`, `testId`. */
5
+ export interface Target {
6
+ readonly role?: string
7
+ readonly name?: string
8
+ readonly label?: string
9
+ readonly text?: string
10
+ readonly testId?: string
11
+ readonly exact?: boolean
12
+ /** Zero-based pick among several matches. */
13
+ readonly nth?: number
14
+ }
15
+
16
+ export type ActDecision =
17
+ | { readonly kind: "tap"; readonly target: Target }
18
+ | { readonly kind: "fill"; readonly target: Target; readonly value: string }
19
+ | { readonly kind: "press"; readonly target: Target; readonly key: string }
20
+ | { readonly kind: "goto"; readonly path: string }
21
+ | { readonly kind: "done"; readonly summary?: string }
22
+ | { readonly kind: "fail"; readonly reason: string }
23
+
24
+ export type PerformedDecision = Exclude<ActDecision, { kind: "done" } | { kind: "fail" }>
25
+
26
+ export interface Verdict {
27
+ readonly pass: boolean | "inconclusive"
28
+ readonly reason: string
29
+ }
30
+
31
+ export type Parsed<T> =
32
+ | { readonly ok: true; readonly value: T }
33
+ | { readonly ok: false; readonly reason: string }
34
+
35
+ const fail = (reason: string): { ok: false; reason: string } => ({ ok: false, reason })
36
+
37
+ function parseTarget(raw: unknown): Parsed<Target> {
38
+ if (!isRecord(raw)) return fail("target must be an object")
39
+ const finders = (["role", "label", "text", "testId"] as const).filter(
40
+ (key) => raw[key] !== undefined,
41
+ )
42
+ if (finders.length !== 1) return fail("target needs exactly one of role, label, text, testId")
43
+ const target: {
44
+ role?: string
45
+ name?: string
46
+ label?: string
47
+ text?: string
48
+ testId?: string
49
+ exact?: boolean
50
+ nth?: number
51
+ } = {}
52
+ for (const key of ["role", "name", "label", "text", "testId"] as const) {
53
+ const value = raw[key]
54
+ if (value === undefined) continue
55
+ if (typeof value !== "string" || value === "")
56
+ return fail(`target.${key} must be a non-empty string`)
57
+ target[key] = value
58
+ }
59
+ if (raw.exact !== undefined) {
60
+ if (typeof raw.exact !== "boolean") return fail("target.exact must be a boolean")
61
+ target.exact = raw.exact
62
+ }
63
+ if (raw.nth !== undefined) {
64
+ if (typeof raw.nth !== "number" || !Number.isInteger(raw.nth) || raw.nth < 0) {
65
+ return fail("target.nth must be a non-negative integer")
66
+ }
67
+ target.nth = raw.nth
68
+ }
69
+ return { ok: true, value: target }
70
+ }
71
+
72
+ export function parseActDecision(raw: unknown): Parsed<ActDecision> {
73
+ if (!isRecord(raw)) return fail("a decision must be an object")
74
+ switch (raw.kind) {
75
+ case "done":
76
+ return {
77
+ ok: true,
78
+ value:
79
+ typeof raw.summary === "string"
80
+ ? { kind: "done", summary: raw.summary }
81
+ : { kind: "done" },
82
+ }
83
+ case "fail":
84
+ return typeof raw.reason === "string" && raw.reason !== ""
85
+ ? { ok: true, value: { kind: "fail", reason: raw.reason } }
86
+ : fail("fail needs a reason")
87
+ case "goto":
88
+ return typeof raw.path === "string" && raw.path.startsWith("/")
89
+ ? { ok: true, value: { kind: "goto", path: raw.path } }
90
+ : fail("goto needs a path that starts with /")
91
+ case "tap":
92
+ case "fill":
93
+ case "press": {
94
+ const target = parseTarget(raw.target)
95
+ if (!target.ok) return target
96
+ if (raw.kind === "tap") return { ok: true, value: { kind: "tap", target: target.value } }
97
+ if (raw.kind === "fill") {
98
+ return typeof raw.value === "string"
99
+ ? { ok: true, value: { kind: "fill", target: target.value, value: raw.value } }
100
+ : fail("fill needs a string value")
101
+ }
102
+ return typeof raw.key === "string" && raw.key !== ""
103
+ ? { ok: true, value: { kind: "press", target: target.value, key: raw.key } }
104
+ : fail("press needs a key")
105
+ }
106
+ default:
107
+ return fail(`unknown decision kind ${JSON.stringify(raw.kind)}`)
108
+ }
109
+ }
110
+
111
+ export function parseVerdict(raw: unknown): Parsed<Verdict> {
112
+ if (!isRecord(raw)) return fail("a verdict must be an object")
113
+ const { pass } = raw
114
+ if (pass !== true && pass !== false && pass !== "inconclusive") {
115
+ return fail('a verdict needs pass: true, false or "inconclusive"')
116
+ }
117
+ return { ok: true, value: { pass, reason: typeof raw.reason === "string" ? raw.reason : "" } }
118
+ }
119
+
120
+ export function parseExtraction(raw: unknown): Parsed<unknown> {
121
+ if (!isRecord(raw) || !Object.hasOwn(raw, "value")) return fail("an extraction needs a value")
122
+ return { ok: true, value: raw.value }
123
+ }
124
+
125
+ export function targetSelector(target: Target): Selector {
126
+ const steps: Step[] = []
127
+ if (target.role !== undefined) {
128
+ const step: { kind: "role"; role: string; name?: string; exact?: boolean } = {
129
+ kind: "role",
130
+ role: target.role,
131
+ }
132
+ if (target.name !== undefined) step.name = target.name
133
+ if (target.exact !== undefined) step.exact = target.exact
134
+ steps.push(step)
135
+ } else if (target.label !== undefined) {
136
+ const step: { kind: "label"; text: string; exact?: boolean } = {
137
+ kind: "label",
138
+ text: target.label,
139
+ }
140
+ if (target.exact !== undefined) step.exact = target.exact
141
+ steps.push(step)
142
+ } else if (target.text !== undefined) {
143
+ const step: { kind: "text"; text: string; exact?: boolean } = {
144
+ kind: "text",
145
+ text: target.text,
146
+ }
147
+ if (target.exact !== undefined) step.exact = target.exact
148
+ steps.push(step)
149
+ } else if (target.testId !== undefined) steps.push({ kind: "testId", id: target.testId })
150
+ if (target.nth !== undefined) steps.push({ kind: "nth", index: target.nth })
151
+ return steps
152
+ }
package/src/engine.ts ADDED
@@ -0,0 +1,92 @@
1
+ export type E2EErrorCode =
2
+ | "LOCATOR_NOT_FOUND"
3
+ | "LOCATOR_AMBIGUOUS"
4
+ | "EXPECT_FAILED"
5
+ | "HYDRATION_TIMEOUT"
6
+ | "ENGINE_MISSING"
7
+ | "NAVIGATION_FAILED"
8
+ | "BAD_PATH"
9
+ | "MODEL_MISSING"
10
+ | "MODEL_INVALID"
11
+ | "STEP_FAILED"
12
+ | "STEP_BUDGET_EXCEEDED"
13
+ | "STEP_TIMEOUT"
14
+ | "ASSERTION_FAILED"
15
+ | "ASSERTION_INCONCLUSIVE"
16
+ | "WAIT_TIMEOUT"
17
+ | "EXTRACT_INVALID"
18
+ | "REPLAY_MISSING"
19
+ | "REPLAY_STALE"
20
+
21
+ export class E2EError extends Error {
22
+ readonly code: E2EErrorCode
23
+
24
+ constructor(code: E2EErrorCode, message: string, options?: ErrorOptions) {
25
+ super(message, options)
26
+ this.name = "E2EError"
27
+ this.code = code
28
+ }
29
+ }
30
+
31
+ /** One link of a locator chain; the first finds from the page, each later one searches inside the matches so far. */
32
+ export type Step =
33
+ | {
34
+ readonly kind: "role"
35
+ readonly role: string
36
+ readonly name?: string
37
+ readonly exact?: boolean
38
+ }
39
+ | { readonly kind: "label"; readonly text: string; readonly exact?: boolean }
40
+ | { readonly kind: "text"; readonly text: string; readonly exact?: boolean }
41
+ | { readonly kind: "testId"; readonly id: string }
42
+ | { readonly kind: "hasText"; readonly text: string }
43
+ | { readonly kind: "nth"; readonly index: number }
44
+
45
+ export type Selector = readonly Step[]
46
+
47
+ export interface ElementState {
48
+ readonly visible: boolean
49
+ readonly text: string
50
+ readonly value?: string
51
+ }
52
+
53
+ export type ElementAction =
54
+ | { readonly kind: "tap" }
55
+ | { readonly kind: "fill"; readonly value: string }
56
+ | { readonly kind: "press"; readonly key: string }
57
+
58
+ /**
59
+ * What a browser or device must offer. `act` waits up to `timeout` ms for exactly one actionable
60
+ * match, then performs the action; it throws `LOCATOR_NOT_FOUND` or `LOCATOR_AMBIGUOUS` otherwise.
61
+ * `resolve` never waits and never throws on zero matches.
62
+ */
63
+ export interface Engine {
64
+ goto(url: string): Promise<void>
65
+ url(): Promise<string>
66
+ resolve(selector: Selector): Promise<readonly ElementState[]>
67
+ /** The page as an accessibility-tree outline, one node per line; what an agent step reads. */
68
+ snapshot(): Promise<string>
69
+ act(selector: Selector, action: ElementAction, timeout: number): Promise<void>
70
+ close(): Promise<void>
71
+ }
72
+
73
+ export interface EngineInit {
74
+ readonly baseUrl: string
75
+ readonly cookies: readonly { readonly name: string; readonly value: string }[]
76
+ readonly hydration: HydrationMode
77
+ }
78
+
79
+ export type EngineFactory = (init: EngineInit) => Promise<Engine>
80
+
81
+ /** `auto` waits for nifra's `data-nifra-hydrated` marker only on pages that load a module script. */
82
+ export type HydrationMode = "auto" | "off"
83
+
84
+ export interface Clock {
85
+ now(): number
86
+ sleep(ms: number): Promise<void>
87
+ }
88
+
89
+ export const realClock: Clock = {
90
+ now: () => Date.now(),
91
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
92
+ }
@@ -0,0 +1,58 @@
1
+ import { INTERACTIVE } from "./snapshot.ts"
2
+
3
+ /** Roles whose text is what the user typed, which differs per run and says nothing about the page. */
4
+ const INPUT_ROLES = new Set(["textbox", "searchbox", "combobox", "spinbutton", "slider"])
5
+ const STATE_ATTRS = /^(?:checked|selected|expanded|pressed)\b/
6
+ const LINE = /^- (\w+)( "(?:[^"\\]|\\.)*")?((?: \[[^\]]*\])*)(?::\s?(.*))?$/s
7
+ const MAX_LINES = 30
8
+
9
+ /** A control or heading, its name and its checked/selected/expanded/pressed state; typed text left out. */
10
+ function evidenceLine(line: string): string | undefined {
11
+ if (!INTERACTIVE.test(line)) return undefined
12
+ const trimmed = line.trim()
13
+ const parts = LINE.exec(trimmed)
14
+ if (parts === null) return trimmed
15
+ const [, role = "", name = "", attrs = "", tail = ""] = parts
16
+ const states = [...attrs.matchAll(/ \[([^\]]*)\]/g)]
17
+ .map((match) => match[1] ?? "")
18
+ .filter((attr) => STATE_ATTRS.test(attr))
19
+ .map((attr) => ` [${attr}]`)
20
+ .join("")
21
+ const text = INPUT_ROLES.has(role) || tail === "" ? "" : `: ${tail}`
22
+ return `- ${role}${name}${states}${text}`
23
+ }
24
+
25
+ function evidenceLines(snapshot: string): string[] {
26
+ const out: string[] = []
27
+ for (const line of snapshot.split("\n")) {
28
+ const kept = evidenceLine(line)
29
+ if (kept !== undefined && !out.includes(kept)) out.push(kept)
30
+ }
31
+ return out
32
+ }
33
+
34
+ export interface Evidence {
35
+ readonly appeared: readonly string[]
36
+ readonly disappeared: readonly string[]
37
+ }
38
+
39
+ /** What the action changed on the page, as controls and headings that came or went, in page order. */
40
+ export function diffEvidence(before: string, after: string): Evidence {
41
+ const was = evidenceLines(before)
42
+ const now = evidenceLines(after)
43
+ return {
44
+ appeared: now.filter((line) => !was.includes(line)).slice(0, MAX_LINES),
45
+ disappeared: was.filter((line) => !now.includes(line)).slice(0, MAX_LINES),
46
+ }
47
+ }
48
+
49
+ export type EvidenceCheck = { readonly ok: true } | { readonly ok: false; readonly detail: string }
50
+
51
+ export function checkEvidence(evidence: Evidence, snapshot: string): EvidenceCheck {
52
+ const now = evidenceLines(snapshot)
53
+ const missing = evidence.appeared.find((line) => !now.includes(line))
54
+ if (missing !== undefined) return { ok: false, detail: `expected ${missing} to be on the page` }
55
+ const lingering = evidence.disappeared.find((line) => now.includes(line))
56
+ if (lingering !== undefined) return { ok: false, detail: `expected ${lingering} to be gone` }
57
+ return { ok: true }
58
+ }