@guren/plugin-cloudflare 0.2.1 → 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 CHANGED
@@ -20,8 +20,8 @@ bunx wrangler deploy
20
20
 
21
21
  ## API
22
22
 
23
- - **`createWorkersHandler(app)`** — wraps a Guren `Application` in a Workers module handler. Boot is lazy and deduplicated on the first request, because bindings only arrive with `fetch` and cannot be read at module scope.
24
- - **`getWorkersEnv<Env>()`** — exposes the first request's bindings to boot-time config through a write-once holder. Use it to hand a D1 binding to the ORM:
23
+ - **`createWorkersHandler(app)`** — wraps a Guren `Application` in a Workers module handler. Boot is lazy and deduplicated on the first request, because `boot()` performs I/O that workerd forbids in global scope. The handler deduplicates boot itself, so boot-once holds for anything matching `WorkersAppLike`, not only Guren's `Application`.
24
+ - **`getWorkersEnv<Env>()`** — exposes the first request's bindings to boot-time config through a write-once holder. workerd can also expose bindings at module scope via `cloudflare:workers`, but importing that from shared config would break every other runtime (Bun, Lambda, Vercel) — the holder keeps `config/*.ts` portable. Use it to hand a D1 binding to the ORM:
25
25
 
26
26
  ```typescript
27
27
  import { createD1Database } from '@guren/core'
@@ -34,6 +34,22 @@ bunx wrangler deploy
34
34
 
35
35
  The binding is a resolver, not a value — it must be read lazily.
36
36
 
37
+ - **`R2Driver`** — a storage driver over the R2 bucket binding, for `StorageManager.registerDisk()`. Same lazy `binding` contract as D1; no credentials and no AWS SDK in the bundle:
38
+
39
+ ```typescript
40
+ import { createStorageManager, LocalStorageDriver } from '@guren/core'
41
+ import { R2Driver, getWorkersEnv } from '@guren/plugin-cloudflare'
42
+
43
+ const storage = createStorageManager({ default: 'media' })
44
+ storage.registerDisk('media', () =>
45
+ isWorkersRuntime()
46
+ ? new R2Driver({ binding: () => getWorkersEnv<{ MEDIA: unknown }>().MEDIA, publicUrl: 'https://media.example.com' })
47
+ : new LocalStorageDriver({ root: './storage/app/public', url: '/storage' }),
48
+ )
49
+ ```
50
+
51
+ with `"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "my-app-media" }]` in `wrangler.jsonc`. Three methods differ from the S3 driver, because the binding differs from S3: `url()` needs `publicUrl` (a custom domain or the r2.dev subdomain — R2 has no derivable public URL); `temporaryUrl()` needs the optional `presign` credentials, and throws with guidance otherwise (bindings cannot sign URLs); `setVisibility()` / `put({ visibility })` throw when asked for the opposite of the bucket's declared `visibility`, because R2 has no per-object ACL to honour the request with. `putFile()` throws — Workers has no filesystem.
52
+
37
53
  - **`cloudflarePlugin()`** — the service provider factory, registered automatically by `guren plugin`.
38
54
 
39
55
  ## Things Workers changes
@@ -181,10 +181,6 @@ function renderWorkerModule(input) {
181
181
  }
182
182
  function scaffoldWranglerConfig(root, out, packageName) {
183
183
  const configPath = resolve(root, "wrangler.jsonc");
184
- if (existsSync(configPath)) {
185
- warnMissingBuildOwnedKeys(configPath, relative(root, out).split(sep).join("/"));
186
- return;
187
- }
188
184
  const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
189
185
  const outRelative = relative(root, out).split(sep).join("/");
190
186
  const config = {
@@ -219,8 +215,16 @@ function scaffoldWranglerConfig(root, out, packageName) {
219
215
  ],
220
216
  vars: { NODE_ENV: "production" }
221
217
  };
222
- writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
223
- `);
218
+ try {
219
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
220
+ `, { flag: "wx" });
221
+ } catch (error) {
222
+ if (error.code === "EEXIST") {
223
+ warnMissingBuildOwnedKeys(configPath, outRelative);
224
+ return;
225
+ }
226
+ throw error;
227
+ }
224
228
  console.log(`Cloudflare build: scaffolded ${configPath} \u2014 fill in d1_databases[0].database_id before deploying.`);
225
229
  }
