rrweb-browser-test 2.1.4 → 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
@@ -3,126 +3,782 @@ var TestFramework = {
3
3
  PLAYWRIGHT: "playwright",
4
4
  PUPPETEER: "puppeteer",
5
5
  CYPRESS: "cypress",
6
- SELENIUM: "selenium"
6
+ SELENIUM: "selenium",
7
+ APPIUM: "appium",
8
+ ESPRESSO: "espresso",
9
+ XCUITEST: "xcuitest",
10
+ DETOX: "detox"
7
11
  };
12
+ var MOBILE_FRAMEWORKS = [
13
+ "appium",
14
+ "espresso",
15
+ "xcuitest",
16
+ "detox"
17
+ ];
8
18
 
9
- // src/cypress/index.ts
19
+ // src/utils.ts
20
+ var indent = (level) => " ".repeat(level);
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
10
40
  import {
11
- EventType,
12
- IncrementalSource,
41
+ EventType as EventType2,
42
+ IncrementalSource as IncrementalSource2,
13
43
  MouseInteractions
14
44
  } from "@rrweb/types";
15
45
 
16
- // src/utils.ts
17
- var indent = (level) => " ".repeat(level);
18
- var buildNodeMapFromFullSnapshots = (fullSnapshots) => {
19
- const idMap = /* @__PURE__ */ new Map();
20
- fullSnapshots.forEach((snapshot) => {
21
- const rootNode = snapshot.data.node;
22
- function processNode(node) {
23
- idMap.set(node.id, node);
24
- if (node.childNodes) {
25
- node.childNodes.forEach((childNode) => {
26
- processNode(childNode);
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);
63
+ }
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;
151
+ }
152
+ }
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 });
166
+ });
167
+ return out.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
168
+ };
169
+
170
+ // src/mobile/shared.ts
171
+ var resourceIdLeaf = (value) => {
172
+ const slash = value.lastIndexOf("/");
173
+ return slash >= 0 ? value.slice(slash + 1) : value;
174
+ };
175
+ var mobileLocator = (node) => {
176
+ if (!node) return void 0;
177
+ const a = node.attributes ?? {};
178
+ const id = a["resource-id"] ?? a["resourceId"] ?? a["testID"] ?? a["data-testid"] ?? a.id;
179
+ if (id) return { strategy: "id", value: String(id) };
180
+ const accessibility = a["content-desc"] ?? a["contentDescription"] ?? a["accessibilityIdentifier"] ?? a["accessibilityLabel"] ?? a["aria-label"] ?? a["name"];
181
+ if (accessibility)
182
+ return { strategy: "accessibility", value: String(accessibility) };
183
+ const text = a["text"] ?? (node.childNodes ?? []).map((n) => n?.textContent).filter(Boolean).join(" ").trim();
184
+ if (text) return { strategy: "text", value: String(text) };
185
+ return void 0;
186
+ };
187
+ var swipeDirection = (d) => {
188
+ const x = d.x ?? 0;
189
+ const y = d.y ?? 0;
190
+ if (Math.abs(y) >= Math.abs(x)) return y >= 0 ? "up" : "down";
191
+ return x >= 0 ? "left" : "right";
192
+ };
193
+ var extractMobileActions = (events) => {
194
+ const actions = [];
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) {
209
+ if (e.data?.href)
210
+ actions.push({ kind: "launch", url: e.data.href });
211
+ return;
212
+ }
213
+ if (e.type !== EventType2.IncrementalSnapshot) return;
214
+ const data = e.data;
215
+ switch (data.source) {
216
+ case IncrementalSource2.MouseInteraction: {
217
+ const d = data;
218
+ if (d.type === MouseInteractions.Click || d.type === MouseInteractions.TouchEnd) {
219
+ actions.push({
220
+ kind: "tap",
221
+ locator: mobileLocator(nodeAt(d.id))
222
+ });
223
+ }
224
+ break;
225
+ }
226
+ case IncrementalSource2.Input: {
227
+ const d = data;
228
+ if (typeof d.text === "string") {
229
+ actions.push({
230
+ kind: "input",
231
+ locator: mobileLocator(nodeAt(d.id)),
232
+ text: d.text
233
+ });
234
+ }
235
+ break;
236
+ }
237
+ case IncrementalSource2.Scroll:
238
+ case IncrementalSource2.TouchMove: {
239
+ actions.push({
240
+ kind: "swipe",
241
+ direction: swipeDirection(data)
27
242
  });
243
+ break;
28
244
  }
245
+ default:
246
+ break;
29
247
  }
