@scwrap/browser 0.1.0 → 0.3.0

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/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # Browser providers
2
+
3
+ `@scwrap/browser` provides the `Browser` Capability whose port, `Browser.open` and `Browser.openIn`, lives in `@scwrap/domain`. Scrapers never import Playwright; a Release or a test picks one of these providers.
4
+
5
+ | Export | Import from | Provides | Source |
6
+ | --- | --- | --- | --- |
7
+ | `browserRun` | `@scwrap/browser/browser-run` | `Browser`: Cloudflare Browser Run through the instance's front desk, with `@cloudflare/playwright`. Needs the `browser:browser-run` grant. Covers no location. | [browser-run.ts](src/browser-run.ts) |
8
+ | `browserUse`, `browserUseWith({ timeoutMinutes })` | `@scwrap/browser/browser-use` | `Browser` for every country: a Browser Use cloud session over CDP whose `proxyCountryCode` is the page's location. Gets the session from the instance's front desk with the `browser:browser-use` grant, or outside an instance with `BROWSER_USE_API_KEY`; stops the session and verifies it stopped when the scope closes. | [browser-use.ts](src/browser-use.ts) |
9
+ | `nodeBrowser({ prepare? })` | `@scwrap/browser/node` | `Browser` over a local Playwright Chromium, for acceptance tests and scripts. `prepare` receives each context, for example to `route` fixture pages. Needs the optional peer `playwright`. | [node.ts](src/node.ts) |
10
+ | `playwrightBrowser({ connect, prepare? })` | `@scwrap/browser` | A provider over any Playwright connection, covering the countries it is typed with. | [playwright.ts](src/playwright.ts) |
11
+
12
+ `browserRun` and `browserUse` load `@cloudflare/playwright` only when a page opens, so Node, such as the `scwrap` CLI, can import them.
13
+
14
+ The reference is [The Browser Capability](../../docs/browser/browser.md) and [Providing a Browser](../../docs/browser/providing-a-browser.md).
15
+
16
+ ## Tests
17
+
18
+ ```sh
19
+ pnpm --filter @scwrap/browser test
20
+ ```
21
+
22
+ [front-desk.test.ts](test/front-desk.test.ts) checks that both providers open sessions through the front desk inside an instance. [node.test.ts](test/node.test.ts) drives a real Chromium through the `Page` API: navigation status, clicks, waits, the time zone option, and a page failure as `BrowserError`.
@@ -0,0 +1,3 @@
1
+ import { Browser } from "@scwrap/domain";
2
+ export declare const browserRun: import("effect/Layer").Layer<Browser<never>, never, never>;
3
+ //# sourceMappingURL=browser-run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-run.d.ts","sourceRoot":"","sources":["../src/browser-run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAuB,MAAM,gBAAgB,CAAC;AAO9D,eAAO,MAAM,UAAU,4DAyBtB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Browser, InstanceCredentials } from "@scwrap/domain";
2
+ import { Effect, Option } from "effect";
3
+ import { cloudflarePlaywright } from "./cloudflare-playwright.js";
4
+ import { frontDeskSession, outsideInstance } from "./front-desk.js";
5
+ import { openPlaywrightPage } from "./playwright.js";
6
+ export const browserRun = Browser.layer((_location, browserOptions) => Effect.gen(function* browserRunPage() {
7
+ const credentials = yield* InstanceCredentials;
8
+ if (Option.isNone(credentials)) {
9
+ return yield* outsideInstance("browser-run");
10
+ }
11
+ const { endpoint } = yield* frontDeskSession(credentials.value, "browser-run", {});
12
+ return yield* openPlaywrightPage(
13
+ // @effect-diagnostics-next-line asyncFunction:off -- Playwright's launch is the Promise boundary; @cloudflare/playwright loads only when a Run opens a browser, so Node can import this provider.
14
+ async () => {
15
+ const { launch } = await cloudflarePlaywright();
16
+ return await launch(endpoint);
17
+ }, browserOptions, () => Effect.void);
18
+ }));
19
+ //# sourceMappingURL=browser-run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-run.js","sourceRoot":"","sources":["../src/browser-run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,SAAS,EAAE,cAAc,EAAE,EAAE,CACpE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,cAAc;IACjC,MAAM,WAAW,GAAG,KAAK,CAAC,CAAC,mBAAmB,CAAC;IAE/C,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;QAC/B,OAAO,KAAK,CAAC,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,CAAC,gBAAgB,CAC1C,WAAW,CAAC,KAAK,EACjB,aAAa,EACb,EAAE,CACH,CAAC;IAEF,OAAO,KAAK,CAAC,CAAC,kBAAkB;IAC9B,kMAAkM;IAClM,KAAK,IAAI,EAAE;QACT,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,oBAAoB,EAAE,CAAC;QAEhD,OAAO,MAAM,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC,EACD,cAAc,EACd,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAClB,CAAC;AACJ,CAAC,CAAC,CACH,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { Browser } from "@scwrap/domain";
2
+ export declare const browserUseWith: (options: {
3
+ readonly timeoutMinutes: number;
4
+ }) => import("effect/Layer").Layer<Browser<"AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW">, never, never>;
5
+ export declare const browserUse: import("effect/Layer").Layer<Browser<"AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW">, never, never>;
6
+ //# sourceMappingURL=browser-use.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-use.d.ts","sourceRoot":"","sources":["../src/browser-use.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAqC,MAAM,gBAAgB,CAAC;AAgH5E,eAAO,MAAM,cAAc,YAAa;IAAE,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;CAAE,swDAgCxE,CAAC;AAEJ,eAAO,MAAM,UAAU,mwDAAyC,CAAC"}
@@ -0,0 +1,57 @@
1
+ import { Browser, BrowserError, InstanceCredentials } from "@scwrap/domain";
2
+ import { Config, Effect, Option, Redacted, Schedule, Schema } from "effect";
3
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse, } from "effect/http";
4
+ import { cloudflarePlaywright } from "./cloudflare-playwright.js";
5
+ import { frontDeskSession } from "./front-desk.js";
6
+ import { openPlaywrightPage } from "./playwright.js";
7
+ const Session = Schema.Struct({
8
+ cdpUrl: Schema.NonEmptyString,
9
+ id: Schema.String,
10
+ });
11
+ const proxyCountry = (location) => {
12
+ if (location === undefined) {
13
+ return null;
14
+ }
15
+ return location === "GB" ? "uk" : location.toLowerCase();
16
+ };
17
+ const failed = (reason) => new BrowserError({ operation: "open", reason });
18
+ const session = Effect.fn("BrowserUse.session")(function* session(location, timeoutMinutes) {
19
+ const key = yield* Config.Redacted("BROWSER_USE_API_KEY").pipe(Effect.mapError(() => failed("Browser Use is not configured")));
20
+ const client = (yield* HttpClient.HttpClient).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl("https://api.browser-use.com/api/v4")), HttpClient.mapRequest(HttpClientRequest.setHeader("X-Browser-Use-API-Key", Redacted.value(key))), HttpClient.filterStatusOk);
21
+ const opened = yield* Effect.acquireRelease(client
22
+ .execute(HttpClientRequest.post("/browsers").pipe(HttpClientRequest.bodyJsonUnsafe({
23
+ proxyCountryCode: proxyCountry(location),
24
+ timeout: timeoutMinutes,
25
+ })))
26
+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Session)), Effect.timeout("30 seconds"), Effect.mapError(() => failed("Browser Use session creation failed"))), ({ id }) => client
27
+ .execute(HttpClientRequest.patch(`/browsers/${id}`).pipe(HttpClientRequest.bodyJsonUnsafe({ action: "stop" })))
28
+ .pipe(Effect.andThen(() => client.get(`/browsers/${id}`)), Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ status: Schema.Literal("stopped") }))), Effect.timeout("10 seconds"), Effect.retry({ schedule: Schedule.spaced("1 second"), times: 2 }), Effect.tapError(() => Effect.logError(`Browser Use session ${id} could not be stopped; its timeout remains active`)), Effect.ignore));
29
+ yield* Effect.annotateCurrentSpan({
30
+ "browserUse.location": location ?? "any",
31
+ "browserUse.session.id": opened.id,
32
+ });
33
+ return opened;
34
+ });
35
+ const webSocketOf = (url) => ({
36
+ // oxlint-disable-next-line typescript/promise-function-async -- @cloudflare/playwright calls this Fetcher-shaped object.
37
+ fetch: () =>
38
+ // @effect-diagnostics-next-line globalFetch:off -- a CDP WebSocket upgrade, handed to @cloudflare/playwright, is not an HTTP request.
39
+ fetch(url.replace(/^ws/u, "http"), { headers: { Upgrade: "websocket" } }),
40
+ });
41
+ const directSession = (location, timeoutMinutes) => session(location, timeoutMinutes).pipe(Effect.map(({ cdpUrl, id }) => ({ endpoint: webSocketOf(cdpUrl), id })), Effect.provide(FetchHttpClient.layer));
42
+ export const browserUseWith = (options) => Browser.layer((location, browserOptions) => Effect.gen(function* opened() {
43
+ const credentials = yield* InstanceCredentials;
44
+ return Option.isSome(credentials)
45
+ ? yield* frontDeskSession(credentials.value, "browser-use", {
46
+ country: location,
47
+ timeoutMinutes: options.timeoutMinutes,
48
+ })
49
+ : yield* directSession(location, options.timeoutMinutes);
50
+ }).pipe(Effect.flatMap(({ endpoint, id, }) => openPlaywrightPage(
51
+ // @effect-diagnostics-next-line asyncFunction:off -- connect is the Promise boundary; @cloudflare/playwright loads only when a Run opens a browser, so Node can import this provider.
52
+ async () => {
53
+ const { connect } = await cloudflarePlaywright();
54
+ return await connect(endpoint, id);
55
+ }, browserOptions, () => Effect.void))));
56
+ export const browserUse = browserUseWith({ timeoutMinutes: 10 });
57
+ //# sourceMappingURL=browser-use.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-use.js","sourceRoot":"","sources":["../src/browser-use.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE5E,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC5E,OAAO,EACL,eAAe,EACf,UAAU,EACV,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAIrD,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5B,MAAM,EAAE,MAAM,CAAC,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC,MAAM;CAClB,CAAC,CAAC;AAEH,MAAM,YAAY,GAAG,CAAC,QA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E,GAIH,EAAE,EAAE,CACH,kBAAkB;AAChB,sLAAsL;AACtL,KAAK,IAAI,EAAE;IACT,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,oBAAoB,EAAE,CAAC;IAEjD,OAAO,MAAM,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACrC,CAAC,EACD,cAAc,EACd,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAClB,CACJ,CACF,CACF,CAAC;AAEJ,MAAM,CAAC,MAAM,UAAU,GAAG,cAAc,CAAC,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type * as Playwright from "playwright-core";
2
+ export interface BrowserBinding {
3
+ readonly fetch: (input: string, init?: {
4
+ readonly headers?: Record<string, string>;
5
+ }) => Promise<Response>;
6
+ }
7
+ interface CloudflarePlaywright {
8
+ readonly connect: (endpoint: BrowserBinding, sessionId: string) => Promise<Playwright.Browser>;
9
+ readonly launch: (endpoint: BrowserBinding) => Promise<Playwright.Browser>;
10
+ }
11
+ export declare const cloudflarePlaywright: () => Promise<CloudflarePlaywright>;
12
+ export {};
13
+ //# sourceMappingURL=cloudflare-playwright.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-playwright.d.ts","sourceRoot":"","sources":["../src/cloudflare-playwright.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAEnD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,KAAK,EAAE,CACd,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,KACjD,OAAO,CAAC,QAAQ,CAAC,CAAC;CACxB;AAED,UAAU,oBAAoB;IAC5B,QAAQ,CAAC,OAAO,EAAE,CAChB,QAAQ,EAAE,cAAc,EACxB,SAAS,EAAE,MAAM,KACd,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;CAC5E;AAGD,eAAO,MAAM,oBAAoB,qCAGiC,CAAC"}
@@ -0,0 +1,6 @@
1
+ // @effect-diagnostics-next-line asyncFunction:off -- a dynamic import is a Promise; @cloudflare/playwright loads only when a Run opens a browser, so Node can import its providers.
2
+ export const cloudflarePlaywright = async () =>
3
+ // SAFETY: @cloudflare/playwright's index.d.ts imports './types/types' without an extension, which NodeNext cannot resolve, so its Browser types are lost; its connect and launch return Playwright's Browser.
4
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the package's own declarations do not resolve under NodeNext.
5
+ (await import("@cloudflare/playwright"));
6
+ //# sourceMappingURL=cloudflare-playwright.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-playwright.js","sourceRoot":"","sources":["../src/cloudflare-playwright.ts"],"names":[],"mappings":"AAiBA,oLAAoL;AACpL,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,IAAI,EAAE;AAC7C,8MAA8M;AAC9M,gIAAgI;AAChI,CAAC,MAAM,MAAM,CAAC,wBAAwB,CAAC,CAAyB,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { BrowserError } from "@scwrap/domain";
2
+ import type { FrontDeskBrowserProvider, InstanceCredentialsService } from "@scwrap/domain";
3
+ import { Effect } from "effect";
4
+ export declare const outsideInstance: (provider: FrontDeskBrowserProvider) => BrowserError;
5
+ export declare const frontDeskSession: (credentials: InstanceCredentialsService, provider: FrontDeskBrowserProvider, options: Parameters<InstanceCredentialsService["browserOpen"]>[1]) => Effect.Effect<{
6
+ endpoint: import("@scwrap/domain").FrontDeskBrowserSession;
7
+ id: string;
8
+ }, BrowserError, import("effect/Scope").Scope>;
9
+ //# sourceMappingURL=front-desk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"front-desk.d.ts","sourceRoot":"","sources":["../src/front-desk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAQhC,eAAO,MAAM,eAAe,aAAc,wBAAwB,iBAG/D,CAAC;AAEJ,eAAO,MAAM,gBAAgB,gBACd,0BAA0B,YAC7B,wBAAwB,WACzB,UAAU,CAAC,0BAA0B,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;;;8CAuBhE,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { BrowserError } from "@scwrap/domain";
2
+ import { Effect } from "effect";
3
+ const failed = (cause) => new BrowserError({
4
+ operation: "open",
5
+ reason: cause instanceof Error ? cause.message : String(cause),
6
+ });
7
+ export const outsideInstance = (provider) => failed(`${provider} for Workers runs only inside a Scwrap instance, whose front desk holds the browser`);
8
+ export const frontDeskSession = (credentials, provider, options) => Effect.acquireRelease(Effect.tryPromise({
9
+ catch: failed,
10
+ // oxlint-disable-next-line typescript/promise-function-async -- browserOpen is the front desk's RPC method, a Promise boundary.
11
+ try: () => credentials.browserOpen(provider, options),
12
+ }), (opened) =>
13
+ // oxlint-disable-next-line typescript/promise-function-async -- close is the front desk session's RPC method, a Promise boundary.
14
+ Effect.tryPromise(() => opened.session.close()).pipe(Effect.tapError(() => Effect.logError(`The front desk could not close a ${provider} session; its timeout remains active`)), Effect.ignore)).pipe(Effect.map(({ session, sessionId }) => ({
15
+ endpoint: session,
16
+ id: sessionId ?? "",
17
+ })));
18
+ //# sourceMappingURL=front-desk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"front-desk.js","sourceRoot":"","sources":["../src/front-desk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;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{ Context } from "effect";
3
- import type { Effect, Scope } from "effect";
4
- import type { Playwright } from "effect-playwright";
5
- export interface BrowserOptions {
6
- readonly proxyRoute?: ProxyRoute;
7
- readonly timezoneId?: string;
8
- readonly userAgent?: string;
9
- }
10
- declare const Browser_base: Context.ServiceClass<Browser, "@scwrap/browser/Browser", {
11
- readonly open: (options?: BrowserOptions) => Effect.Effect<Playwright.BrowserContext, Playwright.PlaywrightError, Scope.Scope>;
12
- }>;
13
- export declare class Browser extends Browser_base {
14
- }
15
- export { clickUntilChanged, navigate } from "./page.js";
1
+ export { playwrightBrowser } from "./playwright.js";
16
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;;mBAKkB,CACb,OAAO,CAAC,EAAE,cAAc,KACrB,MAAM,CAAC,MAAM,CAChB,UAAU,CAAC,cAAc,EACzB,UAAU,CAAC,eAAe,EAC1B,KAAK,CAAC,KAAK,CACZ;;AATL,qBAAa,OAAQ,SAAQ,YAWC;CAAG;AAEjC,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,2 @@
1
- import { Context } from "effect";
2
- export class Browser extends Context.Service()("@scwrap/browser/Browser") {
3
- }
4
- export { clickUntilChanged, navigate } from "./page.js";
1
+ export { playwrightBrowser } from "./playwright.js";
5
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAUjC,MAAM,OAAO,OAAQ,SAAQ,OAAO,CAAC,OAAO,EAWzC,CAAC,yBAAyB,CAAC;CAAG;AAEjC,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type * as Playwright from "playwright-core";
2
+ export declare const nodeBrowser: (options?: {
3
+ readonly prepare?: (context: Playwright.BrowserContext) => Promise<void>;
4
+ }) => import("effect/Layer").Layer<import("@scwrap/domain").Browser<never>, never, never>;
5
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAcnD,eAAO,MAAM,WAAW,aACb;IACP,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1E,wFAYC,CAAC"}
package/dist/node.js ADDED
@@ -0,0 +1,23 @@
1
+ // @effect-diagnostics nodeBuiltinImport:off -- The Node provider runs acceptance tests and scripts, never a Worker release.
2
+ import { existsSync } from "node:fs";
3
+ import { BrowserError } from "@scwrap/domain";
4
+ import { Effect } from "effect";
5
+ import { chromium } from "playwright";
6
+ import { playwrightBrowser } from "./playwright.js";
7
+ const executablePath = [
8
+ chromium.executablePath(),
9
+ "/usr/bin/google-chrome",
10
+ ].find(existsSync);
11
+ const launchOptions = executablePath === undefined
12
+ ? { args: ["--no-sandbox"] }
13
+ : { args: ["--no-sandbox"], executablePath };
14
+ export const nodeBrowser = (options = {}) => playwrightBrowser({
15
+ connect: chromium.launch.bind(chromium, launchOptions),
16
+ prepare: (context) => options.prepare === undefined
17
+ ? Effect.void
18
+ : Effect.tryPromise({
19
+ catch: (cause) => new BrowserError({ operation: "open", reason: String(cause) }),
20
+ try: options.prepare.bind(undefined, context),
21
+ }),
22
+ });
23
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,4HAA4H;AAC5H,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAGtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,cAAc,GAAG;IACrB,QAAQ,CAAC,cAAc,EAAE;IACzB,wBAAwB;CACzB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAEnB,MAAM,aAAa,GACjB,cAAc,KAAK,SAAS;IAC1B,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,cAAc,CAAC,EAAE;IAC5B,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,cAAc,CAAC,EAAE,cAAc,EAAE,CAAC;AAEjD,MAAM,CAAC,MAAM,WAAW,GAAG,CACzB,OAAO,GAEH,EAAE,EACN,EAAE,CACF,iBAAiB,CAAC;IAChB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,aAAa,CAAC;IACtD,OAAO,EAAE,CAAC,OAAO,EAAE,EAAE,CACnB,OAAO,CAAC,OAAO,KAAK,SAAS;QAC3B,CAAC,CAAC,MAAM,CAAC,IAAI;QACb,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;YAChB,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CACf,IAAI,YAAY,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAChE,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC;SAC9C,CAAC;CACT,CAAC,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Browser, BrowserError } from "@scwrap/domain";
2
+ import type { BrowserOptions, CountryCode, Page } from "@scwrap/domain";
3
+ import { Effect } from "effect";
4
+ import type { Scope } from "effect";
5
+ import type * as Playwright from "playwright-core";
6
+ type Code = typeof CountryCode.Type;
7
+ export declare const openPlaywrightPage: (connect: () => Promise<Playwright.Browser>, options: BrowserOptions, prepare: (context: Playwright.BrowserContext) => Effect.Effect<void, BrowserError, Scope.Scope>) => Effect.Effect<Page, BrowserError, Scope.Scope>;
8
+ export declare const playwrightBrowser: <Country extends Code = never>(options: {
9
+ readonly connect: (location: Country | undefined) => Promise<Playwright.Browser>;
10
+ readonly prepare?: (context: Playwright.BrowserContext) => Effect.Effect<void, BrowserError, Scope.Scope>;
11
+ }) => import("effect/Layer").Layer<Browser<Country>, never, never>;
12
+ export {};
13
+ //# sourceMappingURL=playwright.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"playwright.d.ts","sourceRoot":"","sources":["../src/playwright.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAY,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,KAAK,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAEnD,KAAK,IAAI,GAAG,OAAO,WAAW,CAAC,IAAI,CAAC;AA4DpC,eAAO,MAAM,kBAAkB,kBACd,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,8CAG/B,UAAU,CAAC,cAAc,KAC/B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,mDA2BnD,CAAC;AAEH,eAAO,MAAM,iBAAiB,GAAI,OAAO,SAAS,IAAI,GAAG,KAAK,WAAW;IACvE,QAAQ,CAAC,OAAO,EAAE,CAChB,QAAQ,EAAE,OAAO,GAAG,SAAS,KAC1B,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACjC,QAAQ,CAAC,OAAO,CAAC,EAAE,CACjB,OAAO,EAAE,UAAU,CAAC,cAAc,KAC/B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;CACrD,iEAOE,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { Browser, BrowserError } from "@scwrap/domain";
2
+ import { Duration, Effect } from "effect";
3
+ const failure = (operation) => (cause) => new BrowserError({
4
+ operation,
5
+ reason: cause instanceof Error ? cause.message : String(cause),
6
+ });
7
+ const pageOf = (raw) => ({
8
+ click: (selector) => Effect.tryPromise({
9
+ catch: failure("click"),
10
+ try: raw.locator(selector).click.bind(raw.locator(selector), {}),
11
+ }),
12
+ evaluate: (script, arg) => Effect.tryPromise({
13
+ catch: failure("evaluate"),
14
+ // oxlint-disable-next-line typescript/promise-function-async -- evaluate's Promise is the boundary this Effect wraps.
15
+ try: () =>
16
+ // SAFETY: Playwright serializes the script and its argument into the page and resolves with the script's awaited result.
17
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Playwright's Unboxed argument type cannot be named for a generic Arg.
18
+ raw.evaluate(script, arg),
19
+ }),
20
+ goto: (url) => Effect.tryPromise({
21
+ catch: failure("goto"),
22
+ try: raw.goto.bind(raw, url, {}),
23
+ }).pipe(Effect.map((response) => response?.status() ?? 0)),
24
+ waitFor: (predicate, arg) => Effect.tryPromise({
25
+ catch: failure("waitFor"),
26
+ try: async () => {
27
+ // SAFETY: as for evaluate, Playwright serializes the predicate and its argument into the page.
28
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Playwright's Unboxed argument type cannot be named for a generic Arg.
29
+ await raw.waitForFunction(predicate, arg);
30
+ },
31
+ }),
32
+ });
33
+ const contextOptions = (options) => {
34
+ const context = {};
35
+ if (options.timezoneId !== undefined) {
36
+ context.timezoneId = options.timezoneId;
37
+ }
38
+ if (options.userAgent !== undefined) {
39
+ context.userAgent = options.userAgent;
40
+ }
41
+ return context;
42
+ };
43
+ export const openPlaywrightPage = Effect.fnUntraced(function* openPage(connect, options, prepare) {
44
+ const browser = yield* Effect.acquireRelease(Effect.tryPromise({ catch: failure("open"), try: connect }), (opened) => Effect.tryPromise(opened.close.bind(opened, {})).pipe(Effect.ignore));
45
+ const context = yield* Effect.acquireRelease(Effect.tryPromise({
46
+ catch: failure("open"),
47
+ try: browser.newContext.bind(browser, contextOptions(options)),
48
+ }), (opened) => Effect.tryPromise(opened.close.bind(opened, {})).pipe(Effect.ignore));
49
+ yield* prepare(context);
50
+ const raw = yield* Effect.tryPromise({
51
+ catch: failure("open"),
52
+ try: context.newPage.bind(context),
53
+ });
54
+ raw.setDefaultTimeout(Duration.toMillis(options.timeout ?? "10 seconds"));
55
+ return pageOf(raw);
56
+ });
57
+ export const playwrightBrowser = (options) => Browser.layer((location, browserOptions) => openPlaywrightPage(options.connect.bind(undefined, location), browserOptions, options.prepare ?? (() => Effect.void)));
58
+ //# sourceMappingURL=playwright.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"playwright.js","sourceRoot":"","sources":["../src/playwright.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAc1C,MAAM,OAAO,GAAG,CAAC,SAAoB,EAAE,EAAE,CAAC,CAAC,KAAc,EAAE,EAAE,CAC3D,IAAI,YAAY,CAAC;IACf,SAAS;IACT,MAAM,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;CAC/D,CAAC,CAAC;AAEL,MAAM,MAAM,GAAG,CAAC,GAAoB,EAAQ,EAAE,CAAC,CAAC;IAC9C,KAAK,EAAE,CAAC,QAAQ,EAAE,EAAE,CAClB,MAAM,CAAC,UAAU,CAAC;QAChB,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC;QACvB,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;KACjE,CAAC;IACJ,QAAQ,EAAE,CAAS,MAAuB,EAAE,GAAS,EAAE,EAAE,CACvD,MAAM,CAAC,UAAU,CAAC;QAChB,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC;QAC1B,sHAAsH;QACtH,GAAG,EAAE,GAAG,EAAE;QACR,yHAAyH;QACzH,wIAAwI;QACxI,GAAG,CAAC,QAAQ,CAAoB,MAAe,EAAE,GAAY,CAAC;KACjE,CAAC;IACJ,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CACZ,MAAM,CAAC,UAAU,CAAC;QAChB,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC;QACtB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AAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CACvC,CACF,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@scwrap/browser",
3
- "version": "0.1.0",
4
- "description": "The Browser Capability for Scwrap Scrapers, on effect-playwright.",
3
+ "version": "0.3.0",
4
+ "description": "Browser providers for Scwrap's Browser Capability: Cloudflare Browser Run, Browser Use and a local Playwright for tests.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -19,24 +19,51 @@
19
19
  "types": "./dist/index.d.ts",
