@flrande/browserctl 0.5.0-dev.22.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/client.d.ts +34 -0
  2. package/dist/client.js +138 -0
  3. package/dist/commandRegistry.d.ts +16 -0
  4. package/dist/commandRegistry.js +21 -0
  5. package/dist/help.d.ts +4 -0
  6. package/dist/help.js +24 -0
  7. package/dist/index.d.ts +3 -0
  8. package/dist/index.js +23 -0
  9. package/dist/runCli.d.ts +5 -0
  10. package/dist/runCli.js +170 -0
  11. package/package.json +32 -59
  12. package/INSTALL-CN.md +0 -92
  13. package/INSTALL.md +0 -92
  14. package/LICENSE +0 -21
  15. package/README-CN.md +0 -69
  16. package/README.md +0 -69
  17. package/apps/browserctl/src/commands/a11y-snapshot.ts +0 -20
  18. package/apps/browserctl/src/commands/act.test.ts +0 -71
  19. package/apps/browserctl/src/commands/act.ts +0 -64
  20. package/apps/browserctl/src/commands/command-wrappers.test.ts +0 -688
  21. package/apps/browserctl/src/commands/common.test.ts +0 -87
  22. package/apps/browserctl/src/commands/common.ts +0 -191
  23. package/apps/browserctl/src/commands/console-list.test.ts +0 -102
  24. package/apps/browserctl/src/commands/console-list.ts +0 -108
  25. package/apps/browserctl/src/commands/cookie-clear.ts +0 -18
  26. package/apps/browserctl/src/commands/cookie-get.ts +0 -18
  27. package/apps/browserctl/src/commands/cookie-set.ts +0 -22
  28. package/apps/browserctl/src/commands/dialog-arm.ts +0 -20
  29. package/apps/browserctl/src/commands/dom-query-all.ts +0 -18
  30. package/apps/browserctl/src/commands/dom-query.ts +0 -18
  31. package/apps/browserctl/src/commands/download-trigger.ts +0 -22
  32. package/apps/browserctl/src/commands/download-wait.test.ts +0 -67
  33. package/apps/browserctl/src/commands/download-wait.ts +0 -27
  34. package/apps/browserctl/src/commands/element-screenshot.ts +0 -20
  35. package/apps/browserctl/src/commands/frame-list.ts +0 -16
  36. package/apps/browserctl/src/commands/frame-snapshot.ts +0 -18
  37. package/apps/browserctl/src/commands/har-export.test.ts +0 -112
  38. package/apps/browserctl/src/commands/har-export.ts +0 -120
  39. package/apps/browserctl/src/commands/memory-delete.ts +0 -20
  40. package/apps/browserctl/src/commands/memory-inspect.ts +0 -20
  41. package/apps/browserctl/src/commands/memory-list.ts +0 -90
  42. package/apps/browserctl/src/commands/memory-mode-set.ts +0 -29
  43. package/apps/browserctl/src/commands/memory-purge.ts +0 -16
  44. package/apps/browserctl/src/commands/memory-resolve.ts +0 -56
  45. package/apps/browserctl/src/commands/memory-status.ts +0 -16
  46. package/apps/browserctl/src/commands/memory-ttl-set.ts +0 -28
  47. package/apps/browserctl/src/commands/memory-upsert.ts +0 -142
  48. package/apps/browserctl/src/commands/network-list.test.ts +0 -110
  49. package/apps/browserctl/src/commands/network-list.ts +0 -112
  50. package/apps/browserctl/src/commands/network-wait-for.test.ts +0 -90
  51. package/apps/browserctl/src/commands/network-wait-for.ts +0 -100
  52. package/apps/browserctl/src/commands/profile-list.ts +0 -16
  53. package/apps/browserctl/src/commands/profile-use.ts +0 -18
  54. package/apps/browserctl/src/commands/response-body.ts +0 -24
  55. package/apps/browserctl/src/commands/screenshot.ts +0 -16
  56. package/apps/browserctl/src/commands/session-drop.test.ts +0 -36
  57. package/apps/browserctl/src/commands/session-drop.ts +0 -16
  58. package/apps/browserctl/src/commands/session-list.test.ts +0 -81
  59. package/apps/browserctl/src/commands/session-list.ts +0 -70
  60. package/apps/browserctl/src/commands/snapshot.ts +0 -16
  61. package/apps/browserctl/src/commands/status.ts +0 -10
  62. package/apps/browserctl/src/commands/storage-get.ts +0 -20
  63. package/apps/browserctl/src/commands/storage-set.ts +0 -22
  64. package/apps/browserctl/src/commands/tab-close.ts +0 -20
  65. package/apps/browserctl/src/commands/tab-focus.ts +0 -20
  66. package/apps/browserctl/src/commands/tab-open.ts +0 -19
  67. package/apps/browserctl/src/commands/tabs.ts +0 -13
  68. package/apps/browserctl/src/commands/trace-get.test.ts +0 -61
  69. package/apps/browserctl/src/commands/trace-get.ts +0 -62
  70. package/apps/browserctl/src/commands/upload-arm.ts +0 -26
  71. package/apps/browserctl/src/commands/wait-element.test.ts +0 -80
  72. package/apps/browserctl/src/commands/wait-element.ts +0 -76
  73. package/apps/browserctl/src/commands/wait-text.test.ts +0 -110
  74. package/apps/browserctl/src/commands/wait-text.ts +0 -93
  75. package/apps/browserctl/src/commands/wait-url.test.ts +0 -80
  76. package/apps/browserctl/src/commands/wait-url.ts +0 -76
  77. package/apps/browserctl/src/daemon-client.test.ts +0 -512
  78. package/apps/browserctl/src/daemon-client.ts +0 -632
  79. package/apps/browserctl/src/e2e.test.ts +0 -103
  80. package/apps/browserctl/src/main.dispatch.test.ts +0 -461
  81. package/apps/browserctl/src/main.test.ts +0 -334
  82. package/apps/browserctl/src/main.ts +0 -957
  83. package/apps/browserctl/src/smoke.e2e.test.ts +0 -97
  84. package/apps/browserctl/src/test-port.ts +0 -26
  85. package/apps/browserd/src/bootstrap.ts +0 -432
  86. package/apps/browserd/src/chrome-relay-extension-bridge.test.ts +0 -250
  87. package/apps/browserd/src/chrome-relay-extension-bridge.ts +0 -506
  88. package/apps/browserd/src/container.ts +0 -3088
  89. package/apps/browserd/src/main.test.ts +0 -1522
  90. package/apps/browserd/src/main.ts +0 -7
  91. package/apps/browserd/src/test-port.ts +0 -26
  92. package/apps/browserd/src/tool-matrix.test.ts +0 -887
  93. package/bin/browserctl.cjs +0 -21
  94. package/bin/browserd.cjs +0 -21
  95. package/extensions/chrome-relay/README-CN.md +0 -39
  96. package/extensions/chrome-relay/README.md +0 -39
  97. package/extensions/chrome-relay/background.js +0 -1687
  98. package/extensions/chrome-relay/manifest.json +0 -15
  99. package/extensions/chrome-relay/popup.html +0 -369
  100. package/extensions/chrome-relay/popup.js +0 -972
  101. package/packages/core/src/bootstrap.test.ts +0 -10
  102. package/packages/core/src/driver-registry.test.ts +0 -45
  103. package/packages/core/src/driver-registry.ts +0 -22
  104. package/packages/core/src/driver.ts +0 -47
  105. package/packages/core/src/index.ts +0 -6
  106. package/packages/core/src/navigation-memory.test.ts +0 -259
  107. package/packages/core/src/navigation-memory.ts +0 -360
  108. package/packages/core/src/ref-cache.test.ts +0 -61
  109. package/packages/core/src/ref-cache.ts +0 -28
  110. package/packages/core/src/session-store.test.ts +0 -82
  111. package/packages/core/src/session-store.ts +0 -138
  112. package/packages/core/src/types.ts +0 -9
  113. package/packages/driver-chrome-relay/src/chrome-relay-driver.test.ts +0 -744
  114. package/packages/driver-chrome-relay/src/chrome-relay-driver.ts +0 -2429
  115. package/packages/driver-chrome-relay/src/chrome-relay-extension-runtime.test.ts +0 -264
  116. package/packages/driver-chrome-relay/src/chrome-relay-extension-runtime.ts +0 -521
  117. package/packages/driver-chrome-relay/src/index.ts +0 -26
  118. package/packages/driver-managed/src/index.ts +0 -22
  119. package/packages/driver-managed/src/managed-driver.test.ts +0 -183
  120. package/packages/driver-managed/src/managed-driver.ts +0 -341
  121. package/packages/driver-managed/src/managed-local-driver.test.ts +0 -608
  122. package/packages/driver-managed/src/managed-local-driver.ts +0 -2243
  123. package/packages/driver-remote-cdp/src/index.ts +0 -19
  124. package/packages/driver-remote-cdp/src/remote-cdp-driver.test.ts +0 -727
  125. package/packages/driver-remote-cdp/src/remote-cdp-driver.ts +0 -2264
  126. package/packages/protocol/src/envelope.test.ts +0 -25
  127. package/packages/protocol/src/envelope.ts +0 -31
  128. package/packages/protocol/src/errors.test.ts +0 -17
  129. package/packages/protocol/src/errors.ts +0 -11
  130. package/packages/protocol/src/index.ts +0 -3
  131. package/packages/protocol/src/tools.ts +0 -3
  132. package/packages/transport-mcp-stdio/src/index.ts +0 -3
  133. package/packages/transport-mcp-stdio/src/sdk-server.ts +0 -139
  134. package/packages/transport-mcp-stdio/src/server.test.ts +0 -281
  135. package/packages/transport-mcp-stdio/src/server.ts +0 -183
  136. package/packages/transport-mcp-stdio/src/tool-map.ts +0 -84