30
- processNode(rootNode);
31
248
  });
32
- return idMap;
249
+ return actions;
250
+ };
251
+
252
+ // src/appium/index.ts
253
+ var selector = (loc) => {
254
+ if (!loc) return `$('~TODO_add_accessibility_id')`;
255
+ switch (loc.strategy) {
256
+ case "id":
257
+ return `$(${q(`android=new UiSelector().resourceId(${doubleQuoted(loc.value)})`)})`;
258
+ case "accessibility":
259
+ return `$(${q(`~${loc.value}`)})`;
260
+ case "text":
261
+ return `$(${q(`android=new UiSelector().text(${doubleQuoted(loc.value)})`)})`;
262
+ }
263
+ };
264
+ var generateAppiumTests = (events) => {
265
+ const actions = extractMobileActions(events);
266
+ let code = "";
267
+ code += `// Appium + WebdriverIO \u2014 generated from a session recording
268
+ `;
269
+ code += `describe('replayed session', () => {
270
+ `;
271
+ code += `${indent(2)}it('replays the recorded user flow', async () => {
272
+ `;
273
+ actions.forEach((a) => {
274
+ switch (a.kind) {
275
+ case "launch":
276
+ code += `${indent(4)}await driver.launchApp();
277
+ `;
278
+ break;
279
+ case "tap":
280
+ code += `${indent(4)}await ${selector(a.locator)}.click();
281
+ `;
282
+ break;
283
+ case "input":
284
+ code += `${indent(4)}await ${selector(a.locator)}.setValue(${q(a.text)});
285
+ `;
286
+ break;
287
+ case "swipe":
288
+ code += `${indent(4)}await driver.execute('mobile: swipeGesture', { direction: '${a.direction}', percent: 0.75 });
289
+ `;
290
+ break;
291
+ }
292
+ });
293
+ code += `${indent(2)}});
294
+ `;
295
+ code += `});
296
+ `;
297
+ return code;
298
+ };
299
+
300
+ // src/web/actions.ts
301
+ import {
302
+ EventType as EventType3,
303
+ IncrementalSource as IncrementalSource3,
304
+ MediaInteractions,
305
+ MouseInteractions as MouseInteractions2
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;
33
705
  };
34
706
 
