rrweb-browser-test 2.2.0 → 2.3.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.
package/dist/index.js CHANGED
@@ -18,42 +18,156 @@ var MOBILE_FRAMEWORKS = [
18
18
 
19
19
  // src/utils.ts
20
20
  var indent = (level) => " ".repeat(level);
21
- var cssSelector = (node) => {
22
- if (!node?.tagName) return void 0;
23
- const attrs = node.attributes ?? {};
24
- if (attrs.id) return `#${attrs.id}`;
25
- const text = (node.childNodes ?? []).map((n) => n?.textContent).filter(Boolean).join(" ").trim();
26
- if (node.tagName === "a" && text) return `a:has-text("${text}")`;
27
- const cls = attrs.class?.trim();
28
- if (cls) {
29
- const chain = cls.split(/\s+/).filter(Boolean).map((c) => /^[A-Za-z_-][\w-]*$/.test(c) ? c : `[class~="${c}"]`).map((c) => c.startsWith("[") ? c : `.${c}`).join("");
30
- return `${node.tagName}${chain}`;
21
+ var q = (value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").split(String.fromCharCode(8232)).join("\\u2028").split(String.fromCharCode(8233)).join("\\u2029")}'`;
22
+ var escapeDoubleQuoted = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
23
+ var kotlinString = (value) => `"${escapeDoubleQuoted(value).replace(/\$/g, "\\$")}"`;
24
+ var swiftString = (value) => `"${escapeDoubleQuoted(value)}"`;
25
+ var doubleQuoted = (value) => `"${escapeDoubleQuoted(value)}"`;
26
+ var SCRIPT_VALUE_TYPES = /* @__PURE__ */ new Set([
27
+ "range",
28
+ "color",
29
+ "date",
30
+ "time",
31
+ "datetime-local",
32
+ "month",
33
+ "week"
34
+ ]);
35
+ var isScriptValueInput = (t) => !!t.inputType && SCRIPT_VALUE_TYPES.has(t.inputType);
36
+ var MASKED_VALUE_TODO = "// TODO: this value was masked in the recording \u2014 replace with test data";
37
+ var MASKED_PLACEHOLDER = "TODO_MASKED_VALUE";
38
+
39
+ // src/mobile/shared.ts
40
+ import {
41
+ EventType as EventType2,
42
+ IncrementalSource as IncrementalSource2,
43
+ MouseInteractions
44
+ } from "@rrweb/types";
45
+
46
+ // src/mirror.ts
47
+ import {
48
+ EventType,
49
+ IncrementalSource
50
+ } from "@rrweb/types";
51
+ var NodeKind = {
52
+ Document: 0,
53
+ DocumentType: 1,
54
+ Element: 2,
55
+ Text: 3,
56
+ CDATA: 4,
57
+ Comment: 5
58
+ };
59
+ var DomMirror = class {
60
+ nodes = /* @__PURE__ */ new Map();
61
+ get(id) {
62
+ return this.nodes.get(id);
31
63
  }
32
- return node.tagName;
33
- };
34
- var buildNodeMapFromFullSnapshots = (fullSnapshots) => {
35
- const idMap = /* @__PURE__ */ new Map();
36
- fullSnapshots.forEach((snapshot) => {
37
- const rootNode = snapshot.data.node;
38
- function processNode(node) {
39
- idMap.set(node.id, node);
40
- if (node.childNodes) {
41
- node.childNodes.forEach((childNode) => {
42
- processNode(childNode);
43
- });
64
+ parent(node) {
65
+ return node.parentId === void 0 ? void 0 : this.nodes.get(node.parentId);
66
+ }
67
+ children(node) {
68
+ return node.children.map((id) => this.nodes.get(id)).filter((n) => n !== void 0);
69
+ }
70
+ elements() {
71
+ return this.nodes.values();
72
+ }
73
+ /** Apply a single event. Only FullSnapshot and Mutation change the DOM. */
74
+ apply(event) {
75
+ if (event.type === EventType.FullSnapshot) {
76
+ this.nodes.clear();
77
+ this.register(event.data.node, void 0);
78
+ return;
79
+ }
80
+ if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {
81
+ this.mutate(event.data);
82
+ }
83
+ }
84
+ register(raw, parentId) {
85
+ const node = {
86
+ id: raw.id,
87
+ type: raw.type,
88
+ tagName: raw.tagName?.toLowerCase(),
89
+ attributes: { ...raw.attributes ?? {} },
90
+ textContent: raw.textContent,
91
+ isSVG: raw.isSVG,
92
+ parentId,
93
+ children: (raw.childNodes ?? []).map((c) => c.id)
94
+ };
95
+ this.nodes.set(node.id, node);
96
+ (raw.childNodes ?? []).forEach((c) => this.register(c, raw.id));
97
+ }
98
+ removeSubtree(id) {
99
+ const node = this.nodes.get(id);
100
+ if (!node) return;
101
+ node.children.forEach((c) => this.removeSubtree(c));
102
+ this.nodes.delete(id);
103
+ }
104
+ detach(node) {
105
+ const parent = this.parent(node);
106
+ if (parent) parent.children = parent.children.filter((c) => c !== node.id);
107
+ }
108
+ // Same order the rrweb replayer uses: removes, adds, texts, attributes.
109
+ mutate(m) {
110
+ m.removes?.forEach(({ id }) => {
111
+ const node = this.nodes.get(id);
112
+ if (!node) return;
113
+ this.detach(node);
114
+ this.removeSubtree(id);
115
+ });
116
+ m.adds?.forEach((add) => {
117
+ const existing = this.nodes.get(add.node.id);
118
+ if (existing) this.detach(existing);
119
+ this.register(add.node, add.parentId);
120
+ });
121
+ m.adds?.forEach((add) => {
122
+ const parent = this.nodes.get(add.parentId);
123
+ if (!parent || parent.children.includes(add.node.id)) return;
124
+ const at = add.nextId === null || add.nextId === void 0 ? -1 : parent.children.indexOf(add.nextId);
125
+ if (at >= 0) parent.children.splice(at, 0, add.node.id);
126
+ else parent.children.push(add.node.id);
127
+ });
128
+ m.texts?.forEach(({ id, value }) => {
129
+ const node = this.nodes.get(id);
130
+ if (node) node.textContent = value ?? "";
131
+ });
132
+ m.attributes?.forEach(({ id, attributes }) => {
133
+ const node = this.nodes.get(id);
134
+ if (!node) return;
135
+ Object.entries(attributes).forEach(([key, value]) => {
136
+ if (value === null) delete node.attributes[key];
137
+ else if (typeof value !== "object") node.attributes[key] = value;
138
+ });
139
+ });
140
+ }
141
+ };
142
+ var normalizeEvents = (events) => {
143
+ const out = [];
144
+ events.forEach((raw) => {
145
+ let e = raw;
146
+ if (typeof e === "string") {
147
+ try {
148
+ e = JSON.parse(e);
149
+ } catch {
150
+ return;
44
151
  }
45
152
  }
46
- processNode(rootNode);
153
+ if (!e || typeof e !== "object") return;
154
+ let data = e.data;
155
+ if (typeof data === "string") {
156
+ try {
157
+ data = JSON.parse(data);
158
+ } catch {
159
+ return;
160
+ }
161
+ }
162
+ const type = Number(e.type);
163
+ const timestamp = Number(e.timestamp);
164
+ if (!Number.isFinite(type) || data === void 0) return;
165
+ out.push({ ...e, type, timestamp, data });
47
166
  });
48
- return idMap;
167
+ return out.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
49
168
  };
50
169
 
51
170
  // src/mobile/shared.ts
52
- import {
53
- EventType,
54
- IncrementalSource,
55
- MouseInteractions
56
- } from "@rrweb/types";
57
171
  var resourceIdLeaf = (value) => {
58
172
  const slash = value.lastIndexOf("/");
59
173
  return slash >= 0 ? value.slice(slash + 1) : value;
@@ -78,43 +192,50 @@ var swipeDirection = (d) => {
78
192
  };
79
193
  var extractMobileActions = (events) => {
80
194
  const actions = [];
81
- const fullSnapshots = events.filter(
82
- (event) => event.type === EventType.FullSnapshot
83
- );
84
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshots);
85
- events.forEach((event) => {
86
- const e = event;
87
- if (e.type === EventType.Meta) {
195
+ const mirror = new DomMirror();
196
+ const nodeAt = (id) => {
197
+ const node = mirror.get(id);
198
+ if (!node) return void 0;
199
+ return {
200
+ id: node.id,
201
+ tagName: node.tagName,
202
+ attributes: node.attributes,
203
+ childNodes: mirror.children(node).map((c) => ({ id: c.id, textContent: c.textContent }))
204
+ };
205
+ };
206
+ normalizeEvents(events).forEach((e) => {
207
+ mirror.apply(e);
208
+ if (e.type === EventType2.Meta) {
88
209
  if (e.data?.href)
89
210
  actions.push({ kind: "launch", url: e.data.href });
90
211
  return;
91
212
  }
92
- if (e.type !== EventType.IncrementalSnapshot) return;
213
+ if (e.type !== EventType2.IncrementalSnapshot) return;
93
214
  const data = e.data;
94
215
  switch (data.source) {
95
- case IncrementalSource.MouseInteraction: {
216
+ case IncrementalSource2.MouseInteraction: {
96
217
  const d = data;
97
218
  if (d.type === MouseInteractions.Click || d.type === MouseInteractions.TouchEnd) {
98
219
  actions.push({
99
220
  kind: "tap",
100
- locator: mobileLocator(nodeMap.get(d.id))
221
+ locator: mobileLocator(nodeAt(d.id))
101
222
  });
102
223
  }
103
224
  break;
104
225
  }
105
- case IncrementalSource.Input: {
226
+ case IncrementalSource2.Input: {
106
227
  const d = data;
107
228
  if (typeof d.text === "string") {
108
229
  actions.push({
109
230
  kind: "input",
110
- locator: mobileLocator(nodeMap.get(d.id)),
231
+ locator: mobileLocator(nodeAt(d.id)),
111
232
  text: d.text
112
233
  });
113
234
  }
114
235
  break;
115
236
  }
116
- case IncrementalSource.Scroll:
117
- case IncrementalSource.TouchMove: {
237
+ case IncrementalSource2.Scroll:
238
+ case IncrementalSource2.TouchMove: {
118
239
  actions.push({
119
240
  kind: "swipe",
120
241
  direction: swipeDirection(data)
@@ -129,16 +250,15 @@ var extractMobileActions = (events) => {
129
250
  };
130
251
 
131
252
  // src/appium/index.ts
132
- var esc = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
133
253
  var selector = (loc) => {
134
254
  if (!loc) return `$('~TODO_add_accessibility_id')`;
135
255
  switch (loc.strategy) {
136
256
  case "id":
137
- return `$('android=new UiSelector().resourceId("${esc(loc.value)}")')`;
257
+ return `$(${q(`android=new UiSelector().resourceId(${doubleQuoted(loc.value)})`)})`;
138
258
  case "accessibility":
139
- return `$('~${esc(loc.value)}')`;
259
+ return `$(${q(`~${loc.value}`)})`;
140
260
  case "text":
141
- return `$('android=new UiSelector().text("${esc(loc.value)}")')`;
261
+ return `$(${q(`android=new UiSelector().text(${doubleQuoted(loc.value)})`)})`;
142
262
  }
143
263
  };
144
264
  var generateAppiumTests = (events) => {
@@ -161,7 +281,7 @@ var generateAppiumTests = (events) => {
161
281
  `;
162
282
  break;
163
283
  case "input":
164
- code += `${indent(4)}await ${selector(a.locator)}.setValue('${esc(a.text)}');
284
+ code += `${indent(4)}await ${selector(a.locator)}.setValue(${q(a.text)});
165
285
  `;
166
286
  break;
167
287
  case "swipe":
@@ -177,103 +297,488 @@ var generateAppiumTests = (events) => {
177
297
  return code;
178
298
  };
179
299
 
180
- // src/cypress/index.ts
300
+ // src/web/actions.ts
181
301
  import {
182
- EventType as EventType2,
183
- IncrementalSource as IncrementalSource2,
302
+ EventType as EventType3,
303
+ IncrementalSource as IncrementalSource3,
304
+ MediaInteractions,
184
305
  MouseInteractions as MouseInteractions2
185
306
  } from "@rrweb/types";
307
+
308
+ // src/selector.ts
309
+ var TEST_ATTRS = [
310
+ "data-testid",
311
+ "data-test-id",
312
+ "data-test",
313
+ "data-cy",
314
+ "data-qa"
315
+ ];
316
+ var LABEL_ATTRS = ["name", "placeholder", "aria-label", "title", "alt"];
317
+ var INTERACTIVE_TAGS = /* @__PURE__ */ new Set([
318
+ "a",
319
+ "button",
320
+ "input",
321
+ "select",
322
+ "textarea",
323
+ "label",
324
+ "summary",
325
+ "option"
326
+ ]);
327
+ var INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
328
+ "button",
329
+ "link",
330
+ "checkbox",
331
+ "radio",
332
+ "switch",
333
+ "tab",
334
+ "menuitem",
335
+ "menuitemcheckbox",
336
+ "menuitemradio",
337
+ "option",
338
+ "combobox",
339
+ "treeitem"
340
+ ]);
341
+ var SKIPPED_TEXT_TAGS = /* @__PURE__ */ new Set(["script", "style", "noscript", "template"]);
342
+ var MAX_TEXT = 60;
343
+ var MAX_CLIMB = 6;
344
+ var str = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
345
+ var isGeneratedId = (id) => /^:r[0-9a-z]*:?$|^«r|^rc[-_]|^mui-\d|^ember\d|^headlessui-|^radix-|[0-9a-f]{8}-[0-9a-f]{4}|\d{5,}/i.test(
346
+ id
347
+ );
348
+ var isUnstableClass = (c) => /^css-[0-9a-z]+$|^sc-|^jsx-\d|^_[0-9a-z]{5,}$|^[a-z]+_[0-9a-z]{5,}$/i.test(
349
+ c
350
+ ) || /(^|[-_])(active|selected|focus|focused|hover|hovered|open|opened|disabled|checked|visible|hidden|has-value|loading|expanded|collapsed)$/i.test(
351
+ c
352
+ ) || /^(is|has)-/.test(c) || /--after-open$|--before-close$/.test(c);
353
+ var stableClasses = (node) => (str(node.attributes.class) ?? "").split(/\s+/).filter((c) => c && !isUnstableClass(c)).slice(0, 3);
354
+ var cssString = (v) => v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
355
+ var isIdent = (v) => /^-?[A-Za-z_][\w-]*$/.test(v);
356
+ var renderStep = (s) => {
357
+ let out = s.tag;
358
+ s.attrs.forEach(([k, v]) => {
359
+ out += k === "id" && isIdent(v) ? `#${v}` : `[${k}="${cssString(v)}"]`;
360
+ });
361
+ s.classes.forEach((c) => {
362
+ out += isIdent(c) ? `.${c}` : `[class~="${cssString(c)}"]`;
363
+ });
364
+ if (s.nth !== void 0) out += `:nth-of-type(${s.nth})`;
365
+ return out;
366
+ };
367
+ var renderSelector = (steps) => steps.map((s, i) => (i > 0 && s.child ? "> " : "") + renderStep(s)).join(" ");
368
+ var rawText = (mirror, node) => {
369
+ if (node.type === NodeKind.Text) return node.textContent ?? "";
370
+ if (node.tagName && SKIPPED_TEXT_TAGS.has(node.tagName)) return "";
371
+ return mirror.children(node).map((c) => rawText(mirror, c)).join("");
372
+ };
373
+ var elementText = (mirror, node) => rawText(mirror, node).replace(/\s+/g, " ").trim();
374
+ var nthOfType = (mirror, node) => {
375
+ const parent = mirror.parent(node);
376
+ if (!parent) return 1;
377
+ const same = mirror.children(parent).filter((c) => c.type === NodeKind.Element && c.tagName === node.tagName);
378
+ return same.findIndex((c) => c.id === node.id) + 1;
379
+ };
380
+ var matchesStep = (mirror, node, s) => {
381
+ if (node.type !== NodeKind.Element || node.tagName !== s.tag) return false;
382
+ for (const [k, v] of s.attrs) if (str(node.attributes[k]) !== v) return false;
383
+ if (s.classes.length) {
384
+ const own = new Set((str(node.attributes.class) ?? "").split(/\s+/));
385
+ if (!s.classes.every((c) => own.has(c))) return false;
386
+ }
387
+ if (s.nth !== void 0 && nthOfType(mirror, node) !== s.nth) return false;
388
+ return true;
389
+ };
390
+ var matchesChain = (mirror, node, steps, i) => {
391
+ const step = steps[i];
392
+ if (!step || !matchesStep(mirror, node, step)) return false;
393
+ if (i === 0) return true;
394
+ let anc = mirror.parent(node);
395
+ if (step.child) return !!anc && matchesChain(mirror, anc, steps, i - 1);
396
+ while (anc) {
397
+ if (matchesChain(mirror, anc, steps, i - 1)) return true;
398
+ anc = mirror.parent(anc);
399
+ }
400
+ return false;
401
+ };
402
+ var countMatches = (mirror, steps, text) => {
403
+ let n = 0;
404
+ for (const node of mirror.elements()) {
405
+ if (!matchesChain(mirror, node, steps, steps.length - 1)) continue;
406
+ if (text !== void 0 && !elementText(mirror, node).includes(text))
407
+ continue;
408
+ if (++n > 1) return n;
409
+ }
410
+ return n;
411
+ };
412
+ var attributeSteps = (node) => {
413
+ const tag = node.tagName;
414
+ const a = node.attributes;
415
+ const steps = [];
416
+ const add = (k, v) => {
417
+ if (v && v.length <= 120) steps.push({ tag, attrs: [[k, v]], classes: [] });
418
+ };
419
+ TEST_ATTRS.forEach((k) => add(k, str(a[k])));
420
+ const id = str(a.id);
421
+ if (id && !isGeneratedId(id)) add("id", id);
422
+ LABEL_ATTRS.forEach((k) => add(k, str(a[k])));
423
+ if (tag === "a") {
424
+ const href = str(a.href);
425
+ if (href && !href.startsWith("javascript:")) add("href", href);
426
+ }
427
+ if (tag === "label") add("for", str(a.for));
428
+ const role = str(a.role);
429
+ const label = str(a["aria-label"]);
430
+ if (role && label)
431
+ steps.push({
432
+ tag,
433
+ attrs: [
434
+ ["role", role],
435
+ ["aria-label", label]
436
+ ],
437
+ classes: []
438
+ });
439
+ const type = str(a.type);
440
+ if (tag === "input" && type)
441
+ steps.slice().forEach(
442
+ (s) => steps.push({ ...s, attrs: [...s.attrs, ["type", type]] })
443
+ );
444
+ return steps;
445
+ };
446
+ var structuralStep = (node) => {
447
+ const classes = stableClasses(node);
448
+ const role = str(node.attributes.role);
449
+ const type = str(node.attributes.type);
450
+ const attrs = [];
451
+ if (role) attrs.push(["role", role]);
452
+ if (node.tagName === "input" && type) attrs.push(["type", type]);
453
+ return { tag: node.tagName, attrs, classes };
454
+ };
455
+ var bestStep = (node) => attributeSteps(node)[0] ?? structuralStep(node);
456
+ var isElement = (n) => !!n && n.type === NodeKind.Element && !!n.tagName;
457
+ var isSvgPart = (n) => !!n.isSVG || n.tagName === "svg";
458
+ var isInteractive = (n) => INTERACTIVE_TAGS.has(n.tagName) || INTERACTIVE_ROLES.has(str(n.attributes.role) ?? "") || TEST_ATTRS.some((k) => n.attributes[k] !== void 0);
459
+ var clickableAncestor = (mirror, node) => {
460
+ let cur = node;
461
+ while (cur && !isElement(cur)) cur = mirror.parent(cur);
462
+ while (cur && isSvgPart(cur) && isElement(mirror.parent(cur)))
463
+ cur = mirror.parent(cur);
464
+ if (!cur) return void 0;
465
+ let probe = cur;
466
+ for (let i = 0; probe && isElement(probe) && i <= MAX_CLIMB; i++) {
467
+ if (isInteractive(probe)) return probe;
468
+ if (probe.tagName === "body") break;
469
+ probe = mirror.parent(probe);
470
+ }
471
+ return cur;
472
+ };
473
+ var buildTarget = (mirror, node) => {
474
+ if (!isElement(node)) return void 0;
475
+ const base = {
476
+ tagName: node.tagName,
477
+ inputType: str(node.attributes.type)?.toLowerCase()
478
+ };
479
+ for (const s of attributeSteps(node))
480
+ if (countMatches(mirror, [s]) === 1)
481
+ return { ...base, css: renderSelector([s]) };
482
+ const own = bestStep(node);
483
+ if (countMatches(mirror, [own]) === 1)
484
+ return { ...base, css: renderSelector([own]) };
485
+ const text = elementText(mirror, node);
486
+ let withText;
487
+ if (text && text.length <= MAX_TEXT) {
488
+ const parent = mirror.parent(node);
489
+ const candidates = [[own]];
490
+ if (isElement(parent) && parent.tagName !== "body")
491
+ candidates.push([bestStep(parent), { ...own, child: true }]);
492
+ const unique = candidates.find((c) => countMatches(mirror, c, text) === 1);
493
+ if (unique) withText = { css: renderSelector(unique), text };
494
+ }
495
+ let anc = mirror.parent(node);
496
+ for (let i = 0; isElement(anc) && i < MAX_CLIMB; i++) {
497
+ if (anc.tagName === "body" || anc.tagName === "html") break;
498
+ for (const s of attributeSteps(anc)) {
499
+ if (countMatches(mirror, [s]) !== 1) continue;
500
+ const steps = [s, own];
501
+ if (countMatches(mirror, steps) === 1)
502
+ return { ...base, css: renderSelector(steps), withText };
503
+ }
504
+ anc = mirror.parent(anc);
505
+ }
506
+ const path = [];
507
+ let cur = node;
508
+ while (isElement(cur) && cur.tagName !== "html") {
509
+ const step = {
510
+ ...path.length === 0 ? own : bestStep(cur),
511
+ child: true
512
+ };
513
+ path.unshift(step);
514
+ if (countMatches(mirror, path) === 1) break;
515
+ step.nth = nthOfType(mirror, cur);
516
+ if (countMatches(mirror, path) === 1) break;
517
+ cur = mirror.parent(cur);
518
+ }
519
+ if (path[0]) path[0].child = false;
520
+ else path.push(own);
521
+ return { ...base, css: renderSelector(path), withText };
522
+ };
523
+ var isDocumentScroller = (node) => !node || node.type === NodeKind.Document || node.tagName === "html" || node.tagName === "body";
524
+
525
+ // src/web/actions.ts
526
+ var isMasked = (v) => v.length > 0 && /^\*+$/.test(v);
527
+ var num = (v) => typeof v === "number" && Number.isFinite(v);
528
+ var extractWebActions = (events) => {
529
+ const mirror = new DomMirror();
530
+ const actions = [];
531
+ const keys = [];
532
+ let generation = 0;
533
+ let href;
534
+ let viewport;
535
+ let touched = /* @__PURE__ */ new Set();
536
+ let touchedHtmlIds = /* @__PURE__ */ new Set();
537
+ const keyOf = (node) => `${generation}:${node.id}`;
538
+ const lastMeaningful = () => {
539
+ let i = actions.length - 1;
540
+ while (i >= 0 && actions[i].kind === "mousemove") i--;
541
+ return i;
542
+ };
543
+ const dropIfLast = (key) => {
544
+ const i = lastMeaningful();
545
+ if (i < 0 || keys[i] !== key) return false;
546
+ actions.splice(i, 1);
547
+ keys.splice(i, 1);
548
+ return true;
549
+ };
550
+ const push = (action, key, collapse = false) => {
551
+ if (collapse && key !== void 0) dropIfLast(key);
552
+ actions.push(action);
553
+ keys.push(key);
554
+ };
555
+ const markTouched = (node) => {
556
+ if (!node) return;
557
+ touched.add(node.id);
558
+ const forId = node.tagName === "label" ? node.attributes.for : void 0;
559
+ if (typeof forId === "string") touchedHtmlIds.add(forId);
560
+ };
561
+ const isUserInput = (d, node) => {
562
+ if (d.userTriggered !== void 0) return d.userTriggered;
563
+ if (touched.has(node.id)) return true;
564
+ const htmlId = node.attributes.id;
565
+ if (typeof htmlId === "string" && touchedHtmlIds.has(htmlId)) return true;
566
+ let anc = mirror.parent(node);
567
+ for (let i = 0; anc && i < 4; i++, anc = mirror.parent(anc))
568
+ if (anc.tagName === "label" && touched.has(anc.id)) return true;
569
+ return false;
570
+ };
571
+ const setViewport = (width, height) => {
572
+ if (!num(width) || !num(height) || width <= 0 || height <= 0) return;
573
+ const v = `${width}x${height}`;
574
+ if (v === viewport) return;
575
+ viewport = v;
576
+ push({ kind: "viewport", width, height });
577
+ };
578
+ normalizeEvents(events).forEach((e) => {
579
+ switch (e.type) {
580
+ case EventType3.Meta: {
581
+ if (e.data.href && e.data.href !== href) {
582
+ href = e.data.href;
583
+ push({ kind: "navigate", href });
584
+ }
585
+ setViewport(e.data.width, e.data.height);
586
+ return;
587
+ }
588
+ case EventType3.FullSnapshot:
589
+ generation++;
590
+ touched = /* @__PURE__ */ new Set();
591
+ touchedHtmlIds = /* @__PURE__ */ new Set();
592
+ mirror.apply(e);
593
+ return;
594
+ case EventType3.IncrementalSnapshot:
595
+ break;
596
+ default:
597
+ return;
598
+ }
599
+ const data = e.data;
600
+ switch (data.source) {
601
+ case IncrementalSource3.Mutation:
602
+ mirror.apply(e);
603
+ break;
604
+ case IncrementalSource3.MouseMove:
605
+ case IncrementalSource3.TouchMove: {
606
+ const p = data.positions?.[0];
607
+ if (p && num(p.x) && num(p.y))
608
+ push({ kind: "mousemove", x: p.x, y: p.y });
609
+ break;
610
+ }
611
+ case IncrementalSource3.MouseInteraction: {
612
+ const d = data;
613
+ const raw = mirror.get(d.id);
614
+ if (d.type === MouseInteractions2.Focus || d.type === MouseInteractions2.MouseDown || d.type === MouseInteractions2.TouchStart) {
615
+ markTouched(raw);
616
+ break;
617
+ }
618
+ if (d.type !== MouseInteractions2.Click && d.type !== MouseInteractions2.DblClick)
619
+ break;
620
+ const node = clickableAncestor(mirror, raw);
621
+ markTouched(raw);
622
+ markTouched(node);
623
+ const target = buildTarget(mirror, node);
624
+ if (!node || !target) break;
625
+ const key = `click:${keyOf(node)}`;
626
+ if (d.type === MouseInteractions2.DblClick) {
627
+ if (dropIfLast(key)) dropIfLast(key);
628
+ push({ kind: "dblclick", target }, key);
629
+ } else {
630
+ push({ kind: "click", target }, key);
631
+ }
632
+ break;
633
+ }
634
+ case IncrementalSource3.Input: {
635
+ const d = data;
636
+ const node = mirror.get(d.id);
637
+ if (!node || node.type !== NodeKind.Element) break;
638
+ if (!isUserInput(d, node)) break;
639
+ const target = buildTarget(mirror, node);
640
+ if (!target) break;
641
+ const key = `input:${keyOf(node)}`;
642
+ const text = typeof d.text === "string" ? d.text : "";
643
+ if (target.inputType === "checkbox" || target.inputType === "radio") {
644
+ if (target.inputType === "radio" && !d.isChecked) break;
645
+ push({ kind: "check", target, checked: !!d.isChecked }, key, true);
646
+ } else if (target.tagName === "select") {
647
+ push(
648
+ { kind: "select", target, value: text, masked: isMasked(text) },
649
+ key,
650
+ true
651
+ );
652
+ } else {
653
+ push(
654
+ { kind: "fill", target, value: text, masked: isMasked(text) },
655
+ key,
656
+ true
657
+ );
658
+ }
659
+ break;
660
+ }
661
+ case IncrementalSource3.Scroll: {
662
+ const d = data;
663
+ if (!num(d.x) || !num(d.y)) break;
664
+ const node = mirror.get(d.id);
665
+ if (isDocumentScroller(node)) {
666
+ push(
667
+ { kind: "scroll", x: d.x, y: d.y },
668
+ `scroll:${generation}:doc`,
669
+ true
670
+ );
671
+ break;
672
+ }
673
+ if (node?.tagName === "input") break;
674
+ const target = buildTarget(mirror, node);
675
+ if (target)
676
+ push(
677
+ { kind: "scroll", target, x: d.x, y: d.y },
678
+ `scroll:${keyOf(node)}`,
679
+ true
680
+ );
681
+ break;
682
+ }
683
+ case IncrementalSource3.ViewportResize: {
684
+ const d = data;
685
+ setViewport(d.width, d.height);
686
+ break;
687
+ }
688
+ case IncrementalSource3.MediaInteraction: {
689
+ const d = data;
690
+ const target = buildTarget(mirror, mirror.get(d.id));
691
+ if (!target) break;
692
+ if (d.type === MediaInteractions.Play)
693
+ push({ kind: "media", target, action: "play" });
694
+ else if (d.type === MediaInteractions.Pause)
695
+ push({ kind: "media", target, action: "pause" });
696
+ else if (d.type === MediaInteractions.Seeked && num(d.currentTime))
697
+ push({ kind: "seek", target, currentTime: d.currentTime });
698
+ break;
699
+ }
700
+ default:
701
+ break;
702
+ }
703
+ });
704
+ return actions;
705
+ };
706
+
707
+ // src/cypress/index.ts
708
+ var get = (t) => t.withText ? `cy.contains(${q(t.withText.css)}, ${q(t.withText.text)})` : `cy.get(${q(t.css)})`;
709
+ var typeText = (v) => v.replace(/\{/g, "{{}");
186
710
  var generateCypressTests = (events) => {
711
+ const i = indent(4);
187
712
  let code = "";
188
713
  code += `describe('TODO: name the test block', () => {
189
714
  `;
190
715
  code += ` it('TODO: name the test case', () => {
191
716
  `;
192
- const fullSnapshotEvents = events.filter(
193
- (event) => event.type === EventType2.FullSnapshot
194
- );
195
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
196
- events.forEach((event) => {
197
- const e = event;
198
- switch (e.type) {
199
- case EventType2.Meta:
200
- if (e.data.href) {
201
- code += `${indent(3)}cy.visit('${e.data.href}');
717
+ extractWebActions(events).forEach((a) => {
718
+ switch (a.kind) {
719
+ case "navigate":
720
+ code += `${i}cy.visit(${q(a.href)});
202
721
  `;
203
- code += `${indent(3)}cy.url().should('include', '${e.data.href}');
722
+ code += `${i}cy.url().should('include', ${q(a.href)});
204
723
  `;
205
- }
206
- if (e.data.width && e.data.height) {
207
- code += `${indent(3)}cy.viewport(${e.data.width}, ${e.data.height});
724
+ break;
725
+ case "viewport":
726
+ code += `${i}cy.viewport(${a.width}, ${a.height});
727
+ `;
728
+ break;
729
+ case "mousemove":
730
+ code += `${i}cy.get('body').trigger('mousemove', { clientX: ${a.x}, clientY: ${a.y} });
731
+ `;
732
+ break;
733
+ case "click":
734
+ code += `${i}${get(a.target)}.click();
735
+ `;
736
+ break;
737
+ case "dblclick":
738
+ code += `${i}${get(a.target)}.dblclick();
208
739
  `;
209
- }
210
740
  break;
211
- case EventType2.IncrementalSnapshot:
212
- const data = e.data;
213
- const type = data.source;
214
- let d;
215
- switch (type) {
216
- case IncrementalSource2.MouseMove:
217
- case IncrementalSource2.TouchMove:
218
- d = data;
219
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
220
- code += `${indent(3)}cy.get('body').trigger('mousemove', { clientX: ${d.positions[0].x}, clientY: ${d.positions[0].y} });
221
- `;
222
- }
223
- break;
224
- case IncrementalSource2.MouseInteraction:
225
- d = data;
226
- if (d.type === MouseInteractions2.Click) {
227
- const clickNode = nodeMap.get(d.id);
228
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
229
- (node) => node.childNodes?.map(
230
- (n1) => n1?.["textContent"]
231
- )
232
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? cssSelector(clickNode) : void 0;
233
- if (id) {
234
- if (clickNode?.tagName === "nav") {
235
- code += `${indent(3)}cy.contains('${clickNode?.tagName}', ${id}).click();
236
- `;
237
- } else {
238
- code += `${indent(3)}cy.get('${id}').click();
239
- `;
240
- }
241
- }
242
- }
243
- break;
244
- case IncrementalSource2.Scroll:
245
- d = data;
246
- if (d.x && d.y) {
247
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').scrollTo(${d.x}, ${d.y});
248
- `;
249
- }
250
- break;
251
- case IncrementalSource2.ViewportResize:
252
- d = data;
253
- if (d.width && d.height) {
254
- code += `${indent(3)}cy.viewport(${d.width}, ${d.height});
255
- `;
256
- }
257
- break;
258
- case IncrementalSource2.Input:
259
- d = data;
260
- if (d.text) {
261
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').type('${d.text}');
262
- `;
263
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').should('have.value', '${d.text}');
264
- `;
265
- }
266
- break;
267
- case IncrementalSource2.MediaInteraction:
268
- d = data;
269
- if (d.type) {
270
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').then((el) => el[0].${d.type}());
271
- `;
272
- }
273
- break;
741
+ case "fill": {
742
+ const value = a.masked ? MASKED_PLACEHOLDER : a.value;
743
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
744
+ `;
745
+ if (isScriptValueInput(a.target)) {
746
+ code += `${i}${get(a.target)}.invoke('val', ${q(value)}).trigger('input').trigger('change');
747
+ `;
748
+ } else if (value === "") {
749
+ code += `${i}${get(a.target)}.clear();
750
+ `;
751
+ } else {
752
+ code += `${i}${get(a.target)}.clear().type(${q(typeText(value))});
753
+ `;
274
754
  }
755
+ if (!a.masked)
756
+ code += `${i}${get(a.target)}.should('have.value', ${q(value)});
757
+ `;
275
758
  break;
276
- default:
759
+ }
760
+ case "check":
761
+ code += `${i}${get(a.target)}.${a.checked ? "check" : "uncheck"}({ force: true });
762
+ `;
763
+ break;
764
+ case "select":
765
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
766
+ `;
767
+ code += `${i}${get(a.target)}.select(${q(a.masked ? MASKED_PLACEHOLDER : a.value)});
768
+ `;
769
+ break;
770
+ case "scroll":
771
+ code += a.target ? `${i}${get(a.target)}.scrollTo(${a.x}, ${a.y});
772
+ ` : `${i}cy.scrollTo(${a.x}, ${a.y});
773
+ `;
774
+ break;
775
+ case "media":
776
+ code += `${i}${get(a.target)}.then(($el) => $el[0].${a.action}());
777
+ `;
778
+ break;
779
+ case "seek":
780
+ code += `${i}${get(a.target)}.then(($el) => { $el[0].currentTime = ${a.currentTime}; });
781
+ `;
277
782
  break;
278
783
  }
279
784
  });
@@ -285,16 +790,15 @@ var generateCypressTests = (events) => {
285
790
  };
286
791
 
287
792
  // src/detox/index.ts
288
- var esc2 = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
289
793
  var matcher = (loc) => {
290
794
  if (!loc) return `by.id('TODO_add_testID')`;
291
795
  switch (loc.strategy) {
292
796
  case "id":
293
- return `by.id('${esc2(loc.value)}')`;
797
+ return `by.id(${q(loc.value)})`;
294
798
  case "accessibility":
295
- return `by.label('${esc2(loc.value)}')`;
799
+ return `by.label(${q(loc.value)})`;
296
800
  case "text":
297
- return `by.text('${esc2(loc.value)}')`;
801
+ return `by.text(${q(loc.value)})`;
298
802
  }
299
803
  };
300
804
  var generateDetoxTests = (events) => {
@@ -317,7 +821,7 @@ var generateDetoxTests = (events) => {
317
821
  `;
318
822
  break;
319
823
  case "input":
320
- code += `${indent(4)}await element(${matcher(a.locator)}).typeText('${esc2(a.text)}');
824
+ code += `${indent(4)}await element(${matcher(a.locator)}).typeText(${q(a.text)});
321
825
  `;
322
826
  break;
323
827
  case "swipe":
@@ -334,16 +838,17 @@ var generateDetoxTests = (events) => {
334
838
  };
335
839
 
336
840
  // src/espresso/index.ts
337
- var esc3 = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
338
841
  var matcher2 = (loc) => {
339
842
  if (!loc) return `withContentDescription("TODO_add_content_description")`;
340
843
  switch (loc.strategy) {
341
- case "id":
342
- return `withId(R.id.${resourceIdLeaf(loc.value)})`;
844
+ case "id": {
845
+ const leaf = resourceIdLeaf(loc.value);
846
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(leaf) ? `withId(R.id.${leaf})` : `withResourceName(${kotlinString(leaf)})`;
847
+ }
343
848
  case "accessibility":
344
- return `withContentDescription("${esc3(loc.value)}")`;
849
+ return `withContentDescription(${kotlinString(loc.value)})`;
345
850
  case "text":
346
- return `withText("${esc3(loc.value)}")`;
851
+ return `withText(${kotlinString(loc.value)})`;
347
852
  }
348
853
  };
349
854
  var swipeFn = (direction) => ({
@@ -372,7 +877,7 @@ var generateEspressoTests = (events) => {
372
877
  `;
373
878
  break;
374
879
  case "input":
375
- code += `${indent(2)}onView(${matcher2(a.locator)}).perform(typeText("${esc3(a.text)}"), closeSoftKeyboard())
880
+ code += `${indent(2)}onView(${matcher2(a.locator)}).perform(typeText(${kotlinString(a.text)}), closeSoftKeyboard())
376
881
  `;
377
882
  break;
378
883
  case "swipe":
@@ -387,246 +892,184 @@ var generateEspressoTests = (events) => {
387
892
  };
388
893
 
389
894
  // src/playwright/index.ts
390
- import {
391
- EventType as EventType3,
392
- IncrementalSource as IncrementalSource3,
393
- MouseInteractions as MouseInteractions3
394
- } from "@rrweb/types";
895
+ var locator = (t) => t.withText ? `page.locator(${q(t.withText.css)}, { hasText: ${q(t.withText.text)} })` : `page.locator(${q(t.css)})`;
395
896
  var generatePlaywrightTests = (events) => {
897
+ const i = indent(2);
396
898
  let code = "";
397
899
  code += `import { test, expect } from '@playwright/test';
398
900
 
399
901
  `;
400
- code += `test('TODO: name the test block', async ({ page, context }) => {
902
+ code += `test('TODO: name the test block', async ({ page }) => {
401
903
  `;
402
- const fullSnapshotEvents = events.filter(
403
- (event) => event.type === EventType3.FullSnapshot
404
- );
405
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
406
- code += `${indent(2)}const newTab = await context.newPage();
904
+ extractWebActions(events).forEach((a) => {
905
+ switch (a.kind) {
906
+ case "navigate":
907
+ code += `${i}await page.goto(${q(a.href)});
407
908
  `;
408
- events.forEach((event) => {
409
- const e = event;
410
- switch (e.type) {
411
- case EventType3.Meta:
412
- if (e.data.href) {
413
- code += `${indent(2)}await page.goto('${e.data.href}');
909
+ code += `${i}await expect(page).toHaveURL(${q(a.href)});
910
+ `;
911
+ break;
912
+ case "viewport":
913
+ code += `${i}await page.setViewportSize({ width: ${a.width}, height: ${a.height} });
414
914
  `;
415
- code += `${indent(2)}await expect(page).toHaveURL('${e.data.href}');
915
+ code += `${i}await expect(page).toHaveViewportSize({ width: ${a.width}, height: ${a.height} });
416
916
  `;
417
- }
418
- if (e.data.width && e.data.height) {
419
- code += `${indent(2)}await page.setViewportSize({ width: ${e.data.width}, height: ${e.data.height} });
917
+ break;
918
+ case "mousemove":
919
+ code += `${i}await page.mouse.move(${a.x}, ${a.y});
420
920
  `;
421
- code += `${indent(2)}await expect(page).toHaveViewportSize({ width: ${e.data.width}, height: ${e.data.height} });
921
+ break;
922
+ case "click":
923
+ code += `${i}await ${locator(a.target)}.click();
422
924
  `;
423
- }
424
925
  break;
425
- case EventType3.IncrementalSnapshot:
426
- const data = e.data;
427
- const type = data.source;
428
- let d;
429
- switch (type) {
430
- case IncrementalSource3.MouseMove:
431
- case IncrementalSource3.TouchMove:
432
- d = data;
433
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
434
- code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});
435
- `;
436
- }
437
- break;
438
- case IncrementalSource3.MouseInteraction:
439
- d = data;
440
- if (d.type === MouseInteractions3.Click) {
441
- const clickNode = nodeMap.get(d.id);
442
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
443
- (node) => node.childNodes?.map(
444
- (n1) => n1?.["textContent"]
445
- )
446
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? cssSelector(clickNode) : void 0;
447
- if (id && d.x && d.y) {
448
- code += `${indent(2)}await page.locator(\`${id}\`).click();
449
- `;
450
- code += `${indent(2)}await expect(page.locator(\`${id}\`)).toBeVisible();
451
- `;
452
- }
453
- break;
454
- }
455
- break;
456
- case IncrementalSource3.Scroll:
457
- d = data;
458
- if (d.x && d.y) {
459
- code += `${indent(2)}await page.mouse.wheel(() => { document.querySelector('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').scrollTo(${d.x}, ${d.y}); });
460
- `;
461
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toBeVisible();
462
- `;
463
- }
464
- break;
465
- case IncrementalSource3.ViewportResize:
466
- d = data;
467
- if (d.width && d.height) {
468
- code += `${indent(2)}await page.setViewportSize({ width: ${d.width}, height: ${d.height} });
469
- `;
470
- code += `${indent(2)}await expect(page).toHaveViewportSize({ width: ${d.width}, height: ${d.height} });
471
- `;
472
- }
473
- break;
474
- case IncrementalSource3.Input:
475
- d = data;
476
- if (d.text) {
477
- code += `${indent(2)}await page.fill('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]', '${d.text}');
478
- `;
479
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toHaveValue('${d.text}');
480
- `;
481
- }
482
- break;
483
- case IncrementalSource3.MediaInteraction:
484
- d = data;
485
- if (d.type) {
486
- code += `${indent(2)}await page.$eval('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]', el => el.${d.type}());
487
- `;
488
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toBeVisible();
489
- `;
490
- }
491
- break;
926
+ case "dblclick":
927
+ code += `${i}await ${locator(a.target)}.dblclick();
928
+ `;
929
+ break;
930
+ case "fill":
931
+ if (a.masked) {
932
+ code += `${i}${MASKED_VALUE_TODO}
933
+ `;
934
+ code += `${i}await ${locator(a.target)}.fill(${q(MASKED_PLACEHOLDER)});
935
+ `;
936
+ } else {
937
+ code += `${i}await ${locator(a.target)}.fill(${q(a.value)});
938
+ `;
939
+ code += `${i}await expect(${locator(a.target)}).toHaveValue(${q(a.value)});
940
+ `;
492
941
  }
493
942
  break;
494
- default:
943
+ case "check":
944
+ code += `${i}await ${locator(a.target)}.setChecked(${a.checked}, { force: true });
945
+ `;
946
+ code += `${i}await expect(${locator(a.target)}).toBeChecked({ checked: ${a.checked} });
947
+ `;
948
+ break;
949
+ case "select":
950
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
951
+ `;
952
+ code += `${i}await ${locator(a.target)}.selectOption(${q(a.masked ? MASKED_PLACEHOLDER : a.value)});
953
+ `;
954
+ break;
955
+ case "scroll":
956
+ code += a.target ? `${i}await ${locator(a.target)}.evaluate((el) => el.scrollTo(${a.x}, ${a.y}));
957
+ ` : `${i}await page.evaluate(() => window.scrollTo(${a.x}, ${a.y}));
958
+ `;
959
+ break;
960
+ case "media":
961
+ code += `${i}await ${locator(a.target)}.evaluate('(el) => el.${a.action}()');
962
+ `;
963
+ break;
964
+ case "seek":
965
+ code += `${i}await ${locator(a.target)}.evaluate('(el) => { el.currentTime = ${a.currentTime}; }');
966
+ `;
495
967
  break;
496
968
  }
497
969
  });
498
- code += `${indent(1)}});
970
+ code += `});
499
971
  `;
500
972
  return code;
501
973
  };
502
974
 
503
975
  // src/puppeteer/index.ts
504
- import {
505
- EventType as EventType4,
506
- IncrementalSource as IncrementalSource4,
507
- MouseInteractions as MouseInteractions4
508
- } from "@rrweb/types";
509
976
  var generatePuppeteerTests = (events) => {
977
+ const i = indent(4);
510
978
  let code = "";
511
979
  code += `const puppeteer = require('puppeteer');
512
980
 
513
981
  `;
514
982
  code += `describe('TODO: name the test block', () => {
515
983
  `;
516
- code += `${indent(1)}let browser, page;
984
+ code += `${indent(2)}let browser, page;
517
985
 
518
986
  `;
519
- code += `${indent(1)}beforeAll(async () => {
987
+ code += `${indent(2)}beforeAll(async () => {
520
988
  `;
521
- code += `${indent(2)}browser = await puppeteer.launch();
989
+ code += `${i}browser = await puppeteer.launch();
522
990
  `;
523
- code += `${indent(2)}page = await browser.newPage();
991
+ code += `${i}page = await browser.newPage();
524
992
  `;
525
- code += `${indent(1)}});
993
+ code += `${indent(2)}});
526
994
 
527
995
  `;
528
- code += `${indent(1)}afterAll(async () => {
996
+ code += `${indent(2)}afterAll(async () => {
529
997
  `;
530
- code += `${indent(2)}await browser.close();
998
+ code += `${i}await browser.close();
531
999
  `;
532
- code += `${indent(1)}});
1000
+ code += `${indent(2)}});
533
1001
 
534
1002
  `;
535
- code += `${indent(1)}test('TODO: name the test case', async () => {
1003
+ code += `${indent(2)}test('TODO: name the test case', async () => {
536
1004
  `;
537
- const fullSnapshotEvents = events.filter(
538
- (event) => event.type === EventType4.FullSnapshot
539
- );
540
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
541
- events.forEach((event) => {
542
- const e = event;
543
- switch (e.type) {
544
- case EventType4.Meta:
545
- if (e.data.href) {
546
- code += `${indent(2)}await page.goto('${e.data.href}');
1005
+ extractWebActions(events).forEach((a) => {
1006
+ switch (a.kind) {
1007
+ case "navigate":
1008
+ code += `${i}await page.goto(${q(a.href)});
547
1009
  `;
548
- code += `${indent(2)}await expect(page.url()).toBe('${e.data.href}');
1010
+ code += `${i}expect(page.url()).toBe(${q(a.href)});
549
1011
  `;
550
- }
551
- if (e.data.width && e.data.height) {
552
- code += `${indent(2)}await page.setViewport({ width: ${e.data.width}, height: ${e.data.height} });
1012
+ break;
1013
+ case "viewport":
1014
+ code += `${i}await page.setViewport({ width: ${a.width}, height: ${a.height} });
1015
+ `;
1016
+ break;
1017
+ case "mousemove":
1018
+ code += `${i}await page.mouse.move(${a.x}, ${a.y});
553
1019
  `;
554
- }
555
1020
  break;
556
- case EventType4.IncrementalSnapshot:
557
- const data = e.data;
558
- const type = data.source;
559
- let d;
560
- switch (type) {
561
- case IncrementalSource4.MouseMove:
562
- case IncrementalSource4.TouchMove:
563
- d = data;
564
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
565
- code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});
566
- `;
567
- }
568
- break;
569
- case IncrementalSource4.MouseInteraction:
570
- d = data;
571
- if (d.type === MouseInteractions4.Click) {
572
- const clickNode = nodeMap.get(d.id);
573
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
574
- (node) => node.childNodes?.map(
575
- (n1) => n1?.["textContent"]
576
- )
577
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? cssSelector(clickNode) : void 0;
578
- if (id) {
579
- code += `${indent(2)}await page.click('${id}');
580
- `;
581
- }
582
- }
583
- break;
584
- case IncrementalSource4.Scroll:
585
- d = data;
586
- if (d.x && d.y) {
587
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
588
- code += `${indent(2)}await page.evaluate(() => {
589
- `;
590
- code += `${indent(3)}document.querySelector('#${elementId}').scrollTo(${d.x}, ${d.y});
591
- `;
592
- code += `${indent(2)}});
593
- `;
594
- }
595
- break;
596
- case IncrementalSource4.ViewportResize:
597
- d = data;
598
- if (d.width && d.height) {
599
- code += `${indent(2)}await page.setViewport({ width: ${d.width}, height: ${d.height} });
600
- `;
601
- }
602
- break;
603
- case IncrementalSource4.Input:
604
- d = data;
605
- if (d.text) {
606
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
607
- code += `${indent(2)}await page.type('#${elementId}', '${d.text}');
608
- `;
609
- }
610
- break;
611
- case IncrementalSource4.MediaInteraction:
612
- d = data;
613
- if (d.type) {
614
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
615
- code += `${indent(2)}await page.evaluate(() => {
616
- `;
617
- code += `${indent(3)}document.querySelector('#${elementId}').${d.type}();
618
- `;
619
- code += `${indent(2)}});
620
- `;
621
- }
622
- break;
1021
+ case "click":
1022
+ code += `${i}await page.click(${q(a.target.css)});
1023
+ `;
1024
+ break;
1025
+ case "dblclick":
1026
+ code += `${i}await page.click(${q(a.target.css)}, { clickCount: 2 });
1027
+ `;
1028
+ break;
1029
+ case "fill": {
1030
+ const sel = q(a.target.css);
1031
+ const value = a.masked ? MASKED_PLACEHOLDER : a.value;
1032
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
1033
+ `;
1034
+ if (isScriptValueInput(a.target)) {
1035
+ code += `${i}await page.$eval(${sel}, (el, v) => { el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); }, ${q(value)});
1036
+ `;
1037
+ } else {
1038
+ code += `${i}await page.click(${sel}, { clickCount: 3 });
1039
+ `;
1040
+ code += `${i}await page.keyboard.press('Backspace');
1041
+ `;
1042
+ if (value) code += `${i}await page.type(${sel}, ${q(value)});
1043
+ `;
623
1044
  }
624
1045
  break;
625
- default:
1046
+ }
1047
+ case "check":
1048
+ code += `${i}await page.$eval(${q(a.target.css)}, (el) => { if (el.checked !== ${a.checked}) el.click(); });
1049
+ `;
1050
+ break;
1051
+ case "select":
1052
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
1053
+ `;
1054
+ code += `${i}await page.select(${q(a.target.css)}, ${q(a.masked ? MASKED_PLACEHOLDER : a.value)});
1055
+ `;
1056
+ break;
1057
+ case "scroll":
1058
+ code += a.target ? `${i}await page.$eval(${q(a.target.css)}, (el) => el.scrollTo(${a.x}, ${a.y}));
1059
+ ` : `${i}await page.evaluate(() => window.scrollTo(${a.x}, ${a.y}));
1060
+ `;
1061
+ break;
1062
+ case "media":
1063
+ code += `${i}await page.$eval(${q(a.target.css)}, (el) => el.${a.action}());
1064
+ `;
1065
+ break;
1066
+ case "seek":
1067
+ code += `${i}await page.$eval(${q(a.target.css)}, (el) => { el.currentTime = ${a.currentTime}; });
1068
+ `;
626
1069
  break;
627
1070
  }
628
1071
  });
629
- code += `${indent(1)}});
1072
+ code += `${indent(2)}});
630
1073
  `;
631
1074
  code += `});
632
1075
  `;
@@ -634,126 +1077,108 @@ var generatePuppeteerTests = (events) => {
634
1077
  };
635
1078
 
636
1079
  // src/selenium/index.ts
637
- import {
638
- EventType as EventType5,
639
- IncrementalSource as IncrementalSource5,
640
- MouseInteractions as MouseInteractions5
641
- } from "@rrweb/types";
1080
+ var find = (css) => `await driver.findElement(By.css(${q(css)}))`;
1081
+ var SET_VALUE_SCRIPT = q(
1082
+ "arguments[0].value = arguments[1]; arguments[0].dispatchEvent(new Event('input', { bubbles: true })); arguments[0].dispatchEvent(new Event('change', { bubbles: true }));"
1083
+ );
642
1084
  var generateSeleniumTests = (events) => {
1085
+ const i = indent(4);
643
1086
  let code = "";
644
1087
  code += `const { Builder, By, until } = require('selenium-webdriver');
645
1088
 
646
1089
  `;
647
1090
  code += `describe('TODO: name the test block', () => {
648
1091
  `;
649
- code += `${indent(1)}let driver;
1092
+ code += `${indent(2)}let driver;
650
1093
 
651
1094
  `;
652
- code += `${indent(1)}beforeAll(async () => {
1095
+ code += `${indent(2)}beforeAll(async () => {
653
1096
  `;
654
- code += `${indent(2)}driver = await new Builder().forBrowser('chrome').build();
1097
+ code += `${i}driver = await new Builder().forBrowser('chrome').build();
655
1098
  `;
656
- code += `${indent(1)}});
1099
+ code += `${indent(2)}});
657
1100
 
658
1101
  `;
659
- code += `${indent(1)}afterAll(async () => {
1102
+ code += `${indent(2)}afterAll(async () => {
660
1103
  `;
661
- code += `${indent(2)}await driver.quit();
1104
+ code += `${i}await driver.quit();
662
1105
  `;
663
- code += `${indent(1)}});
1106
+ code += `${indent(2)}});
664
1107
 
665
1108
  `;
666
- code += `${indent(1)}test('TODO: name the test case', async () => {
1109
+ code += `${indent(2)}test('TODO: name the test case', async () => {
667
1110
  `;
668
- const fullSnapshotEvents = events.filter(
669
- (event) => event.type === EventType5.FullSnapshot
670
- );
671
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
672
- events.forEach((event) => {
673
- const e = event;
674
- switch (e.type) {
675
- case EventType5.Meta:
676
- if (e.data.href) {
677
- code += `${indent(2)}await driver.get('${e.data.href}');
1111
+ extractWebActions(events).forEach((a) => {
1112
+ switch (a.kind) {
1113
+ case "navigate":
1114
+ code += `${i}await driver.get(${q(a.href)});
678
1115
  `;
679
- code += `${indent(2)}await driver.wait(until.urlIs('${e.data.href}'), 5000);
1116
+ code += `${i}await driver.wait(until.urlIs(${q(a.href)}), 5000);
680
1117
  `;
681
- }
682
- if (e.data.width && e.data.height) {
683
- code += `${indent(2)}await driver.manage().window().setRect({ width: ${e.data.width}, height: ${e.data.height} });
1118
+ break;
1119
+ case "viewport":
1120
+ code += `${i}await driver.manage().window().setRect({ width: ${a.width}, height: ${a.height} });
1121
+ `;
1122
+ break;
1123
+ case "mousemove":
1124
+ code += `${i}await driver.actions().move({ x: ${a.x}, y: ${a.y} }).perform();
1125
+ `;
1126
+ break;
1127
+ case "click":
1128
+ code += `${i}${find(a.target.css)}.click();
1129
+ `;
1130
+ break;
1131
+ case "dblclick":
1132
+ code += `${i}await driver.actions().doubleClick(${find(a.target.css)}).perform();
684
1133
  `;
685
- }
686
1134
  break;
687
- case EventType5.IncrementalSnapshot:
688
- const data = e.data;
689
- const type = data.source;
690
- let d;
691
- switch (type) {
692
- case IncrementalSource5.MouseMove:
693
- case IncrementalSource5.TouchMove:
694
- d = data;
695
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
696
- code += `${indent(2)}await driver.actions().move({ x: ${d.positions[0].x}, y: ${d.positions[0].y} }).perform();
697
- `;
698
- }
699
- break;
700
- case IncrementalSource5.MouseInteraction:
701
- d = data;
702
- if (d.type === MouseInteractions5.Click) {
703
- const clickNode = nodeMap.get(d.id);
704
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
705
- (node) => node.childNodes?.map(
706
- (n1) => n1?.["textContent"]
707
- )
708
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? cssSelector(clickNode) : void 0;
709
- if (id) {
710
- code += `${indent(2)}await driver.findElement(By.css('${id}')).click();
711
- `;
712
- }
713
- }
714
- break;
715
- case IncrementalSource5.Scroll:
716
- d = data;
717
- if (d.x && d.y) {
718
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
719
- code += `${indent(2)}await driver.executeScript('document.querySelector("[id=${elementId}]").scrollTo(${d.x}, ${d.y});');
720
- `;
721
- }
722
- break;
723
- case IncrementalSource5.ViewportResize:
724
- d = data;
725
- if (d.width && d.height) {
726
- code += `${indent(2)}await driver.manage().window().setRect({ width: ${d.width}, height: ${d.height} });
727
- `;
728
- }
729
- break;
730
- case IncrementalSource5.Input:
731
- d = data;
732
- if (d.text) {
733
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
734
- code += `${indent(2)}const input = await driver.findElement(By.css('#${elementId}'));
735
- `;
736
- code += `${indent(2)}await input.clear();
737
- `;
738
- code += `${indent(2)}await input.sendKeys('${d.text}');
739
- `;
740
- }
741
- break;
742
- case IncrementalSource5.MediaInteraction:
743
- d = data;
744
- if (d.type) {
745
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
746
- code += `${indent(2)}await driver.executeScript('document.querySelector("[id=${elementId}]").${d.type}();');
747
- `;
748
- }
749
- break;
1135
+ case "fill": {
1136
+ const value = a.masked ? MASKED_PLACEHOLDER : a.value;
1137
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
1138
+ `;
1139
+ if (isScriptValueInput(a.target)) {
1140
+ code += `${i}await driver.executeScript(${SET_VALUE_SCRIPT}, ${find(a.target.css)}, ${q(value)});
1141
+ `;
1142
+ } else {
1143
+ code += `${i}{
1144
+ `;
1145
+ code += `${i} const el = ${find(a.target.css)};
1146
+ `;
1147
+ code += `${i} await el.clear();
1148
+ `;
1149
+ if (value) code += `${i} await el.sendKeys(${q(value)});
1150
+ `;
1151
+ code += `${i}}
1152
+ `;
750
1153
  }
751
1154
  break;
752
- default:
1155
+ }
1156
+ case "check":
1157
+ code += `${i}await driver.executeScript('if (arguments[0].checked !== arguments[1]) arguments[0].click();', ${find(a.target.css)}, ${a.checked});
1158
+ `;
1159
+ break;
1160
+ case "select":
1161
+ if (a.masked) code += `${i}${MASKED_VALUE_TODO}
1162
+ `;
1163
+ code += `${i}await driver.executeScript(${SET_VALUE_SCRIPT}, ${find(a.target.css)}, ${q(a.masked ? MASKED_PLACEHOLDER : a.value)});
1164
+ `;
1165
+ break;
1166
+ case "scroll":
1167
+ code += a.target ? `${i}await driver.executeScript('arguments[0].scrollTo(arguments[1], arguments[2]);', ${find(a.target.css)}, ${a.x}, ${a.y});
1168
+ ` : `${i}await driver.executeScript('window.scrollTo(arguments[0], arguments[1]);', ${a.x}, ${a.y});
1169
+ `;
1170
+ break;
1171
+ case "media":
1172
+ code += `${i}await driver.executeScript('arguments[0].${a.action}();', ${find(a.target.css)});
1173
+ `;
1174
+ break;
1175
+ case "seek":
1176
+ code += `${i}await driver.executeScript('arguments[0].currentTime = arguments[1];', ${find(a.target.css)}, ${a.currentTime});
1177
+ `;
753
1178
  break;
754
1179
  }
755
1180
  });
756
- code += `${indent(1)}});
1181
+ code += `${indent(2)}});
757
1182
  `;
758
1183
  code += `});
759
1184
  `;
@@ -761,15 +1186,15 @@ var generateSeleniumTests = (events) => {
761
1186
  };
762
1187
 
763
1188
  // src/xcuitest/index.ts
764
- var esc4 = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
765
1189
  var tapTarget = (loc) => {
766
1190
  if (!loc) return `app.buttons["TODO_add_accessibility_identifier"]`;
767
- if (loc.strategy === "text") return `app.staticTexts["${esc4(loc.value)}"]`;
768
- return `app.buttons["${esc4(loc.value)}"]`;
1191
+ if (loc.strategy === "text")
1192
+ return `app.staticTexts[${swiftString(loc.value)}]`;
1193
+ return `app.buttons[${swiftString(loc.value)}]`;
769
1194
  };
770
1195
  var inputTarget = (loc) => {
771
1196
  if (!loc) return `app.textFields["TODO_add_accessibility_identifier"]`;
772
- return `app.textFields["${esc4(loc.value)}"]`;
1197
+ return `app.textFields[${swiftString(loc.value)}]`;
773
1198
  };
774
1199
  var swipeFn2 = (direction) => ({
775
1200
  up: "swipeUp",
@@ -800,7 +1225,7 @@ var generateXcuiTests = (events) => {
800
1225
  case "input":
801
1226
  code += `${indent(2)}${inputTarget(a.locator)}.tap()
802
1227
  `;
803
- code += `${indent(2)}${inputTarget(a.locator)}.typeText("${esc4(a.text)}")
1228
+ code += `${indent(2)}${inputTarget(a.locator)}.typeText(${swiftString(a.text)})
804
1229
  `;
805
1230
  break;
806
1231
  case "swipe":