@guren/plugin-cloudflare 0.3.1 → 0.3.2
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/dist/build-DxgM3l-5.js +294 -0
- package/dist/commands.d.ts +13 -14
- package/dist/commands.js +25 -33
- package/dist/index.d.ts +155 -152
- package/dist/index.js +341 -348
- package/package.json +5 -5
- package/dist/chunk-6DV73MBR.js +0 -321
package/dist/index.js
CHANGED
|
@@ -1,386 +1,379 @@
|
|
|
1
|
-
import {
|
|
2
|
-
buildCloudflareOutput,
|
|
3
|
-
flattenD1Migrations
|
|
4
|
-
} from "./chunk-6DV73MBR.js";
|
|
5
|
-
|
|
6
|
-
// src/index.ts
|
|
1
|
+
import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-DxgM3l-5.js";
|
|
7
2
|
import { definePlugin } from "@guren/core";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
3
|
+
//#region src/env.ts
|
|
4
|
+
let holder;
|
|
5
|
+
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
11
6
|
function captureWorkersEnv(env) {
|
|
12
|
-
|
|
7
|
+
holder ??= { env };
|
|
13
8
|
}
|
|
9
|
+
/** Throws with a clear message if called before the first request captured env. */
|
|
14
10
|
function getWorkersEnv() {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
"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"
|
|
18
|
-
);
|
|
19
|
-
}
|
|
20
|
-
return holder.env;
|
|
11
|
+
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");
|
|
12
|
+
return holder.env;
|
|
21
13
|
}
|
|
14
|
+
/** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
|
|
22
15
|
function resetWorkersEnv() {
|
|
23
|
-
|
|
16
|
+
holder = void 0;
|
|
24
17
|
}
|
|
25
|
-
|
|
26
|
-
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/handler.ts
|
|
27
20
|
function createWorkersHandler(app) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
};
|
|
21
|
+
let bootPromise;
|
|
22
|
+
return { async fetch(request, env, ctx) {
|
|
23
|
+
captureWorkersEnv(env);
|
|
24
|
+
let attempt;
|
|
25
|
+
try {
|
|
26
|
+
attempt = bootPromise ??= app.boot();
|
|
27
|
+
await attempt;
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (bootPromise === attempt) {
|
|
30
|
+
bootPromise = void 0;
|
|
31
|
+
resetWorkersEnv();
|
|
32
|
+
}
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
return app.fetch(request, env, ctx);
|
|
36
|
+
} };
|
|
46
37
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/storage/sigv4.ts
|
|
40
|
+
const ALGORITHM = "AWS4-HMAC-SHA256";
|
|
41
|
+
const TERMINATOR = "aws4_request";
|
|
42
|
+
/**
|
|
43
|
+
* S3 accepts an unsigned payload for presigned URLs — the signature covers
|
|
44
|
+
* the request line, the query, and `host`, not the bytes.
|
|
45
|
+
*/
|
|
46
|
+
const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
|
|
47
|
+
/**
|
|
48
|
+
* Percent-encoding per RFC 3986, which is stricter than `encodeURIComponent`:
|
|
49
|
+
* `!`, `'`, `(`, `)` and `*` are reserved and must be escaped, or the
|
|
50
|
+
* canonical request the server rebuilds will not match ours.
|
|
51
|
+
*/
|
|
52
52
|
function encodeRfc3986(value) {
|
|
53
|
-
|
|
54
|
-
/[!'()*]/g,
|
|
55
|
-
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
|
|
56
|
-
);
|
|
53
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
57
54
|
}
|
|
55
|
+
/** Path segments are encoded individually; `/` stays a separator. */
|
|
58
56
|
function canonicalPath(pathname) {
|
|
59
|
-
|
|
57
|
+
return pathname.split("/").map(decodeAndEncodeSegment).join("/");
|
|
60
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The URL arrives already percent-encoded (callers build it with `URL`), but
|
|
61
|
+
* SigV4 canonicalizes from the decoded form — encoding again without
|
|
62
|
+
* decoding first would sign `%2520` where the server sees `%20`.
|
|
63
|
+
*/
|
|
61
64
|
function decodeAndEncodeSegment(segment) {
|
|
62
|
-
|
|
65
|
+
return encodeRfc3986(decodeURIComponent(segment));
|
|
63
66
|
}
|
|
67
|
+
/** Query parameters sorted by encoded name, then encoded value. */
|
|
64
68
|
function canonicalQuery(searchParams) {
|
|
65
|
-
|
|
66
|
-
([leftName, leftValue], [rightName, rightValue]) => leftName === rightName ? leftValue < rightValue ? -1 : 1 : leftName < rightName ? -1 : 1
|
|
67
|
-
).map(([name, value]) => `${name}=${value}`).join("&");
|
|
69
|
+
return Array.from(searchParams).map(([name, value]) => [encodeRfc3986(name), encodeRfc3986(value)]).sort(([leftName, leftValue], [rightName, rightValue]) => leftName === rightName ? leftValue < rightValue ? -1 : 1 : leftName < rightName ? -1 : 1).map(([name, value]) => `${name}=${value}`).join("&");
|
|
68
70
|
}
|
|
69
71
|
function toHex(bytes) {
|
|
70
|
-
|
|
72
|
+
return Array.from(new Uint8Array(bytes)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
71
73
|
}
|
|
72
74
|
async function sha256Hex(value) {
|
|
73
|
-
|
|
75
|
+
return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
|
|
74
76
|
}
|
|
75
77
|
async function hmac(key, value) {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
["sign"]
|
|
82
|
-
);
|
|
83
|
-
return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
|
|
78
|
+
const cryptoKey = await crypto.subtle.importKey("raw", key, {
|
|
79
|
+
name: "HMAC",
|
|
80
|
+
hash: "SHA-256"
|
|
81
|
+
}, false, ["sign"]);
|
|
82
|
+
return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
|
|
84
83
|
}
|
|
84
|
+
/** `AWS4<secret>` → date → region → service → terminator. */
|
|
85
85
|
async function signingKey(secretAccessKey, dateStamp, region, service) {
|
|
86
|
-
|
|
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);
|
|
86
|
+
return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
|
|
91
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Presign a GET so the URL alone authorizes the read until it expires.
|
|
90
|
+
*
|
|
91
|
+
* @returns the signed absolute URL
|
|
92
|
+
*/
|
|
92
93
|
async function presignGetUrl(options) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
94
|
+
const { accessKeyId, secretAccessKey, region, service, expiresIn } = options;
|
|
95
|
+
const amzDate = `${(options.date ?? /* @__PURE__ */ new 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}\n`,
|
|
109
|
+
"host",
|
|
110
|
+
UNSIGNED_PAYLOAD
|
|
111
|
+
].join("\n");
|
|
112
|
+
const stringToSign = [
|
|
113
|
+
ALGORITHM,
|
|
114
|
+
amzDate,
|
|
115
|
+
scope,
|
|
116
|
+
await sha256Hex(canonicalRequest)
|
|
117
|
+
].join("\n");
|
|
118
|
+
const key = await signingKey(secretAccessKey, dateStamp, region, service);
|
|
119
|
+
url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
|
|
120
|
+
return url.toString();
|
|
117
121
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/storage/R2Driver.ts
|
|
124
|
+
/** R2 rejects presigned URLs valid for longer than seven days. */
|
|
125
|
+
const MAX_PRESIGN_SECONDS = 604800;
|
|
126
|
+
/** `R2Bucket.delete()` accepts at most this many keys per call. */
|
|
127
|
+
const DELETE_BATCH_SIZE = 1e3;
|
|
128
|
+
/** How many delete batches may be in flight at once. */
|
|
129
|
+
const DELETE_CONCURRENCY = 6;
|
|
130
|
+
/**
|
|
131
|
+
* Cloudflare R2 storage driver over the Workers binding.
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```ts
|
|
135
|
+
* const storage = createStorageManager({ default: 'media' })
|
|
136
|
+
* storage.registerDisk('media', () => new R2Driver({
|
|
137
|
+
* binding: () => getWorkersEnv<Env>().MEDIA,
|
|
138
|
+
* publicUrl: 'https://media.example.com',
|
|
139
|
+
* }))
|
|
140
|
+
* ```
|
|
141
|
+
*/
|
|
123
142
|
var R2Driver = class {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
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
|
-
}
|
|
143
|
+
resolveBinding;
|
|
144
|
+
publicUrl;
|
|
145
|
+
prefix;
|
|
146
|
+
diskVisibility;
|
|
147
|
+
presign;
|
|
148
|
+
constructor(options) {
|
|
149
|
+
this.resolveBinding = options.binding;
|
|
150
|
+
this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
|
|
151
|
+
this.prefix = trimSlashes(options.prefix ?? "");
|
|
152
|
+
this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
|
|
153
|
+
this.presign = options.presign;
|
|
154
|
+
}
|
|
155
|
+
bucket() {
|
|
156
|
+
const binding = this.resolveBinding();
|
|
157
|
+
if (binding == null) throw new Error("R2Driver: the \"binding\" resolver returned no R2 bucket. On Workers this usually means it ran before the first request — 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\" }].");
|
|
158
|
+
return binding;
|
|
159
|
+
}
|
|
160
|
+
key(path) {
|
|
161
|
+
const normalized = trimSlashes(path);
|
|
162
|
+
if (!this.prefix) return normalized;
|
|
163
|
+
return normalized ? `${this.prefix}/${normalized}` : this.prefix;
|
|
164
|
+
}
|
|
165
|
+
/** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
|
|
166
|
+
unkey(key) {
|
|
167
|
+
return this.prefix && key.startsWith(`${this.prefix}/`) ? key.slice(this.prefix.length + 1) : key;
|
|
168
|
+
}
|
|
169
|
+
directoryPrefix(directory) {
|
|
170
|
+
const key = this.key(directory);
|
|
171
|
+
return key ? `${key}/` : "";
|
|
172
|
+
}
|
|
173
|
+
assertVisibility(requested, operation) {
|
|
174
|
+
if (requested && requested !== this.diskVisibility) throw new Error(`R2Driver.${operation}: cannot make an object ${requested} on a ${this.diskVisibility} bucket. R2 has no per-object visibility — access is decided per bucket (custom domain / r2.dev). Declare the bucket’s visibility with the driver’s "visibility" option, or serve private files through a signed app route.`);
|
|
175
|
+
}
|
|
176
|
+
async put(path, content, options) {
|
|
177
|
+
this.assertVisibility(options?.visibility, "put");
|
|
178
|
+
const putOptions = {};
|
|
179
|
+
if (options?.contentType) putOptions.httpMetadata = { contentType: options.contentType };
|
|
180
|
+
if (options?.metadata) putOptions.customMetadata = options.metadata;
|
|
181
|
+
await this.bucket().put(this.key(path), content, putOptions);
|
|
182
|
+
return trimSlashes(path);
|
|
183
|
+
}
|
|
184
|
+
async putFile(_path, _localPath, _options) {
|
|
185
|
+
throw new Error("R2Driver.putFile is not supported: Workers has no filesystem to read from. Read the file yourself and call put().");
|
|
186
|
+
}
|
|
187
|
+
async get(path) {
|
|
188
|
+
const object = await this.bucket().get(this.key(path));
|
|
189
|
+
if (!object) return null;
|
|
190
|
+
return Buffer.from(await object.arrayBuffer());
|
|
191
|
+
}
|
|
192
|
+
async getAsString(path) {
|
|
193
|
+
const object = await this.bucket().get(this.key(path));
|
|
194
|
+
return object ? object.text() : null;
|
|
195
|
+
}
|
|
196
|
+
async exists(path) {
|
|
197
|
+
return await this.bucket().head(this.key(path)) !== null;
|
|
198
|
+
}
|
|
199
|
+
async delete(path) {
|
|
200
|
+
const bucket = this.bucket();
|
|
201
|
+
const key = this.key(path);
|
|
202
|
+
if (await bucket.head(key) === null) return false;
|
|
203
|
+
await bucket.delete(key);
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
async deleteMany(paths) {
|
|
207
|
+
return this.deleteKeys(paths.map((path) => this.key(path)));
|
|
208
|
+
}
|
|
209
|
+
async deleteKeys(rawKeys) {
|
|
210
|
+
const keys = Array.from(new Set(rawKeys));
|
|
211
|
+
if (keys.length === 0) return 0;
|
|
212
|
+
const bucket = this.bucket();
|
|
213
|
+
const batches = [];
|
|
214
|
+
for (let index = 0; index < keys.length; index += DELETE_BATCH_SIZE) batches.push(keys.slice(index, index + DELETE_BATCH_SIZE));
|
|
215
|
+
for (let index = 0; index < batches.length; index += DELETE_CONCURRENCY) await Promise.all(batches.slice(index, index + DELETE_CONCURRENCY).map((batch) => bucket.delete(batch)));
|
|
216
|
+
return keys.length;
|
|
217
|
+
}
|
|
218
|
+
async copy(from, to) {
|
|
219
|
+
const bucket = this.bucket();
|
|
220
|
+
const source = await bucket.get(this.key(from));
|
|
221
|
+
if (!source) throw new Error(`File not found: ${from}`);
|
|
222
|
+
const options = {};
|
|
223
|
+
if (source.httpMetadata) options.httpMetadata = source.httpMetadata;
|
|
224
|
+
if (source.customMetadata) options.customMetadata = source.customMetadata;
|
|
225
|
+
await bucket.put(this.key(to), source.body, options);
|
|
226
|
+
return trimSlashes(to);
|
|
227
|
+
}
|
|
228
|
+
async move(from, to) {
|
|
229
|
+
const destination = await this.copy(from, to);
|
|
230
|
+
await this.bucket().delete(this.key(from));
|
|
231
|
+
return destination;
|
|
232
|
+
}
|
|
233
|
+
url(path) {
|
|
234
|
+
if (!this.publicUrl) throw new Error("R2Driver.url() requires the \"publicUrl\" option (the bucket’s custom domain or r2.dev subdomain). R2 has no derivable public URL.");
|
|
235
|
+
return `${this.publicUrl}/${encodeKey(this.key(path))}`;
|
|
236
|
+
}
|
|
237
|
+
async temporaryUrl(path, expiration) {
|
|
238
|
+
if (!this.presign) throw new Error("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.");
|
|
239
|
+
const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
|
|
240
|
+
if (expiresIn > MAX_PRESIGN_SECONDS) throw new Error(`R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`);
|
|
241
|
+
return presignGetUrl({
|
|
242
|
+
url: `https://${this.presign.accountId}.r2.cloudflarestorage.com/${this.presign.bucket}/${encodeKey(this.key(path))}`,
|
|
243
|
+
accessKeyId: this.presign.accessKeyId,
|
|
244
|
+
secretAccessKey: this.presign.secretAccessKey,
|
|
245
|
+
region: "auto",
|
|
246
|
+
service: "s3",
|
|
247
|
+
expiresIn: Math.max(1, expiresIn)
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
async size(path) {
|
|
251
|
+
return (await this.metadataOrFail(path)).size;
|
|
252
|
+
}
|
|
253
|
+
async lastModified(path) {
|
|
254
|
+
return (await this.metadataOrFail(path)).lastModified;
|
|
255
|
+
}
|
|
256
|
+
async metadataOrFail(path) {
|
|
257
|
+
const metadata = await this.metadata(path);
|
|
258
|
+
if (!metadata) throw new Error(`File not found: ${path}`);
|
|
259
|
+
return metadata;
|
|
260
|
+
}
|
|
261
|
+
async metadata(path) {
|
|
262
|
+
const object = await this.bucket().head(this.key(path));
|
|
263
|
+
if (!object) return null;
|
|
264
|
+
return {
|
|
265
|
+
path: trimSlashes(path),
|
|
266
|
+
size: object.size,
|
|
267
|
+
lastModified: object.uploaded,
|
|
268
|
+
contentType: object.httpMetadata?.contentType,
|
|
269
|
+
visibility: this.diskVisibility,
|
|
270
|
+
metadata: object.customMetadata
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
async files(directory) {
|
|
274
|
+
return this.collectFiles({
|
|
275
|
+
prefix: this.directoryPrefix(directory),
|
|
276
|
+
delimiter: "/"
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
async directories(directory) {
|
|
280
|
+
const result = [];
|
|
281
|
+
for await (const page of this.pages({
|
|
282
|
+
prefix: this.directoryPrefix(directory),
|
|
283
|
+
delimiter: "/"
|
|
284
|
+
})) for (const prefix of page.delimitedPrefixes) {
|
|
285
|
+
const relative = trimTrailingSlashes(this.unkey(prefix));
|
|
286
|
+
if (relative) result.push(relative);
|
|
287
|
+
}
|
|
288
|
+
return result.sort();
|
|
289
|
+
}
|
|
290
|
+
async allFiles(directory) {
|
|
291
|
+
return this.collectFiles({ prefix: this.directoryPrefix(directory) });
|
|
292
|
+
}
|
|
293
|
+
/** App-relative paths of every listed object, minus folder markers. */
|
|
294
|
+
async collectFiles(options) {
|
|
295
|
+
const result = [];
|
|
296
|
+
for await (const object of this.objects(options)) if (!object.key.endsWith("/")) result.push(this.unkey(object.key));
|
|
297
|
+
return result.sort();
|
|
298
|
+
}
|
|
299
|
+
async *objects(options) {
|
|
300
|
+
for await (const page of this.pages(options)) yield* page.objects;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Follows `cursor` until `truncated` is false. A single `list()` call is
|
|
304
|
+
* capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
|
|
305
|
+
* silently truncates larger directories.
|
|
306
|
+
*/
|
|
307
|
+
async *pages(options) {
|
|
308
|
+
const bucket = this.bucket();
|
|
309
|
+
let cursor;
|
|
310
|
+
do {
|
|
311
|
+
const page = await bucket.list(cursor ? {
|
|
312
|
+
...options,
|
|
313
|
+
cursor
|
|
314
|
+
} : options);
|
|
315
|
+
yield page;
|
|
316
|
+
cursor = page.truncated ? page.cursor : void 0;
|
|
317
|
+
} while (cursor);
|
|
318
|
+
}
|
|
319
|
+
async makeDirectory(path) {
|
|
320
|
+
const normalized = trimSlashes(path);
|
|
321
|
+
if (!normalized) return;
|
|
322
|
+
await this.bucket().put(`${this.key(normalized)}/`, "");
|
|
323
|
+
}
|
|
324
|
+
async deleteDirectory(path) {
|
|
325
|
+
const bucket = this.bucket();
|
|
326
|
+
for await (const page of this.pages({ prefix: this.directoryPrefix(path) })) if (page.objects.length > 0) await bucket.delete(page.objects.map((object) => object.key));
|
|
327
|
+
}
|
|
328
|
+
async setVisibility(path, visibility) {
|
|
329
|
+
this.assertVisibility(visibility, "setVisibility");
|
|
330
|
+
await this.metadataOrFail(path);
|
|
331
|
+
}
|
|
332
|
+
async getVisibility(path) {
|
|
333
|
+
await this.metadataOrFail(path);
|
|
334
|
+
return this.diskVisibility;
|
|
335
|
+
}
|
|
336
|
+
/** The key prefix (for tests and diagnostics). */
|
|
337
|
+
getPrefix() {
|
|
338
|
+
return this.prefix;
|
|
339
|
+
}
|
|
351
340
|
};
|
|
341
|
+
/** Percent-encode a key for the S3 URL path, keeping `/` as a separator. */
|
|
352
342
|
function encodeKey(key) {
|
|
353
|
-
|
|
343
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
354
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Twins of `@guren/server`'s `support/trim-slashes` (not exported from the
|
|
347
|
+
* package): regex-free so request-derived paths cannot make them backtrack.
|
|
348
|
+
*/
|
|
355
349
|
function trimTrailingSlashes(value) {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
350
|
+
let end = value.length;
|
|
351
|
+
while (end > 0 && value[end - 1] === "/") end--;
|
|
352
|
+
return value.slice(0, end);
|
|
359
353
|
}
|
|
360
354
|
function trimSlashes(value) {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
355
|
+
let start = 0;
|
|
356
|
+
let end = value.length;
|
|
357
|
+
while (start < end && value[start] === "/") start++;
|
|
358
|
+
while (end > start && value[end - 1] === "/") end--;
|
|
359
|
+
return value.slice(start, end);
|
|
366
360
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
}
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region src/index.ts
|
|
363
|
+
const factory = definePlugin({
|
|
364
|
+
name: "cloudflare",
|
|
365
|
+
register() {}
|
|
373
366
|
});
|
|
367
|
+
/**
|
|
368
|
+
* Register the Cloudflare plugin.
|
|
369
|
+
*
|
|
370
|
+
* @example
|
|
371
|
+
* ```typescript
|
|
372
|
+
* createApp({ providers: [cloudflarePlugin()] })
|
|
373
|
+
* ```
|
|
374
|
+
*/
|
|
374
375
|
function cloudflarePlugin(config = {}) {
|
|
375
|
-
|
|
376
|
+
return factory(config);
|
|
376
377
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
buildCloudflareOutput,
|
|
380
|
-
captureWorkersEnv,
|
|
381
|
-
cloudflarePlugin,
|
|
382
|
-
createWorkersHandler,
|
|
383
|
-
flattenD1Migrations,
|
|
384
|
-
getWorkersEnv,
|
|
385
|
-
resetWorkersEnv
|
|
386
|
-
};
|
|
378
|
+
//#endregion
|
|
379
|
+
export { R2Driver, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
|