35
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, "{{}");
36
710
  var generateCypressTests = (events) => {
711
+ const i = indent(4);
37
712
  let code = "";
38
713
  code += `describe('TODO: name the test block', () => {
39
714
  `;
40
715
  code += ` it('TODO: name the test case', () => {
41
716
  `;
42
- const fullSnapshotEvents = events.filter(
43
- (event) => event.type === EventType.FullSnapshot
44
- );
45
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
46
- events.forEach((event) => {
47
- const e = event;
48
- switch (e.type) {
49
- case EventType.Meta:
50
- if (e.data.href) {
51
- 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)});
52
721
  `;
53
- code += `${indent(3)}cy.url().should('include', '${e.data.href}');
722
+ code += `${i}cy.url().should('include', ${q(a.href)});
54
723
  `;
55
- }
56
- if (e.data.width && e.data.height) {
57
- 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});
58
727
  `;
59
- }
60
728
  break;
61
- case EventType.IncrementalSnapshot:
62
- const data = e.data;
63
- const type = data.source;
64
- let d;
65
- switch (type) {
66
- case (IncrementalSource.MouseMove || IncrementalSource.TouchMove):
67
- d = data;
68
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
69
- code += `${indent(3)}cy.get('body').trigger('mousemove', { clientX: ${d.positions[0].x}, clientY: ${d.positions[0].y} });
70
- `;
71
- }
72
- break;
73
- case IncrementalSource.MouseInteraction:
74
- d = data;
75
- if (d.type === MouseInteractions.Click) {
76
- const clickNode = nodeMap.get(d.id);
77
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
78
- (node) => node.childNodes?.map(
79
- (n1) => n1?.["textContent"]
80
- )
81
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? `${clickNode?.tagName}.${clickNode?.attributes?.class}` : void 0;
82
- if (id) {
83
- if (clickNode?.tagName === "nav") {
84
- code += `${indent(3)}cy.contains('${clickNode?.tagName}', ${id}).click();
85
- `;
86
- } else {
87
- code += `${indent(3)}cy.get('${id}').click();
88
- `;
89
- }
90
- }
91
- }
92
- break;
93
- case IncrementalSource.Scroll:
94
- d = data;
95
- if (d.x && d.y) {
96
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').scrollTo(${d.x}, ${d.y});
97
- `;
98
- }
99
- break;
100
- case IncrementalSource.ViewportResize:
101
- d = data;
102
- if (d.width && d.height) {
103
- code += `${indent(3)}cy.viewport(${d.width}, ${d.height});
104
- `;
105
- }
106
- break;
107
- case IncrementalSource.Input:
108
- d = data;
109
- if (d.text) {
110
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').type('${d.text}');
111
- `;
112
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').should('have.value', '${d.text}');
113
- `;
114
- }
115
- break;
116
- case IncrementalSource.MediaInteraction:
117
- d = data;
118
- if (d.type) {
119
- code += `${indent(3)}cy.get('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').then((el) => el[0].${d.type}());
120
- `;
121
- }
122
- 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();
739
+ `;
740
+ 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
+ `;
123
754
  }
755
+ if (!a.masked)
756
+ code += `${i}${get(a.target)}.should('have.value', ${q(value)});
757
+ `;
124
758
  break;
