@jeffawe/understudy 0.0.0-stage → 0.2.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 (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +171 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1008 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +79 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,530 @@
1
+ /**
2
+ * Script source — turn an existing Playwright script into a RawRecording.
3
+ *
4
+ * Handles both `playwright codegen` output and hand-written `.spec.ts` suites,
5
+ * because they are the same thing: codegen just produces an unusually regular
6
+ * subset. This is what makes the input side open — a team with an existing
7
+ * suite can import it without recording anything by hand.
8
+ *
9
+ * WHY A REAL AST, NOT REGEX:
10
+ * codegen output is regular enough to regex, but hand-written tests are not —
11
+ * chains split across lines, strings contain parentheses, comments contain
12
+ * code-shaped text, and TypeScript syntax sits in the middle of it. The
13
+ * TypeScript compiler is already a dependency and parses all of that correctly.
14
+ *
15
+ * WHY STATIC PARSING RATHER THAN EXECUTION:
16
+ * running someone's suite needs their fixtures, auth, environment and a live
17
+ * app. Reading it needs none of those. The tradeoff is that a static read
18
+ * cannot know runtime values or which page it is on — see `url` below.
19
+ *
20
+ * A DELIBERATE WIN: a non-literal argument becomes a `valueRef` rather than a
21
+ * value. `page.getByRole('textbox', {name: 'Email'}).fill(MEMBER.email)`
22
+ * records `valueRef: 'MEMBER.email'` — which is exactly the parameterised shape
23
+ * the IR wants, arrived at for free.
24
+ */
25
+ import { readFile } from 'node:fs/promises';
26
+ import { existsSync } from 'node:fs';
27
+ import { basename, dirname, isAbsolute, join } from 'node:path';
28
+ import ts from 'typescript';
29
+ import { buildRecording, redactValue, } from '../../core/recording.js';
30
+ /** Terminal calls that are actions rather than refinements. */
31
+ const ACTIONS = {
32
+ click: 'click',
33
+ dblclick: 'click',
34
+ fill: 'fill',
35
+ type: 'fill',
36
+ press: 'press',
37
+ check: 'check',
38
+ uncheck: 'uncheck',
39
+ selectOption: 'select',
40
+ setInputFiles: 'upload',
41
+ goto: 'goto',
42
+ // Playwright's own name for "scroll whatever container holds this until it
43
+ // is visible". Chosen as the capture form over a raw
44
+ // `evaluate(el => el.scrollTop = el.scrollHeight)` deliberately: it is
45
+ // element-addressed, so it fits the role/name/css model the rest of the IR
46
+ // uses, and importing it needs no evaluation of arbitrary page script.
47
+ scrollIntoViewIfNeeded: 'scroll_container',
48
+ };
49
+ /**
50
+ * Calls that mean "take a picture here".
51
+ *
52
+ * `toHaveScreenshot` is Playwright's own; the rest are the wrapper names teams
53
+ * put around it — a suite almost always has one, because the raw assertion
54
+ * needs the same masking and options at every call site. Add yours here.
55
+ */
56
+ const SNAPSHOT_CALLS = new Set(['toHaveScreenshot', 'checkpoint', 'visualCheckpoint', 'snapshot']);
57
+ /**
58
+ * Calls that DO something to the page but that the IR cannot express.
59
+ *
60
+ * These exist to be warned about, not to be mapped. An unmapped call used to
61
+ * fall through the walk in silence, which is the worst possible outcome: the
62
+ * import "succeeds", the step count looks plausible, and the recording is
63
+ * quietly missing a step the flow depends on. That is exactly how one spec's
64
+ * `page.evaluate` scroll — the thing that unlocked its submit button —
65
+ * disappeared between a spec that passes and a recording that cannot.
66
+ *
67
+ * A missing step must cost a warning, every time.
68
+ */
69
+ const UNEXPRESSIBLE = new Set([
70
+ 'evaluate', 'evaluateHandle', '$eval', '$$eval',
71
+ 'dispatchEvent', 'hover', 'dragTo', 'focus', 'blur', 'tap',
72
+ 'setChecked', 'clear', 'selectText', 'waitForTimeout', 'waitForFunction',
73
+ 'addStyleTag', 'addScriptTag', 'route', 'unroute',
74
+ ]);
75
+ /**
76
+ * Recognise the one `evaluate` shape worth reading rather than warning about:
77
+ * scrolling a nested pane to an edge.
78
+ *
79
+ * Deliberately narrow. This matches on SOURCE TEXT, which is a heuristic and
80
+ * not a parse, so it only claims a call when both halves are unambiguous — a
81
+ * `querySelector` with a literal argument, and an assignment to `scrollTop`.
82
+ * Anything else falls through to the warning, because guessing at arbitrary
83
+ * page script is how you get a recording that lies.
84
+ *
85
+ * Worth special-casing because a scroll gate is not exotic: any "review your
86
+ * answers before submitting" screen has one, and without this the whole tail of
87
+ * such a flow is uncapturable.
88
+ */
89
+ function scrollContainerFrom(node) {
90
+ const body = node.arguments.map((a) => a.getText()).join(' ');
91
+ if (!/\.scrollTop\s*=/.test(body))
92
+ return undefined;
93
+ const css = body.match(/querySelector(?:All)?\(\s*['"`]([^'"`]+)['"`]\s*\)/)?.[1];
94
+ if (!css)
95
+ return undefined;
96
+ // `= el.scrollHeight` means bottom; `= 0` means top. Anything else is a
97
+ // partial scroll the IR has no way to say, so leave it to the warning.
98
+ if (/\.scrollTop\s*=\s*[^;]*scrollHeight/.test(body))
99
+ return { css, edge: 'bottom' };
100
+ if (/\.scrollTop\s*=\s*0\b/.test(body))
101
+ return { css, edge: 'top' };
102
+ return undefined;
103
+ }
104
+ const text = (node) => ts.isStringLiteralLike(node) ? node.text : undefined;
105
+ /** Join a possibly-relative spec URL onto the app's base URL. */
106
+ function absolute(url, base) {
107
+ try {
108
+ return new URL(url, base).toString();
109
+ }
110
+ catch {
111
+ // An unparseable base is not worth failing the whole import over; the
112
+ // literal at least records what the spec said.
113
+ return url;
114
+ }
115
+ }
116
+ /**
117
+ * Resolve a file path a spec passes to setInputFiles.
118
+ *
119
+ * Specs write these relative to the repo they run in ('tests/fixtures/x.png'),
120
+ * because that is where Playwright's cwd is. Understudy replays from its own
121
+ * directory, so storing the literal produced ENOENT on every upload step. Walk
122
+ * up from the spec file until the path resolves — that finds the repo root
123
+ * without needing to know how the other project is laid out.
124
+ */
125
+ function resolveFixture(value, specPath) {
126
+ if (isAbsolute(value))
127
+ return value;
128
+ let dir = dirname(specPath);
129
+ for (let up = 0; up < 6; up++) {
130
+ const candidate = join(dir, value);
131
+ if (existsSync(candidate))
132
+ return candidate;
133
+ const parent = dirname(dir);
134
+ if (parent === dir)
135
+ break;
136
+ dir = parent;
137
+ }
138
+ // Not found anywhere: keep the literal so the failure names what the spec
139
+ // asked for rather than a path this function invented.
140
+ return value;
141
+ }
142
+ function textMatch(node) {
143
+ if (!node)
144
+ return undefined;
145
+ if (ts.isStringLiteralLike(node))
146
+ return { source: node.text, regex: false, flags: '' };
147
+ if (ts.isRegularExpressionLiteral(node)) {
148
+ // getText() is the literal as written, e.g. `/^No$/i`.
149
+ const raw = node.getText();
150
+ const close = raw.lastIndexOf('/');
151
+ return { source: raw.slice(1, close), regex: true, flags: raw.slice(close + 1) };
152
+ }
153
+ return undefined;
154
+ }
155
+ /**
156
+ * Read `{ name: 'Login', exact: true }`.
157
+ * Only literal properties are useful; a computed name can't be known statically.
158
+ */
159
+ function readOptions(node) {
160
+ if (!node || !ts.isObjectLiteralExpression(node))
161
+ return {};
162
+ const out = {};
163
+ for (const prop of node.properties) {
164
+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name))
165
+ continue;
166
+ if (prop.name.text === 'name') {
167
+ const match = textMatch(prop.initializer);
168
+ if (match !== undefined)
169
+ out.name = match;
170
+ }
171
+ if (prop.name.text === 'exact') {
172
+ out.exact = prop.initializer.kind === ts.SyntaxKind.TrueKeyword;
173
+ }
174
+ }
175
+ return out;
176
+ }
177
+ /**
178
+ * Read `.filter({ hasText: ... })`.
179
+ *
180
+ * THIS IS ADDRESSING, NOT DECORATION. `filter` used to be treated as a
181
+ * refinement "that doesn't change which element we're addressing", which is
182
+ * exactly backwards: `page.locator('label').filter({hasText: 'I accept'})`
183
+ * narrows every label on the page down to one. Dropping it turned a precise
184
+ * locator into `css=label` — and silently, with no warning, so the recording
185
+ * looked clean and would have clicked whatever label happened to be first.
186
+ *
187
+ * `has` / `hasNot` take a Locator rather than text and cannot be represented in
188
+ * the IR, so they are reported instead of quietly ignored.
189
+ */
190
+ function readFilter(node) {
191
+ if (!node || !ts.isObjectLiteralExpression(node))
192
+ return {};
193
+ for (const prop of node.properties) {
194
+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name))
195
+ continue;
196
+ const key = prop.name.text;
197
+ if (key === 'hasText') {
198
+ const match = textMatch(prop.initializer);
199
+ if (match)
200
+ return { hasText: match };
201
+ return { unsupported: 'filter({hasText}) with a non-literal value' };
202
+ }
203
+ if (key === 'has' || key === 'hasNot' || key === 'hasNotText') {
204
+ return { unsupported: `filter({${key}})` };
205
+ }
206
+ }
207
+ return {};
208
+ }
209
+ /** What one link in a locator chain contributes to addressing the element. */
210
+ function locatorBit(method, args) {
211
+ const first = args[0];
212
+ switch (method) {
213
+ case 'getByRole': {
214
+ const role = first ? text(first) : undefined;
215
+ const { name, exact } = readOptions(args[1]);
216
+ return role ? { role, ...(name !== undefined ? { name } : {}), ...(exact ? { exact } : {}) } : undefined;
217
+ }
218
+ // Playwright's accname falls back to the placeholder, so a placeholder
219
+ // lookup and an accessible name are the same thing to us.
220
+ case 'getByPlaceholder':
221
+ case 'getByLabel':
222
+ case 'getByText':
223
+ case 'getByTitle':
224
+ case 'getByAltText': {
225
+ const name = textMatch(first);
226
+ const { exact } = readOptions(args[1]);
227
+ return name !== undefined ? { name, ...(exact ? { exact } : {}) } : undefined;
228
+ }
229
+ case 'getByTestId': {
230
+ const id = first ? text(first) : undefined;
231
+ return id !== undefined ? { testId: id } : undefined;
232
+ }
233
+ case 'locator': {
234
+ const css = first ? text(first) : undefined;
235
+ return css !== undefined ? { css } : undefined;
236
+ }
237
+ case 'frameLocator': {
238
+ const frame = first ? text(first) : undefined;
239
+ // Suffix match, never exact — iframe ids are frequently generated.
240
+ return frame !== undefined ? { frameHint: frame.replace(/^#/, '') } : undefined;
241
+ }
242
+ case 'first':
243
+ return { nth: 0 };
244
+ case 'last':
245
+ return { nth: -1 };
246
+ case 'nth': {
247
+ const n = first && ts.isNumericLiteral(first) ? Number(first.text) : undefined;
248
+ return n !== undefined ? { nth: n } : undefined;
249
+ }
250
+ // NOT a no-op — see readFilter. This is what narrows `locator('label')`
251
+ // from every label on the page down to the one that says "I accept".
252
+ case 'filter': {
253
+ const { hasText, unsupported } = readFilter(first);
254
+ return {
255
+ ...(hasText ? { hasText } : {}),
256
+ ...(unsupported ? { unsupported } : {}),
257
+ };
258
+ }
259
+ // These genuinely don't narrow by anything the IR can express.
260
+ case 'and':
261
+ case 'or':
262
+ return {};
263
+ default:
264
+ return undefined;
265
+ }
266
+ }
267
+ /**
268
+ * Read an action's argument as either a literal value or a reference.
269
+ *
270
+ * `fill('standard_user')` → value
271
+ * `fill(MEMBER.email)` → valueRef 'MEMBER.email' ← already the IR shape
272
+ * `fill(process.env.SHOP_PASSWORD!)` → valueRef 'ENV.SHOP_PASSWORD'
273
+ */
274
+ function readArgument(arg) {
275
+ if (!arg)
276
+ return {};
277
+ const literal = text(arg);
278
+ if (literal !== undefined)
279
+ return { value: literal };
280
+ // A script reading its own environment — what an agent's script usually
281
+ // does for a password. Every spelling of it becomes ENV.<NAME>, whose value
282
+ // is then found under that same variable at replay (store/settings.ts).
283
+ const env = envVariable(arg);
284
+ if (env)
285
+ return { valueRef: `ENV.${env}` };
286
+ if (ts.isPropertyAccessExpression(arg) || ts.isIdentifier(arg)) {
287
+ return { valueRef: arg.getText() };
288
+ }
289
+ if (ts.isTemplateExpression(arg))
290
+ return { valueRef: arg.getText() };
291
+ return { valueRef: arg.getText().slice(0, 80) };
292
+ }
293
+ /** `process.env.X`, `process.env.X!`, `process.env['X']`, `process.env.X ?? ''` → 'X'. */
294
+ function envVariable(arg) {
295
+ let e = arg;
296
+ while (true) {
297
+ if (ts.isNonNullExpression(e) || ts.isParenthesizedExpression(e) || ts.isAsExpression(e))
298
+ e = e.expression;
299
+ else if (ts.isBinaryExpression(e) && (e.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || e.operatorToken.kind === ts.SyntaxKind.BarBarToken))
300
+ e = e.left;
301
+ else
302
+ break;
303
+ }
304
+ const isProcessEnv = (x) => ts.isPropertyAccessExpression(x) && x.name.text === 'env' && ts.isIdentifier(x.expression) && x.expression.text === 'process';
305
+ if (ts.isPropertyAccessExpression(e) && isProcessEnv(e.expression))
306
+ return e.name.text;
307
+ if (ts.isElementAccessExpression(e) && isProcessEnv(e.expression) && ts.isStringLiteralLike(e.argumentExpression))
308
+ return e.argumentExpression.text;
309
+ return undefined;
310
+ }
311
+ export async function parseScript(filePath, appSlug, fallbackUrl) {
312
+ const source = await readFile(filePath, 'utf8');
313
+ const sourceFile = ts.createSourceFile(basename(filePath), source, ts.ScriptTarget.Latest,
314
+ /* setParentNodes */ true, filePath.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS);
315
+ const events = [];
316
+ const warnings = [];
317
+ // A static read cannot know which page it is on, so the last goto stands in.
318
+ // Anything before the first goto is attributed to the fallback URL.
319
+ let currentUrl = fallbackUrl ?? '';
320
+ let startUrl = fallbackUrl ?? '';
321
+ const visit = (node) => {
322
+ // VISUAL CHECKPOINTS, WHICH ARE NOT PAGE METHODS.
323
+ //
324
+ // `expect(page).toHaveScreenshot('x.png')` is a chain off expect(), and a
325
+ // helper like `checkpoint(page, testInfo, '01-bmi')` is a bare call — so
326
+ // neither reaches the page-rooted walker below, and both were silently
327
+ // dropped. They are the most valuable thing in the file for this purpose:
328
+ // somebody decided, by hand, exactly where a picture is worth taking.
329
+ if (ts.isCallExpression(node)) {
330
+ const callee = ts.isPropertyAccessExpression(node.expression)
331
+ ? node.expression.name.text
332
+ : ts.isIdentifier(node.expression)
333
+ ? node.expression.text
334
+ : undefined;
335
+ if (callee && SNAPSHOT_CALLS.has(callee)) {
336
+ // The label is the first string literal in the arguments, wherever it
337
+ // sits — `toHaveScreenshot('x.png')` has it first, `checkpoint(page,
338
+ // testInfo, 'x')` third.
339
+ const raw = node.arguments.map(text).find((t) => t !== undefined);
340
+ const label = raw?.replace(/\.png$/i, '');
341
+ if (label) {
342
+ events.push({
343
+ seq: events.length,
344
+ ts: events.length,
345
+ action: 'snapshot',
346
+ value: label,
347
+ url: currentUrl,
348
+ resolution: 'script-literal',
349
+ });
350
+ }
351
+ else {
352
+ warnings.push(`visual checkpoint with no literal name: ${node.getText().slice(0, 70)}`);
353
+ }
354
+ }
355
+ }
356
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
357
+ const method = node.expression.name.text;
358
+ const action = ACTIONS[method];
359
+ // An unmappable call is REPORTED, never dropped. See UNEXPRESSIBLE.
360
+ if (!action && UNEXPRESSIBLE.has(method)) {
361
+ const scroll = method.startsWith('evaluate') ? scrollContainerFrom(node) : undefined;
362
+ if (scroll) {
363
+ events.push({
364
+ seq: events.length,
365
+ ts: events.length,
366
+ action: 'scroll_container',
367
+ css: scroll.css,
368
+ value: scroll.edge,
369
+ url: currentUrl,
370
+ // The pane was addressed by CSS in the spec and nothing resolved a
371
+ // role or name for it, which is precisely what 'unresolved' means.
372
+ resolution: 'unresolved',
373
+ });
374
+ }
375
+ else {
376
+ warnings.push(`${method}() cannot be expressed by the IR, step DROPPED: ${node.getText().slice(0, 70)}`);
377
+ }
378
+ }
379
+ if (action) {
380
+ // Unwind the chain back to its root, collecting addressing bits.
381
+ const bits = [];
382
+ let cursor = node.expression.expression;
383
+ let rooted = false;
384
+ let unknown;
385
+ while (ts.isCallExpression(cursor) && ts.isPropertyAccessExpression(cursor.expression)) {
386
+ const bit = locatorBit(cursor.expression.name.text, cursor.arguments);
387
+ if (!bit)
388
+ unknown ??= cursor.expression.name.text;
389
+ else
390
+ bits.unshift(bit);
391
+ cursor = cursor.expression.expression;
392
+ }
393
+ // The root must be something page-like. `page`, `frame`, a page object's
394
+ // `this.page` — but NOT `expect(...)`, which is an assertion.
395
+ const rootText = cursor.getText();
396
+ rooted = /(^|\.)page$|^frame$|^context$/.test(rootText) || rootText === 'page';
397
+ if (rooted) {
398
+ // A CHAIN IS SCOPE + TARGET, NOT ONE MERGED ELEMENT.
399
+ //
400
+ // `page.getByRole('navigation').getByText('Login')` addresses the
401
+ // text "Login" *inside* the navigation landmark. Flattening the chain
402
+ // produced role=navigation name="Login" — an element that does not
403
+ // exist, and a locator that would never resolve on replay.
404
+ //
405
+ // So the TARGET is the last link that actually addresses something,
406
+ // and everything before it is scope, kept as a hint rather than
407
+ // folded into the element's own identity.
408
+ const addresses = (b) => b.role !== undefined || b.name !== undefined || b.css !== undefined || b.testId !== undefined;
409
+ let targetIndex = -1;
410
+ for (let i = bits.length - 1; i >= 0; i--) {
411
+ if (addresses(bits[i])) {
412
+ targetIndex = i;
413
+ break;
414
+ }
415
+ }
416
+ const target = targetIndex >= 0 ? bits[targetIndex] : {};
417
+ const scopeBits = targetIndex > 0 ? bits.slice(0, targetIndex).filter(addresses) : [];
418
+ // nth, frameHint and hasText are positional/structural: they apply to
419
+ // the target wherever in the chain they were written. hasText takes
420
+ // the LAST one, matching nth — in practice a filter directly follows
421
+ // the locator it narrows.
422
+ const nth = [...bits].reverse().find((b) => b.nth !== undefined)?.nth;
423
+ const frameHint = bits.find((b) => b.frameHint !== undefined)?.frameHint;
424
+ const hasText = [...bits].reverse().find((b) => b.hasText !== undefined)?.hasText;
425
+ const unsupported = bits.find((b) => b.unsupported !== undefined)?.unsupported;
426
+ if (unsupported) {
427
+ warnings.push(`${unsupported} could not be represented: ${node.getText().slice(0, 70)}`);
428
+ }
429
+ const merged = {
430
+ ...target,
431
+ ...(nth !== undefined ? { nth } : {}),
432
+ ...(frameHint !== undefined ? { frameHint } : {}),
433
+ ...(hasText !== undefined ? { hasText } : {}),
434
+ };
435
+ const scope = scopeBits.length
436
+ ? scopeBits.map((b) => (b.role ? `role=${b.role}` : b.css ? `css=${b.css}` : `name=${b.name?.source}`))
437
+ : undefined;
438
+ if (action === 'goto') {
439
+ const urlArg = node.arguments[0];
440
+ const literal = urlArg ? text(urlArg) : undefined;
441
+ // RESOLVE AGAINST THE BASE URL. Playwright specs are written with
442
+ // relative paths on purpose — `page.goto('/overview')` plus a
443
+ // `baseURL` in the config — so the literal alone is not navigable.
444
+ // Storing it raw produced "Cannot navigate to invalid URL" on the
445
+ // very first step of every imported spec.
446
+ const url = literal && fallbackUrl ? absolute(literal, fallbackUrl) : literal;
447
+ if (url) {
448
+ currentUrl = url;
449
+ if (!startUrl)
450
+ startUrl = url;
451
+ events.push({
452
+ seq: events.length,
453
+ ts: events.length,
454
+ action: 'goto',
455
+ value: url,
456
+ url,
457
+ resolution: 'script-literal',
458
+ });
459
+ }
460
+ else {
461
+ warnings.push(`goto with a non-literal URL: ${node.getText().slice(0, 70)}`);
462
+ }
463
+ }
464
+ else if (!merged.role && !merged.name && !merged.css && !merged.testId) {
465
+ warnings.push(`unaddressable ${action}: ${node.getText().slice(0, 70)}`);
466
+ }
467
+ else {
468
+ const raw = readArgument(node.arguments[0]);
469
+ const fieldHint = merged.name?.source || merged.testId || merged.css || 'field';
470
+ const secretSignal = [merged.name?.source, merged.css, merged.testId].filter(Boolean).join(' ');
471
+ // A literal password in a committed test still must not reach the
472
+ // corpus. A valueRef is already a reference and passes through.
473
+ // An upload's argument is a PATH, not a value to redact — and it
474
+ // needs resolving against the spec's own repo before it can be read.
475
+ const valued = action === 'upload' && raw.value !== undefined
476
+ ? { value: resolveFixture(raw.value, filePath) }
477
+ : raw.value !== undefined
478
+ ? redactValue(fieldHint, raw.value, undefined, secretSignal)
479
+ : raw;
480
+ events.push({
481
+ seq: events.length,
482
+ ts: events.length,
483
+ action,
484
+ ...(merged.role ? { role: merged.role } : {}),
485
+ // `name` stays a plain string because sig(), selector dedupe and
486
+ // the embeddings all key on it. When the source was a regex, the
487
+ // string is its SOURCE and hints carry the regex-ness so replay
488
+ // can rebuild the real matcher — `exact` would be wrong here, a
489
+ // source like `Version 2\.5` never equals an accessible name.
490
+ ...(merged.name !== undefined ? { name: merged.name.source } : {}),
491
+ ...(merged.exact ? { exact: merged.exact } : {}),
492
+ ...valued,
493
+ ...(merged.css ? { css: merged.css } : {}),
494
+ ...(merged.testId ? { testId: merged.testId } : {}),
495
+ ...(merged.frameHint ? { frameHint: merged.frameHint } : {}),
496
+ url: currentUrl,
497
+ resolution: 'script-literal',
498
+ ...(merged.nth !== undefined || unknown || scope || merged.hasText || merged.name?.regex
499
+ ? {
500
+ hints: {
501
+ ...(merged.nth !== undefined ? { nth: merged.nth } : {}),
502
+ ...(scope ? { scope } : {}),
503
+ ...(unknown ? { unparsedChainStep: unknown } : {}),
504
+ ...(merged.hasText
505
+ ? {
506
+ hasText: merged.hasText.source,
507
+ ...(merged.hasText.regex
508
+ ? { hasTextRegex: true, hasTextFlags: merged.hasText.flags }
509
+ : {}),
510
+ }
511
+ : {}),
512
+ ...(merged.name?.regex
513
+ ? { nameRegex: true, nameFlags: merged.name.flags }
514
+ : {}),
515
+ },
516
+ }
517
+ : {}),
518
+ });
519
+ }
520
+ }
521
+ }
522
+ }
523
+ ts.forEachChild(node, visit);
524
+ };
525
+ visit(sourceFile);
526
+ return {
527
+ recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl }, events.map((e, i) => ({ ...e, seq: i }))),
528
+ warnings,
529
+ };
530
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What the in-page recorder sends, and how it becomes a recording step.
3
+ *
4
+ * Shared by both recorders — the Playwright one (live.ts) and the Chrome
5
+ * extension (extension.ts) — so a flow recorded either way produces exactly
6
+ * the same steps. The in-page script itself is injected.ts.
7
+ */
8
+ import { type RawEvent, type RecordedAction } from '../../core/recording.js';
9
+ /** What the in-page script sends for each action. */
10
+ export interface WireEvent {
11
+ seq: number;
12
+ action: RecordedAction;
13
+ stamp: number;
14
+ url: string;
15
+ hintRole: string;
16
+ hintName: string;
17
+ /** Which path produced hintRole/hintName in the page: the accname library, or a heuristic. */
18
+ resolvedBy?: 'accname' | 'heuristic';
19
+ css?: string;
20
+ testId?: string;
21
+ testIdAttr?: string;
22
+ inputType?: string;
23
+ frameHint?: string;
24
+ value?: string;
25
+ label?: string;
26
+ /** Files on a file input. The page can count them; it cannot name them. */
27
+ fileCount?: number;
28
+ }
29
+ /**
30
+ * Turn one wire event into a recording step.
31
+ *
32
+ * `resolved` overrides role/name when the caller could look the element up
33
+ * more reliably (live.ts does, when the page fell back to its heuristic).
34
+ * `value` overrides the typed value — live.ts passes an upload's stored path.
35
+ */
36
+ export declare function toRawEvent(wire: WireEvent, ts: number, opts?: {
37
+ resolved?: {
38
+ role?: string | null;
39
+ name?: string | null;
40
+ };
41
+ value?: string;
42
+ }): RawEvent;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * What the in-page recorder sends, and how it becomes a recording step.
3
+ *
4
+ * Shared by both recorders — the Playwright one (live.ts) and the Chrome
5
+ * extension (extension.ts) — so a flow recorded either way produces exactly
6
+ * the same steps. The in-page script itself is injected.ts.
7
+ */
8
+ import { redactValue } from '../../core/recording.js';
9
+ /**
10
+ * Turn one wire event into a recording step.
11
+ *
12
+ * `resolved` overrides role/name when the caller could look the element up
13
+ * more reliably (live.ts does, when the page fell back to its heuristic).
14
+ * `value` overrides the typed value — live.ts passes an upload's stored path.
15
+ */
16
+ export function toRawEvent(wire, ts, opts = {}) {
17
+ const inPage = wire.resolvedBy === 'accname';
18
+ const role = inPage ? wire.hintRole : (opts.resolved?.role || wire.hintRole);
19
+ const name = inPage ? wire.hintName : (opts.resolved?.name || wire.hintName);
20
+ const resolution = inPage || opts.resolved ? 'accname' : 'unresolved';
21
+ // The value-reference name comes from the field's name alone; detection
22
+ // looks at every hint (joining all three once produced
23
+ // `SECRET.password_password_password`).
24
+ const fieldHint = name || wire.testId || wire.css || 'field';
25
+ const secretSignal = [name, wire.css, wire.testId].filter(Boolean).join(' ');
26
+ // A key press's value is a key name ('Enter'), never a credential, and an
27
+ // upload's value is a path. Only typed input can be a secret.
28
+ const valued = opts.value !== undefined
29
+ ? { value: opts.value }
30
+ : wire.value !== undefined
31
+ ? wire.action === 'press'
32
+ ? { value: wire.value }
33
+ : redactValue(fieldHint, wire.value, wire.inputType, secretSignal)
34
+ : {};
35
+ return {
36
+ seq: 0,
37
+ ts,
38
+ action: wire.action,
39
+ ...(role ? { role } : {}),
40
+ ...(name ? { name } : {}),
41
+ ...valued,
42
+ ...(wire.css ? { css: wire.css } : {}),
43
+ ...(wire.testId ? { testId: wire.testId } : {}),
44
+ ...(wire.testIdAttr ? { testIdAttr: wire.testIdAttr } : {}),
45
+ ...(wire.frameHint ? { frameHint: wire.frameHint } : {}),
46
+ // Kept so an app can later choose to treat email fields as placeholders.
47
+ ...(wire.inputType === 'email' ? { hints: { inputType: 'email' } } : {}),
48
+ url: wire.url,
49
+ resolution,
50
+ };
51
+ }