@guren/plugin-cloudflare 0.12.3 → 0.13.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.
@@ -0,0 +1,117 @@
1
+ //#region src/worker-manifest.d.ts
2
+ declare const WORKER_MANIFEST_VERSION = 2;
3
+ /** One binding's resource identity, settled by a deploy and carried over by every build. */
4
+ interface ResolvedResource {
5
+ id?: string;
6
+ name?: string;
7
+ }
8
+ interface WorkerManifest {
9
+ version: typeof WORKER_MANIFEST_VERSION;
10
+ /** Paths are relative to the app root, POSIX, each starting with `./`. */
11
+ entrypoint: string;
12
+ assetsDirectory: string;
13
+ compatibilityFlags: string[];
14
+ htmlHandling: 'none';
15
+ alias: Record<string, string>;
16
+ define: Record<string, string>;
17
+ /** Plain-text bindings; `define` cannot reach a runtime `process.env[key]` read. */
18
+ vars: Record<string, string>;
19
+ d1: {
20
+ binding: string;
21
+ databaseName: string;
22
+ };
23
+ /** KV namespace bindings the build owns (`OAUTH_KV` under `--mcp-oauth`). */
24
+ kvNamespaces: string[];
25
+ /** Cron schedules for a `scheduled` trigger; empty when the worker schedules nothing. */
26
+ crons: string[];
27
+ /** `config/cloudflare.ts` names by binding, which the plan resolves and creates under. */
28
+ resourceNames: Record<string, string>;
29
+ /** Why the schedule kernel could not be read; the plan blocks unless the config sets its own triggers. */
30
+ scheduleUnreadable?: string;
31
+ /** Agent classes hosted as SQLite-backed Durable Objects, with the binding each gets. */
32
+ agents: Array<{
33
+ exportName: string;
34
+ binding: string;
35
+ }>;
36
+ /** R2 bucket bindings the introspected app's disks name (RFC 0035 §2); absent from a manifest older than that. */
37
+ r2Buckets?: string[];
38
+ /** Keyed by binding name. The build never writes an entry, only carries them over. */
39
+ resolved: Record<string, ResolvedResource>;
40
+ }
41
+ //#endregion
42
+ //#region src/config.d.ts
43
+ /**
44
+ * Guren's deploy settings, read by `cloudflare:build` and `cloudflare:deploy` and never by
45
+ * the running app (RFC 0035 §3). Default-exported from `config/cloudflare.ts`.
46
+ */
47
+ interface CloudflareDeployConfig {
48
+ /** Front the App MCP endpoint with the OAuth provider, which binds `OAUTH_KV`. Replaces `--mcp-oauth`. */
49
+ mcpOAuth?: boolean;
50
+ /** Where the App MCP endpoint is mounted, as `mcpPlugin({ path })` has it. Defaults to `/mcp`. */
51
+ mcpPath?: string;
52
+ /** Resource names by binding (`DB`, `OAUTH_KV`), for one the default name does not fit or collides with. */
53
+ resourceNames?: Record<string, string>;
54
+ }
55
+ declare function defineCloudflareConfig(config: CloudflareDeployConfig): CloudflareDeployConfig;
56
+ interface GurenWorkerOptions {
57
+ /** The Worker's name, the same one `cf deploy` deploys under. */
58
+ name: string;
59
+ /** The `cloudflare:build` output directory, relative to the app root. Defaults to `.guren/cloudflare`. */
60
+ outputDir?: string;
61
+ }
62
+ /** The bindings and exports below are the plain objects `bindings.*()` and `exports.*()` from `cf/config` return. */
63
+ type GurenBinding = {
64
+ type: 'd1';
65
+ name?: string;
66
+ id?: string;
67
+ } | {
68
+ type: 'kv';
69
+ id?: string;
70
+ } | {
71
+ type: 'r2';
72
+ name?: string;
73
+ } | {
74
+ type: 'durable-object';
75
+ worker: string;
76
+ exportName: string;
77
+ } | {
78
+ type: 'text';
79
+ value: string;
80
+ };
81
+ interface GurenWorker {
82
+ name: string;
83
+ entrypoint: string;
84
+ compatibilityFlags: string[];
85
+ assets: {
86
+ htmlHandling: WorkerManifest['htmlHandling'];
87
+ };
88
+ env: Record<string, GurenBinding>;
89
+ exports: Record<string, {
90
+ type: 'durable-object';
91
+ storage: 'sqlite';
92
+ }>;
93
+ /** Absent when nothing is scheduled; a `triggers` key after the spread replaces it. */
94
+ triggers?: Array<{
95
+ type: 'scheduled';
96
+ schedule: string;
97
+ }>;
98
+ }
99
+ interface GurenWranglerBundle {
100
+ keepNames: true;
101
+ alias: Record<string, string>;
102
+ define: Record<string, string>;
103
+ assetsDirectory: string;
104
+ }
105
+ /**
106
+ * The Worker as `cloudflare:build` assembled it, to spread into `defineConfig({ worker })`.
107
+ * `compatibilityDate` is left to the config file: a date that moved with each
108
+ * build would change the runtime's behaviour on every deploy.
109
+ */
110
+ declare function gurenWorker(options: GurenWorkerOptions): Promise<GurenWorker>;
111
+ /**
112
+ * The bundler options for `defineWranglerConfig()`. `keepNames` is pinned on:
113
+ * queued jobs, events, notifications and durable agents are stored by class name.
114
+ */
115
+ declare function gurenWranglerBundle(options?: Pick<GurenWorkerOptions, 'outputDir'>): Promise<GurenWranglerBundle>;
116
+ //#endregion
117
+ export { CloudflareDeployConfig, GurenBinding, GurenWorker, GurenWorkerOptions, GurenWranglerBundle, defineCloudflareConfig, gurenWorker, gurenWranglerBundle };
package/dist/config.js ADDED
@@ -0,0 +1,102 @@
1
+ import { r as WORKER_MANIFEST_FILE, s as resourceName, t as CF_OUTPUT_DIR } from "./worker-manifest-16SJawlX.js";
2
+ import { resolve } from "node:path";
3
+ import { readFile } from "node:fs/promises";
4
+ //#region src/config.ts
5
+ /**
6
+ * `@guren/plugin-cloudflare/config`: Guren's part of `cloudflare.config.ts` and
7
+ * `wrangler.config.ts` for the `cf` CLI (RFC 0035 §3). `cf` evaluates those files
8
+ * under Node, in another process from the Bun build that knows the app, so this
9
+ * module computes nothing about the app: it reads the manifest `cloudflare:build`
10
+ * wrote, and imports only Node builtins and the manifest's types.
11
+ */
12
+ function defineCloudflareConfig(config) {
13
+ return config;
14
+ }
15
+ /**
16
+ * The Worker as `cloudflare:build` assembled it, to spread into `defineConfig({ worker })`.
17
+ * `compatibilityDate` is left to the config file: a date that moved with each
18
+ * build would change the runtime's behaviour on every deploy.
19
+ */
20
+ async function gurenWorker(options) {
21
+ const manifest = await readWorkerManifest(options.outputDir);
22
+ const resolved = manifest.resolved;
23
+ const env = {};
24
+ const d1 = resolved[manifest.d1.binding];
25
+ env[manifest.d1.binding] = {
26
+ type: "d1",
27
+ name: d1?.name ?? manifest.d1.databaseName,
28
+ ...d1?.id ? { id: d1.id } : {}
29
+ };
30
+ for (const binding of manifest.kvNamespaces) {
31
+ const id = resolved[binding]?.id;
32
+ env[binding] = {
33
+ type: "kv",
34
+ ...id ? { id } : {}
35
+ };
36
+ }
37
+ for (const binding of manifest.r2Buckets ?? []) env[binding] = {
38
+ type: "r2",
39
+ name: resourceName(options.name, binding, manifest.resourceNames, resolved[binding]?.name)
40
+ };
41
+ for (const [key, value] of Object.entries(manifest.vars)) env[key] = {
42
+ type: "text",
43
+ value
44
+ };
45
+ const exports = {};
46
+ for (const agent of manifest.agents) {
47
+ env[agent.binding] = {
48
+ type: "durable-object",
49
+ worker: options.name,
50
+ exportName: agent.exportName
51
+ };
52
+ exports[agent.exportName] = {
53
+ type: "durable-object",
54
+ storage: "sqlite"
55
+ };
56
+ }
57
+ return {
58
+ name: options.name,
59
+ entrypoint: manifest.entrypoint,
60
+ compatibilityFlags: manifest.compatibilityFlags,
61
+ assets: { htmlHandling: manifest.htmlHandling },
62
+ env,
63
+ exports,
64
+ ...manifest.crons.length > 0 ? { triggers: manifest.crons.map((schedule) => ({
65
+ type: "scheduled",
66
+ schedule
67
+ })) } : {}
68
+ };
69
+ }
70
+ /**
71
+ * The bundler options for `defineWranglerConfig()`. `keepNames` is pinned on:
72
+ * queued jobs, events, notifications and durable agents are stored by class name.
73
+ */
74
+ async function gurenWranglerBundle(options = {}) {
75
+ const manifest = await readWorkerManifest(options.outputDir);
76
+ return {
77
+ keepNames: true,
78
+ alias: manifest.alias,
79
+ define: manifest.define,
80
+ assetsDirectory: manifest.assetsDirectory
81
+ };
82
+ }
83
+ /** `cf` runs from the app root (it refuses a directory without the project's manifest), so paths resolve from the cwd. */
84
+ async function readWorkerManifest(outputDir = CF_OUTPUT_DIR) {
85
+ const path = resolve(process.cwd(), outputDir, WORKER_MANIFEST_FILE);
86
+ let text;
87
+ try {
88
+ text = await readFile(path, "utf8");
89
+ } catch {
90
+ throw new Error(`@guren/plugin-cloudflare/config: ${path} not found. Run \`bunx guren cloudflare:build\` first (\`bunx guren cloudflare:deploy\` runs it for you); it writes this manifest. A build given another outputDir needs the same outputDir here.`);
91
+ }
92
+ let manifest;
93
+ try {
94
+ manifest = JSON.parse(text);
95
+ } catch {
96
+ manifest = null;
97
+ }
98
+ if (manifest?.version !== 2) throw new Error(`@guren/plugin-cloudflare/config: ${path} is not a version 2 manifest (it reads ${manifest === null ? "as no JSON object" : `version ${String(manifest.version)}`}). Run \`bunx guren cloudflare:build\` again with the installed plugin.`);
99
+ return manifest;
100
+ }
101
+ //#endregion
102
+ export { defineCloudflareConfig, gurenWorker, gurenWranglerBundle };
package/dist/env.d.ts CHANGED
@@ -9,6 +9,12 @@
9
9
  * bundle. The root keeps re-exporting them for compatibility;