125
- 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
+ `;
126
782
  break;
127
783
  }
128
784
  });
@@ -133,245 +789,287 @@ var generateCypressTests = (events) => {
133
789
  return code;
134
790
  };
135
791
 
792
+ // src/detox/index.ts
793
+ var matcher = (loc) => {
794
+ if (!loc) return `by.id('TODO_add_testID')`;
795
+ switch (loc.strategy) {
796
+ case "id":
797
+ return `by.id(${q(loc.value)})`;
798
+ case "accessibility":
799
+ return `by.label(${q(loc.value)})`;
800
+ case "text":
801
+ return `by.text(${q(loc.value)})`;
802
+ }
803
+ };
804
+ var generateDetoxTests = (events) => {
805
+ const actions = extractMobileActions(events);
806
+ let code = "";
807
+ code += `// Detox \u2014 generated from a session recording
808
+ `;
809
+ code += `describe('replayed session', () => {
810
+ `;
811
+ code += `${indent(2)}it('replays the recorded user flow', async () => {
812
+ `;
813
+ actions.forEach((a) => {
814
+ switch (a.kind) {
815
+ case "launch":
816
+ code += `${indent(4)}await device.launchApp({ newInstance: true });
817
+ `;
818
+ break;
819
+ case "tap":
820
+ code += `${indent(4)}await element(${matcher(a.locator)}).tap();
821
+ `;
822
+ break;
823
+ case "input":
824
+ code += `${indent(4)}await element(${matcher(a.locator)}).typeText(${q(a.text)});
825
+ `;
826
+ break;
827
+ case "swipe":
828
+ code += `${indent(4)}await element(by.id('scrollView')).swipe('${a.direction}');
829
+ `;
830
+ break;
831
+ }
832
+ });
833
+ code += `${indent(2)}});
834
+ `;
835
+ code += `});
836
+ `;
837
+ return code;
838
+ };
839
+
840
+ // src/espresso/index.ts
841
+ var matcher2 = (loc) => {
842
+ if (!loc) return `withContentDescription("TODO_add_content_description")`;
843
+ switch (loc.strategy) {
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
+ }
848
+ case "accessibility":
849
+ return `withContentDescription(${kotlinString(loc.value)})`;
850
+ case "text":
851
+ return `withText(${kotlinString(loc.value)})`;
852
+ }
853
+ };
854
+ var swipeFn = (direction) => ({
855
+ up: "swipeUp",
856
+ down: "swipeDown",
857
+ left: "swipeLeft",
858
+ right: "swipeRight"
859
+ })[direction];
860
+ var generateEspressoTests = (events) => {
861
+ const actions = extractMobileActions(events);
862
+ let code = "";
863
+ code += `// Espresso (Kotlin) \u2014 generated from a session recording
864
+ `;
865
+ code += `@Test
866
+ `;
867
+ code += `fun replaySession() {
868
+ `;
869
+ actions.forEach((a) => {
870
+ switch (a.kind) {
871
+ case "launch":
872
+ code += `${indent(2)}// App launch is handled by ActivityScenarioRule
873
+ `;
874
+ break;
875
+ case "tap":
876
+ code += `${indent(2)}onView(${matcher2(a.locator)}).perform(click())
877
+ `;
878
+ break;
879
+ case "input":
880
+ code += `${indent(2)}onView(${matcher2(a.locator)}).perform(typeText(${kotlinString(a.text)}), closeSoftKeyboard())
881
+ `;
882
+ break;
883
+ case "swipe":
884
+ code += `${indent(2)}onView(isRoot()).perform(${swipeFn(a.direction)}())
885
+ `;
886
+ break;
887
+ }
888
+ });
889
+ code += `}
890
+ `;
891
+ return code;
892
+ };
893
+
136
894
  // src/playwright/index.ts
137
- import {
138
- EventType as EventType2,
139
- IncrementalSource as IncrementalSource2,
140
- MouseInteractions as MouseInteractions2
141
- } 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)})`;
142
896
  var generatePlaywrightTests = (events) => {
897
+ const i = indent(2);
143
898
  let code = "";
144
899
  code += `import { test, expect } from '@playwright/test';
145
900
 
146
901
  `;
147
- code += `test('TODO: name the test block', async ({ page, context }) => {
902
+ code += `test('TODO: name the test block', async ({ page }) => {
148
903
  `;
149
- const fullSnapshotEvents = events.filter(
150
- (event) => event.type === EventType2.FullSnapshot
151
- );
152
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
153
- 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)});
154
908
  `;
155
- events.forEach((event) => {
156
- const e = event;
157
- switch (e.type) {
158
- case EventType2.Meta:
159
- if (e.data.href) {
160
- code += `${indent(2)}await page.goto('${e.data.href}');
909
+ code += `${i}await expect(page).toHaveURL(${q(a.href)});
161
910
  `;
162
- code += `${indent(2)}await expect(page).toHaveURL('${e.data.href}');
911
+ break;
912
+ case "viewport":
913
+ code += `${i}await page.setViewportSize({ width: ${a.width}, height: ${a.height} });
163
914
  `;
164
- }
165
- if (e.data.width && e.data.height) {
166
- code += `${indent(2)}await page.setViewportSize({ width: ${e.data.width}, height: ${e.data.height} });
915
+ code += `${i}await expect(page).toHaveViewportSize({ width: ${a.width}, height: ${a.height} });
916
+ `;
917
+ break;
918
+ case "mousemove":
919
+ code += `${i}await page.mouse.move(${a.x}, ${a.y});
167
920
  `;
168
- 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();
924
+ `;
925
+ break;
926
+ case "dblclick":
927
+ code += `${i}await ${locator(a.target)}.dblclick();
169
928
  `;
170
- }
171
929
  break;
172
- case EventType2.IncrementalSnapshot:
173
- const data = e.data;
174
- const type = data.source;
175
- let d;
176
- switch (type) {
177
- case (IncrementalSource2.MouseMove || IncrementalSource2.TouchMove):
178
- d = data;
179
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
180
- code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});
181
- `;
182
- }
183
- break;
184
- case IncrementalSource2.MouseInteraction:
185
- d = data;
186
- if (d.type === MouseInteractions2.Click) {
187
- const clickNode = nodeMap.get(d.id);
188
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
189
- (node) => node.childNodes?.map(
190
- (n1) => n1?.["textContent"]
191
- )
192
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? `${clickNode?.tagName}.${clickNode?.attributes?.class}` : void 0;
193
- if (id && d.x && d.y) {
194
- code += `${indent(2)}await page.locator(\`${id}\`).click();
195
- `;
196
- code += `${indent(2)}await expect(page.locator(\`${id}\`)).toBeVisible();
197
- `;
198
- }
199
- break;
200
- }
201
- break;
202
- case IncrementalSource2.Scroll:
203
- d = data;
204
- if (d.x && d.y) {
205
- code += `${indent(2)}await page.mouse.wheel(() => { document.querySelector('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]').scrollTo(${d.x}, ${d.y}); });
206
- `;
207
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toBeVisible();
208
- `;
209
- }
210
- break;
211
- case IncrementalSource2.ViewportResize:
212
- d = data;
213
- if (d.width && d.height) {
214
- code += `${indent(2)}await page.setViewportSize({ width: ${d.width}, height: ${d.height} });
215
- `;
216
- code += `${indent(2)}await expect(page).toHaveViewportSize({ width: ${d.width}, height: ${d.height} });
217
- `;
218
- }
219
- break;
220
- case IncrementalSource2.Input:
221
- d = data;
222
- if (d.text) {
223
- code += `${indent(2)}await page.fill('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]', '${d.text}');
224
- `;
225
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toHaveValue('${d.text}');
226
- `;
227
- }
228
- break;
229
- case IncrementalSource2.MediaInteraction:
230
- d = data;
231
- if (d.type) {
232
- code += `${indent(2)}await page.$eval('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]', el => el.${d.type}());
233
- `;
234
- code += `${indent(2)}await expect(page.locator('[data-id="${nodeMap.get(d.id)?.attributes?.id}"]')).toBeVisible();
235
- `;
236
- }
237
- 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
+ `;
238
941
  }
239
942
  break;
240
- 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
+ `;
241
967
  break;
242
968
  }
243
969
  });
244
- code += `${indent(1)}});
970
+ code += `});
245
971
  `;
246
972
  return code;
247
973
  };
248
974
 
249
975
  // src/puppeteer/index.ts
250
- import {
251
- EventType as EventType3,
252
- IncrementalSource as IncrementalSource3,
253
- MouseInteractions as MouseInteractions3
254
- } from "@rrweb/types";
255
976
  var generatePuppeteerTests = (events) => {
977
+ const i = indent(4);
256
978
  let code = "";
257
979
  code += `const puppeteer = require('puppeteer');
