graphql-upload-nextjs 1.0.0 → 2.0.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/CODE_OF_CONDUCT.md +25 -0
- package/CONTRIBUTING.md +45 -0
- package/LICENSE +21 -21
- package/README.md +319 -364
- package/SECURITY.md +25 -0
- package/index.d.ts +37 -23
- package/index.js +280 -111
- package/package.json +78 -62
package/SECURITY.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Supported Versions
|
|
4
|
+
|
|
5
|
+
We provide security fixes exclusively for the latest major version.
|
|
6
|
+
|
|
7
|
+
| Version | Supported |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| 2.x | Yes |
|
|
10
|
+
| < 2.0 | No |
|
|
11
|
+
|
|
12
|
+
## Reporting a Vulnerability
|
|
13
|
+
|
|
14
|
+
If GitHub private vulnerability reporting is active on this repository, please utilize it to submit your report securely.
|
|
15
|
+
|
|
16
|
+
If private reporting is unavailable, open a regular GitHub issue with a concise, non-sensitive description. Request a private disclosure channel from a maintainers before sharing exploits, secrets, or payloads.
|
|
17
|
+
|
|
18
|
+
Please include:
|
|
19
|
+
|
|
20
|
+
* The affected package version.
|
|
21
|
+
* A clear description of the potential impact.
|
|
22
|
+
* Safe steps to reproduce the issue, if they can be shared securely.
|
|
23
|
+
* Any known temporary workarounds.
|
|
24
|
+
|
|
25
|
+
We review valid reports promptly to coordinate fixes and issue security releases.
|
package/index.d.ts
CHANGED
|
@@ -1,22 +1,37 @@
|
|
|
1
|
-
import { GraphQLScalarType, GraphQLError } from 'graphql';
|
|
2
|
-
import { NextResponse } from 'next/server.js';
|
|
3
1
|
import type { GraphQLResponse } from '@apollo/server';
|
|
2
|
+
import { GraphQLScalarType } from 'graphql';
|
|
3
|
+
import { NextResponse } from 'next/server.js';
|
|
4
|
+
/** Represents a processed file with metadata and stream access. */
|
|
4
5
|
export interface File {
|
|
5
6
|
createReadStream: () => NodeJS.ReadableStream;
|
|
6
7
|
encoding: string;
|
|
7
|
-
fileName: string;
|
|
8
8
|
fileSize: number;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
export interface FileStream extends FormDataFile {
|
|
12
|
-
stream: () => Promise<NodeJS.ReadableStream>;
|
|
9
|
+
filename: string;
|
|
10
|
+
mimetype: string;
|
|
13
11
|
}
|
|
12
|
+
/** Raw file entry extracted from multipart FormData. */
|
|
14
13
|
export interface FormDataFile {
|
|
15
14
|
lastModified: number;
|
|
16
15
|
name: string;
|
|
17
16
|
size: number;
|
|
18
17
|
type: string;
|
|
19
18
|
}
|
|
19
|
+
/** Extends FormDataFile with a stream method for reading file contents. */
|
|
20
|
+
export interface FileStream extends FormDataFile {
|
|
21
|
+
stream: () => ReadableStream;
|
|
22
|
+
}
|
|
23
|
+
/** Minimal request interface compatible with Next.js and Web API requests. */
|
|
24
|
+
export interface MinimalRequest {
|
|
25
|
+
formData: () => Promise<FormData>;
|
|
26
|
+
headers: {
|
|
27
|
+
get: (name: string) => string | null;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Parameters for Apollo Server's executeOperation method. */
|
|
31
|
+
interface ServerExecuteOperationParams {
|
|
32
|
+
query: string;
|
|
33
|
+
variables: Record<string, unknown>;
|
|
34
|
+
}
|
|
20
35
|
/**
|
|
21
36
|
* Represents an instance of a file upload.
|
|
22
37
|
* Holds a promise that resolves with the file details once processed.
|
|
@@ -28,23 +43,21 @@ export declare class Upload {
|
|
|
28
43
|
resolve: (file: File) => void;
|
|
29
44
|
constructor();
|
|
30
45
|
}
|
|
31
|
-
|
|
32
|
-
export declare
|
|
46
|
+
/** Custom GraphQL scalar type for handling file uploads. */
|
|
47
|
+
export declare const GraphQLUpload: GraphQLScalarType<Promise<File>, never>;
|
|
48
|
+
/** Converts a Buffer into a Node.js readable stream. */
|
|
33
49
|
export declare function bufferToStream(buffer: Buffer): NodeJS.ReadableStream;
|
|
50
|
+
/** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
|
|
51
|
+
export declare function parseOperationsJSON(input: string): Record<string, unknown> | Record<string, unknown>[];
|
|
52
|
+
/** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
|
|
34
53
|
export declare function sanitizeAndValidateJSON(input: string): unknown;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
get: (name: string) => string | null;
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Processes a GraphQL multipart request with file uploads.
|
|
47
|
-
*/
|
|
54
|
+
/** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
|
|
55
|
+
export declare function setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): void;
|
|
56
|
+
/** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
|
|
57
|
+
export declare function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer>;
|
|
58
|
+
/** Validates that each map entry is an array of string paths. */
|
|
59
|
+
export declare function validateMap(map: Record<string, unknown>): string | null;
|
|
60
|
+
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
48
61
|
export declare function uploadProcess<TContext extends Record<string, unknown>>(request: MinimalRequest, contextValueInput: TContext, server: {
|
|
49
62
|
executeOperation: (params: ServerExecuteOperationParams, context: {
|
|
50
63
|
contextValue: TContext;
|
|
@@ -52,5 +65,6 @@ export declare function uploadProcess<TContext extends Record<string, unknown>>(
|
|
|
52
65
|
}, settings?: {
|
|
53
66
|
allowedTypes?: string[];
|
|
54
67
|
maxFileSize?: number;
|
|
55
|
-
|
|
68
|
+
maxFiles?: number;
|
|
69
|
+
}): Promise<NextResponse>;
|
|
56
70
|
export {};
|
package/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { GraphQLScalarType, GraphQLError } from 'graphql';
|
|
2
|
-
import { NextResponse } from 'next/server.js';
|
|
3
1
|
import { fileTypeFromBuffer } from 'file-type';
|
|
2
|
+
import { GraphQLError, GraphQLScalarType } from 'graphql';
|
|
4
3
|
import { isText } from 'istextorbinary';
|
|
4
|
+
import { NextResponse } from 'next/server.js';
|
|
5
|
+
import { Readable } from 'stream';
|
|
6
|
+
const DEFAULT_MIME_TYPE = 'application/octet-stream';
|
|
5
7
|
/**
|
|
6
8
|
* Represents an instance of a file upload.
|
|
7
9
|
* Holds a promise that resolves with the file details once processed.
|
|
@@ -22,176 +24,343 @@ export class Upload {
|
|
|
22
24
|
this.promise.catch(() => { });
|
|
23
25
|
}
|
|
24
26
|
}
|
|
27
|
+
/** Custom GraphQL scalar type for handling file uploads. */
|
|
25
28
|
export const GraphQLUpload = new GraphQLScalarType({
|
|
26
29
|
description: 'The Upload scalar type represents a file upload.',
|
|
27
30
|
name: 'Upload',
|
|
28
|
-
parseLiteral(node) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
parseLiteral(node) {
|
|
32
|
+
throw new GraphQLError('Upload literal unsupported.', { nodes: node });
|
|
33
|
+
},
|
|
34
|
+
parseValue(value) {
|
|
35
|
+
if (value instanceof Upload)
|
|
36
|
+
return value.promise;
|
|
37
|
+
throw new GraphQLError('Upload value invalid.');
|
|
38
|
+
},
|
|
39
|
+
serialize() {
|
|
40
|
+
throw new GraphQLError('Upload serialization unsupported.');
|
|
41
|
+
},
|
|
31
42
|
});
|
|
43
|
+
/** Converts a Buffer into a Node.js readable stream. */
|
|
44
|
+
export function bufferToStream(buffer) {
|
|
45
|
+
const stream = new Readable();
|
|
46
|
+
stream.push(buffer);
|
|
47
|
+
stream.push(null);
|
|
48
|
+
return stream;
|
|
49
|
+
}
|
|
50
|
+
/** Collects a GraphQL response into a serializable result object. */
|
|
51
|
+
async function collectResponse(response) {
|
|
52
|
+
if (response.body.kind === 'single') {
|
|
53
|
+
return response.body.singleResult;
|
|
54
|
+
}
|
|
55
|
+
if (response.body.kind === 'incremental') {
|
|
56
|
+
const { initialResult, subsequentResults } = response.body;
|
|
57
|
+
const collected = [];
|
|
58
|
+
for await (const result of subsequentResults) {
|
|
59
|
+
collected.push(result);
|
|
60
|
+
}
|
|
61
|
+
return { initialResult, subsequentResults: collected };
|
|
62
|
+
}
|
|
63
|
+
return { errors: [{ message: 'Unexpected server response format' }] };
|
|
64
|
+
}
|
|
65
|
+
/** Extracts File entries from multipart FormData. */
|
|
32
66
|
async function extractFiles(formData) {
|
|
33
67
|
const files = {};
|
|
34
|
-
for (const [key, value] of
|
|
68
|
+
for (const [key, value] of formData.entries()) {
|
|
35
69
|
if (value instanceof globalThis.File) {
|
|
36
70
|
files[key] = value;
|
|
37
71
|
}
|
|
38
72
|
}
|
|
39
73
|
return files;
|
|
40
74
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
75
|
+
/** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
|
|
76
|
+
export function parseOperationsJSON(input) {
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
result = JSON.parse(input);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new Error('Invalid JSON in the operations multipart field.');
|
|
83
|
+
}
|
|
84
|
+
if (typeof result !== 'object' || result === null) {
|
|
85
|
+
throw new Error('Invalid type for the operations multipart field.');
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Processes a file from FormData, detects its MIME type via magic bytes,
|
|
91
|
+
* and returns a resolved Upload instance with streaming file access.
|
|
92
|
+
*/
|
|
93
|
+
async function processUpload(file, allowedTypes) {
|
|
94
|
+
if (!file.name || typeof file.size !== 'number' || !Number.isFinite(file.size) || file.size < 0) {
|
|
95
|
+
throw new Error('Invalid file properties: name or size is missing or invalid.');
|
|
96
|
+
}
|
|
97
|
+
const blob = file;
|
|
98
|
+
// Only read the first 4100 bytes for MIME type detection via magic bytes.
|
|
99
|
+
// This avoids buffering the entire file into memory.
|
|
100
|
+
const DETECTION_BYTES = 4100;
|
|
101
|
+
const headerBuffer = Buffer.from(await blob.slice(0, DETECTION_BYTES).arrayBuffer());
|
|
102
|
+
const fileTypeInfo = await fileTypeFromBuffer(new Uint8Array(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength));
|
|
103
|
+
let mimetype = DEFAULT_MIME_TYPE;
|
|
104
|
+
if (fileTypeInfo) {
|
|
105
|
+
mimetype = fileTypeInfo.mime;
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
try {
|
|
109
|
+
if (await isText(file.name, headerBuffer)) {
|
|
110
|
+
mimetype = 'text/plain';
|
|
111
|
+
}
|
|
49
112
|
}
|
|
50
|
-
|
|
51
|
-
|
|
113
|
+
catch {
|
|
114
|
+
// Fallback: isText detection failed, keeping the unknown binary default.
|
|
52
115
|
}
|
|
53
116
|
}
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
117
|
+
if (allowedTypes && !allowedTypes.includes(mimetype)) {
|
|
118
|
+
throw new Error(`File type ${mimetype} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
|
|
119
|
+
}
|
|
120
|
+
const upload = new Upload();
|
|
121
|
+
upload.resolve({
|
|
122
|
+
createReadStream: () => Readable.fromWeb(blob.stream()),
|
|
123
|
+
encoding: 'binary',
|
|
124
|
+
fileSize: file.size,
|
|
125
|
+
filename: file.name,
|
|
126
|
+
mimetype,
|
|
127
|
+
});
|
|
128
|
+
return upload;
|
|
62
129
|
}
|
|
130
|
+
/** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
|
|
63
131
|
export function sanitizeAndValidateJSON(input) {
|
|
132
|
+
let result;
|
|
64
133
|
try {
|
|
65
|
-
|
|
66
|
-
if (typeof result !== 'object' || result === null) {
|
|
67
|
-
throw new Error('Invalid JSON structure: not an object.');
|
|
68
|
-
}
|
|
69
|
-
return result;
|
|
134
|
+
result = JSON.parse(input);
|
|
70
135
|
}
|
|
71
136
|
catch (error) {
|
|
72
137
|
throw new Error(`Invalid JSON input: ${error.message}`);
|
|
73
138
|
}
|
|
139
|
+
if (typeof result !== 'object' || result === null || Array.isArray(result)) {
|
|
140
|
+
throw new Error('Invalid JSON structure: expected a non-null object.');
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
/** Dangerous property names that could lead to prototype pollution. */
|
|
145
|
+
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
146
|
+
/** Checks whether a value is a plain object record suitable for GraphQL variables. */
|
|
147
|
+
function isObjectRecord(value) {
|
|
148
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
149
|
+
}
|
|
150
|
+
/** Validates the minimal GraphQL operation shape required for execution. */
|
|
151
|
+
function validateOperation(operation, label) {
|
|
152
|
+
if (!isObjectRecord(operation)) {
|
|
153
|
+
return `Invalid ${label}: expected an operation object.`;
|
|
154
|
+
}
|
|
155
|
+
if (typeof operation.query !== 'string') {
|
|
156
|
+
return `Invalid ${label}: expected query to be a string.`;
|
|
157
|
+
}
|
|
158
|
+
if (operation.variables !== undefined && !isObjectRecord(operation.variables)) {
|
|
159
|
+
return `Invalid ${label}: expected variables to be an object when provided.`;
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
/** Validates upload process settings before request body processing starts. */
|
|
164
|
+
function validateSettings(settings) {
|
|
165
|
+
if (settings?.maxFileSize !== undefined && (typeof settings.maxFileSize !== 'number' ||
|
|
166
|
+
!Number.isFinite(settings.maxFileSize) ||
|
|
167
|
+
settings.maxFileSize < 0)) {
|
|
168
|
+
return 'Invalid maxFileSize setting: expected a finite non-negative number.';
|
|
169
|
+
}
|
|
170
|
+
if (settings?.maxFiles !== undefined && (typeof settings.maxFiles !== 'number' ||
|
|
171
|
+
!Number.isFinite(settings.maxFiles) ||
|
|
172
|
+
settings.maxFiles < 0)) {
|
|
173
|
+
return 'Invalid maxFiles setting: expected a finite non-negative number.';
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
74
176
|
}
|
|
75
|
-
|
|
177
|
+
/** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
|
|
178
|
+
export function setValueAtPath(obj, path, value) {
|
|
76
179
|
const keys = path.split('.');
|
|
77
180
|
let current = obj;
|
|
78
181
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
79
182
|
const key = keys[i];
|
|
183
|
+
if (BLOCKED_KEYS.has(key)) {
|
|
184
|
+
throw new Error(`Invalid path segment: '${key}' is not allowed.`);
|
|
185
|
+
}
|
|
80
186
|
const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
|
|
81
|
-
if (!current[key] ||
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
187
|
+
if (!current[key] ||
|
|
188
|
+
typeof current[key] !== 'object' ||
|
|
189
|
+
(nextKeyIsArrayIndex && !Array.isArray(current[key])) ||
|
|
190
|
+
(!nextKeyIsArrayIndex && Array.isArray(current[key]))) {
|
|
85
191
|
current[key] = nextKeyIsArrayIndex ? [] : {};
|
|
86
192
|
}
|
|
87
193
|
current = current[key];
|
|
88
194
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
if (!file.name || typeof file.size !== 'number' || !file.type) {
|
|
93
|
-
throw new Error('Invalid file properties: name, size, or type is missing or invalid.');
|
|
94
|
-
}
|
|
95
|
-
const stream = await file.stream();
|
|
96
|
-
const buffer = await streamToBuffer(stream);
|
|
97
|
-
const uint8ArrayForFileType = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
98
|
-
const fileTypeInfo = await fileTypeFromBuffer(uint8ArrayForFileType);
|
|
99
|
-
let mimeType = file.type;
|
|
100
|
-
if (fileTypeInfo) {
|
|
101
|
-
mimeType = fileTypeInfo.mime;
|
|
195
|
+
const finalKey = keys[keys.length - 1];
|
|
196
|
+
if (BLOCKED_KEYS.has(finalKey)) {
|
|
197
|
+
throw new Error(`Invalid path segment: '${finalKey}' is not allowed.`);
|
|
102
198
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
199
|
+
current[finalKey] = value;
|
|
200
|
+
}
|
|
201
|
+
/** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
|
|
202
|
+
export async function streamToBuffer(stream) {
|
|
203
|
+
const chunks = [];
|
|
204
|
+
for await (const chunk of stream) {
|
|
205
|
+
if (Buffer.isBuffer(chunk)) {
|
|
206
|
+
chunks.push(chunk);
|
|
109
207
|
}
|
|
110
|
-
|
|
111
|
-
|
|
208
|
+
else if (typeof chunk === 'string') {
|
|
209
|
+
chunks.push(Buffer.from(chunk));
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
chunks.push(Buffer.from(chunk));
|
|
112
213
|
}
|
|
113
214
|
}
|
|
114
|
-
|
|
115
|
-
|
|
215
|
+
return Buffer.concat(chunks);
|
|
216
|
+
}
|
|
217
|
+
/** Validates that each map entry is an array of string paths. */
|
|
218
|
+
export function validateMap(map) {
|
|
219
|
+
for (const [key, paths] of Object.entries(map)) {
|
|
220
|
+
if (!Array.isArray(paths)) {
|
|
221
|
+
return `Invalid type for map entry '${key}': expected an array of paths.`;
|
|
222
|
+
}
|
|
223
|
+
for (const p of paths) {
|
|
224
|
+
if (typeof p !== 'string') {
|
|
225
|
+
return `Invalid path in map entry '${key}': expected string.`;
|
|
226
|
+
}
|
|
227
|
+
if (!p) {
|
|
228
|
+
return `Invalid path in map entry '${key}': path cannot be empty.`;
|
|
229
|
+
}
|
|
230
|
+
const segments = p.split('.');
|
|
231
|
+
for (const segment of segments) {
|
|
232
|
+
if (!segment) {
|
|
233
|
+
return `Invalid path in map entry '${key}': path cannot contain empty segments.`;
|
|
234
|
+
}
|
|
235
|
+
if (BLOCKED_KEYS.has(segment)) {
|
|
236
|
+
return `Invalid path segment in map entry '${key}': '${segment}' is not allowed.`;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
116
240
|
}
|
|
117
|
-
|
|
118
|
-
upload.resolve({
|
|
119
|
-
fileSize: file.size,
|
|
120
|
-
fileName: file.name,
|
|
121
|
-
mimeType: mimeType,
|
|
122
|
-
encoding: 'binary',
|
|
123
|
-
createReadStream: () => bufferToStream(buffer)
|
|
124
|
-
});
|
|
125
|
-
return upload;
|
|
241
|
+
return null;
|
|
126
242
|
}
|
|
127
|
-
/**
|
|
128
|
-
* Processes a GraphQL multipart request with file uploads.
|
|
129
|
-
*/
|
|
243
|
+
/** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
|
|
130
244
|
export async function uploadProcess(request, contextValueInput, server, settings) {
|
|
131
245
|
try {
|
|
246
|
+
const settingsError = validateSettings(settings);
|
|
247
|
+
if (settingsError) {
|
|
248
|
+
return NextResponse.json({ errors: [{ message: settingsError }] }, { status: 400 });
|
|
249
|
+
}
|
|
132
250
|
const formData = await request.formData();
|
|
133
251
|
const files = await extractFiles(formData);
|
|
134
|
-
const
|
|
135
|
-
const
|
|
136
|
-
if (!
|
|
137
|
-
|
|
252
|
+
const mapRaw = formData.get('map');
|
|
253
|
+
const operationsRaw = formData.get('operations');
|
|
254
|
+
if (!mapRaw || !operationsRaw || typeof mapRaw !== 'string' || typeof operationsRaw !== 'string') {
|
|
255
|
+
return NextResponse.json({ errors: [{ message: 'Missing or invalid map/operations in form data.' }] }, { status: 400 });
|
|
138
256
|
}
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
257
|
+
const mapString = mapRaw;
|
|
258
|
+
const operationsString = operationsRaw;
|
|
259
|
+
// Parse and validate the map field (must be an object, not array).
|
|
260
|
+
let map;
|
|
261
|
+
try {
|
|
262
|
+
map = sanitizeAndValidateJSON(mapString);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return NextResponse.json({ errors: [{ message: 'Invalid JSON in the map multipart field.' }] }, { status: 400 });
|
|
266
|
+
}
|
|
267
|
+
const mapError = validateMap(map);
|
|
268
|
+
if (mapError) {
|
|
269
|
+
return NextResponse.json({ errors: [{ message: mapError }] }, { status: 400 });
|
|
270
|
+
}
|
|
271
|
+
// Parse the operations field (object or array for batching).
|
|
272
|
+
let parsedOperations;
|
|
273
|
+
try {
|
|
274
|
+
parsedOperations = parseOperationsJSON(operationsString);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return NextResponse.json({ errors: [{ message: 'Invalid JSON in the operations multipart field.' }] }, { status: 400 });
|
|
278
|
+
}
|
|
279
|
+
if (Array.isArray(parsedOperations)) {
|
|
280
|
+
for (let i = 0; i < parsedOperations.length; i++) {
|
|
281
|
+
const operationError = validateOperation(parsedOperations[i], `operation at index ${i}`);
|
|
282
|
+
if (operationError) {
|
|
283
|
+
return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
144
286
|
}
|
|
287
|
+
else {
|
|
288
|
+
const operationError = validateOperation(parsedOperations, 'operation');
|
|
289
|
+
if (operationError) {
|
|
290
|
+
return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
// Check maxFiles limit.
|
|
294
|
+
if (settings?.maxFiles !== undefined && Object.keys(map).length > settings.maxFiles) {
|
|
295
|
+
return NextResponse.json({ errors: [{ message: `${settings.maxFiles} max file uploads exceeded.` }] }, { status: 413 });
|
|
296
|
+
}
|
|
297
|
+
// Normalize operations into a keyed object for path resolution.
|
|
298
|
+
// Single: paths are "variables.file" → use the operation object directly.
|
|
299
|
+
// Batch: paths are "0.variables.file" → use indices as keys in a wrapper object.
|
|
300
|
+
const isBatch = Array.isArray(parsedOperations);
|
|
301
|
+
let operationsRoot;
|
|
302
|
+
if (isBatch) {
|
|
303
|
+
const batchOperations = parsedOperations;
|
|
304
|
+
operationsRoot = {};
|
|
305
|
+
for (let i = 0; i < batchOperations.length; i++) {
|
|
306
|
+
const op = batchOperations[i];
|
|
307
|
+
if (!op.variables)
|
|
308
|
+
op.variables = {};
|
|
309
|
+
operationsRoot[String(i)] = op;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
const singleOp = parsedOperations;
|
|
314
|
+
if (!singleOp.variables)
|
|
315
|
+
singleOp.variables = {};
|
|
316
|
+
operationsRoot = singleOp;
|
|
317
|
+
}
|
|
318
|
+
// Process files and resolve Upload instances at mapped paths.
|
|
319
|
+
const fileProcessingPromises = [];
|
|
145
320
|
for (const fileKeyInMap of Object.keys(map)) {
|
|
146
321
|
const file = files[fileKeyInMap];
|
|
147
322
|
if (!file) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
323
|
+
// Per spec: reject Upload promise when file is missing from the request.
|
|
324
|
+
for (const filePath of map[fileKeyInMap]) {
|
|
325
|
+
const missingUpload = new Upload();
|
|
326
|
+
missingUpload.reject(new Error('File missing in the request.'));
|
|
327
|
+
setValueAtPath(operationsRoot, filePath, missingUpload);
|
|
328
|
+
}
|
|
151
329
|
continue;
|
|
152
330
|
}
|
|
153
|
-
if (settings?.maxFileSize && file.size > settings.maxFileSize) {
|
|
154
|
-
return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${settings.maxFileSize / (1024 * 1024)}MB.` }] }, { status: 413 });
|
|
331
|
+
if (settings?.maxFileSize !== undefined && file.size > settings.maxFileSize) {
|
|
332
|
+
return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${(settings.maxFileSize / (1024 * 1024)).toFixed(2)}MB.` }] }, { status: 413 });
|
|
155
333
|
}
|
|
156
334
|
const variablePaths = map[fileKeyInMap];
|
|
157
335
|
const filePromise = processUpload(file, settings?.allowedTypes)
|
|
158
336
|
.then(uploadInstance => {
|
|
159
|
-
|
|
160
|
-
setValueAtPath(
|
|
161
|
-
}
|
|
337
|
+
for (const filePath of variablePaths) {
|
|
338
|
+
setValueAtPath(operationsRoot, filePath, uploadInstance);
|
|
339
|
+
}
|
|
162
340
|
})
|
|
163
|
-
.catch(error => {
|
|
164
|
-
|
|
341
|
+
.catch((error) => {
|
|
342
|
+
for (const filePath of variablePaths) {
|
|
165
343
|
const uploadError = new Upload();
|
|
166
344
|
uploadError.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
|
|
167
|
-
setValueAtPath(
|
|
168
|
-
}
|
|
169
|
-
throw new Error(`Failed to process file ${file.name}: ${error.message}`);
|
|
345
|
+
setValueAtPath(operationsRoot, filePath, uploadError);
|
|
346
|
+
}
|
|
170
347
|
});
|
|
171
348
|
fileProcessingPromises.push(filePromise);
|
|
172
349
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
else if (response.body.kind === 'incremental') {
|
|
184
|
-
const { initialResult, subsequentResults } = response.body;
|
|
185
|
-
const collectedSubsequentResults = [];
|
|
186
|
-
for await (const result of subsequentResults) {
|
|
187
|
-
collectedSubsequentResults.push(result);
|
|
350
|
+
await Promise.all(fileProcessingPromises);
|
|
351
|
+
// Execute operations and collect results.
|
|
352
|
+
if (isBatch) {
|
|
353
|
+
const results = [];
|
|
354
|
+
const sortedKeys = Object.keys(operationsRoot).sort((a, b) => Number(a) - Number(b));
|
|
355
|
+
for (const key of sortedKeys) {
|
|
356
|
+
const op = operationsRoot[key];
|
|
357
|
+
const response = await server.executeOperation({ query: op.query, variables: op.variables || {} }, { contextValue: contextValueInput });
|
|
358
|
+
results.push(await collectResponse(response));
|
|
188
359
|
}
|
|
189
|
-
return NextResponse.json(
|
|
190
|
-
initialResult,
|
|
191
|
-
subsequentResults: collectedSubsequentResults,
|
|
192
|
-
});
|
|
360
|
+
return NextResponse.json(results);
|
|
193
361
|
}
|
|
194
|
-
|
|
362
|
+
const response = await server.executeOperation({ query: operationsRoot.query, variables: operationsRoot.variables }, { contextValue: contextValueInput });
|
|
363
|
+
return NextResponse.json(await collectResponse(response));
|
|
195
364
|
}
|
|
196
365
|
catch (error) {
|
|
197
366
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error during upload processing.';
|