@opencode/browse 0.0.18-dev.193 → 0.0.18-dev.198

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 (45) hide show
  1. package/dist/cli.mjs +62 -117
  2. package/package.json +13 -33
  3. package/dist/Runtime-r9sev1rq.mjs +0 -16
  4. package/dist/THIRD_PARTY_NOTICES.txt +0 -310
  5. package/dist/Undici-xgvbtsb1.mjs +0 -25295
  6. package/dist/cli-ekwkvvmm.mjs +0 -5943
  7. package/dist/coreBundle-mbshhes2.mjs +0 -8
  8. package/dist/helpers-3ycvp75a.mjs +0 -71
  9. package/dist/index-xsb9s479.mjs +0 -13
  10. package/dist/legacy-runtime-v1sdjj5h.mjs +0 -135
  11. package/dist/log-yek648ak.mjs +0 -9
  12. package/dist/main-1qwrze1y.mjs +0 -140
  13. package/dist/main-2p0v71q0.mjs +0 -1752
  14. package/dist/main-3g7fdzbh.mjs +0 -5360
  15. package/dist/main-55a4gpef.mjs +0 -1261
  16. package/dist/main-693wwz19.mjs +0 -4
  17. package/dist/main-91vhk5de.mjs +0 -38
  18. package/dist/main-9t32k44b.mjs +0 -798
  19. package/dist/main-bv9nawja.mjs +0 -5191
  20. package/dist/main-cgnkhs2x.mjs +0 -35
  21. package/dist/main-esdgpebk.mjs +0 -161
  22. package/dist/main-fg5awggs.mjs +0 -5514
  23. package/dist/main-gexpjhk5.mjs +0 -32
  24. package/dist/main-gt2gskrq.mjs +0 -160
  25. package/dist/main-gw77et6v.mjs +0 -342
  26. package/dist/main-j98fzrvv.mjs +0 -68
  27. package/dist/main-kcw411ep.mjs +0 -891
  28. package/dist/main-nnfxg7re.mjs +0 -11403
  29. package/dist/main-pcqtqhgv.mjs +0 -64
  30. package/dist/main-pmfd055v.mjs +0 -63
  31. package/dist/main-pxs5m0kb.mjs +0 -329
  32. package/dist/main-qazf3bhk.mjs +0 -223
  33. package/dist/main-sf7vaxb6.mjs +0 -17
  34. package/dist/main-stf180y1.mjs +0 -229
  35. package/dist/main-tk4axre7.mjs +0 -39
  36. package/dist/main-zedq93ez.mjs +0 -215
  37. package/dist/main-zzggnpf4.mjs +0 -73
  38. package/dist/mcp-xfx04fxe.mjs +0 -9470
  39. package/dist/migrate-4rewxqd7.mjs +0 -354
  40. package/dist/relay-me036e19.mjs +0 -18765
  41. package/dist/remove-stored-secrets-ymhge5va.mjs +0 -6
  42. package/dist/runtime-update-hd2cvy1c.mjs +0 -246
  43. package/dist/setup-0hmbzam5.mjs +0 -1052
  44. package/dist/update-vnkjbc0e.mjs +0 -17
  45. package/dist/version-jn0h3rmc.mjs +0 -8