20
20
  "import": "./dist/index.js",
21
21
  "default": "./dist/index.js"
22
+ },
23
+ "./browser-run": {
24
+ "types": "./dist/browser-run.d.ts",
25
+ "import": "./dist/browser-run.js",
26
+ "default": "./dist/browser-run.js"
27
+ },
28
+ "./browser-use": {
29
+ "types": "./dist/browser-use.d.ts",
30
+ "import": "./dist/browser-use.js",
31
+ "default": "./dist/browser-use.js"
32
+ },
33
+ "./node": {
34
+ "types": "./dist/node.d.ts",
35
+ "import": "./dist/node.js",
36
+ "default": "./dist/node.js"
22
37
  }
23
38
  },
24
39
  "publishConfig": {
25
40
  "access": "public"
26
41
  },
27
42
  "dependencies": {
28
- "effect-playwright": "0.8.0",
29
- "@scwrap/domain": "0.1.0"
43
+ "@cloudflare/playwright": "1.4.0",
44
+ "playwright-core": "1.63.0",
45
+ "@scwrap/domain": "0.3.0"
30
46
  },
31
47
  "devDependencies": {
48
+ "@effect/vitest": "4.0.5",
49
+ "@types/node": "24.13.6",
32
50
  "effect": "4.0.5",
33
- "typescript": "7.0.2"
51
+ "playwright": "1.63.0",
52
+ "typescript": "7.0.2",
53
+ "vitest": "5.0.1"
34
54
  },
