qarpeo 0.1.11 → 0.1.13
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/cli/index.mjs +35 -18
- package/dist/module.mjs +5 -17
- package/dist/runtime/app/components/FileUpload.vue +5 -5
- package/dist/runtime/app/composables/storage.d.ts +47 -2
- package/dist/runtime/app/composables/storage.mjs +204 -1
- package/dist/runtime/server/utils/storage.d.ts +29 -0
- package/dist/runtime/server/utils/storage.mjs +79 -0
- package/dist/utils/cloudflare-api.d.ts +1 -0
- package/package.json +1 -1
package/dist/cli/index.mjs
CHANGED
|
@@ -842,6 +842,19 @@ async function listCloudflareWorkers(auth) {
|
|
|
842
842
|
const data = await res.json();
|
|
843
843
|
return data.result || [];
|
|
844
844
|
}
|
|
845
|
+
async function deleteCloudflareWorker(auth, workerName) {
|
|
846
|
+
const url = `https://api.cloudflare.com/client/v4/accounts/${auth.accountId}/workers/scripts/${encodeURIComponent(workerName)}?force=true`;
|
|
847
|
+
const res = await fetch(url, {
|
|
848
|
+
method: "DELETE",
|
|
849
|
+
headers: { Authorization: `Bearer ${auth.token}` }
|
|
850
|
+
});
|
|
851
|
+
if (!res.ok) {
|
|
852
|
+
const errText = await res.text();
|
|
853
|
+
throw new Error(`Failed to delete Cloudflare Worker (HTTP ${res.status}): ${errText}`);
|
|
854
|
+
}
|
|
855
|
+
const data = await res.json();
|
|
856
|
+
return data.success === true;
|
|
857
|
+
}
|
|
845
858
|
|
|
846
859
|
function getWranglerBin$1(cwd) {
|
|
847
860
|
return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
|
|
@@ -909,6 +922,7 @@ const deleteCommand = defineCommand({
|
|
|
909
922
|
async run({ args }) {
|
|
910
923
|
const cwd = resolve(process.cwd(), args.cwd);
|
|
911
924
|
loadDotEnv$3(cwd);
|
|
925
|
+
const auth = await getCloudflareAuth(cwd);
|
|
912
926
|
let workerName = args.name;
|
|
913
927
|
if (!workerName) {
|
|
914
928
|
const nameFlagIdx = process.argv.indexOf("--name");
|
|
@@ -918,7 +932,6 @@ const deleteCommand = defineCommand({
|
|
|
918
932
|
}
|
|
919
933
|
if (!workerName && stdin.isTTY) {
|
|
920
934
|
try {
|
|
921
|
-
const auth = await getCloudflareAuth(cwd);
|
|
922
935
|
if (auth) {
|
|
923
936
|
process.stdout.write("\u{1F50D} [qarpeo] Fetching deployed Workers from Cloudflare...\n");
|
|
924
937
|
const workers = await listCloudflareWorkers(auth);
|
|
@@ -980,20 +993,30 @@ const deleteCommand = defineCommand({
|
|
|
980
993
|
}
|
|
981
994
|
}
|
|
982
995
|
}
|
|
996
|
+
if (args.dryRun) {
|
|
997
|
+
console.log(`
|
|
998
|
+
\u{1F50D} [qarpeo] Dry-run completed. Worker "${workerName}" was not deleted.
|
|
999
|
+
`);
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
console.log(`
|
|
1003
|
+
\u{1F5D1}\uFE0F [qarpeo] Deleting Worker "${workerName}" from Cloudflare...`);
|
|
1004
|
+
if (auth) {
|
|
1005
|
+
try {
|
|
1006
|
+
await deleteCloudflareWorker(auth, workerName);
|
|
1007
|
+
console.log(`
|
|
1008
|
+
\u2705 [qarpeo] Successfully deleted Worker "${workerName}" from Cloudflare!
|
|
1009
|
+
`);
|
|
1010
|
+
return;
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
983
1014
|
await ensurePackage("wrangler", {
|
|
984
1015
|
cwd,
|
|
985
1016
|
purpose: "deleting Cloudflare Worker"
|
|
986
1017
|
});
|
|
987
1018
|
const wrangler = getWranglerBin$1(cwd);
|
|
988
|
-
|
|
989
|
-
\u{1F5D1}\uFE0F [qarpeo] Deleting Worker "${workerName}" from Cloudflare...`);
|
|
990
|
-
const wranglerArgs = ["delete", workerName];
|
|
991
|
-
if (args.dryRun) {
|
|
992
|
-
wranglerArgs.push("--dry-run");
|
|
993
|
-
}
|
|
994
|
-
if (args.force) {
|
|
995
|
-
wranglerArgs.push("--force");
|
|
996
|
-
}
|
|
1019
|
+
const wranglerArgs = ["delete", workerName, "--force"];
|
|
997
1020
|
if (args.env) {
|
|
998
1021
|
wranglerArgs.push("--env", args.env);
|
|
999
1022
|
}
|
|
@@ -1008,15 +1031,9 @@ const deleteCommand = defineCommand({
|
|
|
1008
1031
|
\u274C [qarpeo] Failed to delete Worker "${workerName}".`);
|
|
1009
1032
|
process.exit(result.status ?? 1);
|
|
1010
1033
|
}
|
|
1011
|
-
|
|
1012
|
-
console.log(`
|
|
1013
|
-
\u{1F50D} [qarpeo] Dry-run completed. Worker "${workerName}" was not deleted.
|
|
1014
|
-
`);
|
|
1015
|
-
} else {
|
|
1016
|
-
console.log(`
|
|
1034
|
+
console.log(`
|
|
1017
1035
|
\u2705 [qarpeo] Successfully deleted Worker "${workerName}" from Cloudflare!
|
|
1018
1036
|
`);
|
|
1019
|
-
}
|
|
1020
1037
|
}
|
|
1021
1038
|
});
|
|
1022
1039
|
|
|
@@ -2192,7 +2209,7 @@ const whoami = defineCommand({
|
|
|
2192
2209
|
const main = defineCommand({
|
|
2193
2210
|
meta: {
|
|
2194
2211
|
name: "qp",
|
|
2195
|
-
version: "0.1.
|
|
2212
|
+
version: "0.1.12",
|
|
2196
2213
|
description: "Cloudflare-native powerhouse module for Nuxt"
|
|
2197
2214
|
},
|
|
2198
2215
|
subCommands: {
|
package/dist/module.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import 'drizzle-orm/node-sqlite';
|
|
|
19
19
|
import 'node:process';
|
|
20
20
|
import 'node:readline/promises';
|
|
21
21
|
|
|
22
|
-
const version = "0.1.
|
|
22
|
+
const version = "0.1.13";
|
|
23
23
|
|
|
24
24
|
function ensureDevEnv(rootDir) {
|
|
25
25
|
const envPath = join(rootDir, ".env");
|
|
@@ -3195,14 +3195,6 @@ export default queueHandler;
|
|
|
3195
3195
|
images: blobConfig.images
|
|
3196
3196
|
};
|
|
3197
3197
|
publicConfig.qarpeo.storage = publicConfig.qarpeo.blob;
|
|
3198
|
-
addServerHandler({
|
|
3199
|
-
route: `${storagePrefix}/upload`,
|
|
3200
|
-
handler: resolver.resolve("./runtime/server/routes/storage/upload.post")
|
|
3201
|
-
});
|
|
3202
|
-
addServerHandler({
|
|
3203
|
-
route: `${storagePrefix}/presigned`,
|
|
3204
|
-
handler: resolver.resolve("./runtime/server/routes/storage/presigned.post")
|
|
3205
|
-
});
|
|
3206
3198
|
addServerHandler({
|
|
3207
3199
|
route: `${storagePrefix}/files`,
|
|
3208
3200
|
handler: resolver.resolve("./runtime/server/routes/storage/files.get")
|
|
@@ -3220,14 +3212,6 @@ export default queueHandler;
|
|
|
3220
3212
|
handler: resolver.resolve("./runtime/server/routes/storage/file/[...key].delete")
|
|
3221
3213
|
});
|
|
3222
3214
|
if (storagePrefix !== "/api/blob") {
|
|
3223
|
-
addServerHandler({
|
|
3224
|
-
route: "/api/blob/upload",
|
|
3225
|
-
handler: resolver.resolve("./runtime/server/routes/storage/upload.post")
|
|
3226
|
-
});
|
|
3227
|
-
addServerHandler({
|
|
3228
|
-
route: "/api/blob/presigned",
|
|
3229
|
-
handler: resolver.resolve("./runtime/server/routes/storage/presigned.post")
|
|
3230
|
-
});
|
|
3231
3215
|
addServerHandler({
|
|
3232
3216
|
route: "/api/blob/files",
|
|
3233
3217
|
handler: resolver.resolve("./runtime/server/routes/storage/files.get")
|
|
@@ -3272,6 +3256,10 @@ export default queueHandler;
|
|
|
3272
3256
|
filePath: resolver.resolve("./runtime/app/components/FileUpload")
|
|
3273
3257
|
});
|
|
3274
3258
|
addServerImports([
|
|
3259
|
+
{
|
|
3260
|
+
name: "handleUpload",
|
|
3261
|
+
from: resolver.resolve("./runtime/server/utils/storage")
|
|
3262
|
+
},
|
|
3275
3263
|
{
|
|
3276
3264
|
name: "uploadStorageFile",
|
|
3277
3265
|
from: resolver.resolve("./runtime/server/utils/storage")
|
|
@@ -17,18 +17,18 @@ const props = withDefaults(defineProps<{
|
|
|
17
17
|
disabled?: boolean
|
|
18
18
|
/** Automatically trigger upload immediately on file selection. */
|
|
19
19
|
autoUpload?: boolean
|
|
20
|
+
/** Target upload endpoint URL (e.g. '/api/avatars'). Defaults to '/api/upload'. */
|
|
21
|
+
url?: string
|
|
20
22
|
/** Uploaded file(s) v-model. */
|
|
21
23
|
modelValue?: UploadedFile | UploadedFile[] | null
|
|
22
|
-
/** Use presigned direct-to-R2 upload ticket. */
|
|
23
|
-
presigned?: boolean
|
|
24
24
|
/** Additional CSS class for the wrapper container. */
|
|
25
25
|
dropzoneClass?: string
|
|
26
26
|
}>(), {
|
|
27
|
+
url: "/api/upload",
|
|
27
28
|
multiple: false,
|
|
28
29
|
disabled: false,
|
|
29
30
|
autoUpload: true,
|
|
30
31
|
modelValue: null,
|
|
31
|
-
presigned: false,
|
|
32
32
|
dropzoneClass: "",
|
|
33
33
|
})
|
|
34
34
|
|
|
@@ -45,7 +45,7 @@ const inputRef = ref<HTMLInputElement | null>(null)
|
|
|
45
45
|
const isDragging = ref(false)
|
|
46
46
|
const clientError = ref<string | null>(null)
|
|
47
47
|
|
|
48
|
-
const { isUploading, progress, error, upload, uploadMultiple, reset } = useUpload()
|
|
48
|
+
const { isUploading, progress, error, upload, uploadMultiple, reset } = useUpload(() => props.url)
|
|
49
49
|
|
|
50
50
|
function open() {
|
|
51
51
|
if (props.disabled || isUploading.value) return
|
|
@@ -85,7 +85,7 @@ async function processFiles(files: FileList | File[]) {
|
|
|
85
85
|
emit("update:modelValue", results)
|
|
86
86
|
emit("success", results)
|
|
87
87
|
} else {
|
|
88
|
-
const result = await upload(fileList[0]
|
|
88
|
+
const result = await upload(fileList[0]!)
|
|
89
89
|
emit("update:modelValue", result)
|
|
90
90
|
emit("success", result)
|
|
91
91
|
}
|
|
@@ -41,8 +41,53 @@ export declare function useStorage(): {
|
|
|
41
41
|
reset: () => void;
|
|
42
42
|
abort: () => void;
|
|
43
43
|
};
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
export interface UseUploadOptions {
|
|
45
|
+
/** Upload endpoint URL (e.g. '/api/avatars', '/api/upload'). Defaults to '/api/upload'. */
|
|
46
|
+
url?: string | Ref<string> | (() => string);
|
|
47
|
+
/** Default custom metadata */
|
|
48
|
+
customMetadata?: Record<string, string>;
|
|
49
|
+
/** Access tier for file: 'public' | 'unlisted' | 'private' */
|
|
50
|
+
access?: BlobAccessTier;
|
|
51
|
+
/** Extra headers to send with the upload request */
|
|
52
|
+
headers?: Record<string, string>;
|
|
53
|
+
/** Additional form data fields to attach */
|
|
54
|
+
body?: Record<string, any>;
|
|
55
|
+
}
|
|
56
|
+
export interface UploadFileOptions {
|
|
57
|
+
/** Override the upload endpoint for this specific call */
|
|
58
|
+
url?: string;
|
|
59
|
+
/** Override filename */
|
|
60
|
+
filename?: string;
|
|
61
|
+
/** Custom metadata */
|
|
62
|
+
customMetadata?: Record<string, string>;
|
|
63
|
+
/** Access tier */
|
|
64
|
+
access?: BlobAccessTier;
|
|
65
|
+
/** Extra headers */
|
|
66
|
+
headers?: Record<string, string>;
|
|
67
|
+
/** Extra body fields */
|
|
68
|
+
body?: Record<string, any>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Primary composable for file uploads with custom API endpoints.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* // Using default '/api/upload'
|
|
76
|
+
* const { upload, isUploading, progress, error } = useUpload()
|
|
77
|
+
*
|
|
78
|
+
* // Using a custom API route
|
|
79
|
+
* const { upload, uploadMultiple, isUploading, progress, error, abort, reset } = useUpload('/api/avatars')
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export declare function useUpload(endpointOrOptions?: string | Ref<string> | (() => string) | UseUploadOptions, initialOptions?: UseUploadOptions): {
|
|
83
|
+
upload: (file: File | Blob, opts?: UploadFileOptions) => Promise<UploadedFile>;
|
|
84
|
+
uploadMultiple: (files: FileList | File[], opts?: UploadFileOptions) => Promise<UploadedFile[]>;
|
|
85
|
+
isUploading: Ref<boolean, boolean>;
|
|
86
|
+
progress: Ref<number, number>;
|
|
87
|
+
error: Ref<Error | null, Error | null>;
|
|
88
|
+
abort: () => void;
|
|
89
|
+
reset: () => void;
|
|
90
|
+
};
|
|
46
91
|
/**
|
|
47
92
|
* Composable to resolve an R2 blob URL with optional image transforms or presets. Accepts string,
|
|
48
93
|
* ref, or getter for full Vue reactivity.
|
|
@@ -279,7 +279,210 @@ export function useStorage() {
|
|
|
279
279
|
abort
|
|
280
280
|
};
|
|
281
281
|
}
|
|
282
|
-
export
|
|
282
|
+
export function useUpload(endpointOrOptions, initialOptions = {}) {
|
|
283
|
+
const isUploading = ref(false);
|
|
284
|
+
const progress = ref(0);
|
|
285
|
+
const error = ref(null);
|
|
286
|
+
let activeXhr = null;
|
|
287
|
+
const resolveUrl = (overrideUrl) => {
|
|
288
|
+
if (overrideUrl) return overrideUrl;
|
|
289
|
+
if (typeof endpointOrOptions === "string") return endpointOrOptions;
|
|
290
|
+
if (endpointOrOptions && typeof endpointOrOptions === "function") return endpointOrOptions();
|
|
291
|
+
if (endpointOrOptions && typeof endpointOrOptions === "object" && "value" in endpointOrOptions) {
|
|
292
|
+
return toValue(endpointOrOptions);
|
|
293
|
+
}
|
|
294
|
+
if (endpointOrOptions && typeof endpointOrOptions === "object" && "url" in endpointOrOptions) {
|
|
295
|
+
return toValue(endpointOrOptions.url) || "/api/upload";
|
|
296
|
+
}
|
|
297
|
+
return toValue(initialOptions.url) || "/api/upload";
|
|
298
|
+
};
|
|
299
|
+
const reset = () => {
|
|
300
|
+
isUploading.value = false;
|
|
301
|
+
progress.value = 0;
|
|
302
|
+
error.value = null;
|
|
303
|
+
activeXhr = null;
|
|
304
|
+
};
|
|
305
|
+
const abort = () => {
|
|
306
|
+
if (activeXhr) {
|
|
307
|
+
activeXhr.abort();
|
|
308
|
+
activeXhr = null;
|
|
309
|
+
}
|
|
310
|
+
isUploading.value = false;
|
|
311
|
+
};
|
|
312
|
+
const upload = async (file, opts = {}) => {
|
|
313
|
+
isUploading.value = true;
|
|
314
|
+
progress.value = 0;
|
|
315
|
+
error.value = null;
|
|
316
|
+
const targetUrl = resolveUrl(opts.url);
|
|
317
|
+
const filename = opts.filename || (file instanceof File ? file.name : "upload");
|
|
318
|
+
return new Promise((resolve, reject) => {
|
|
319
|
+
const xhr = new XMLHttpRequest();
|
|
320
|
+
activeXhr = xhr;
|
|
321
|
+
const formData = new FormData();
|
|
322
|
+
formData.append("file", file, filename);
|
|
323
|
+
const mergedMeta = {
|
|
324
|
+
...typeof endpointOrOptions === "object" && "customMetadata" in endpointOrOptions ? endpointOrOptions.customMetadata : {},
|
|
325
|
+
...initialOptions.customMetadata,
|
|
326
|
+
...opts.customMetadata
|
|
327
|
+
};
|
|
328
|
+
if (Object.keys(mergedMeta).length > 0) {
|
|
329
|
+
formData.append("metadata", JSON.stringify(mergedMeta));
|
|
330
|
+
}
|
|
331
|
+
const mergedBody = {
|
|
332
|
+
...typeof endpointOrOptions === "object" && "body" in endpointOrOptions ? endpointOrOptions.body : {},
|
|
333
|
+
...initialOptions.body,
|
|
334
|
+
...opts.body
|
|
335
|
+
};
|
|
336
|
+
for (const [k, v] of Object.entries(mergedBody)) {
|
|
337
|
+
formData.append(k, typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
338
|
+
}
|
|
339
|
+
xhr.upload.addEventListener("progress", (event) => {
|
|
340
|
+
if (event.lengthComputable) {
|
|
341
|
+
progress.value = Math.round(event.loaded / event.total * 100);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
xhr.addEventListener("load", () => {
|
|
345
|
+
isUploading.value = false;
|
|
346
|
+
activeXhr = null;
|
|
347
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
348
|
+
try {
|
|
349
|
+
const data = JSON.parse(xhr.responseText);
|
|
350
|
+
const result = data.files ? data.files[0] : Array.isArray(data) ? data[0] : data;
|
|
351
|
+
resolve(result);
|
|
352
|
+
} catch (err) {
|
|
353
|
+
error.value = err;
|
|
354
|
+
reject(err);
|
|
355
|
+
}
|
|
356
|
+
} else {
|
|
357
|
+
const err = new Error(xhr.responseText || `Upload failed with HTTP ${xhr.status}`);
|
|
358
|
+
error.value = err;
|
|
359
|
+
reject(err);
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
xhr.addEventListener("error", () => {
|
|
363
|
+
isUploading.value = false;
|
|
364
|
+
activeXhr = null;
|
|
365
|
+
const err = new Error("Network error during file upload");
|
|
366
|
+
error.value = err;
|
|
367
|
+
reject(err);
|
|
368
|
+
});
|
|
369
|
+
xhr.addEventListener("abort", () => {
|
|
370
|
+
isUploading.value = false;
|
|
371
|
+
activeXhr = null;
|
|
372
|
+
const err = new Error("File upload aborted");
|
|
373
|
+
error.value = err;
|
|
374
|
+
reject(err);
|
|
375
|
+
});
|
|
376
|
+
const targetAccess = opts.access || (typeof endpointOrOptions === "object" && "access" in endpointOrOptions ? endpointOrOptions.access : initialOptions.access);
|
|
377
|
+
const finalUrl = targetAccess ? `${targetUrl}${targetUrl.includes("?") ? "&" : "?"}access=${targetAccess}` : targetUrl;
|
|
378
|
+
xhr.open("POST", finalUrl);
|
|
379
|
+
xhr.withCredentials = true;
|
|
380
|
+
const mergedHeaders = {
|
|
381
|
+
...typeof endpointOrOptions === "object" && "headers" in endpointOrOptions ? endpointOrOptions.headers : {},
|
|
382
|
+
...initialOptions.headers,
|
|
383
|
+
...opts.headers
|
|
384
|
+
};
|
|
385
|
+
for (const [k, v] of Object.entries(mergedHeaders)) {
|
|
386
|
+
xhr.setRequestHeader(k, v);
|
|
387
|
+
}
|
|
388
|
+
xhr.send(formData);
|
|
389
|
+
});
|
|
390
|
+
};
|
|
391
|
+
const uploadMultiple = async (files, opts = {}) => {
|
|
392
|
+
isUploading.value = true;
|
|
393
|
+
progress.value = 0;
|
|
394
|
+
error.value = null;
|
|
395
|
+
const fileArray = Array.from(files);
|
|
396
|
+
if (fileArray.length === 0) {
|
|
397
|
+
isUploading.value = false;
|
|
398
|
+
return [];
|
|
399
|
+
}
|
|
400
|
+
const targetUrl = resolveUrl(opts.url);
|
|
401
|
+
return new Promise((resolve, reject) => {
|
|
402
|
+
const xhr = new XMLHttpRequest();
|
|
403
|
+
activeXhr = xhr;
|
|
404
|
+
const formData = new FormData();
|
|
405
|
+
for (const file of fileArray) {
|
|
406
|
+
formData.append("files", file, file.name);
|
|
407
|
+
}
|
|
408
|
+
const mergedMeta = {
|
|
409
|
+
...typeof endpointOrOptions === "object" && "customMetadata" in endpointOrOptions ? endpointOrOptions.customMetadata : {},
|
|
410
|
+
...initialOptions.customMetadata,
|
|
411
|
+
...opts.customMetadata
|
|
412
|
+
};
|
|
413
|
+
if (Object.keys(mergedMeta).length > 0) {
|
|
414
|
+
formData.append("metadata", JSON.stringify(mergedMeta));
|
|
415
|
+
}
|
|
416
|
+
const mergedBody = {
|
|
417
|
+
...typeof endpointOrOptions === "object" && "body" in endpointOrOptions ? endpointOrOptions.body : {},
|
|
418
|
+
...initialOptions.body,
|
|
419
|
+
...opts.body
|
|
420
|
+
};
|
|
421
|
+
for (const [k, v] of Object.entries(mergedBody)) {
|
|
422
|
+
formData.append(k, typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
423
|
+
}
|
|
424
|
+
xhr.upload.addEventListener("progress", (event) => {
|
|
425
|
+
if (event.lengthComputable) {
|
|
426
|
+
progress.value = Math.round(event.loaded / event.total * 100);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
xhr.addEventListener("load", () => {
|
|
430
|
+
isUploading.value = false;
|
|
431
|
+
activeXhr = null;
|
|
432
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
433
|
+
try {
|
|
434
|
+
const data = JSON.parse(xhr.responseText);
|
|
435
|
+
const result = Array.isArray(data) ? data : data.files || [data];
|
|
436
|
+
resolve(result);
|
|
437
|
+
} catch (err) {
|
|
438
|
+
error.value = err;
|
|
439
|
+
reject(err);
|
|
440
|
+
}
|
|
441
|
+
} else {
|
|
442
|
+
const err = new Error(xhr.responseText || `Upload failed with HTTP ${xhr.status}`);
|
|
443
|
+
error.value = err;
|
|
444
|
+
reject(err);
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
xhr.addEventListener("error", () => {
|
|
448
|
+
isUploading.value = false;
|
|
449
|
+
activeXhr = null;
|
|
450
|
+
const err = new Error("Network error during multi-file upload");
|
|
451
|
+
error.value = err;
|
|
452
|
+
reject(err);
|
|
453
|
+
});
|
|
454
|
+
xhr.addEventListener("abort", () => {
|
|
455
|
+
isUploading.value = false;
|
|
456
|
+
activeXhr = null;
|
|
457
|
+
const err = new Error("Multi-file upload aborted");
|
|
458
|
+
error.value = err;
|
|
459
|
+
reject(err);
|
|
460
|
+
});
|
|
461
|
+
const targetAccess = opts.access || (typeof endpointOrOptions === "object" && "access" in endpointOrOptions ? endpointOrOptions.access : initialOptions.access);
|
|
462
|
+
const finalUrl = targetAccess ? `${targetUrl}${targetUrl.includes("?") ? "&" : "?"}access=${targetAccess}` : targetUrl;
|
|
463
|
+
xhr.open("POST", finalUrl);
|
|
464
|
+
xhr.withCredentials = true;
|
|
465
|
+
const mergedHeaders = {
|
|
466
|
+
...typeof endpointOrOptions === "object" && "headers" in endpointOrOptions ? endpointOrOptions.headers : {},
|
|
467
|
+
...initialOptions.headers,
|
|
468
|
+
...opts.headers
|
|
469
|
+
};
|
|
470
|
+
for (const [k, v] of Object.entries(mergedHeaders)) {
|
|
471
|
+
xhr.setRequestHeader(k, v);
|
|
472
|
+
}
|
|
473
|
+
xhr.send(formData);
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
return {
|
|
477
|
+
upload,
|
|
478
|
+
uploadMultiple,
|
|
479
|
+
isUploading,
|
|
480
|
+
progress,
|
|
481
|
+
error,
|
|
482
|
+
abort,
|
|
483
|
+
reset
|
|
484
|
+
};
|
|
485
|
+
}
|
|
283
486
|
export function useBlobUrl(key, transform) {
|
|
284
487
|
const { getOptimizedImageUrl } = useStorage();
|
|
285
488
|
return computed(() => {
|
|
@@ -109,3 +109,32 @@ export declare function listStorageFiles(event: any, options?: {
|
|
|
109
109
|
* enforcement, ETag caching, and download headers.
|
|
110
110
|
*/
|
|
111
111
|
export declare function serveStorageFile(event: any, key: string): Promise<Response | null>;
|
|
112
|
+
export interface HandleUploadOptions {
|
|
113
|
+
/** Target key in R2 bucket (or key generator function) */
|
|
114
|
+
key?: string | ((file: {
|
|
115
|
+
filename: string;
|
|
116
|
+
type: string;
|
|
117
|
+
size: number;
|
|
118
|
+
}) => string);
|
|
119
|
+
/** Target directory or prefix in R2 (e.g. 'avatars', 'documents') */
|
|
120
|
+
dir?: string;
|
|
121
|
+
/** Access tier: 'public' | 'unlisted' | 'private' */
|
|
122
|
+
access?: BlobAccessTier;
|
|
123
|
+
/** Custom metadata to attach to the R2 object */
|
|
124
|
+
customMetadata?: Record<string, string>;
|
|
125
|
+
/** Max file size override (e.g. '10MB' or bytes) */
|
|
126
|
+
maxSize?: string | number;
|
|
127
|
+
/** Allowed MIME types override (e.g. ['image/*'], ['image/png', 'image/jpeg']) */
|
|
128
|
+
allowedTypes?: string[];
|
|
129
|
+
}
|
|
130
|
+
/** Helper to extract files from multipart/form-data or raw request body. */
|
|
131
|
+
export declare function readEventMultipartFormData(event: any): Promise<Array<{
|
|
132
|
+
filename?: string;
|
|
133
|
+
type?: string;
|
|
134
|
+
data: Uint8Array;
|
|
135
|
+
}>>;
|
|
136
|
+
/**
|
|
137
|
+
* High-level server utility to handle file uploads in custom API routes (e.g. server/api/avatars.post.ts).
|
|
138
|
+
* Parses incoming multipart form data, validates, uploads to Cloudflare R2, and returns uploaded file metadata.
|
|
139
|
+
*/
|
|
140
|
+
export declare function handleUpload(event: any, options?: HandleUploadOptions): Promise<any>;
|
|
@@ -652,3 +652,82 @@ export async function serveStorageFile(event, key) {
|
|
|
652
652
|
}
|
|
653
653
|
return new Response(object.body, { headers });
|
|
654
654
|
}
|
|
655
|
+
export async function readEventMultipartFormData(event) {
|
|
656
|
+
const req = event.req || event.request;
|
|
657
|
+
if (req?.formData) {
|
|
658
|
+
try {
|
|
659
|
+
const fd = await req.formData();
|
|
660
|
+
const parts = [];
|
|
661
|
+
for (const [_, val] of fd.entries()) {
|
|
662
|
+
if (val && typeof val === "object" && "arrayBuffer" in val) {
|
|
663
|
+
const file = val;
|
|
664
|
+
parts.push({
|
|
665
|
+
filename: file.name,
|
|
666
|
+
type: file.type,
|
|
667
|
+
data: new Uint8Array(await file.arrayBuffer())
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (parts.length > 0) return parts;
|
|
672
|
+
} catch {
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
const { readMultipartFormData } = await import("h3");
|
|
677
|
+
const form = await readMultipartFormData(event);
|
|
678
|
+
if (form && form.length > 0) {
|
|
679
|
+
return form.filter((part) => part.filename && part.data).map((part) => ({
|
|
680
|
+
filename: part.filename,
|
|
681
|
+
type: part.type,
|
|
682
|
+
data: part.data instanceof Uint8Array ? part.data : new Uint8Array(part.data)
|
|
683
|
+
}));
|
|
684
|
+
}
|
|
685
|
+
} catch {
|
|
686
|
+
}
|
|
687
|
+
return [];
|
|
688
|
+
}
|
|
689
|
+
export async function handleUpload(event, options = {}) {
|
|
690
|
+
const files = await readEventMultipartFormData(event);
|
|
691
|
+
if (!files || files.length === 0) {
|
|
692
|
+
throw createError({
|
|
693
|
+
statusCode: 400,
|
|
694
|
+
statusMessage: "Bad Request",
|
|
695
|
+
message: "No files provided in upload request"
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
const results = [];
|
|
699
|
+
for (const file of files) {
|
|
700
|
+
let targetKey;
|
|
701
|
+
if (typeof options.key === "function") {
|
|
702
|
+
targetKey = options.key({
|
|
703
|
+
filename: file.filename || "file",
|
|
704
|
+
type: file.type || "application/octet-stream",
|
|
705
|
+
size: file.data.byteLength
|
|
706
|
+
});
|
|
707
|
+
} else if (typeof options.key === "string") {
|
|
708
|
+
targetKey = options.key;
|
|
709
|
+
} else if (options.dir) {
|
|
710
|
+
const cleanDir = options.dir.replace(/^\/+|\/+$/g, "");
|
|
711
|
+
const rawName = file.filename || `file-${Date.now()}`;
|
|
712
|
+
const cleanName = sanitizeFilename(rawName);
|
|
713
|
+
const uniqueId = `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
|
|
714
|
+
targetKey = `${cleanDir}/${uniqueId}-${cleanName}`;
|
|
715
|
+
}
|
|
716
|
+
const uploaded = await uploadStorageFile(
|
|
717
|
+
event,
|
|
718
|
+
{
|
|
719
|
+
data: file.data,
|
|
720
|
+
filename: file.filename,
|
|
721
|
+
type: file.type,
|
|
722
|
+
size: file.data.byteLength
|
|
723
|
+
},
|
|
724
|
+
{
|
|
725
|
+
key: targetKey,
|
|
726
|
+
access: options.access,
|
|
727
|
+
customMetadata: options.customMetadata
|
|
728
|
+
}
|
|
729
|
+
);
|
|
730
|
+
results.push(uploaded);
|
|
731
|
+
}
|
|
732
|
+
return results.length === 1 ? results[0] : results;
|
|
733
|
+
}
|
|
@@ -11,3 +11,4 @@ export interface WorkerScriptItem {
|
|
|
11
11
|
}
|
|
12
12
|
export declare function getCloudflareAuth(cwd?: string): Promise<CloudflareAuth | null>;
|
|
13
13
|
export declare function listCloudflareWorkers(auth: CloudflareAuth): Promise<WorkerScriptItem[]>;
|
|
14
|
+
export declare function deleteCloudflareWorker(auth: CloudflareAuth, workerName: string): Promise<boolean>;
|