@@ -1,2429 +0,0 @@
1
- import type {
2
- BrowserDriver,
3
- BrowserDriverScreenshot,
4
- DriverObject
5
- } from "../../core/src/driver";
6
- import type { ProfileId, TargetId } from "../../core/src/types";
7
-
8
- export type ChromeRelayConsoleEntryLocation = {
9
- url?: string;
10
- lineNumber?: number;
11
- columnNumber?: number;
12
- };
13
-
14
- export type ChromeRelayConsoleEntry = {
15
- type: string;
16
- text: string;
17
- timestamp: string;
18
- location?: ChromeRelayConsoleEntryLocation;
19
- };
20
-
21
- export type ChromeRelayNetworkRequestSummary = {
22
- requestId: string;
23
- url: string;
24
- method?: string;
25
- resourceType?: string;
26
- status?: number;
27
- timestamp: string;
28
- };
29
-
30
- export type ChromeRelayNetworkResponseBody = {
31
- body: string;
32
- encoding: "utf8" | "base64";
33
- };
34
-
35
- export type ChromeRelaySnapshot = {
36
- kind: "chrome-relay";
37
- profile: ProfileId;
38
- targetId: TargetId;
39
- relayUrl: string;
40
- hasTarget: boolean;
41
- url?: string;
42
- title?: string;
43
- html?: string;
44
- requestSummaries?: ChromeRelayNetworkRequestSummary[];
45
- };
46
-
47
- export type ChromeRelayScreenshot = {
48
- kind: "chrome-relay";
49
- profile: ProfileId;
50
- targetId: TargetId;
51
- relayUrl: string;
52
- hasTarget: boolean;
53
- mimeType?: string;
54
- encoding?: "base64";
55
- imageBase64?: string;
56
- width?: number;
57
- height?: number;
58
- };
59
-
60
- export type ChromeRelayTelemetryDriverExtensions = {
61
- getConsoleEntries?(targetId: TargetId, profile?: ProfileId): ChromeRelayConsoleEntry[];
62
- getNetworkResponseBody?(
63
- requestId: string,
64
- targetId: TargetId,
65
- profile?: ProfileId
66
- ): ChromeRelayNetworkResponseBody | undefined;
67
- };
68
-
69
- export type ChromeRelayLocator = {
70
- click(): Promise<void>;
71
- fill(value: string): Promise<void>;
72
- type(value: string): Promise<void>;
73
- };
74
-
75
- export type ChromeRelayKeyboard = {
76
- press(key: string): Promise<void>;
77
- };
78
-
79
- export type ChromeRelayPage = {
80
- goto(url: string): Promise<void>;
81
- bringToFront(): Promise<void>;
82
- close(): Promise<void>;
83
- url(): string;
84
- title(): Promise<string>;
85
- content(): Promise<string>;
86
- screenshot?(options?: Record<string, unknown>): Promise<unknown>;
87
- domQuery?(selector: string): Promise<unknown>;
88
- domQueryAll?(selector: string): Promise<unknown>;
89
- elementScreenshot?(selector: string): Promise<unknown>;
90
- a11ySnapshot?(selector?: string): Promise<unknown>;
91
- cookieGet?(name?: string): Promise<unknown>;
92
- cookieSet?(cookie: { name: string; value: string; url?: string }): Promise<unknown>;
93
- cookieClear?(name?: string): Promise<unknown>;
94
- storageGet?(scope: string, key: string): Promise<unknown>;
95
- storageSet?(scope: string, key: string, value: string): Promise<unknown>;
96
- frameList?(): Promise<unknown>;
97
- frameSnapshot?(frameId: string): Promise<unknown>;
98
- scroll?(deltaX?: number, deltaY?: number): Promise<unknown>;
99
- locator(selector: string): ChromeRelayLocator;
100
- route?(url: string, handler: ChromeRelayNetworkMockHandler): Promise<void>;
101
- unroute?(url: string, handler?: ChromeRelayNetworkMockHandler): Promise<void>;
102
- keyboard?: ChromeRelayKeyboard;
103
- on?(eventName: string, listener: (payload: unknown) => unknown): void;
104
- };
105
-
106
- export type ChromeRelayBrowserContext = {
107
- newPage(): Promise<ChromeRelayPage>;
108
- close?(): Promise<void>;
109
- };
110
-
111
- export type ChromeRelayBrowser = {
112
- contexts(): ChromeRelayBrowserContext[];
113
- newContext?(): Promise<ChromeRelayBrowserContext>;
114
- close(): Promise<void>;
115
- };
116
-
117
- export type ChromeRelayDriverRuntime = {
118
- connectOverCDP(endpointUrl: string): Promise<ChromeRelayBrowser>;
119
- fetchJson?(url: string): Promise<unknown>;
120
- isConnected?(): boolean | Promise<boolean>;
121
- };
122
-
123
- export type ChromeRelayDriverConfig = {
124
- relayUrl?: string;
125
- runtime?: ChromeRelayDriverRuntime;
126
- };
127
-
128
- export type ChromeRelayDriverStatus = {
129
- kind: "chrome-relay";
130
- connected: boolean;
131
- relayUrl: string;
132
- };
133
-
134
- const DEFAULT_PROFILE_ID: ProfileId = "profile:chrome-relay:default";
135
- const DEFAULT_RELAY_URL = "http://127.0.0.1:9223";
136
- const TELEMETRY_EVENT_LIMIT = 200;
137
-
138
- type ChromeRelayTab = {
139
- url: string;
140
- page: ChromeRelayPage;
141
- };
142
-
143
- type ChromeRelayProfileState = {
144
- nextTargetNumber: number;
145
- tabs: Map<TargetId, ChromeRelayTab>;
146
- tabOrder: TargetId[];
147
- focusedTargetId?: TargetId;
148
- };
149
-
150
- type ChromeRelayTargetOperationState = {
151
- uploadFiles: string[];
152
- dialogArmedCount: number;
153
- triggerCount: number;
154
- nextNetworkMockNumber: number;
155
- networkMocks: Map<string, ChromeRelayNetworkMockBinding>;
156
- requestedDownloadPath?: string;
157
- downloadInFlight?: Promise<ChromeRelayDownloadArtifact>;
158
- latestDownload?: ChromeRelayDownloadArtifact;
159
- latestRawDownload?: unknown;
160
- };
161
-
162
- type ChromeRelayDownloadArtifact = {
163
- path: string;
164
- suggestedFilename?: string;
165
- url?: string;
166
- mimeType?: string;
167
- };
168
-
169
- type ChromeRelayNetworkMockHandler = (...args: unknown[]) => Promise<void>;
170
- type ChromeRelayNetworkMockBinding = {
171
- urlPattern: string;
172
- handler: ChromeRelayNetworkMockHandler;
173
- };
174
-
175
- type ChromeRelayTargetTelemetryState = {
176
- consoleEntries: ChromeRelayConsoleEntry[];
177
- requestSummaries: ChromeRelayNetworkRequestSummary[];
178
- networkResponseBodies: Map<string, ChromeRelayNetworkResponseBody>;
179
- nextRequestNumber: number;
180
- };
181
-
182
- function resolveProfileId(profile?: ProfileId): ProfileId {
183
- return profile ?? DEFAULT_PROFILE_ID;
184
- }
185
-
186
- function createTargetId(profileId: ProfileId, targetNumber: number): TargetId {
187
- return `target:chrome-relay:${profileId}:${targetNumber}`;
188
- }
189
-
190
- function createProfileState(): ChromeRelayProfileState {
191
- return {
192
- nextTargetNumber: 1,
193
- tabs: new Map<TargetId, ChromeRelayTab>(),
194
- tabOrder: []
195
- };
196
- }
197
-
198
- function createTargetOperationState(): ChromeRelayTargetOperationState {
199
- return {
200
- uploadFiles: [],
201
- dialogArmedCount: 0,
202
- triggerCount: 0,
203
- nextNetworkMockNumber: 1,
204
- networkMocks: new Map<string, ChromeRelayNetworkMockBinding>()
205
- };
206
- }
207
-
208
- function createTargetTelemetryState(): ChromeRelayTargetTelemetryState {
209
- return {
210
- consoleEntries: [],
211
- requestSummaries: [],
212
- networkResponseBodies: new Map<string, ChromeRelayNetworkResponseBody>(),
213
- nextRequestNumber: 1
214
- };
215
- }
216
-
217
- function trimConsoleEntries(telemetryState: ChromeRelayTargetTelemetryState): void {
218
- if (telemetryState.consoleEntries.length <= TELEMETRY_EVENT_LIMIT) {
219
- return;
220
- }
221
-
222
- telemetryState.consoleEntries.splice(
223
- 0,
224
- telemetryState.consoleEntries.length - TELEMETRY_EVENT_LIMIT
225
- );
226
- }
227
-
228
- function trimNetworkTelemetry(telemetryState: ChromeRelayTargetTelemetryState): void {
229
- if (telemetryState.requestSummaries.length > TELEMETRY_EVENT_LIMIT) {
230
- const removedSummaries = telemetryState.requestSummaries.splice(
231
- 0,
232
- telemetryState.requestSummaries.length - TELEMETRY_EVENT_LIMIT
233
- );
234
- for (const removed of removedSummaries) {
235
- telemetryState.networkResponseBodies.delete(removed.requestId);
236
- }
237
- }
238
-
239
- const knownRequestIds = new Set(
240
- telemetryState.requestSummaries.map((summary) => summary.requestId)
241
- );
242
- for (const requestId of telemetryState.networkResponseBodies.keys()) {
243
- if (!knownRequestIds.has(requestId)) {
244
- telemetryState.networkResponseBodies.delete(requestId);
245
- }
246
- }
247
- }
248
-
249
- function sanitizePathSegment(value: string): string {
250
- return value.replace(/[^a-zA-Z0-9._-]+/g, "_");
251
- }
252
-
253
- function createDownloadPath(profileId: ProfileId, targetId: TargetId, triggerCount: number): string {
254
- return `chrome-relay-${sanitizePathSegment(profileId)}-${sanitizePathSegment(targetId)}-${triggerCount}.bin`;
255
- }
256
-
257
- function createRequestId(profileId: ProfileId, targetId: TargetId, requestNumber: number): string {
258
- return `request:chrome-relay:${encodeURIComponent(profileId)}:${encodeURIComponent(targetId)}:${requestNumber}`;
259
- }
260
-
261
- function parseRelayUrl(config?: ChromeRelayDriverConfig): string {
262
- const rawRelayUrl = config?.relayUrl === undefined ? DEFAULT_RELAY_URL : config.relayUrl.trim();
263
- if (rawRelayUrl.trim().length === 0) {
264
- throw new Error("Invalid relayUrl: value must not be empty.");
265
- }
266
-
267
- try {
268
- return new URL(rawRelayUrl).toString();
269
- } catch {
270
- throw new Error(`Invalid relayUrl: ${rawRelayUrl}`);
271
- }
272
- }
273
-
274
- function toErrorMessage(error: unknown): string {
275
- return error instanceof Error ? error.message : "Unexpected chrome-relay driver failure.";
276
- }
277
-
278
- function readActionPayloadString(payload: DriverObject | undefined, key: string): string | undefined {
279
- const value = payload?.[key];
280
- return typeof value === "string" && value.trim().length > 0 ? value : undefined;
281
- }
282
-
283
- function readActionPayloadNumber(payload: DriverObject | undefined, key: string): number | undefined {
284
- const value = payload?.[key];
285
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
286
- }
287
-
288
- function isObjectRecord(value: unknown): value is Record<string, unknown> {
289
- return typeof value === "object" && value !== null && !Array.isArray(value);
290
- }
291
-
292
- function readObjectMethod<TValue>(value: unknown, methodName: string): TValue | undefined {
293
- if (typeof value !== "object" || value === null) {
294
- return undefined;
295
- }
296
-
297
- const method = (value as Record<string, unknown>)[methodName];
298
- if (typeof method !== "function") {
299
- return undefined;
300
- }
301
-
302
- try {
303
- return (method as () => TValue).call(value);
304
- } catch {
305
- return undefined;
306
- }
307
- }
308
-
309
- function getObjectMethod(
310
- value: unknown,
311
- methodName: string
312
- ): ((...args: unknown[]) => unknown) | undefined {
313
- if (typeof value !== "object" || value === null) {
314
- return undefined;
315
- }
316
-
317
- const method = (value as Record<string, unknown>)[methodName];
318
- return typeof method === "function" ? (method as (...args: unknown[]) => unknown) : undefined;
319
- }
320
-
321
- function readObjectStringProperty(value: unknown, key: string): string | undefined {
322
- if (typeof value !== "object" || value === null) {
323
- return undefined;
324
- }
325
-
326
- const property = (value as Record<string, unknown>)[key];
327
- return typeof property === "string" ? property : undefined;
328
- }
329
-
330
- function readObjectNumberProperty(value: unknown, key: string): number | undefined {
331
- if (typeof value !== "object" || value === null) {
332
- return undefined;
333
- }
334
-
335
- const property = (value as Record<string, unknown>)[key];
336
- return typeof property === "number" ? property : undefined;
337
- }
338
-
339
- async function readRuntimeConnectionStatus(
340
- runtime: ChromeRelayDriverRuntime
341
- ): Promise<boolean | undefined> {
342
- if (typeof runtime.isConnected !== "function") {
343
- return undefined;
344
- }
345
-
346
- try {
347
- const connected = await runtime.isConnected();
348
- return typeof connected === "boolean" ? connected : undefined;
349
- } catch {
350
- return undefined;
351
- }
352
- }
353
-
354
- function readConsoleEntry(value: unknown): ChromeRelayConsoleEntry {
355
- const locationValue = readObjectMethod<unknown>(value, "location");
356
- const locationUrl = readObjectStringProperty(locationValue, "url");
357
- const locationLineNumber = readObjectNumberProperty(locationValue, "lineNumber");
358
- const locationColumnNumber = readObjectNumberProperty(locationValue, "columnNumber");
359
-
360
- const hasLocation =
361
- locationUrl !== undefined || locationLineNumber !== undefined || locationColumnNumber !== undefined;
362
-
363
- return {
364
- type: readObjectMethod<string>(value, "type") ?? "log",
365
- text: readObjectMethod<string>(value, "text") ?? "",
366
- timestamp: new Date().toISOString(),
367
- ...(hasLocation
368
- ? {
369
- location: {
370
- ...(locationUrl !== undefined ? { url: locationUrl } : {}),
371
- ...(locationLineNumber !== undefined ? { lineNumber: locationLineNumber } : {}),
372
- ...(locationColumnNumber !== undefined ? { columnNumber: locationColumnNumber } : {})
373
- }
374
- }
375
- : {})
376
- };
377
- }
378
-
379
- function readNetworkSummary(value: unknown, requestId: string): ChromeRelayNetworkRequestSummary {
380
- const requestValue = readObjectMethod<unknown>(value, "request");
381
- const method = readObjectMethod<string>(requestValue, "method");
382
- const resourceType = readObjectMethod<string>(requestValue, "resourceType");
383
- const status = readObjectMethod<number>(value, "status");
384
-
385
- return {
386
- requestId,
387
- url: readObjectMethod<string>(value, "url") ?? "",
388
- ...(typeof method === "string" ? { method } : {}),
389
- ...(typeof resourceType === "string" ? { resourceType } : {}),
390
- ...(typeof status === "number" ? { status } : {}),
391
- timestamp: new Date().toISOString()
392
- };
393
- }
394
-
395
- function toBase64(value: ArrayBuffer | Uint8Array): string {
396
- const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
397
- return Buffer.from(bytes).toString("base64");
398
- }
399
-
400
- function parseScreenshotBase64(
401
- value: string
402
- ): { mimeType: string; imageBase64: string } | undefined {
403
- const trimmedValue = value.trim();
404
- if (trimmedValue.length === 0) {
405
- return undefined;
406
- }
407
-
408
- const dataUrlMatch = /^data:([^;,]+);base64,(.+)$/i.exec(trimmedValue);
409
- if (dataUrlMatch !== null) {
410
- const mimeType = dataUrlMatch[1] ?? "image/png";
411
- const imageBase64 = dataUrlMatch[2] ?? "";
412
- if (imageBase64.length === 0) {
413
- return undefined;
414
- }
415
-
416
- return {
417
- mimeType,
418
- imageBase64
419
- };
420
- }
421
-
422
- return {
423
- mimeType: "image/png",
424
- imageBase64: trimmedValue
425
- };
426
- }
427
-
428
- type ChromeRelayScreenshotImage = {
429
- mimeType: string;
430
- encoding: "base64";
431
- imageBase64: string;
432
- width?: number;
433
- height?: number;
434
- };
435
-
436
- function toOptionalPositiveNumber(value: unknown): number | undefined {
437
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
438
- }
439
-
440
- function readScreenshotImage(value: unknown): ChromeRelayScreenshotImage | undefined {
441
- if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
442
- return {
443
- mimeType: "image/png",
444
- encoding: "base64",
445
- imageBase64: toBase64(value)
446
- };
447
- }
448
-
449
- if (typeof value === "string") {
450
- const parsed = parseScreenshotBase64(value);
451
- if (parsed === undefined) {
452
- return undefined;
453
- }
454
-
455
- return {
456
- mimeType: parsed.mimeType,
457
- encoding: "base64",
458
- imageBase64: parsed.imageBase64
459
- };
460
- }
461
-
462
- if (typeof value !== "object" || value === null) {
463
- return undefined;
464
- }
465
-
466
- const imageBase64 = readObjectStringProperty(value, "imageBase64");
467
- if (imageBase64 === undefined || imageBase64.trim().length === 0) {
468
- return undefined;
469
- }
470
-
471
- const rawEncoding = readObjectStringProperty(value, "encoding");
472
- if (rawEncoding !== undefined && rawEncoding !== "base64") {
473
- return undefined;
474
- }
475
-
476
- const mimeType = readObjectStringProperty(value, "mimeType") ?? "image/png";
477
- const width = toOptionalPositiveNumber(readObjectNumberProperty(value, "width"));
478
- const height = toOptionalPositiveNumber(readObjectNumberProperty(value, "height"));
479
-
480
- return {
481
- mimeType,
482
- encoding: "base64",
483
- imageBase64: imageBase64.trim(),
484
- ...(width !== undefined ? { width } : {}),
485
- ...(height !== undefined ? { height } : {})
486
- };
487
- }
488
-
489
- async function capturePageScreenshot(page: ChromeRelayPage): Promise<ChromeRelayScreenshotImage> {
490
- const screenshotMethod = getObjectMethod(page, "screenshot");
491
- if (typeof screenshotMethod !== "function") {
492
- throw new Error("Screenshot is not supported by this driver runtime.");
493
- }
494
-
495
- const screenshot = await screenshotMethod.call(page, {
496
- type: "png"
497
- });
498
- const parsedScreenshot = readScreenshotImage(screenshot);
499
- if (parsedScreenshot === undefined) {
500
- throw new Error("Unexpected screenshot payload from driver runtime.");
501
- }
502
-
503
- return parsedScreenshot;
504
- }
505
-
506
- type ChromeRelayCookie = {
507
- name: string;
508
- value: string;
509
- domain?: string;
510
- path?: string;
511
- expires?: number;
512
- httpOnly?: boolean;
513
- secure?: boolean;
514
- sameSite?: string;
515
- url?: string;
516
- };
517
-
518
- function normalizeCookies(value: unknown): ChromeRelayCookie[] {
519
- if (!Array.isArray(value)) {
520
- return [];
521
- }
522
-
523
- const cookies: ChromeRelayCookie[] = [];
524
- for (const item of value) {
525
- if (!isObjectRecord(item)) {
526
- continue;
527
- }
528
-
529
- const name = readObjectStringProperty(item, "name");
530
- const cookieValue = readObjectStringProperty(item, "value");
531
- if (name === undefined || cookieValue === undefined) {
532
- continue;
533
- }
534
-
535
- const domain = readObjectStringProperty(item, "domain");
536
- const path = readObjectStringProperty(item, "path");
537
- const sameSite = readObjectStringProperty(item, "sameSite");
538
- const url = readObjectStringProperty(item, "url");
539
- const expiresRaw = readObjectNumberProperty(item, "expires");
540
- const httpOnlyRaw = item.httpOnly;
541
- const secureRaw = item.secure;
542
-
543
- cookies.push({
544
- name,
545
- value: cookieValue,
546
- ...(domain !== undefined ? { domain } : {}),
547
- ...(path !== undefined ? { path } : {}),
548
- ...(typeof expiresRaw === "number" && Number.isFinite(expiresRaw) ? { expires: expiresRaw } : {}),
549
- ...(typeof httpOnlyRaw === "boolean" ? { httpOnly: httpOnlyRaw } : {}),
550
- ...(typeof secureRaw === "boolean" ? { secure: secureRaw } : {}),
551
- ...(sameSite !== undefined ? { sameSite } : {}),
552
- ...(url !== undefined ? { url } : {})
553
- });
554
- }
555
-
556
- return cookies;
557
- }
558
-
559
- function toCookieInput(cookie: ChromeRelayCookie): Record<string, unknown> | undefined {
560
- const base: Record<string, unknown> = {
561
- name: cookie.name,
562
- value: cookie.value
563
- };
564
-
565
- if (cookie.url !== undefined) {
566
- return {
567
- ...base,
568
- url: cookie.url,
569
- ...(cookie.expires !== undefined ? { expires: cookie.expires } : {}),
570
- ...(cookie.httpOnly !== undefined ? { httpOnly: cookie.httpOnly } : {}),
571
- ...(cookie.secure !== undefined ? { secure: cookie.secure } : {}),
572
- ...(cookie.sameSite !== undefined ? { sameSite: cookie.sameSite } : {})
573
- };
574
- }
575
-
576
- if (cookie.domain !== undefined && cookie.path !== undefined) {
577
- return {
578
- ...base,
579
- domain: cookie.domain,
580
- path: cookie.path,
581
- ...(cookie.expires !== undefined ? { expires: cookie.expires } : {}),
582
- ...(cookie.httpOnly !== undefined ? { httpOnly: cookie.httpOnly } : {}),
583
- ...(cookie.secure !== undefined ? { secure: cookie.secure } : {}),
584
- ...(cookie.sameSite !== undefined ? { sameSite: cookie.sameSite } : {})
585
- };
586
- }
587
-
588
- return undefined;
589
- }
590
-
591
- function parseStorageScope(scope: string | undefined): "local" | "session" | undefined {
592
- if (scope === "local" || scope === "session") {
593
- return scope;
594
- }
595
-
596
- return undefined;
597
- }
598
-
599
- function parseFrameIndex(frameId: string | undefined): number | undefined {
600
- if (typeof frameId !== "string") {
601
- return undefined;
602
- }
603
-
604
- const match = /^frame:(\d+)$/.exec(frameId.trim());
605
- if (match === null) {
606
- return undefined;
607
- }
608
-
609
- const parsed = Number.parseInt(match[1] ?? "", 10);
610
- return Number.isFinite(parsed) ? parsed : undefined;
611
- }
612
-
613
- async function evaluateInPage<TResult>(
614
- page: ChromeRelayPage,
615
- callback: (arg: unknown) => unknown,
616
- arg: unknown
617
- ): Promise<TResult> {
618
- const evaluateMethod = getObjectMethod(page, "evaluate");
619
- if (typeof evaluateMethod !== "function") {
620
- throw new Error("Driver runtime page does not support evaluate.");
621
- }
622
-
623
- const result = await evaluateMethod.call(page, callback, arg);
624
- return result as TResult;
625
- }
626
-
627
- async function readNetworkResponseBody(
628
- value: unknown
629
- ): Promise<ChromeRelayNetworkResponseBody | undefined> {
630
- const textMethod = getObjectMethod(value, "text");
631
- if (typeof textMethod === "function") {
632
- try {
633
- const textResult = await textMethod.call(value);
634
- if (typeof textResult === "string") {
635
- return {
636
- body: textResult,
637
- encoding: "utf8"
638
- };
639
- }
640
- } catch {
641
- // Ignore body extraction failures from optional runtime hooks.
642
- }
643
- }
644
-
645
- const bodyMethod = getObjectMethod(value, "body");
646
- if (typeof bodyMethod !== "function") {
647
- return undefined;
648
- }
649
-
650
- try {
651
- const bodyResult = await bodyMethod.call(value);
652
- if (typeof bodyResult === "string") {
653
- return {
654
- body: bodyResult,
655
- encoding: "utf8"
656
- };
657
- }
658
-
659
- if (bodyResult instanceof Uint8Array || bodyResult instanceof ArrayBuffer) {
660
- return {
661
- body: toBase64(bodyResult),
662
- encoding: "base64"
663
- };
664
- }
665
-
666
- return undefined;
667
- } catch {
668
- return undefined;
669
- }
670
- }
671
-
672
- function attachTelemetryListeners(
673
- page: ChromeRelayPage,
674
- profileId: ProfileId,
675
- targetId: TargetId,
676
- telemetryState: ChromeRelayTargetTelemetryState,
677
- operationState: ChromeRelayTargetOperationState
678
- ): void {
679
- if (typeof page.on !== "function") {
680
- return;
681
- }
682
-
683
- page.on("console", (message) => {
684
- telemetryState.consoleEntries.push(readConsoleEntry(message));
685
- trimConsoleEntries(telemetryState);
686
- });
687
-
688
- page.on("response", async (response) => {
689
- const requestId = createRequestId(profileId, targetId, telemetryState.nextRequestNumber);
690
- telemetryState.nextRequestNumber += 1;
691
- telemetryState.requestSummaries.push(readNetworkSummary(response, requestId));
692
- trimNetworkTelemetry(telemetryState);
693
-
694
- const body = await readNetworkResponseBody(response);
695
- if (body !== undefined) {
696
- telemetryState.networkResponseBodies.set(requestId, body);
697
- trimNetworkTelemetry(telemetryState);
698
- }
699
- });
700
-
701
- page.on("dialog", async (dialog) => {
702
- if (operationState.dialogArmedCount <= 0) {
703
- return;
704
- }
705
-
706
- operationState.dialogArmedCount -= 1;
707
- const acceptMethod = getObjectMethod(dialog, "accept");
708
- if (typeof acceptMethod === "function") {
709
- try {
710
- await acceptMethod.call(dialog);
711
- return;
712
- } catch {
713
- // Fall through to dismiss.
714
- }
715
- }
716
-
717
- const dismissMethod = getObjectMethod(dialog, "dismiss");
718
- if (typeof dismissMethod === "function") {
719
- try {
720
- await dismissMethod.call(dialog);
721
- } catch {
722
- // Ignore dialog dismissal failures.
723
- }
724
- }
725
- });
726
- }
727
-
728
- async function readDownloadArtifact(
729
- value: unknown,
730
- fallbackPath: string
731
- ): Promise<ChromeRelayDownloadArtifact> {
732
- let resolvedPath = fallbackPath;
733
- const pathMethod = getObjectMethod(value, "path");
734
- if (typeof pathMethod === "function") {
735
- try {
736
- const pathResult = await pathMethod.call(value);
737
- if (typeof pathResult === "string" && pathResult.trim().length > 0) {
738
- resolvedPath = pathResult;
739
- }
740
- } catch {
741
- // Ignore path() failures and keep fallback path.
742
- }
743
- }
744
-
745
- const saveAsMethod = getObjectMethod(value, "saveAs");
746
- if (typeof saveAsMethod === "function") {
747
- try {
748
- await saveAsMethod.call(value, fallbackPath);
749
- resolvedPath = fallbackPath;
750
- } catch {
751
- // Ignore saveAs failures and keep best-effort path.
752
- }
753
- }
754
-
755
- const suggestedFilename = readObjectMethod<string>(value, "suggestedFilename");
756
- const url = readObjectMethod<string>(value, "url");
757
- const mimeType = readObjectMethod<string>(value, "mimeType");
758
-
759
- return {
760
- path: resolvedPath,
761
- ...(typeof suggestedFilename === "string" ? { suggestedFilename } : {}),
762
- ...(typeof url === "string" ? { url } : {}),
763
- ...(typeof mimeType === "string" ? { mimeType } : {})
764
- };
765
- }
766
-
767
- function readWebSocketDebuggerUrl(value: unknown): string | undefined {
768
- const rawUrl = readObjectStringProperty(value, "webSocketDebuggerUrl");
769
- if (rawUrl === undefined) {
770
- return undefined;
771
- }
772
-
773
- try {
774
- const parsed = new URL(rawUrl);
775
- if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
776
- return undefined;
777
- }
778
-
779
- return parsed.toString();
780
- } catch {
781
- return undefined;
782
- }
783
- }
784
-
785
- async function resolveRelayEndpoint(relayUrl: string, runtime: ChromeRelayDriverRuntime): Promise<string> {
786
- const parsedRelayUrl = new URL(relayUrl);
787
- if (parsedRelayUrl.protocol === "ws:" || parsedRelayUrl.protocol === "wss:") {
788
- return parsedRelayUrl.toString();
789
- }
790
-
791
- if (parsedRelayUrl.protocol === "http:" || parsedRelayUrl.protocol === "https:") {
792
- if (typeof runtime.fetchJson === "function") {
793
- const jsonVersionUrl = new URL("/json/version", parsedRelayUrl).toString();
794
- try {
795
- const payload = await runtime.fetchJson(jsonVersionUrl);
796
- const debuggerUrl = readWebSocketDebuggerUrl(payload);
797
- if (debuggerUrl !== undefined) {
798
- return debuggerUrl;
799
- }
800
- } catch {
801
- // Fall through to connect directly to relay URL.
802
- }
803
- }
804
- }
805
-
806
- return parsedRelayUrl.toString();
807
- }
808
-
809
- function createPlaywrightRuntime(): ChromeRelayDriverRuntime {
810
- return {
811
- connectOverCDP: async (endpointUrl) => {
812
- const playwright = await import("playwright-core");
813
- return (await playwright.chromium.connectOverCDP(endpointUrl)) as unknown as ChromeRelayBrowser;
814
- },
815
- fetchJson: async (url) => {
816
- const response = await fetch(url);
817
- if (!response.ok) {
818
- throw new Error(`Relay metadata request failed (${response.status}) for ${url}`);
819
- }
820
-
821
- return response.json();
822
- }
823
- };
824
- }
825
-
826
- function cloneConsoleEntry(entry: ChromeRelayConsoleEntry): ChromeRelayConsoleEntry {
827
- return {
828
- ...entry,
829
- ...(entry.location !== undefined ? { location: { ...entry.location } } : {})
830
- };
831
- }
832
-
833
- function cloneRequestSummary(summary: ChromeRelayNetworkRequestSummary): ChromeRelayNetworkRequestSummary {
834
- return { ...summary };
835
- }
836
-
837
- export function createChromeRelayDriver(
838
- config: ChromeRelayDriverConfig = {}
839
- ): BrowserDriver<ChromeRelayDriverStatus, ChromeRelaySnapshot> &
840
- ChromeRelayTelemetryDriverExtensions &
841
- BrowserDriverScreenshot<ChromeRelayScreenshot> {
842
- const relayUrl = parseRelayUrl(config);
843
- const runtime = config.runtime ?? createPlaywrightRuntime();
844
- const profileStates = new Map<ProfileId, ChromeRelayProfileState>();
845
- const targetOperationStates = new Map<ProfileId, Map<TargetId, ChromeRelayTargetOperationState>>();
846
- const targetTelemetryStates = new Map<ProfileId, Map<TargetId, ChromeRelayTargetTelemetryState>>();
847
- let browser: ChromeRelayBrowser | undefined;
848
- let browserConnectInFlight: Promise<ChromeRelayBrowser> | undefined;
849
- let browserContext: ChromeRelayBrowserContext | undefined;
850
- let browserContextInFlight: Promise<ChromeRelayBrowserContext> | undefined;
851
- let resolvedEndpointUrl: string | undefined;
852
- let endpointResolveInFlight: Promise<string> | undefined;
853
-
854
- async function ensureEndpointUrl(): Promise<string> {
855
- if (resolvedEndpointUrl !== undefined) {
856
- return resolvedEndpointUrl;
857
- }
858
-
859
- if (endpointResolveInFlight === undefined) {
860
- endpointResolveInFlight = resolveRelayEndpoint(relayUrl, runtime)
861
- .then((resolved) => {
862
- resolvedEndpointUrl = resolved;
863
- return resolved;
864
- })
865
- .finally(() => {
866
- endpointResolveInFlight = undefined;
867
- });
868
- }
869
-
870
- return endpointResolveInFlight;
871
- }
872
-
873
- async function ensureBrowser(): Promise<ChromeRelayBrowser> {
874
- if (browser !== undefined) {
875
- return browser;
876
- }
877
-
878
- if (browserConnectInFlight === undefined) {
879
- browserConnectInFlight = (async () => {
880
- const endpointUrl = await ensureEndpointUrl();
881
- const createdBrowser = await runtime.connectOverCDP(endpointUrl);
882
- browser = createdBrowser;
883
- return createdBrowser;
884
- })().finally(() => {
885
- browserConnectInFlight = undefined;
886
- });
887
- }
888
-
889
- return browserConnectInFlight;
890
- }
891
-
892
- async function ensureBrowserContext(): Promise<ChromeRelayBrowserContext> {
893
- if (browserContext !== undefined) {
894
- return browserContext;
895
- }
896
-
897
- if (browserContextInFlight === undefined) {
898
- browserContextInFlight = (async () => {
899
- const connectedBrowser = await ensureBrowser();
900
- const existingContext = connectedBrowser.contexts()[0];
901
- if (existingContext !== undefined) {
902
- browserContext = existingContext;
903
- return existingContext;
904
- }
905
-
906
- if (typeof connectedBrowser.newContext !== "function") {
907
- throw new Error("No browser context available from relay CDP connection.");
908
- }
909
-
910
- const createdContext = await connectedBrowser.newContext();
911
- browserContext = createdContext;
912
- return createdContext;
913
- })().finally(() => {
914
- browserContextInFlight = undefined;
915
- });
916
- }
917
-
918
- return browserContextInFlight;
919
- }
920
-
921
- function getOrCreateProfileState(profileId: ProfileId): ChromeRelayProfileState {
922
- const existingState = profileStates.get(profileId);
923
- if (existingState !== undefined) {
924
- return existingState;
925
- }
926
-
927
- const createdState = createProfileState();
928
- profileStates.set(profileId, createdState);
929
- return createdState;
930
- }
931
-
932
- function requireTargetInProfile(
933
- profileId: ProfileId,
934
- targetId: TargetId
935
- ): { profileState: ChromeRelayProfileState; tab: ChromeRelayTab } {
936
- const profileState = profileStates.get(profileId);
937
- const tab = profileState?.tabs.get(targetId);
938
- if (profileState === undefined || tab === undefined) {
939
- throw new Error(`Unknown targetId: ${targetId} (profile: ${profileId})`);
940
- }
941
-
942
- return { profileState, tab };
943
- }
944
-
945
- function getOrCreateTargetOperationState(
946
- profileId: ProfileId,
947
- targetId: TargetId,
948
- validateTarget = true
949
- ): ChromeRelayTargetOperationState {
950
- if (validateTarget) {
951
- requireTargetInProfile(profileId, targetId);
952
- }
953
-
954
- let profileOperationStates = targetOperationStates.get(profileId);
955
- if (profileOperationStates === undefined) {
956
- profileOperationStates = new Map<TargetId, ChromeRelayTargetOperationState>();
957
- targetOperationStates.set(profileId, profileOperationStates);
958
- }
959
-
960
- const existingState = profileOperationStates.get(targetId);
961
- if (existingState !== undefined) {
962
- return existingState;
963
- }
964
-
965
- const createdState = createTargetOperationState();
966
- profileOperationStates.set(targetId, createdState);
967
- return createdState;
968
- }
969
-
970
- function getOrCreateProfileTelemetryStates(
971
- profileId: ProfileId
972
- ): Map<TargetId, ChromeRelayTargetTelemetryState> {
973
- const existingStates = targetTelemetryStates.get(profileId);
974
- if (existingStates !== undefined) {
975
- return existingStates;
976
- }
977
-
978
- const createdStates = new Map<TargetId, ChromeRelayTargetTelemetryState>();
979
- targetTelemetryStates.set(profileId, createdStates);
980
- return createdStates;
981
- }
982
-
983
- function findTelemetryState(
984
- targetId: TargetId,
985
- profile?: ProfileId
986
- ): ChromeRelayTargetTelemetryState | undefined {
987
- if (profile !== undefined) {
988
- return targetTelemetryStates.get(resolveProfileId(profile))?.get(targetId);
989
- }
990
-
991
- for (const profileTelemetryStates of targetTelemetryStates.values()) {
992
- const telemetryState = profileTelemetryStates.get(targetId);
993
- if (telemetryState !== undefined) {
994
- return telemetryState;
995
- }
996
- }
997
-
998
- return undefined;
999
- }
1000
-
1001
- function ensureDownloadInFlight(
1002
- profileId: ProfileId,
1003
- targetId: TargetId,
1004
- tab: ChromeRelayTab,
1005
- operationState: ChromeRelayTargetOperationState,
1006
- requestedPath?: string
1007
- ): Promise<ChromeRelayDownloadArtifact> {
1008
- if (requestedPath !== undefined) {
1009
- operationState.requestedDownloadPath = requestedPath;
1010
- }
1011
-
1012
- if (operationState.downloadInFlight !== undefined) {
1013
- return operationState.downloadInFlight;
1014
- }
1015
-
1016
- const fallbackPath =
1017
- operationState.requestedDownloadPath ??
1018
- createDownloadPath(profileId, targetId, Math.max(operationState.triggerCount, 1));
1019
- const waitForEventMethod = getObjectMethod(tab.page, "waitForEvent");
1020
- if (typeof waitForEventMethod !== "function") {
1021
- const artifact: ChromeRelayDownloadArtifact = { path: fallbackPath };
1022
- operationState.requestedDownloadPath = undefined;
1023
- operationState.latestDownload = artifact;
1024
- operationState.latestRawDownload = undefined;
1025
- const resolved = Promise.resolve(artifact);
1026
- operationState.downloadInFlight = resolved;
1027
- return resolved;
1028
- }
1029
-
1030
- const inFlight = (async () => {
1031
- const rawDownload = await waitForEventMethod.call(tab.page, "download");
1032
- operationState.latestRawDownload = rawDownload;
1033
- const persistedPath =
1034
- operationState.requestedDownloadPath ??
1035
- createDownloadPath(profileId, targetId, Math.max(operationState.triggerCount, 1));
1036
- const artifact = await readDownloadArtifact(rawDownload, persistedPath);
1037
- operationState.latestDownload = artifact;
1038
- operationState.requestedDownloadPath = undefined;
1039
- return artifact;
1040
- })().finally(() => {
1041
- if (operationState.downloadInFlight === inFlight) {
1042
- operationState.downloadInFlight = undefined;
1043
- }
1044
- });
1045
-
1046
- operationState.downloadInFlight = inFlight;
1047
- return inFlight;
1048
- }
1049
-
1050
- async function resolveDownloadArtifactPath(
1051
- operationState: ChromeRelayTargetOperationState,
1052
- artifact: ChromeRelayDownloadArtifact,
1053
- requestedPath?: string
1054
- ): Promise<ChromeRelayDownloadArtifact> {
1055
- if (requestedPath === undefined || requestedPath.trim().length === 0 || artifact.path === requestedPath) {
1056
- return artifact;
1057
- }
1058
-
1059
- const failurePrefix = `Failed to persist download to requested path: ${requestedPath}`;
1060
- const saveAsMethod = getObjectMethod(operationState.latestRawDownload, "saveAs");
1061
- if (typeof saveAsMethod !== "function") {
1062
- throw new Error(failurePrefix);
1063
- }
1064
-
1065
- try {
1066
- await saveAsMethod.call(operationState.latestRawDownload, requestedPath);
1067
- return { ...artifact, path: requestedPath };
1068
- } catch (error) {
1069
- const message = error instanceof Error ? error.message : String(error);
1070
- throw new Error(message.length > 0 ? `${failurePrefix} (${message})` : failurePrefix);
1071
- }
1072
- }
1073
-
1074
- return {
1075
- status: async () => {
1076
- const runtimeConnected = await readRuntimeConnectionStatus(runtime);
1077
- return {
1078
- kind: "chrome-relay",
1079
- connected: runtimeConnected ?? browser !== undefined,
1080
- relayUrl
1081
- };
1082
- },
1083
- listProfiles: async () => {
1084
- const knownProfiles = new Set<ProfileId>([DEFAULT_PROFILE_ID]);
1085
- for (const profileId of profileStates.keys()) {
1086
- knownProfiles.add(profileId);
1087
- }
1088
-
1089
- return Array.from(knownProfiles).sort();
1090
- },
1091
- listTabs: async (profile) => {
1092
- const profileId = resolveProfileId(profile);
1093
- const profileState = profileStates.get(profileId);
1094
- return profileState === undefined ? [] : [...profileState.tabOrder];
1095
- },
1096
- openTab: async (url, profile) => {
1097
- const profileId = resolveProfileId(profile);
1098
- const profileState = getOrCreateProfileState(profileId);
1099
- const targetId = createTargetId(profileId, profileState.nextTargetNumber);
1100
- const page = await (await ensureBrowserContext()).newPage();
1101
- const telemetryState = createTargetTelemetryState();
1102
- const operationState = getOrCreateTargetOperationState(profileId, targetId, false);
1103
- attachTelemetryListeners(page, profileId, targetId, telemetryState, operationState);
1104
- await page.goto(url);
1105
-
1106
- profileState.nextTargetNumber += 1;
1107
- profileState.tabs.set(targetId, { url, page });
1108
- profileState.tabOrder.push(targetId);
1109
- getOrCreateProfileTelemetryStates(profileId).set(targetId, telemetryState);
1110
- if (profileState.focusedTargetId === undefined) {
1111
- profileState.focusedTargetId = targetId;
1112
- }
1113
-
1114
- return targetId;
1115
- },
1116
- focusTab: async (targetId, profile) => {
1117
- const profileId = resolveProfileId(profile);
1118
- const { profileState, tab } = requireTargetInProfile(profileId, targetId);
1119
- await tab.page.bringToFront();
1120
- profileState.focusedTargetId = targetId;
1121
- },
1122
- closeTab: async (targetId, profile) => {
1123
- const profileId = resolveProfileId(profile);
1124
- const { profileState, tab } = requireTargetInProfile(profileId, targetId);
1125
- await tab.page.close();
1126
-
1127
- profileState.tabs.delete(targetId);
1128
- profileState.tabOrder = profileState.tabOrder.filter((existingTargetId) => existingTargetId !== targetId);
1129
- if (profileState.focusedTargetId === targetId) {
1130
- profileState.focusedTargetId = profileState.tabOrder[0];
1131
- }
1132
-
1133
- const profileOperationStates = targetOperationStates.get(profileId);
1134
- profileOperationStates?.delete(targetId);
1135
- if (profileOperationStates !== undefined && profileOperationStates.size === 0) {
1136
- targetOperationStates.delete(profileId);
1137
- }
1138
-
1139
- const profileTelemetryStates = targetTelemetryStates.get(profileId);
1140
- profileTelemetryStates?.delete(targetId);
1141
- if (profileTelemetryStates !== undefined && profileTelemetryStates.size === 0) {
1142
- targetTelemetryStates.delete(profileId);
1143
- }
1144
- },
1145
- snapshot: async (targetId, profile) => {
1146
- const profileId = resolveProfileId(profile);
1147
- const tab = profileStates.get(profileId)?.tabs.get(targetId);
1148
- if (tab === undefined) {
1149
- return {
1150
- kind: "chrome-relay",
1151
- profile: profileId,
1152
- targetId,
1153
- relayUrl,
1154
- hasTarget: false
1155
- };
1156
- }
1157
-
1158
- const requestSummaries =
1159
- targetTelemetryStates
1160
- .get(profileId)
1161
- ?.get(targetId)
1162
- ?.requestSummaries.map(cloneRequestSummary) ?? [];
1163
-
1164
- return {
1165
- kind: "chrome-relay",
1166
- profile: profileId,
1167
- targetId,
1168
- relayUrl,
1169
- hasTarget: true,
1170
- url: tab.page.url(),
1171
- title: await tab.page.title(),
1172
- html: await tab.page.content(),
1173
- requestSummaries
1174
- };
1175
- },
1176
- screenshot: async (targetId, profile) => {
1177
- const profileId = resolveProfileId(profile);
1178
- const tab = profileStates.get(profileId)?.tabs.get(targetId);
1179
- if (tab === undefined) {
1180
- return {
1181
- kind: "chrome-relay",
1182
- profile: profileId,
1183
- targetId,
1184
- relayUrl,
1185
- hasTarget: false
1186
- };
1187
- }
1188
-
1189
- const screenshot = await capturePageScreenshot(tab.page);
1190
- return {
1191
- kind: "chrome-relay",
1192
- profile: profileId,
1193
- targetId,
1194
- relayUrl,
1195
- hasTarget: true,
1196
- ...screenshot
1197
- };
1198
- },
1199
- act: async (action, targetId, profile) => {
1200
- const profileId = resolveProfileId(profile);
1201
- const tab = profileStates.get(profileId)?.tabs.get(targetId);
1202
- if (tab === undefined) {
1203
- return {
1204
- actionType: action.type,
1205
- profile: profileId,
1206
- targetId,
1207
- relayUrl,
1208
- targetKnown: false,
1209
- ok: false,
1210
- executed: false,
1211
- error: `Unknown targetId: ${targetId} (profile: ${profileId})`
1212
- };
1213
- }
1214
-
1215
- const payload = action.payload;
1216
- const operationState = getOrCreateTargetOperationState(profileId, targetId);
1217
- const baseResult = {
1218
- actionType: action.type,
1219
- profile: profileId,
1220
- targetId,
1221
- relayUrl,
1222
- targetKnown: true
1223
- };
1224
-
1225
- const performAction = async (): Promise<{
1226
- ok: boolean;
1227
- executed: boolean;
1228
- error?: string;
1229
- data?: Record<string, unknown>;
1230
- }> => {
1231
- switch (action.type) {
1232
- case "navigate":
1233
- case "goto": {
1234
- const nextUrl = readActionPayloadString(payload, "url");
1235
- if (nextUrl === undefined) {
1236
- return {
1237
- ok: false,
1238
- executed: false,
1239
- error: "action.payload.url is required for navigate action."
1240
- };
1241
- }
1242
-
1243
- await tab.page.goto(nextUrl);
1244
- tab.url = nextUrl;
1245
- return { ok: true, executed: true };
1246
- }
1247
- case "click": {
1248
- const selector = readActionPayloadString(payload, "selector");
1249
- if (selector === undefined) {
1250
- return {
1251
- ok: false,
1252
- executed: false,
1253
- error: "action.payload.selector is required for click action."
1254
- };
1255
- }
1256
-
1257
- const locator = tab.page.locator(selector);
1258
- if (operationState.uploadFiles.length > 0) {
1259
- const setInputFilesMethod = getObjectMethod(locator, "setInputFiles");
1260
- if (typeof setInputFilesMethod === "function") {
1261
- await setInputFilesMethod.call(locator, [...operationState.uploadFiles]);
1262
- operationState.uploadFiles = [];
1263
- return { ok: true, executed: true };
1264
- }
1265
- }
1266
-
1267
- await locator.click();
1268
- return { ok: true, executed: true };
1269
- }
1270
- case "fill": {
1271
- const selector = readActionPayloadString(payload, "selector");
1272
- const value = readActionPayloadString(payload, "value");
1273
- if (selector === undefined || value === undefined) {
1274
- return {
1275
- ok: false,
1276
- executed: false,
1277
- error: "action.payload.selector and action.payload.value are required for fill action."
1278
- };
1279
- }
1280
-
1281
- await tab.page.locator(selector).fill(value);
1282
- return { ok: true, executed: true };
1283
- }
1284
- case "type": {
1285
- const selector = readActionPayloadString(payload, "selector");
1286
- const text = readActionPayloadString(payload, "text");
1287
- if (selector === undefined || text === undefined) {
1288
- return {
1289
- ok: false,
1290
- executed: false,
1291
- error: "action.payload.selector and action.payload.text are required for type action."
1292
- };
1293
- }
1294
-
1295
- await tab.page.locator(selector).type(text);
1296
- return { ok: true, executed: true };
1297
- }
1298
- case "press": {
1299
- const key = readActionPayloadString(payload, "key");
1300
- if (key === undefined || tab.page.keyboard === undefined) {
1301
- return {
1302
- ok: false,
1303
- executed: false,
1304
- error: "action.payload.key is required for press action."
1305
- };
1306
- }
1307
-
1308
- await tab.page.keyboard.press(key);
1309
- return { ok: true, executed: true };
1310
- }
1311
- case "scroll": {
1312
- const deltaX = readActionPayloadNumber(payload, "deltaX") ?? 0;
1313
- const deltaY = readActionPayloadNumber(payload, "deltaY") ?? 900;
1314
-
1315
- const customScrollMethod = getObjectMethod(tab.page, "scroll");
1316
- if (typeof customScrollMethod === "function") {
1317
- const customResult = await customScrollMethod.call(tab.page, deltaX, deltaY);
1318
- return {
1319
- ok: true,
1320
- executed: true,
1321
- data: isObjectRecord(customResult)
1322
- ? customResult
1323
- : {
1324
- deltaX,
1325
- deltaY
1326
- }
1327
- };
1328
- }
1329
-
1330
- const evaluateMethod = getObjectMethod(tab.page, "evaluate");
1331
- if (typeof evaluateMethod !== "function") {
1332
- return {
1333
- ok: true,
1334
- executed: false
1335
- };
1336
- }
1337
-
1338
- const scrollResult = await evaluateMethod.call(
1339
- tab.page,
1340
- (rawArg: unknown) => {
1341
- const value =
1342
- rawArg !== null && typeof rawArg === "object"
1343
- ? (rawArg as { deltaX?: unknown; deltaY?: unknown })
1344
- : {};
1345
- const resolvedDeltaX =
1346
- typeof value.deltaX === "number" && Number.isFinite(value.deltaX) ? value.deltaX : 0;
1347
- const resolvedDeltaY =
1348
- typeof value.deltaY === "number" && Number.isFinite(value.deltaY) ? value.deltaY : 900;
1349
- window.scrollBy({
1350
- left: resolvedDeltaX,
1351
- top: resolvedDeltaY
1352
- });
1353
-
1354
- return {
1355
- deltaX: resolvedDeltaX,
1356
- deltaY: resolvedDeltaY,
1357
- scrollX: window.scrollX,
1358
- scrollY: window.scrollY
1359
- };
1360
- },
1361
- {
1362
- deltaX,
1363
- deltaY
1364
- }
1365
- );
1366
-
1367
- return {
1368
- ok: true,
1369
- executed: true,
1370
- data: isObjectRecord(scrollResult)
1371
- ? scrollResult
1372
- : {
1373
- deltaX,
1374
- deltaY
1375
- }
1376
- };
1377
- }
1378
- case "networkMockAdd": {
1379
- const urlPattern = readActionPayloadString(payload, "urlPattern");
1380
- if (urlPattern === undefined) {
1381
- return {
1382
- ok: false,
1383
- executed: false,
1384
- error: "action.payload.urlPattern is required for networkMockAdd action."
1385
- };
1386
- }
1387
-
1388
- const routeMethod = getObjectMethod(tab.page, "route");
1389
- if (typeof routeMethod !== "function") {
1390
- return {
1391
- ok: true,
1392
- executed: false
1393
- };
1394
- }
1395
-
1396
- const methodFilter = readActionPayloadString(payload, "method")?.toUpperCase();
1397
- const status = readActionPayloadNumber(payload, "status") ?? 200;
1398
- if (!Number.isInteger(status) || status < 100 || status > 599) {
1399
- return {
1400
- ok: false,
1401
- executed: false,
1402
- error: "action.payload.status must be an integer between 100 and 599 for networkMockAdd action."
1403
- };
1404
- }
1405
- const body = readActionPayloadString(payload, "body") ?? "";
1406
- const contentType = readActionPayloadString(payload, "contentType") ?? "text/plain";
1407
- const mockId = `mock:${operationState.nextNetworkMockNumber}`;
1408
- operationState.nextNetworkMockNumber += 1;
1409
- const handler: ChromeRelayNetworkMockHandler = async (...args) => {
1410
- const route = args[0];
1411
- const explicitRequest = args[1];
1412
- const request = explicitRequest ?? readObjectMethod<unknown>(route, "request");
1413
- if (methodFilter !== undefined) {
1414
- const requestMethod = readObjectMethod<string>(request, "method");
1415
- if (requestMethod?.toUpperCase() !== methodFilter) {
1416
- const continueMethod = getObjectMethod(route, "continue");
1417
- if (typeof continueMethod === "function") {
1418
- await continueMethod.call(route);
1419
- return;
1420
- }
1421
-
1422
- const fallbackMethod = getObjectMethod(route, "fallback");
1423
- if (typeof fallbackMethod === "function") {
1424
- await fallbackMethod.call(route);
1425
- return;
1426
- }
1427
-
1428
- return;
1429
- }
1430
- }
1431
-
1432
- const fulfillMethod = getObjectMethod(route, "fulfill");
1433
- if (typeof fulfillMethod !== "function") {
1434
- return;
1435
- }
1436
-
1437
- await fulfillMethod.call(route, {
1438
- status,
1439
- body,
1440
- headers: {
1441
- "content-type": contentType
1442
- }
1443
- });
1444
- };
1445
-
1446
- await routeMethod.call(tab.page, urlPattern, handler);
1447
- operationState.networkMocks.set(mockId, {
1448
- urlPattern,
1449
- handler
1450
- });
1451
- return {
1452
- ok: true,
1453
- executed: true,
1454
- data: {
1455
- mockId,
1456
- urlPattern,
1457
- ...(methodFilter !== undefined ? { method: methodFilter } : {}),
1458
- status
1459
- }
1460
- };
1461
- }
1462
- case "networkMockClear": {
1463
- const unrouteMethod = getObjectMethod(tab.page, "unroute");
1464
- if (typeof unrouteMethod !== "function") {
1465
- return {
1466
- ok: true,
1467
- executed: false
1468
- };
1469
- }
1470
-
1471
- const mockId = readActionPayloadString(payload, "mockId");
1472
- if (mockId !== undefined) {
1473
- const binding = operationState.networkMocks.get(mockId);
1474
- if (binding === undefined) {
1475
- return {
1476
- ok: false,
1477
- executed: false,
1478
- error: `Unknown network mock id: ${mockId}`
1479
- };
1480
- }
1481
-
1482
- await unrouteMethod.call(tab.page, binding.urlPattern, binding.handler);
1483
- operationState.networkMocks.delete(mockId);
1484
- return {
1485
- ok: true,
1486
- executed: true,
1487
- data: {
1488
- cleared: 1,
1489
- mockId
1490
- }
1491
- };
1492
- }
1493
-
1494
- let cleared = 0;
1495
- for (const [registeredId, binding] of operationState.networkMocks.entries()) {
1496
- try {
1497
- await unrouteMethod.call(tab.page, binding.urlPattern, binding.handler);
1498
- } catch {
1499
- // Ignore per-route cleanup failures.
1500
- }
1501
- operationState.networkMocks.delete(registeredId);
1502
- cleared += 1;
1503
- }
1504
-
1505
- return {
1506
- ok: true,
1507
- executed: true,
1508
- data: {
1509
- cleared
1510
- }
1511
- };
1512
- }
1513
- case "domQuery": {
1514
- const selector = readActionPayloadString(payload, "selector");
1515
- if (selector === undefined) {
1516
- return {
1517
- ok: false,
1518
- executed: false,
1519
- error: "action.payload.selector is required for domQuery action."
1520
- };
1521
- }
1522
-
1523
- const customDomQueryMethod = getObjectMethod(tab.page, "domQuery");
1524
- if (typeof customDomQueryMethod === "function") {
1525
- const customResult = await customDomQueryMethod.call(tab.page, selector);
1526
- return {
1527
- ok: true,
1528
- executed: true,
1529
- data: isObjectRecord(customResult)
1530
- ? customResult
1531
- : {
1532
- selector,
1533
- found: false
1534
- }
1535
- };
1536
- }
1537
-
1538
- const queryResult = await evaluateInPage<Record<string, unknown>>(
1539
- tab.page,
1540
- (rawArg) => {
1541
- const selectorValue =
1542
- rawArg !== null &&
1543
- typeof rawArg === "object" &&
1544
- typeof (rawArg as { selector?: unknown }).selector === "string"
1545
- ? (rawArg as { selector: string }).selector
1546
- : "";
1547
- const element = selectorValue.length > 0 ? document.querySelector(selectorValue) : null;
1548
- if (element === null) {
1549
- return {
1550
- selector: selectorValue,
1551
- found: false
1552
- };
1553
- }
1554
-
1555
- const attributes: Record<string, string> = {};
1556
- for (const attribute of Array.from(element.attributes)) {
1557
- attributes[attribute.name] = attribute.value;
1558
- }
1559
-
1560
- return {
1561
- selector: selectorValue,
1562
- found: true,
1563
- node: {
1564
- tagName: element.tagName.toLowerCase(),
1565
- id: element.id || undefined,
1566
- className: element.className || undefined,
1567
- text: (element.textContent || "").trim().slice(0, 300),
1568
- attributes
1569
- }
1570
- };
1571
- },
1572
- { selector }
1573
- );
1574
-
1575
- return {
1576
- ok: true,
1577
- executed: true,
1578
- data: isObjectRecord(queryResult)
1579
- ? queryResult
1580
- : {
1581
- selector,
1582
- found: false
1583
- }
1584
- };
1585
- }
1586
- case "domQueryAll": {
1587
- const selector = readActionPayloadString(payload, "selector");
1588
- if (selector === undefined) {
1589
- return {
1590
- ok: false,
1591
- executed: false,
1592
- error: "action.payload.selector is required for domQueryAll action."
1593
- };
1594
- }
1595
-
1596
- const customDomQueryAllMethod = getObjectMethod(tab.page, "domQueryAll");
1597
- if (typeof customDomQueryAllMethod === "function") {
1598
- const customResult = await customDomQueryAllMethod.call(tab.page, selector);
1599
- return {
1600
- ok: true,
1601
- executed: true,
1602
- data: isObjectRecord(customResult)
1603
- ? customResult
1604
- : {
1605
- selector,
1606
- count: 0,
1607
- nodes: []
1608
- }
1609
- };
1610
- }
1611
-
1612
- const queryResult = await evaluateInPage<Record<string, unknown>>(
1613
- tab.page,
1614
- (rawArg) => {
1615
- const selectorValue =
1616
- rawArg !== null &&
1617
- typeof rawArg === "object" &&
1618
- typeof (rawArg as { selector?: unknown }).selector === "string"
1619
- ? (rawArg as { selector: string }).selector
1620
- : "";
1621
- const elements = selectorValue.length > 0 ? document.querySelectorAll(selectorValue) : [];
1622
- const nodes = Array.from(elements).map((element, index) => {
1623
- const attributes: Record<string, string> = {};
1624
- for (const attribute of Array.from(element.attributes)) {
1625
- attributes[attribute.name] = attribute.value;
1626
- }
1627
-
1628
- return {
1629
- index,
1630
- tagName: element.tagName.toLowerCase(),
1631
- id: element.id || undefined,
1632
- className: element.className || undefined,
1633
- text: (element.textContent || "").trim().slice(0, 300),
1634
- attributes
1635
- };
1636
- });
1637
-
1638
- return {
1639
- selector: selectorValue,
1640
- count: nodes.length,
1641
- nodes
1642
- };
1643
- },
1644
- { selector }
1645
- );
1646
-
1647
- return {
1648
- ok: true,
1649
- executed: true,
1650
- data: isObjectRecord(queryResult)
1651
- ? queryResult
1652
- : {
1653
- selector,
1654
- count: 0,
1655
- nodes: []
1656
- }
1657
- };
1658
- }
1659
- case "elementScreenshot": {
1660
- const selector = readActionPayloadString(payload, "selector");
1661
- if (selector === undefined) {
1662
- return {
1663
- ok: false,
1664
- executed: false,
1665
- error: "action.payload.selector is required for elementScreenshot action."
1666
- };
1667
- }
1668
-
1669
- const customElementScreenshotMethod = getObjectMethod(tab.page, "elementScreenshot");
1670
- if (typeof customElementScreenshotMethod === "function") {
1671
- const customResult = await customElementScreenshotMethod.call(tab.page, selector);
1672
- return {
1673
- ok: true,
1674
- executed: true,
1675
- data: isObjectRecord(customResult)
1676
- ? customResult
1677
- : {
1678
- selector,
1679
- found: false
1680
- }
1681
- };
1682
- }
1683
-
1684
- const found = await evaluateInPage<boolean>(
1685
- tab.page,
1686
- (rawArg) => {
1687
- const selectorValue =
1688
- rawArg !== null &&
1689
- typeof rawArg === "object" &&
1690
- typeof (rawArg as { selector?: unknown }).selector === "string"
1691
- ? (rawArg as { selector: string }).selector
1692
- : "";
1693
- return selectorValue.length > 0 && document.querySelector(selectorValue) !== null;
1694
- },
1695
- { selector }
1696
- );
1697
- if (!found) {
1698
- return {
1699
- ok: true,
1700
- executed: true,
1701
- data: {
1702
- selector,
1703
- found: false
1704
- }
1705
- };
1706
- }
1707
-
1708
- const locator = tab.page.locator(selector);
1709
- const locatorScreenshotMethod = getObjectMethod(locator, "screenshot");
1710
- if (typeof locatorScreenshotMethod !== "function") {
1711
- return {
1712
- ok: true,
1713
- executed: false
1714
- };
1715
- }
1716
-
1717
- const rawScreenshot = await locatorScreenshotMethod.call(locator, { type: "png" });
1718
- const parsedScreenshot = readScreenshotImage(rawScreenshot);
1719
- if (parsedScreenshot === undefined) {
1720
- return {
1721
- ok: false,
1722
- executed: false,
1723
- error: "Unable to parse element screenshot payload."
1724
- };
1725
- }
1726
-
1727
- return {
1728
- ok: true,
1729
- executed: true,
1730
- data: {
1731
- selector,
1732
- found: true,
1733
- ...parsedScreenshot
1734
- }
1735
- };
1736
- }
1737
- case "a11ySnapshot": {
1738
- const selector = readActionPayloadString(payload, "selector");
1739
- const customA11ySnapshotMethod = getObjectMethod(tab.page, "a11ySnapshot");
1740
- if (typeof customA11ySnapshotMethod === "function") {
1741
- const customResult = await customA11ySnapshotMethod.call(tab.page, selector);
1742
- return {
1743
- ok: true,
1744
- executed: true,
1745
- data: isObjectRecord(customResult)
1746
- ? customResult
1747
- : {
1748
- found: false
1749
- }
1750
- };
1751
- }
1752
-
1753
- const accessibilityValue =
1754
- typeof tab.page === "object" && tab.page !== null
1755
- ? (tab.page as Record<string, unknown>).accessibility
1756
- : undefined;
1757
- const accessibilitySnapshotMethod = getObjectMethod(accessibilityValue, "snapshot");
1758
- if (typeof accessibilitySnapshotMethod === "function") {
1759
- const snapshot = await accessibilitySnapshotMethod.call(accessibilityValue, {});
1760
- return {
1761
- ok: true,
1762
- executed: true,
1763
- data: {
1764
- selector,
1765
- found: true,
1766
- snapshot
1767
- }
1768
- };
1769
- }
1770
-
1771
- const fallbackSnapshot = await evaluateInPage<Record<string, unknown>>(
1772
- tab.page,
1773
- (rawArg) => {
1774
- const selectorValue =
1775
- rawArg !== null &&
1776
- typeof rawArg === "object" &&
1777
- typeof (rawArg as { selector?: unknown }).selector === "string"
1778
- ? (rawArg as { selector: string }).selector
1779
- : "";
1780
- const root =
1781
- selectorValue.length > 0
1782
- ? document.querySelector(selectorValue)
1783
- : document.body ?? document.documentElement;
1784
- if (root === null) {
1785
- return {
1786
- selector: selectorValue,
1787
- found: false
1788
- };
1789
- }
1790
-
1791
- const build = (element: Element, depth: number): Record<string, unknown> => {
1792
- const role =
1793
- element.getAttribute("role") ??
1794
- (element.tagName.toLowerCase() === "a"
1795
- ? "link"
1796
- : element.tagName.toLowerCase() === "button"
1797
- ? "button"
1798
- : element.tagName.toLowerCase() === "input"
1799
- ? "textbox"
1800
- : "generic");
1801
- const name =
1802
- element.getAttribute("aria-label") ??
1803
- element.getAttribute("alt") ??
1804
- (element.textContent || "").trim().slice(0, 120);
1805
- if (depth >= 5) {
1806
- return {
1807
- role,
1808
- ...(name.length > 0 ? { name } : {})
1809
- };
1810
- }
1811
-
1812
- const children = Array.from(element.children)
1813
- .slice(0, 30)
1814
- .map((child) => build(child, depth + 1));
1815
- return {
1816
- role,
1817
- ...(name.length > 0 ? { name } : {}),
1818
- ...(children.length > 0 ? { children } : {})
1819
- };
1820
- };
1821
-
1822
- return {
1823
- selector: selectorValue,
1824
- found: true,
1825
- snapshot: build(root, 0)
1826
- };
1827
- },
1828
- { selector: selector ?? "" }
1829
- );
1830
-
1831
- return {
1832
- ok: true,
1833
- executed: true,
1834
- data: isObjectRecord(fallbackSnapshot)
1835
- ? fallbackSnapshot
1836
- : {
1837
- selector,
1838
- found: false
1839
- }
1840
- };
1841
- }
1842
- case "cookieGet": {
1843
- const cookieName = readActionPayloadString(payload, "name");
1844
- const customCookieGetMethod = getObjectMethod(tab.page, "cookieGet");
1845
- if (typeof customCookieGetMethod === "function") {
1846
- const customResult = await customCookieGetMethod.call(tab.page, cookieName);
1847
- return {
1848
- ok: true,
1849
- executed: true,
1850
- data: isObjectRecord(customResult)
1851
- ? customResult
1852
- : {
1853
- cookies: []
1854
- }
1855
- };
1856
- }
1857
-
1858
- const contextMethod = getObjectMethod(tab.page, "context");
1859
- if (typeof contextMethod !== "function") {
1860
- return {
1861
- ok: true,
1862
- executed: false
1863
- };
1864
- }
1865
-
1866
- const context = await contextMethod.call(tab.page);
1867
- const cookiesMethod = getObjectMethod(context, "cookies");
1868
- if (typeof cookiesMethod !== "function") {
1869
- return {
1870
- ok: true,
1871
- executed: false
1872
- };
1873
- }
1874
-
1875
- let rawCookies: unknown;
1876
- try {
1877
- rawCookies = await cookiesMethod.call(context, [tab.page.url()]);
1878
- } catch {
1879
- rawCookies = await cookiesMethod.call(context);
1880
- }
1881
- const cookies = normalizeCookies(rawCookies).filter(
1882
- (cookie) => cookieName === undefined || cookie.name === cookieName
1883
- );
1884
- return {
1885
- ok: true,
1886
- executed: true,
1887
- data: {
1888
- cookies,
1889
- ...(cookieName !== undefined ? { name: cookieName } : {})
1890
- }
1891
- };
1892
- }
1893
- case "cookieSet": {
1894
- const cookieName = readActionPayloadString(payload, "name");
1895
- const cookieValue = readActionPayloadString(payload, "value");
1896
- const cookieUrl = readActionPayloadString(payload, "url") ?? tab.page.url();
1897
- if (cookieName === undefined || cookieValue === undefined) {
1898
- return {
1899
- ok: false,
1900
- executed: false,
1901
- error: "action.payload.name and action.payload.value are required for cookieSet action."
1902
- };
1903
- }
1904
-
1905
- const customCookieSetMethod = getObjectMethod(tab.page, "cookieSet");
1906
- if (typeof customCookieSetMethod === "function") {
1907
- const customResult = await customCookieSetMethod.call(tab.page, {
1908
- name: cookieName,
1909
- value: cookieValue,
1910
- url: cookieUrl
1911
- });
1912
- return {
1913
- ok: true,
1914
- executed: true,
1915
- data: isObjectRecord(customResult)
1916
- ? customResult
1917
- : {
1918
- set: true,
1919
- cookie: {
1920
- name: cookieName,
1921
- value: cookieValue,
1922
- url: cookieUrl
1923
- }
1924
- }
1925
- };
1926
- }
1927
-
1928
- const contextMethod = getObjectMethod(tab.page, "context");
1929
- if (typeof contextMethod !== "function") {
1930
- return {
1931
- ok: true,
1932
- executed: false
1933
- };
1934
- }
1935
-
1936
- const context = await contextMethod.call(tab.page);
1937
- const addCookiesMethod = getObjectMethod(context, "addCookies");
1938
- if (typeof addCookiesMethod !== "function") {
1939
- return {
1940
- ok: true,
1941
- executed: false
1942
- };
1943
- }
1944
-
1945
- await addCookiesMethod.call(context, [
1946
- {
1947
- name: cookieName,
1948
- value: cookieValue,
1949
- url: cookieUrl
1950
- }
1951
- ]);
1952
-
1953
- return {
1954
- ok: true,
1955
- executed: true,
1956
- data: {
1957
- set: true,
1958
- cookie: {
1959
- name: cookieName,
1960
- value: cookieValue,
1961
- url: cookieUrl
1962
- }
1963
- }
1964
- };
1965
- }
1966
- case "cookieClear": {
1967
- const cookieName = readActionPayloadString(payload, "name");
1968
- const customCookieClearMethod = getObjectMethod(tab.page, "cookieClear");
1969
- if (typeof customCookieClearMethod === "function") {
1970
- const customResult = await customCookieClearMethod.call(tab.page, cookieName);
1971
- return {
1972
- ok: true,
1973
- executed: true,
1974
- data: isObjectRecord(customResult)
1975
- ? customResult
1976
- : {
1977
- cleared: true
1978
- }
1979
- };
1980
- }
1981
-
1982
- const contextMethod = getObjectMethod(tab.page, "context");
1983
- if (typeof contextMethod !== "function") {
1984
- return {
1985
- ok: true,
1986
- executed: false
1987
- };
1988
- }
1989
-
1990
- const context = await contextMethod.call(tab.page);
1991
- const clearCookiesMethod = getObjectMethod(context, "clearCookies");
1992
- if (typeof clearCookiesMethod !== "function") {
1993
- return {
1994
- ok: true,
1995
- executed: false
1996
- };
1997
- }
1998
-
1999
- if (cookieName === undefined) {
2000
- await clearCookiesMethod.call(context);
2001
- return {
2002
- ok: true,
2003
- executed: true,
2004
- data: {
2005
- cleared: true,
2006
- count: -1
2007
- }
2008
- };
2009
- }
2010
-
2011
- const cookiesMethod = getObjectMethod(context, "cookies");
2012
- const addCookiesMethod = getObjectMethod(context, "addCookies");
2013
- if (typeof cookiesMethod !== "function" || typeof addCookiesMethod !== "function") {
2014
- return {
2015
- ok: true,
2016
- executed: false
2017
- };
2018
- }
2019
-
2020
- let rawCookies: unknown;
2021
- try {
2022
- rawCookies = await cookiesMethod.call(context, [tab.page.url()]);
2023
- } catch {
2024
- rawCookies = await cookiesMethod.call(context);
2025
- }
2026
- const currentCookies = normalizeCookies(rawCookies);
2027
- const keptCookieInputs = currentCookies
2028
- .filter((cookie) => cookie.name !== cookieName)
2029
- .map((cookie) => toCookieInput(cookie))
2030
- .filter((cookie): cookie is Record<string, unknown> => cookie !== undefined);
2031
- const removedCount = currentCookies.length - keptCookieInputs.length;
2032
-
2033
- await clearCookiesMethod.call(context);
2034
- if (keptCookieInputs.length > 0) {
2035
- await addCookiesMethod.call(context, keptCookieInputs);
2036
- }
2037
-
2038
- return {
2039
- ok: true,
2040
- executed: true,
2041
- data: {
2042
- cleared: true,
2043
- name: cookieName,
2044
- count: removedCount
2045
- }
2046
- };
2047
- }
2048
- case "storageGet": {
2049
- const scope = parseStorageScope(readActionPayloadString(payload, "scope"));
2050
- const key = readActionPayloadString(payload, "key");
2051
- if (scope === undefined || key === undefined) {
2052
- return {
2053
- ok: false,
2054
- executed: false,
2055
- error: "action.payload.scope and action.payload.key are required for storageGet action."
2056
- };
2057
- }
2058
-
2059
- const customStorageGetMethod = getObjectMethod(tab.page, "storageGet");
2060
- if (typeof customStorageGetMethod === "function") {
2061
- const customResult = await customStorageGetMethod.call(tab.page, scope, key);
2062
- return {
2063
- ok: true,
2064
- executed: true,
2065
- data: isObjectRecord(customResult)
2066
- ? customResult
2067
- : {
2068
- scope,
2069
- key,
2070
- exists: false
2071
- }
2072
- };
2073
- }
2074
-
2075
- const result = await evaluateInPage<Record<string, unknown>>(
2076
- tab.page,
2077
- (rawArg) => {
2078
- const scopeValue =
2079
- rawArg !== null &&
2080
- typeof rawArg === "object" &&
2081
- typeof (rawArg as { scope?: unknown }).scope === "string"
2082
- ? (rawArg as { scope: string }).scope
2083
- : "local";
2084
- const keyValue =
2085
- rawArg !== null &&
2086
- typeof rawArg === "object" &&
2087
- typeof (rawArg as { key?: unknown }).key === "string"
2088
- ? (rawArg as { key: string }).key
2089
- : "";
2090
- const storage = scopeValue === "session" ? window.sessionStorage : window.localStorage;
2091
- const value = storage.getItem(keyValue);
2092
- return {
2093
- scope: scopeValue,
2094
- key: keyValue,
2095
- exists: value !== null,
2096
- ...(value !== null ? { value } : {})
2097
- };
2098
- },
2099
- { scope, key }
2100
- );
2101
-
2102
- return {
2103
- ok: true,
2104
- executed: true,
2105
- data: isObjectRecord(result)
2106
- ? result
2107
- : {
2108
- scope,
2109
- key,
2110
- exists: false
2111
- }
2112
- };
2113
- }
2114
- case "storageSet": {
2115
- const scope = parseStorageScope(readActionPayloadString(payload, "scope"));
2116
- const key = readActionPayloadString(payload, "key");
2117
- const value = readActionPayloadString(payload, "value");
2118
- if (scope === undefined || key === undefined || value === undefined) {
2119
- return {
2120
- ok: false,
2121
- executed: false,
2122
- error: "action.payload.scope, action.payload.key and action.payload.value are required for storageSet action."
2123
- };
2124
- }
2125
-
2126
- const customStorageSetMethod = getObjectMethod(tab.page, "storageSet");
2127
- if (typeof customStorageSetMethod === "function") {
2128
- const customResult = await customStorageSetMethod.call(tab.page, scope, key, value);
2129
- return {
2130
- ok: true,
2131
- executed: true,
2132
- data: isObjectRecord(customResult)
2133
- ? customResult
2134
- : {
2135
- scope,
2136
- key,
2137
- value,
2138
- set: true
2139
- }
2140
- };
2141
- }
2142
-
2143
- await evaluateInPage(
2144
- tab.page,
2145
- (rawArg) => {
2146
- const scopeValue =
2147
- rawArg !== null &&
2148
- typeof rawArg === "object" &&
2149
- typeof (rawArg as { scope?: unknown }).scope === "string"
2150
- ? (rawArg as { scope: string }).scope
2151
- : "local";
2152
- const keyValue =
2153
- rawArg !== null &&
2154
- typeof rawArg === "object" &&
2155
- typeof (rawArg as { key?: unknown }).key === "string"
2156
- ? (rawArg as { key: string }).key
2157
- : "";
2158
- const valueText =
2159
- rawArg !== null &&
2160
- typeof rawArg === "object" &&
2161
- typeof (rawArg as { value?: unknown }).value === "string"
2162
- ? (rawArg as { value: string }).value
2163
- : "";
2164
- const storage = scopeValue === "session" ? window.sessionStorage : window.localStorage;
2165
- storage.setItem(keyValue, valueText);
2166
- },
2167
- { scope, key, value }
2168
- );
2169
-
2170
- return {
2171
- ok: true,
2172
- executed: true,
2173
- data: {
2174
- scope,
2175
- key,
2176
- value,
2177
- set: true
2178
- }
2179
- };
2180
- }
2181
- case "frameList": {
2182
- const customFrameListMethod = getObjectMethod(tab.page, "frameList");
2183
- if (typeof customFrameListMethod === "function") {
2184
- const customResult = await customFrameListMethod.call(tab.page);
2185
- return {
2186
- ok: true,
2187
- executed: true,
2188
- data: isObjectRecord(customResult)
2189
- ? customResult
2190
- : {
2191
- frames: []
2192
- }
2193
- };
2194
- }
2195
-
2196
- const framesMethod = getObjectMethod(tab.page, "frames");
2197
- if (typeof framesMethod !== "function") {
2198
- return {
2199
- ok: true,
2200
- executed: false
2201
- };
2202
- }
2203
-
2204
- const rawFrames = await framesMethod.call(tab.page);
2205
- if (!Array.isArray(rawFrames)) {
2206
- return {
2207
- ok: true,
2208
- executed: true,
2209
- data: {
2210
- frames: []
2211
- }
2212
- };
2213
- }
2214
-
2215
- const mainFrameMethod = getObjectMethod(tab.page, "mainFrame");
2216
- const mainFrame = typeof mainFrameMethod === "function" ? await mainFrameMethod.call(tab.page) : undefined;
2217
- const frames = rawFrames.map((frame, index) => {
2218
- const name = readObjectMethod<string>(frame, "name");
2219
- const url = readObjectMethod<string>(frame, "url") ?? "";
2220
- return {
2221
- frameId: `frame:${index}`,
2222
- index,
2223
- ...(typeof name === "string" && name.length > 0 ? { name } : {}),
2224
- url,
2225
- isMainFrame: frame === mainFrame
2226
- };
2227
- });
2228
-
2229
- return {
2230
- ok: true,
2231
- executed: true,
2232
- data: {
2233
- frames
2234
- }
2235
- };
2236
- }
2237
- case "frameSnapshot": {
2238
- const frameId = readActionPayloadString(payload, "frameId");
2239
- if (frameId === undefined) {
2240
- return {
2241
- ok: false,
2242
- executed: false,
2243
- error: "action.payload.frameId is required for frameSnapshot action."
2244
- };
2245
- }
2246
-
2247
- const customFrameSnapshotMethod = getObjectMethod(tab.page, "frameSnapshot");
2248
- if (typeof customFrameSnapshotMethod === "function") {
2249
- const customResult = await customFrameSnapshotMethod.call(tab.page, frameId);
2250
- return {
2251
- ok: true,
2252
- executed: true,
2253
- data: isObjectRecord(customResult)
2254
- ? customResult
2255
- : {
2256
- frameId,
2257
- found: false
2258
- }
2259
- };
2260
- }
2261
-
2262
- const frameIndex = parseFrameIndex(frameId);
2263
- if (frameIndex === undefined) {
2264
- return {
2265
- ok: false,
2266
- executed: false,
2267
- error: `Invalid frameId: ${frameId}`
2268
- };
2269
- }
2270
-
2271
- const framesMethod = getObjectMethod(tab.page, "frames");
2272
- if (typeof framesMethod !== "function") {
2273
- return {
2274
- ok: true,
2275
- executed: false
2276
- };
2277
- }
2278
-
2279
- const rawFrames = await framesMethod.call(tab.page);
2280
- if (!Array.isArray(rawFrames) || frameIndex >= rawFrames.length) {
2281
- return {
2282
- ok: true,
2283
- executed: true,
2284
- data: {
2285
- frameId,
2286
- found: false
2287
- }
2288
- };
2289
- }
2290
-
2291
- const frame = rawFrames[frameIndex];
2292
- const contentMethod = getObjectMethod(frame, "content");
2293
- if (typeof contentMethod !== "function") {
2294
- return {
2295
- ok: true,
2296
- executed: false
2297
- };
2298
- }
2299
-
2300
- const mainFrameMethod = getObjectMethod(tab.page, "mainFrame");
2301
- const mainFrame = typeof mainFrameMethod === "function" ? await mainFrameMethod.call(tab.page) : undefined;
2302
- const frameName = readObjectMethod<string>(frame, "name");
2303
- const frameUrl = readObjectMethod<string>(frame, "url") ?? "";
2304
- const frameHtml = await contentMethod.call(frame);
2305
-
2306
- return {
2307
- ok: true,
2308
- executed: true,
2309
- data: {
2310
- frameId,
2311
- index: frameIndex,
2312
- found: true,
2313
- ...(typeof frameName === "string" && frameName.length > 0 ? { name: frameName } : {}),
2314
- url: frameUrl,
2315
- isMainFrame: frame === mainFrame,
2316
- html: typeof frameHtml === "string" ? frameHtml : ""
2317
- }
2318
- };
2319
- }
2320
- default:
2321
- return {
2322
- ok: true,
2323
- executed: false
2324
- };
2325
- }
2326
- };
2327
-
2328
- try {
2329
- return {
2330
- ...baseResult,
2331
- ...(await performAction())
2332
- };
2333
- } catch (error) {
2334
- return {
2335
- ...baseResult,
2336
- ok: false,
2337
- executed: false,
2338
- error: toErrorMessage(error)
2339
- };
2340
- }
2341
- },
2342
- armUpload: async (targetId, files, profile) => {
2343
- const profileId = resolveProfileId(profile);
2344
- const operationState = getOrCreateTargetOperationState(profileId, targetId);
2345
- operationState.uploadFiles = [...files];
2346
- },
2347
- armDialog: async (targetId, profile) => {
2348
- const profileId = resolveProfileId(profile);
2349
- const operationState = getOrCreateTargetOperationState(profileId, targetId);
2350
- operationState.dialogArmedCount += 1;
2351
- },
2352
- waitDownload: async (targetId, profile, path) => {
2353
- const profileId = resolveProfileId(profile);
2354
- const { tab } = requireTargetInProfile(profileId, targetId);
2355
- const operationState = getOrCreateTargetOperationState(profileId, targetId);
2356
- const requestedPath = path !== undefined && path.trim().length > 0 ? path : undefined;
2357
- if (operationState.downloadInFlight === undefined && operationState.latestDownload !== undefined) {
2358
- const download = await resolveDownloadArtifactPath(
2359
- operationState,
2360
- { ...operationState.latestDownload },
2361
- requestedPath
2362
- );
2363
-
2364
- operationState.latestDownload = undefined;
2365
- operationState.latestRawDownload = undefined;
2366
- operationState.requestedDownloadPath = undefined;
2367
- return {
2368
- path: download.path,
2369
- profile: profileId,
2370
- targetId,
2371
- relayUrl,
2372
- uploadFiles: [...operationState.uploadFiles],
2373
- dialogArmedCount: operationState.dialogArmedCount,
2374
- triggerCount: operationState.triggerCount,
2375
- ...(download.suggestedFilename !== undefined
2376
- ? { suggestedFilename: download.suggestedFilename }
2377
- : {}),
2378
- ...(download.url !== undefined ? { url: download.url } : {}),
2379
- ...(download.mimeType !== undefined ? { mimeType: download.mimeType } : {})
2380
- };
2381
- }
2382
-
2383
- const inFlightDownload = await ensureDownloadInFlight(
2384
- profileId,
2385
- targetId,
2386
- tab,
2387
- operationState,
2388
- requestedPath
2389
- );
2390
- const download = await resolveDownloadArtifactPath(operationState, inFlightDownload, requestedPath);
2391
- operationState.latestDownload = undefined;
2392
- operationState.latestRawDownload = undefined;
2393
- operationState.requestedDownloadPath = undefined;
2394
-
2395
- return {
2396
- path: download.path,
2397
- profile: profileId,
2398
- targetId,
2399
- relayUrl,
2400
- uploadFiles: [...operationState.uploadFiles],
2401
- dialogArmedCount: operationState.dialogArmedCount,
2402
- triggerCount: operationState.triggerCount,
2403
- ...(download.suggestedFilename !== undefined
2404
- ? { suggestedFilename: download.suggestedFilename }
2405
- : {}),
2406
- ...(download.url !== undefined ? { url: download.url } : {}),
2407
- ...(download.mimeType !== undefined ? { mimeType: download.mimeType } : {})
2408
- };
2409
- },
2410
- triggerDownload: async (targetId, profile) => {
2411
- const profileId = resolveProfileId(profile);
2412
- const { tab } = requireTargetInProfile(profileId, targetId);
2413
- const operationState = getOrCreateTargetOperationState(profileId, targetId);
2414
- operationState.triggerCount += 1;
2415
- operationState.latestDownload = undefined;
2416
- operationState.latestRawDownload = undefined;
2417
- operationState.requestedDownloadPath = undefined;
2418
- void ensureDownloadInFlight(profileId, targetId, tab, operationState);
2419
- },
2420
- getConsoleEntries: (targetId, profile) => {
2421
- const telemetryState = findTelemetryState(targetId, profile);
2422
- return telemetryState === undefined ? [] : telemetryState.consoleEntries.map(cloneConsoleEntry);
2423
- },
2424
- getNetworkResponseBody: (requestId, targetId, profile) => {
2425
- const body = findTelemetryState(targetId, profile)?.networkResponseBodies.get(requestId);
2426
- return body === undefined ? undefined : { ...body };
2427
- }
2428
- };
2429
- }