@opencode/browse 0.0.17-dev.179 → 0.0.17-dev.181

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