@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0-beta.192
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.
- package/LICENSE +21 -0
- package/dist/Alarm-CbhflIzz.mjs +1931 -0
- package/dist/Alarm-CbhflIzz.mjs.map +1 -0
- package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
- package/dist/Alarm.d.mts +3 -0
- package/dist/Alarm.mjs +3 -0
- package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
- package/dist/BrowserCredentials.d.mts +2 -0
- package/dist/BrowserCredentials.mjs +1 -0
- package/dist/BrowserRestCapture.d.mts +14 -0
- package/dist/BrowserRestCapture.mjs +195 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
- package/dist/BrowserSession.d.mts +3 -0
- package/dist/BrowserSession.mjs +4 -0
- package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
- package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
- package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
- package/dist/BrowserUse.d.mts +2 -0
- package/dist/BrowserUse.mjs +1 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
- package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
- package/dist/CloudflareAiGateway.d.mts +2 -0
- package/dist/CloudflareAiGateway.mjs +1 -0
- package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
- package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
- package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
- package/dist/CloudflareBindings.d.mts +2 -0
- package/dist/CloudflareBindings.mjs +1 -0
- package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
- package/dist/CloudflareBrowser.d.mts +3 -0
- package/dist/CloudflareBrowser.mjs +1 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
- package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
- package/dist/CloudflareCodeMode.d.mts +2 -0
- package/dist/CloudflareCodeMode.mjs +1 -0
- package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +1 -0
- package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
- package/dist/CloudflareMemory.d.mts +2 -0
- package/dist/CloudflareMemory.mjs +1 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
- package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
- package/dist/CloudflareScheduling.d.mts +2 -0
- package/dist/CloudflareScheduling.mjs +1 -0
- package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
- package/dist/CloudflareSubscriptions.d.mts +2 -0
- package/dist/CloudflareSubscriptions.mjs +1 -0
- package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
- package/dist/CloudflareThreadClient.d.mts +3 -0
- package/dist/CloudflareThreadClient.mjs +3 -0
- package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
- package/dist/InteractiveBrowser.d.mts +2 -0
- package/dist/InteractiveBrowser.mjs +1 -0
- package/dist/LiveText-CfpcZaGb.d.mts +91 -0
- package/dist/LiveText-DaF0tN_p.mjs +148 -0
- package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
- package/dist/LiveText.d.mts +2 -0
- package/dist/LiveText.mjs +1 -0
- package/dist/R2ToolResultStorage.d.mts +27 -0
- package/dist/R2ToolResultStorage.mjs +84 -0
- package/dist/R2ToolResultStorage.mjs.map +1 -0
- package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
- package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
- package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -0
- package/dist/ThreadObject.mjs +1 -0
- package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
- package/dist/WakeScheduler.d.mts +2 -0
- package/dist/WakeScheduler.mjs +1 -0
- package/dist/boundary-YrOnE2zO.mjs +41 -0
- package/dist/boundary-YrOnE2zO.mjs.map +1 -0
- package/dist/browser-failure-CWBBnf1j.mjs +70 -0
- package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
- package/dist/index.d.mts +17 -0
- package/dist/index.mjs +17 -0
- package/dist/prepared-admission-DngoYN74.mjs +57 -0
- package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +134 -3
- package/src/Alarm.ts +3402 -0
- package/src/BrowserCredentials.ts +181 -0
- package/src/BrowserRestCapture.ts +383 -0
- package/src/BrowserSession.ts +993 -0
- package/src/BrowserUse.ts +438 -0
- package/src/CloudflareAiGateway.ts +176 -0
- package/src/CloudflareBindings.ts +225 -0
- package/src/CloudflareBrowser.ts +9 -0
- package/src/CloudflareCodeMode.ts +896 -0
- package/src/CloudflareConfig.ts +142 -0
- package/src/CloudflareMemory.ts +418 -0
- package/src/CloudflareScheduling.ts +736 -0
- package/src/CloudflareSubscriptions.ts +1032 -0
- package/src/CloudflareThreadClient.ts +980 -0
- package/src/InteractiveBrowser.ts +3300 -0
- package/src/LiveText.ts +145 -0
- package/src/R2ToolResultStorage.ts +131 -0
- package/src/ThreadObject.ts +1348 -0
- package/src/WakeScheduler.ts +102 -0
- package/src/index.ts +16 -0
- package/src/internal/boundary.ts +53 -0
- package/src/internal/browser-binding.ts +483 -0
- package/src/internal/browser-credentials.ts +481 -0
- package/src/internal/browser-failure.ts +145 -0
- package/src/internal/browser-file-selection.ts +146 -0
- package/src/internal/browser-quick-action.ts +666 -0
- package/src/internal/browser-readonly-live-view.ts +121 -0
- package/src/internal/browser-session-lifecycle.ts +200 -0
- package/src/internal/crypto.ts +44 -0
- package/src/internal/due-queue.ts +452 -0
- package/src/internal/host-protocol-error.ts +23 -0
- package/src/internal/layers.ts +1181 -0
- package/src/internal/live-text-observation.ts +8 -0
- package/src/internal/live-text-protocol.ts +59 -0
- package/src/internal/live-text.ts +339 -0
- package/src/internal/message-delivery.ts +149 -0
- package/src/internal/page-function.ts +12 -0
- package/src/internal/prepared-admission.ts +83 -0
- package/src/internal/progress-wait.ts +121 -0
- package/src/internal/transport.ts +53 -0
- package/README.md +0 -3
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
+
import * as FailureDiagnostic from "@systemfsoftware/agent/failure-diagnostic";
|
|
3
|
+
import * as Cause from "effect/Cause";
|
|
4
|
+
import * as Clock from "effect/Clock";
|
|
5
|
+
import * as Context from "effect/Context";
|
|
6
|
+
import * as Effect from "effect/Effect";
|
|
7
|
+
import * as Exit from "effect/Exit";
|
|
8
|
+
import * as Fiber from "effect/Fiber";
|
|
9
|
+
import * as Layer from "effect/Layer";
|
|
10
|
+
import * as Redacted from "effect/Redacted";
|
|
11
|
+
import * as Schema from "effect/Schema";
|
|
12
|
+
import * as Scope from "effect/Scope";
|
|
13
|
+
import * as Semaphore from "effect/Semaphore";
|
|
14
|
+
import { d as CredentialForm, g as LoginCredential, h as FillCredentialRequest, i as CardCredential, l as CredentialFillError, m as CredentialTarget, o as CredentialBinding, p as CredentialOrigin, t as BrowserCredentialAccess, u as CredentialFillResult } from "./BrowserCredentials-CktBoPgE.mjs";
|
|
15
|
+
import { b as BrowserRunRefusal, c as BrowserRunLiveViewResult, n as BrowserRunHandoffResult, r as BrowserRunHandoffState, s as BrowserRunLiveViewRequest, t as BrowserRunHandoffRequest, v as BrowserRunSessionLifecycle, y as BrowserRunBinding } from "./InteractiveBrowser-e8ZvxC1C.mjs";
|
|
16
|
+
import { a as reportBrowserCause, i as mapBrowserError, n as browserFailure, o as reportedBrowserError, r as inheritBrowserReport, t as BrowserRunFailure } from "./browser-failure-CWBBnf1j.mjs";
|
|
17
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
|
|
18
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
19
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
20
|
+
import * as Stream from "effect/Stream";
|
|
21
|
+
// src/internal/browser-credentials.ts
|
|
22
|
+
/** Supplied only under the attachment lock, with the remaining command/session budget. */
|
|
23
|
+
var BrowserSessionPage = class extends Context.Service()("@effect-agent/platform-cloudflare/internal/BrowserSessionPage") {};
|
|
24
|
+
const TargetReply = Schema.Union([Schema.Struct({
|
|
25
|
+
action: Schema.String.check(Schema.isMaxLength(2048)),
|
|
26
|
+
shape: Schema.String.check(Schema.isMaxLength(131072))
|
|
27
|
+
}), Schema.Struct({ reason: Schema.Literals(["stale-target", "unsupported"]) })]);
|
|
28
|
+
const WriteReply = Schema.Literals([
|
|
29
|
+
"filled",
|
|
30
|
+
"stale-target",
|
|
31
|
+
"unsupported-before-write",
|
|
32
|
+
"unsupported"
|
|
33
|
+
]);
|
|
34
|
+
const prepareFields = `(() => {
|
|
35
|
+
const doc = document;
|
|
36
|
+
let fields = [];
|
|
37
|
+
let form;
|
|
38
|
+
let snapshots = [];
|
|
39
|
+
const describe = el => {
|
|
40
|
+
if (!el || !el.isConnected || el.ownerDocument !== doc || doc !== document) return null;
|
|
41
|
+
const native = el instanceof HTMLTextAreaElement ||
|
|
42
|
+
(el instanceof HTMLSelectElement && !el.multiple) ||
|
|
43
|
+
(el instanceof HTMLInputElement && ['text','email','password','tel','number','month','search','url','date','time','week','datetime-local'].includes(el.type));
|
|
44
|
+
if (!native || el.matches(':disabled') || el.readOnly || !el.form) return null;
|
|
45
|
+
const values = [el.form.action, el.form.method, el.form.enctype, el.name, el.type, el.autocomplete ?? ''];
|
|
46
|
+
if (values.some(value => value.length > 2048)) return null;
|
|
47
|
+
return JSON.stringify(values);
|
|
48
|
+
};
|
|
49
|
+
const validate = () => fields.length > 0 && fields.every((el, index) =>
|
|
50
|
+
el.form === form && describe(el) !== null && describe(el) === snapshots[index]);
|
|
51
|
+
return {
|
|
52
|
+
prepare(selectors, roles) {
|
|
53
|
+
try {
|
|
54
|
+
fields = selectors.map(selector => {
|
|
55
|
+
const matches = doc.querySelectorAll(selector);
|
|
56
|
+
return matches.length === 1 ? matches[0] : null;
|
|
57
|
+
});
|
|
58
|
+
} catch { return {reason: 'stale-target'}; }
|
|
59
|
+
if (fields.some(el => !el) || new Set(fields).size !== fields.length) return {reason: 'stale-target'};
|
|
60
|
+
if (fields.some((el, index) => roles[index] === 'password' && el.type !== 'password')) return {reason: 'unsupported'};
|
|
61
|
+
snapshots = fields.map(describe);
|
|
62
|
+
form = fields[0].form;
|
|
63
|
+
if (!form || snapshots.some(value => value === null) || fields.some(el => el.form !== form)) return {reason: 'unsupported'};
|
|
64
|
+
return {action: form.action, shape: JSON.stringify(snapshots)};
|
|
65
|
+
},
|
|
66
|
+
target() { return validate() ? {action: form.action, shape: JSON.stringify(snapshots)} : {reason: 'stale-target'}; },
|
|
67
|
+
node(index) { return index === 0 ? doc.documentElement : index === 1 ? form : fields[index - 2]; },
|
|
68
|
+
fill(index, value) {
|
|
69
|
+
if (!validate()) return 'stale-target';
|
|
70
|
+
const el = fields[index];
|
|
71
|
+
if (el instanceof HTMLSelectElement) {
|
|
72
|
+
const options = [...el.options].filter(option => option.value === value);
|
|
73
|
+
if (options.length !== 1 || options[0].matches(':disabled')) return 'unsupported-before-write';
|
|
74
|
+
}
|
|
75
|
+
let prototype = Object.getPrototypeOf(el);
|
|
76
|
+
let setter;
|
|
77
|
+
while (prototype && !setter) { setter = Object.getOwnPropertyDescriptor(prototype, 'value')?.set; prototype = Object.getPrototypeOf(prototype); }
|
|
78
|
+
if (!setter) return 'unsupported-before-write';
|
|
79
|
+
setter.call(el, value);
|
|
80
|
+
if (el.value !== value) return 'unsupported';
|
|
81
|
+
el.dispatchEvent(new Event('input', {bubbles: true}));
|
|
82
|
+
el.dispatchEvent(new Event('change', {bubbles: true}));
|
|
83
|
+
return 'filled';
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
})()`;
|
|
87
|
+
const secretFor = (material, role) => {
|
|
88
|
+
if (material._tag === "LoginCredential") return role === "username" ? material.username : role === "password" ? material.password : void 0;
|
|
89
|
+
switch (role) {
|
|
90
|
+
case "card-name": return material.name;
|
|
91
|
+
case "card-number": return material.number;
|
|
92
|
+
case "card-expiry": return material.expiry;
|
|
93
|
+
case "card-expiry-month": return material.expiryMonth;
|
|
94
|
+
case "card-expiry-year": return material.expiryYear;
|
|
95
|
+
case "card-security-code": return material.securityCode;
|
|
96
|
+
case "username":
|
|
97
|
+
case "password": return;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/** Acquire exact native controls for this Scope; no credential material is resolved. */
|
|
101
|
+
const openForm = Effect.fnUntraced(function* (input) {
|
|
102
|
+
const { page } = yield* BrowserSessionPage;
|
|
103
|
+
const fail = (reason) => CredentialFillError.make({
|
|
104
|
+
reason,
|
|
105
|
+
dispatch: "not-dispatched",
|
|
106
|
+
filled: 0,
|
|
107
|
+
cleanup: "not-requested"
|
|
108
|
+
});
|
|
109
|
+
const remote = (run) => Effect.tryPromise({
|
|
110
|
+
try: run,
|
|
111
|
+
catch: () => fail("provider")
|
|
112
|
+
});
|
|
113
|
+
const release = (handles) => Effect.promise(async () => {
|
|
114
|
+
await Promise.all(handles.map((handle) => handle.dispose().catch(() => {})));
|
|
115
|
+
}).pipe(Effect.interruptible, Effect.timeoutOption("1 second"), Effect.asVoid);
|
|
116
|
+
const acquire = (run) => Effect.acquireRelease(remote(async (signal) => {
|
|
117
|
+
const handles = await run();
|
|
118
|
+
if (signal.aborted) {
|
|
119
|
+
await Promise.all(handles.map((handle) => handle.dispose().catch(() => {})));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
return handles;
|
|
123
|
+
}).pipe(Effect.filterOrFail((handles) => handles !== void 0, () => fail("provider")), Effect.interruptible), release);
|
|
124
|
+
const origin = Effect.fnUntraced(function* (value) {
|
|
125
|
+
const url = yield* Effect.try({
|
|
126
|
+
try: () => new URL(value),
|
|
127
|
+
catch: () => fail("denied")
|
|
128
|
+
});
|
|
129
|
+
if (url.username || url.password) return yield* fail("denied");
|
|
130
|
+
return yield* Schema.decodeEffect(CredentialOrigin)(url.origin).pipe(Effect.mapError(() => fail("denied")));
|
|
131
|
+
});
|
|
132
|
+
const request = yield* Schema.decodeEffect(CredentialForm, { onExcessProperty: "error" })(input).pipe(Effect.mapError(() => fail("denied")));
|
|
133
|
+
const roles = request.fields.map((field) => field.role);
|
|
134
|
+
if (new Set(roles).size !== roles.length || roles.some((role) => request.kind === "login" !== (role === "username" || role === "password"))) return yield* fail("denied");
|
|
135
|
+
let frame = page.mainFrame();
|
|
136
|
+
for (const selector of request.frame ?? []) {
|
|
137
|
+
const matches = yield* acquire(() => frame.$$(selector));
|
|
138
|
+
const element = matches[0];
|
|
139
|
+
if (matches.length !== 1 || element === void 0) return yield* fail("stale-target");
|
|
140
|
+
const child = yield* remote(() => element.contentFrame());
|
|
141
|
+
if (child === null) return yield* fail("unsupported");
|
|
142
|
+
frame = child;
|
|
143
|
+
}
|
|
144
|
+
const held = (yield* acquire(async () => [await frame.isolatedRealm().evaluateHandle(prepareFields)]))[0];
|
|
145
|
+
if (held === void 0) return yield* fail("provider");
|
|
146
|
+
const inspect = (raw) => Schema.decodeUnknownEffect(TargetReply)(raw).pipe(Effect.mapError(() => fail("provider")), Effect.filterOrFail((reply) => "action" in reply, (reply) => fail("reason" in reply ? reply.reason : "provider")));
|
|
147
|
+
const prepared = yield* remote(() => held.evaluate((state, selectors, roles) => {
|
|
148
|
+
if (typeof state !== "object" || state === null) return null;
|
|
149
|
+
return Reflect.apply(Reflect.get(state, "prepare"), state, [selectors, roles]);
|
|
150
|
+
}, request.fields.map((field) => field.selector), roles)).pipe(Effect.flatMap(inspect));
|
|
151
|
+
const target = CredentialTarget.make({
|
|
152
|
+
topOrigin: yield* origin(page.url()),
|
|
153
|
+
frameOrigin: yield* origin(frame.url()),
|
|
154
|
+
recipientOrigin: yield* origin(prepared.action)
|
|
155
|
+
});
|
|
156
|
+
const validate = Effect.gen(function* () {
|
|
157
|
+
if (frame.detached || (yield* origin(page.url())) !== target.topOrigin || (yield* origin(frame.url())) !== target.frameOrigin) return yield* fail("stale-target");
|
|
158
|
+
const current = yield* remote(() => held.evaluate((state) => {
|
|
159
|
+
if (typeof state !== "object" || state === null) return null;
|
|
160
|
+
return Reflect.apply(Reflect.get(state, "target"), state, []);
|
|
161
|
+
})).pipe(Effect.flatMap(inspect));
|
|
162
|
+
if ((yield* origin(current.action)) !== target.recipientOrigin) return yield* fail("stale-target");
|
|
163
|
+
});
|
|
164
|
+
return {
|
|
165
|
+
held,
|
|
166
|
+
target,
|
|
167
|
+
validate,
|
|
168
|
+
binding: Effect.gen(function* () {
|
|
169
|
+
const nodes = [];
|
|
170
|
+
for (let index = 0; index <= request.fields.length + 1; index++) {
|
|
171
|
+
const element = (yield* acquire(async () => [await held.evaluateHandle((state, index) => {
|
|
172
|
+
if (typeof state !== "object" || state === null) return null;
|
|
173
|
+
return Reflect.apply(Reflect.get(state, "node"), state, [index]);
|
|
174
|
+
}, index)]))[0]?.asElement();
|
|
175
|
+
if (element === null || element === void 0) return yield* fail("stale-target");
|
|
176
|
+
nodes.push(yield* remote(() => element.backendNodeId()));
|
|
177
|
+
}
|
|
178
|
+
yield* validate;
|
|
179
|
+
const digest = yield* remote(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(prepared.shape)));
|
|
180
|
+
return CredentialBinding.make({
|
|
181
|
+
version: 1,
|
|
182
|
+
pageId: page.mainFrame()._id,
|
|
183
|
+
frameId: frame._id,
|
|
184
|
+
target,
|
|
185
|
+
nodes,
|
|
186
|
+
shape: Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
187
|
+
});
|
|
188
|
+
})
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
/** Bind a host-owned request to this exact document and fields without reading their values. */
|
|
192
|
+
const prepareCredential = Effect.fnUntraced(function* (input) {
|
|
193
|
+
return yield* (yield* openForm(input)).binding;
|
|
194
|
+
}, Effect.scoped, Effect.withTracerEnabled(false));
|
|
195
|
+
/**
|
|
196
|
+
* Fill explicit native fields on an existing page without submitting. The owning browser session
|
|
197
|
+
* serializes operations and closes on timeout, interruption or uncertain dispatch; this function releases
|
|
198
|
+
* only its local handles. Ordinary native observations remain available, including credential echoes.
|
|
199
|
+
*/
|
|
200
|
+
const fillCredential = Effect.fnUntraced(function* (input) {
|
|
201
|
+
const { commandTimeoutMillis } = yield* BrowserSessionPage;
|
|
202
|
+
let dispatch = "not-dispatched";
|
|
203
|
+
let filled = 0;
|
|
204
|
+
const fail = (reason) => CredentialFillError.make({
|
|
205
|
+
reason,
|
|
206
|
+
dispatch,
|
|
207
|
+
filled,
|
|
208
|
+
cleanup: "not-requested"
|
|
209
|
+
});
|
|
210
|
+
const remote = (run) => Effect.tryPromise({
|
|
211
|
+
try: async (signal) => {
|
|
212
|
+
try {
|
|
213
|
+
return {
|
|
214
|
+
ok: true,
|
|
215
|
+
value: await run(signal)
|
|
216
|
+
};
|
|
217
|
+
} catch {
|
|
218
|
+
return { ok: false };
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
catch: () => fail("provider")
|
|
222
|
+
}).pipe(Effect.flatMap((result) => result.ok ? Effect.succeed(result.value) : Effect.fail(fail("provider"))));
|
|
223
|
+
return yield* Effect.gen(function* () {
|
|
224
|
+
const request = yield* Schema.decodeEffect(FillCredentialRequest, { onExcessProperty: "error" })(input).pipe(Effect.mapError(() => fail("denied")));
|
|
225
|
+
const form = yield* openForm(CredentialForm.make({
|
|
226
|
+
kind: request.kind,
|
|
227
|
+
fields: request.fields,
|
|
228
|
+
...request.frame === void 0 ? {} : { frame: request.frame }
|
|
229
|
+
}));
|
|
230
|
+
const { held, target } = form;
|
|
231
|
+
const validate = form.validate.pipe(Effect.mapError((error) => fail(error.reason)));
|
|
232
|
+
const roles = request.fields.map((field) => field.role);
|
|
233
|
+
if (request.binding !== void 0) {
|
|
234
|
+
const actual = yield* form.binding;
|
|
235
|
+
const expected = request.binding;
|
|
236
|
+
if (actual.pageId !== expected.pageId || actual.frameId !== expected.frameId || actual.shape !== expected.shape || actual.nodes.length !== expected.nodes.length || actual.nodes.some((node, index) => node !== expected.nodes[index]) || actual.target.topOrigin !== expected.target.topOrigin || actual.target.frameOrigin !== expected.target.frameOrigin || actual.target.recipientOrigin !== expected.target.recipientOrigin) return yield* fail("stale-target");
|
|
237
|
+
}
|
|
238
|
+
const access = yield* BrowserCredentialAccess;
|
|
239
|
+
const authorization = {
|
|
240
|
+
credential: request.credential,
|
|
241
|
+
kind: request.kind,
|
|
242
|
+
target,
|
|
243
|
+
roles
|
|
244
|
+
};
|
|
245
|
+
const authorize = Effect.suspend(() => access.authorize(authorization)).pipe(Effect.mapError((error) => fail(error.reason)));
|
|
246
|
+
yield* authorize;
|
|
247
|
+
yield* validate;
|
|
248
|
+
const raw = yield* access.resolve(authorization).pipe(Effect.mapError((error) => fail(error.reason)));
|
|
249
|
+
const material = yield* Schema.decodeEffect(request.kind === "login" ? LoginCredential : CardCredential)(raw).pipe(Effect.mapError(() => fail("resolver")));
|
|
250
|
+
for (const role of roles) if (secretFor(material, role) === void 0) return yield* fail("missing-credential");
|
|
251
|
+
for (const [index, role] of roles.entries()) {
|
|
252
|
+
yield* authorize;
|
|
253
|
+
yield* validate;
|
|
254
|
+
const value = secretFor(material, role);
|
|
255
|
+
if (value === void 0) return yield* fail("missing-credential");
|
|
256
|
+
const previous = dispatch;
|
|
257
|
+
const result = yield* remote((signal) => {
|
|
258
|
+
if (signal.aborted) return Promise.reject(fail("provider"));
|
|
259
|
+
dispatch = "possibly-dispatched";
|
|
260
|
+
return held.evaluate((state, field, secret) => {
|
|
261
|
+
if (typeof state !== "object" || state === null) return "stale-target";
|
|
262
|
+
return Reflect.apply(Reflect.get(state, "fill"), state, [field, secret]);
|
|
263
|
+
}, index, Redacted.value(value));
|
|
264
|
+
}).pipe(Effect.flatMap(Schema.decodeUnknownEffect(WriteReply)), Effect.mapError(() => fail("provider")));
|
|
265
|
+
if (result === "stale-target" || result === "unsupported-before-write") {
|
|
266
|
+
dispatch = previous;
|
|
267
|
+
return yield* fail(result === "stale-target" ? "stale-target" : "unsupported");
|
|
268
|
+
}
|
|
269
|
+
if (result === "unsupported") return yield* fail("unsupported");
|
|
270
|
+
dispatch = "dispatched";
|
|
271
|
+
filled++;
|
|
272
|
+
}
|
|
273
|
+
return CredentialFillResult.make({
|
|
274
|
+
dispatch: "dispatched",
|
|
275
|
+
filled
|
|
276
|
+
});
|
|
277
|
+
}).pipe(Effect.scoped, Effect.timeoutOrElse({
|
|
278
|
+
duration: commandTimeoutMillis,
|
|
279
|
+
orElse: () => Effect.fail(fail("timeout"))
|
|
280
|
+
}), Effect.catchCause((cause) => {
|
|
281
|
+
if (Cause.hasInterrupts(cause)) return Effect.interrupt;
|
|
282
|
+
if (cause.reasons.some((reason) => reason._tag === "Die" || reason._tag === "Fail" && !Schema.is(CredentialFillError)(reason.error))) return Effect.fail(fail("provider"));
|
|
283
|
+
const expected = cause.reasons.find((reason) => reason._tag === "Fail" && Schema.is(CredentialFillError)(reason.error));
|
|
284
|
+
return Effect.fail(fail(expected?._tag === "Fail" && Schema.is(CredentialFillError)(expected.error) ? expected.error.reason : "provider"));
|
|
285
|
+
}), Effect.withTracerEnabled(false));
|
|
286
|
+
});
|
|
287
|
+
// src/internal/browser-readonly-live-view.ts
|
|
288
|
+
const Identity = Schema.Struct({
|
|
289
|
+
sessionId: Schema.String.check(Schema.isUUID()),
|
|
290
|
+
targetId: Schema.NonEmptyString.check(Schema.isMaxLength(256))
|
|
291
|
+
});
|
|
292
|
+
const Reply = Schema.fromJsonString(Schema.Struct({
|
|
293
|
+
id: Identity.fields.targetId,
|
|
294
|
+
options: Schema.Struct({
|
|
295
|
+
mode: Schema.Literal("tab"),
|
|
296
|
+
guardrails: Schema.Struct({ mode: Schema.Literal("readonly") })
|
|
297
|
+
}),
|
|
298
|
+
devtoolsFrontendUrl: Schema.String
|
|
299
|
+
}));
|
|
300
|
+
const operation = "session.readonlyLiveView";
|
|
301
|
+
/** Only the REST endpoint can mint provider-enforced read-only connections. */
|
|
302
|
+
var BrowserRunReadonlyLiveView = class extends Context.Service()("@effect-agent/platform-cloudflare/internal/BrowserRunReadonlyLiveView") {
|
|
303
|
+
static layer(options) {
|
|
304
|
+
return Layer.effect(this, Effect.gen(function* () {
|
|
305
|
+
const client = yield* HttpClient.HttpClient;
|
|
306
|
+
return { mint: Effect.fnUntraced(function* (sessionId, targetId, request) {
|
|
307
|
+
const identity = yield* Schema.decodeEffect(Identity)({
|
|
308
|
+
sessionId: Redacted.value(sessionId),
|
|
309
|
+
targetId: Redacted.value(targetId)
|
|
310
|
+
});
|
|
311
|
+
const input = yield* Schema.decodeEffect(BrowserRunLiveViewRequest)(request);
|
|
312
|
+
const response = yield* client.execute(HttpClientRequest.post(`https://api.cloudflare.com/client/v4/accounts/${options.accountId}/browser-rendering/devtools/browser/${identity.sessionId}/live_view`).pipe(HttpClientRequest.bearerToken(options.apiToken), HttpClientRequest.bodyJsonUnsafe({
|
|
313
|
+
mode: input.mode,
|
|
314
|
+
expiresInMs: input.expiresInMs,
|
|
315
|
+
targetId: identity.targetId,
|
|
316
|
+
guardrails: { mode: "readonly" }
|
|
317
|
+
}))).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
|
|
318
|
+
if (response.status !== 200) return yield* new BrowserRunFailure({
|
|
319
|
+
operation,
|
|
320
|
+
reason: "provider",
|
|
321
|
+
status: response.status
|
|
322
|
+
});
|
|
323
|
+
const bytes = yield* Stream.runFoldEffect(response.stream, () => /* @__PURE__ */ new Uint8Array(), (body, chunk) => {
|
|
324
|
+
if (body.byteLength + chunk.byteLength > 16384) return Effect.fail(new BrowserRunFailure({
|
|
325
|
+
operation,
|
|
326
|
+
reason: "malformed"
|
|
327
|
+
}));
|
|
328
|
+
const combined = new Uint8Array(body.byteLength + chunk.byteLength);
|
|
329
|
+
combined.set(body);
|
|
330
|
+
combined.set(chunk, body.byteLength);
|
|
331
|
+
return Effect.succeed(combined);
|
|
332
|
+
});
|
|
333
|
+
const reply = yield* Schema.decodeEffect(Reply)(new TextDecoder().decode(bytes));
|
|
334
|
+
if (reply.id !== identity.targetId) return yield* new BrowserRunFailure({
|
|
335
|
+
operation,
|
|
336
|
+
reason: "malformed"
|
|
337
|
+
});
|
|
338
|
+
return yield* Schema.decodeEffect(BrowserRunLiveViewResult)({ devtoolsFrontendUrl: Redacted.make(reply.devtoolsFrontendUrl) });
|
|
339
|
+
}, Effect.mapError((cause) => browserFailure(operation, cause)), Effect.withTracerEnabled(false)) };
|
|
340
|
+
}));
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
// src/BrowserSession.ts
|
|
344
|
+
var BrowserSession_exports = /* @__PURE__ */ __exportAll({
|
|
345
|
+
BrowserRunHandoffRequest: () => BrowserRunHandoffRequest,
|
|
346
|
+
BrowserRunHandoffResult: () => BrowserRunHandoffResult,
|
|
347
|
+
BrowserRunHandoffState: () => BrowserRunHandoffState,
|
|
348
|
+
BrowserRunLiveViewRequest: () => BrowserRunLiveViewRequest,
|
|
349
|
+
BrowserRunLiveViewResult: () => BrowserRunLiveViewResult,
|
|
350
|
+
BrowserSessionError: () => BrowserSessionError,
|
|
351
|
+
BrowserSessionOptions: () => BrowserSessionOptions,
|
|
352
|
+
BrowserSessionReference: () => BrowserSessionReference,
|
|
353
|
+
BrowserSessions: () => BrowserSessions
|
|
354
|
+
});
|
|
355
|
+
const PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER));
|
|
356
|
+
const SessionId = Schema.Redacted(Schema.String.check(Schema.isUUID()));
|
|
357
|
+
const ProviderId = Schema.Redacted(Schema.NonEmptyString.check(Schema.isMaxLength(256)));
|
|
358
|
+
/** Private host record, not a model capability. Persist together with the owner's controller state. */
|
|
359
|
+
var BrowserSessionReference = class extends Schema.Class("BrowserSessionReference")({
|
|
360
|
+
version: Schema.Literal(1),
|
|
361
|
+
sessionId: SessionId,
|
|
362
|
+
contextId: ProviderId,
|
|
363
|
+
targetId: ProviderId,
|
|
364
|
+
expiresAt: PositiveMillis,
|
|
365
|
+
commandTimeoutMillis: PositiveMillis
|
|
366
|
+
}) {};
|
|
367
|
+
var BrowserSessionOptions = class extends Schema.Class("BrowserSessionOptions")({
|
|
368
|
+
maxElapsedMillis: PositiveMillis,
|
|
369
|
+
keepAliveMillis: Schema.optionalKey(PositiveMillis.check(Schema.isLessThanOrEqualTo(6e5))),
|
|
370
|
+
commandTimeoutMillis: Schema.optionalKey(PositiveMillis)
|
|
371
|
+
}) {};
|
|
372
|
+
/** No SDK text, selectors, page data, or credential values are retained in public failures. */
|
|
373
|
+
var BrowserSessionError = class extends Schema.TaggedError()("BrowserSessionError", {
|
|
374
|
+
reason: Schema.Literals([
|
|
375
|
+
"invalid",
|
|
376
|
+
"expired",
|
|
377
|
+
"missing-page",
|
|
378
|
+
"busy",
|
|
379
|
+
"closed",
|
|
380
|
+
"provider",
|
|
381
|
+
"timeout",
|
|
382
|
+
"cleanup"
|
|
383
|
+
]),
|
|
384
|
+
dispatch: Schema.Literals(["not-dispatched", "possibly-dispatched"]),
|
|
385
|
+
cleanup: Schema.Literals([
|
|
386
|
+
"not-requested",
|
|
387
|
+
"confirmed",
|
|
388
|
+
"unconfirmed"
|
|
389
|
+
])
|
|
390
|
+
}) {};
|
|
391
|
+
const failure = (reason, dispatch = "not-dispatched", cleanup = "not-requested", cause) => {
|
|
392
|
+
const error = BrowserSessionError.make({
|
|
393
|
+
reason,
|
|
394
|
+
dispatch,
|
|
395
|
+
cleanup
|
|
396
|
+
});
|
|
397
|
+
return cause === void 0 ? error : FailureDiagnostic.withCause(error, cause);
|
|
398
|
+
};
|
|
399
|
+
const annotateSessionCleanup = (error, cleanup) => Schema.is(BrowserSessionError)(error) && Object.prototype.isPrototypeOf.call(BrowserSessionError.prototype, error) ? inheritBrowserReport(error, FailureDiagnostic.withCause(BrowserSessionError.make({
|
|
400
|
+
...error,
|
|
401
|
+
cleanup
|
|
402
|
+
}), error)) : error;
|
|
403
|
+
const decode = (schema, input) => Schema.decodeUnknownEffect(schema, { onExcessProperty: "error" })(input).pipe(mapBrowserError((error) => failure("invalid", "not-dispatched", "not-requested", error)));
|
|
404
|
+
/** Scope finalizers require E=never. Preserve pure cancellation and wrap every other cause privately. */
|
|
405
|
+
const cleanupFinalizer = (effect) => effect.pipe(Effect.asVoid, Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason))) : Effect.die(failure("cleanup", "not-dispatched", "unconfirmed", cause))));
|
|
406
|
+
/** A deadline owns its work until stopped; cleanup failures join the timeout outcome. */
|
|
407
|
+
const timeout = (options) => (self) => Effect.suspend(() => {
|
|
408
|
+
let consumed = false;
|
|
409
|
+
const stop = (fiber) => Effect.uninterruptible(Effect.gen(function* () {
|
|
410
|
+
if (consumed) return;
|
|
411
|
+
yield* Fiber.interrupt(fiber);
|
|
412
|
+
const exit = yield* Fiber.await(fiber);
|
|
413
|
+
consumed = true;
|
|
414
|
+
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause);
|
|
415
|
+
}));
|
|
416
|
+
return Effect.uninterruptibleMask((restore) => Effect.acquireUseRelease(Effect.gen(function* () {
|
|
417
|
+
const scope = yield* Scope.make();
|
|
418
|
+
return {
|
|
419
|
+
scope,
|
|
420
|
+
fiber: yield* Effect.forkIn(self.pipe(Effect.interruptible), scope)
|
|
421
|
+
};
|
|
422
|
+
}), ({ fiber }) => restore(Fiber.await(fiber).pipe(Effect.timeoutOrElse({
|
|
423
|
+
duration: options.duration,
|
|
424
|
+
orElse: () => Effect.as(Effect.void, void 0)
|
|
425
|
+
}))).pipe(Effect.flatMap((exit) => {
|
|
426
|
+
if (exit !== void 0) {
|
|
427
|
+
consumed = true;
|
|
428
|
+
return exit;
|
|
429
|
+
}
|
|
430
|
+
return Effect.uninterruptible(Effect.exit(stop(fiber)).pipe(Effect.flatMap((stopped) => options.orElse().pipe(Effect.onExit(() => Exit.isFailure(stopped) ? Effect.failCause(stopped.cause) : Effect.void)))));
|
|
431
|
+
})), ({ scope, fiber }) => stop(fiber).pipe(Effect.onExit((exit) => Scope.close(scope, exit)))));
|
|
432
|
+
});
|
|
433
|
+
const native = Effect.fnUntraced(function* (operation, action) {
|
|
434
|
+
const runReport = Effect.runPromiseWith(yield* Effect.context());
|
|
435
|
+
return yield* Effect.tryPromise({
|
|
436
|
+
try: async (signal) => {
|
|
437
|
+
try {
|
|
438
|
+
return {
|
|
439
|
+
ok: true,
|
|
440
|
+
value: await action(signal)
|
|
441
|
+
};
|
|
442
|
+
} catch (cause) {
|
|
443
|
+
if (!signal.aborted || cause !== signal.reason) await runReport(reportBrowserCause(operation, Cause.fail(cause)));
|
|
444
|
+
return {
|
|
445
|
+
ok: false,
|
|
446
|
+
cause
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
catch: (cause) => failure("provider", "not-dispatched", "not-requested", cause)
|
|
451
|
+
}).pipe(Effect.flatMap((result) => result.ok ? Effect.succeed(result.value) : Effect.fail(reportedBrowserError(failure("provider", "not-dispatched", "not-requested", result.cause)))), Effect.withTracerEnabled(false));
|
|
452
|
+
});
|
|
453
|
+
const withCdp = Effect.fnUntraced(function* (page, commandTimeoutMillis, action) {
|
|
454
|
+
const runCleanup = Effect.runPromiseWith(yield* Effect.context());
|
|
455
|
+
let acquired;
|
|
456
|
+
let released = false;
|
|
457
|
+
const release = Effect.uninterruptible(Effect.suspend(() => {
|
|
458
|
+
if (acquired === void 0 || released) return Effect.void;
|
|
459
|
+
released = true;
|
|
460
|
+
const cdp = acquired;
|
|
461
|
+
return native("session.cdp.detach", () => cdp.detach()).pipe(timeout({
|
|
462
|
+
duration: commandTimeoutMillis,
|
|
463
|
+
orElse: () => Effect.fail(failure("cleanup", "not-dispatched", "unconfirmed", failure("timeout")))
|
|
464
|
+
}));
|
|
465
|
+
}));
|
|
466
|
+
return yield* Effect.uninterruptibleMask((restore) => Effect.acquireUseRelease(restore(native("session.cdp.attach", async (signal) => {
|
|
467
|
+
const cdp = await page.createCDPSession();
|
|
468
|
+
acquired = cdp;
|
|
469
|
+
if (signal.aborted) {
|
|
470
|
+
await runCleanup(release);
|
|
471
|
+
signal.throwIfAborted();
|
|
472
|
+
}
|
|
473
|
+
return cdp;
|
|
474
|
+
})), (cdp) => restore(action(cdp)), () => release).pipe(Effect.onExit(() => release)));
|
|
475
|
+
});
|
|
476
|
+
const targetId = (page, commandTimeoutMillis) => withCdp(page, commandTimeoutMillis, (cdp) => native("session.target", async () => (await cdp.send("Target.getTargetInfo")).targetInfo.targetId));
|
|
477
|
+
/** Native Cloudflare sessions; no framework browser workflow, checkpoint transfer, or observation policy. */
|
|
478
|
+
var BrowserSessions = class BrowserSessions extends Context.Service()("@effect-agent/platform-cloudflare/BrowserSessions") {
|
|
479
|
+
static layerNoDeps = Layer.effect(this, Effect.gen(function* () {
|
|
480
|
+
const binding = yield* BrowserRunBinding;
|
|
481
|
+
const lifecycle = yield* BrowserRunSessionLifecycle;
|
|
482
|
+
const readonlyLiveView = yield* BrowserRunReadonlyLiveView;
|
|
483
|
+
const close = (sessionId) => decode(SessionId, sessionId).pipe(Effect.flatMap((id) => lifecycle.close(id).pipe(mapBrowserError((error) => failure("cleanup", "not-dispatched", "unconfirmed", error)))));
|
|
484
|
+
const cleanup = (sessionId) => close(sessionId).pipe(Effect.as("confirmed"), Effect.tapCause((cause) => reportBrowserCause("session.close", cause)));
|
|
485
|
+
const connect = Effect.fnUntraced(function* (sessionId) {
|
|
486
|
+
let attachment;
|
|
487
|
+
const retire = Effect.suspend(() => attachment === void 0 ? Effect.void : attachment.retire.pipe(timeout({
|
|
488
|
+
duration: "10 seconds",
|
|
489
|
+
orElse: () => Effect.fail(failure("cleanup"))
|
|
490
|
+
}), Effect.tapCause((cause) => reportBrowserCause("session.disconnect", cause)), mapBrowserError((error) => failure("cleanup", "not-dispatched", "unconfirmed", error))));
|
|
491
|
+
yield* Effect.addFinalizer(() => cleanupFinalizer(retire));
|
|
492
|
+
return {
|
|
493
|
+
browser: yield* native("session.connect", (signal) => {
|
|
494
|
+
attachment = binding.connect(Redacted.value(sessionId), "session.connect", signal);
|
|
495
|
+
return attachment.browser;
|
|
496
|
+
}),
|
|
497
|
+
retire
|
|
498
|
+
};
|
|
499
|
+
});
|
|
500
|
+
const allocate = Effect.fnUntraced(function* (input, retain, cleanupState) {
|
|
501
|
+
const options = yield* decode(BrowserSessionOptions, input);
|
|
502
|
+
const expiresAt = (yield* Clock.currentTimeMillis) + options.maxElapsedMillis;
|
|
503
|
+
if (!Number.isSafeInteger(expiresAt)) return yield* failure("invalid");
|
|
504
|
+
let sessionId;
|
|
505
|
+
let retained = false;
|
|
506
|
+
const runCleanup = Effect.runPromiseWith(yield* Effect.context());
|
|
507
|
+
yield* Effect.addFinalizer(() => sessionId === void 0 || retained ? Effect.void : cleanupFinalizer(cleanup(sessionId).pipe(Effect.tap((result) => Effect.sync(() => {
|
|
508
|
+
cleanupState.result = result;
|
|
509
|
+
})))));
|
|
510
|
+
cleanupState.result = "unconfirmed";
|
|
511
|
+
let refusal;
|
|
512
|
+
let acquisitionExited = false;
|
|
513
|
+
sessionId = yield* Effect.uninterruptibleMask((restore) => restore(native("session.acquire", async (signal) => {
|
|
514
|
+
const acquired = await binding.acquire(options.keepAliveMillis ?? 6e5, "session.acquire");
|
|
515
|
+
if (acquired instanceof BrowserRunRefusal) {
|
|
516
|
+
refusal = acquired;
|
|
517
|
+
if (acquisitionExited) await runCleanup(acquired.collect.pipe(Effect.andThen(reportBrowserCause("session.acquire", Cause.fail(acquired.error)))));
|
|
518
|
+
return acquired;
|
|
519
|
+
}
|
|
520
|
+
const id = Redacted.make(acquired);
|
|
521
|
+
if (signal.aborted) {
|
|
522
|
+
await runCleanup(cleanup(id));
|
|
523
|
+
signal.throwIfAborted();
|
|
524
|
+
}
|
|
525
|
+
return id;
|
|
526
|
+
})).pipe(Effect.onExit((exit) => {
|
|
527
|
+
acquisitionExited = true;
|
|
528
|
+
return Exit.isFailure(exit) && refusal !== void 0 ? refusal.failure : Effect.void;
|
|
529
|
+
}), Effect.filterOrElse((acquired) => !(acquired instanceof BrowserRunRefusal), (refusal) => refusal.failure), Effect.tapCause((cause) => reportBrowserCause("session.acquire", cause)), mapBrowserError((error) => error instanceof BrowserRunFailure ? reportedBrowserError(failure("provider", "not-dispatched", "not-requested", error)) : error)));
|
|
530
|
+
const connection = yield* connect(sessionId);
|
|
531
|
+
const page = yield* native("session.page", async () => {
|
|
532
|
+
return await (await connection.browser.createBrowserContext()).newPage();
|
|
533
|
+
});
|
|
534
|
+
const reference = yield* decode(BrowserSessionReference, {
|
|
535
|
+
version: 1,
|
|
536
|
+
sessionId,
|
|
537
|
+
contextId: Redacted.make(page.browserContext().id ?? ""),
|
|
538
|
+
targetId: Redacted.make(yield* targetId(page, options.commandTimeoutMillis ?? 3e4)),
|
|
539
|
+
expiresAt,
|
|
540
|
+
commandTimeoutMillis: options.commandTimeoutMillis ?? 3e4
|
|
541
|
+
});
|
|
542
|
+
yield* Effect.uninterruptibleMask((restore) => restore(retain(reference)).pipe(Effect.tap(() => Effect.sync(() => {
|
|
543
|
+
retained = true;
|
|
544
|
+
cleanupState.result = "not-requested";
|
|
545
|
+
}))));
|
|
546
|
+
return {
|
|
547
|
+
reference,
|
|
548
|
+
page,
|
|
549
|
+
...connection
|
|
550
|
+
};
|
|
551
|
+
});
|
|
552
|
+
const create = Effect.fnUntraced(function* (input, retain) {
|
|
553
|
+
const cleanupState = { result: "not-requested" };
|
|
554
|
+
return yield* allocate(input, retain, cleanupState).pipe(Effect.map(({ reference }) => reference), timeout({
|
|
555
|
+
duration: "30 seconds",
|
|
556
|
+
orElse: () => Effect.fail(failure("timeout"))
|
|
557
|
+
}), Effect.scoped, mapBrowserError((error) => annotateSessionCleanup(error, cleanupState.result), (defect) => annotateSessionCleanup(defect, cleanupState.result)), Effect.withTracerEnabled(false));
|
|
558
|
+
});
|
|
559
|
+
const makeSession = Effect.fnUntraced(function* (reference, browser, currentPage, retire) {
|
|
560
|
+
const scope = yield* Effect.scope;
|
|
561
|
+
const lock = yield* Semaphore.make(1);
|
|
562
|
+
let invalid = false;
|
|
563
|
+
let cleanupResult = "not-requested";
|
|
564
|
+
const terminate = Effect.suspend(() => {
|
|
565
|
+
if (invalid) return Effect.void;
|
|
566
|
+
invalid = true;
|
|
567
|
+
cleanupResult = "unconfirmed";
|
|
568
|
+
return retire.pipe(Effect.onExit(() => cleanup(reference.sessionId).pipe(Effect.tap((result) => Effect.sync(() => {
|
|
569
|
+
cleanupResult = result;
|
|
570
|
+
})), Effect.asVoid)));
|
|
571
|
+
});
|
|
572
|
+
const failAfterTermination = (cause, annotate) => Effect.uninterruptible(terminate.pipe(Effect.exit, Effect.flatMap((exit) => {
|
|
573
|
+
const original = Cause.map(cause, (error) => annotate(error, cleanupResult));
|
|
574
|
+
return Effect.failCause(Exit.isFailure(exit) ? Cause.combine(original, exit.cause) : original);
|
|
575
|
+
})));
|
|
576
|
+
const runEffect = (action) => lock.withPermitsIfAvailable(1)(Effect.gen(function* () {
|
|
577
|
+
if (invalid || scope.state._tag === "Closed" || !browser.isConnected()) return yield* failure("closed");
|
|
578
|
+
const remaining = reference.expiresAt - (yield* Clock.currentTimeMillis);
|
|
579
|
+
if (remaining <= 0) return yield* failAfterTermination(Cause.fail(failure("expired")), (error, cleanup) => failure(error.reason, error.dispatch, cleanup, error));
|
|
580
|
+
return yield* action(Math.min(remaining, reference.commandTimeoutMillis)).pipe(Effect.onExit((exit) => !invalid && Exit.isFailure(exit) && (Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause)) ? (Cause.hasInterruptsOnly(exit.cause) ? Effect.void : reportBrowserCause("session.command", exit.cause)).pipe(Effect.onExit(() => terminate)) : Effect.void));
|
|
581
|
+
})).pipe(Effect.flatMap(Effect.fromOption(() => failure("busy"))), Effect.withTracerEnabled(false));
|
|
582
|
+
const runAction = (authorize, action, terminateOnError = false, timeoutMillis) => runEffect((commandTimeoutMillis) => authorize.pipe(Effect.andThen(() => Effect.uninterruptibleMask((restore) => restore(action(Math.min(commandTimeoutMillis, timeoutMillis ?? commandTimeoutMillis))).pipe(Effect.catchCause((cause) => {
|
|
583
|
+
const annotate = (error, cleanup) => inheritBrowserReport(error, failure(error.reason, "possibly-dispatched", cleanup, error));
|
|
584
|
+
return terminateOnError && !invalid ? failAfterTermination(cause, annotate) : Effect.failCause(Cause.map(cause, (error) => annotate(error, error.cleanup)));
|
|
585
|
+
})))), timeout({
|
|
586
|
+
duration: Math.min(commandTimeoutMillis, timeoutMillis ?? commandTimeoutMillis),
|
|
587
|
+
orElse: () => failAfterTermination(Cause.fail(failure("timeout", "possibly-dispatched")), (error, cleanup) => failure(error.reason, error.dispatch, cleanup, error))
|
|
588
|
+
})));
|
|
589
|
+
const run = (authorize, action, terminateOnError = false, timeoutMillis) => runAction(authorize, () => native("session.command", () => action(currentPage)), terminateOnError, timeoutMillis);
|
|
590
|
+
const command = (authorize, method, parameters, schema) => runAction(authorize, (commandTimeoutMillis) => withCdp(currentPage, commandTimeoutMillis, (cdp) => native("session.command", () => Reflect.apply(Reflect.get(cdp, "send"), cdp, [method, parameters])).pipe(Effect.flatMap((result) => Schema.decodeUnknownEffect(schema)(result).pipe(mapBrowserError((error) => failure("provider", "not-dispatched", "not-requested", error)))))), method === "Cloudflare.handoff");
|
|
591
|
+
return {
|
|
592
|
+
reference,
|
|
593
|
+
run: (authorize, action, options) => options === void 0 ? run(authorize, action) : decode(PositiveMillis, options.timeoutMillis).pipe(Effect.flatMap((timeoutMillis) => run(authorize, action, false, timeoutMillis))),
|
|
594
|
+
prepareCredential: (request) => runEffect((commandTimeoutMillis) => prepareCredential(request).pipe(Effect.provideService(BrowserSessionPage, {
|
|
595
|
+
page: currentPage,
|
|
596
|
+
commandTimeoutMillis
|
|
597
|
+
}), timeout({
|
|
598
|
+
duration: commandTimeoutMillis,
|
|
599
|
+
orElse: () => failAfterTermination(Cause.fail(failure("timeout")), (error, cleanup) => failure(error.reason, error.dispatch, cleanup, error))
|
|
600
|
+
}))),
|
|
601
|
+
fillCredential: (request) => runEffect((commandTimeoutMillis) => fillCredential(request).pipe(Effect.provideService(BrowserSessionPage, {
|
|
602
|
+
page: currentPage,
|
|
603
|
+
commandTimeoutMillis
|
|
604
|
+
}), Effect.catchCauseIf((cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && (reason.error.reason === "timeout" || reason.error.dispatch === "possibly-dispatched")), (cause) => failAfterTermination(cause, (error, cleanup) => FailureDiagnostic.withCause(CredentialFillError.make({
|
|
605
|
+
...error,
|
|
606
|
+
cleanup
|
|
607
|
+
}), error))))),
|
|
608
|
+
handoff: (authorize, request) => decode(BrowserRunHandoffRequest, request).pipe(Effect.flatMap((value) => command(authorize, "Cloudflare.handoff", {
|
|
609
|
+
instructions: value.instructions,
|
|
610
|
+
timeout: value.timeout
|
|
611
|
+
}, Schema.Struct({ handoffId: Schema.NonEmptyString.check(Schema.isMaxLength(1024)) }))), Effect.map((value) => BrowserRunHandoffResult.make({ handoffId: Redacted.make(value.handoffId) }))),
|
|
612
|
+
getLiveView: (authorize, request) => decode(BrowserRunLiveViewRequest, request).pipe(Effect.flatMap((value) => command(authorize, "Cloudflare.getLiveView", {
|
|
613
|
+
mode: value.mode,
|
|
614
|
+
expiresInMs: value.expiresInMs
|
|
615
|
+
}, Schema.Struct({ devtoolsFrontendUrl: Schema.String }))), Effect.flatMap((value) => decode(BrowserRunLiveViewResult, { devtoolsFrontendUrl: Redacted.make(value.devtoolsFrontendUrl) }))),
|
|
616
|
+
getReadOnlyLiveView: (authorize, request) => decode(BrowserRunLiveViewRequest, request).pipe(Effect.flatMap((value) => runEffect((commandTimeoutMillis) => authorize.pipe(Effect.andThen(() => readonlyLiveView.mint(reference.sessionId, reference.targetId, value).pipe(Effect.tapCause((cause) => reportBrowserCause("session.readonlyLiveView", cause)), mapBrowserError((error) => reportedBrowserError(failure("provider", "not-dispatched", "not-requested", error))))), timeout({
|
|
617
|
+
duration: commandTimeoutMillis,
|
|
618
|
+
orElse: () => Effect.fail(failure("timeout"))
|
|
619
|
+
}))))),
|
|
620
|
+
getHandoffState: (authorize) => command(authorize, "Cloudflare.getHandoffState", {}, Schema.Struct({
|
|
621
|
+
active: Schema.Boolean,
|
|
622
|
+
handoffId: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(1024))),
|
|
623
|
+
durationMs: Schema.optionalKey(Schema.Natural)
|
|
624
|
+
})).pipe(Effect.map((value) => BrowserRunHandoffState.make({
|
|
625
|
+
active: value.active,
|
|
626
|
+
...value.handoffId === void 0 ? {} : { handoffId: Redacted.make(value.handoffId) },
|
|
627
|
+
...value.durationMs === void 0 ? {} : { durationMs: value.durationMs }
|
|
628
|
+
})))
|
|
629
|
+
};
|
|
630
|
+
});
|
|
631
|
+
const createAttached = Effect.fnUntraced(function* (input, retain) {
|
|
632
|
+
const scope = yield* Scope.fork(yield* Effect.scope);
|
|
633
|
+
const cleanupState = { result: "not-requested" };
|
|
634
|
+
return yield* allocate(input, retain, cleanupState).pipe(Effect.flatMap(({ reference, browser, page, retire }) => makeSession(reference, browser, page, retire)), Effect.provideService(Scope.Scope, scope), timeout({
|
|
635
|
+
duration: "30 seconds",
|
|
636
|
+
orElse: () => Effect.fail(failure("timeout"))
|
|
637
|
+
}), Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void), mapBrowserError((error) => annotateSessionCleanup(error, cleanupState.result), (defect) => annotateSessionCleanup(defect, cleanupState.result)), Effect.withTracerEnabled(false));
|
|
638
|
+
});
|
|
639
|
+
const attachPage = Effect.fnUntraced(function* (input) {
|
|
640
|
+
const reference = yield* decode(BrowserSessionReference, input);
|
|
641
|
+
if (reference.expiresAt <= (yield* Clock.currentTimeMillis)) return yield* failure("expired");
|
|
642
|
+
const { browser, retire } = yield* connect(reference.sessionId);
|
|
643
|
+
const context = browser.browserContexts().find((value) => value.id === Redacted.value(reference.contextId));
|
|
644
|
+
if (context === void 0) return yield* failure("missing-page");
|
|
645
|
+
for (const page of yield* native("session.pages", () => context.pages())) if ((yield* targetId(page, reference.commandTimeoutMillis)) === Redacted.value(reference.targetId)) return yield* makeSession(reference, browser, page, retire);
|
|
646
|
+
return yield* failure("missing-page");
|
|
647
|
+
});
|
|
648
|
+
const attach = Effect.fnUntraced(function* (input) {
|
|
649
|
+
const reference = yield* decode(BrowserSessionReference, input);
|
|
650
|
+
const scope = yield* Scope.fork(yield* Effect.scope);
|
|
651
|
+
return yield* attachPage(reference).pipe(Effect.provideService(Scope.Scope, scope), timeout({
|
|
652
|
+
duration: reference.commandTimeoutMillis,
|
|
653
|
+
orElse: () => reportBrowserCause("session.connect", Cause.fail(failure("timeout"))).pipe(Effect.andThen(Effect.fail(reportedBrowserError(failure("timeout")))))
|
|
654
|
+
}), Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void));
|
|
655
|
+
});
|
|
656
|
+
return BrowserSessions.of({
|
|
657
|
+
create,
|
|
658
|
+
createAttached,
|
|
659
|
+
attach,
|
|
660
|
+
close,
|
|
661
|
+
keepAlive: (sessionId) => decode(SessionId, sessionId).pipe(Effect.flatMap((id) => binding.keepAlive(Redacted.value(id)).pipe(timeout({
|
|
662
|
+
duration: "10 seconds",
|
|
663
|
+
orElse: () => Effect.fail(failure("timeout"))
|
|
664
|
+
}), Effect.tapCause((cause) => reportBrowserCause("session.keepAlive", cause)), mapBrowserError((error) => reportedBrowserError(failure(error.reason === "timeout" ? "timeout" : "provider", "not-dispatched", "not-requested", error))))), Effect.withTracerEnabled(false))
|
|
665
|
+
});
|
|
666
|
+
}));
|
|
667
|
+
static layer(options) {
|
|
668
|
+
return this.layerNoDeps.pipe(Layer.provide(BrowserRunBinding.layer(options.browser)), Layer.provide(BrowserRunSessionLifecycle.layer(options)), Layer.provide(BrowserRunReadonlyLiveView.layer(options)));
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
export { BrowserSessions as a, BrowserSession_exports as i, BrowserSessionOptions as n, BrowserSessionReference as r, BrowserSessionError as t };
|
|
672
|
+
|
|
673
|
+
//# sourceMappingURL=BrowserSession-Ce8cWN1A.mjs.map
|