35
55
  "peerDependencies": {
36
- "effect": "4.0.5"
56
+ "effect": "4.0.5",
57
+ "playwright": "1.63.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "playwright": {
61
+ "optional": true
62
+ }
37
63
  },
38
64
  "scripts": {
39
65
  "typecheck": "tsc --noEmit -p tsconfig.json",
40
- "build": "tsc -p tsconfig.build.json"
66
+ "build": "tsc -p tsconfig.build.json",
67
+ "test": "vitest run"
41
68
  }
42
69
  }
@@ -0,0 +1,33 @@
1
+ import { Browser, InstanceCredentials } from "@scwrap/domain";
2
+ import { Effect, Option } from "effect";
3
+
4
+ import { cloudflarePlaywright } from "./cloudflare-playwright.js";
5
+ import { frontDeskSession, outsideInstance } from "./front-desk.js";
6
+ import { openPlaywrightPage } from "./playwright.js";
7
+
8
+ export const browserRun = Browser.layer((_location, browserOptions) =>
9
+ Effect.gen(function* browserRunPage() {
10
+ const credentials = yield* InstanceCredentials;
11
+
12
+ if (Option.isNone(credentials)) {
13
+ return yield* outsideInstance("browser-run");
14
+ }
15
+
16
+ const { endpoint } = yield* frontDeskSession(
17
+ credentials.value,
18
+ "browser-run",
19
+ {}
20
+ );
21
+
22
+ return yield* openPlaywrightPage(
23
+ // @effect-diagnostics-next-line asyncFunction:off -- Playwright's launch is the Promise boundary; @cloudflare/playwright loads only when a Run opens a browser, so Node can import this provider.
24
+ async () => {
25
+ const { launch } = await cloudflarePlaywright();
26
+
27
+ return await launch(endpoint);
28
+ },
29
+ browserOptions,
30
+ () => Effect.void
31
+ );
32
+ })
33
+ );
@@ -0,0 +1,147 @@
1
+ import { Browser, BrowserError, InstanceCredentials } from "@scwrap/domain";
2
+ import type { CountryCode } from "@scwrap/domain";
3
+ import { Config, Effect, Option, Redacted, Schedule, Schema } from "effect";
4
+ import {
5
+ FetchHttpClient,
6
+ HttpClient,
7
+ HttpClientRequest,
8
+ HttpClientResponse,
9
+ } from "effect/http";
10
+
11
+ import { cloudflarePlaywright } from "./cloudflare-playwright.js";
12
+ import type { BrowserBinding } from "./cloudflare-playwright.js";
13
+ import { frontDeskSession } from "./front-desk.js";
14
+ import { openPlaywrightPage } from "./playwright.js";
15
+
16
+ type Code = typeof CountryCode.Type;
17
+
18
+ const Session = Schema.Struct({
19
+ cdpUrl: Schema.NonEmptyString,
20
+ id: Schema.String,
21
+ });
22
+
23
+ const proxyCountry = (location: Code | undefined) => {
24
+ if (location === undefined) {
25
+ return null;
26
+ }
27
+
28
+ return location === "GB" ? "uk" : location.toLowerCase();
29
+ };
30
+
31
+ const failed = (reason: string) =>
32
+ new BrowserError({ operation: "open", reason });
33
+
34
+ const session = Effect.fn("BrowserUse.session")(function* session(
35
+ location: Code | undefined,
36
+ timeoutMinutes: number
37
+ ) {
38
+ const key = yield* Config.Redacted("BROWSER_USE_API_KEY").pipe(
39
+ Effect.mapError(() => failed("Browser Use is not configured"))
40
+ );
41
+
42
+ const client = (yield* HttpClient.HttpClient).pipe(
43
+ HttpClient.mapRequest(
44
+ HttpClientRequest.prependUrl("https://api.browser-use.com/api/v4")
45
+ ),
46
+ HttpClient.mapRequest(
47
+ HttpClientRequest.setHeader("X-Browser-Use-API-Key", Redacted.value(key))
48
+ ),
49
+ HttpClient.filterStatusOk
50
+ );
51
+
52
+ const opened = yield* Effect.acquireRelease(
53
+ client
54
+ .execute(
55
+ HttpClientRequest.post("/browsers").pipe(
56
+ HttpClientRequest.bodyJsonUnsafe({
57
+ proxyCountryCode: proxyCountry(location),
58
+ timeout: timeoutMinutes,
59
+ })
60
+ )
61
+ )
62
+ .pipe(
63
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(Session)),
64
+ Effect.timeout("30 seconds"),
65
+ Effect.mapError(() => failed("Browser Use session creation failed"))
66
+ ),
67
+ ({ id }) =>
68
+ client
69
+ .execute(
70
+ HttpClientRequest.patch(`/browsers/${id}`).pipe(
71
+ HttpClientRequest.bodyJsonUnsafe({ action: "stop" })
72
+ )
73
+ )
74
+ .pipe(
75
+ Effect.andThen(() => client.get(`/browsers/${id}`)),
76
+ Effect.flatMap(
77
+ HttpClientResponse.schemaBodyJson(
78
+ Schema.Struct({ status: Schema.Literal("stopped") })
79
+ )
80
+ ),
81
+ Effect.timeout("10 seconds"),
82
+ Effect.retry({ schedule: Schedule.spaced("1 second"), times: 2 }),
83
+ Effect.tapError(() =>
84
+ Effect.logError(
85
+ `Browser Use session ${id} could not be stopped; its timeout remains active`
86
+ )
87
+ ),
88
+ Effect.ignore
89
+ )
90
+ );
91
+
92
+ yield* Effect.annotateCurrentSpan({
93
+ "browserUse.location": location ?? "any",
94
+ "browserUse.session.id": opened.id,
95
+ });
96
+
97
+ return opened;
98
+ });
99
+
100
+ const webSocketOf = (url: string) => ({
101
+ // oxlint-disable-next-line typescript/promise-function-async -- @cloudflare/playwright calls this Fetcher-shaped object.
102
+ fetch: () =>
103
+ // @effect-diagnostics-next-line globalFetch:off -- a CDP WebSocket upgrade, handed to @cloudflare/playwright, is not an HTTP request.
104
+ fetch(url.replace(/^ws/u, "http"), { headers: { Upgrade: "websocket" } }),
105
+ });
106
+
107
+ const directSession = (location: Code | undefined, timeoutMinutes: number) =>
108
+ session(location, timeoutMinutes).pipe(
109
+ Effect.map(({ cdpUrl, id }) => ({ endpoint: webSocketOf(cdpUrl), id })),
110
+ Effect.provide(FetchHttpClient.layer)
111
+ );
112
+
113
+ export const browserUseWith = (options: { readonly timeoutMinutes: number }) =>
114
+ Browser.layer<Code>((location, browserOptions) =>
115
+ Effect.gen(function* opened() {
116
+ const credentials = yield* InstanceCredentials;
117
+
118
+ return Option.isSome(credentials)
119
+ ? yield* frontDeskSession(credentials.value, "browser-use", {
120
+ country: location,
121
+ timeoutMinutes: options.timeoutMinutes,
122
+ })
123
+ : yield* directSession(location, options.timeoutMinutes);
124
+ }).pipe(
125
+ Effect.flatMap(
126
+ ({
127
+ endpoint,
128
+ id,
129
+ }: {
130
+ readonly endpoint: BrowserBinding;
131
+ readonly id: string;
132
+ }) =>
133
+ openPlaywrightPage(
134
+ // @effect-diagnostics-next-line asyncFunction:off -- connect is the Promise boundary; @cloudflare/playwright loads only when a Run opens a browser, so Node can import this provider.
135
+ async () => {
136
+ const { connect } = await cloudflarePlaywright();
137
+
138
+ return await connect(endpoint, id);
139
+ },
140
+ browserOptions,
141
+ () => Effect.void
142
+ )
143
+ )
144
+ )
145
+ );
146
+
147
+ export const browserUse = browserUseWith({ timeoutMinutes: 10 });
@@ -0,0 +1,22 @@
1
+ import type * as Playwright from "playwright-core";
2
+
3
+ export interface BrowserBinding {
4
+ readonly fetch: (
5
+ input: string,
6
+ init?: { readonly headers?: Record<string, string> }
7
+ ) => Promise<Response>;
8
+ }
9
+
10
+ interface CloudflarePlaywright {
11
+ readonly connect: (
12
+ endpoint: BrowserBinding,
13
+ sessionId: string
14
+ ) => Promise<Playwright.Browser>;
15
+ readonly launch: (endpoint: BrowserBinding) => Promise<Playwright.Browser>;
16
+ }
17
+
18
+ // @effect-diagnostics-next-line asyncFunction:off -- a dynamic import is a Promise; @cloudflare/playwright loads only when a Run opens a browser, so Node can import its providers.
19
+ export const cloudflarePlaywright = async () =>
20
+ // SAFETY: @cloudflare/playwright's index.d.ts imports './types/types' without an extension, which NodeNext cannot resolve, so its Browser types are lost; its connect and launch return Playwright's Browser.
21
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the package's own declarations do not resolve under NodeNext.
22
+ (await import("@cloudflare/playwright")) as CloudflarePlaywright;
@@ -0,0 +1,45 @@
1
+ import { BrowserError } from "@scwrap/domain";
2
+ import type {
3
+ FrontDeskBrowserProvider,
4
+ InstanceCredentialsService,
5
+ } from "@scwrap/domain";
6
+ import { Effect } from "effect";
7
+
8
+ const failed = (cause: unknown) =>
9
+ new BrowserError({
10
+ operation: "open",
11
+ reason: cause instanceof Error ? cause.message : String(cause),
12
+ });
13
+
14
+ export const outsideInstance = (provider: FrontDeskBrowserProvider) =>
15
+ failed(
16
+ `${provider} for Workers runs only inside a Scwrap instance, whose front desk holds the browser`
17
+ );
18
+
19
+ export const frontDeskSession = (
20
+ credentials: InstanceCredentialsService,
21
+ provider: FrontDeskBrowserProvider,
22
+ options: Parameters<InstanceCredentialsService["browserOpen"]>[1]
23
+ ) =>
24
+ Effect.acquireRelease(
25
+ Effect.tryPromise({
26
+ catch: failed,
27
+ // oxlint-disable-next-line typescript/promise-function-async -- browserOpen is the front desk's RPC method, a Promise boundary.
28
+ try: () => credentials.browserOpen(provider, options),
29
+ }),
30
+ (opened) =>
31
+ // oxlint-disable-next-line typescript/promise-function-async -- close is the front desk session's RPC method, a Promise boundary.
32
+ Effect.tryPromise(() => opened.session.close()).pipe(
33
+ Effect.tapError(() =>
34
+ Effect.logError(
35
+ `The front desk could not close a ${provider} session; its timeout remains active`
36
+ )
37
+ ),
38
+ Effect.ignore
39
+ )
40
+ ).pipe(
41
+ Effect.map(({ session, sessionId }) => ({
42
+ endpoint: session,
43
+ id: sessionId ?? "",
44
+ }))
45
+ );
package/src/index.ts CHANGED
@@ -1,25 +1 @@
1
- import type { ProxyRoute } from "@scwrap/domain";
2
- import { Context } from "effect";
3
- import type { Effect, Scope } from "effect";
4
- import type { Playwright } from "effect-playwright";
5
-
6
- export interface BrowserOptions {
7
- readonly proxyRoute?: ProxyRoute;
8
- readonly timezoneId?: string;
9
- readonly userAgent?: string;
10
- }
11
-
12
- export class Browser extends Context.Service<
13
- Browser,
14
- {
15
- readonly open: (
16
- options?: BrowserOptions
17
- ) => Effect.Effect<
18
- Playwright.BrowserContext,
19
- Playwright.PlaywrightError,
20
- Scope.Scope
21
- >;
22
- }
23
- >()("@scwrap/browser/Browser") {}
24
-
25
- export { clickUntilChanged, navigate } from "./page.js";
1
+ export { playwrightBrowser } from "./playwright.js";
package/src/node.ts ADDED
@@ -0,0 +1,36 @@
1
+ // @effect-diagnostics nodeBuiltinImport:off -- The Node provider runs acceptance tests and scripts, never a Worker release.
2
+ import { existsSync } from "node:fs";
3
+
4
+ import { BrowserError } from "@scwrap/domain";
5
+ import { Effect } from "effect";
6
+ import { chromium } from "playwright";
7
+ import type * as Playwright from "playwright-core";
8
+
9
+ import { playwrightBrowser } from "./playwright.js";
10
+
11
+ const executablePath = [
12
+ chromium.executablePath(),
13
+ "/usr/bin/google-chrome",
14
+ ].find(existsSync);
15
+
16
+ const launchOptions =
17
+ executablePath === undefined
18
+ ? { args: ["--no-sandbox"] }
19
+ : { args: ["--no-sandbox"], executablePath };
20
+
21
+ export const nodeBrowser = (
22
+ options: {
23
+ readonly prepare?: (context: Playwright.BrowserContext) => Promise<void>;
24
+ } = {}
25
+ ) =>
26
+ playwrightBrowser({
27
+ connect: chromium.launch.bind(chromium, launchOptions),
28
+ prepare: (context) =>
29
+ options.prepare === undefined
30
+ ? Effect.void
31
+ : Effect.tryPromise({
32
+ catch: (cause) =>
33
+ new BrowserError({ operation: "open", reason: String(cause) }),
34
+ try: options.prepare.bind(undefined, context),
35
+ }),
36
+ });
@@ -0,0 +1,116 @@
1
+ import { Browser, BrowserError } from "@scwrap/domain";
2
+ import type { BrowserOptions, CountryCode, Page } from "@scwrap/domain";
3
+ import { Duration, Effect } from "effect";
4
+ import type { Scope } from "effect";
5
+ // @effect-diagnostics asyncFunction:off -- This module is the boundary that wraps Playwright's Promise API in Effect.
6
+ import type * as Playwright from "playwright-core";
7
+
8
+ type Code = typeof CountryCode.Type;
9
+
10
+ type Operation = (typeof BrowserError.fields.operation)["Type"];
11
+
12
+ interface ContextOptions {
13
+ timezoneId?: string;
14
+ userAgent?: string;
15
+ }
16
+
17
+ const failure = (operation: Operation) => (cause: unknown) =>
18
+ new BrowserError({
19
+ operation,
20
+ reason: cause instanceof Error ? cause.message : String(cause),
21
+ });
22
+
23
+ const pageOf = (raw: Playwright.Page): Page => ({
24
+ click: (selector) =>
25
+ Effect.tryPromise({
26
+ catch: failure("click"),
27
+ try: raw.locator(selector).click.bind(raw.locator(selector), {}),
28
+ }),
29
+ evaluate: <A, Arg>(script: (arg: Arg) => A, arg?: Arg) =>
30
+ Effect.tryPromise({
31
+ catch: failure("evaluate"),
32
+ // oxlint-disable-next-line typescript/promise-function-async -- evaluate's Promise is the boundary this Effect wraps.
33
+ try: () =>
34
+ // SAFETY: Playwright serializes the script and its argument into the page and resolves with the script's awaited result.
35
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Playwright's Unboxed argument type cannot be named for a generic Arg.
36
+ raw.evaluate<Awaited<A>, never>(script as never, arg as never),
37
+ }),
38
+ goto: (url) =>
39
+ Effect.tryPromise({
40
+ catch: failure("goto"),
41
+ try: raw.goto.bind(raw, url, {}),
42
+ }).pipe(Effect.map((response) => response?.status() ?? 0)),
43
+ waitFor: (predicate, arg) =>
44
+ Effect.tryPromise({
45
+ catch: failure("waitFor"),
46
+ try: async () => {
47
+ // SAFETY: as for evaluate, Playwright serializes the predicate and its argument into the page.
48
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Playwright's Unboxed argument type cannot be named for a generic Arg.
49
+ await raw.waitForFunction(predicate as never, arg as never);
50
+ },
51
+ }),
52
+ });
53
+
54
+ const contextOptions = (options: BrowserOptions) => {
55
+ const context: ContextOptions = {};
56
+
57
+ if (options.timezoneId !== undefined) {
58
+ context.timezoneId = options.timezoneId;
59
+ }
60
+
61
+ if (options.userAgent !== undefined) {
62
+ context.userAgent = options.userAgent;
63
+ }
64
+
65
+ return context;
66
+ };
67
+
68
+ export const openPlaywrightPage = Effect.fnUntraced(function* openPage(
69
+ connect: () => Promise<Playwright.Browser>,
70
+ options: BrowserOptions,
71
+ prepare: (
72
+ context: Playwright.BrowserContext
73
+ ) => Effect.Effect<void, BrowserError, Scope.Scope>
74
+ ) {
75
+ const browser = yield* Effect.acquireRelease(
76
+ Effect.tryPromise({ catch: failure("open"), try: connect }),
77
+ (opened) =>
78
+ Effect.tryPromise(opened.close.bind(opened, {})).pipe(Effect.ignore)
79
+ );
80
+
81
+ const context = yield* Effect.acquireRelease(
82
+ Effect.tryPromise({
83
+ catch: failure("open"),
84
+ try: browser.newContext.bind(browser, contextOptions(options)),
85
+ }),
86
+ (opened) =>
87
+ Effect.tryPromise(opened.close.bind(opened, {})).pipe(Effect.ignore)
88
+ );
89
+
90
+ yield* prepare(context);
91
+
92
+ const raw = yield* Effect.tryPromise({
93
+ catch: failure("open"),
94
+ try: context.newPage.bind(context),
95
+ });
96
+
97
+ raw.setDefaultTimeout(Duration.toMillis(options.timeout ?? "10 seconds"));
98
+
99
+ return pageOf(raw);
100
+ });
101
+
102
+ export const playwrightBrowser = <Country extends Code = never>(options: {
103
+ readonly connect: (
104
+ location: Country | undefined
105
+ ) => Promise<Playwright.Browser>;
106
+ readonly prepare?: (
107
+ context: Playwright.BrowserContext
108
+ ) => Effect.Effect<void, BrowserError, Scope.Scope>;
109
+ }) =>
110
+ Browser.layer<Country>((location, browserOptions) =>
111
+ openPlaywrightPage(
112
+ options.connect.bind(undefined, location),
113
+ browserOptions,
114
+ options.prepare ?? (() => Effect.void)
115
+ )
116
+ );
package/dist/page.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import { Effect } from "effect";
2
- import type { Playwright } from "effect-playwright";
3
- export declare const navigate: (page: Playwright.Page, url: string, source: string) => Effect.Effect<number, import("@scwrap/domain").Blocked | Playwright.PlaywrightError | import("@scwrap/domain").RateLimited | import("@scwrap/domain").UpstreamDown, never>;
4
- export declare const clickUntilChanged: <E>(page: Playwright.Page, selector: string, signature: () => string, onStall: () => E) => Effect.Effect<void, E | Playwright.PlaywrightError, never>;
5
- //# sourceMappingURL=page.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"page.d.ts","sourceRoot":"","sources":["../src/page.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,eAAO,MAAM,QAAQ,oOAiBnB,CAAC;AAEH,eAAO,MAAM,iBAAiB,GACA,CAAC,4DAGV,MAAM,iBACR,CAAC,+DAgBnB,CAAC"}
package/dist/page.js DELETED
@@ -1,22 +0,0 @@
1
- import { httpStatusFailure } from "@scwrap/domain";
2
- import { Effect } from "effect";
3
- export const navigate = Effect.fn("Browser.navigate")(function* navigate(page, url, source) {
4
- const response = yield* page.use(
5
- // oxlint-disable-next-line typescript/promise-function-async -- effect-playwright's goto drops the response; its status decides the failure.
6
- (raw) => raw.goto(url, { timeout: 30_000 }));
7
- const status = response?.status() ?? 0;
8
- if (status >= 200 && status < 300) {
9
- return status;
10
- }
11
- return yield* httpStatusFailure(status, `${source} answered ${status}`);
12
- });
13
- export const clickUntilChanged = Effect.fn("Browser.clickUntilChanged")(function* clickUntilChanged(page, selector, signature, onStall) {
14
- const before = yield* page.evaluate(signature);
15
- yield* page.locator(selector).click();
16
- yield* page
17
- .use(
18
- // oxlint-disable-next-line typescript/promise-function-async -- effect-playwright's waitForFunction takes a function; the caller's signature is composed into one page expression with the signature read before the click.
19
- (raw) => raw.waitForFunction(`(${String(signature)})() !== ${JSON.stringify(before)}`))
20
- .pipe(Effect.mapError(onStall));
21
- });
22
- //# sourceMappingURL=page.js.map
package/dist/page.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"page.js","sourceRoot":"","sources":["../src/page.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,EAAE,CAAC,kBAAkB,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CACtE,IAAqB,EACrB,GAAW,EACX,MAAc;IAEd,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG;IAC9B,6IAA6I;IAC7I,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAC5C,CAAC;IAEF,MAAM,MAAM,GAAG,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAEvC,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC;QAClC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,OAAO,KAAK,CAAC,CAAC,iBAAiB,CAAC,MAAM,EAAE,GAAG,MAAM,aAAa,MAAM,EAAE,CAAC,CAAC;AAC1E,CAAC,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,EAAE,CAAC,2BAA2B,CAAC,CACrE,QAAQ,CAAC,CAAC,iBAAiB,CACzB,IAAqB,EACrB,QAAgB,EAChB,SAAuB,EACvB,OAAgB;IAEhB,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAE/C,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,CAAC;IAEtC,KAAK,CAAC,CAAC,IAAI;SACR,GAAG;IACF,4NAA4N;IAC5N,CAAC,GAAG,EAAE,EAAE,CACN,GAAG,CAAC,eAAe,CACjB,IAAI,MAAM,CAAC,SAAS,CAAC,WAAW,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CACzD,CACJ;SACA,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;AACpC,CAAC,CACF,CAAC"}
package/src/page.ts DELETED
@@ -1,45 +0,0 @@
1
- import { httpStatusFailure } from "@scwrap/domain";
2
- import { Effect } from "effect";
3
- import type { Playwright } from "effect-playwright";
4
-
5
- export const navigate = Effect.fn("Browser.navigate")(function* navigate(
6
- page: Playwright.Page,
7
- url: string,
8
- source: string
9
- ) {
10
- const response = yield* page.use(
11
- // oxlint-disable-next-line typescript/promise-function-async -- effect-playwright's goto drops the response; its status decides the failure.
12
- (raw) => raw.goto(url, { timeout: 30_000 })
13
- );
14
-
15
- const status = response?.status() ?? 0;
16
-
17
- if (status >= 200 && status < 300) {
18
- return status;
19
- }
20
-
21
- return yield* httpStatusFailure(status, `${source} answered ${status}`);
22
- });
23
-
24
- export const clickUntilChanged = Effect.fn("Browser.clickUntilChanged")(
25
- function* clickUntilChanged<E>(
26
- page: Playwright.Page,
27
- selector: string,
28
- signature: () => string,
29
- onStall: () => E
30
- ) {
31
- const before = yield* page.evaluate(signature);
32
-
33
- yield* page.locator(selector).click();
34
-
35
- yield* page
36
- .use(
37
- // oxlint-disable-next-line typescript/promise-function-async -- effect-playwright's waitForFunction takes a function; the caller's signature is composed into one page expression with the signature read before the click.
38
- (raw) =>
39
- raw.waitForFunction(
40
- `(${String(signature)})() !== ${JSON.stringify(before)}`
41
- )
42
- )
43
- .pipe(Effect.mapError(onStall));
44
- }
45
- );