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