qarpeo 0.1.12 → 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/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.12";
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]!, { presigned: props.presigned })
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
- /** Primary composable for file uploads. */
45
- export declare const useUpload: typeof useStorage;
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 const useUpload = useStorage;
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qarpeo",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "Zero-config Cloudflare Edge Platform for Nuxt",
5
5
  "keywords": [
6
6
  "analytics-engine",