10
10
  * `tests/lean-env-subpath.test.ts` holds the boundary.
11
11
  */
12
+ /**
13
+ * Where the captured env lives: a registry symbol on `globalThis`, so `@guren/orm`
14
+ * resolves `createD1Database({ binding: 'DB' })` without importing this package, and two
15
+ * installed copies of it share one env. `@guren/orm`'s d1.ts spells the same key.
16
+ */
17
+ declare const WORKERS_ENV_SLOT: unique symbol;
12
18
  /**
13
19
  * First call wins; later calls are ignored (never overwrite a live env). Not the
14
20
  * hard error RFC 0017 §6 asks for: under the Workers Vitest integration a Worker
@@ -23,13 +29,19 @@ declare function captureWorkersEnv(env: unknown): void;
23
29
  * entrypoint booted first, which may be the Worker's rather than the object's.
24
30
  */
25
31
  declare function getWorkersEnv<E = unknown>(): E;
32
+ /**
33
+ * The binding a driver was given by name, read when it is first used. `owner` prefixes the
34
+ * errors; `@guren/orm`'s `createD1Database` words its own the same way.
35
+ */
36
+ declare function readWorkersBinding(name: string, owner: string): unknown;
26
37
  /** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
27
38
  declare function resetWorkersEnv(): void;
28
39
  /**
29
- * Whether this code is running on workerd, which identifies itself through the
30
- * standard navigator user agent. The switch an app's `config/database.ts` needs
31
- * to pick D1 over a local driver, and to keep filesystem work out of the Worker.
40
+ * Whether this code runs on workerd (its navigator user agent): the switch an app's
41
+ * `config/database.ts` takes to pick D1 and keep filesystem work out of the Worker.
42
+ * Also true in the Cloudflare build's introspection (RFC 0035 §2.1); both variables
43
+ * are required, so an exported target alone never changes `bun run dev`.
32
44
  */