@@ -1,891 +0,0 @@
1
- import {
2
- unpackedExtensionId,
3
- parseJsonObject
4
- } from "./main-9t32k44b.mjs";
5
- import {
6
- decodeUnknownOption,
7
- optionalKey,
8
- Literal,
9
- Unknown,
10
- String3,
11
- Number2,
12
- Boolean3,
13
- Struct,
14
- fieldsAssign,
15
- Record,
16
- ArraySchema,
17
- Union,
18
- Literals,
19
- NullOr,
20
- TaggedUnion,
21
- makeFilter,
22
- isPattern,
23
- isGreaterThanOrEqualTo,
24
- isBetween,
25
- isInt,
26
- Int2,
27
- NonEmptyString,
28
- TaggedError2,
29
- Json
30
- } from "./main-fg5awggs.mjs";
31
- import {
32
- isNone,
33
- match,
34
- succeed6,
35
- sync2,
36
- void_3,
37
- callback2,
38
- fail6,
39
- catch_
40
- } from "./main-bv9nawja.mjs";
41
- import {
42
- isString,
43
- isNumber,
44
- isObject
45
- } from "./main-qazf3bhk.mjs";
46
-
47
- // src/relay/schema.ts
48
- var SessionHandoff = Struct({
49
- message: String3,
50
- tabId: Number2,
51
- startedAt: String3
52
- });
53
- var SessionSummary = Struct({
54
- id: String3,
55
- createdAt: String3,
56
- updatedAt: String3,
57
- connected: Boolean3,
58
- pageUrl: NullOr(String3),
59
- stateKeys: ArraySchema(String3),
60
- readOnly: optionalKey(Boolean3),
61
- allowedOrigins: optionalKey(ArraySchema(String3)),
62
- keepVisible: optionalKey(Boolean3),
63
- browser: optionalKey(String3),
64
- handoff: optionalKey(SessionHandoff)
65
- });
66
- var ExecuteSessionSummary = SessionSummary.pipe(fieldsAssign({
67
- created: optionalKey(Boolean3)
68
- }));
69
- var SessionContainer = Struct({
70
- session: SessionSummary
71
- });
72
- var SessionsContainer = Struct({
73
- sessions: ArraySchema(SessionSummary)
74
- });
75
- var SessionStopReport = Struct({
76
- execute: Boolean3,
77
- handoff: Boolean3,
78
- forced: Boolean3
79
- });
80
- var SessionDeleted = Struct({
81
- deleted: Boolean3,
82
- id: String3,
83
- stopped: optionalKey(SessionStopReport)
84
- });
85
- var SessionResetResponse = Struct({
86
- session: SessionSummary,
87
- stopped: optionalKey(SessionStopReport)
88
- });
89
- var TargetSelection = Struct({
90
- urlIncludes: optionalKey(NonEmptyString),
91
- index: optionalKey(Int2.check(isGreaterThanOrEqualTo(0)))
92
- }).check(makeFilter((selection) => {
93
- const hasUrl = selection.urlIncludes !== undefined;
94
- const hasIndex = selection.index !== undefined;
95
- return hasUrl !== hasIndex ? undefined : "targetSelection must contain exactly one of urlIncludes or index";
96
- }));
97
- var ExecuteRequest = Struct({
98
- sessionId: optionalKey(String3),
99
- code: String3,
100
- createIfMissing: Boolean3,
101
- browser: optionalKey(String3),
102
- removeAfterExecute: optionalKey(Boolean3),
103
- timeoutMs: optionalKey(Int2.check(isGreaterThanOrEqualTo(0))),
104
- targetSelection: optionalKey(TargetSelection)
105
- });
106
- var SessionAdoptRequest = Struct({
107
- sessionId: optionalKey(String3),
108
- createIfMissing: Boolean3,
109
- targetSelection: optionalKey(TargetSelection),
110
- tabId: optionalKey(Int2)
111
- });
112
- var SessionNewRequest = Struct({
113
- id: optionalKey(String3),
114
- readOnly: optionalKey(Boolean3),
115
- allowedOrigins: optionalKey(ArraySchema(String3)),
116
- keepVisible: optionalKey(Boolean3),
117
- browser: optionalKey(String3)
118
- });
119
- var SessionEnsureRequest = Struct({
120
- id: NonEmptyString,
121
- readOnly: optionalKey(Boolean3)
122
- });
123
- var SessionIdRequest = Struct({
124
- id: String3
125
- });
126
- var SessionAllowlistRequest = Struct({
127
- id: String3,
128
- allowedOrigins: ArraySchema(String3)
129
- });
130
- var SessionAdoptResponse = Struct({
131
- session: ExecuteSessionSummary,
132
- adoptedUrl: String3,
133
- adoptedTargetId: String3
134
- });
135
- var ExecuteLogLocation = Struct({
136
- url: String3,
137
- lineNumber: Number2,
138
- columnNumber: Number2
139
- });
140
- var ExecuteLogEntry = Struct({
141
- source: Literals(["script", "page"]),
142
- type: String3,
143
- text: String3,
144
- location: optionalKey(ExecuteLogLocation),
145
- repeatCount: optionalKey(Number2)
146
- });
147
- var ExecuteLogSummary = Struct({
148
- totalCount: Number2,
149
- returnedCount: Number2,
150
- repeatedCount: Number2,
151
- omittedCount: Number2
152
- });
153
- var ExecuteAftermath = Struct({
154
- startUrl: NullOr(String3),
155
- endUrl: NullOr(String3),
156
- navigations: ArraySchema(String3),
157
- consoleErrorCount: Number2,
158
- pageErrorCount: Number2,
159
- handoffs: Number2,
160
- challenge: optionalKey(Struct({
161
- vendor: String3,
162
- kind: Literals(["non-interactive", "interactive", "block"]),
163
- status: Literals(["cleared", "blocked"]),
164
- signal: String3,
165
- url: String3,
166
- waitedMs: Number2,
167
- recommendation: Literals(["continue", "handoff", "stop"])
168
- }))
169
- });
170
- var ExecuteMedia = Struct({
171
- type: Literal("image"),
172
- mimeType: String3,
173
- data: String3,
174
- size: Number2
175
- });
176
- var ExecuteResponse = Struct({
177
- text: String3,
178
- value: optionalKey(Unknown),
179
- media: optionalKey(ArraySchema(ExecuteMedia)),
180
- isError: Boolean3,
181
- logs: ArraySchema(ExecuteLogEntry),
182
- logSummary: optionalKey(ExecuteLogSummary),
183
- warnings: optionalKey(ArraySchema(String3)),
184
- diagnostic: optionalKey(String3),
185
- aftermath: optionalKey(ExecuteAftermath),
186
- session: ExecuteSessionSummary
187
- });
188
- var AuthenticatedJsonMethod = Literals(["GET", "POST", "PUT", "PATCH", "DELETE"]);
189
- var AuthenticatedJsonRequest = Struct({
190
- sessionId: NonEmptyString,
191
- origin: NonEmptyString,
192
- startUrl: optionalKey(NonEmptyString),
193
- method: AuthenticatedJsonMethod,
194
- path: NonEmptyString,
195
- headers: optionalKey(Record(String3, String3)),
196
- body: optionalKey(Json),
197
- sensitive: optionalKey(Boolean3),
198
- handoffOnAuthFailure: optionalKey(Boolean3),
199
- handoffMessage: optionalKey(String3),
200
- timeoutMs: optionalKey(Int2.check(isBetween({ minimum: 1, maximum: 120000 }))),
201
- maxResponseBytes: optionalKey(Int2.check(isBetween({ minimum: 1, maximum: 1e7 })))
202
- });
203
- var AuthenticatedJsonOutcome = TaggedUnion({
204
- Success: {
205
- status: Int2,
206
- value: Json
207
- },
208
- OriginMismatch: {
209
- expectedOrigin: String3,
210
- actualOrigin: String3
211
- },
212
- RequestFailed: {
213
- outcome: Literals(["not-sent", "unknown"])
214
- },
215
- HttpError: {
216
- status: Int2
217
- },
218
- ResponseTooLarge: {
219
- status: Int2,
220
- maxResponseBytes: Int2
221
- },
222
- InvalidJson: {
223
- status: Int2
224
- },
225
- SensitiveCaptureActive: {}
226
- });
227
- var TargetSummary = Struct({
228
- id: String3,
229
- type: String3,
230
- title: String3,
231
- url: String3,
232
- tabId: optionalKey(Number2),
233
- sessionId: optionalKey(String3),
234
- opencodeBrowserSessionId: optionalKey(String3),
235
- owner: optionalKey(Literals(["relay", "user"])),
236
- crashed: optionalKey(Boolean3),
237
- protectedUi: optionalKey(Boolean3)
238
- });
239
- var TargetSummaries = ArraySchema(TargetSummary);
240
- var ConnectedBrowser = Struct({
241
- id: String3,
242
- name: String3,
243
- default: Boolean3,
244
- connected: Boolean3,
245
- unresponsive: optionalKey(Boolean3),
246
- version: NullOr(String3),
247
- tabs: Int2.check(isGreaterThanOrEqualTo(0))
248
- });
249
- var ExtensionStatus = Struct({
250
- connected: Boolean3,
251
- pairingState: optionalKey(Literals(["connected", "incompatible", "refused", "unpaired", "paired-offline", "not-seen"])),
252
- nextStep: optionalKey(String3),
253
- version: NullOr(String3),
254
- build: optionalKey(NullOr(String3)),
255
- origin: optionalKey(NullOr(String3)),
256
- protocolVersion: optionalKey(NullOr(Number2)),
257
- protocolCompatible: optionalKey(NullOr(Boolean3)),
258
- protocolLegacy: optionalKey(NullOr(Boolean3)),
259
- browsers: optionalKey(ArraySchema(ConnectedBrowser)),
260
- rejectedConnections: optionalKey(Int2.check(isGreaterThanOrEqualTo(0))),
261
- pairingFailures: optionalKey(Int2.check(isGreaterThanOrEqualTo(0))),
262
- processFaults: optionalKey(Struct({
263
- suppressed: Int2.check(isGreaterThanOrEqualTo(0)),
264
- lastAt: optionalKey(String3),
265
- lastMessage: optionalKey(String3)
266
- })),
267
- activeTargets: Number2,
268
- childTargets: optionalKey(Number2),
269
- cdpClients: optionalKey(Number2),
270
- sessions: optionalKey(ArraySchema(SessionSummary)),
271
- targets: optionalKey(TargetSummaries)
272
- });
273
- var RelayVersion = Struct({
274
- version: String3,
275
- buildId: optionalKey(String3),
276
- instanceId: optionalKey(String3),
277
- startedAt: optionalKey(String3),
278
- pid: optionalKey(Number2),
279
- managed: optionalKey(Boolean3),
280
- shutdownProtocol: optionalKey(Literal(2))
281
- });
282
- var RelayIdentity = String3.check(isPattern(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}(?![\s\S])/));
283
- var RelayBuildId = String3.check(isPattern(/^[A-Za-z0-9][A-Za-z0-9._:+-]{0,255}(?![\s\S])/));
284
- var RelayShutdownRequest = Struct({
285
- instanceId: RelayIdentity,
286
- requestId: RelayIdentity,
287
- reason: Literal("explicit-restart"),
288
- client: Struct({
289
- kind: Literals(["cli", "mcp", "sdk"]),
290
- instanceId: RelayIdentity,
291
- buildId: RelayBuildId
292
- }),
293
- force: optionalKey(Boolean3)
294
- });
295
- var RelayShutdownResponse = Struct({
296
- stopping: Literal(true)
297
- });
298
- var NetworkStartRequest = Struct({
299
- sessionId: NonEmptyString,
300
- urlFilter: optionalKey(String3)
301
- });
302
- var NetworkSessionRequest = Struct({ sessionId: NonEmptyString });
303
- var NetworkStatusResponse = Struct({
304
- active: Boolean3,
305
- startedAt: optionalKey(String3),
306
- entryCount: Number2,
307
- responseCount: Number2,
308
- failureCount: Number2,
309
- capturedBodyBytes: Number2,
310
- truncatedBodyCount: Number2,
311
- droppedEntryCount: Number2,
312
- urlFilter: optionalKey(String3),
313
- endsAt: optionalKey(String3),
314
- ended: optionalKey(String3)
315
- });
316
- var NetworkHeader = Struct({
317
- name: String3,
318
- value: String3
319
- });
320
- var NetworkBody = Struct({
321
- size: Number2,
322
- mimeType: String3,
323
- text: optionalKey(String3),
324
- truncated: Boolean3
325
- });
326
- var NetworkExchange = Struct({
327
- id: String3,
328
- startedDateTime: String3,
329
- durationMs: Number2,
330
- request: Struct({
331
- method: String3,
332
- url: String3,
333
- headers: ArraySchema(NetworkHeader),
334
- resourceType: String3,
335
- body: optionalKey(NetworkBody),
336
- redirectedFrom: optionalKey(String3)
337
- }),
338
- response: optionalKey(Struct({
339
- status: Number2,
340
- statusText: String3,
341
- headers: ArraySchema(NetworkHeader),
342
- body: optionalKey(NetworkBody)
343
- })),
344
- failure: optionalKey(String3)
345
- });
346
- var NetworkStopRequest = NetworkSessionRequest;
347
- var NetworkStopResponse = NetworkStatusResponse.pipe(fieldsAssign({
348
- active: Literal(false),
349
- stoppedAt: String3,
350
- exchanges: ArraySchema(NetworkExchange)
351
- }));
352
- var NetworkCancelResponse = Struct({ cancelled: Boolean3 });
353
- var RecordingFrameRate = Number2.check(isInt(), isBetween({ minimum: 1, maximum: 60 }));
354
- var RecordingQuality = Struct({
355
- width: Number2,
356
- height: Number2,
357
- frameRate: Number2,
358
- sourceFrameCount: Number2,
359
- encodedSourceFrameCount: Number2,
360
- coalescedFrameCount: Number2,
361
- droppedFrameCount: Number2,
362
- achievedSourceFrameRate: Number2,
363
- achievedEncodedSourceFrameRate: Number2,
364
- screenshotFallback: Boolean3,
365
- sourceWidth: optionalKey(Number2),
366
- sourceHeight: optionalKey(Number2)
367
- });
368
- var RecordingTargetRequest = Struct({
369
- sessionId: optionalKey(String3),
370
- tabId: optionalKey(Number2)
371
- });
372
- var RecordingStartRequest = RecordingTargetRequest.pipe(fieldsAssign({
373
- outputPath: String3,
374
- frameRate: optionalKey(RecordingFrameRate),
375
- maxDurationMs: optionalKey(Number2)
376
- }));
377
- var RecordingArtifactType = Literals(["webm", "mp4"]);
378
- var RecordingStartResponse = Struct({
379
- success: Boolean3,
380
- tabId: optionalKey(Number2),
381
- startedAt: optionalKey(Number2),
382
- path: optionalKey(String3),
383
- mimeType: optionalKey(String3),
384
- artifactType: optionalKey(RecordingArtifactType),
385
- frameRate: optionalKey(Number2),
386
- error: optionalKey(String3)
387
- });
388
- var RecordingStopResponse = Struct({
389
- success: Boolean3,
390
- tabId: optionalKey(Number2),
391
- duration: optionalKey(Number2),
392
- path: optionalKey(String3),
393
- size: optionalKey(Number2),
394
- artifactType: optionalKey(RecordingArtifactType),
395
- frameCount: optionalKey(Number2),
396
- quality: optionalKey(RecordingQuality),
397
- error: optionalKey(String3)
398
- });
399
- var RecordingStatusResponse = Struct({
400
- isRecording: Boolean3,
401
- tabId: optionalKey(Number2),
402
- startedAt: optionalKey(Number2),
403
- path: optionalKey(String3),
404
- size: optionalKey(Number2),
405
- artifactType: optionalKey(RecordingArtifactType),
406
- frameCount: optionalKey(Number2),
407
- quality: optionalKey(RecordingQuality)
408
- });
409
- var TabsCleanupResponse = Struct({
410
- closed: ArraySchema(Struct({ tabId: Number2, title: String3, idleMinutes: Number2 }))
411
- });
412
- var SettingValue = Union([String3, Number2]);
413
- var SettingReport = Struct({
414
- value: SettingValue,
415
- effective: SettingValue,
416
- allowed: ArraySchema(SettingValue),
417
- description: String3,
418
- overriddenBy: optionalKey(String3)
419
- });
420
- var SettingsGetResponse = Struct({
421
- settings: Record(String3, SettingReport),
422
- note: String3
423
- });
424
- var SettingsSetResponse = Struct({
425
- changed: ArraySchema(Struct({ key: String3, from: SettingValue, to: SettingValue })),
426
- unchanged: ArraySchema(String3),
427
- overridden: ArraySchema(Struct({ key: String3, requested: SettingValue, variable: String3, effective: SettingValue })),
428
- settings: Record(String3, SettingReport),
429
- message: String3
430
- });
431
- var RecordingCancelResponse = Struct({
432
- success: Boolean3,
433
- error: optionalKey(String3)
434
- });
435
- var RelayErrorCode = Literals([
436
- "browser-unavailable",
437
- "invalid-request",
438
- "unauthorized",
439
- "relay-starting",
440
- "relay-busy",
441
- "auth-profile-not-found",
442
- "capture-conflict",
443
- "session-already-exists",
444
- "session-inactive",
445
- "session-not-found",
446
- "session-timeout",
447
- "setup-failed",
448
- "target-ambiguous",
449
- "target-changed",
450
- "target-not-found",
451
- "target-owned",
452
- "internal"
453
- ]);
454
- var ErrorEnvelope = Struct({
455
- error: String3,
456
- code: optionalKey(RelayErrorCode)
457
- });
458
-
459
- // src/relay/http.ts
460
- var maxCliBodyBytes = 1e6;
461
-
462
- class HttpRouteError2 extends TaggedError2()("HttpApi.HttpRouteError", { message: String3, status: Number2, code: RelayErrorCode }) {
463
- }
464
- function formatHostForUrl2(host) {
465
- if (host.includes(":") && !host.startsWith("[")) {
466
- return `[${host}]`;
467
- }
468
- return host;
469
- }
470
- function listenHttpServer2(options) {
471
- return callback2((resume) => {
472
- const onError = (error) => {
473
- resume(fail6(error));
474
- };
475
- options.server.once("error", onError);
476
- options.server.listen(options.port, options.host, () => {
477
- options.server.off("error", onError);
478
- resume(void_3);
479
- });
480
- return sync2(() => {
481
- options.server.off("error", onError);
482
- });
483
- });
484
- }
485
- function closeHttpServer2(server) {
486
- if (!server.listening) {
487
- return void_3;
488
- }
489
- return callback2((resume) => {
490
- server.close((error) => {
491
- if (error) {
492
- resume(fail6(new Error("close http server", { cause: error })));
493
- return;
494
- }
495
- resume(void_3);
496
- });
497
- server.closeAllConnections();
498
- return void_3;
499
- });
500
- }
501
- function closeWebSocketServer2(server) {
502
- return callback2((resume) => {
503
- server.close((error) => {
504
- const nodeError = error;
505
- if (nodeError?.code === "ERR_SERVER_NOT_RUNNING") {
506
- resume(void_3);
507
- return;
508
- }
509
- if (error) {
510
- resume(fail6(new Error("close websocket server", { cause: error })));
511
- return;
512
- }
513
- resume(void_3);
514
- });
515
- return void_3;
516
- });
517
- }
518
- function logCloseError2(message) {
519
- return (effect) => {
520
- return catch_(effect, (error) => {
521
- return sync2(() => {
522
- console.error(message, error);
523
- });
524
- });
525
- };
526
- }
527
- function sendJson2(response, value, status = 200) {
528
- response.writeHead(status, { "content-type": "application/json" });
529
- response.end(JSON.stringify(value));
530
- }
531
- function readJsonBody2(request) {
532
- const contentType = request.headers["content-type"];
533
- const contentTypeValue = Array.isArray(contentType) ? contentType[0] : contentType;
534
- if (!contentTypeValue?.toLowerCase().includes("application/json")) {
535
- return fail6(new HttpRouteError2({ message: "Content-Type must be application/json", status: 415, code: "invalid-request" }));
536
- }
537
- return callback2((resume) => {
538
- const chunks = [];
539
- let totalBytes = 0;
540
- let completed = false;
541
- const onData = (chunk) => {
542
- if (completed) {
543
- return;
544
- }
545
- totalBytes += chunk.byteLength;
546
- if (totalBytes > maxCliBodyBytes) {
547
- completed = true;
548
- request.destroy(new Error(`Request body exceeds ${maxCliBodyBytes} bytes`));
549
- resume(fail6(new HttpRouteError2({ message: `Request body exceeds ${maxCliBodyBytes} bytes`, status: 413, code: "invalid-request" })));
550
- return;
551
- }
552
- chunks.push(chunk);
553
- };
554
- const onError = (error) => {
555
- if (completed) {
556
- return;
557
- }
558
- completed = true;
559
- resume(fail6(new Error("read request body", { cause: error })));
560
- };
561
- const onAbort = () => {
562
- if (completed) {
563
- return;
564
- }
565
- completed = true;
566
- resume(fail6(new Error("request body aborted")));
567
- };
568
- const onClose = () => {
569
- if (completed || request.complete) {
570
- return;
571
- }
572
- completed = true;
573
- resume(fail6(new Error("request closed before body completed")));
574
- };
575
- const onEnd = () => {
576
- if (completed) {
577
- return;
578
- }
579
- completed = true;
580
- const text = Buffer.concat(chunks).toString("utf8");
581
- if (!text.trim()) {
582
- resume(succeed6({}));
583
- return;
584
- }
585
- try {
586
- resume(succeed6(parseJsonObject(text)));
587
- } catch (error) {
588
- resume(fail6(new HttpRouteError2({ message: "Invalid JSON body", status: 400, code: "invalid-request" })));
589
- }
590
- };
591
- request.on("data", onData);
592
- request.on("error", onError);
593
- request.on("aborted", onAbort);
594
- request.on("close", onClose);
595
- request.on("end", onEnd);
596
- return sync2(() => {
597
- request.off("data", onData);
598
- request.off("error", onError);
599
- request.off("aborted", onAbort);
600
- request.off("close", onClose);
601
- request.off("end", onEnd);
602
- });
603
- });
604
- }
605
-
606
- // src/relay/origins.ts
607
- import crypto from "node:crypto";
608
- var stableUnpackedExtensionOrigin2 = `chrome-extension://${unpackedExtensionId}`;
609
- function chromeExtensionOriginForPath2(extensionPath, platform = process.platform) {
610
- const normalizedPath = platform === "win32" && /^[a-z]:/.test(extensionPath) ? extensionPath.charAt(0).toUpperCase() + extensionPath.slice(1) : extensionPath;
611
- const pathBytes = platform === "win32" ? Buffer.from(normalizedPath, "utf16le") : normalizedPath;
612
- const digest = crypto.createHash("sha256").update(pathBytes).digest();
613
- let extensionId = "";
614
- for (const byte of digest.subarray(0, 16)) {
615
- extensionId += String.fromCharCode(97 + (byte >> 4), 97 + (byte & 15));
616
- }
617
- return `chrome-extension://${extensionId}`;
618
- }
619
- var chromeExtensionOriginPattern = /^chrome-extension:\/\/[a-p]+$/;
620
- function parseAdditionalExtensionOrigins2(raw) {
621
- if (!raw) {
622
- return [];
623
- }
624
- const seen = new Set;
625
- const origins = [];
626
- for (const token of raw.split(/[\s,]+/)) {
627
- const value = token.trim();
628
- if (!value || !chromeExtensionOriginPattern.test(value) || seen.has(value)) {
629
- continue;
630
- }
631
- seen.add(value);
632
- origins.push(value);
633
- }
634
- return origins;
635
- }
636
- function validateHostHeader2(options) {
637
- const parsed = parseHostHeader(options.hostHeader);
638
- if (!parsed) {
639
- return "Invalid Host header";
640
- }
641
- if (parsed.port !== undefined && parsed.port !== options.port) {
642
- return "Invalid Host header port";
643
- }
644
- const allowedHosts = new Set(["localhost", "127.0.0.1", "::1", normalizeHostname(options.host)]);
645
- if (!allowedHosts.has(parsed.hostname)) {
646
- return "Invalid Host header";
647
- }
648
- return;
649
- }
650
- function validateBrowserFetchSite2(request) {
651
- const secFetchSite = request.headers["sec-fetch-site"];
652
- const value = Array.isArray(secFetchSite) ? secFetchSite[0] : secFetchSite;
653
- if (!value || value === "same-origin" || value === "none") {
654
- return;
655
- }
656
- return "Cross-origin browser requests are not allowed";
657
- }
658
- function validateWebSocketOrigin2(options) {
659
- if (!options.origin) {
660
- return options.requireChromeExtension ? "Extension WebSocket origin is required" : undefined;
661
- }
662
- if (options.origin === stableUnpackedExtensionOrigin2 || options.additionalChromeExtensionOrigins?.has(options.origin)) {
663
- return;
664
- }
665
- if (options.requireChromeExtension) {
666
- return "Extension WebSocket origin is not allowed";
667
- }
668
- return "WebSocket origin is not allowed";
669
- }
670
- function normalizeHostname(host) {
671
- const value = host.trim().toLowerCase();
672
- if (value.startsWith("[") && value.endsWith("]")) {
673
- return value.slice(1, -1);
674
- }
675
- return value;
676
- }
677
- function parseHostHeader(hostHeader) {
678
- const value = hostHeader?.trim().toLowerCase();
679
- if (!value) {
680
- return;
681
- }
682
- if (value.startsWith("[")) {
683
- const closingBracket = value.indexOf("]");
684
- if (closingBracket === -1) {
685
- return;
686
- }
687
- const hostname = value.slice(1, closingBracket);
688
- const rest = value.slice(closingBracket + 1);
689
- if (!hostname) {
690
- return;
691
- }
692
- if (!rest) {
693
- return { hostname };
694
- }
695
- if (!rest.startsWith(":")) {
696
- return;
697
- }
698
- const port = parsePort(rest.slice(1));
699
- return port === undefined ? undefined : { hostname, port };
700
- }
701
- if (value === "::1") {
702
- return { hostname: "::1" };
703
- }
704
- const colonCount = value.split(":").length - 1;
705
- if (colonCount > 1) {
706
- return;
707
- }
708
- if (colonCount === 0) {
709
- return { hostname: value };
710
- }
711
- const [hostname, portText] = value.split(":");
712
- if (!hostname || portText === undefined) {
713
- return;
714
- }
715
- const port = parsePort(portText);
716
- return port === undefined ? undefined : { hostname, port };
717
- }
718
- function parsePort(value) {
719
- if (!/^\d+$/.test(value)) {
720
- return;
721
- }
722
- const port = Number(value);
723
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
724
- return;
725
- }
726
- return port;
727
- }
728
-
729
- // src/relay/helpers.ts
730
- var defaultHost2 = "127.0.0.1";
731
- var defaultPort2 = 19988;
732
- var RawTargetSelection = Struct({
733
- urlIncludes: optionalKey(String3),
734
- index: optionalKey(Int2.check(isGreaterThanOrEqualTo(0)))
735
- });
736
- var decodeRawTargetSelection = decodeUnknownOption(RawTargetSelection);
737
- var RawTargetInfo = Struct({
738
- targetId: String3,
739
- type: Literals(["page", "iframe", "worker"]),
740
- title: optionalKey(String3),
741
- url: String3,
742
- canAccessOpener: optionalKey(Boolean3),
743
- browserContextId: optionalKey(String3),
744
- openerId: optionalKey(String3),
745
- parentFrameId: optionalKey(String3)
746
- });
747
- var decodeRawTargetInfo = decodeUnknownOption(RawTargetInfo);
748
- function optionalSessionId2(value) {
749
- if (!isString(value) || !value.trim()) {
750
- return;
751
- }
752
- const id = value.trim();
753
- if (!isValidSessionId2(id)) {
754
- throw new HttpRouteError2({
755
- message: "Session ids must use lowercase letters, numbers, and dashes, and be at most 63 characters",
756
- status: 400,
757
- code: "invalid-request"
758
- });
759
- }
760
- return id;
761
- }
762
- function isValidSessionId2(id) {
763
- if (id.length < 1 || id.length > 63 || id === "." || id === "..")
764
- return false;
765
- if (/[A-Z/\\:\0-\x1f\x7f]/.test(id))
766
- return false;
767
- return /^(?:[\p{Extended_Pictographic}\u200d\ufe0f]+\s*)?[a-z0-9][a-z0-9\p{Extended_Pictographic}\u200d\ufe0f\s_-]*$/u.test(id);
768
- }
769
- function requiredSessionId2(value) {
770
- const id = optionalSessionId2(value);
771
- if (!id) {
772
- throw new HttpRouteError2({ message: "sessionId is required", status: 400, code: "invalid-request" });
773
- }
774
- return id;
775
- }
776
- function parseTargetSelection2(value) {
777
- if (value === undefined) {
778
- return;
779
- }
780
- if (!getObject2(value)) {
781
- throw new HttpRouteError2({ message: "targetSelection must be an object", status: 400, code: "invalid-request" });
782
- }
783
- const decoded = decodeRawTargetSelection(value);
784
- if (isNone(decoded)) {
785
- throw new HttpRouteError2({ message: "targetSelection.index must be a non-negative integer", status: 400, code: "invalid-request" });
786
- }
787
- const urlIncludes = decoded.value.urlIncludes ? decoded.value.urlIncludes : undefined;
788
- const index = decoded.value.index;
789
- if (urlIncludes && index !== undefined) {
790
- throw new HttpRouteError2({ message: "Use only one target selector", status: 400, code: "invalid-request" });
791
- }
792
- return {
793
- ...urlIncludes ? { urlIncludes } : {},
794
- ...index !== undefined ? { index } : {}
795
- };
796
- }
797
- function generateSessionId2(existing) {
798
- const adjectives = ["amber", "brisk", "calm", "clever", "cosmic", "gentle", "lucky", "quiet", "rapid", "tidy"];
799
- const nouns = ["badger", "comet", "falcon", "otter", "panda", "raven", "sparrow", "tiger", "walrus", "wombat"];
800
- for (let attempt = 0;attempt < 100; attempt++) {
801
- const adjective = adjectives[Math.floor(Math.random() * adjectives.length)] ?? "calm";
802
- const noun = nouns[Math.floor(Math.random() * nouns.length)] ?? "otter";
803
- const suffix = String(Math.floor(Math.random() * 1000)).padStart(3, "0");
804
- const id = `${adjective}-${noun}-${suffix}`;
805
- if (!existing.has(id)) {
806
- return id;
807
- }
808
- }
809
- return `session-${Date.now().toString(36)}`;
810
- }
811
- function sendCdpResponse2(socket, response) {
812
- socket.send(JSON.stringify(response));
813
- }
814
- function sendCdpEvent2(socket, event) {
815
- socket.send(JSON.stringify(event));
816
- }
817
- function getObject2(value) {
818
- return isObject(value) ? value : undefined;
819
- }
820
- function getString2(object, key) {
821
- const value = object?.[key];
822
- return isString(value) ? value : undefined;
823
- }
824
- function createTargetUrl2(params) {
825
- const url = getString2(params, "url");
826
- return url === undefined || url === "" ? "about:blank" : url;
827
- }
828
- function getNumber2(object, key) {
829
- const value = object?.[key];
830
- return isNumber(value) ? value : undefined;
831
- }
832
- function getIdText2(object, key) {
833
- const value = object?.[key];
834
- return isNumber(value) || isString(value) ? String(value) : undefined;
835
- }
836
- function headerValue2(value) {
837
- if (!isString(value) || !value)
838
- return;
839
- try {
840
- return decodeURIComponent(value);
841
- } catch {
842
- return value;
843
- }
844
- }
845
- function getTargetInfo2(value) {
846
- return match(decodeRawTargetInfo(value), {
847
- onNone: () => {
848
- return;
849
- },
850
- onSome: (info) => ({
851
- targetId: info.targetId,
852
- type: info.type,
853
- title: info.title ?? info.url,
854
- url: info.url,
855
- attached: true,
856
- canAccessOpener: info.canAccessOpener ?? false,
857
- ...info.browserContextId === undefined ? {} : { browserContextId: info.browserContextId },
858
- ...info.openerId === undefined ? {} : { openerId: info.openerId },
859
- ...info.parentFrameId === undefined ? {} : { parentFrameId: info.parentFrameId }
860
- })
861
- });
862
- }
863
- function isRestrictedTarget2(targetInfo) {
864
- if (targetInfo.type !== "page" && targetInfo.type !== "iframe" && targetInfo.type !== "worker") {
865
- return true;
866
- }
867
- return isRestrictedUrl2(targetInfo.url);
868
- }
869
- var restrictedUrlPrefixes = ["chrome://", "chrome-extension://", "chrome-untrusted://", "devtools://", "edge://", "brave://"];
870
- function isRestrictedUrl2(url) {
871
- if (!url) {
872
- return false;
873
- }
874
- return restrictedUrlPrefixes.some((prefix) => url.startsWith(prefix));
875
- }
876
- async function dataUrlDocument2(url) {
877
- const response = await fetch(url);
878
- const type = (response.headers.get("content-type") ?? "text/plain").split(";")[0]?.trim().toLowerCase() ?? "text/plain";
879
- if (type === "text/html" || type === "application/xhtml+xml")
880
- return await response.text();
881
- if (type.startsWith("text/") || type === "application/json" || type.endsWith("+json") || type === "application/javascript") {
882
- const text = (await response.text()).replace(/[&<>]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[char] ?? char);
883
- return `<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">${text}</pre></body></html>`;
884
- }
885
- if (type.startsWith("image/")) {
886
- return `<html><body style="margin: 0; display: grid; place-items: center; min-height: 100vh;"><img src="${url.replace(/"/g, "%22")}"></body></html>`;
887
- }
888
- return;
889
- }
890
-
891
- export { SessionContainer, SessionsContainer, SessionDeleted, SessionResetResponse, ExecuteRequest, SessionAdoptRequest, SessionNewRequest, SessionEnsureRequest, SessionIdRequest, SessionAllowlistRequest, SessionAdoptResponse, ExecuteLogEntry, ExecuteLogSummary, ExecuteAftermath, ExecuteResponse, AuthenticatedJsonRequest, AuthenticatedJsonOutcome, TargetSummaries, ExtensionStatus, RelayVersion, RelayShutdownRequest, RelayShutdownResponse, NetworkStartRequest, NetworkSessionRequest, NetworkStatusResponse, NetworkStopRequest, NetworkStopResponse, NetworkCancelResponse, RecordingQuality, RecordingTargetRequest, RecordingStartRequest, RecordingStartResponse, RecordingStopResponse, RecordingStatusResponse, TabsCleanupResponse, SettingsGetResponse, SettingsSetResponse, RecordingCancelResponse, RelayErrorCode, ErrorEnvelope, HttpRouteError2, formatHostForUrl2, listenHttpServer2, closeHttpServer2, closeWebSocketServer2, logCloseError2, sendJson2, readJsonBody2, stableUnpackedExtensionOrigin2, chromeExtensionOriginForPath2, parseAdditionalExtensionOrigins2, validateHostHeader2, validateBrowserFetchSite2, validateWebSocketOrigin2, defaultHost2, defaultPort2, optionalSessionId2, isValidSessionId2, requiredSessionId2, parseTargetSelection2, generateSessionId2, sendCdpResponse2, sendCdpEvent2, getObject2, getString2, createTargetUrl2, getNumber2, getIdText2, headerValue2, getTargetInfo2, isRestrictedTarget2, isRestrictedUrl2, dataUrlDocument2 };