226
230
  function warnMissingBuildOwnedKeys(configPath, outRelative) {
package/dist/commands.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  buildCloudflareOutput
3
- } from "./chunk-N2ARYMZQ.js";
3
+ } from "./chunk-32YY6FCY.js";
4
4
 
5
5
  // src/commands.ts
6
6
  import { defineCommand } from "citty";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ServiceProviderConstructor } from '@guren/core';
1
+ import { StorageDriver, PutOptions, FileMetadata, ServiceProviderConstructor } from '@guren/core';
2
2
  import { PathLike } from '@guren/core/internal/deploy-build';
3
3
 
4
4
  /** First call wins; later calls are ignored (never overwrite a live env). */
@@ -12,6 +12,11 @@ interface WorkersExecutionContext {
12
12
  waitUntil(promise: Promise<unknown>): void;
13
13
  passThroughOnException?(): void;
14
14
  }
15
+ /**
16
+ * The shape `createWorkersHandler` needs from an app. Structural rather than
17
+ * `Application` itself, so `boot()` is not assumed to be idempotent — each
18
+ * handler dedupes boot across its own requests for anything conforming here.
19
+ */
15
20
  interface WorkersAppLike {
16
21
  boot(): Promise<void>;
17
22
  fetch(request: Request, env?: unknown, executionCtx?: unknown): Response | Promise<Response>;
@@ -56,6 +61,176 @@ declare function buildCloudflareOutput(options?: BuildCloudflareOutputOptions):
56
61
  */
57
62
  declare function flattenD1Migrations(migrationsDir: string, outDir: string): void;
58
63
 
64
+ /**
65
+ * Structural view of the R2 binding, in the same spirit as the S3 driver's
66
+ * local `S3Client { send() }`: only what this driver calls, so
67
+ * `@cloudflare/workers-types` stays a devDependency. `R2Driver.types.test.ts`
68
+ * pins that the real `R2Bucket` satisfies it.
69
+ */
70
+ interface R2HttpMetadataLike {
71
+ contentType?: string;
72
+ contentLanguage?: string;
73
+ contentDisposition?: string;
74
+ contentEncoding?: string;
75
+ cacheControl?: string;
76
+ cacheExpiry?: Date;
77
+ }
78
+ interface R2ObjectLike {
79
+ key: string;
80
+ size: number;
81
+ uploaded: Date;
82
+ httpMetadata?: R2HttpMetadataLike;
83
+ customMetadata?: Record<string, string>;
84
+ }
85
+ /**
86
+ * Streams and blobs are typed structurally rather than as the global
87
+ * `ReadableStream`/`Blob`: `@cloudflare/workers-types` declares its own
88
+ * interfaces for both, and neither direction is assignable to the runtime
89
+ * globals, so naming the globals here would make the real `R2Bucket` fail
90
+ * the `R2BucketLike` check while being perfectly usable at runtime.
91
+ */
92
+ interface R2StreamLike {
93
+ locked: boolean;
94
+ getReader(): unknown;
95
+ cancel(reason?: unknown): Promise<void>;
96
+ }
97
+ interface R2BlobLike {
98
+ size: number;
99
+ type: string;
100
+ arrayBuffer(): Promise<ArrayBuffer>;
101
+ text(): Promise<string>;
102
+ }
103
+ interface R2ObjectBodyLike extends R2ObjectLike {
104
+ body: R2StreamLike;
105
+ arrayBuffer(): Promise<ArrayBuffer>;
106
+ text(): Promise<string>;
107
+ }
108
+ interface R2ObjectsLike {
109
+ objects: R2ObjectLike[];
110
+ truncated: boolean;
111
+ cursor?: string;
112
+ delimitedPrefixes: string[];
113
+ }
114
+ interface R2ListOptionsLike {
115
+ prefix?: string;
116
+ delimiter?: string;
117
+ cursor?: string;
118
+ limit?: number;
119
+ }
120
+ interface R2PutOptionsLike {
121
+ httpMetadata?: R2HttpMetadataLike;
122
+ customMetadata?: Record<string, string>;
123
+ }
124
+ type R2PutValue = R2StreamLike | R2BlobLike | ArrayBuffer | ArrayBufferView | string | null;
125
+ interface R2BucketLike {
126
+ head(key: string): Promise<R2ObjectLike | null>;
127
+ get(key: string): Promise<R2ObjectBodyLike | null>;
128
+ put(key: string, value: R2PutValue, options?: R2PutOptionsLike): Promise<R2ObjectLike | null>;
129
+ delete(keys: string | string[]): Promise<void>;
130
+ list(options?: R2ListOptionsLike): Promise<R2ObjectsLike>;
131
+ }
132
+ interface R2PresignOptions {
133
+ /** Cloudflare account id — the S3 endpoint is `https://<accountId>.r2.cloudflarestorage.com`. */
134
+ accountId: string;
135
+ /** Bucket name as R2 knows it (the binding does not expose it). */
136
+ bucket: string;
137
+ /** R2 API token credentials (S3-compatible access key pair). */
138
+ accessKeyId: string;
139
+ secretAccessKey: string;
140
+ }
141
+ interface R2DriverOptions {
142
+ /**
143
+ * Resolver returning the R2 bucket binding. Bindings arrive with the first
144
+ * request on Workers, so this must be a deferred closure, e.g.
145
+ * `binding: () => getWorkersEnv<Env>().BUCKET` — the same contract as
146
+ * `createD1Database({ binding })`.
147
+ */
148
+ binding: () => unknown;
149
+ /**
150
+ * Base URL for `url()`: the bucket's custom domain (recommended) or its
151
+ * r2.dev subdomain. R2 has no derivable default — unlike S3 there is no
152
+ * `https://<bucket>.s3.<region>.amazonaws.com` — so `url()` throws with
153
+ * guidance when this is unset.
154
+ */
155
+ publicUrl?: string;
156
+ /** Key prefix, same semantics as `S3DriverOptions.prefix`. */
157
+ prefix?: string;
158
+ /**
159
+ * The visibility every object in this bucket effectively has. R2 has no
160
+ * per-object ACL: a bucket is public (custom domain / r2.dev) or it is not.
161
+ * Defaults to `'public'` when `publicUrl` is set, `'private'` otherwise.
162
+ * `put({ visibility })` and `setVisibility()` throw when asked for the
163
+ * other value — the driver refuses to pretend it can enforce a per-object
164
+ * flag it cannot.
165
+ */
166
+ visibility?: 'public' | 'private';
167
+ /**
168
+ * S3 API credentials used only by `temporaryUrl()`. Optional — omit it and
169
+ * `temporaryUrl()` throws with guidance.
170
+ */
171
+ presign?: R2PresignOptions;
172
+ }
173
+ /**
174
+ * Cloudflare R2 storage driver over the Workers binding.
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const storage = createStorageManager({ default: 'media' })
179
+ * storage.registerDisk('media', () => new R2Driver({
180
+ * binding: () => getWorkersEnv<Env>().MEDIA,
181
+ * publicUrl: 'https://media.example.com',
182
+ * }))
183
+ * ```
184
+ */
185
+ declare class R2Driver implements StorageDriver {
186
+ private readonly resolveBinding;
187
+ private readonly publicUrl?;
188
+ private readonly prefix;
189
+ private readonly diskVisibility;
190
+ private readonly presign?;
191
+ constructor(options: R2DriverOptions);
192
+ private bucket;
193
+ private key;
194
+ /** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
195
+ private unkey;
196
+ private directoryPrefix;
197
+ private assertVisibility;
198
+ put(path: string, content: Buffer | string, options?: PutOptions): Promise<string>;
199
+ putFile(_path: string, _localPath: string, _options?: PutOptions): Promise<string>;
200
+ get(path: string): Promise<Buffer | null>;
201
+ getAsString(path: string): Promise<string | null>;
202
+ exists(path: string): Promise<boolean>;
203
+ delete(path: string): Promise<boolean>;
204
+ deleteMany(paths: string[]): Promise<number>;
205
+ private deleteKeys;
206
+ copy(from: string, to: string): Promise<string>;
207
+ move(from: string, to: string): Promise<string>;
208
+ url(path: string): string;
209
+ temporaryUrl(path: string, expiration: Date): Promise<string>;
210
+ size(path: string): Promise<number>;
211
+ lastModified(path: string): Promise<Date>;
212
+ private metadataOrFail;
213
+ metadata(path: string): Promise<FileMetadata | null>;
214
+ files(directory: string): Promise<string[]>;
215
+ directories(directory: string): Promise<string[]>;
216
+ allFiles(directory: string): Promise<string[]>;
217
+ /** App-relative paths of every listed object, minus folder markers. */
218
+ private collectFiles;
219
+ private objects;
220
+ /**
221
+ * Follows `cursor` until `truncated` is false. A single `list()` call is
222
+ * capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
223
+ * silently truncates larger directories.
224
+ */
225
+ private pages;
226
+ makeDirectory(path: string): Promise<void>;
227
+ deleteDirectory(path: string): Promise<void>;
228
+ setVisibility(path: string, visibility: 'public' | 'private'): Promise<void>;
229
+ getVisibility(path: string): Promise<'public' | 'private'>;
230
+ /** The key prefix (for tests and diagnostics). */
231
+ getPrefix(): string;
232
+ }
233
+
59
234
  /**
60
235
  * Configuration for the Cloudflare plugin. Currently empty — reserved for
61
236
  * upcoming RFC 0003 parts (session/OAuth-state store wiring on Workers).
@@ -72,4 +247,4 @@ interface CloudflarePluginConfig {
72
247
  */
73
248
  declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
74
249
 
75
- export { type BuildCloudflareOutputOptions, type CloudflarePluginConfig, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
250
+ export { type BuildCloudflareOutputOptions, type CloudflarePluginConfig, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildCloudflareOutput,
3
3
  flattenD1Migrations
4
- } from "./chunk-N2ARYMZQ.js";
4
+ } from "./chunk-32YY6FCY.js";
5
5
 
6
6
  // src/index.ts
7
7
  import { definePlugin } from "@guren/core";
@@ -29,12 +29,15 @@ function createWorkersHandler(app) {
29
29
  return {
30
30
  async fetch(request, env, ctx) {
31
31
  captureWorkersEnv(env);
32
- bootPromise ??= app.boot();
32
+ let attempt;
33
33
  try {
34
- await bootPromise;
34
+ attempt = bootPromise ??= app.boot();
35
+ await attempt;
35
36
  } catch (error) {
36
- bootPromise = void 0;
37
- resetWorkersEnv();
37
+ if (bootPromise === attempt) {
38
+ bootPromise = void 0;
39
+ resetWorkersEnv();
40
+ }
38
41
  throw error;
39
42
  }
40
43
  return app.fetch(request, env, ctx);
@@ -42,6 +45,326 @@ function createWorkersHandler(app) {
42
45
  };
43
46
  }
44
47
 
48
+ // src/storage/sigv4.ts
49
+ var ALGORITHM = "AWS4-HMAC-SHA256";
50
+ var TERMINATOR = "aws4_request";
51
+ var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
52
+ function encodeRfc3986(value) {
53
+ return encodeURIComponent(value).replace(
54
+ /[!'()*]/g,
55
+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
56
+ );
57
+ }
58
+ function canonicalPath(pathname) {
59
+ return pathname.split("/").map(decodeAndEncodeSegment).join("/");
60
+ }
61
+ function decodeAndEncodeSegment(segment) {
62
+ return encodeRfc3986(decodeURIComponent(segment));
63
+ }
64
+ function canonicalQuery(searchParams) {
65
+ return Array.from(searchParams).map(([name, value]) => [encodeRfc3986(name), encodeRfc3986(value)]).sort(
66
+ ([leftName, leftValue], [rightName, rightValue]) => leftName === rightName ? leftValue < rightValue ? -1 : 1 : leftName < rightName ? -1 : 1
67
+ ).map(([name, value]) => `${name}=${value}`).join("&");
68
+ }
69
+ function toHex(bytes) {
70
+ return Array.from(new Uint8Array(bytes)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
71
+ }
72
+ async function sha256Hex(value) {
73
+ return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
74
+ }
75
+ async function hmac(key, value) {
76
+ const cryptoKey = await crypto.subtle.importKey(
77
+ "raw",
78
+ key,
79
+ { name: "HMAC", hash: "SHA-256" },
80
+ false,
81
+ ["sign"]
82
+ );
83
+ return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
84
+ }
85
+ async function signingKey(secretAccessKey, dateStamp, region, service) {
86
+ const initial = new TextEncoder().encode(`AWS4${secretAccessKey}`);
87
+ const byDate = await hmac(initial, dateStamp);
88
+ const byRegion = await hmac(byDate, region);
89
+ const byService = await hmac(byRegion, service);
90
+ return hmac(byService, TERMINATOR);
91
+ }
92
+ async function presignGetUrl(options) {
93
+ const { accessKeyId, secretAccessKey, region, service, expiresIn } = options;
94
+ const date = options.date ?? /* @__PURE__ */ new Date();
95
+ const amzDate = `${date.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
96
+ const dateStamp = amzDate.slice(0, 8);
97
+ const scope = `${dateStamp}/${region}/${service}/${TERMINATOR}`;
98
+ const url = new URL(options.url);
99
+ url.searchParams.set("X-Amz-Algorithm", ALGORITHM);
100
+ url.searchParams.set("X-Amz-Credential", `${accessKeyId}/${scope}`);
101
+ url.searchParams.set("X-Amz-Date", amzDate);
102
+ url.searchParams.set("X-Amz-Expires", String(expiresIn));
103
+ url.searchParams.set("X-Amz-SignedHeaders", "host");
104
+ const canonicalRequest = [
105
+ "GET",
106
+ canonicalPath(url.pathname),
107
+ canonicalQuery(url.searchParams),
108
+ `host:${url.host}
109
+ `,
110
+ "host",
111
+ UNSIGNED_PAYLOAD
112
+ ].join("\n");
113
+ const stringToSign = [ALGORITHM, amzDate, scope, await sha256Hex(canonicalRequest)].join("\n");
114
+ const key = await signingKey(secretAccessKey, dateStamp, region, service);
115
+ url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
116
+ return url.toString();
117
+ }
118
+
119
+ // src/storage/R2Driver.ts
120
+ var MAX_PRESIGN_SECONDS = 7 * 24 * 60 * 60;
121
+ var DELETE_BATCH_SIZE = 1e3;
122
+ var DELETE_CONCURRENCY = 6;
123
+ var R2Driver = class {
124
+ resolveBinding;
125
+ publicUrl;
126
+ prefix;
127
+ diskVisibility;
128
+ presign;
129
+ constructor(options) {
130
+ this.resolveBinding = options.binding;
131
+ this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
132
+ this.prefix = trimSlashes(options.prefix ?? "");
133
+ this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
134
+ this.presign = options.presign;
135
+ }
136
+ bucket() {
137
+ const binding = this.resolveBinding();
138
+ if (binding == null) {
139
+ throw new Error(
140
+ 'R2Driver: the "binding" resolver returned no R2 bucket. On Workers this usually means it ran before the first request \u2014 defer access (e.g. binding: () => getWorkersEnv<Env>().BUCKET) and check the r2_buckets entry in wrangler.jsonc, e.g. "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-app-media" }].'
141
+ );
142
+ }
143
+ return binding;
144
+ }
145
+ key(path) {
146
+ const normalized = trimSlashes(path);
147
+ if (!this.prefix) return normalized;
148
+ return normalized ? `${this.prefix}/${normalized}` : this.prefix;
149
+ }
150
+ /** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
151
+ unkey(key) {
152
+ return this.prefix && key.startsWith(`${this.prefix}/`) ? key.slice(this.prefix.length + 1) : key;
153
+ }
154
+ directoryPrefix(directory) {
155
+ const key = this.key(directory);
156
+ return key ? `${key}/` : "";
157
+ }
158
+ assertVisibility(requested, operation) {
159
+ if (requested && requested !== this.diskVisibility) {
160
+ throw new Error(
161
+ `R2Driver.${operation}: cannot make an object ${requested} on a ${this.diskVisibility} bucket. R2 has no per-object visibility \u2014 access is decided per bucket (custom domain / r2.dev). Declare the bucket\u2019s visibility with the driver\u2019s "visibility" option, or serve private files through a signed app route.`
162
+ );
163
+ }
164
+ }
165
+ async put(path, content, options) {
166
+ this.assertVisibility(options?.visibility, "put");
167
+ const putOptions = {};
168
+ if (options?.contentType) putOptions.httpMetadata = { contentType: options.contentType };
169
+ if (options?.metadata) putOptions.customMetadata = options.metadata;
170
+ await this.bucket().put(this.key(path), content, putOptions);
171
+ return trimSlashes(path);
172
+ }
173
+ async putFile(_path, _localPath, _options) {
174
+ throw new Error(
175
+ "R2Driver.putFile is not supported: Workers has no filesystem to read from. Read the file yourself and call put()."
176
+ );
177
+ }
178
+ async get(path) {
179
+ const object = await this.bucket().get(this.key(path));
180
+ if (!object) return null;
181
+ return Buffer.from(await object.arrayBuffer());
182
+ }
183
+ async getAsString(path) {
184
+ const object = await this.bucket().get(this.key(path));
185
+ return object ? object.text() : null;
186
+ }
187
+ async exists(path) {
188
+ return await this.bucket().head(this.key(path)) !== null;
189
+ }
190
+ async delete(path) {
191
+ const bucket = this.bucket();
192
+ const key = this.key(path);
193
+ if (await bucket.head(key) === null) return false;
194
+ await bucket.delete(key);
195
+ return true;
196
+ }
197
+ async deleteMany(paths) {
198
+ return this.deleteKeys(paths.map((path) => this.key(path)));
199
+ }
200
+ async deleteKeys(rawKeys) {
201
+ const keys = Array.from(new Set(rawKeys));
202
+ if (keys.length === 0) return 0;
203
+ const bucket = this.bucket();
204
+ const batches = [];
205
+ for (let index = 0; index < keys.length; index += DELETE_BATCH_SIZE) {
206
+ batches.push(keys.slice(index, index + DELETE_BATCH_SIZE));
207
+ }
208
+ for (let index = 0; index < batches.length; index += DELETE_CONCURRENCY) {
209
+ await Promise.all(batches.slice(index, index + DELETE_CONCURRENCY).map((batch) => bucket.delete(batch)));
210
+ }
211
+ return keys.length;
212
+ }
213
+ async copy(from, to) {
214
+ const bucket = this.bucket();
215
+ const source = await bucket.get(this.key(from));
216
+ if (!source) {
217
+ throw new Error(`File not found: ${from}`);
218
+ }
219
+ const options = {};
220
+ if (source.httpMetadata) options.httpMetadata = source.httpMetadata;
221
+ if (source.customMetadata) options.customMetadata = source.customMetadata;
222
+ await bucket.put(this.key(to), source.body, options);
223
+ return trimSlashes(to);
224
+ }
225
+ async move(from, to) {
226
+ const destination = await this.copy(from, to);
227
+ await this.bucket().delete(this.key(from));
228
+ return destination;
229
+ }
230
+ url(path) {
231
+ if (!this.publicUrl) {
232
+ throw new Error(
233
+ 'R2Driver.url() requires the "publicUrl" option (the bucket\u2019s custom domain or r2.dev subdomain). R2 has no derivable public URL.'
234
+ );
235
+ }
236
+ return `${this.publicUrl}/${encodeKey(this.key(path))}`;
237
+ }
238
+ async temporaryUrl(path, expiration) {
239
+ if (!this.presign) {
240
+ throw new Error(
241
+ 'R2Driver.temporaryUrl() cannot sign URLs through the R2 binding. Either configure "presign: { accountId, bucket, accessKeyId, secretAccessKey }" (an R2 API token, used with the S3-compatible endpoint) or serve private files through a signed app route.'
242
+ );
243
+ }
244
+ const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
245
+ if (expiresIn > MAX_PRESIGN_SECONDS) {
246
+ throw new Error(
247
+ `R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`
248
+ );
249
+ }
250
+ return presignGetUrl({
251
+ url: `https://${this.presign.accountId}.r2.cloudflarestorage.com/${this.presign.bucket}/${encodeKey(this.key(path))}`,
252
+ accessKeyId: this.presign.accessKeyId,
253
+ secretAccessKey: this.presign.secretAccessKey,
254
+ // R2's S3 API is single-region.
255
+ region: "auto",
256
+ service: "s3",
257
+ expiresIn: Math.max(1, expiresIn)
258
+ });
259
+ }
260
+ async size(path) {
261
+ return (await this.metadataOrFail(path)).size;
262
+ }
263
+ async lastModified(path) {
264
+ return (await this.metadataOrFail(path)).lastModified;
265
+ }
266
+ async metadataOrFail(path) {
267
+ const metadata = await this.metadata(path);
268
+ if (!metadata) {
269
+ throw new Error(`File not found: ${path}`);
270
+ }
271
+ return metadata;
272
+ }
273
+ async metadata(path) {
274
+ const object = await this.bucket().head(this.key(path));
275
+ if (!object) return null;
276
+ return {
277
+ path: trimSlashes(path),
278
+ size: object.size,
279
+ lastModified: object.uploaded,
280
+ contentType: object.httpMetadata?.contentType,
281
+ visibility: this.diskVisibility,
282
+ metadata: object.customMetadata
283
+ };
284
+ }
285
+ async files(directory) {
286
+ return this.collectFiles({ prefix: this.directoryPrefix(directory), delimiter: "/" });
287
+ }
288
+ async directories(directory) {
289
+ const result = [];
290
+ for await (const page of this.pages({ prefix: this.directoryPrefix(directory), delimiter: "/" })) {
291
+ for (const prefix of page.delimitedPrefixes) {
292
+ const relative = trimTrailingSlashes(this.unkey(prefix));
293
+ if (relative) result.push(relative);
294
+ }
295
+ }
296
+ return result.sort();
297
+ }
298
+ async allFiles(directory) {
299
+ return this.collectFiles({ prefix: this.directoryPrefix(directory) });
300
+ }
301
+ /** App-relative paths of every listed object, minus folder markers. */
302
+ async collectFiles(options) {
303
+ const result = [];
304
+ for await (const object of this.objects(options)) {
305
+ if (!object.key.endsWith("/")) result.push(this.unkey(object.key));
306
+ }
307
+ return result.sort();
308
+ }
309
+ async *objects(options) {
310
+ for await (const page of this.pages(options)) yield* page.objects;
311
+ }
312
+ /**
313
+ * Follows `cursor` until `truncated` is false. A single `list()` call is
314
+ * capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
315
+ * silently truncates larger directories.
316
+ */
317
+ async *pages(options) {
318
+ const bucket = this.bucket();
319
+ let cursor;
320
+ do {
321
+ const page = await bucket.list(cursor ? { ...options, cursor } : options);
322
+ yield page;
323
+ cursor = page.truncated ? page.cursor : void 0;
324
+ } while (cursor);
325
+ }
326
+ async makeDirectory(path) {
327
+ const normalized = trimSlashes(path);
328
+ if (!normalized) return;
329
+ await this.bucket().put(`${this.key(normalized)}/`, "");
330
+ }
331
+ async deleteDirectory(path) {
332
+ const bucket = this.bucket();
333
+ for await (const page of this.pages({ prefix: this.directoryPrefix(path) })) {
334
+ if (page.objects.length > 0) {
335
+ await bucket.delete(page.objects.map((object) => object.key));
336
+ }
337
+ }
338
+ }
339
+ async setVisibility(path, visibility) {
340
+ this.assertVisibility(visibility, "setVisibility");
341
+ await this.metadataOrFail(path);
342
+ }
343
+ async getVisibility(path) {
344
+ await this.metadataOrFail(path);
345
+ return this.diskVisibility;
346
+ }
347
+ /** The key prefix (for tests and diagnostics). */
348
+ getPrefix() {
349
+ return this.prefix;
350
+ }
351
+ };
352
+ function encodeKey(key) {
353
+ return key.split("/").map(encodeURIComponent).join("/");
354
+ }
355
+ function trimTrailingSlashes(value) {
356
+ let end = value.length;
357
+ while (end > 0 && value[end - 1] === "/") end--;
358
+ return value.slice(0, end);
359
+ }
360
+ function trimSlashes(value) {
361
+ let start = 0;
362
+ let end = value.length;
363
+ while (start < end && value[start] === "/") start++;
364
+ while (end > start && value[end - 1] === "/") end--;
365
+ return value.slice(start, end);
366
+ }
367
+
45
368
  // src/index.ts
46
369
  var factory = definePlugin({
47
370
  name: "cloudflare",
@@ -52,6 +375,7 @@ function cloudflarePlugin(config = {}) {
52
375
  return factory(config);
53
376
  }
54
377
  export {
378
+ R2Driver,
55
379
  buildCloudflareOutput,
56
380
  captureWorkersEnv,
57
381
  cloudflarePlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,12 +41,13 @@
41
41
  "typecheck": "tsc --noEmit"
42
42
  },
43
43
  "dependencies": {
44
- "@guren/core": "^1.4.0",
44
+ "@guren/core": "^1.5.2",
45
45
  "citty": "^0.1.6"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@cloudflare/workers-types": "^4.20260702.1",
49
49
  "@types/node": "^20.14.10",
50
+ "miniflare": "5.20260801.1-alpha",
50
51
  "tsup": "^8.5.0",
51
52
  "typescript": "^5.4.0"
52
53
  }