33
45
  declare function isWorkersRuntime(): boolean;
34
46
  //#endregion
35
- export { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
47
+ export { WORKERS_ENV_SLOT, captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv };
package/dist/env.js CHANGED
@@ -9,7 +9,13 @@
9
9
  * bundle. The root keeps re-exporting them for compatibility;
10
10
  * `tests/lean-env-subpath.test.ts` holds the boundary.
11
11
  */
12
- let holder;
12
+ /**
13
+ * Where the captured env lives: a registry symbol on `globalThis`, so `@guren/orm`
14
+ * resolves `createD1Database({ binding: 'DB' })` without importing this package, and two
15
+ * installed copies of it share one env. `@guren/orm`'s d1.ts spells the same key.
16
+ */
17
+ const WORKERS_ENV_SLOT = Symbol.for("guren.workersEnv");
18
+ const slots = globalThis;
13
19
  /**
14
20
  * First call wins; later calls are ignored (never overwrite a live env). Not the
15
21
  * hard error RFC 0017 §6 asks for: under the Workers Vitest integration a Worker
@@ -18,7 +24,7 @@ let holder;
18
24
  * latch in `boot.ts` is what keeps one isolate on one application.
19
25
  */
20
26
  function captureWorkersEnv(env) {
21
- holder ??= { env };
27
+ slots[WORKERS_ENV_SLOT] ??= { env };
22
28
  }
23
29
  /**
24
30
  * Throws with a clear message if called before the first request captured env.
@@ -26,20 +32,34 @@ function captureWorkersEnv(env) {
26
32
  * entrypoint booted first, which may be the Worker's rather than the object's.
27
33
  */
28
34
  function getWorkersEnv() {
35
+ const holder = slots[WORKERS_ENV_SLOT];
29
36
  if (!holder) throw new Error("getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB");
30
37
  return holder.env;
31
38
  }
39
+ /**
40
+ * The binding a driver was given by name, read when it is first used. `owner` prefixes the
41
+ * errors; `@guren/orm`'s `createD1Database` words its own the same way.
42
+ */
43
+ function readWorkersBinding(name, owner) {
44
+ const holder = slots[WORKERS_ENV_SLOT];
45
+ if (!holder) throw new Error(`${owner}: the "${name}" binding was read before the first request captured the Workers env. Use it inside a request.`);
46
+ const value = holder.env?.[name];
47
+ if (value == null) throw new Error(`${owner}: the Workers env has no "${name}" binding. Check wrangler.jsonc, or the binding in cloudflare.config.ts.`);
48
+ return value;
49
+ }
32
50
  /** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
33
51
  function resetWorkersEnv() {
34
- holder = void 0;
52
+ slots[WORKERS_ENV_SLOT] = void 0;
35
53
  }
36
54
  /**
37
- * Whether this code is running on workerd, which identifies itself through the
38
- * standard navigator user agent. The switch an app's `config/database.ts` needs
39
- * to pick D1 over a local driver, and to keep filesystem work out of the Worker.
55
+ * Whether this code runs on workerd (its navigator user agent): the switch an app's
56
+ * `config/database.ts` takes to pick D1 and keep filesystem work out of the Worker.
57
+ * Also true in the Cloudflare build's introspection (RFC 0035 §2.1); both variables
58
+ * are required, so an exported target alone never changes `bun run dev`.
40
59
  */
41
60
  function isWorkersRuntime() {
42
- return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
61
+ if (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return true;
62
+ return typeof process !== "undefined" && process.env?.GUREN_INTROSPECT === "1" && process.env?.GUREN_INTROSPECT_TARGET === "cloudflare";
43
63
  }
44
64
  //#endregion
45
- export { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv };
65
+ export { WORKERS_ENV_SLOT, captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
2
2
  import { FileMetadata, GetStreamOptions, PutOptions, ServiceProviderConstructor, StorageDriver, StorageDriverCapabilities, TemporaryUrlOptions } from "@guren/core";
3
3
  import { PathLike } from "@guren/core/internal/deploy-build";
4
+ import "@guren/core/internal/deploy-check";
4
5
  //#region src/boot.d.ts
5
6
  interface WorkersExecutionContext {
6
7
  waitUntil(promise: Promise<unknown>): void;
@@ -157,12 +158,15 @@ interface BuildCloudflareOutputOptions {
157
158
  * leaves the endpoint outside the OAuth boundary silently.
158
159
  */
159
160
  mcpPath?: string;
161
+ /** Send the app build's own output to stderr, so stdout carries only a caller's JSON. */
162
+ appBuildToStderr?: boolean;
160
163
  }
161
164
  /**
162
- * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
163
- * built Guren app: a generated worker entry that statically wires the SSR
164
- * bundle, static assets for Workers Static Assets, and a one-time
165
- * `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
165
+ * Assemble a deployable Cloudflare Workers directory from a built Guren app: a
166
+ * generated worker entry that statically wires the SSR bundle, and static assets
167
+ * for Workers Static Assets. On the Wrangler backend it goes to `.cloudflare/` with
168
+ * a one-time `wrangler.jsonc` scaffold; on the cf backend to `.guren/cloudflare/`
169
+ * with the `guren-worker.json` manifest `gurenWorker()` reads (RFC 0035 §3).
166
170
  */
167
171
  declare function buildCloudflareOutput(options?: BuildCloudflareOutputOptions): Promise<void>;
168
172
  /**
@@ -326,12 +330,11 @@ interface R2PresignOptions {
326
330
  }
327
331
  interface R2DriverOptions {
328
332
  /**
329
- * Resolver returning the R2 bucket binding. Bindings arrive with the first
330
- * request on Workers, so this must be a deferred closure, e.g.
331
- * `binding: () => getWorkersEnv<Env>().BUCKET` — the same contract as
332
- * `createD1Database({ binding })`.
333
+ * The R2 bucket binding: its name (`'MEDIA'`), read from the Workers env the first
334
+ * request captured, or a deferred closure such as `() => getWorkersEnv<Env>().MEDIA`.
335
+ * The same contract as `createD1Database({ binding })`.
333
336
  */
334
- binding: () => unknown;
337
+ binding: string | (() => unknown);
335
338
  /**
336
339
  * Base URL for `url()`: the bucket's custom domain (recommended) or its r2.dev
337
340
  * subdomain. R2 has no derivable default, so `url()` throws when this is unset.
@@ -414,6 +417,16 @@ declare class R2Driver implements StorageDriver {
414
417
  /** The key prefix (for tests and diagnostics). */
415
418
  getPrefix(): string;
416
419
  }
420
+ /**
421
+ * The arguments `StorageManager.registerDisk()` takes for an R2 disk: its factory, and the
422
+ * description introspection reports without building it (RFC 0035 §2.1). One options object
423
+ * feeds both, so the binding the deploy sees is the one the driver reads.
424
+ * @example storage.registerDisk('media', ...r2Disk({ binding: 'MEDIA', publicUrl }))
425
+ */
426
+ declare function r2Disk(options: R2DriverOptions): [() => R2Driver, {
427
+ driver: 'r2';
428
+ binding?: string;
429
+ }];
417
430
  //#endregion
418
431
  //#region src/index.d.ts
419
432
  /**
@@ -424,4 +437,4 @@ interface CloudflarePluginConfig {}
424
437
  /** Register the Cloudflare plugin: `createApp({ providers: [cloudflarePlugin()] })`. */
425
438
  declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
426
439
  //#endregion
427
- export { type BuildCloudflareOutputOptions, type BundleAttribution, type BundleReport, type BundleSize, CloudflarePluginConfig, type EsbuildMetafile, OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, type OAuthPurgeOptions, type OAuthPurgeResult, type OAuthPurgerLike, type OAuthSweepEnv, type OAuthSweepKvLike, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type ReportBundleSizeOptions, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, type WorkersScheduledEvent, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
440
+ export { type BuildCloudflareOutputOptions, type BundleAttribution, type BundleReport, type BundleSize, CloudflarePluginConfig, type EsbuildMetafile, OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, type OAuthPurgeOptions, type OAuthPurgeResult, type OAuthPurgerLike, type OAuthSweepEnv, type OAuthSweepKvLike, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type ReportBundleSizeOptions, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, type WorkersScheduledEvent, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, r2Disk, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, resetWorkersEnv } from "./env.js";
2
- import { a as printBundleReport, c as buildCloudflareOutput, i as parseWranglerSize, l as flattenD1Migrations, n as WORKER_SIZE_WARN_SHARE, o as renderBundleReport, r as attributeBundle, s as reportBundleSize, t as WORKER_SIZE_LIMIT } from "./bundle-size-CUn3w_nY.js";
1
+ import { captureWorkersEnv, getWorkersEnv, isWorkersRuntime, readWorkersBinding, resetWorkersEnv } from "./env.js";
2
+ import { _ as flattenD1Migrations, a as parseWranglerSize, c as reportBundleSize, i as attributeBundle, n as WORKER_SIZE_WARN_SHARE, o as printBundleReport, p as buildCloudflareOutput, s as renderBundleReport, t as WORKER_SIZE_LIMIT } from "./bundle-size-CcXTKLKq.js";
3
3
  import { definePlugin } from "@guren/core";
4
4
  //#region src/boot.ts
5
5
  const latches = /* @__PURE__ */ new WeakMap();
@@ -237,7 +237,9 @@ var R2Driver = class {
237
237
  diskVisibility;
238
238
  presign;
239
239
  constructor(options) {
240
- this.resolveBinding = options.binding;
240
+ const { binding } = options;
241
+ if (binding === "") throw new Error("R2Driver: `binding` names no binding; pass its name, such as 'MEDIA'.");
242
+ this.resolveBinding = typeof binding === "string" ? () => readWorkersBinding(binding, "R2Driver") : binding;
241
243
  this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
242
244
  this.prefix = trimSlashes(options.prefix ?? "");
243
245
  this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
@@ -459,6 +461,19 @@ function trimSlashes(value) {
459
461
  while (end > start && value[end - 1] === "/") end--;
460
462
  return value.slice(start, end);
461
463
  }
464
+ /**
465
+ * The arguments `StorageManager.registerDisk()` takes for an R2 disk: its factory, and the
466
+ * description introspection reports without building it (RFC 0035 §2.1). One options object
467
+ * feeds both, so the binding the deploy sees is the one the driver reads.
468
+ * @example storage.registerDisk('media', ...r2Disk({ binding: 'MEDIA', publicUrl }))
469
+ */
470
+ function r2Disk(options) {
471
+ const binding = typeof options.binding === "string" ? options.binding : void 0;
472
+ return [() => new R2Driver(options), binding ? {
473
+ driver: "r2",
474
+ binding
475
+ } : { driver: "r2" }];
476
+ }
462
477
  //#endregion
463
478
  //#region src/index.ts
464
479
  const factory = definePlugin({
@@ -471,4 +486,4 @@ function cloudflarePlugin(config = {}) {
471
486
  return factory(config);
472
487
  }
473
488
  //#endregion
474
- export { OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, R2Driver, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
489
+ export { OAUTH_PURGE_BATCH, OAUTH_PURGE_INTERVAL_MS, OAUTH_PURGE_MARKER, R2Driver, WORKER_SIZE_LIMIT, WORKER_SIZE_WARN_SHARE, attributeBundle, bootAndFetch, bootAndRunDueTasks, bootWorkersApp, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, isWorkersRuntime, parseWranglerSize, printBundleReport, r2Disk, renderBundleReport, reportBundleSize, resetWorkersEnv, sweepOAuthStorage };
@@ -0,0 +1,31 @@
1
+ //#region src/worker-manifest.ts
2
+ /**
3
+ * The build manifest `cloudflare:build` writes for the `cf` backend (RFC 0035 §3):
4
+ * what `gurenWorker()` turns into `cloudflare.config.ts` bindings. It is written
5
+ * by the Bun build and read under Node by `cf`, so this module imports nothing.
6
+ * On the Wrangler backend it holds only `version` and `resolved`.
7
+ */
8
+ /** The file name inside the output directory. */
9
+ const WORKER_MANIFEST_FILE = "guren-worker.json";
10
+ /** The `cf` backend's output directory, relative to the app root (RFC 0035 §3.3). */
11
+ const CF_OUTPUT_DIR = ".guren/cloudflare";
12
+ /** The Wrangler backend's, which the committed wrangler.jsonc points into. */
13
+ const WRANGLER_OUTPUT_DIR = ".cloudflare";
14
+ /** The output directory of each backend, which the build writes and the deploy reads. */
15
+ function outputDirFor(backend) {
16
+ return backend === "cf" ? CF_OUTPUT_DIR : WRANGLER_OUTPUT_DIR;
17
+ }
18
+ /** Inside the output directory: the flattened copy of `db/migrations`. */
19
+ const D1_MIGRATIONS_DIR = "d1-migrations";
20
+ /** The Wrangler backend's deploy config, rendered into its output directory with the resolved ids. */
21
+ const WRANGLER_DEPLOY_CONFIG_FILE = "wrangler.deploy.json";
22
+ /** The name `cf` and Wrangler provision a binding under: `<worker>-<binding>`, `_` as `-` (RFC 0035 §4). */
23
+ function autoProvisionedName(worker, binding) {
24
+ return `${worker}-${binding.toLowerCase().replaceAll("_", "-")}`;
25
+ }
26
+ /** A binding's resource name: one the config states, then `config/cloudflare.ts`'s, then the default. */
27
+ function resourceName(worker, binding, resourceNames, stated) {
28
+ return stated ?? resourceNames?.[binding] ?? autoProvisionedName(worker, binding);
29
+ }
30
+ //#endregion
31
+ export { WRANGLER_OUTPUT_DIR as a, WRANGLER_DEPLOY_CONFIG_FILE as i, D1_MIGRATIONS_DIR as n, outputDirFor as o, WORKER_MANIFEST_FILE as r, resourceName as s, CF_OUTPUT_DIR as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.12.3",
3
+ "version": "0.13.0",
4
4
  "description": "Deploy a Guren application to Cloudflare Workers, with D1 as the database.",
5
5
  "keywords": [
6
6
  "guren",
@@ -32,8 +32,10 @@
32
32
  "commands": {
33
33
  "entry": "./dist/commands.js",
34
34
  "names": [
35
+ "cloudflare:init",
35
36
  "cloudflare:build",
36
- "cloudflare:size"
37
+ "cloudflare:size",
38
+ "cloudflare:deploy"
37
39
  ]
38
40
  }
39
41
  },
@@ -51,6 +53,10 @@
51
53
  "./env": {
52
54
  "types": "./dist/env.d.ts",
53
55
  "default": "./dist/env.js"
56
+ },
57
+ "./config": {
58
+ "types": "./dist/config.d.ts",
59
+ "default": "./dist/config.js"
54
60
  }
55
61
  },
56
62
  "scripts": {
@@ -59,10 +65,11 @@
59
65
  "typecheck": "tsc --noEmit"
60
66
  },
61
67
  "dependencies": {
62
- "@guren/core": "^1.22.0",
68
+ "@guren/core": "^1.25.0",
63
69
  "citty": "^0.1.6"
64
70
  },
65
71
  "devDependencies": {
72
+ "@cloudflare/config": "0.27.0",
66
73
  "@cloudflare/workers-oauth-provider": "^0.10.3",
67
74
  "@cloudflare/workers-types": "^4.20260702.1",
68
75
  "@types/node": "^20.14.10",