@effect-agent/platform-cloudflare 0.1.0-beta.8 → 0.1.0-beta.80

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 (100) hide show
  1. package/dist/Alarm.d.mts +183 -0
  2. package/dist/Alarm.mjs +454 -0
  3. package/dist/Alarm.mjs.map +1 -0
  4. package/dist/BrowserRestCapture.d.mts +35 -0
  5. package/dist/BrowserRestCapture.mjs +238 -0
  6. package/dist/BrowserRestCapture.mjs.map +1 -0
  7. package/dist/BrowserRestCrawl.d.mts +17 -0
  8. package/dist/BrowserRestCrawl.mjs +244 -0
  9. package/dist/BrowserRestCrawl.mjs.map +1 -0
  10. package/dist/CloudflareAiGateway.d.mts +64 -0
  11. package/dist/CloudflareAiGateway.mjs +70 -0
  12. package/dist/CloudflareAiGateway.mjs.map +1 -0
  13. package/dist/CloudflareBindings.d.mts +112 -0
  14. package/dist/CloudflareBindings.mjs +101 -0
  15. package/dist/CloudflareBindings.mjs.map +1 -0
  16. package/dist/CloudflareBrowser-D4YqaTAl.mjs +495 -0
  17. package/dist/CloudflareBrowser-D4YqaTAl.mjs.map +1 -0
  18. package/dist/CloudflareBrowser-DJq53niJ.d.mts +80 -0
  19. package/dist/CloudflareBrowser.d.mts +2 -0
  20. package/dist/CloudflareBrowser.mjs +2 -0
  21. package/dist/CloudflareCodeMode.d.mts +44 -0
  22. package/dist/CloudflareCodeMode.mjs +616 -0
  23. package/dist/CloudflareCodeMode.mjs.map +1 -0
  24. package/dist/CloudflareConfig-f3CqTel1.d.mts +101 -0
  25. package/dist/CloudflareConfig.d.mts +2 -0
  26. package/dist/CloudflareConfig.mjs +122 -0
  27. package/dist/CloudflareConfig.mjs.map +1 -0
  28. package/dist/CloudflareMemory.d.mts +142 -0
  29. package/dist/CloudflareMemory.mjs +195 -0
  30. package/dist/CloudflareMemory.mjs.map +1 -0
  31. package/dist/CloudflareScheduling.d.mts +52 -0
  32. package/dist/CloudflareScheduling.mjs +389 -0
  33. package/dist/CloudflareScheduling.mjs.map +1 -0
  34. package/dist/CloudflareSubscriptions.d.mts +87 -0
  35. package/dist/CloudflareSubscriptions.mjs +524 -0
  36. package/dist/CloudflareSubscriptions.mjs.map +1 -0
  37. package/dist/CloudflareThreadClient.d.mts +1286 -0
  38. package/dist/CloudflareThreadClient.mjs +386 -0
  39. package/dist/CloudflareThreadClient.mjs.map +1 -0
  40. package/dist/InteractiveBrowser.d.mts +144 -0
  41. package/dist/InteractiveBrowser.mjs +1090 -0
  42. package/dist/InteractiveBrowser.mjs.map +1 -0
  43. package/dist/ProtectedBrowser.d.mts +65 -0
  44. package/dist/ProtectedBrowser.mjs +859 -0
  45. package/dist/ProtectedBrowser.mjs.map +1 -0
  46. package/dist/ThreadObject-3uDpKfB3.d.mts +816 -0
  47. package/dist/ThreadObject-DGkXv41C.mjs +836 -0
  48. package/dist/ThreadObject-DGkXv41C.mjs.map +1 -0
  49. package/dist/ThreadObject.d.mts +2 -0
  50. package/dist/ThreadObject.mjs +3 -0
  51. package/dist/WakeScheduler.d.mts +23 -0
  52. package/dist/WakeScheduler.mjs +60 -0
  53. package/dist/WakeScheduler.mjs.map +1 -0
  54. package/dist/boundary-BguazVkh.mjs +42 -0
  55. package/dist/boundary-BguazVkh.mjs.map +1 -0
  56. package/dist/browser-session-lifecycle-CUbVfEgP.mjs +84 -0
  57. package/dist/browser-session-lifecycle-CUbVfEgP.mjs.map +1 -0
  58. package/dist/browser-session-lifecycle-DJpqLXy_.d.mts +21 -0
  59. package/dist/index.d.mts +13 -1547
  60. package/dist/index.mjs +13 -1636
  61. package/dist/prepared-admission-DSi55W-7.mjs +73 -0
  62. package/dist/prepared-admission-DSi55W-7.mjs.map +1 -0
  63. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  64. package/package.json +1 -53
  65. package/src/Alarm.ts +953 -0
  66. package/src/BrowserRestCapture.ts +477 -0
  67. package/src/BrowserRestCrawl.ts +540 -0
  68. package/src/CloudflareAiGateway.ts +170 -0
  69. package/src/CloudflareBindings.ts +180 -0
  70. package/src/CloudflareBrowser.ts +15 -0
  71. package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +372 -204
  72. package/src/{config.ts → CloudflareConfig.ts} +9 -8
  73. package/src/CloudflareMemory.ts +406 -0
  74. package/src/CloudflareScheduling.ts +733 -0
  75. package/src/CloudflareSubscriptions.ts +1045 -0
  76. package/src/CloudflareThreadClient.ts +807 -0
  77. package/src/InteractiveBrowser.ts +2357 -0
  78. package/src/ProtectedBrowser.ts +2 -0
  79. package/src/ThreadObject.ts +1179 -0
  80. package/src/{wake-scheduler.ts → WakeScheduler.ts} +23 -23
  81. package/src/index.ts +12 -23
  82. package/src/internal/boundary.ts +55 -0
  83. package/src/internal/browser-quick-action.ts +857 -0
  84. package/src/internal/browser-session-lifecycle.ts +160 -0
  85. package/src/internal/layers.ts +751 -0
  86. package/src/internal/message-delivery.ts +148 -0
  87. package/src/internal/prepared-admission.ts +116 -0
  88. package/src/internal/progress-wait.ts +121 -0
  89. package/src/internal/transport.ts +42 -0
  90. package/src/protected-browser/binding.ts +187 -0
  91. package/src/protected-browser/inspect-frame.ts +125 -0
  92. package/src/protected-browser/native.ts +429 -0
  93. package/src/protected-browser/policy.ts +719 -0
  94. package/dist/index.mjs.map +0 -1
  95. package/src/alarm.ts +0 -334
  96. package/src/bindings.ts +0 -145
  97. package/src/client.ts +0 -646
  98. package/src/conversation-object.ts +0 -768
  99. package/src/layers.ts +0 -376
  100. package/src/transport.ts +0 -38
