@hamur/blob 0.0.0-stage → 0.0.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.
Files changed (43) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +51 -2
  3. package/dist/src/client/index.js +158 -0
  4. package/dist/src/index.js +220 -0
  5. package/dist/src/server/index.js +498 -0
  6. package/dist/types/src/build/setup.d.ts +7 -0
  7. package/dist/types/src/client/index.d.ts +28 -0
  8. package/dist/types/src/drivers/cloudflare-r2.d.ts +75 -0
  9. package/dist/types/src/drivers/fs.d.ts +14 -0
  10. package/dist/types/src/drivers/s3.d.ts +12 -0
  11. package/dist/types/src/drivers/suite.d.ts +9 -0
  12. package/dist/types/src/index.d.ts +2 -0
  13. package/dist/types/src/module.d.ts +3 -0
  14. package/dist/types/src/options.d.ts +19 -0
  15. package/dist/types/src/runtime/choose.d.ts +3 -0
  16. package/dist/types/src/runtime/driver.d.ts +29 -0
  17. package/dist/types/src/runtime/mime.d.ts +6 -0
  18. package/dist/types/src/runtime/multipart.d.ts +34 -0
  19. package/dist/types/src/runtime/store.d.ts +10 -0
  20. package/dist/types/src/server/blob.d.ts +3 -0
  21. package/dist/types/src/server/ensure.d.ts +22 -0
  22. package/dist/types/src/server/index.d.ts +12 -0
  23. package/dist/types/src/types.d.ts +152 -0
  24. package/package.json +41 -4
  25. package/src/build/setup.ts +137 -0
  26. package/src/client/index.ts +206 -0
  27. package/src/drivers/cloudflare-r2.ts +232 -0
  28. package/src/drivers/fs.ts +398 -0
  29. package/src/drivers/s3.ts +311 -0
  30. package/src/drivers/suite.ts +314 -0
  31. package/src/env.d.ts +16 -0
  32. package/src/index.ts +10 -0
  33. package/src/module.ts +11 -0
  34. package/src/options.ts +102 -0
  35. package/src/runtime/choose.ts +18 -0
  36. package/src/runtime/driver.ts +82 -0
  37. package/src/runtime/mime.ts +18 -0
  38. package/src/runtime/multipart.ts +319 -0
  39. package/src/runtime/store.ts +190 -0
  40. package/src/server/blob.ts +26 -0
  41. package/src/server/ensure.ts +52 -0
  42. package/src/server/index.ts +20 -0
  43. package/src/types.ts +155 -0
