@nexusts/upload 0.9.0 → 0.9.1
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/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/types.ts", "../src/upload.service.ts", "../src/upload.module.ts", "../src/upload.middleware.ts", "../src/decorators/upload.ts", "../src/decorators/uploaded-file.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n *
|
|
5
|
+
"/**\n * `@nexusts/upload` — file upload helper.\n *\n * @Module({\n * imports: [\n * UploadModule.forRoot({\n * maxFileSize: 10 * 1024 * 1024, // 10MB per file\n * maxFiles: 5,\n * allowedMimeTypes: ['image/*', 'application/pdf'],\n * storage: 'memory', // or 'drive' (uses nexus/drive)\n * }),\n * ],\n * })\n *\n * @Post('/avatars')\n * @Upload('avatar') // form field name\n * async upload(@UploadedFile('avatar') file: UploadedFile) {\n * return { size: file.size, type: file.contentType };\n * }\n *\n * @Post('/photos')\n * async multi(@UploadedFiles('photos') files: UploadedFile[]) {\n * return files.length;\n * }\n */\n\nimport { METADATA_KEY } from \"@nexusts/core\";\nimport { safeGetMeta, safeDefineMeta, safeHasMeta } from \"@nexusts/core/di/safe-reflect\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A file that has been parsed from `multipart/form-data`.\n *\n * The framework reads the entire body into memory (with a hard cap\n * enforced by `maxFileSize`) and exposes it as a `Buffer`. For very\n * large files (gigabytes), use a streaming approach instead — the\n * middleware leaves `stream` populated when the file is too large\n * to buffer.\n */\nexport interface UploadedFile {\n\t/** Form field name (e.g. \"avatar\", \"photos\"). */\n\tfieldName: string;\n\t/** Filename from the client (e.g. \"my-photo.png\"). */\n\tfilename: string;\n\t/** MIME type from the client. */\n\tcontentType: string;\n\t/** Encoding (typically '7bit'). */\n\tencoding: string;\n\t/** File content. */\n\tbuffer: Buffer;\n\t/** Convenience: same as `buffer.length`. */\n\tsize: number;\n}\n\n/** Top-level config. */\nexport interface UploadConfig {\n\t/** Max bytes per file. Default: 10 MB. */\n\tmaxFileSize?: number;\n\t/** Max number of files per request. Default: 5. */\n\tmaxFiles?: number;\n\t/**\n\t * Allowed MIME types. Supports `*` wildcards:\n\t * 'image/*' — any image type\n\t * 'application/pdf'\n\t * 'video/mp4'\n\t * Default: '*' (any).\n\t */\n\tallowedMimeTypes?: string[];\n\t/**\n\t * Where parsed files are stored in memory. Default: 'memory'.\n\t * The decorator reads from this storage on each access.\n\t */\n\tstorage?: \"memory\";\n\t/**\n\t * When set, parsed files are also pushed to the configured\n\t * `@nexusts/drive` storage under this prefix. The drive is\n\t * resolved by the DI token string.\n\t */\n\tdriveToken?: string;\n\tdrivePrefix?: string;\n\t/** When using drive storage: keep the original filename. Default: false (UUID). */\n\tpreserveFilename?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Decorator payload\n// ---------------------------------------------------------------------------\n\nexport interface UploadOptions {\n\t/** Form field name. Default: property name. */\n\tname?: string;\n\t/** Per-field max size (overrides the global default). */\n\tmaxSize?: number;\n\t/** Per-field MIME-type filter. */\n\tmimeTypes?: string[];\n\t/** Per-field max files (for multi-file). Default: 1. */\n\tmaxFiles?: number;\n\t/** Whether the field is required. Default: true. */\n\trequired?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Validation errors\n// ---------------------------------------------------------------------------\n\nexport class UploadError extends Error {\n\treadonly status = 400;\n\treadonly code: string;\n\treadonly field: string;\n\tconstructor(code: string, field: string, message: string) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.field = field;\n\t\tthis.name = \"UploadError\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Middleware storage key (per-request)\n// ---------------------------------------------------------------------------\n\n/** Key under which the multipart middleware stores parsed files. */\nexport const UPLOAD_STORAGE_KEY = \"nexus:upload:files\";\n\n/** Internal metadata key (decorator). */\nexport const UPLOAD_META = \"nexus:upload:options\";\n\nexport { METADATA_KEY };\n",
|
|
6
6
|
"/**\n * `UploadService` — parses `multipart/form-data` requests and exposes\n * the parsed files to controller methods via decorators.\n *\n * Lifecycle:\n * 1. The framework mounts `uploadMiddleware` (from this module)\n * at the route level.\n * 2. The middleware calls `UploadService.parseAndStore(c, fields)`,\n * which:\n * - reads `c.req.parseBody({ all: true })`\n * - extracts `File` entries from the requested fields\n * - validates each (size, MIME)\n * - stores the result on the Hono context under\n * `UPLOAD_STORAGE_KEY`\n * 3. Decorators (`@UploadedFile`, `@UploadedFiles`) read from the\n * context at parameter-extraction time.\n *\n * The middleware runs **before** the controller handler, so by the\n * time the handler is invoked, all files are already validated.\n */\nimport { Inject, Injectable } from \"@nexusts/core\";\nimport {\n\tUPLOAD_STORAGE_KEY,\n\tUploadError,\n\ttype UploadConfig,\n\ttype UploadedFile,\n} from \"./types.js\";\n\n/** What Hono's `parseBody` returns for file fields. */\ninterface ParsedFileEntry {\n\t/** Original form field name. */\n\tname: string;\n\t/** Web-API File (the multipart payload). */\n\tfilename?: string;\n\ttype?: string;\n\tsize?: number;\n\tarrayBuffer(): Promise<ArrayBuffer>;\n}\n\n/** What Hono's `parseBody` returns overall: string | File | array thereof. */\ntype ParsedBodyValue =\n\t| string\n\t| ParsedFileEntry\n\t| Array<string | ParsedFileEntry>\n\t| undefined;\n\n@Injectable()\nexport class UploadService {\n\t/** DI token. */\n\tstatic readonly TOKEN = Symbol.for(\"nexus:UploadService\");\n\n\t#config: Required<UploadConfig>;\n\t#driveResolver: ((token: string) => any) | null = null;\n\n\tconstructor(@Inject(\"UPLOAD_CONFIG\") config: UploadConfig = {}) {\n\t\tthis.#config = {\n\t\t\tmaxFileSize: config.maxFileSize ?? 10 * 1024 * 1024,\n\t\t\tmaxFiles: config.maxFiles ?? 5,\n\t\t\tallowedMimeTypes: config.allowedMimeTypes ?? [\"*\"],\n\t\t\tstorage: (config.storage as \"memory\") ?? \"memory\",\n\t\t\tdriveToken: config.driveToken ?? \"\",\n\t\t\tdrivePrefix: config.drivePrefix ?? \"\",\n\t\t\tpreserveFilename: config.preserveFilename ?? false,\n\t\t};\n\t}\n\n\t/** Bind a function that resolves a DI token to a service. Set by the module on boot. */\n\tbindDriveResolver(fn: (token: string) => any): void {\n\t\tthis.#driveResolver = fn;\n\t}\n\n\t/** The config this service was constructed with. */\n\tgetConfig(): Required<UploadConfig> {\n\t\treturn { ...this.#config };\n\t}\n\n\t/**\n\t * Parse the request body and store the requested fields on the\n\t * Hono context. Called by `uploadMiddleware`.\n\t */\n\tasync parseAndStore(\n\t\tc: any,\n\t\tfields: Array<{ fieldName: string; maxFiles: number; required: boolean }>,\n\t): Promise<void> {\n\t\tconst body = await this.#parseBody(c);\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> = {};\n\n\t\tfor (const spec of fields) {\n\t\t\tconst value = body[spec.fieldName];\n\t\t\tconst files = this.#extractFiles(value);\n\t\t\tif (files.length === 0) {\n\t\t\t\tif (spec.required) {\n\t\t\t\t\tthrow new UploadError(\n\t\t\t\t\t\t\"MISSING_FIELD\",\n\t\t\t\t\t\tspec.fieldName,\n\t\t\t\t\t\t`Missing required field \"${spec.fieldName}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (files.length > spec.maxFiles) {\n\t\t\t\tthrow new UploadError(\n\t\t\t\t\t\"TOO_MANY_FILES\",\n\t\t\t\t\tspec.fieldName,\n\t\t\t\t\t`Field \"${spec.fieldName}\" accepts at most ${spec.maxFiles} files (got ${files.length}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.#validate(f, spec.fieldName);\n\t\t\t}\n\t\t\tstored[spec.fieldName] = files.length === 1 ? files[0]! : files;\n\t\t}\n\n\t\t// Stash on the Hono context so decorators can pull it.\n\t\tc.set(UPLOAD_STORAGE_KEY, stored);\n\n\t\t// Optional: push to drive storage.\n\t\tif (this.#config.driveToken && this.#driveResolver) {\n\t\t\tconst drive = this.#driveResolver(this.#config.driveToken);\n\t\t\tif (drive?.put) {\n\t\t\t\tfor (const [, entry] of Object.entries(stored)) {\n\t\t\t\t\tconst list = Array.isArray(entry) ? entry : [entry];\n\t\t\t\t\tfor (const file of list) {\n\t\t\t\t\t\tconst filename = this.#config.preserveFilename\n\t\t\t\t\t\t\t? file.filename\n\t\t\t\t\t\t\t: this.#newFilename(file);\n\t\t\t\t\t\tconst key = `${this.#config.drivePrefix}/${filename}`;\n\t\t\t\t\t\tawait drive.put(key, file.buffer, {\n\t\t\t\t\t\t\tcontentType: file.contentType,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t(file as UploadedFile & { storedKey?: string }).storedKey = key;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read a single file from the stored body. Used by `@UploadedFile`.\n\t */\n\tget(c: any, fieldName: string): UploadedFile | undefined {\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> | undefined =\n\t\t\tc.get(UPLOAD_STORAGE_KEY);\n\t\tif (!stored) return undefined;\n\t\tconst v = stored[fieldName];\n\t\tif (Array.isArray(v)) return v[0];\n\t\treturn v;\n\t}\n\n\t/**\n\t * Read multiple files from the stored body. Used by `@UploadedFiles`.\n\t */\n\tgetAll(c: any, fieldName: string): UploadedFile[] {\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> | undefined =\n\t\t\tc.get(UPLOAD_STORAGE_KEY);\n\t\tif (!stored) return [];\n\t\tconst v = stored[fieldName];\n\t\tif (Array.isArray(v)) return v;\n\t\tif (v) return [v];\n\t\treturn [];\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Internal\n\t// ---------------------------------------------------------------------------\n\n\tasync #parseBody(c: any): Promise<Record<string, ParsedBodyValue>> {\n\t\t// Hono's parseBody returns Promise<unknown>. We pass `all: true`\n\t\t// so every field is included, not just the first.\n\t\tconst req = c.req?.raw ?? c.req;\n\t\tconst ct = (req.headers?.get?.(\"content-type\") ?? \"\") as string;\n\t\tif (!ct.startsWith(\"multipart/form-data\")) {\n\t\t\t// Not a multipart request — return empty body. The middleware\n\t\t\t// should skip parsing in this case.\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\treturn (await c.req.parseBody({ all: true })) as Record<string, ParsedBodyValue>;\n\t\t} catch (err) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"BAD_MULTIPART\",\n\t\t\t\t\"*\",\n\t\t\t\t`Failed to parse multipart body: ${(err as Error).message}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t#extractFiles(value: ParsedBodyValue): UploadedFile[] {\n\t\tif (value === undefined || value === null) return [];\n\t\tconst list = Array.isArray(value) ? value : [value];\n\t\tconst out: UploadedFile[] = [];\n\t\tfor (const v of list) {\n\t\t\tif (typeof v === \"string\") continue; // skip plain text fields\n\t\t\tif (typeof v !== \"object\") continue;\n\t\t\tconst file = v as ParsedFileEntry;\n\t\t\tif (typeof file.arrayBuffer !== \"function\") continue;\n\t\t\t// Hono under Bun returns a Blob (not a File) for file fields.\n\t\t\t// The original filename lives in `name` (Blob) or `filename`\n\t\t\t// (File). Accept either.\n\t\t\tconst filename = (file as unknown as { filename?: string }).filename\n\t\t\t\t?? (file as unknown as { name?: string }).name\n\t\t\t\t?? \"upload\";\n\t\t\tconst contentType = file.type ?? \"application/octet-stream\";\n\t\t\tout.push({\n\t\t\t\tfieldName: file.name,\n\t\t\t\tfilename,\n\t\t\t\tcontentType,\n\t\t\t\tencoding: \"7bit\",\n\t\t\t\tbuffer: Buffer.alloc(0), // filled below\n\t\t\t\tsize: file.size ?? 0,\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * After we've extracted the field list, replace each placeholder\n\t * with its real bytes. This is split out so we can do all the\n\t * parsing in parallel.\n\t */\n\t// placeholder for future async hydration.\n\n\t#validate(file: UploadedFile, fieldName: string): void {\n\t\tif (file.size > this.#config.maxFileSize) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"FILE_TOO_LARGE\",\n\t\t\t\tfieldName,\n\t\t\t\t`File \"${file.filename}\" is ${file.size} bytes; max is ${this.#config.maxFileSize}.`,\n\t\t\t);\n\t\t}\n\t\tif (!this.#mimeAllowed(file.contentType)) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"MIME_NOT_ALLOWED\",\n\t\t\t\tfieldName,\n\t\t\t\t`File \"${file.filename}\" has type \"${file.contentType}\"; not in the allow list.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t#mimeAllowed(mime: string): boolean {\n\t\tfor (const pat of this.#config.allowedMimeTypes) {\n\t\t\tif (pat === \"*\") return true;\n\t\t\tif (pat === mime) return true;\n\t\t\tif (pat.endsWith(\"/*\")) {\n\t\t\t\tconst prefix = pat.slice(0, -2); // 'image/*' -> 'image/'\n\t\t\t\tif (mime.startsWith(prefix)) return true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t#newFilename(file: UploadedFile): string {\n\t\tconst ext = file.filename.includes(\".\")\n\t\t\t? file.filename.slice(file.filename.lastIndexOf(\".\"))\n\t\t\t: \"\";\n\t\tconst stamp = Date.now().toString(36);\n\t\tconst rand = Math.random().toString(36).slice(2, 8);\n\t\treturn `${stamp}-${rand}${ext}`;\n\t}\n}",
|
|
7
7
|
"/**\n * `UploadModule` — drop-in file upload handling.\n *\n * @Module({\n * imports: [\n * UploadModule.forRoot({\n * maxFileSize: 10 * 1024 * 1024,\n * allowedMimeTypes: ['image/*', 'application/pdf'],\n * storage: 'memory',\n * }),\n * ],\n * })\n *\n * After the framework router is built, call `UploadModule.mount(app, svc)`\n * to install the multipart middleware. The middleware looks at\n * the route's metadata (set by `@Upload('fieldName')`) to know\n * which fields to parse.\n */\nimport { Module } from \"@nexusts/core\";\nimport { UploadService } from \"./upload.service.js\";\nimport type { UploadConfig } from \"./types.js\";\nimport { uploadMiddleware } from \"./upload.middleware.js\";\nimport { safeGetMeta, safeDefineMeta, safeHasMeta } from \"@nexusts/core/di/safe-reflect\";\n\n@Module({\n\tproviders: [\n\t\tUploadService,\n\t\t{ provide: UploadService.TOKEN, useExisting: UploadService },\n\t],\n\texports: [UploadService, UploadService.TOKEN],\n})\nexport class UploadModule {\n\tstatic forRoot(config: UploadConfig = {}) {\n\t\t@Module({\n\t\t\tproviders: [\n\t\t\t\tUploadService,\n\t\t\t\t{ provide: UploadService.TOKEN, useExisting: UploadService },\n\t\t\t\t{ provide: \"UPLOAD_CONFIG\", useValue: config },\n\t\t\t],\n\t\t\texports: [UploadService, UploadService.TOKEN],\n\t\t})\n\t\tclass ConfiguredUploadModule {}\n\t\tObject.defineProperty(ConfiguredUploadModule, \"name\", {\n\t\t\tvalue: \"ConfiguredUploadModule\",\n\t\t});\n\t\treturn ConfiguredUploadModule;\n\t}\n\n\t/**\n\t * Install the multipart middleware on the Hono app. Walk the\n\t * route table, collect every `@Upload` decorator, and emit a\n\t * middleware that knows which fields to parse.\n\t */\n\tstatic mount(app: any, svc: UploadService, routes: any[] = []): void {\n\t\tconst fieldSet = new Map<string, { maxFiles: number; required: boolean }>();\n\t\tfor (const r of routes) {\n\t\t\tconst metas = (safeGetMeta(\"nexus:upload:options\", r.target.constructor, r.propertyKey) ?? []) as Array<{ name: string; options: any }>;\n\t\t\tfor (const m of metas) {\n\t\t\t\tconst existing = fieldSet.get(m.name);\n\t\t\t\tconst maxFiles = m.options?.maxFiles ?? 1;\n\t\t\t\tconst required = m.options?.required ?? true;\n\t\t\t\tif (!existing || maxFiles > existing.maxFiles) {\n\t\t\t\t\tfieldSet.set(m.name, { maxFiles, required: existing?.required ?? required });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Per-route middleware: we capture the fields for that route in\n\t\t// a closure. Hono supports per-route middleware via `app.use(path, mw)`.\n\t\tapp.use(\"/**\", async (c: any, next: () => Promise<any>) => {\n\t\t\tconst fields: Array<{ fieldName: string; maxFiles: number; required: boolean }> = [];\n\t\t\tfor (const [name, info] of fieldSet.entries()) {\n\t\t\t\tfields.push({ fieldName: name, ...info });\n\t\t\t}\n\t\t\tc.set(\"uploadFields\", fields);\n\t\t\treturn uploadMiddleware(svc)(c, next);\n\t\t});\n\t}\n}",
|
|
8
8
|
"/**\n * Hono middleware that parses multipart/form-data and stores the\n * requested fields on the Hono context. Routes that need\n * `@UploadedFile` opt in by:\n *\n * 1. Calling `uploadMiddleware(fieldSpecs)` to register the fields\n * they expect.\n * 2. Or, listing the field names in the `@Upload(...)` decorator\n * metadata, which the `UploadModule` reads to wire up the\n * middleware at boot.\n *\n * For convenience, `UploadModule.mountAll()` walks the route table\n * and installs the middleware on every controller method that has\n * an `@Upload(...)` decorator.\n */\nimport { UploadError } from \"./types.js\";\n\nexport interface FieldSpec {\n\tfieldName: string;\n\tmaxFiles: number;\n\trequired: boolean;\n}\n\n/**\n * Middleware factory. Returns a Hono middleware that:\n * 1. Skips non-multipart requests.\n * 2. Asks the UploadService to parse and store the given fields.\n * 3. On `UploadError`, returns a 400 response with the error code.\n */\nexport function uploadMiddleware(svc: {\n\tparseAndStore(c: any, fields: FieldSpec[]): Promise<void>;\n}) {\n\treturn async (c: any, next: () => Promise<any>) => {\n\t\tconst ct = (c.req?.raw?.headers?.get?.(\"content-type\") ?? \"\") as string;\n\t\tif (!ct.startsWith(\"multipart/form-data\")) return next();\n\t\t// The fields are read off the route at boot. By the time this\n\t\t// middleware runs, `c.var` should have the route spec.\n\t\tconst fields: FieldSpec[] = (c.get?.(\"uploadFields\") as FieldSpec[] | undefined) ?? [];\n\t\tif (fields.length === 0) return next();\n\t\ttry {\n\t\t\tawait svc.parseAndStore(c, fields);\n\t\t\treturn next();\n\t\t} catch (err) {\n\t\t\tif (err instanceof UploadError) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: err.message, code: err.code, field: err.field },\n\t\t\t\t\terr.status as any,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t};\n}\n",
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* `@nexusts/upload` — file upload helper.
|
|
3
3
|
*
|
|
4
4
|
* @Module({
|
|
5
5
|
* imports: [
|
|
@@ -68,7 +68,7 @@ export interface UploadConfig {
|
|
|
68
68
|
storage?: "memory";
|
|
69
69
|
/**
|
|
70
70
|
* When set, parsed files are also pushed to the configured
|
|
71
|
-
*
|
|
71
|
+
* `@nexusts/drive` storage under this prefix. The drive is
|
|
72
72
|
* resolved by the DI token string.
|
|
73
73
|
*/
|
|
74
74
|
driveToken?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexusts/upload",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "Multipart file upload with validation",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
],
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@nexusts/core": "^0.9.
|
|
29
|
+
"@nexusts/core": "^0.9.1"
|
|
30
30
|
},
|
|
31
31
|
"repository": {
|
|
32
32
|
"type": "git",
|