258
980
 
259
981
  `;
260
982
  code += `describe('TODO: name the test block', () => {
261
983
  `;
262
- code += `${indent(1)}let browser, page;
984
+ code += `${indent(2)}let browser, page;
263
985
 
264
986
  `;
265
- code += `${indent(1)}beforeAll(async () => {
987
+ code += `${indent(2)}beforeAll(async () => {
266
988
  `;
267
- code += `${indent(2)}browser = await puppeteer.launch();
989
+ code += `${i}browser = await puppeteer.launch();
268
990
  `;
269
- code += `${indent(2)}page = await browser.newPage();
991
+ code += `${i}page = await browser.newPage();
270
992
  `;
271
- code += `${indent(1)}});
993
+ code += `${indent(2)}});
272
994
 
273
995
  `;
274
- code += `${indent(1)}afterAll(async () => {
996
+ code += `${indent(2)}afterAll(async () => {
275
997
  `;
276
- code += `${indent(2)}await browser.close();
998
+ code += `${i}await browser.close();
277
999
  `;
278
- code += `${indent(1)}});
1000
+ code += `${indent(2)}});
279
1001
 
280
1002
  `;
281
- code += `${indent(1)}test('TODO: name the test case', async () => {
1003
+ code += `${indent(2)}test('TODO: name the test case', async () => {
282
1004
  `;
283
- const fullSnapshotEvents = events.filter(
284
- (event) => event.type === EventType3.FullSnapshot
285
- );
286
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
287
- events.forEach((event) => {
288
- const e = event;
289
- switch (e.type) {
290
- case EventType3.Meta:
291
- if (e.data.href) {
292
- 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)});
293
1009
  `;
294
- code += `${indent(2)}await expect(page.url()).toBe('${e.data.href}');
1010
+ code += `${i}expect(page.url()).toBe(${q(a.href)});
295
1011
  `;
296
- }
297
- if (e.data.width && e.data.height) {
298
- 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} });
299
1015
  `;
300
- }
301
1016
  break;
302
- case EventType3.IncrementalSnapshot:
303
- const data = e.data;
304
- const type = data.source;
305
- let d;
306
- switch (type) {
307
- case (IncrementalSource3.MouseMove || IncrementalSource3.TouchMove):
308
- d = data;
309
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
310
- code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});
311
- `;
312
- }
313
- break;
314
- case IncrementalSource3.MouseInteraction:
315
- d = data;
316
- if (d.type === MouseInteractions3.Click) {
317
- const clickNode = nodeMap.get(d.id);
318
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
319
- (node) => node.childNodes?.map(
320
- (n1) => n1?.["textContent"]
321
- )
322
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? `${clickNode?.tagName}.${clickNode?.attributes?.class}` : void 0;
323
- if (id) {
324
- code += `${indent(2)}await page.click('${id}');
325
- `;
326
- }
327
- }
328
- break;
329
- case IncrementalSource3.Scroll:
330
- d = data;
331
- if (d.x && d.y) {
332
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
333
- code += `${indent(2)}await page.evaluate(() => {
334
- `;
335
- code += `${indent(3)}document.querySelector('#${elementId}').scrollTo(${d.x}, ${d.y});
336
- `;
337
- code += `${indent(2)}});
338
- `;
339
- }
340
- break;
341
- case IncrementalSource3.ViewportResize:
342
- d = data;
343
- if (d.width && d.height) {
344
- code += `${indent(2)}await page.setViewport({ width: ${d.width}, height: ${d.height} });
345
- `;
346
- }
347
- break;
348
- case IncrementalSource3.Input:
349
- d = data;
350
- if (d.text) {
351
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
352
- code += `${indent(2)}await page.type('#${elementId}', '${d.text}');
353
- `;
354
- }
355
- break;
356
- case IncrementalSource3.MediaInteraction:
357
- d = data;
358
- if (d.type) {
359
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
360
- code += `${indent(2)}await page.evaluate(() => {
361
- `;
362
- code += `${indent(3)}document.querySelector('#${elementId}').${d.type}();
363
- `;
364
- code += `${indent(2)}});
365
- `;
366
- }
367
- break;
1017
+ case "mousemove":
1018
+ code += `${i}await page.mouse.move(${a.x}, ${a.y});
1019
+ `;
1020
+ 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
+ `;
368
1044
  }
369
1045
  break;
370
- 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
+ `;
371
1069
  break;
372
1070
  }
