The best way to control Claude Code, Codex and more from any computer or phone

main
ts 175 lines 7.43 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Data from "effect/Data";
4 import type * as Effect from "effect/Effect";
5 import type * as Stream from "effect/Stream";
6 import * as Binding from "./Binding.ts";
7 import type { BrowserBinding } from "./BrowserBinding.ts";
8
9 const TypeId = "Cloudflare.Browser" as const;
10 type TypeId = typeof TypeId;
11
12 export class BrowserError extends Data.TaggedError("BrowserError")<{
13 message: string;
14 cause: unknown;
15 }> {}
16
17 /** The `Response` type returned by the Cloudflare Browser Rendering binding. */
18 export type BrowserResponse = Awaited<ReturnType<cf.BrowserRun["fetch"]>>;
19
20 /** An Effect produced by a {@link BrowserClient} operation. */
21 type BrowserEffect<A> = Effect.Effect<A, BrowserError, RuntimeContext>;
22
23 /** A byte stream produced by a binary {@link BrowserClient} action. */
24 type BrowserByteStream = Stream.Stream<Uint8Array, BrowserError, RuntimeContext>;
25
26 // Quick action option types, re-exported so callers don't reach into the
27 // `@cloudflare/workers-types` namespace directly.
28 export type BrowserScreenshotOptions = cf.BrowserRunScreenshotOptions;
29 export type BrowserPDFOptions = cf.BrowserRunPDFOptions;
30 export type BrowserContentOptions = cf.BrowserRunContentOptions;
31 export type BrowserScrapeOptions = cf.BrowserRunScrapeOptions;
32 export type BrowserLinksOptions = cf.BrowserRunLinksOptions;
33 export type BrowserSnapshotOptions = cf.BrowserRunSnapshotOptions;
34 export type BrowserJsonOptions = cf.BrowserRunJsonOptions;
35 export type BrowserMarkdownOptions = cf.BrowserRunMarkdownOptions;
36
37 // Quick action success payloads.
38 export type BrowserContentResult = cf.BrowserRunContentSuccessResponse;
39 export type BrowserScrapeResult = cf.BrowserRunScrapeSuccessResponse;
40 export type BrowserLinksResult = cf.BrowserRunLinksSuccessResponse;
41 export type BrowserSnapshotResult = cf.BrowserRunSnapshotSuccessResponse;
42 export type BrowserJsonResult = cf.BrowserRunJsonSuccessResponse;
43 export type BrowserMarkdownResult = cf.BrowserRunMarkdownSuccessResponse;
44 export type BrowserErrorResponse = cf.BrowserRunErrorResponse;
45
46 /**
47 * Effect-native client for a Cloudflare Browser Rendering binding.
48 *
49 * Mirrors the runtime {@link cf.BrowserRun} binding, translating its shapes into
50 * Effect-native ones: JSON quick actions resolve to their parsed success
51 * payload, and binary actions (`screenshot`, `pdf`) resolve to a `Stream` of the
52 * response bytes. Non-success responses fail with {@link BrowserError}. The
53 * {@link raw} accessor and {@link fetch} are the promise-shaped escape hatches
54 * for libraries like `@cloudflare/puppeteer`.
55 */
56 export interface BrowserClient {
57 /** Effect resolving to the raw Cloudflare Browser Rendering runtime binding. */
58 raw: Effect.Effect<cf.BrowserRun, never, RuntimeContext>;
59 /** Send a raw HTTP request to the Browser Run API. */
60 fetch(...args: Parameters<cf.BrowserRun["fetch"]>): BrowserEffect<BrowserResponse>;
61 /** Run a Browser Run quick action, resolving to the parsed payload. */
62 quickAction(action: "screenshot", options: BrowserScreenshotOptions): BrowserByteStream;
63 quickAction(action: "pdf", options: BrowserPDFOptions): BrowserByteStream;
64 quickAction(
65 action: "content",
66 options: BrowserContentOptions,
67 ): BrowserEffect<BrowserContentResult>;
68 quickAction(action: "scrape", options: BrowserScrapeOptions): BrowserEffect<BrowserScrapeResult>;
69 quickAction(action: "links", options: BrowserLinksOptions): BrowserEffect<BrowserLinksResult>;
70 quickAction(
71 action: "snapshot",
72 options: BrowserSnapshotOptions,
73 ): BrowserEffect<BrowserSnapshotResult>;
74 quickAction(action: "json", options: BrowserJsonOptions): BrowserEffect<BrowserJsonResult>;
75 quickAction(
76 action: "markdown",
77 options: BrowserMarkdownOptions,
78 ): BrowserEffect<BrowserMarkdownResult>;
79 /** Take a screenshot of a web page, streaming the raw image bytes. */
80 screenshot(options: BrowserScreenshotOptions): BrowserByteStream;
81 /** Generate a PDF of a web page, streaming the raw PDF bytes. */
82 pdf(options: BrowserPDFOptions): BrowserByteStream;
83 /** Get the HTML content of a web page. */
84 content(options: BrowserContentOptions): BrowserEffect<BrowserContentResult>;
85 /** Scrape elements from a web page by CSS selector. */
86 scrape(options: BrowserScrapeOptions): BrowserEffect<BrowserScrapeResult>;
87 /** Extract all links from a web page. */
88 links(options: BrowserLinksOptions): BrowserEffect<BrowserLinksResult>;
89 /** Get both the HTML content and a base64-encoded screenshot of a web page. */
90 snapshot(options: BrowserSnapshotOptions): BrowserEffect<BrowserSnapshotResult>;
91 /** Extract structured JSON data from a web page using AI. */
92 json(options: BrowserJsonOptions): BrowserEffect<BrowserJsonResult>;
93 /** Convert a web page to Markdown. */
94 markdown(options: BrowserMarkdownOptions): BrowserEffect<BrowserMarkdownResult>;
95 }
96
97 /**
98 * A Cloudflare Browser Rendering binding for launching headless browser sessions
99 * from Workers — a Worker-only binding with no backing cloud resource.
100 *
101 * `Browser` is a single value that is at once the `Binding.Service` tag, the
102 * callable that produces a {@link BrowserBinding}, and the type. Declare it on a
103 * Worker's `env` (it flows through `InferEnv` → `cf.BrowserRun`) or `yield*` it
104 * inside an Effect-native Worker to attach the binding and obtain the
105 * {@link BrowserClient}.
106 *
107 * ### Effect-style Worker (recommended)
108 * **Example:** Bind the runtime client and convert a page to Markdown
109 * ```typescript
110 * import * as Effect from "effect/Effect";
111 *
112 * Cloudflare.Worker(
113 * "BrowserWorker",
114 * { main: import.meta.url },
115 * Effect.gen(function* () {
116 * const browser = yield* Cloudflare.Browser("BROWSER");
117 *
118 * return {
119 * fetch: Effect.gen(function* () {
120 * return yield* browser.markdown({ url: "https://example.com" });
121 * }),
122 * };
123 * }).pipe(Effect.provide(Cloudflare.Workers.BrowserBinding)),
124 * );
125 * ```
126 *
127 * ### Worker binding metadata
128 * **Example:** Declare the binding on `env`
129 * ```typescript
130 * export const Worker = Cloudflare.Worker("Worker", {
131 * main: "./src/worker.ts",
132 * env: { BROWSER: Cloudflare.Browser() },
133 * });
134 *
135 * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
136 * // { BROWSER: BrowserRun }
137 * ```
138 *
139 * ### Local development
140 * **Example:** Proxy to the real Browser Rendering service in dev
141 * ```typescript
142 * // Default: a real headless Chrome is launched locally and driven over
143 * // CDP under `alchemy dev`. Alchemy.remote() opts the binding into the
144 * // real Browser Rendering service instead — in an Effect-native Worker:
145 * const browser = yield* Cloudflare.Browser("BROWSER").pipe(Alchemy.remote());
146 *
147 * // or declared on an async Worker's env:
148 * env: { BROWSER: Cloudflare.Browser("BROWSER").pipe(Alchemy.remote()) }
149 * ```
150 *
151 * @see https://developers.cloudflare.com/browser-rendering/workers-binding-api/
152 *
153 * @binding
154 * @product Browser Rendering
155 * @category Developer Platform
156 */
157 export interface Browser extends Binding.Service<Browser, TypeId, BrowserClient> {
158 /**
159 * @param name Binding name (logical id) — the `env` key it resolves to.
160 * @default "BROWSER"
161 */
162 (name?: string): BrowserBinding;
163 }
164
165 export const Browser = Binding.Service<Browser>({
166 id: TypeId,
167 defaultName: "BROWSER",
168 toWorkerBinding: (binding) => ({
169 type: "browser",
170 name: binding.name,
171 }),
172 });
173
174 export const isBrowser = (value: unknown): value is BrowserBinding =>
175 Binding.isBinding(value) && value.kind === TypeId;