@@ -0,0 +1,498 @@
1
+ // @bun
2
+ // packages/blob/src/server/blob.ts
3
+ import { bodyLimit, config, drivers, preset, prerender } from "#hamur/blob/config";
4
+ import { readSecret as readSecret2 } from "hamur/server/internal";
5
+
6
+ // packages/blob/src/runtime/choose.ts
7
+ function chooseDriver(prerendering, config, prerender) {
8
+ const chosen = prerendering ? prerender : config;
9
+ if (!chosen)
10
+ throw new Error("@hamur/blob has no driver for this preset; set blob.driver");
11
+ if (prerendering && chosen.driver === "cloudflare-r2") {
12
+ throw new Error('@hamur/blob: the "cloudflare-r2" driver cannot run in the prerender (it runs on: cloudflare); set blob.dev');
13
+ }
14
+ return chosen;
15
+ }
16
+
17
+ // packages/blob/src/runtime/multipart.ts
18
+ import { createError as createError4, isHamurError, readBodyBytes } from "hamur/server";
19
+ import { isEnvRef, readSecret } from "hamur/server/internal";
20
+ import { contentType as defaultContentType2 } from "hamur/server/http";
21
+
22
+ // packages/blob/src/server/ensure.ts
23
+ import { createError } from "hamur/server";
24
+
25
+ // packages/blob/src/runtime/mime.ts
26
+ var TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
27
+ var QUOTED = '"(?:[\\x20\\x21\\x23-\\x2b\\x2d-\\x5b\\x5d-\\x7e]|\\\\[\\x20-\\x7e])*"';
28
+ var PARAM = `[ \\t]*;[ \\t]*(${TOKEN})=(${TOKEN}|${QUOTED})`;
29
+ var TYPE = new RegExp(`^[ \\t]*(${TOKEN})/(${TOKEN})((?:${PARAM})*)[ \\t]*$`);
30
+ var PARAMS = new RegExp(PARAM, "g");
31
+ function parseContentType(value) {
32
+ if (value.includes(","))
33
+ return;
34
+ const match = TYPE.exec(value);
35
+ if (!match)
36
+ return;
37
+ const params = [...match[3].matchAll(PARAMS)].map(([, name, param]) => `; ${name.toLowerCase()}=${param}`).join("");
38
+ return `${match[1].toLowerCase()}/${match[2].toLowerCase()}${params}`;
39
+ }
40
+
41
+ // packages/blob/src/server/ensure.ts
42
+ var UNITS = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3 };
43
+ function parseSize(size) {
44
+ if (typeof size === "number" && Number.isFinite(size) && size >= 0)
45
+ return { bytes: size, unit: "B", shown: `${size}B` };
46
+ const match = typeof size === "string" ? /^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/.exec(size) : null;
47
+ if (!match)
48
+ throw new TypeError(`ensureBlob maxSize must be a number of bytes or a size such as "8MB" (got ${JSON.stringify(size)})`);
49
+ const unit = match[2];
50
+ return { bytes: Number(match[1]) * UNITS[unit], unit, shown: size };
51
+ }
52
+ var shownSize = (bytes, unit) => unit === "B" ? `${bytes}B` : `${(bytes / UNITS[unit]).toFixed(1)}${unit}`;
53
+ function ensureBlob(blob, options) {
54
+ if (options?.maxSize === undefined && options?.types === undefined)
55
+ throw new TypeError("ensureBlob needs maxSize or types");
56
+ if (options.maxSize !== undefined) {
57
+ const max = parseSize(options.maxSize);
58
+ if (blob.size > max.bytes)
59
+ throw createError({ status: 400, message: `File size ${shownSize(blob.size, max.unit)} is over ${max.shown}` });
60
+ }
61
+ if (options.types !== undefined) {
62
+ const given = "contentType" in blob ? blob.contentType : blob.type;
63
+ const parsed = given ? parseContentType(given) : "application/octet-stream";
64
+ const type = parsed?.split(";")[0];
65
+ const allowed = type !== undefined && options.types.some((entry) => {
66
+ const wanted = entry.toLowerCase();
67
+ return wanted.includes("/") ? type === wanted : type.split("/")[0] === wanted;
68
+ });
69
+ if (!allowed)
70
+ throw createError({
71
+ status: 400,
72
+ message: `File type ${type ?? given} is not allowed (allowed: ${options.types.join(", ")})`
73
+ });
74
+ }
75
+ }
76
+
77
+ // packages/blob/src/runtime/driver.ts
78
+ import { createError as createError2 } from "hamur/server";
79
+ var invalidPathname = (pathname) => new TypeError(`Invalid blob pathname ${JSON.stringify(String(pathname))}`);
80
+ var uploadNotFound = () => createError2({ status: 404, message: "Upload not found" });
81
+ var invalidUpload = (cause) => createError2({ status: 400, message: "Invalid upload request", ...cause === undefined ? {} : { cause } });
82
+ var PART_SIZE = 10 * 1024 * 1024;
83
+
84
+ // packages/blob/src/runtime/store.ts
85
+ import { createError as createError3 } from "hamur/server";
86
+ import { contentType as defaultContentType, matchesETag, parseRange } from "hamur/server/http";
87
+ var MAX_PATHNAME_BYTES = 1024;
88
+ var METADATA_KEY = /^[a-z0-9-]+$/;
89
+ var METADATA_VALUE = /^(?:[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?)?$/;
90
+ var METADATA_BYTES = 2048;
91
+ var SANDBOX = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
92
+ var CACHE_CONTROL = "private, no-cache";
93
+ var READ_TRIES = 3;
94
+ var encoder = new TextEncoder;
95
+ function checkPathname(pathname) {
96
+ const path = typeof pathname === "string" ? pathname.replace(/^\//, "") : "";
97
+ const valid = path !== "" && path.isWellFormed() && encoder.encode(path).length <= MAX_PATHNAME_BYTES && !/[\\\0]/.test(path) && path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
98
+ if (!valid)
99
+ throw invalidPathname(pathname);
100
+ return path;
101
+ }
102
+ function checkPrefix(prefix) {
103
+ if (prefix === undefined || prefix === "" || prefix === "/")
104
+ return "";
105
+ const path = prefix.replace(/^\//, "");
106
+ checkPathname(path.endsWith("/") ? path.slice(0, -1) : path);
107
+ return path;
108
+ }
109
+ function checkMetadata(metadata) {
110
+ const checked = {};
111
+ let bytes = 0;
112
+ for (const [key, value] of Object.entries(metadata ?? {})) {
113
+ if (!METADATA_KEY.test(key))
114
+ throw new TypeError(`Invalid customMetadata key ${JSON.stringify(key)}: use a-z, 0-9 and "-"`);
115
+ if (typeof value !== "string" || !METADATA_VALUE.test(value)) {
116
+ throw new TypeError(`Invalid customMetadata value for ${JSON.stringify(key)}: use printable ASCII with no leading or trailing space`);
117
+ }
118
+ bytes += key.length + value.length;
119
+ checked[key] = value;
120
+ }
121
+ if (bytes > METADATA_BYTES)
122
+ throw new TypeError(`customMetadata is ${bytes} bytes; keys and values together may hold at most ${METADATA_BYTES} (S3's limit)`);
123
+ return checked;
124
+ }
125
+ function checkContentType(type) {
126
+ const parsed = parseContentType(type);
127
+ if (!parsed)
128
+ throw new TypeError(`Invalid blob content type ${JSON.stringify(type)}: use one type/subtype with optional ; parameters`);
129
+ return parsed;
130
+ }
131
+ function randomSuffix() {
132
+ const bytes = crypto.getRandomValues(new Uint8Array(8));
133
+ return Array.from(bytes, (byte) => (byte % 36).toString(36)).join("");
134
+ }
135
+ function withRandomSuffix(pathname) {
136
+ const slash = pathname.lastIndexOf("/");
137
+ const dot = pathname.lastIndexOf(".");
138
+ const at = dot > slash + 1 ? dot : pathname.length;
139
+ return `${pathname.slice(0, at)}-${randomSuffix()}${pathname.slice(at)}`;
140
+ }
141
+ function normalizeBody(body) {
142
+ if (typeof body === "string")
143
+ return encoder.encode(body);
144
+ if (body instanceof ArrayBuffer)
145
+ return new Uint8Array(body);
146
+ if (body instanceof Uint8Array || body instanceof Blob || body instanceof ReadableStream)
147
+ return body;
148
+ throw new TypeError("blob put takes a string, ArrayBuffer, Uint8Array, Blob or ReadableStream body");
149
+ }
150
+ function createBlobStore(driver) {
151
+ async function serve(event, pathname, options = {}) {
152
+ const path = checkPathname(pathname);
153
+ const backend = await driver();
154
+ const request = event.request;
155
+ for (let attempt = 1;; attempt++) {
156
+ const object = await backend.head(path);
157
+ if (!object)
158
+ throw createError3({ status: 404, message: "Blob not found" });
159
+ const headers = new Headers({
160
+ "content-type": object.contentType,
161
+ etag: object.etag,
162
+ "last-modified": object.uploadedAt.toUTCString(),
163
+ "accept-ranges": "bytes",
164
+ "cache-control": options.cacheControl ?? CACHE_CONTROL,
165
+ "content-security-policy": SANDBOX,
166
+ "x-content-type-options": "nosniff"
167
+ });
168
+ const ifNoneMatch = request.headers.get("if-none-match");
169
+ const ifModifiedSince = ifNoneMatch === null ? Date.parse(request.headers.get("if-modified-since") ?? "") : Number.NaN;
170
+ if (matchesETag(ifNoneMatch, object.etag) || Math.floor(object.uploadedAt.getTime() / 1000) <= Math.floor(ifModifiedSince / 1000)) {
171
+ headers.delete("content-type");
172
+ return new Response(null, { status: 304, headers });
173
+ }
174
+ const range = request.headers.has("if-range") ? undefined : parseRange(request.headers.get("range"), object.size);
175
+ if (range === "unsatisfiable") {
176
+ headers.delete("content-type");
177
+ headers.set("content-range", `bytes */${object.size}`);
178
+ return new Response(null, { status: 416, headers });
179
+ }
180
+ if (range) {
181
+ headers.set("content-range", `bytes ${range.start}-${range.end}/${object.size}`);
182
+ headers.set("content-length", String(range.end - range.start + 1));
183
+ } else {
184
+ headers.set("content-length", String(object.size));
185
+ }
186
+ const status = range ? 206 : 200;
187
+ if (request.method === "HEAD")
188
+ return new Response(null, { status, headers });
189
+ const body = await backend.open(path, object.etag, range);
190
+ if (body === undefined)
191
+ throw createError3({ status: 404, message: "Blob not found" });
192
+ if (body !== "changed")
193
+ return new Response(body, { status, headers });
194
+ if (attempt === READ_TRIES)
195
+ throw createError3({ status: 503, message: "Blob changed while it was read" });
196
+ }
197
+ }
198
+ return {
199
+ async put(pathname, body, options = {}) {
200
+ let path = checkPathname(pathname);
201
+ if (options.addRandomSuffix)
202
+ path = checkPathname(withRandomSuffix(path));
203
+ const value = normalizeBody(body);
204
+ const given = options.contentType || value instanceof Blob && value.type || "";
205
+ const type = given ? checkContentType(given) : defaultContentType(path);
206
+ return (await driver()).put(path, value, {
207
+ contentType: type,
208
+ customMetadata: checkMetadata(options.customMetadata)
209
+ });
210
+ },
211
+ async get(pathname) {
212
+ return (await driver()).get(checkPathname(pathname));
213
+ },
214
+ async head(pathname) {
215
+ return (await driver()).head(checkPathname(pathname));
216
+ },
217
+ async list(options = {}) {
218
+ const limit = options.limit ?? 1000;
219
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
220
+ throw new TypeError(`blob list limit must be an integer from 1 to 1000 (got ${limit})`);
221
+ return (await driver()).list({
222
+ prefix: checkPrefix(options.prefix),
223
+ limit,
224
+ folded: options.folded === true,
225
+ ...options.cursor ? { cursor: options.cursor } : {}
226
+ });
227
+ },
228
+ async delete(pathnames) {
229
+ const paths = (Array.isArray(pathnames) ? pathnames : [pathnames]).map(checkPathname);
230
+ if (paths.length)
231
+ await (await driver()).delete(paths);
232
+ },
233
+ serve,
234
+ async presign(pathname, options) {
235
+ const path = checkPathname(pathname);
236
+ const { method, expiresIn = 3600, contentType } = options;
237
+ if (method !== "GET" && method !== "PUT")
238
+ throw new TypeError(`presign method must be "GET" or "PUT" (got ${JSON.stringify(method)})`);
239
+ if (method === "GET") {
240
+ if (contentType !== undefined)
241
+ throw new TypeError("presign contentType is signed on a PUT only: a GET sends no body");
242
+ return (await driver()).presign(path, { method, expiresIn });
243
+ }
244
+ if (contentType !== undefined && checkContentType(contentType) !== contentType) {
245
+ throw new TypeError(`Invalid presign content type ${JSON.stringify(contentType)}: pass ${JSON.stringify(checkContentType(contentType))}, the form that is signed`);
246
+ }
247
+ return (await driver()).presign(path, { method, expiresIn, contentType: contentType ?? defaultContentType(path) });
248
+ }
249
+ };
250
+ }
251
+
252
+ // packages/blob/src/runtime/multipart.ts
253
+ var MAX_PARTS = 1e4;
254
+ var MIN_PART_SIZE = 5 * 1024 * 1024;
255
+ var MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;
256
+ var DEFAULT_PART_SIZE = 10 * 1024 * 1024;
257
+ var MIN_SECRET_LENGTH = 32;
258
+ var TOKEN_LIFETIME_MS = 24 * 60 * 60 * 1000;
259
+ var TOKEN_LABEL = "hamur blob multipart upload token";
260
+ var BODY_LIMITS = {
261
+ vercel: "is over the function's 4.5 MB request body",
262
+ netlify: "is within 1 MB of the function's 6 MB request body"
263
+ };
264
+ var STEP_METHODS = { create: "POST", complete: "POST", abort: "DELETE" };
265
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
266
+ var isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
267
+ var isPartNumber = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_PARTS;
268
+ var encoder2 = new TextEncoder;
269
+ var base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
270
+ function fromBase64url(text) {
271
+ if (!/^[A-Za-z0-9_-]*$/.test(text))
272
+ return;
273
+ let bytes;
274
+ try {
275
+ bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
276
+ } catch {
277
+ return;
278
+ }
279
+ return base64url(bytes) === text ? bytes : undefined;
280
+ }
281
+ var keys = new Map;
282
+ function tokenKey(secret) {
283
+ let key = keys.get(secret);
284
+ if (!key) {
285
+ key = (async () => {
286
+ const root = await crypto.subtle.importKey("raw", encoder2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
287
+ const derived = await crypto.subtle.sign("HMAC", root, encoder2.encode(TOKEN_LABEL));
288
+ return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
289
+ })();
290
+ keys.set(secret, key);
291
+ }
292
+ return key;
293
+ }
294
+ async function signToken(secret, upload) {
295
+ const payload = base64url(encoder2.encode(JSON.stringify([upload.pathname, upload.size, upload.partSize, upload.uploadId, upload.expires])));
296
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", await tokenKey(secret), encoder2.encode(payload)));
297
+ return `${payload}.${base64url(signature)}`;
298
+ }
299
+ async function readToken(secret, token, pathname) {
300
+ if (typeof token !== "string" || token === "")
301
+ throw invalidUpload();
302
+ const dot = token.lastIndexOf(".");
303
+ const signature = fromBase64url(token.slice(dot + 1));
304
+ const payload = dot < 1 ? undefined : fromBase64url(token.slice(0, dot));
305
+ if (!payload || !signature || !await crypto.subtle.verify("HMAC", await tokenKey(secret), signature, encoder2.encode(token.slice(0, dot))))
306
+ throw uploadNotFound();
307
+ const [stored, size, partSize, uploadId, expires] = JSON.parse(new TextDecoder().decode(payload));
308
+ if (stored !== pathname || Date.now() >= expires)
309
+ throw uploadNotFound();
310
+ return { pathname: stored, size, partSize, uploadId, expires };
311
+ }
312
+ var partCount = (upload) => Math.max(1, Math.ceil(upload.size / upload.partSize));
313
+ var partBytes = (upload, partNumber) => partNumber < partCount(upload) ? upload.partSize : upload.size - (partCount(upload) - 1) * upload.partSize;
314
+ async function readJson(event) {
315
+ const bytes = await readBodyBytes(event);
316
+ try {
317
+ const value = JSON.parse(new TextDecoder().decode(bytes ?? new Uint8Array(0)));
318
+ if (isObject(value))
319
+ return value;
320
+ } catch {}
321
+ throw invalidUpload();
322
+ }
323
+ var warned = new Set;
324
+ function uploadSecret(event, option) {
325
+ if (typeof option !== "string" && !isEnvRef(option))
326
+ throw new TypeError('handleMultipartUpload secret must be a string or env("NAME")');
327
+ const key = typeof option === "string" ? "secret" : `env ${JSON.stringify(option["~env"])}`;
328
+ let value;
329
+ try {
330
+ value = readSecret(option, "handleMultipartUpload secret");
331
+ } catch {}
332
+ if (value !== undefined && value.length >= MIN_SECRET_LENGTH)
333
+ return value;
334
+ if (!warned.has(key)) {
335
+ warned.add(key);
336
+ event.log.error(`handleMultipartUpload needs ${key} (at least ${MIN_SECRET_LENGTH} characters)`);
337
+ }
338
+ throw createError4({ status: 503, message: "Upload endpoint is not configured" });
339
+ }
340
+ function createMultipartUpload(driver, { preset, bodyLimit }) {
341
+ return async function handleMultipartUpload(event, options) {
342
+ const { action, direct = false, expiresIn = 900 } = options;
343
+ if (!direct && preset !== null && BODY_LIMITS[preset]) {
344
+ throw new Error(`handleMultipartUpload on the ${preset} preset needs direct: true: a part of at least 5 MiB ${BODY_LIMITS[preset]}`);
345
+ }
346
+ const backend = await driver();
347
+ if (direct && backend.name !== "s3")
348
+ throw new Error(`handleMultipartUpload direct: true needs the s3 driver (blob.driver is "${backend.name}")`);
349
+ const method = action === "upload" ? direct ? "POST" : "PUT" : Object.hasOwn(STEP_METHODS, action) ? STEP_METHODS[action] : undefined;
350
+ if (!method)
351
+ throw createError4({ status: 404, message: `Unknown upload step ${JSON.stringify(action)}` });
352
+ if (event.request.method !== method) {
353
+ event.response.headers.set("allow", method);
354
+ throw createError4({ status: 405, message: `The upload step ${JSON.stringify(action)} takes ${method}` });
355
+ }
356
+ const secret = uploadSecret(event, options.secret);
357
+ const stored = (name) => {
358
+ if (typeof name !== "string")
359
+ throw invalidUpload();
360
+ let checked;
361
+ try {
362
+ checked = checkPathname(name);
363
+ } catch (error) {
364
+ throw createError4({ status: 400, message: error.message });
365
+ }
366
+ try {
367
+ return checkPathname(options.pathname ? options.pathname(checked) : checked);
368
+ } catch (error) {
369
+ if (isHamurError(error))
370
+ throw error;
371
+ throw createError4({ status: 500, cause: error });
372
+ }
373
+ };
374
+ if (action === "create") {
375
+ const body = await readJson(event);
376
+ if (typeof body.pathname !== "string" || body.contentType !== undefined && typeof body.contentType !== "string")
377
+ throw invalidUpload();
378
+ if (!isCount(body.size))
379
+ throw createError4({ status: 400, message: "create needs size (the file's bytes)" });
380
+ const size = body.size;
381
+ const partSize = body.partSize ?? DEFAULT_PART_SIZE;
382
+ if (!isCount(partSize) || partSize < MIN_PART_SIZE || partSize > MAX_PART_SIZE) {
383
+ throw createError4({
384
+ status: 400,
385
+ message: `create partSize must be a whole number of bytes from 5 MiB to 5 GiB (got ${JSON.stringify(partSize)})`
386
+ });
387
+ }
388
+ if (!direct && partSize > bodyLimit) {
389
+ throw createError4({
390
+ status: 400,
391
+ message: `create partSize ${partSize} is over the request body limit of ${bodyLimit} bytes${preset ? ` on the ${preset} preset` : ""}; send smaller parts, or use direct: true`
392
+ });
393
+ }
394
+ if (partCount({ size, partSize }) > MAX_PARTS)
395
+ throw createError4({
396
+ status: 400,
397
+ message: `A file of ${size} bytes needs more than ${MAX_PARTS} parts of ${partSize} bytes`
398
+ });
399
+ let name = body.pathname;
400
+ try {
401
+ name = checkPathname(name);
402
+ if (options.put?.addRandomSuffix)
403
+ name = checkPathname(withRandomSuffix(name));
404
+ } catch (error) {
405
+ throw createError4({ status: 400, message: error.message });
406
+ }
407
+ const pathname = stored(name);
408
+ const given = body.contentType || defaultContentType2(pathname);
409
+ if (options.ensure)
410
+ ensureBlob({ size, contentType: given }, options.ensure);
411
+ let contentType;
412
+ try {
413
+ contentType = checkContentType(given);
414
+ } catch (error) {
415
+ throw createError4({ status: 400, message: error.message });
416
+ }
417
+ const uploadId = await backend.multipart.create(pathname, {
418
+ contentType,
419
+ customMetadata: checkMetadata(options.put?.customMetadata)
420
+ });
421
+ const token = await signToken(secret, {
422
+ pathname,
423
+ size,
424
+ partSize,
425
+ uploadId,
426
+ expires: Date.now() + TOKEN_LIFETIME_MS
427
+ });
428
+ return Response.json({ pathname: name, uploadId: token, partSize, ...direct ? { direct: true } : {} });
429
+ }
430
+ if (action === "abort") {
431
+ const query = event.url.searchParams;
432
+ const upload = await readToken(secret, query.get("uploadId"), stored(query.get("pathname")));
433
+ await backend.multipart.abort(upload.pathname, upload.uploadId);
434
+ return new Response(null, { status: 204 });
435
+ }
436
+ if (action === "upload" && !direct) {
437
+ const query = event.url.searchParams;
438
+ const upload = await readToken(secret, query.get("uploadId"), stored(query.get("pathname")));
439
+ const partNumber = Number(query.get("partNumber"));
440
+ if (!isPartNumber(partNumber) || partNumber > partCount(upload))
441
+ throw invalidUpload();
442
+ const expected = partBytes(upload, partNumber);
443
+ const bytes = await readBodyBytes(event, { maxBodySize: expected }) ?? new Uint8Array(0);
444
+ if (bytes.length !== expected)
445
+ throw invalidUpload();
446
+ const etag = await backend.multipart.uploadPart(upload.pathname, upload.uploadId, partNumber, bytes);
447
+ return Response.json({ partNumber, etag });
448
+ }
449
+ const body = await readJson(event);
450
+ const upload = await readToken(secret, body.uploadId, stored(body.pathname));
451
+ if (action === "upload") {
452
+ if (!isPartNumber(body.partNumber) || body.partNumber > partCount(upload) || body.size !== partBytes(upload, body.partNumber))
453
+ throw invalidUpload();
454
+ const query = { partNumber: String(body.partNumber), uploadId: upload.uploadId };
455
+ const url = await backend.presign(upload.pathname, { method: "PUT", expiresIn, contentLength: body.size, query });
456
+ return Response.json({ partNumber: body.partNumber, url });
457
+ }
458
+ const parts = body.parts;
459
+ if (!Array.isArray(parts) || parts.length !== partCount(upload))
460
+ throw invalidUpload();
461
+ const listed = [];
462
+ for (const [at, part] of parts.entries()) {
463
+ if (!isObject(part) || part.partNumber !== at + 1 || typeof part.etag !== "string" || part.etag === "")
464
+ throw invalidUpload();
465
+ listed.push({ partNumber: at + 1, etag: part.etag });
466
+ }
467
+ return Response.json(await backend.multipart.complete(upload.pathname, upload.uploadId, listed));
468
+ };
469
+ }
470
+
471
+ // packages/blob/src/server/blob.ts
472
+ var secret = (option, value) => value === undefined ? undefined : readSecret2(value, `blob.${option}`);
473
+ var opened;
474
+ function openDriver() {
475
+ return opened ??= (async () => {
476
+ const chosen = chooseDriver(import.meta.prerender === true, config, prerender);
477
+ const { default: open } = await drivers[chosen.driver]();
478
+ return open(chosen, secret);
479
+ })().catch((error) => {
480
+ opened = undefined;
481
+ throw error;
482
+ });
483
+ }
484
+ var store = createBlobStore(openDriver);
485
+ var multipartUpload = createMultipartUpload(openDriver, { preset, bodyLimit });
486
+
487
+ // packages/blob/src/server/index.ts
488
+ function useBlob() {
489
+ return store;
490
+ }
491
+ function handleMultipartUpload(event, options) {
492
+ return multipartUpload(event, options);
493
+ }
494
+ export {
495
+ ensureBlob,
496
+ handleMultipartUpload,
497
+ useBlob
498
+ };
@@ -0,0 +1,7 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import { type ResolvedBlobOptions } from "../options.ts";
3
+ import type { ResolvedBlobDriver } from "../types.ts";
4
+ /** The preset's own store when `blob` names no driver; none on vercel and netlify, whose file systems keep nothing. */
5
+ export declare function presetDefault(preset: string): ResolvedBlobDriver | undefined;
6
+ /** The driver per run (`dev` under `hamur dev` and the prerender), the preset checks, the import guard and `#hamur/blob/config`. */
7
+ export declare function setupBlob(options: ResolvedBlobOptions, hamur: HamurContext): void;
@@ -0,0 +1,28 @@
1
+ import type { BlobObject } from "../types.ts";
2
+ export interface MultipartUploadClientOptions {
3
+ /** Bytes per part, 5 MiB to 5 GiB (S3's limits); the last part may be smaller. Default 10 MiB. */
4
+ partSize?: number;
5
+ /** Parts in flight at once, default 1. */
6
+ concurrency?: number;
7
+ }
8
+ export interface MultipartFileOptions {
9
+ /** The name sent at `create`, default the file's name; the handler maps it to the stored pathname. */
10
+ pathname?: string;
11
+ /** Called after each part is stored: the bytes of the stored parts, and the file's size. */
12
+ onProgress?: (sent: number, total: number) => void;
13
+ }
14
+ export interface MultipartUpload {
15
+ completed: Promise<BlobObject>;
16
+ /**
17
+ * Before `complete` is sent: stops the parts in flight, removes the upload's stored parts, and `completed` rejects with an
18
+ * `AbortError`. Once `complete` is sent the upload is no longer stopped: it resolves when `completed` settles. It never rejects.
19
+ */
20
+ abort(): Promise<void>;
21
+ }
22
+ /**
23
+ * Uploads a file in parts through the steps of `handleMultipartUpload` at `url` (`<url>/create`, `<url>/upload`,
24
+ * `<url>/complete`, `<url>/abort`); when the handler answers a part with a storage URL, the part goes there. A part that
25
+ * fails on the network or with a 5xx is sent once more, then the upload is aborted. Plain `fetch`, no UI library: the same in
26
+ * every adapter.
27
+ */
28
+ export declare function useMultipartUpload(url: string, options?: MultipartUploadClientOptions): (file: File, fileOptions?: MultipartFileOptions) => MultipartUpload;
@@ -0,0 +1,75 @@
1
+ import { type OpenDriver } from "../runtime/driver.ts";
2
+ import type { BlobDriver, ResolvedBlobDriver } from "../types.ts";
3
+ /** The part of an R2 object the driver reads. */
4
+ export interface R2Object {
5
+ key: string;
6
+ size: number;
7
+ httpEtag: string;
8
+ uploaded: Date;
9
+ httpMetadata?: {
10
+ contentType?: string;
11
+ };
12
+ customMetadata?: Record<string, string>;
13
+ }
14
+ interface R2ObjectBody extends R2Object {
15
+ body: ReadableStream<Uint8Array>;
16
+ arrayBuffer(): Promise<ArrayBuffer>;
17
+ }
18
+ interface R2PutOptions {
19
+ httpMetadata?: {
20
+ contentType?: string;
21
+ };
22
+ customMetadata?: Record<string, string>;
23
+ }
24
+ interface R2MultipartUpload {
25
+ readonly uploadId: string;
26
+ uploadPart(partNumber: number, value: Uint8Array): Promise<{
27
+ partNumber: number;
28
+ etag: string;
29
+ }>;
30
+ complete(parts: {
31
+ partNumber: number;
32
+ etag: string;
33
+ }[]): Promise<R2Object>;
34
+ abort(): Promise<void>;
35
+ }
36
+ /** The part of an R2 bucket binding the driver uses. */
37
+ export interface R2Bucket {
38
+ head(key: string): Promise<R2Object | null>;
39
+ /** With `onlyIf` not met, the object without a `body`. */
40
+ get(key: string, options?: {
41
+ onlyIf?: {
42
+ etagMatches: string;
43
+ };
44
+ range?: {
45
+ offset: number;
46
+ length: number;
47
+ };
48
+ }): Promise<R2ObjectBody | R2Object | null>;
49
+ put(key: string, value: Uint8Array | Blob, options?: R2PutOptions): Promise<R2Object | null>;
50
+ createMultipartUpload(key: string, options?: R2PutOptions): Promise<R2MultipartUpload>;
51
+ resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;
52
+ delete(keys: string | string[]): Promise<void>;
53
+ list(options?: {
54
+ prefix?: string;
55
+ cursor?: string;
56
+ limit?: number;
57
+ delimiter?: string;
58
+ }): Promise<{
59
+ objects: R2Object[];
60
+ truncated: boolean;
61
+ cursor?: string;
62
+ delimitedPrefixes?: string[];
63
+ }>;
64
+ }
65
+ type R2Config = Extract<ResolvedBlobDriver, {
66
+ driver: "cloudflare-r2";
67
+ }>;
68
+ /**
69
+ * One object per pathname at `<base><pathname>` in the bucket `env[binding]`, its type in `httpMetadata` and its
70
+ * metadata in `customMetadata`. A stream that does not end within 10 MiB is written as a multipart upload in 10 MiB parts
71
+ * (`put` needs a known length).
72
+ */
73
+ export declare function createR2Driver(config: R2Config, env?: () => Promise<Record<string, unknown>>): BlobDriver;
74
+ export declare const openR2Driver: OpenDriver<R2Config>;
75
+ export default openR2Driver;
@@ -0,0 +1,14 @@
1
+ import { type OpenDriver } from "../runtime/driver.ts";
2
+ import type { ResolvedBlobDriver } from "../types.ts";
3
+ /**
4
+ * The metadata of a pathname at `<base>/meta/<pathname>.json` names its object file
5
+ * `<base>/objects/<pathname>.<id>.data`, each segment percent-encoded with `.` too. A put streams the bytes to a temporary
6
+ * file, renames it to a new id, then renames a temporary metadata file over the old one, and only then removes the object
7
+ * file the old metadata named: a reader sees the old pair or the new pair, never a mix, and an object file it opened keeps
8
+ * its bytes. Commits to one pathname run one at a time in the process, so a put that loses a race removes nothing it
9
+ * should keep and leaves nothing behind; processes sharing one `base` can still leave an unread object file.
10
+ */
11
+ export declare const openFsDriver: OpenDriver<Extract<ResolvedBlobDriver, {
12
+ driver: "fs";
13
+ }>>;
14
+ export default openFsDriver;
@@ -0,0 +1,12 @@
1
+ import { type OpenDriver } from "../runtime/driver.ts";
2
+ import type { ResolvedBlobDriver } from "../types.ts";
3
+ type S3Config = Extract<ResolvedBlobDriver, {
4
+ driver: "s3";
5
+ }>;
6
+ /**
7
+ * One object per pathname at `<base><pathname>`, no envelope; the type, ETag, upload time and `x-amz-meta-*` are the
8
+ * object's own. Every request is signed by `signS3Request` over `fetch`, on every preset. A stream that does not end within
9
+ * 10 MiB is written as a multipart upload in 10 MiB parts. Options not given come from `S3_*`/`AWS_*` in the environment.
10
+ */
11
+ export declare const openS3Driver: OpenDriver<S3Config>;
12
+ export default openS3Driver;
@@ -0,0 +1,9 @@
1
+ import type { BlobStore } from "../types.ts";
2
+ export interface SuiteOptions {
3
+ /** A store on a fresh base. */
4
+ make(): Promise<BlobStore>;
5
+ /** The sizes of the parts written since the last call, on drivers that write in parts. */
6
+ parts?(): number[];
7
+ }
8
+ /** Put, get, head, list with `cursor` and `folded`, delete and serve, the same on every driver. */
9
+ export declare function blobSuite(name: string, options: SuiteOptions): void;
@@ -0,0 +1,2 @@
1
+ export { default } from "./module.ts";
2
+ export type { BlobConfig, BlobList, BlobListItem, BlobObject, BlobPutOptions, BlobServeOptions, BlobStore, } from "./types.ts";
@@ -0,0 +1,3 @@
1
+ import type { BlobConfig } from "./types.ts";
2
+ declare const _default: import("hamur/kit").HamurModule<BlobConfig>;
3
+ export default _default;