373
1071
  });
374
- code += `${indent(1)}});
1072
+ code += `${indent(2)}});
375
1073
  `;
376
1074
  code += `});
377
1075
  `;
@@ -379,131 +1077,168 @@ var generatePuppeteerTests = (events) => {
379
1077
  };
380
1078
 
381
1079
  // src/selenium/index.ts
382
- import {
383
- EventType as EventType4,
384
- IncrementalSource as IncrementalSource4,
385
- MouseInteractions as MouseInteractions4
386
- } 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
+ );
387
1084
  var generateSeleniumTests = (events) => {
1085
+ const i = indent(4);
388
1086
  let code = "";
389
1087
  code += `const { Builder, By, until } = require('selenium-webdriver');
390
1088
 
391
1089
  `;
392
1090
  code += `describe('TODO: name the test block', () => {
393
1091
  `;
394
- code += `${indent(1)}let driver;
1092
+ code += `${indent(2)}let driver;
395
1093
 
396
1094
  `;
397
- code += `${indent(1)}beforeAll(async () => {
1095
+ code += `${indent(2)}beforeAll(async () => {
398
1096
  `;
399
- code += `${indent(2)}driver = await new Builder().forBrowser('chrome').build();
1097
+ code += `${i}driver = await new Builder().forBrowser('chrome').build();
400
1098
  `;
401
- code += `${indent(1)}});
1099
+ code += `${indent(2)}});
402
1100
 
403
1101
  `;
404
- code += `${indent(1)}afterAll(async () => {
1102
+ code += `${indent(2)}afterAll(async () => {
405
1103
  `;
406
- code += `${indent(2)}await driver.quit();
1104
+ code += `${i}await driver.quit();
407
1105
  `;
408
- code += `${indent(1)}});
1106
+ code += `${indent(2)}});
409
1107
 
410
1108
  `;
411
- code += `${indent(1)}test('TODO: name the test case', async () => {
1109
+ code += `${indent(2)}test('TODO: name the test case', async () => {
412
1110
  `;
413
- const fullSnapshotEvents = events.filter(
414
- (event) => event.type === EventType4.FullSnapshot
415
- );
416
- const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshotEvents);
417
- events.forEach((event) => {
418
- const e = event;
419
- switch (e.type) {
420
- case EventType4.Meta:
421
- if (e.data.href) {
422
- 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)});
423
1115
  `;
424
- code += `${indent(2)}await driver.wait(until.urlIs('${e.data.href}'), 5000);
1116
+ code += `${i}await driver.wait(until.urlIs(${q(a.href)}), 5000);
425
1117
  `;
426
- }
427
- if (e.data.width && e.data.height) {
428
- 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();
429
1129
  `;
430
- }
431
1130
  break;
432
- case EventType4.IncrementalSnapshot:
433
- const data = e.data;
434
- const type = data.source;
435
- let d;
436
- switch (type) {
437
- case (IncrementalSource4.MouseMove || IncrementalSource4.TouchMove):
438
- d = data;
439
- if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
440
- code += `${indent(2)}await driver.actions().move({ x: ${d.positions[0].x}, y: ${d.positions[0].y} }).perform();
441
- `;
442
- }
443
- break;
444
- case IncrementalSource4.MouseInteraction:
445
- d = data;
446
- if (d.type === MouseInteractions4.Click) {
447
- const clickNode = nodeMap.get(d.id);
448
- const id = clickNode?.attributes?.id ? `#${clickNode?.attributes?.id}` : clickNode?.tagName === "nav" ? `${clickNode?.tagName}:text-is("${clickNode.childNodes?.filter((f) => f.tagName === "a")?.map(
449
- (node) => node.childNodes?.map(
450
- (n1) => n1?.["textContent"]
451
- )
452
- ).join(" ")}")` : clickNode?.tagName === "a" ? `${clickNode?.tagName}:has-text("${clickNode.childNodes?.map((node) => node?.["textContent"]).join(" ")}")` : clickNode !== void 0 ? `${clickNode?.tagName}.${clickNode?.attributes?.class}` : void 0;
453
- if (id) {
454
- code += `${indent(2)}await driver.findElement(By.css('${id}')).click();
455
- `;
456
- }
457
- }
458
- break;
459
- case IncrementalSource4.Scroll:
460
- d = data;
461
- if (d.x && d.y) {
462
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
463
- code += `${indent(2)}await driver.executeScript('document.querySelector("[id=${elementId}]").scrollTo(${d.x}, ${d.y});');
464
- `;
465
- }
466
- break;
467
- case IncrementalSource4.ViewportResize:
468
- d = data;
469
- if (d.width && d.height) {
470
- code += `${indent(2)}await driver.manage().window().setRect({ width: ${d.width}, height: ${d.height} });
471
- `;
472
- }
473
- break;
474
- case IncrementalSource4.Input:
475
- d = data;
476
- if (d.text) {
477
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
478
- code += `${indent(2)}const input = await driver.findElement(By.css('#${elementId}'));
479
- `;
480
- code += `${indent(2)}await input.clear();
481
- `;
482
- code += `${indent(2)}await input.sendKeys('${d.text}');
483
- `;
484
- }
485
- break;
486
- case IncrementalSource4.MediaInteraction:
487
- d = data;
488
- if (d.type) {
489
- const elementId = nodeMap.get(d.id)?.attributes?.id || "";
490
- code += `${indent(2)}await driver.executeScript('document.querySelector("[id=${elementId}]").${d.type}();');
491
- `;
492
- }
493
- break;
1131
+ case "dblclick":
1132
+ code += `${i}await driver.actions().doubleClick(${find(a.target.css)}).perform();
1133
+ `;
1134
+ 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
+ `;
494
1153
  }
495
1154
  break;
496
- 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
+ `;
497
1178
  break;
498
1179
  }
499
1180
  });
