rrweb-browser-test 2.1.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/example/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  import { generateBrowserTests, TestFramework } from '../dist/index.cjs';
2
- import events from '../events.json' with { type: 'json' };
2
+ import events from 'events.json' with { type: 'json' };
3
3
 
4
- // console.log(generateBrowserTests(events));
4
+ console.log(generateBrowserTests(events).toCode());
5
5
  console.log(
6
6
  generateBrowserTests(events, {
7
- framework: TestFramework.CYPRESS,
8
- }),
7
+ framework: TestFramework.PLAYWRIGHT,
8
+ }).toCode(),
9
+ );
10
+ console.log(
11
+ generateBrowserTests(events, { framework: TestFramework.CYPRESS }).toCode(),
12
+ );
13
+ console.log(
14
+ generateBrowserTests(events, { framework: TestFramework.SELENIUM }).toCode(),
15
+ );
16
+ console.log(
17
+ generateBrowserTests(events, { framework: TestFramework.PUPPETEER }).toCode(),
9
18
  );
10
- // console.log(
11
- // generateBrowserTests(events, { framework: TestFramework.CYPRESS }),
12
- // );
13
- // console.log(
14
- // generateBrowserTests(events, { framework: TestFramework.SELENIUM }),
15
- // );
16
- // console.log(
17
- // generateBrowserTests(events, { framework: TestFramework.PUPPETEER }),
18
- // );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rrweb-browser-test",
3
- "version": "2.1.3",
3
+ "version": "2.2.0",
4
4
  "description": "RRWeb events to generating browser test scripts",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -15,6 +15,7 @@