@@ -0,0 +1,1090 @@
1
+ import { n as BrowserRunSessionLifecycle, t as BrowserRunCleanupError } from "./browser-session-lifecycle-CUbVfEgP.mjs";
2
+ import { Clock, Context, Duration, Effect, Layer, Option, Redacted, Ref, Schema, Semaphore } from "effect";
3
+ import { PageScreenshotResult } from "@effect-agent/sandbox/PageScreenshot";
4
+ import { SandboxImplementation } from "@effect-agent/sandbox/Sandbox";
5
+ import puppeteer from "@cloudflare/puppeteer";
6
+ import { BrowserActionResult, BrowserNavigationResult, BrowserScreenshotRequest, BrowserScrollRequest, BrowserTextResult, InteractiveBrowser, InteractiveBrowserActionError, InteractiveBrowserBusyError, InteractiveBrowserCapacityError, InteractiveBrowserExpiredError, InteractiveBrowserLimitError, InteractiveBrowserPolicy, InteractiveBrowserPolicyDeniedError, InteractiveBrowserProtocolError, InteractiveBrowserTargetUrl, InteractiveBrowserUnsupportedError } from "@effect-agent/sandbox/InteractiveBrowser";
7
+ //#region src/InteractiveBrowser.ts
8
+ const browserRunInteractiveImplementation = SandboxImplementation.make({
9
+ isolation: "isolated",
10
+ identity: "cloudflare-browser-run-interactive"
11
+ });
12
+ const MIN_KEEP_ALIVE_MILLIS = 1e4;
13
+ const MAX_KEEP_ALIVE_MILLIS = 6e5;
14
+ const MAX_TEXT_LENGTH = 8388608;
15
+ const MAX_SCREENSHOT_BYTES = 8388608;
16
+ const MIN_LIVE_VIEW_EXPIRY_MILLIS = 6e4;
17
+ const MAX_LIVE_VIEW_EXPIRY_MILLIS = 36e5;
18
+ const MAX_HANDOFF_TIMEOUT_MILLIS = 18e5;
19
+ const MAX_HOST_TEXT_LENGTH = 8192;
20
+ const CLEANUP_STEP_TIMEOUT_MILLIS = 1e4;
21
+ const ACTION_NETWORK_QUIET_MILLIS = 200;
22
+ const ACTION_NETWORK_SETTLE_MILLIS = 2e3;
23
+ const ACTION_POST_STATE_MILLIS = 250;
24
+ const MAX_OBSERVED_CONTROLS = 64;
25
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
26
+ const BoundedHostText = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(MAX_HOST_TEXT_LENGTH));
27
+ const BoundedRemoteText = Schema.String.check(Schema.isMaxLength(MAX_TEXT_LENGTH));
28
+ const TextObservation = Schema.Union([
29
+ Schema.Struct({
30
+ _tag: Schema.Literal("Text"),
31
+ text: BoundedRemoteText
32
+ }),
33
+ Schema.Struct({ _tag: Schema.Literal("MissingElement") }),
34
+ Schema.Struct({
35
+ _tag: Schema.Literal("OverLimit"),
36
+ observed: Schema.Natural
37
+ })
38
+ ]);
39
+ const ActionTargetState = Schema.Struct({
40
+ matchCount: Schema.Natural,
41
+ invalidSelector: Schema.optionalKey(Schema.Boolean),
42
+ kind: Schema.optionalKey(Schema.Literals([
43
+ "button",
44
+ "checkbox",
45
+ "radio",
46
+ "select",
47
+ "text",
48
+ "link",
49
+ "other"
50
+ ])),
51
+ checked: Schema.optionalKey(Schema.Boolean),
52
+ selected: Schema.optionalKey(Schema.Boolean),
53
+ disabled: Schema.optionalKey(Schema.Boolean),
54
+ required: Schema.optionalKey(Schema.Boolean),
55
+ valid: Schema.optionalKey(Schema.Boolean),
56
+ formValid: Schema.optionalKey(Schema.Boolean)
57
+ });
58
+ const ActionNetworkState = Schema.Struct({
59
+ total: Schema.Natural,
60
+ status2xx: Schema.Natural,
61
+ status3xx: Schema.Natural,
62
+ status4xx: Schema.Natural,
63
+ status5xx: Schema.Natural,
64
+ failed: Schema.Natural,
65
+ pending: Schema.Natural,
66
+ settleTimedOut: Schema.Boolean
67
+ });
68
+ const ActionObservation = Schema.Struct({
69
+ before: ActionTargetState,
70
+ after: Schema.optionalKey(ActionTargetState),
71
+ afterUnavailable: Schema.Boolean,
72
+ network: ActionNetworkState
73
+ });
74
+ const PageObservation = Schema.fromJsonString(Schema.Struct({
75
+ pageText: BoundedRemoteText,
76
+ selectorMatchCount: Schema.Natural,
77
+ controlsTruncated: Schema.Boolean,
78
+ controls: Schema.Array(Schema.Struct({
79
+ selector: BoundedRemoteText,
80
+ kind: BoundedRemoteText,
81
+ label: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200))),
82
+ checked: Schema.optionalKey(Schema.Boolean),
83
+ selected: Schema.optionalKey(Schema.Boolean),
84
+ disabled: Schema.optionalKey(Schema.Boolean),
85
+ required: Schema.optionalKey(Schema.Boolean),
86
+ valid: Schema.optionalKey(Schema.Boolean),
87
+ formValid: Schema.optionalKey(Schema.Boolean)
88
+ })).check(Schema.isMaxLength(MAX_OBSERVED_CONTROLS))
89
+ }));
90
+ const PngBytes = Schema.Uint8Array.check(Schema.isMaxLength(MAX_SCREENSHOT_BYTES), Schema.makeFilter((bytes) => bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10, { title: "PNG bytes" }));
91
+ const BrowserRunSessionId = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256), Schema.makeFilter((value) => /^[A-Za-z0-9_-]+$/.test(value), { title: "a Browser Run session identifier" }));
92
+ const LiveViewUrl = Schema.String.check(Schema.isMaxLength(MAX_HOST_TEXT_LENGTH), Schema.makeFilter((value) => {
93
+ try {
94
+ const url = new URL(value);
95
+ return url.protocol === "https:" && url.host === "live.browser.run" && url.username === "" && url.password === "" && url.pathname === "/ui/view" && url.searchParams.get("mode") === "tab" && (url.searchParams.get("wss") ?? "").startsWith("live.browser.run/api/devtools/browser/");
96
+ } catch {
97
+ return false;
98
+ }
99
+ }, { title: "a Cloudflare Live View HTTPS URL" }));
100
+ const LiveViewObservation = Schema.Struct({ devtoolsFrontendUrl: LiveViewUrl });
101
+ const HandoffObservation = Schema.Struct({ handoffId: BoundedHostText });
102
+ const HandoffDuration = Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_HANDOFF_TIMEOUT_MILLIS));
103
+ const HandoffStateObservation = Schema.Union([Schema.Struct({
104
+ active: Schema.Literal(true),
105
+ handoffId: BoundedHostText,
106
+ durationMs: HandoffDuration
107
+ }), Schema.Struct({
108
+ active: Schema.Literal(false),
109
+ handoffId: Schema.optionalKey(BoundedHostText),
110
+ durationMs: Schema.optionalKey(HandoffDuration)
111
+ })]);
112
+ /**
113
+ * Host presentation state in CSS pixels. Dimensions are integers in 1..2048,
114
+ * density is finite in 1..2 (default 1), and neither scaled dimension may exceed
115
+ * 2048 pixels. Mobile, touch, and orientation emulation are not supported.
116
+ */
117
+ var BrowserRunViewport = class extends Schema.Class("BrowserRunViewport")(Schema.Struct({
118
+ width: PositiveInt.check(Schema.isLessThanOrEqualTo(2048)),
119
+ height: PositiveInt.check(Schema.isLessThanOrEqualTo(2048)),
120
+ deviceScaleFactor: Schema.optionalKey(Schema.Finite.check(Schema.isBetween({
121
+ minimum: 1,
122
+ maximum: 2
123
+ })))
124
+ }).check(Schema.makeFilter((viewport) => Math.max(viewport.width, viewport.height) * (viewport.deviceScaleFactor ?? 1) <= 2048, { title: "a viewport with scaled dimensions no larger than 2048 pixels" }))) {};
125
+ const decodeViewport = (input) => Schema.decodeUnknownEffect(BrowserRunViewport)(input, { onExcessProperty: "error" }).pipe(Effect.mapError(() => policyError("The browser viewport is malformed")), Effect.map((viewport) => ({
126
+ width: viewport.width,
127
+ height: viewport.height,
128
+ deviceScaleFactor: viewport.deviceScaleFactor ?? 1
129
+ })));
130
+ /** Host-only request for a redacted Cloudflare Live View URL. */
131
+ var BrowserRunLiveViewRequest = class extends Schema.Class("BrowserRunLiveViewRequest")({
132
+ mode: Schema.Literal("tab"),
133
+ expiresInMs: PositiveInt.check(Schema.isBetween({
134
+ minimum: MIN_LIVE_VIEW_EXPIRY_MILLIS,
135
+ maximum: MAX_LIVE_VIEW_EXPIRY_MILLIS
136
+ }))
137
+ }) {};
138
+ var BrowserRunLiveViewResult = class extends Schema.Class("BrowserRunLiveViewResult")({ devtoolsFrontendUrl: Schema.Redacted(LiveViewUrl) }) {};
139
+ /** Start one bounded handoff; controller ownership remains a consumer concern. */
140
+ var BrowserRunHandoffRequest = class extends Schema.Class("BrowserRunHandoffRequest")({
141
+ instructions: BoundedHostText.check(Schema.isMaxLength(1024)),
142
+ timeout: PositiveInt.check(Schema.isLessThanOrEqualTo(MAX_HANDOFF_TIMEOUT_MILLIS))
143
+ }) {};
144
+ var BrowserRunHandoffResult = class extends Schema.Class("BrowserRunHandoffResult")({ handoffId: Schema.Redacted(BoundedHostText) }) {};
145
+ var BrowserRunHandoffState = class extends Schema.Class("BrowserRunHandoffState")({
146
+ active: Schema.Boolean,
147
+ handoffId: Schema.optionalKey(Schema.Redacted(BoundedHostText)),
148
+ durationMs: Schema.optionalKey(HandoffDuration)
149
+ }) {};
150
+ /** Host-supplied Browser Run binding projected into one fakeable launch operation. */
151
+ var BrowserRunInteractiveBinding = class BrowserRunInteractiveBinding extends Context.Service()("@effect-agent/platform-cloudflare/BrowserRunInteractiveBinding") {
152
+ static layer(options) {
153
+ return Layer.effect(BrowserRunInteractiveBinding)(Effect.gen(function* () {
154
+ const lifecycle = yield* BrowserRunSessionLifecycle;
155
+ const viewport = options.viewport === void 0 ? void 0 : yield* decodeViewport(options.viewport);
156
+ return {
157
+ launch: async (keepAliveMillis) => makeProductionBrowser(await puppeteer.launch(options.browser, {
158
+ keep_alive: keepAliveMillis,
159
+ ...viewport === void 0 ? {} : { defaultViewport: { ...viewport } }
160
+ })),
161
+ closeSession: (sessionId) => lifecycle.close(sessionId).pipe(Effect.mapError((cause) => actionError("close", cause)))
162
+ };
163
+ }));
164
+ }
165
+ };
166
+ /** Cloudflare host authority kept separate from the provider-neutral browser handle. */
167
+ var BrowserRunInteractiveHost = class extends Context.Service()("@effect-agent/platform-cloudflare/BrowserRunInteractiveHost") {};
168
+ const makeProductionRequest = (request) => ({
169
+ url: () => request.url(),
170
+ abort: () => request.abort("blockedbyclient"),
171
+ continue: () => request.continue()
172
+ });
173
+ const makeProductionCdpSession = (session) => ({
174
+ send: async (command, parameters) => {
175
+ const send = Reflect.get(session, "send");
176
+ return await Reflect.apply(send, session, [command, parameters]);
177
+ },
178
+ detach: () => session.detach()
179
+ });
180
+ var BrowserRunActionUndispatched = class extends Error {
181
+ matchCount;
182
+ constructor(matchCount) {
183
+ super("The browser action selector did not resolve to exactly one element");
184
+ this.matchCount = matchCount;
185
+ }
186
+ };
187
+ const readActionTarget = (page, selector) => page.evaluate((requestedSelector) => {
188
+ const pageDocument = Reflect.get(globalThis, "document");
189
+ let matches;
190
+ try {
191
+ matches = Reflect.apply(Reflect.get(pageDocument, "querySelectorAll"), pageDocument, [requestedSelector]);
192
+ } catch (cause) {
193
+ if (cause instanceof Error && cause.name === "SyntaxError") return {
194
+ matchCount: 0,
195
+ invalidSelector: true
196
+ };
197
+ throw cause;
198
+ }
199
+ if (typeof matches !== "object" || matches === null) throw new Error("Invalid query result");
200
+ const matchCount = Math.min(1e4, Reflect.get(matches, "length"));
201
+ const element = Reflect.get(matches, 0);
202
+ if (element === void 0) return { matchCount };
203
+ const associated = Reflect.get(element, "control") ?? element;
204
+ const tagName = String(Reflect.get(associated, "tagName") ?? "").toLowerCase();
205
+ const inputType = String(Reflect.get(associated, "type") ?? "").toLowerCase();
206
+ const role = String(Reflect.apply(Reflect.get(element, "getAttribute"), element, ["role"]) ?? "").toLowerCase();
207
+ const kind = tagName === "button" || role === "button" ? "button" : inputType === "checkbox" || role === "checkbox" || role === "switch" ? "checkbox" : inputType === "radio" || role === "radio" ? "radio" : tagName === "select" ? "select" : tagName === "input" || tagName === "textarea" ? "text" : tagName === "a" ? "link" : "other";
208
+ const checked = Reflect.get(associated, "checked");
209
+ const selected = tagName === "select" ? Reflect.get(associated, "selectedIndex") >= 0 : Reflect.get(associated, "selected");
210
+ const disabled = Reflect.get(associated, "disabled");
211
+ const required = Reflect.get(associated, "required");
212
+ const validity = Reflect.get(associated, "validity");
213
+ const form = Reflect.get(associated, "form");
214
+ const formMatches = form === null || form === void 0 ? void 0 : Reflect.get(form, "matches");
215
+ const ariaChecked = Reflect.apply(Reflect.get(element, "getAttribute"), element, ["aria-checked"]);
216
+ const ariaDisabled = Reflect.apply(Reflect.get(element, "getAttribute"), element, ["aria-disabled"]);
217
+ const ariaSelected = Reflect.apply(Reflect.get(element, "getAttribute"), element, ["aria-selected"]);
218
+ return {
219
+ matchCount,
220
+ kind,
221
+ ...typeof checked === "boolean" ? { checked } : ariaChecked === "true" || ariaChecked === "false" ? { checked: ariaChecked === "true" } : {},
222
+ ...typeof selected === "boolean" ? { selected } : ariaSelected === "true" || ariaSelected === "false" ? { selected: ariaSelected === "true" } : {},
223
+ disabled: typeof disabled === "boolean" ? disabled : ariaDisabled === "true",
224
+ ...typeof required === "boolean" ? { required } : {},
225
+ ...validity !== void 0 && typeof Reflect.get(validity, "valid") === "boolean" ? { valid: Reflect.get(validity, "valid") } : {},
226
+ ...typeof formMatches === "function" ? { formValid: Reflect.apply(formMatches, form, [":valid"]) } : {}
227
+ };
228
+ }, selector);
229
+ const boundedBestEffort = async (promise, millis) => {
230
+ let timer;
231
+ try {
232
+ return await Promise.race([promise.catch(() => void 0), new Promise((resolve) => {
233
+ timer = setTimeout(resolve, millis);
234
+ })]);
235
+ } finally {
236
+ clearTimeout(timer);
237
+ }
238
+ };
239
+ const readActionTargetAfter = (page, selector) => boundedBestEffort(readActionTarget(page, selector).then(Schema.decodeUnknownSync(ActionTargetState)), ACTION_POST_STATE_MILLIS);
240
+ const makeActionRequestTracker = (page, signal) => {
241
+ const pending = /* @__PURE__ */ new Set();
242
+ let total = 0;
243
+ let status2xx = 0;
244
+ let status3xx = 0;
245
+ let status4xx = 0;
246
+ let status5xx = 0;
247
+ let failed = 0;
248
+ let lastChange = performance.now();
249
+ let closed = false;
250
+ let wake;
251
+ let timer;
252
+ const relevant = (request) => {
253
+ const resourceType = request.resourceType();
254
+ return resourceType === "fetch" || resourceType === "xhr";
255
+ };
256
+ const onRequest = (request) => {
257
+ if (!relevant(request)) return;
258
+ pending.add(request);
259
+ total++;
260
+ lastChange = performance.now();
261
+ };
262
+ const onFinished = (request) => {
263
+ if (!pending.delete(request)) return;
264
+ let status;
265
+ try {
266
+ status = request.response()?.status();
267
+ } catch {}
268
+ if (status !== void 0) {
269
+ if (status >= 200 && status < 300) status2xx++;
270
+ else if (status >= 300 && status < 400) status3xx++;
271
+ else if (status >= 400 && status < 500) status4xx++;
272
+ else if (status >= 500 && status < 600) status5xx++;
273
+ }
274
+ lastChange = performance.now();
275
+ };
276
+ const onFailed = (request) => {
277
+ if (!pending.delete(request)) return;
278
+ failed++;
279
+ lastChange = performance.now();
280
+ };
281
+ const close = () => {
282
+ if (closed) return;
283
+ closed = true;
284
+ page.off("request", onRequest);
285
+ page.off("requestfinished", onFinished);
286
+ page.off("requestfailed", onFailed);
287
+ signal.removeEventListener("abort", close);
288
+ clearTimeout(timer);
289
+ wake?.();
290
+ };
291
+ try {
292
+ page.on("request", onRequest);
293
+ page.on("requestfinished", onFinished);
294
+ page.on("requestfailed", onFailed);
295
+ signal.addEventListener("abort", close, { once: true });
296
+ if (signal.aborted) close();
297
+ } catch (cause) {
298
+ close();
299
+ throw cause;
300
+ }
301
+ const wait = async () => {
302
+ const startedAt = performance.now();
303
+ let settleTimedOut = false;
304
+ while (!closed) {
305
+ const now = performance.now();
306
+ if (pending.size === 0 && now - lastChange >= ACTION_NETWORK_QUIET_MILLIS) break;
307
+ if (now - startedAt >= ACTION_NETWORK_SETTLE_MILLIS) {
308
+ settleTimedOut = true;
309
+ break;
310
+ }
311
+ await new Promise((resolve) => {
312
+ wake = resolve;
313
+ timer = setTimeout(() => resolve(), 50);
314
+ });
315
+ wake = void 0;
316
+ }
317
+ return {
318
+ total,
319
+ status2xx,
320
+ status3xx,
321
+ status4xx,
322
+ status5xx,
323
+ failed,
324
+ pending: pending.size,
325
+ settleTimedOut
326
+ };
327
+ };
328
+ return {
329
+ wait,
330
+ close,
331
+ markActionSettled: () => {
332
+ lastChange = performance.now();
333
+ }
334
+ };
335
+ };
336
+ const disposeActionHandles = async (handles) => {
337
+ await boundedBestEffort(Promise.allSettled(handles.map(async (handle) => handle.dispose())), ACTION_POST_STATE_MILLIS);
338
+ };
339
+ const runObservedPageAction = async (page, selector, signal, onDispatch, action) => {
340
+ if (signal.aborted) throw new BrowserRunActionUndispatched(0);
341
+ const before = Schema.decodeUnknownSync(ActionTargetState)(await readActionTarget(page, selector));
342
+ if (before.matchCount !== 1 || before.invalidSelector === true) throw new BrowserRunActionUndispatched(before.matchCount);
343
+ const matches = await page.$$(selector);
344
+ if (matches.length !== 1 || matches[0] === void 0) {
345
+ await disposeActionHandles(matches);
346
+ throw new BrowserRunActionUndispatched(Math.min(1e4, matches.length));
347
+ }
348
+ if (signal.aborted) {
349
+ await disposeActionHandles(matches);
350
+ throw new BrowserRunActionUndispatched(1);
351
+ }
352
+ let tracker;
353
+ let disposing;
354
+ const dispose = () => disposing ??= disposeActionHandles(matches);
355
+ const onAbort = () => {
356
+ dispose();
357
+ };
358
+ signal.addEventListener("abort", onAbort, { once: true });
359
+ try {
360
+ tracker = makeActionRequestTracker(page, signal);
361
+ if (signal.aborted) throw new BrowserRunActionUndispatched(1);
362
+ onDispatch();
363
+ await action(matches[0]);
364
+ tracker.markActionSettled();
365
+ const network = await tracker.wait();
366
+ const after = signal.aborted ? void 0 : await readActionTargetAfter(page, selector);
367
+ return {
368
+ before,
369
+ ...after === void 0 ? {} : { after },
370
+ afterUnavailable: after === void 0,
371
+ network
372
+ };
373
+ } finally {
374
+ tracker?.close();
375
+ signal.removeEventListener("abort", onAbort);
376
+ await dispose();
377
+ }
378
+ };
379
+ const makeProductionPage = (page) => {
380
+ const listeners = /* @__PURE__ */ new Map();
381
+ return {
382
+ close: () => page.close(),
383
+ setBypassServiceWorker: (enabled) => page.setBypassServiceWorker(enabled),
384
+ setRequestInterception: (enabled) => page.setRequestInterception(enabled),
385
+ onRequest: (listener) => {
386
+ const sdkListener = (request) => listener(makeProductionRequest(request));
387
+ listeners.set(listener, sdkListener);
388
+ page.on("request", sdkListener);
389
+ },
390
+ offRequest: (listener) => {
391
+ const sdkListener = listeners.get(listener);
392
+ if (sdkListener !== void 0) {
393
+ page.off("request", sdkListener);
394
+ listeners.delete(listener);
395
+ }
396
+ },
397
+ goto: async (url) => {
398
+ await page.goto(url, {
399
+ waitUntil: "domcontentloaded",
400
+ timeout: 3e4
401
+ });
402
+ },
403
+ url: () => page.url(),
404
+ readText: async (selector, maximumBytes) => {
405
+ const observation = Schema.decodeUnknownSync(TextObservation)(await page.evaluate((requestedSelector, maximum, maximumControls) => {
406
+ const pageDocument = Reflect.get(globalThis, "document");
407
+ const matches = requestedSelector === void 0 ? void 0 : Reflect.apply(Reflect.get(pageDocument, "querySelectorAll"), pageDocument, [requestedSelector]);
408
+ const selectorMatchCount = matches === void 0 || matches === null ? 1 : Math.min(1e4, Reflect.get(matches, "length"));
409
+ const element = matches === void 0 || matches === null ? Reflect.get(pageDocument, "body") : Reflect.get(matches, 0);
410
+ if (element === null) return { _tag: "MissingElement" };
411
+ if (element === void 0) return { _tag: "MissingElement" };
412
+ const innerText = Reflect.get(element, "innerText");
413
+ const textContent = Reflect.get(element, "textContent");
414
+ const pageText = typeof innerText === "string" ? innerText : typeof textContent === "string" ? textContent : "";
415
+ const primaryControlSelector = "input,select,textarea,label,button,[role=\"checkbox\"],[role=\"radio\"],[role=\"option\"],[role=\"switch\"],[role=\"tab\"],[role=\"button\"]";
416
+ const optionSelector = "select option";
417
+ const secondaryControlSelector = "a[href]";
418
+ const controlSelector = `${primaryControlSelector},${optionSelector},${secondaryControlSelector}`;
419
+ const selectorFor = (candidate) => {
420
+ const parts = [];
421
+ let current = candidate;
422
+ while (current !== null && current !== void 0) {
423
+ const tagName = String(Reflect.get(current, "tagName") ?? "").toLowerCase();
424
+ if (tagName === "") break;
425
+ const parent = Reflect.get(current, "parentElement");
426
+ if (parent === null) {
427
+ parts.push(tagName);
428
+ break;
429
+ }
430
+ let sibling = Reflect.get(current, "previousElementSibling");
431
+ let index = 1;
432
+ while (sibling !== null && sibling !== void 0) {
433
+ if (String(Reflect.get(sibling, "tagName") ?? "").toLowerCase() === tagName) index++;
434
+ sibling = Reflect.get(sibling, "previousElementSibling");
435
+ }
436
+ parts.push(`${tagName}:nth-of-type(${index})`);
437
+ current = parent;
438
+ }
439
+ return parts.reverse().join(" > ");
440
+ };
441
+ const visible = (candidate) => {
442
+ const hidden = Reflect.get(candidate, "hidden");
443
+ const ariaHidden = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["aria-hidden"]);
444
+ const rects = Reflect.apply(Reflect.get(candidate, "getClientRects"), candidate, []);
445
+ return hidden !== true && ariaHidden !== "true" && typeof rects === "object" && rects !== null && Reflect.get(rects, "length") > 0;
446
+ };
447
+ const candidates = [];
448
+ let controlsTruncated = false;
449
+ const consider = (candidate) => {
450
+ const tagName = String(Reflect.get(candidate, "tagName") ?? "").toLowerCase();
451
+ const visibilityTarget = tagName === "option" ? Reflect.apply(Reflect.get(candidate, "closest"), candidate, ["select"]) : candidate;
452
+ if (!(tagName !== "label" || Reflect.get(candidate, "control") !== null) || typeof visibilityTarget !== "object" || visibilityTarget === null || !visible(visibilityTarget)) return;
453
+ candidates.push(candidate);
454
+ if (candidates.length > maximumControls) controlsTruncated = true;
455
+ };
456
+ const elementMatches = Reflect.get(element, "matches");
457
+ if (typeof elementMatches === "function" && Reflect.apply(elementMatches, element, [controlSelector])) consider(element);
458
+ const considerSelector = (candidateSelector) => {
459
+ const descendants = Reflect.apply(Reflect.get(element, "querySelectorAll"), element, [candidateSelector]);
460
+ if (typeof descendants !== "object" || descendants === null) return;
461
+ const descendantCount = Reflect.get(descendants, "length");
462
+ for (let index = 0; index < descendantCount && !controlsTruncated; index++) consider(Reflect.get(descendants, index));
463
+ };
464
+ considerSelector(primaryControlSelector);
465
+ if (!controlsTruncated) considerSelector(optionSelector);
466
+ if (!controlsTruncated) considerSelector(secondaryControlSelector);
467
+ const controls = candidates.slice(0, maximumControls).map((candidate) => {
468
+ const associated = Reflect.get(candidate, "control") ?? candidate;
469
+ const tagName = String(Reflect.get(candidate, "tagName") ?? "").toLowerCase();
470
+ const inputType = String(Reflect.get(associated, "type") ?? "").toLowerCase();
471
+ const role = String(Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["role"]) ?? "").toLowerCase();
472
+ const ariaLabel = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["aria-label"]);
473
+ const candidateText = tagName === "textarea" || tagName === "input" || tagName === "select" ? void 0 : Reflect.get(candidate, tagName === "option" ? "label" : "innerText");
474
+ const associatedLabels = Reflect.get(associated, "labels");
475
+ const associatedLabel = associatedLabels !== void 0 && associatedLabels !== null && Reflect.get(associatedLabels, "length") > 0 ? Reflect.get(Reflect.get(associatedLabels, 0), "innerText") : void 0;
476
+ const label = String(typeof ariaLabel === "string" && ariaLabel !== "" ? ariaLabel : typeof candidateText === "string" && candidateText !== "" ? candidateText : associatedLabel ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
477
+ const checked = Reflect.get(associated, "checked");
478
+ const selected = tagName === "select" ? Reflect.get(associated, "selectedIndex") >= 0 : Reflect.get(associated, "selected");
479
+ const disabled = Reflect.get(associated, "disabled");
480
+ const required = Reflect.get(associated, "required");
481
+ const validity = Reflect.get(associated, "validity");
482
+ const form = Reflect.get(associated, "form");
483
+ const formMatches = form === null || form === void 0 ? void 0 : Reflect.get(form, "matches");
484
+ const ariaChecked = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["aria-checked"]);
485
+ const ariaSelected = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["aria-selected"]);
486
+ const ariaDisabled = Reflect.apply(Reflect.get(candidate, "getAttribute"), candidate, ["aria-disabled"]);
487
+ return {
488
+ selector: selectorFor(candidate),
489
+ kind: tagName === "label" ? `label:${inputType || "control"}` : tagName === "input" ? `input:${inputType || "text"}` : role !== "" ? `role:${role}` : tagName,
490
+ ...label === "" ? {} : { label },
491
+ ...typeof checked === "boolean" ? { checked } : ariaChecked === "true" || ariaChecked === "false" ? { checked: ariaChecked === "true" } : {},
492
+ ...typeof selected === "boolean" ? { selected } : ariaSelected === "true" || ariaSelected === "false" ? { selected: ariaSelected === "true" } : {},
493
+ ...typeof disabled === "boolean" ? { disabled } : ariaDisabled === "true" || ariaDisabled === "false" ? { disabled: ariaDisabled === "true" } : {},
494
+ ...typeof required === "boolean" ? { required } : {},
495
+ ...validity !== void 0 && typeof Reflect.get(validity, "valid") === "boolean" ? { valid: Reflect.get(validity, "valid") } : {},
496
+ ...typeof formMatches === "function" ? { formValid: Reflect.apply(formMatches, form, [":valid"]) } : {}
497
+ };
498
+ });
499
+ const text = JSON.stringify({
500
+ pageText,
501
+ selectorMatchCount,
502
+ controls,
503
+ controlsTruncated
504
+ });
505
+ const observed = new TextEncoder().encode(text).byteLength;
506
+ return observed > maximum ? {
507
+ _tag: "OverLimit",
508
+ observed
509
+ } : {
510
+ _tag: "Text",
511
+ text
512
+ };
513
+ }, selector, maximumBytes, MAX_OBSERVED_CONTROLS));
514
+ if (observation._tag === "Text") Schema.decodeUnknownSync(PageObservation)(observation.text);
515
+ return observation;
516
+ },
517
+ fill: (selector, value, signal, onDispatch) => runObservedPageAction(page, selector, signal, onDispatch, (element) => element.evaluate((element, nextValue) => {
518
+ let prototype = Reflect.getPrototypeOf(element);
519
+ let setValue;
520
+ while (prototype !== null) {
521
+ const setter = Reflect.getOwnPropertyDescriptor(prototype, "value")?.set;
522
+ if (typeof setter === "function") {
523
+ setValue = setter;
524
+ break;
525
+ }
526
+ prototype = Reflect.getPrototypeOf(prototype);
527
+ }
528
+ if (setValue === void 0) throw new Error("The selector did not resolve to a fillable field");
529
+ const focus = Reflect.get(element, "focus");
530
+ if (typeof focus === "function") Reflect.apply(focus, element, []);
531
+ Reflect.apply(setValue, element, [nextValue]);
532
+ const dispatchEvent = Reflect.get(element, "dispatchEvent");
533
+ if (typeof dispatchEvent === "function") {
534
+ Reflect.apply(dispatchEvent, element, [new Event("input", { bubbles: true })]);
535
+ Reflect.apply(dispatchEvent, element, [new Event("change", { bubbles: true })]);
536
+ }
537
+ }, value)),
538
+ click: (selector, signal, onDispatch) => runObservedPageAction(page, selector, signal, onDispatch, (element) => element.click()),
539
+ screenshot: (fullPage) => page.screenshot({
540
+ type: "png",
541
+ fullPage
542
+ }),
543
+ scroll: (deltaX, deltaY) => page.evaluate((x, y) => {
544
+ const scrollBy = Reflect.get(globalThis, "scrollBy");
545
+ Reflect.apply(scrollBy, globalThis, [{
546
+ left: x,
547
+ top: y,
548
+ behavior: "instant"
549
+ }]);
550
+ }, deltaX, deltaY),
551
+ createCdpSession: async () => makeProductionCdpSession(await page.createCDPSession()),
552
+ setViewport: (viewport) => page.setViewport(viewport)
553
+ };
554
+ };
555
+ const makeProductionContext = (context) => ({
556
+ newPage: async () => makeProductionPage(await context.newPage()),
557
+ close: () => context.close()
558
+ });
559
+ const makeProductionBrowser = (browser) => ({
560
+ createContext: async () => makeProductionContext(await browser.createBrowserContext()),
561
+ close: () => browser.close(),
562
+ sessionId: () => browser.sessionId(),
563
+ isConnected: () => browser.isConnected(),
564
+ onDisconnected: (listener) => {
565
+ browser.on("disconnected", listener);
566
+ },
567
+ offDisconnected: (listener) => {
568
+ browser.off("disconnected", listener);
569
+ }
570
+ });
571
+ const protocolError = (message, cause) => InteractiveBrowserProtocolError.make({
572
+ implementation: browserRunInteractiveImplementation,
573
+ message,
574
+ ...cause === void 0 ? {} : { cause }
575
+ });
576
+ const actionError = (operation, cause) => InteractiveBrowserActionError.make({
577
+ implementation: browserRunInteractiveImplementation,
578
+ operation,
579
+ message: `The interactive browser ${operation} operation failed`,
580
+ ...cause === void 0 ? {} : { cause }
581
+ });
582
+ const undispatchedActionError = (operation) => InteractiveBrowserActionError.make({
583
+ implementation: browserRunInteractiveImplementation,
584
+ operation,
585
+ message: `The interactive browser ${operation} operation was not dispatched`
586
+ });
587
+ /** Recognizes a local pre-dispatch refusal without exposing selector or page content. */
588
+ const isBrowserRunUndispatchedActionError = (error) => Schema.is(InteractiveBrowserActionError)(error) && error.implementation.identity === browserRunInteractiveImplementation.identity && (error.operation === "click" || error.operation === "fill") && error.message === `The interactive browser ${error.operation} operation was not dispatched`;
589
+ const policyError = (message) => InteractiveBrowserPolicyDeniedError.make({
590
+ implementation: browserRunInteractiveImplementation,
591
+ message
592
+ });
593
+ const expiredError = () => InteractiveBrowserExpiredError.make({
594
+ implementation: browserRunInteractiveImplementation,
595
+ message: "The remote browser is no longer usable"
596
+ });
597
+ const causeText = (cause) => {
598
+ if (cause instanceof Error) return cause.message.slice(0, 8e3);
599
+ return String(cause).slice(0, 8e3);
600
+ };
601
+ const isCapacityRefusal = (cause) => /(^|\D)429(\D|$)|browser time limit|capacity|too many concurrent/i.test(causeText(cause));
602
+ const isRemoteClosure = (cause) => /target closed|browser.*closed|session.*closed|connection.*closed|not connected|websocket.*closed/i.test(causeText(cause));
603
+ const snapshotPolicy = Effect.fn("BrowserRunInteractive.snapshotPolicy")(function* (input) {
604
+ const decoded = yield* Schema.decodeUnknownEffect(InteractiveBrowserPolicy)(input).pipe(Effect.mapError(() => policyError("The interactive browser policy is malformed")));
605
+ if (decoded.network._tag === "PublicWeb") return yield* InteractiveBrowserUnsupportedError.make({
606
+ implementation: browserRunInteractiveImplementation,
607
+ feature: "policy",
608
+ message: "Cloudflare Browser Run cannot enforce the PublicWeb network policy for all session traffic"
609
+ });
610
+ return Object.freeze({
611
+ network: decoded.network._tag === "ExactHosts" ? Object.freeze({
612
+ _tag: decoded.network._tag,
613
+ allowedHosts: Object.freeze([...decoded.network.allowedHosts])
614
+ }) : Object.freeze({ _tag: decoded.network._tag }),
615
+ maxActions: decoded.maxActions,
616
+ maxElapsedMillis: decoded.maxElapsedMillis,
617
+ maxReturnedBytes: decoded.maxReturnedBytes
618
+ });
619
+ });
620
+ const hostAllowed = (policy, value) => {
621
+ if (policy.network._tag === "Unrestricted") return true;
622
+ try {
623
+ const url = new URL(value);
624
+ return url.protocol === "https:" && url.username === "" && url.password === "" && policy.network.allowedHosts.some((host) => host === url.host);
625
+ } catch {
626
+ return false;
627
+ }
628
+ };
629
+ const keepAliveMillis = (policy) => Math.max(MIN_KEEP_ALIVE_MILLIS, Math.min(MAX_KEEP_ALIVE_MILLIS, policy.maxElapsedMillis));
630
+ const closeLateAcquisition = async (signal, acquire, close) => {
631
+ const acquired = await acquire();
632
+ if (!signal.aborted) return acquired;
633
+ try {
634
+ await close(acquired);
635
+ } catch {}
636
+ throw new Error("The interrupted browser acquisition completed late");
637
+ };
638
+ const closeWithWarning = (close, warning) => Effect.tryPromise({
639
+ try: close,
640
+ catch: () => protocolError(warning)
641
+ }).pipe(Effect.timeoutOrElse({
642
+ duration: Duration.millis(CLEANUP_STEP_TIMEOUT_MILLIS),
643
+ orElse: () => Effect.fail(protocolError(warning))
644
+ }), Effect.catchCause(() => Effect.logWarning(warning)));
645
+ const deadlineError = Effect.fn("BrowserRunInteractive.deadlineError")(function* (policy, startedAt) {
646
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
647
+ return yield* InteractiveBrowserLimitError.make({
648
+ implementation: browserRunInteractiveImplementation,
649
+ limit: "elapsed",
650
+ maximum: policy.maxElapsedMillis,
651
+ observed: Math.max(policy.maxElapsedMillis, now - startedAt),
652
+ message: "The browser elapsed-time limit was reached"
653
+ });
654
+ });
655
+ const withinDeadline = Effect.fn("BrowserRunInteractive.withinDeadline")(function* (effect, policy, startedAt, onTimeout) {
656
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
657
+ const elapsed = Math.max(0, now - startedAt);
658
+ const remaining = policy.maxElapsedMillis - elapsed;
659
+ if (remaining <= 0) return yield* deadlineError(policy, startedAt);
660
+ return yield* effect.pipe(Effect.timeoutOrElse({
661
+ duration: Duration.millis(remaining),
662
+ orElse: () => Effect.sync(() => onTimeout?.()).pipe(Effect.andThen(deadlineError(policy, startedAt)))
663
+ }));
664
+ });
665
+ const stateFailure = (state) => {
666
+ if (state.violation.value !== void 0) return state.violation.value;
667
+ if (state.closed.value || state.disconnected.value || state.uncertain.value) return expiredError();
668
+ };
669
+ var BrowserRunRemoteFailure = class {
670
+ cause;
671
+ constructor(cause) {
672
+ this.cause = cause;
673
+ }
674
+ };
675
+ const awaitPendingRequests = (state) => Effect.suspend(() => {
676
+ const pending = [...state.pendingRequests];
677
+ return pending.length === 0 ? Effect.void : Effect.promise(() => Promise.all(pending)).pipe(Effect.asVoid, Effect.andThen(awaitPendingRequests(state)));
678
+ });
679
+ const decodeNavigationResult = Effect.fn("BrowserRunInteractive.decodeNavigationResult")(function* (page, policy) {
680
+ const url = yield* Effect.try({
681
+ try: page.url,
682
+ catch: (cause) => protocolError("Reading the browser navigation URL failed", cause)
683
+ });
684
+ const result = yield* Schema.decodeUnknownEffect(BrowserNavigationResult)({ url }).pipe(Effect.mapError((cause) => protocolError("The browser returned a malformed navigation URL", cause)));
685
+ if (!hostAllowed(policy, result.url)) return yield* policyError("The browser returned an off-policy page URL");
686
+ return result;
687
+ });
688
+ const decodeActionResult = Effect.fn("BrowserRunInteractive.decodeActionResult")(function* (page, policy) {
689
+ const url = yield* Effect.try({
690
+ try: page.url,
691
+ catch: (cause) => protocolError("Reading the browser page URL failed", cause)
692
+ });
693
+ const result = yield* Schema.decodeUnknownEffect(BrowserActionResult)({ url }).pipe(Effect.mapError((cause) => protocolError("The browser returned a malformed page URL", cause)));
694
+ if (!hostAllowed(policy, result.url)) return yield* policyError("The browser returned an off-policy page URL");
695
+ return result;
696
+ });
697
+ const makeRequestListener = (policy, state) => (request) => {
698
+ let allowed = false;
699
+ try {
700
+ allowed = hostAllowed(policy, request.url());
701
+ } catch {
702
+ allowed = false;
703
+ }
704
+ if (!allowed) state.violation.value = policyError("The browser requested an off-policy URL");
705
+ let settlement;
706
+ try {
707
+ settlement = allowed ? request.continue() : request.abort();
708
+ } catch {
709
+ state.violation.value = protocolError("Resolving an intercepted browser request failed");
710
+ return;
711
+ }
712
+ const observed = settlement.catch(() => {
713
+ state.violation.value = protocolError("Resolving an intercepted browser request failed");
714
+ }).finally(() => {
715
+ state.pendingRequests.delete(observed);
716
+ });
717
+ state.pendingRequests.add(observed);
718
+ };
719
+ const makeHandle = Effect.fn("BrowserRunInteractive.makeHandle")(function* (page, policy, startedAt, state, close) {
720
+ const permits = yield* Semaphore.make(1);
721
+ const actions = yield* Ref.make(0);
722
+ const remote = (operation, evaluate) => Effect.tryPromise({
723
+ try: evaluate,
724
+ catch: (cause) => new BrowserRunRemoteFailure(cause)
725
+ }).pipe(Effect.catch((failure) => {
726
+ const cause = failure.cause;
727
+ if (cause instanceof BrowserRunActionUndispatched) return Effect.logInfo("Browser interactive action was not dispatched").pipe(Effect.annotateLogs({
728
+ "browser.action": operation,
729
+ "browser.selector_match_count": cause.matchCount
730
+ }), Effect.andThen(Effect.fail(undispatchedActionError(operation))));
731
+ if (state.disconnected.value || isRemoteClosure(cause)) {
732
+ state.disconnected.value = true;
733
+ return Effect.fail(expiredError());
734
+ }
735
+ return Effect.fail(actionError(operation, cause));
736
+ }));
737
+ const observedAction = (operation, evaluate) => Effect.suspend(() => {
738
+ let dispatched = false;
739
+ let pending;
740
+ return remote(operation, (signal) => {
741
+ pending = evaluate(signal, () => {
742
+ dispatched = true;
743
+ });
744
+ return pending;
745
+ }).pipe(Effect.onInterrupt(() => Effect.gen(function* () {
746
+ state.uncertain.value = true;
747
+ yield* Effect.logWarning("Browser interactive action interrupted").pipe(Effect.annotateLogs({
748
+ "browser.action": operation,
749
+ "browser.action_dispatched": dispatched,
750
+ "browser.action_outcome_unknown": dispatched
751
+ }));
752
+ const completion = pending;
753
+ if (completion !== void 0) yield* Effect.promise(() => boundedBestEffort(completion, 500));
754
+ })));
755
+ });
756
+ const decodeActionObservation = Effect.fn("BrowserRunInteractive.decodeActionObservation")(function* (raw) {
757
+ return yield* Schema.decodeUnknownEffect(ActionObservation)(raw).pipe(Effect.mapError((cause) => protocolError("The browser returned a malformed action observation", cause)));
758
+ });
759
+ const logActionObservation = (operation, observation) => Effect.logInfo("Browser interactive action observed").pipe(Effect.annotateLogs({
760
+ "browser.action": operation,
761
+ "browser.selector_match_count": observation.before.matchCount,
762
+ ...observation.before.kind === void 0 ? {} : { "browser.target_kind": observation.before.kind },
763
+ ...observation.before.checked === void 0 ? {} : { "browser.target_checked_before": observation.before.checked },
764
+ ...observation.after?.checked === void 0 ? {} : { "browser.target_checked_after": observation.after.checked },
765
+ ...observation.before.selected === void 0 ? {} : { "browser.target_selected_before": observation.before.selected },
766
+ ...observation.after?.selected === void 0 ? {} : { "browser.target_selected_after": observation.after.selected },
767
+ ...observation.before.disabled === void 0 ? {} : { "browser.target_disabled_before": observation.before.disabled },
768
+ ...observation.after?.disabled === void 0 ? {} : { "browser.target_disabled_after": observation.after.disabled },
769
+ ...observation.before.required === void 0 ? {} : { "browser.target_required_before": observation.before.required },
770
+ ...observation.after?.required === void 0 ? {} : { "browser.target_required_after": observation.after.required },
771
+ ...observation.before.valid === void 0 ? {} : { "browser.target_valid_before": observation.before.valid },
772
+ ...observation.after?.valid === void 0 ? {} : { "browser.target_valid_after": observation.after.valid },
773
+ ...observation.before.formValid === void 0 ? {} : { "browser.form_valid_before": observation.before.formValid },
774
+ ...observation.after?.formValid === void 0 ? {} : { "browser.form_valid_after": observation.after.formValid },
775
+ "browser.target_after_unavailable": observation.afterUnavailable,
776
+ "browser.fetch_xhr_total": observation.network.total,
777
+ "browser.fetch_xhr_2xx": observation.network.status2xx,
778
+ "browser.fetch_xhr_3xx": observation.network.status3xx,
779
+ "browser.fetch_xhr_4xx": observation.network.status4xx,
780
+ "browser.fetch_xhr_5xx": observation.network.status5xx,
781
+ "browser.fetch_xhr_failed": observation.network.failed,
782
+ "browser.fetch_xhr_pending": observation.network.pending,
783
+ "browser.network_settle_timed_out": observation.network.settleTimedOut
784
+ }));
785
+ const run = (effect, preflight = Effect.void, consumeAction = true) => permits.withPermitsIfAvailable(1)(Effect.gen(function* () {
786
+ const unavailable = stateFailure(state);
787
+ if (unavailable !== void 0) return yield* unavailable;
788
+ yield* preflight;
789
+ if (consumeAction) {
790
+ const admitted = yield* Ref.modify(actions, (count) => count >= policy.maxActions ? [{
791
+ allowed: false,
792
+ observed: count + 1
793
+ }, count] : [{
794
+ allowed: true,
795
+ observed: count + 1
796
+ }, count + 1]);
797
+ if (!admitted.allowed) return yield* InteractiveBrowserLimitError.make({
798
+ implementation: browserRunInteractiveImplementation,
799
+ limit: "actions",
800
+ maximum: policy.maxActions,
801
+ observed: admitted.observed,
802
+ message: "The browser action limit was reached"
803
+ });
804
+ }
805
+ const completed = effect.pipe(Effect.catch((error) => {
806
+ const failure = stateFailure(state);
807
+ return Effect.fail(failure ?? error);
808
+ }), Effect.flatMap((result) => awaitPendingRequests(state).pipe(Effect.flatMap(() => {
809
+ const failure = stateFailure(state);
810
+ return failure === void 0 ? Effect.succeed(result) : Effect.fail(failure);
811
+ }))));
812
+ return yield* withinDeadline(completed, policy, startedAt, () => {
813
+ state.uncertain.value = true;
814
+ }).pipe(Effect.onInterrupt(() => Effect.sync(() => {
815
+ state.uncertain.value = true;
816
+ })), Effect.catch((error) => {
817
+ if (Schema.is(InteractiveBrowserLimitError)(error) && error.limit === "elapsed") return Effect.fail(error);
818
+ const failure = stateFailure(state);
819
+ if (Schema.is(InteractiveBrowserActionError)(error) && !isBrowserRunUndispatchedActionError(error)) state.uncertain.value = true;
820
+ return Effect.fail(failure ?? error);
821
+ }));
822
+ })).pipe(Effect.flatMap((result) => Option.isSome(result) ? Effect.succeed(result.value) : Effect.fail(InteractiveBrowserBusyError.make({
823
+ implementation: browserRunInteractiveImplementation,
824
+ message: "The browser handle already has an operation in flight"
825
+ }))));
826
+ return {
827
+ handle: {
828
+ navigate: (request) => run(Effect.gen(function* () {
829
+ yield* remote("navigate", () => page.goto(request.url));
830
+ return yield* decodeNavigationResult(page, policy);
831
+ }), Effect.suspend(() => Schema.is(InteractiveBrowserTargetUrl)(request.url) && hostAllowed(policy, request.url) ? Effect.void : Effect.fail(policyError("The navigation URL is outside the browser policy")))),
832
+ readText: (request) => run(Effect.gen(function* () {
833
+ const raw = yield* remote("read-text", () => page.readText(request.selector, policy.maxReturnedBytes));
834
+ const observation = yield* Schema.decodeUnknownEffect(TextObservation)(raw).pipe(Effect.mapError((cause) => protocolError("The browser returned a malformed text observation", cause)));
835
+ if (observation._tag === "MissingElement") return yield* actionError("read-text");
836
+ if (observation._tag === "OverLimit") return yield* InteractiveBrowserLimitError.make({
837
+ implementation: browserRunInteractiveImplementation,
838
+ limit: "returned-bytes",
839
+ maximum: policy.maxReturnedBytes,
840
+ observed: observation.observed,
841
+ message: "The browser returned-text limit was reached"
842
+ });
843
+ const observed = new TextEncoder().encode(observation.text).byteLength;
844
+ if (observed > policy.maxReturnedBytes) return yield* InteractiveBrowserLimitError.make({
845
+ implementation: browserRunInteractiveImplementation,
846
+ limit: "returned-bytes",
847
+ maximum: policy.maxReturnedBytes,
848
+ observed,
849
+ message: "The browser returned-text limit was reached"
850
+ });
851
+ return yield* Schema.decodeUnknownEffect(BrowserTextResult)({ text: observation.text }).pipe(Effect.mapError((cause) => protocolError("The browser returned malformed page text", cause)));
852
+ })),
853
+ fill: (request) => run(Effect.gen(function* () {
854
+ const observation = yield* observedAction("fill", (signal, onDispatch) => page.fill(request.selector, request.value, signal, onDispatch)).pipe(Effect.flatMap(decodeActionObservation));
855
+ yield* logActionObservation("fill", observation);
856
+ return yield* decodeActionResult(page, policy);
857
+ })),
858
+ click: (request) => run(Effect.gen(function* () {
859
+ const observation = yield* observedAction("click", (signal, onDispatch) => page.click(request.selector, signal, onDispatch)).pipe(Effect.flatMap(decodeActionObservation));
860
+ yield* logActionObservation("click", observation);
861
+ return yield* decodeActionResult(page, policy);
862
+ })),
863
+ screenshot: (request) => Schema.decodeUnknownEffect(BrowserScreenshotRequest)(request).pipe(Effect.mapError(() => policyError("The browser screenshot request is malformed")), Effect.flatMap((decoded) => run(Effect.gen(function* () {
864
+ const raw = yield* remote("screenshot", () => page.screenshot(decoded.fullPage));
865
+ const bytes = yield* Schema.decodeUnknownEffect(PngBytes)(raw).pipe(Effect.mapError(() => protocolError("The browser returned a malformed PNG screenshot")));
866
+ if (bytes.length > policy.maxReturnedBytes) return yield* InteractiveBrowserLimitError.make({
867
+ implementation: browserRunInteractiveImplementation,
868
+ limit: "returned-bytes",
869
+ maximum: policy.maxReturnedBytes,
870
+ observed: bytes.length,
871
+ message: "The browser screenshot byte limit was reached"
872
+ });
873
+ return yield* Schema.decodeUnknownEffect(PageScreenshotResult)({
874
+ implementation: browserRunInteractiveImplementation,
875
+ mediaType: "image/png",
876
+ bytes: new Uint8Array(bytes)
877
+ }).pipe(Effect.mapError(() => protocolError("The browser returned a malformed PNG screenshot")));
878
+ }), decodeActionResult(page, policy).pipe(Effect.asVoid)))),
879
+ scroll: (request) => Schema.decodeUnknownEffect(BrowserScrollRequest)(request).pipe(Effect.mapError(() => policyError("The browser scroll request is malformed")), Effect.flatMap((decoded) => run(remote("scroll", () => page.scroll(decoded.deltaX, decoded.deltaY)).pipe(Effect.andThen(decodeActionResult(page, policy))), decodeActionResult(page, policy).pipe(Effect.asVoid)))),
880
+ close
881
+ },
882
+ run
883
+ };
884
+ });
885
+ const remainingMillis = Effect.fn("BrowserRunInteractive.remainingMillis")(function* (policy, startedAt) {
886
+ const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
887
+ return Math.max(0, policy.maxElapsedMillis - Math.max(0, now - startedAt));
888
+ });
889
+ const closeEntry = (close, warning) => ({
890
+ close: Effect.tryPromise({
891
+ try: close,
892
+ catch: (cause) => actionError("close", cause)
893
+ }).pipe(Effect.timeoutOrElse({
894
+ duration: Duration.millis(CLEANUP_STEP_TIMEOUT_MILLIS),
895
+ orElse: () => Effect.fail(actionError("close"))
896
+ })),
897
+ warning
898
+ });
899
+ const syncCloseEntry = (close, warning) => ({
900
+ close: Effect.try({
901
+ try: close,
902
+ catch: (cause) => actionError("close", cause)
903
+ }),
904
+ warning
905
+ });
906
+ const runTeardown = (entries) => Effect.forEach([...entries].reverse(), (entry) => entry.close.pipe(Effect.match({
907
+ onFailure: (error) => ({
908
+ error,
909
+ warning: entry.warning
910
+ }),
911
+ onSuccess: () => void 0
912
+ }))).pipe(Effect.map((failures) => failures.filter((failure) => failure !== void 0)));
913
+ const cdpCommand = (page, state, command, parameters, output, malformedMessage) => Effect.scoped(Effect.gen(function* () {
914
+ const cdp = yield* Effect.acquireRelease(Effect.tryPromise({
915
+ try: (signal) => closeLateAcquisition(signal, page.createCdpSession, (acquired) => acquired.detach()),
916
+ catch: (cause) => state.disconnected.value || isRemoteClosure(cause) ? expiredError() : protocolError("Creating the Cloudflare browser control session failed", cause)
917
+ }), (acquired) => closeWithWarning(acquired.detach, "Detaching the Cloudflare browser control session failed"), { interruptible: true });
918
+ const raw = yield* Effect.tryPromise({
919
+ try: () => cdp.send(command, parameters),
920
+ catch: (cause) => state.disconnected.value || isRemoteClosure(cause) ? expiredError() : protocolError("The Cloudflare browser control command failed", cause)
921
+ });
922
+ return yield* Schema.decodeUnknownEffect(output)(raw).pipe(Effect.mapError(() => protocolError(malformedMessage)));
923
+ }));
924
+ const makeHostService = (binding) => {
925
+ const closeSession = binding.closeSession;
926
+ const terminate = Effect.fn("BrowserRunInteractiveHost.terminate")(function* (sessionId, entries) {
927
+ const deadline = (yield* Clock.currentTimeMillis) + 1e4;
928
+ yield* closeSession(sessionId).pipe(Effect.interruptible, Effect.timeoutOrElse({
929
+ duration: "10 seconds",
930
+ orElse: () => Effect.fail(actionError("close"))
931
+ }));
932
+ const remaining = deadline - (yield* Clock.currentTimeMillis);
933
+ if (remaining <= 0) return yield* Effect.logWarning("Local browser teardown skipped after confirmed termination deadline");
934
+ yield* runTeardown(entries).pipe(Effect.flatMap((failures) => Effect.forEach(failures, (failure) => Effect.logWarning(failure.warning), { discard: true })), Effect.interruptible, Effect.timeout(`${remaining} millis`), Effect.catchCause(() => Effect.logWarning("Local browser teardown incomplete after confirmed termination")));
935
+ });
936
+ const closeAcquired = Effect.fn("BrowserRunInteractiveHost.closeAcquired")(function* (browser) {
937
+ const sessionId = yield* Effect.try({
938
+ try: browser.sessionId,
939
+ catch: () => actionError("close")
940
+ }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(BrowserRunSessionId)), Effect.mapError(() => actionError("close")), Effect.onError(() => closeWithWarning(browser.close, "Closing an unidentified browser failed")));
941
+ yield* terminate(Redacted.make(sessionId), [closeEntry(browser.close, "Closing the local browser connection failed")]);
942
+ });
943
+ const open = Effect.fn("BrowserRunInteractiveHost.open")(function* (policy) {
944
+ const fixedPolicy = yield* snapshotPolicy(policy);
945
+ const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
946
+ const runCleanup = Effect.runPromiseWith(Context.make(Clock.Clock, yield* Clock.Clock));
947
+ const state = {
948
+ closed: { value: false },
949
+ disconnected: { value: false },
950
+ uncertain: { value: false },
951
+ violation: { value: void 0 },
952
+ pendingRequests: /* @__PURE__ */ new Set()
953
+ };
954
+ const lifecycle = { managedTeardownInstalled: false };
955
+ const closers = [];
956
+ const releaseBeforeManaged = (entry) => Effect.suspend(() => lifecycle.managedTeardownInstalled ? Effect.void : entry.close.pipe(Effect.catchCause(() => Effect.logWarning(entry.warning))));
957
+ const browser = yield* Effect.acquireRelease(withinDeadline(Effect.tryPromise({
958
+ try: (signal) => closeLateAcquisition(signal, () => binding.launch(keepAliveMillis(fixedPolicy)), (acquired) => runCleanup(closeAcquired(acquired))),
959
+ catch: (cause) => isCapacityRefusal(cause) ? InteractiveBrowserCapacityError.make({
960
+ implementation: browserRunInteractiveImplementation,
961
+ message: "Browser Run has no capacity for a new browser session"
962
+ }) : protocolError("Launching the Browser Run session failed", cause)
963
+ }), fixedPolicy, startedAt), (acquired) => {
964
+ state.disconnected.value = true;
965
+ return lifecycle.managedTeardownInstalled ? Effect.void : closeAcquired(acquired).pipe(Effect.catch(() => Effect.logWarning("Whole-browser cleanup remains unconfirmed")));
966
+ }, { interruptible: true });
967
+ closers.push(closeEntry(browser.close, "Closing the interactive browser failed"));
968
+ const disconnected = () => {
969
+ state.disconnected.value = true;
970
+ };
971
+ yield* Effect.acquireRelease(Effect.try({
972
+ try: () => browser.onDisconnected(disconnected),
973
+ catch: (cause) => protocolError("Installing the browser disconnect listener failed", cause)
974
+ }), () => releaseBeforeManaged(syncCloseEntry(() => browser.offDisconnected(disconnected), "Removing the browser disconnect listener failed")));
975
+ closers.push(syncCloseEntry(() => browser.offDisconnected(disconnected), "Removing the browser disconnect listener failed"));
976
+ if (!(yield* Effect.try({
977
+ try: browser.isConnected,
978
+ catch: (cause) => protocolError("Reading the Browser Run connection state failed", cause)
979
+ }))) {
980
+ state.disconnected.value = true;
981
+ return yield* expiredError();
982
+ }
983
+ const sessionIdValue = yield* Effect.try({
984
+ try: browser.sessionId,
985
+ catch: (cause) => protocolError("Reading the Browser Run session identity failed", cause)
986
+ }).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(BrowserRunSessionId)(value).pipe(Effect.mapError(() => protocolError("The Browser Run session identity was malformed")))));
987
+ const context = yield* Effect.acquireRelease(withinDeadline(Effect.tryPromise({
988
+ try: (signal) => closeLateAcquisition(signal, browser.createContext, (acquired) => acquired.close()),
989
+ catch: (cause) => state.disconnected.value || isRemoteClosure(cause) ? expiredError() : protocolError("Creating the browser context failed", cause)
990
+ }), fixedPolicy, startedAt), (acquired) => releaseBeforeManaged(closeEntry(acquired.close, "Closing the interactive browser context failed")), { interruptible: true });
991
+ closers.push(closeEntry(context.close, "Closing the interactive browser context failed"));
992
+ const page = yield* Effect.acquireRelease(withinDeadline(Effect.tryPromise({
993
+ try: (signal) => closeLateAcquisition(signal, context.newPage, (acquired) => acquired.close()),
994
+ catch: (cause) => state.disconnected.value || isRemoteClosure(cause) ? expiredError() : protocolError("Creating the browser page failed", cause)
995
+ }), fixedPolicy, startedAt), (acquired) => releaseBeforeManaged(closeEntry(acquired.close, "Closing the interactive browser page failed")), { interruptible: true });
996
+ closers.push(closeEntry(page.close, "Closing the interactive browser page failed"));
997
+ yield* withinDeadline(Effect.tryPromise({
998
+ try: () => page.setBypassServiceWorker(true),
999
+ catch: (cause) => protocolError("Bypassing browser service workers failed", cause)
1000
+ }), fixedPolicy, startedAt);
1001
+ const requestListener = makeRequestListener(fixedPolicy, state);
1002
+ yield* Effect.acquireRelease(Effect.try({
1003
+ try: () => page.onRequest(requestListener),
1004
+ catch: (cause) => protocolError("Installing the browser request listener failed", cause)
1005
+ }), () => releaseBeforeManaged(syncCloseEntry(() => page.offRequest(requestListener), "Removing the browser request policy failed")));
1006
+ closers.push(syncCloseEntry(() => page.offRequest(requestListener), "Removing the browser request policy failed"));
1007
+ yield* withinDeadline(Effect.tryPromise({
1008
+ try: () => page.setRequestInterception(true),
1009
+ catch: (cause) => protocolError("Installing the browser request policy failed", cause)
1010
+ }), fixedPolicy, startedAt);
1011
+ yield* withinDeadline(awaitPendingRequests(state), fixedPolicy, startedAt);
1012
+ const setupFailure = stateFailure(state);
1013
+ if (setupFailure !== void 0) return yield* setupFailure;
1014
+ const teardown = yield* Effect.uninterruptible(Effect.gen(function* () {
1015
+ const cached = yield* Effect.cached(terminate(Redacted.make(sessionIdValue), closers));
1016
+ lifecycle.managedTeardownInstalled = true;
1017
+ yield* Effect.addFinalizer(() => Effect.uninterruptible(Effect.sync(() => {
1018
+ state.closed.value = true;
1019
+ state.disconnected.value = true;
1020
+ }).pipe(Effect.andThen(cached), Effect.catch(() => Effect.logWarning("Whole-browser cleanup remains unconfirmed")))));
1021
+ return cached;
1022
+ }));
1023
+ const close = Effect.uninterruptible(Effect.sync(() => {
1024
+ state.closed.value = true;
1025
+ state.disconnected.value = true;
1026
+ }).pipe(Effect.andThen(teardown)));
1027
+ const runtime = yield* makeHandle(page, fixedPolicy, startedAt, state, close);
1028
+ const currentPagePreflight = decodeActionResult(page, fixedPolicy).pipe(Effect.asVoid);
1029
+ const requestFitsSession = (requestedMillis) => remainingMillis(fixedPolicy, startedAt).pipe(Effect.flatMap((remaining) => remaining > 0 && requestedMillis <= remaining ? Effect.void : Effect.fail(policyError("The host browser request exceeds the remaining session time"))));
1030
+ return {
1031
+ handle: runtime.handle,
1032
+ sessionId: Redacted.make(sessionIdValue),
1033
+ resizeViewport: (viewport) => decodeViewport(viewport).pipe(Effect.flatMap((decoded) => runtime.run(Effect.tryPromise({
1034
+ try: () => page.setViewport(decoded),
1035
+ catch: (cause) => {
1036
+ if (state.disconnected.value || isRemoteClosure(cause)) {
1037
+ state.disconnected.value = true;
1038
+ return expiredError();
1039
+ }
1040
+ return protocolError("Resizing the browser viewport failed", cause);
1041
+ }
1042
+ }), currentPagePreflight, false))),
1043
+ getLiveView: (request) => Schema.decodeUnknownEffect(BrowserRunLiveViewRequest)(request).pipe(Effect.mapError(() => policyError("The Live View request is malformed")), Effect.flatMap((decoded) => runtime.run(cdpCommand(page, state, "Cloudflare.getLiveView", {
1044
+ mode: decoded.mode,
1045
+ expiresInMs: decoded.expiresInMs
1046
+ }, LiveViewObservation, "Cloudflare returned a malformed Live View response").pipe(Effect.flatMap((observation) => Schema.decodeUnknownEffect(BrowserRunLiveViewResult)({ devtoolsFrontendUrl: Redacted.make(observation.devtoolsFrontendUrl) }).pipe(Effect.mapError(() => protocolError("Cloudflare returned a malformed Live View response"))))), currentPagePreflight.pipe(Effect.andThen(requestFitsSession(decoded.expiresInMs)))))),
1047
+ handoff: (request) => Schema.decodeUnknownEffect(BrowserRunHandoffRequest)(request).pipe(Effect.mapError(() => policyError("The browser handoff request is malformed")), Effect.flatMap((decoded) => runtime.run(cdpCommand(page, state, "Cloudflare.handoff", {
1048
+ instructions: decoded.instructions,
1049
+ timeout: decoded.timeout
1050
+ }, HandoffObservation, "Cloudflare returned a malformed browser handoff response").pipe(Effect.flatMap((observation) => Schema.decodeUnknownEffect(BrowserRunHandoffResult)({ handoffId: Redacted.make(observation.handoffId) }).pipe(Effect.mapError(() => protocolError("Cloudflare returned a malformed browser handoff response"))))), currentPagePreflight.pipe(Effect.andThen(requestFitsSession(decoded.timeout)))))),
1051
+ getHandoffState: runtime.run(cdpCommand(page, state, "Cloudflare.getHandoffState", {}, HandoffStateObservation, "Cloudflare returned a malformed browser handoff state").pipe(Effect.flatMap((observation) => Schema.decodeUnknownEffect(BrowserRunHandoffState)({
1052
+ active: observation.active,
1053
+ ...observation.handoffId === void 0 ? {} : { handoffId: Redacted.make(observation.handoffId) },
1054
+ ...observation.durationMs === void 0 ? {} : { durationMs: observation.durationMs }
1055
+ }).pipe(Effect.mapError(() => protocolError("Cloudflare returned a malformed browser handoff state"))))), currentPagePreflight),
1056
+ close
1057
+ };
1058
+ });
1059
+ return BrowserRunInteractiveHost.of({
1060
+ open,
1061
+ closeSession,
1062
+ cleanupSemantics: "confirmed-terminal"
1063
+ });
1064
+ };
1065
+ /** Cloudflare host controls and private session identity for one scoped Browser Run pass. */
1066
+ const browserRunInteractiveHostLayer = () => Layer.effect(BrowserRunInteractiveHost, Effect.gen(function* () {
1067
+ return makeHostService(yield* BrowserRunInteractiveBinding);
1068
+ }));
1069
+ /** Worker-only generic adapter; Cloudflare identity and controls remain host-only. */
1070
+ const browserRunInteractiveLayer = () => Layer.effect(InteractiveBrowser, Effect.gen(function* () {
1071
+ const binding = yield* BrowserRunInteractiveBinding;
1072
+ const host = makeHostService(binding);
1073
+ return InteractiveBrowser.of({ open: (policy) => host.open(policy).pipe(Effect.map((session) => session.handle)) });
1074
+ }));
1075
+ const interactiveBindingLayer = (options) => BrowserRunInteractiveBinding.layer(options).pipe(Layer.provide(BrowserRunSessionLifecycle.layer(options)));
1076
+ /** Worker-only assembly; importing ordinary capture never loads Puppeteer. */
1077
+ const CloudflareInteractiveBrowser = {
1078
+ /**
1079
+ * Assemble binding, confirmed-session cleanup, and the generic browser service.
1080
+ * HttpClient and construction errors remain visible. Opening a pass still requires
1081
+ * an explicit policy and Scope; no browser is launched during Layer construction.
1082
+ */
1083
+ layer: (options) => browserRunInteractiveLayer().pipe(Layer.provide(interactiveBindingLayer(options))),
1084
+ /** Opt into private host controls instead of exposing them through the generic service. */
1085
+ hostLayer: (options) => browserRunInteractiveHostLayer().pipe(Layer.provide(interactiveBindingLayer(options)))
1086
+ };
1087
+ //#endregion
1088
+ export { BrowserRunCleanupError, BrowserRunHandoffRequest, BrowserRunHandoffResult, BrowserRunHandoffState, BrowserRunInteractiveBinding, BrowserRunInteractiveHost, BrowserRunLiveViewRequest, BrowserRunLiveViewResult, BrowserRunSessionLifecycle, BrowserRunViewport, CloudflareInteractiveBrowser, browserRunInteractiveHostLayer, browserRunInteractiveImplementation, browserRunInteractiveLayer, isBrowserRunUndispatchedActionError };
1089
+
1090
+ //# sourceMappingURL=InteractiveBrowser.mjs.map