500
- code += `${indent(1)}});
1181
+ code += `${indent(2)}});
501
1182
  `;
502
1183
  code += `});
503
1184
  `;
504
1185
  return code;
505
1186
  };
506
1187
 
1188
+ // src/xcuitest/index.ts
1189
+ var tapTarget = (loc) => {
1190
+ if (!loc) return `app.buttons["TODO_add_accessibility_identifier"]`;
1191
+ if (loc.strategy === "text")
1192
+ return `app.staticTexts[${swiftString(loc.value)}]`;
1193
+ return `app.buttons[${swiftString(loc.value)}]`;
1194
+ };
1195
+ var inputTarget = (loc) => {
1196
+ if (!loc) return `app.textFields["TODO_add_accessibility_identifier"]`;
1197
+ return `app.textFields[${swiftString(loc.value)}]`;
1198
+ };
1199
+ var swipeFn2 = (direction) => ({
1200
+ up: "swipeUp",
1201
+ down: "swipeDown",
1202
+ left: "swipeLeft",
1203
+ right: "swipeRight"
1204
+ })[direction];
1205
+ var generateXcuiTests = (events) => {
1206
+ const actions = extractMobileActions(events);
1207
+ let code = "";
1208
+ code += `// XCUITest (Swift) \u2014 generated from a session recording
1209
+ `;
1210
+ code += `func testReplaySession() {
1211
+ `;
1212
+ code += `${indent(2)}let app = XCUIApplication()
1213
+ `;
1214
+ code += `${indent(2)}app.launch()
1215
+ `;
1216
+ actions.forEach((a) => {
1217
+ switch (a.kind) {
1218
+ case "launch":
1219
+ break;
1220
+ // already launched above
1221
+ case "tap":
1222
+ code += `${indent(2)}${tapTarget(a.locator)}.tap()
1223
+ `;
1224
+ break;
1225
+ case "input":
1226
+ code += `${indent(2)}${inputTarget(a.locator)}.tap()
1227
+ `;
1228
+ code += `${indent(2)}${inputTarget(a.locator)}.typeText(${swiftString(a.text)})
1229
+ `;
1230
+ break;
1231
+ case "swipe":
1232
+ code += `${indent(2)}app.${swipeFn2(a.direction)}()
1233
+ `;
1234
+ break;
1235
+ }
1236
+ });
1237
+ code += `}
1238
+ `;
1239
+ return code;
1240
+ };
1241
+
507
1242
  // src/core.ts
508
1243
  var generateTests = (events, options) => {
509
1244
  switch (options?.framework) {
@@ -515,6 +1250,14 @@ var generateTests = (events, options) => {
515
1250
  return generateSeleniumTests(events);
516
1251
  case TestFramework.PUPPETEER:
517
1252
  return generatePuppeteerTests(events);
1253
+ case TestFramework.APPIUM:
1254
+ return generateAppiumTests(events);
1255
+ case TestFramework.ESPRESSO:
1256
+ return generateEspressoTests(events);
1257
+ case TestFramework.XCUITEST:
1258
+ return generateXcuiTests(events);
1259
+ case TestFramework.DETOX:
1260
+ return generateDetoxTests(events);
518
1261
  default:
519
1262
  return generatePlaywrightTests(events);
520
1263
  }
@@ -523,6 +1266,7 @@ var generateBrowserTests = (events, options) => {
523
1266
  return generateTests(events, options);
524
1267
  };
525
1268
  export {
1269
+ MOBILE_FRAMEWORKS,
526
1270
  TestFramework,
527
1271
  generateBrowserTests
528
1272
  };