15
15
  "scripts": {
16
16
  "dev": "vitest",
17
17
  "build": "tsup",
18
+ "prepare": "tsup",
18
19
  "ci": "npm run build && npm run check-format && npm run check-exports && npm run lint && npm run test",
19
20
  "format": "prettier --write .",
20
21
  "lint": "tsc",
@@ -0,0 +1,50 @@
1
+ import type { eventWithTime } from '@rrweb/types';
2
+ import { indent } from '../utils';
3
+ import { extractMobileActions, type MobileLocator } from '../mobile/shared';
4
+
5
+ const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
6
+
7
+ const selector = (loc?: MobileLocator): string => {
8
+ if (!loc) return `$('~TODO_add_accessibility_id')`;
9
+ switch (loc.strategy) {
10
+ case 'id':
11
+ return `$('android=new UiSelector().resourceId("${esc(loc.value)}")')`;
12
+ case 'accessibility':
13
+ return `$('~${esc(loc.value)}')`;
14
+ case 'text':
15
+ return `$('android=new UiSelector().text("${esc(loc.value)}")')`;
16
+ }
17
+ };
18
+
19
+ /** Appium (WebdriverIO) mobile test from a session recording. */
20
+ export const generateAppiumTests = (
21
+ events: Array<eventWithTime | string>,
22
+ ): string => {
23
+ const actions = extractMobileActions(events);
24
+ let code = '';
25
+
26
+ code += `// Appium + WebdriverIO — generated from a session recording\n`;
27
+ code += `describe('replayed session', () => {\n`;
28
+ code += `${indent(2)}it('replays the recorded user flow', async () => {\n`;
29
+
30
+ actions.forEach((a) => {
31
+ switch (a.kind) {
32
+ case 'launch':
33
+ code += `${indent(4)}await driver.launchApp();\n`;
34
+ break;
35
+ case 'tap':
36
+ code += `${indent(4)}await ${selector(a.locator)}.click();\n`;
37
+ break;
38
+ case 'input':
39
+ code += `${indent(4)}await ${selector(a.locator)}.setValue('${esc(a.text)}');\n`;
40
+ break;
41
+ case 'swipe':
42
+ code += `${indent(4)}await driver.execute('mobile: swipeGesture', { direction: '${a.direction}', percent: 0.75 });\n`;
43
+ break;
44
+ }
45
+ });
46
+
47
+ code += `${indent(2)}});\n`;
48
+ code += `});\n`;
49
+ return code;
50
+ };
package/src/core.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { eventWithTime } from '@rrweb/types';
2
+ import { generateAppiumTests } from './appium';
2
3
  import { generateCypressTests } from './cypress';
4
+ import { generateDetoxTests } from './detox';
5
+ import { generateEspressoTests } from './espresso';
3
6
  import { generatePlaywrightTests } from './playwright';
4
7
  import { generatePuppeteerTests } from './puppeteer';
5
8
  import { generateSeleniumTests } from './selenium';
9
+ import { generateXcuiTests } from './xcuitest';
6
10
  import { TestFramework, type TestOptions } from './types';
7
11
 
8
12
  const generateTests = (
@@ -18,6 +22,14 @@ const generateTests = (
18
22
  return generateSeleniumTests(events);
19
23
  case TestFramework.PUPPETEER:
20
24
  return generatePuppeteerTests(events);
25
+ case TestFramework.APPIUM:
26
+ return generateAppiumTests(events);
27
+ case TestFramework.ESPRESSO:
28
+ return generateEspressoTests(events);
29
+ case TestFramework.XCUITEST:
30
+ return generateXcuiTests(events);
31
+ case TestFramework.DETOX:
32
+ return generateDetoxTests(events);
21
33
  default:
22
34
  return generatePlaywrightTests(events);
23
35
  }
@@ -11,7 +11,7 @@ import {
11
11
  type scrollData,
12
12
  type viewportResizeData,
13
13
  } from '@rrweb/types';
14
- import { buildNodeMapFromFullSnapshots, indent } from '../utils';
14
+ import { buildNodeMapFromFullSnapshots, cssSelector, indent } from '../utils';
15
15
 
16
16
  export const generateCypressTests = (
17
17
  events: Array<eventWithTime | string>,
@@ -44,7 +44,8 @@ export const generateCypressTests = (
44
44
  const type = data.source;
45
45
  let d;
46
46
  switch (type) {
47
- case IncrementalSource.MouseMove || IncrementalSource.TouchMove:
47
+ case IncrementalSource.MouseMove:
48
+ case IncrementalSource.TouchMove:
48
49
  d = data as mousemoveData;
49
50
  if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
50
51
  code += `${indent(3)}cy.get('body').trigger('mousemove', { clientX: ${d.positions[0].x}, clientY: ${d.positions[0].y} });\n`;
@@ -71,7 +72,7 @@ export const generateCypressTests = (
71
72
  ?.map((node) => (node as any)?.['textContent'])
72
73
  .join(' ')}")`
73
74
  : clickNode !== undefined
74
- ? `${clickNode?.tagName}.${clickNode?.attributes?.class}`
75
+ ? cssSelector(clickNode)
75
76
  : undefined;
76
77
  if (id) {
77
78
  if (clickNode?.tagName === 'nav') {
@@ -0,0 +1,50 @@
1
+ import type { eventWithTime } from '@rrweb/types';
2
+ import { indent } from '../utils';
3
+ import { extractMobileActions, type MobileLocator } from '../mobile/shared';
4
+
5
+ const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
6
+
7
+ const matcher = (loc?: MobileLocator): string => {
8
+ if (!loc) return `by.id('TODO_add_testID')`;
9
+ switch (loc.strategy) {
10
+ case 'id':
11
+ return `by.id('${esc(loc.value)}')`;
12
+ case 'accessibility':
13
+ return `by.label('${esc(loc.value)}')`;
14
+ case 'text':
15
+ return `by.text('${esc(loc.value)}')`;
16
+ }
17
+ };
18
+
19
+ /** Detox (JavaScript) mobile test from a session recording. */
20
+ export const generateDetoxTests = (
21
+ events: Array<eventWithTime | string>,
22
+ ): string => {
23
+ const actions = extractMobileActions(events);
24
+ let code = '';
25
+
26
+ code += `// Detox — generated from a session recording\n`;
27
+ code += `describe('replayed session', () => {\n`;
28
+ code += `${indent(2)}it('replays the recorded user flow', async () => {\n`;
29
+
30
+ actions.forEach((a) => {
31
+ switch (a.kind) {
32
+ case 'launch':
33
+ code += `${indent(4)}await device.launchApp({ newInstance: true });\n`;
34
+ break;
35
+ case 'tap':
36
+ code += `${indent(4)}await element(${matcher(a.locator)}).tap();\n`;
37
+ break;
38
+ case 'input':
39
+ code += `${indent(4)}await element(${matcher(a.locator)}).typeText('${esc(a.text)}');\n`;
40
+ break;
41
+ case 'swipe':
42
+ code += `${indent(4)}await element(by.id('scrollView')).swipe('${a.direction}');\n`;
43
+ break;
44
+ }
45
+ });
46
+
47
+ code += `${indent(2)}});\n`;
48
+ code += `});\n`;
49
+ return code;
50
+ };
@@ -0,0 +1,61 @@
1
+ import type { eventWithTime } from '@rrweb/types';
2
+ import { indent } from '../utils';
3
+ import {
4
+ extractMobileActions,
5
+ resourceIdLeaf,
6
+ type MobileLocator,
7
+ } from '../mobile/shared';
8
+
9
+ const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
10
+
11
+ const matcher = (loc?: MobileLocator): string => {
12
+ if (!loc) return `withContentDescription("TODO_add_content_description")`;
13
+ switch (loc.strategy) {
14
+ case 'id':
15
+ return `withId(R.id.${resourceIdLeaf(loc.value)})`;
16
+ case 'accessibility':
17
+ return `withContentDescription("${esc(loc.value)}")`;
18
+ case 'text':
19
+ return `withText("${esc(loc.value)}")`;
20
+ }
21
+ };
22
+
23
+ const swipeFn = (direction: 'up' | 'down' | 'left' | 'right') =>
24
+ ({
25
+ up: 'swipeUp',
26
+ down: 'swipeDown',
27
+ left: 'swipeLeft',
28
+ right: 'swipeRight',
29
+ })[direction];
30
+
31
+ /** Espresso (Kotlin) mobile test from a session recording. */
32
+ export const generateEspressoTests = (
33
+ events: Array<eventWithTime | string>,
34
+ ): string => {
35
+ const actions = extractMobileActions(events);
36
+ let code = '';
37
+
38
+ code += `// Espresso (Kotlin) — generated from a session recording\n`;
39
+ code += `@Test\n`;
40
+ code += `fun replaySession() {\n`;
41
+
42
+ actions.forEach((a) => {
43
+ switch (a.kind) {
44
+ case 'launch':
45
+ code += `${indent(2)}// App launch is handled by ActivityScenarioRule\n`;
46
+ break;
47
+ case 'tap':
48
+ code += `${indent(2)}onView(${matcher(a.locator)}).perform(click())\n`;
49
+ break;
50
+ case 'input':
51
+ code += `${indent(2)}onView(${matcher(a.locator)}).perform(typeText("${esc(a.text)}"), closeSoftKeyboard())\n`;
52
+ break;
53
+ case 'swipe':
54
+ code += `${indent(2)}onView(isRoot()).perform(${swipeFn(a.direction)}())\n`;
55
+ break;
56
+ }
57
+ });
58
+
59
+ code += `}\n`;
60
+ return code;
61
+ };
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
- export { TestFramework } from './types';
1
+ export { TestFramework, MOBILE_FRAMEWORKS } from './types';
2
+ export type { TestOptions } from './types';
2
3
  export { generateBrowserTests } from './core';
@@ -0,0 +1,146 @@
1
+ import {
2
+ EventType,
3
+ IncrementalSource,
4
+ MouseInteractions,
5
+ type eventWithTime,
6
+ type fullSnapshotEvent,
7
+ type inputData,
8
+ type mouseInteractionData,
9
+ type scrollData,
10
+ } from '@rrweb/types';
11
+ import { buildNodeMapFromFullSnapshots } from '../utils';
12
+ import type { SerializedNodeWithId } from '../types';
13
+
14
+ export type MobileLocatorStrategy = 'id' | 'accessibility' | 'text';
15
+
16
+ export interface MobileLocator {
17
+ strategy: MobileLocatorStrategy;
18
+ value: string;
19
+ }
20
+
21
+ export type MobileAction =
22
+ | { kind: 'launch'; url?: string }
23
+ | { kind: 'tap'; locator?: MobileLocator }
24
+ | { kind: 'input'; locator?: MobileLocator; text: string }
25
+ | { kind: 'swipe'; direction: 'up' | 'down' | 'left' | 'right' };
26
+
27
+ /** Native `resource-id` values often look like `com.app:id/foo` — keep the leaf. */
28
+ export const resourceIdLeaf = (value: string): string => {
29
+ const slash = value.lastIndexOf('/');
30
+ return slash >= 0 ? value.slice(slash + 1) : value;
31
+ };
32
+
33
+ /**
34
+ * Derive the most reliable locator for a native element from its captured
35
+ * attributes, preferring a stable id, then an accessibility label, then text.
36
+ */
37
+ export const mobileLocator = (
38
+ node?: SerializedNodeWithId,
39
+ ): MobileLocator | undefined => {
40
+ if (!node) return undefined;
41
+ const a = node.attributes ?? {};
42
+
43
+ const id =
44
+ a['resource-id'] ??
45
+ a['resourceId'] ??
46
+ a['testID'] ??
47
+ a['data-testid'] ??
48
+ a.id;
49
+ if (id) return { strategy: 'id', value: String(id) };
50
+
51
+ const accessibility =
52
+ a['content-desc'] ??
53
+ a['contentDescription'] ??
54
+ a['accessibilityIdentifier'] ??
55
+ a['accessibilityLabel'] ??
56
+ a['aria-label'] ??
57
+ a['name'];
58
+ if (accessibility)
59
+ return { strategy: 'accessibility', value: String(accessibility) };
60
+
61
+ const text =
62
+ a['text'] ??
63
+ (node.childNodes ?? [])
64
+ .map((n) => (n as any)?.textContent as string | undefined)
65
+ .filter(Boolean)
66
+ .join(' ')
67
+ .trim();
68
+ if (text) return { strategy: 'text', value: String(text) };
69
+
70
+ return undefined;
71
+ };
72
+
73
+ const swipeDirection = (
74
+ d: scrollData | { x?: number; y?: number },
75
+ ): 'up' | 'down' | 'left' | 'right' => {
76
+ const x = (d as any).x ?? 0;
77
+ const y = (d as any).y ?? 0;
78
+ if (Math.abs(y) >= Math.abs(x)) return y >= 0 ? 'up' : 'down';
79
+ return x >= 0 ? 'left' : 'right';
80
+ };
81
+
82
+ /**
83
+ * Walk the rrweb event stream and produce an ordered list of high-level mobile
84
+ * actions (launch / tap / input / swipe). Shared by every mobile generator so
85
+ * the frameworks only differ in how they render each action.
86
+ */
87
+ export const extractMobileActions = (
88
+ events: Array<eventWithTime | string>,
89
+ ): MobileAction[] => {
90
+ const actions: MobileAction[] = [];
91
+
92
+ const fullSnapshots = events.filter(
93
+ (event) => (event as eventWithTime).type === EventType.FullSnapshot,
94
+ ) as fullSnapshotEvent[];
95
+ const nodeMap = buildNodeMapFromFullSnapshots(fullSnapshots);
96
+
97
+ events.forEach((event) => {
98
+ const e = event as eventWithTime;
99
+ if (e.type === EventType.Meta) {
100
+ if ((e.data as any)?.href)
101
+ actions.push({ kind: 'launch', url: (e.data as any).href });
102
+ return;
103
+ }
104
+ if (e.type !== EventType.IncrementalSnapshot) return;
105
+
106
+ const data = e.data;
107
+ switch (data.source) {
108
+ case IncrementalSource.MouseInteraction: {
109
+ const d = data as mouseInteractionData;
110
+ if (
111
+ d.type === MouseInteractions.Click ||
112
+ d.type === MouseInteractions.TouchEnd
113
+ ) {
114
+ actions.push({
115
+ kind: 'tap',
116
+ locator: mobileLocator(nodeMap.get(d.id)),
117
+ });
118
+ }
119
+ break;
120
+ }
121
+ case IncrementalSource.Input: {
122
+ const d = data as inputData;
123
+ if (typeof d.text === 'string') {
124
+ actions.push({
125
+ kind: 'input',
126
+ locator: mobileLocator(nodeMap.get(d.id)),
127
+ text: d.text,
128
+ });
129
+ }
130
+ break;
131
+ }
132
+ case IncrementalSource.Scroll:
133
+ case IncrementalSource.TouchMove: {
134
+ actions.push({
135
+ kind: 'swipe',
136
+ direction: swipeDirection(data as scrollData),
137
+ });
138
+ break;
139
+ }
140
+ default:
141
+ break;
142
+ }
143
+ });
144
+
145
+ return actions;
146
+ };
@@ -11,7 +11,7 @@ import {
11
11
  type scrollData,
12
12
  type viewportResizeData,
13
13
  } from '@rrweb/types';
14
- import { buildNodeMapFromFullSnapshots, indent } from '../utils';
14
+ import { buildNodeMapFromFullSnapshots, cssSelector, indent } from '../utils';
15
15
 
16
16
  export const generatePlaywrightTests = (
17
17
  events: Array<eventWithTime | string>,
@@ -47,7 +47,8 @@ export const generatePlaywrightTests = (
47
47
  const type = data.source;
48
48
  let d;
49
49
  switch (type) {
50
- case IncrementalSource.MouseMove || IncrementalSource.TouchMove:
50
+ case IncrementalSource.MouseMove:
51
+ case IncrementalSource.TouchMove:
51
52
  d = data as mousemoveData;
52
53
  if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
53
54
  code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});\n`;
@@ -58,7 +59,6 @@ export const generatePlaywrightTests = (
58
59
  d = data as mouseInteractionData;
59
60
  if (d.type === MouseInteractions.Click) {
60
61
  const clickNode = nodeMap.get(d.id);
61
- console.log(clickNode);
62
62
  const id = clickNode?.attributes?.id
63
63
  ? `#${clickNode?.attributes?.id}`
64
64
  : clickNode?.tagName === 'nav'
@@ -75,7 +75,7 @@ export const generatePlaywrightTests = (
75
75
  ?.map((node) => (node as any)?.['textContent'])
76
76
  .join(' ')}")`
77
77
  : clickNode !== undefined
78
- ? `${clickNode?.tagName}.${clickNode?.attributes?.class}`
78
+ ? cssSelector(clickNode)
79
79
  : undefined;
80
80
 
81
81
  if (id && d.x && d.y) {
@@ -11,7 +11,7 @@ import {
11
11
  type scrollData,
12
12
  type viewportResizeData,
13
13
  } from '@rrweb/types';
14
- import { buildNodeMapFromFullSnapshots, indent } from '../utils';
14
+ import { buildNodeMapFromFullSnapshots, cssSelector, indent } from '../utils';
15
15
 
16
16
  export const generatePuppeteerTests = (
17
17
  events: Array<eventWithTime | string>,
@@ -54,7 +54,8 @@ export const generatePuppeteerTests = (
54
54
  const type = data.source;
55
55
  let d;
56
56
  switch (type) {
57
- case IncrementalSource.MouseMove || IncrementalSource.TouchMove:
57
+ case IncrementalSource.MouseMove:
58
+ case IncrementalSource.TouchMove:
58
59
  d = data as mousemoveData;
59
60
  if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
60
61
  code += `${indent(2)}await page.mouse.move(${d.positions[0].x}, ${d.positions[0].y});\n`;
@@ -65,7 +66,6 @@ export const generatePuppeteerTests = (
65
66
  d = data as mouseInteractionData;
66
67
  if (d.type === MouseInteractions.Click) {
67
68
  const clickNode = nodeMap.get(d.id);
68
- console.log(clickNode);
69
69
  const id = clickNode?.attributes?.id
70
70
  ? `#${clickNode?.attributes?.id}`
71
71
  : clickNode?.tagName === 'nav'
@@ -82,7 +82,7 @@ export const generatePuppeteerTests = (
82
82
  ?.map((node) => (node as any)?.['textContent'])
83
83
  .join(' ')}")`
84
84
  : clickNode !== undefined
85
- ? `${clickNode?.tagName}.${clickNode?.attributes?.class}`
85
+ ? cssSelector(clickNode)
86
86
  : undefined;
87
87
 
88
88
  if (id) {
@@ -11,7 +11,7 @@ import {
11
11
  type scrollData,
12
12
  type viewportResizeData,
13
13
  } from '@rrweb/types';
14
- import { buildNodeMapFromFullSnapshots, indent } from '../utils';
14
+ import { buildNodeMapFromFullSnapshots, cssSelector, indent } from '../utils';
15
15
 
16
16
  export const generateSeleniumTests = (
17
17
  events: Array<eventWithTime | string>,
@@ -53,7 +53,8 @@ export const generateSeleniumTests = (
53
53
  const type = data.source;
54
54
  let d;
55
55
  switch (type) {
56
- case IncrementalSource.MouseMove || IncrementalSource.TouchMove:
56
+ case IncrementalSource.MouseMove:
57
+ case IncrementalSource.TouchMove:
57
58
  d = data as mousemoveData;
58
59
  if (d.positions?.[0]?.x && d.positions?.[0]?.y) {
59
60
  code += `${indent(2)}await driver.actions().move({ x: ${d.positions[0].x}, y: ${d.positions[0].y} }).perform();\n`;
@@ -80,7 +81,7 @@ export const generateSeleniumTests = (
80
81
  ?.map((node) => (node as any)?.['textContent'])
81
82
  .join(' ')}")`
82
83
  : clickNode !== undefined
83
- ? `${clickNode?.tagName}.${clickNode?.attributes?.class}`
84
+ ? cssSelector(clickNode)
84
85
  : undefined;
85
86
  if (id) {
86
87
  code += `${indent(2)}await driver.findElement(By.css('${id}')).click();\n`;
package/src/types.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  export type TestOptions = {
2
- framework: 'playwright' | 'puppeteer' | 'cypress' | 'selenium';
2
+ framework:
3
+ | 'playwright'
4
+ | 'puppeteer'
5
+ | 'cypress'
6
+ | 'selenium'
7
+ | 'appium'
8
+ | 'espresso'
9
+ | 'xcuitest'
10
+ | 'detox';
3
11
  };
4
12
 
5
13
  export type SerializedNodeWithId = {
@@ -14,4 +22,16 @@ export const TestFramework = {
14
22
  PUPPETEER: 'puppeteer',
15
23
  CYPRESS: 'cypress',
16
24
  SELENIUM: 'selenium',
17
- };
25
+ APPIUM: 'appium',
26
+ ESPRESSO: 'espresso',
27
+ XCUITEST: 'xcuitest',
28
+ DETOX: 'detox',
29
+ } as const;
30
+
31
+ /** Frameworks that target native mobile apps (vs. web browsers). */
32
+ export const MOBILE_FRAMEWORKS = [
33
+ 'appium',
34
+ 'espresso',
35
+ 'xcuitest',
36
+ 'detox',
37
+ ] as const;
package/src/utils.ts CHANGED
@@ -2,6 +2,41 @@ import type { fullSnapshotEvent } from '@rrweb/types';
2
2
  import type { SerializedNodeWithId } from './types';
3
3
 
4
4
  export const indent = (level: number) => ' '.repeat(level);
5
+
6
+ /**
7
+ * Builds a safe CSS selector for a node. Handles the common cases:
8
+ * an `id`, multiple space-separated classes (joined with `.`), links/nav
9
+ * with their text, or a bare tag name — never emits `tag.undefined`.
10
+ */
11
+ export const cssSelector = (
12
+ node?: SerializedNodeWithId,
13
+ ): string | undefined => {
14
+ if (!node?.tagName) return undefined;
15
+ const attrs = node.attributes ?? {};
16
+ if (attrs.id) return `#${attrs.id}`;
17
+
18
+ const text = (node.childNodes ?? [])
19
+ .map((n) => (n as any)?.textContent as string | undefined)
20
+ .filter(Boolean)
21
+ .join(' ')
22
+ .trim();
23
+
24
+ if (node.tagName === 'a' && text) return `a:has-text("${text}")`;
25
+
26
+ const cls = (attrs.class as string | undefined)?.trim();
27
+ if (cls) {
28
+ const chain = cls
29
+ .split(/\s+/)
30
+ .filter(Boolean)
31
+ // CSS.escape-lite: guard classes that start with a digit or contain
32
+ // characters that aren't valid in a bare class selector.
33
+ .map((c) => (/^[A-Za-z_-][\w-]*$/.test(c) ? c : `[class~="${c}"]`))
34
+ .map((c) => (c.startsWith('[') ? c : `.${c}`))
35
+ .join('');
36
+ return `${node.tagName}${chain}`;
37
+ }
38
+ return node.tagName;
39
+ };
5
40
  /**
6
41
  * Builds a map of all nodes by their IDs from a FullSnapshotEvent.
7
42
  * @param rootNode - The root node of the snapshot tree.
@@ -0,0 +1,58 @@
1
+ import type { eventWithTime } from '@rrweb/types';
2
+ import { indent } from '../utils';
3
+ import { extractMobileActions, type MobileLocator } from '../mobile/shared';
4
+
5
+ const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
6
+
7
+ /** Swift XCUIElement query for a tap target. */
8
+ const tapTarget = (loc?: MobileLocator): string => {
9
+ if (!loc) return `app.buttons["TODO_add_accessibility_identifier"]`;
10
+ if (loc.strategy === 'text') return `app.staticTexts["${esc(loc.value)}"]`;
11
+ return `app.buttons["${esc(loc.value)}"]`;
12
+ };
13
+
14
+ const inputTarget = (loc?: MobileLocator): string => {
15
+ if (!loc) return `app.textFields["TODO_add_accessibility_identifier"]`;
16
+ return `app.textFields["${esc(loc.value)}"]`;
17
+ };
18
+
19
+ const swipeFn = (direction: 'up' | 'down' | 'left' | 'right') =>
20
+ ({
21
+ up: 'swipeUp',
22
+ down: 'swipeDown',
23
+ left: 'swipeLeft',
24
+ right: 'swipeRight',
25
+ })[direction];
26
+
27
+ /** XCUITest (Swift) mobile test from a session recording. */
28
+ export const generateXcuiTests = (
29
+ events: Array<eventWithTime | string>,
30
+ ): string => {
31
+ const actions = extractMobileActions(events);
32
+ let code = '';
33
+
34
+ code += `// XCUITest (Swift) — generated from a session recording\n`;
35
+ code += `func testReplaySession() {\n`;
36
+ code += `${indent(2)}let app = XCUIApplication()\n`;
37
+ code += `${indent(2)}app.launch()\n`;
38
+
39
+ actions.forEach((a) => {
40
+ switch (a.kind) {
41
+ case 'launch':
42
+ break; // already launched above
43
+ case 'tap':
44
+ code += `${indent(2)}${tapTarget(a.locator)}.tap()\n`;
45
+ break;
46
+ case 'input':
47
+ code += `${indent(2)}${inputTarget(a.locator)}.tap()\n`;
48
+ code += `${indent(2)}${inputTarget(a.locator)}.typeText("${esc(a.text)}")\n`;
49
+ break;
50
+ case 'swipe':
51
+ code += `${indent(2)}app.${swipeFn(a.direction)}()\n`;
52
+ break;
53
+ }
54
+ });
55
+
56
+ code += `}\n`;
57
+ return code;
58
+ };