graphql-upload-nextjs 3.0.0 → 3.1.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/core.js ADDED
@@ -0,0 +1,341 @@
1
+ /** Defines upload values, MIME detection, validation, and execution shared by both upload APIs. */
2
+ import { fileTypeFromBuffer } from 'file-type';
3
+ import { GraphQLError, GraphQLScalarType } from 'graphql';
4
+ import { isText } from 'istextorbinary';
5
+ import { NextResponse } from 'next/server.js';
6
+ import { Readable } from 'stream';
7
+ const DEFAULT_MIME_TYPE = 'application/octet-stream';
8
+ /**
9
+ * Represents an instance of a file upload.
10
+ * Holds a promise that resolves with the file details once processed.
11
+ */
12
+ export class Upload {
13
+ file;
14
+ promise;
15
+ reject = () => { };
16
+ resolve = () => { };
17
+ constructor() {
18
+ this.promise = new Promise((resolve, reject) => {
19
+ this.resolve = (file) => {
20
+ this.file = file;
21
+ resolve(file);
22
+ };
23
+ this.reject = reject;
24
+ });
25
+ this.promise.catch(() => { });
26
+ }
27
+ }
28
+ /** Custom GraphQL scalar type for handling file uploads. */
29
+ export const GraphQLUpload = new GraphQLScalarType({
30
+ description: 'The Upload scalar type represents a file upload.',
31
+ name: 'Upload',
32
+ parseLiteral(node) {
33
+ throw new GraphQLError('Upload literal unsupported.', { nodes: node });
34
+ },
35
+ parseValue(value) {
36
+ if (value instanceof Upload)
37
+ return value.promise;
38
+ throw new GraphQLError('Upload value invalid.');
39
+ },
40
+ serialize() {
41
+ throw new GraphQLError('Upload serialization unsupported.');
42
+ },
43
+ });
44
+ /** Converts a Buffer into a Node.js readable stream. */
45
+ export function bufferToStream(buffer) {
46
+ const stream = new Readable();
47
+ stream.push(buffer);
48
+ stream.push(null);
49
+ return stream;
50
+ }
51
+ /** Collects a GraphQL response into a serializable result object. */
52
+ async function collectResponse(response) {
53
+ if (response.body.kind === 'single') {
54
+ return response.body.singleResult;
55
+ }
56
+ if (response.body.kind === 'incremental') {
57
+ const { initialResult, subsequentResults } = response.body;
58
+ const collected = [];
59
+ for await (const result of subsequentResults) {
60
+ collected.push(result);
61
+ }
62
+ return { initialResult, subsequentResults: collected };
63
+ }
64
+ return { errors: [{ message: 'Unexpected server response format' }] };
65
+ }
66
+ /** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
67
+ export function parseOperationsJSON(input) {
68
+ let result;
69
+ try {
70
+ result = JSON.parse(input);
71
+ }
72
+ catch {
73
+ throw new Error('Invalid JSON in the operations multipart field.');
74
+ }
75
+ if (typeof result !== 'object' || result === null) {
76
+ throw new Error('Invalid type for the operations multipart field.');
77
+ }
78
+ return result;
79
+ }
80
+ /**
81
+ * Processes a file from FormData, detects its MIME type via magic bytes,
82
+ * and returns buffered file metadata with replayable stream access.
83
+ */
84
+ export async function processUpload(file, allowedTypes) {
85
+ if (!file.name || typeof file.size !== 'number' || !Number.isFinite(file.size) || file.size < 0) {
86
+ throw new Error('Invalid file properties: name or size is missing or invalid.');
87
+ }
88
+ const blob = file;
89
+ // Only read the first 4100 bytes for MIME type detection via magic bytes.
90
+ // The runtime has already received the body; detection adds only a bounded prefix copy.
91
+ const DETECTION_BYTES = 4100;
92
+ const headerBuffer = Buffer.from(await blob.slice(0, DETECTION_BYTES).arrayBuffer());
93
+ const mimetype = await detectMimeType(headerBuffer, allowedTypes);
94
+ return {
95
+ createReadStream: () => Readable.fromWeb(blob.stream()),
96
+ encoding: 'binary',
97
+ fileSize: file.size,
98
+ filename: file.name,
99
+ mimetype,
100
+ };
101
+ }
102
+ /** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
103
+ export function sanitizeAndValidateJSON(input) {
104
+ let result;
105
+ try {
106
+ result = JSON.parse(input);
107
+ }
108
+ catch (error) {
109
+ throw new Error(`Invalid JSON input: ${error.message}`);
110
+ }
111
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) {
112
+ throw new Error('Invalid JSON structure: expected a non-null object.');
113
+ }
114
+ return result;
115
+ }
116
+ /** Dangerous property names that could lead to prototype pollution. */
117
+ const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
118
+ /** Checks whether a value is a plain object record suitable for GraphQL variables. */
119
+ function isObjectRecord(value) {
120
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
121
+ }
122
+ /** Validates the minimal GraphQL operation shape required for execution. */
123
+ function validateOperation(operation, label) {
124
+ if (!isObjectRecord(operation)) {
125
+ return `Invalid ${label}: expected an operation object.`;
126
+ }
127
+ if (typeof operation.query !== 'string') {
128
+ return `Invalid ${label}: expected query to be a string.`;
129
+ }
130
+ if (operation.variables !== undefined && !isObjectRecord(operation.variables)) {
131
+ return `Invalid ${label}: expected variables to be an object when provided.`;
132
+ }
133
+ if (operation.operationName !== undefined && typeof operation.operationName !== 'string') {
134
+ return `Invalid ${label}: expected operationName to be a string when provided.`;
135
+ }
136
+ return null;
137
+ }
138
+ /** Validates upload process settings before request body processing starts. */
139
+ function validateSettings(settings) {
140
+ if (settings?.maxFileSize !== undefined && (typeof settings.maxFileSize !== 'number' ||
141
+ !Number.isFinite(settings.maxFileSize) ||
142
+ settings.maxFileSize < 0)) {
143
+ return 'Invalid maxFileSize setting: expected a finite non-negative number.';
144
+ }
145
+ if (settings?.maxFiles !== undefined && (typeof settings.maxFiles !== 'number' ||
146
+ !Number.isSafeInteger(settings.maxFiles) ||
147
+ settings.maxFiles < 0)) {
148
+ return 'Invalid maxFiles setting: expected a non-negative safe integer.';
149
+ }
150
+ if (settings?.allowedTypes !== undefined && (!Array.isArray(settings.allowedTypes) ||
151
+ settings.allowedTypes.some(type => typeof type !== 'string' || !type.trim()))) {
152
+ return 'Invalid allowedTypes setting: expected an array of non-empty MIME types.';
153
+ }
154
+ return null;
155
+ }
156
+ /** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
157
+ export function setValueAtPath(obj, path, value) {
158
+ const keys = path.split('.');
159
+ let current = obj;
160
+ for (let i = 0; i < keys.length - 1; i++) {
161
+ const key = keys[i];
162
+ if (BLOCKED_KEYS.has(key)) {
163
+ throw new Error(`Invalid path segment: '${key}' is not allowed.`);
164
+ }
165
+ const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
166
+ if (!current[key] ||
167
+ typeof current[key] !== 'object' ||
168
+ (nextKeyIsArrayIndex && !Array.isArray(current[key])) ||
169
+ (!nextKeyIsArrayIndex && Array.isArray(current[key]))) {
170
+ current[key] = nextKeyIsArrayIndex ? [] : {};
171
+ }
172
+ current = current[key];
173
+ }
174
+ const finalKey = keys[keys.length - 1];
175
+ if (BLOCKED_KEYS.has(finalKey)) {
176
+ throw new Error(`Invalid path segment: '${finalKey}' is not allowed.`);
177
+ }
178
+ current[finalKey] = value;
179
+ }
180
+ /** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
181
+ export async function streamToBuffer(stream) {
182
+ const chunks = [];
183
+ for await (const chunk of stream) {
184
+ if (Buffer.isBuffer(chunk)) {
185
+ chunks.push(chunk);
186
+ }
187
+ else if (typeof chunk === 'string') {
188
+ chunks.push(Buffer.from(chunk));
189
+ }
190
+ else {
191
+ chunks.push(Buffer.from(chunk));
192
+ }
193
+ }
194
+ return Buffer.concat(chunks);
195
+ }
196
+ /** Validates that each map entry is an array of string paths. */
197
+ export function validateMap(map) {
198
+ for (const [key, paths] of Object.entries(map)) {
199
+ if (!Array.isArray(paths)) {
200
+ return `Invalid type for map entry '${key}': expected an array of paths.`;
201
+ }
202
+ for (const p of paths) {
203
+ if (typeof p !== 'string') {
204
+ return `Invalid path in map entry '${key}': expected string.`;
205
+ }
206
+ if (!p) {
207
+ return `Invalid path in map entry '${key}': path cannot be empty.`;
208
+ }
209
+ const segments = p.split('.');
210
+ for (const segment of segments) {
211
+ if (!segment) {
212
+ return `Invalid path in map entry '${key}': path cannot contain empty segments.`;
213
+ }
214
+ if (BLOCKED_KEYS.has(segment)) {
215
+ return `Invalid path segment in map entry '${key}': '${segment}' is not allowed.`;
216
+ }
217
+ }
218
+ }
219
+ }
220
+ return null;
221
+ }
222
+ /** Identifies a bounded file prefix without trusting its name or declared content type. */
223
+ export async function detectMimeType(headerBuffer, allowedTypes) {
224
+ const fileTypeInfo = await fileTypeFromBuffer(new Uint8Array(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength));
225
+ let mimetype = DEFAULT_MIME_TYPE;
226
+ if (fileTypeInfo) {
227
+ mimetype = fileTypeInfo.mime;
228
+ }
229
+ else {
230
+ try {
231
+ if (await isText(null, headerBuffer)) {
232
+ mimetype = 'text/plain';
233
+ }
234
+ }
235
+ catch {
236
+ // Fallback: isText detection failed, keeping the unknown binary default.
237
+ }
238
+ }
239
+ if (allowedTypes && !allowedTypes.includes(mimetype)) {
240
+ throw new Error(`File type ${mimetype} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
241
+ }
242
+ return mimetype;
243
+ }
244
+ /** Distinguishes safe protocol errors from unexpected server exceptions. */
245
+ export class UploadRequestError extends Error {
246
+ status;
247
+ constructor(message, status = 400) {
248
+ super(message);
249
+ this.status = status;
250
+ }
251
+ }
252
+ /** Checks configuration and the preflight boundary before consuming request bytes. */
253
+ export function checkUploadRequest(headers, settings) {
254
+ if (!headers.get('apollo-require-preflight')?.trim() && !headers.get('x-apollo-operation-name')?.trim()) {
255
+ throw new UploadRequestError('Upload requests require an Apollo-Require-Preflight header.');
256
+ }
257
+ const error = validateSettings(settings);
258
+ if (error)
259
+ throw new UploadRequestError(error);
260
+ }
261
+ /** Validates every target before replacing nulls; assignment preserves existing container shapes. */
262
+ export function prepareOperations(operationsRaw, mapRaw, maxFiles) {
263
+ let parsed;
264
+ let map;
265
+ try {
266
+ parsed = parseOperationsJSON(operationsRaw);
267
+ map = sanitizeAndValidateJSON(mapRaw);
268
+ }
269
+ catch (error) {
270
+ throw new UploadRequestError(error.message);
271
+ }
272
+ const mapError = validateMap(map);
273
+ if (mapError)
274
+ throw new UploadRequestError(mapError);
275
+ const batch = Array.isArray(parsed);
276
+ const operations = Array.isArray(parsed) ? parsed : [parsed];
277
+ if (!operations.length)
278
+ throw new UploadRequestError('Operations batch cannot be empty.');
279
+ for (const [index, operation] of operations.entries()) {
280
+ const error = validateOperation(operation, batch ? `operation at index ${index}` : 'operation');
281
+ if (error)
282
+ throw new UploadRequestError(error);
283
+ }
284
+ if (maxFiles !== undefined && Object.keys(map).length > maxFiles) {
285
+ throw new UploadRequestError(`${maxFiles} max file uploads exceeded.`, 413);
286
+ }
287
+ const uploads = new Map();
288
+ const locations = [];
289
+ const owners = new Map();
290
+ for (const [field, paths] of Object.entries(map)) {
291
+ const upload = new Upload();
292
+ uploads.set(field, upload);
293
+ for (const path of paths) {
294
+ const keys = path.split('.');
295
+ const offset = batch ? 1 : 0;
296
+ if ((batch && (!/^(0|[1-9]\d*)$/.test(keys[0]) || Number(keys[0]) >= operations.length)) ||
297
+ keys[offset] !== 'variables' || keys.length <= offset + 1) {
298
+ throw new UploadRequestError('File paths must target operation variables.');
299
+ }
300
+ if (owners.has(path) && owners.get(path) !== field) {
301
+ throw new UploadRequestError('Multiple files cannot target the same placeholder.');
302
+ }
303
+ owners.set(path, field);
304
+ let parent = parsed;
305
+ for (const key of keys.slice(0, -1)) {
306
+ if (parent === null || typeof parent !== 'object' || !Object.hasOwn(parent, key)) {
307
+ throw new UploadRequestError('File paths must reference existing null placeholders.');
308
+ }
309
+ parent = parent[key];
310
+ }
311
+ const key = keys[keys.length - 1];
312
+ if (parent === null || typeof parent !== 'object' || !Object.hasOwn(parent, key) ||
313
+ parent[key] !== null) {
314
+ throw new UploadRequestError('File paths must reference existing null placeholders.');
315
+ }
316
+ locations.push({ parent: parent, key, upload });
317
+ }
318
+ }
319
+ for (const { parent, key, upload } of locations)
320
+ parent[key] = upload;
321
+ return { operations: parsed, uploads };
322
+ }
323
+ /** Preserves operation order, context, and the existing response envelope in both APIs. */
324
+ export async function executeOperations(operations, context, server) {
325
+ const results = [];
326
+ for (const op of Array.isArray(operations) ? operations : [operations]) {
327
+ const response = await server.executeOperation({
328
+ query: op.query, variables: op.variables || {},
329
+ ...(op.operationName !== undefined && { operationName: op.operationName }),
330
+ }, { contextValue: context });
331
+ results.push(await collectResponse(response));
332
+ }
333
+ return NextResponse.json(Array.isArray(operations) ? results : results[0]);
334
+ }
335
+ /** Only intentional request errors may expose their details to an untrusted client. */
336
+ export function uploadErrorResponse(error) {
337
+ return NextResponse.json({ errors: [{ message: error instanceof UploadRequestError
338
+ ? error.message : 'Unexpected error during upload processing.' }] }, {
339
+ status: error instanceof UploadRequestError ? error.status : 500,
340
+ });
341
+ }
package/index.d.ts CHANGED
@@ -1,77 +1,11 @@
1
- import { GraphQLScalarType } from 'graphql';
2
- import { NextResponse } from 'next/server.js';
3
- /** Represents a processed file with metadata and stream access. */
4
- export interface File {
5
- createReadStream: () => NodeJS.ReadableStream;
6
- encoding: string;
7
- fileSize: number;
8
- filename: string;
9
- mimetype: string;
10
- }
11
- /** Raw file entry extracted from multipart FormData. */
12
- export interface FormDataFile {
13
- lastModified: number;
14
- name: string;
15
- size: number;
16
- type: string;
17
- }
18
- /** Extends FormDataFile with a stream method for reading file contents. */
19
- export interface FileStream extends FormDataFile {
20
- stream: () => ReadableStream;
21
- }
22
- /** Minimal request interface compatible with Next.js and Web API requests. */
23
- export interface MinimalRequest {
24
- formData: () => Promise<FormData>;
25
- headers: {
26
- get: (name: string) => string | null;
27
- };
28
- }
29
- /** Parameters for Apollo Server's executeOperation method. */
30
- interface ServerExecuteOperationParams {
31
- operationName?: string;
32
- query: string;
33
- variables: Record<string, unknown>;
34
- }
35
- /** Minimal response shape consumed from Apollo Server executeOperation. */
36
- interface ServerExecuteOperationResponse {
37
- body: {
38
- kind: string;
39
- [key: string]: unknown;
40
- };
41
- }
42
- /**
43
- * Represents an instance of a file upload.
44
- * Holds a promise that resolves with the file details once processed.
45
- */
46
- export declare class Upload {
47
- file?: File;
48
- promise: Promise<File>;
49
- reject: (reason?: Error | string) => void;
50
- resolve: (file: File) => void;
51
- constructor();
52
- }
53
- /** Custom GraphQL scalar type for handling file uploads. */
54
- export declare const GraphQLUpload: GraphQLScalarType<Promise<File>, never>;
55
- /** Converts a Buffer into a Node.js readable stream. */
56
- export declare function bufferToStream(buffer: Buffer): NodeJS.ReadableStream;
57
- /** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
58
- export declare function parseOperationsJSON(input: string): Record<string, unknown> | Record<string, unknown>[];
59
- /** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
60
- export declare function sanitizeAndValidateJSON(input: string): unknown;
61
- /** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
62
- export declare function setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): void;
63
- /** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
64
- export declare function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer>;
65
- /** Validates that each map entry is an array of string paths. */
66
- export declare function validateMap(map: Record<string, unknown>): string | null;
67
- /** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
68
- export declare function uploadProcess<TContext extends Record<string, unknown>>(request: MinimalRequest, contextValueInput: TContext, server: {
69
- executeOperation: (params: ServerExecuteOperationParams, context: {
70
- contextValue: TContext;
71
- }) => Promise<ServerExecuteOperationResponse>;
72
- }, settings?: {
1
+ /** Preserves the buffered upload API and exports the optional streaming integration. */
2
+ import type { NextResponse } from 'next/server.js';
3
+ import { type MinimalRequest, type UploadServer } from './core.js';
4
+ export { type File, type FileStream, type FormDataFile, type MinimalRequest, GraphQLUpload, Upload, bufferToStream, parseOperationsJSON, sanitizeAndValidateJSON, setValueAtPath, streamToBuffer, validateMap, } from './core.js';
5
+ export { type StreamingFile, type StreamingRequest, type StreamingUploadSettings, uploadProcessStreaming } from './streaming.js';
6
+ /** Fully receives files before executing GraphQL; existing callers retain numeric file sizes. */
7
+ export declare function uploadProcess<TContext extends Record<string, unknown>>(request: MinimalRequest, contextValueInput: TContext, server: UploadServer<TContext>, settings?: {
73
8
  allowedTypes?: string[];
74
9
  maxFileSize?: number;
75
10
  maxFiles?: number;
76
11
  }): Promise<NextResponse>;
77
- export {};