multermate 1.1.0 → 2.1.0

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.
@@ -0,0 +1,452 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MIME_TYPES = exports.ALLOWED_FILE_TYPES = exports.MultermateError = void 0;
7
+ exports.uploadSingle = uploadSingle;
8
+ exports.uploadMultiple = uploadMultiple;
9
+ exports.deleteFile = deleteFile;
10
+ const promises_1 = __importDefault(require("fs/promises"));
11
+ const multer_1 = __importDefault(require("multer"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const uuid_1 = require("uuid");
14
+ // Custom error class for MulterMate
15
+ class MultermateError extends Error {
16
+ constructor(message, code, field) {
17
+ super(message);
18
+ this.name = 'MultermateError';
19
+ this.code = code;
20
+ this.field = field;
21
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
22
+ if (Error.captureStackTrace) {
23
+ Error.captureStackTrace(this, MultermateError);
24
+ }
25
+ }
26
+ }
27
+ exports.MultermateError = MultermateError;
28
+ // Define allowed MIME types - comprehensive list including all common file types
29
+ const ALLOWED_MIME_TYPES = {
30
+ // Images (all common image formats)
31
+ images: [
32
+ "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp",
33
+ "image/svg+xml", "image/bmp", "image/tiff", "image/ico", "image/avif",
34
+ "image/heic", "image/heif", "image/x-icon", "image/vnd.microsoft.icon"
35
+ ],
36
+ // Videos (all common video formats)
37
+ videos: [
38
+ "video/mp4", "video/mpeg", "video/ogg", "video/webm", "video/avi",
39
+ "video/mov", "video/wmv", "video/flv", "video/mkv", "video/m4v", "video/3gp",
40
+ "video/quicktime", "video/x-msvideo", "video/x-ms-wmv", "video/x-flv"
41
+ ],
42
+ // Audio (all common audio formats)
43
+ audio: [
44
+ "audio/mpeg", "audio/wav", "audio/ogg", "audio/aac", "audio/flac",
45
+ "audio/m4a", "audio/wma", "audio/mp3", "audio/webm", "audio/x-wav",
46
+ "audio/x-m4a", "audio/x-aac", "audio/opus", "audio/amr"
47
+ ],
48
+ // Documents (all common document formats)
49
+ documents: [
50
+ "application/pdf", "application/msword",
51
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
52
+ "application/vnd.ms-excel",
53
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
54
+ "application/vnd.ms-powerpoint",
55
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
56
+ "application/rtf", "application/vnd.oasis.opendocument.text",
57
+ "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.presentation",
58
+ "application/vnd.apple.pages", "application/vnd.apple.numbers", "application/vnd.apple.keynote"
59
+ ],
60
+ // Text files (all common text formats)
61
+ text: [
62
+ "text/plain", "text/csv", "text/html", "text/css", "text/javascript",
63
+ "text/xml", "text/markdown", "text/x-python", "text/x-java-source",
64
+ "text/x-c", "text/x-c++", "text/x-php", "text/x-ruby", "text/x-go",
65
+ "text/x-rust", "text/x-typescript", "text/x-swift", "text/x-kotlin",
66
+ "text/x-scala", "text/x-perl", "text/x-shell", "text/x-sh", "text/x-bash",
67
+ "text/x-yaml", "text/yaml", "text/x-toml", "text/x-ini", "text/x-log"
68
+ ],
69
+ // Archives (all common archive formats)
70
+ archives: [
71
+ "application/zip", "application/x-rar-compressed", "application/x-tar",
72
+ "application/gzip", "application/x-7z-compressed", "application/x-bzip2",
73
+ "application/x-xz", "application/x-compress", "application/x-lz4",
74
+ "application/x-lzma", "application/vnd.rar"
75
+ ],
76
+ // Code files (programming language files)
77
+ code: [
78
+ "application/json", "application/xml", "application/javascript",
79
+ "application/typescript", "text/x-python", "text/x-java-source",
80
+ "text/x-c", "text/x-c++", "text/x-php", "text/x-ruby", "text/x-go",
81
+ "text/x-rust", "text/x-swift", "text/x-kotlin", "text/x-scala",
82
+ "text/x-csharp", "text/x-vb", "text/x-sql", "application/sql"
83
+ ],
84
+ // Spreadsheets (separate category)
85
+ spreadsheets: [
86
+ "application/vnd.ms-excel",
87
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
88
+ "text/csv", "application/csv"
89
+ ],
90
+ // Presentations (separate category)
91
+ presentations: [
92
+ "application/vnd.ms-powerpoint",
93
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
94
+ "application/vnd.oasis.opendocument.presentation"
95
+ ],
96
+ // Fonts (font files)
97
+ fonts: [
98
+ "font/woff", "font/woff2", "font/ttf", "font/otf", "font/eot",
99
+ "application/font-woff", "application/font-woff2", "application/x-font-ttf",
100
+ "application/x-font-otf", "application/vnd.ms-fontobject"
101
+ ],
102
+ // CAD files
103
+ cad: [
104
+ "application/dwg", "application/dxf", "model/vnd.dwf",
105
+ "application/acad", "image/vnd.dwg"
106
+ ],
107
+ // 3D models
108
+ models: [
109
+ "model/obj", "model/gltf+json", "model/gltf-binary", "model/x3d+xml",
110
+ "model/stl", "model/ply", "application/x-blender"
111
+ ],
112
+ // PDFs (separate category for backward compatibility)
113
+ pdfs: ["application/pdf"],
114
+ // All allowed types - comprehensive list (this is for backward compatibility)
115
+ all: [
116
+ // Images
117
+ "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp",
118
+ "image/svg+xml", "image/bmp", "image/tiff", "image/ico", "image/avif",
119
+ "image/heic", "image/heif", "image/x-icon", "image/vnd.microsoft.icon",
120
+ // Videos
121
+ "video/mp4", "video/mpeg", "video/ogg", "video/webm", "video/avi",
122
+ "video/mov", "video/wmv", "video/flv", "video/mkv", "video/m4v", "video/3gp",
123
+ "video/quicktime", "video/x-msvideo", "video/x-ms-wmv", "video/x-flv",
124
+ // Audio
125
+ "audio/mpeg", "audio/wav", "audio/ogg", "audio/aac", "audio/flac",
126
+ "audio/m4a", "audio/wma", "audio/mp3", "audio/webm", "audio/x-wav",
127
+ "audio/x-m4a", "audio/x-aac", "audio/opus", "audio/amr",
128
+ // Documents
129
+ "application/pdf", "application/msword",
130
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
131
+ "application/vnd.ms-excel",
132
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
133
+ "application/vnd.ms-powerpoint",
134
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
135
+ "application/rtf", "application/vnd.oasis.opendocument.text",
136
+ "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.presentation",
137
+ "application/vnd.apple.pages", "application/vnd.apple.numbers", "application/vnd.apple.keynote",
138
+ // Text files
139
+ "text/plain", "text/csv", "text/html", "text/css", "text/javascript",
140
+ "text/xml", "text/markdown", "text/x-python", "text/x-java-source",
141
+ "text/x-c", "text/x-c++", "text/x-php", "text/x-ruby", "text/x-go",
142
+ "text/x-rust", "text/x-typescript", "text/x-swift", "text/x-kotlin",
143
+ "text/x-scala", "text/x-perl", "text/x-shell", "text/x-sh", "text/x-bash",
144
+ "text/x-yaml", "text/yaml", "text/x-toml", "text/x-ini", "text/x-log",
145
+ // Archives
146
+ "application/zip", "application/x-rar-compressed", "application/x-tar",
147
+ "application/gzip", "application/x-7z-compressed", "application/x-bzip2",
148
+ "application/x-xz", "application/x-compress", "application/x-lz4",
149
+ "application/x-lzma", "application/vnd.rar",
150
+ // Code/Data
151
+ "application/json", "application/xml", "application/javascript",
152
+ "application/typescript", "text/x-csharp", "text/x-vb", "text/x-sql", "application/sql",
153
+ // Fonts
154
+ "font/woff", "font/woff2", "font/ttf", "font/otf", "font/eot",
155
+ "application/font-woff", "application/font-woff2", "application/x-font-ttf",
156
+ "application/x-font-otf", "application/vnd.ms-fontobject"
157
+ ],
158
+ };
159
+ /**
160
+ * Function to configure storage for Multer.
161
+ *
162
+ * @param destination - The destination folder where files will be stored.
163
+ * @returns Multer storage configuration object.
164
+ */
165
+ const configureStorage = (destination) => {
166
+ return multer_1.default.diskStorage({
167
+ destination: (req, file, cb) => {
168
+ const dir = destination || "uploads";
169
+ // Create directory synchronously to avoid callback issues
170
+ try {
171
+ require('fs').mkdirSync(dir, { recursive: true });
172
+ cb(null, dir);
173
+ }
174
+ catch (error) {
175
+ // Directory might already exist, that's okay
176
+ if (error.code === 'EEXIST') {
177
+ cb(null, dir);
178
+ }
179
+ else {
180
+ cb(new MultermateError(`Failed to create destination directory: ${dir}`, 'DESTINATION_ERROR'), '');
181
+ }
182
+ }
183
+ },
184
+ filename: (_req, file, cb) => {
185
+ try {
186
+ const sanitizedFilename = file.originalname.replace(/\\/g, "/");
187
+ const extension = path_1.default.extname(sanitizedFilename);
188
+ const fieldName = file.fieldname || "file";
189
+ const uniqueName = (0, uuid_1.v4)();
190
+ let fileName = `${uniqueName}-${fieldName}${extension}`;
191
+ // Replace backslashes with forward slashes in the final filename
192
+ fileName = fileName.replace(/\\/g, "/");
193
+ cb(null, fileName);
194
+ }
195
+ catch (error) {
196
+ cb(new MultermateError('Failed to generate filename', 'FILENAME_ERROR'), '');
197
+ }
198
+ },
199
+ });
200
+ };
201
+ /**
202
+ * Function to configure file filter for Multer.
203
+ *
204
+ * @param allowedMimeTypes - Array of allowed MIME types. Empty array means allow all file types.
205
+ * @returns File filter function for Multer.
206
+ */
207
+ const configureFileFilter = (allowedMimeTypes) => {
208
+ return (_req, file, cb) => {
209
+ try {
210
+ // If no specific file types are restricted, allow ALL file types
211
+ if (allowedMimeTypes.length === 0) {
212
+ cb(null, true);
213
+ return;
214
+ }
215
+ // Check if the file's MIME type is in the allowed list
216
+ if (allowedMimeTypes.includes(file.mimetype)) {
217
+ cb(null, true);
218
+ }
219
+ else {
220
+ const error = new MultermateError(`Invalid file type: ${file.mimetype}. Allowed types: ${allowedMimeTypes.join(', ')}`, 'INVALID_FILE_TYPE', file.fieldname);
221
+ cb(error);
222
+ }
223
+ }
224
+ catch (error) {
225
+ cb(new MultermateError('File filter error', 'FILTER_ERROR'));
226
+ }
227
+ };
228
+ };
229
+ /**
230
+ * Function to configure Multer with the provided options.
231
+ *
232
+ * @param options - Configuration options for Multer.
233
+ * @returns Multer instance configured with the provided options.
234
+ */
235
+ const configureMulter = ({ destination, filename, fileTypes = [], customMimeTypes = [], fileSizeLimit, preservePath = false, }) => {
236
+ try {
237
+ const storage = configureStorage(destination);
238
+ // Combine allowed MIME types based on fileTypes array
239
+ let allowedMimeTypes = [];
240
+ if (customMimeTypes.length > 0) {
241
+ // Use custom MIME types if provided
242
+ allowedMimeTypes = customMimeTypes;
243
+ }
244
+ else if (fileTypes.length > 0) {
245
+ // Use default MIME types for specified fileTypes
246
+ fileTypes.forEach((type) => {
247
+ if (ALLOWED_MIME_TYPES[type]) {
248
+ allowedMimeTypes = allowedMimeTypes.concat(ALLOWED_MIME_TYPES[type]);
249
+ }
250
+ });
251
+ }
252
+ // If neither customMimeTypes nor fileTypes are provided, allowedMimeTypes remains empty
253
+ // This means ALL file types are allowed (no restrictions)
254
+ // Remove duplicates
255
+ allowedMimeTypes = [...new Set(allowedMimeTypes)];
256
+ const fileFilter = configureFileFilter(allowedMimeTypes);
257
+ return (0, multer_1.default)({
258
+ storage,
259
+ fileFilter,
260
+ limits: { fileSize: fileSizeLimit || 1024 * 1024 * 50 }, // Default 50MB file size limit
261
+ preservePath,
262
+ });
263
+ }
264
+ catch (error) {
265
+ throw new MultermateError('Failed to configure multer', 'CONFIGURATION_ERROR');
266
+ }
267
+ };
268
+ /**
269
+ * Function to handle a single file upload.
270
+ *
271
+ * @param options - Configuration options for the single file upload.
272
+ * @returns Multer middleware configured for single file upload.
273
+ */
274
+ function uploadSingle(options = {}) {
275
+ try {
276
+ const destination = options.destination || 'uploads';
277
+ const multerInstance = configureMulter(options);
278
+ const middleware = multerInstance.single(options.filename || "file");
279
+ return (req, res, next) => {
280
+ // Make sure the destination directory exists
281
+ try {
282
+ require('fs').mkdirSync(destination, { recursive: true });
283
+ }
284
+ catch (error) {
285
+ // Directory might already exist, ignore error
286
+ }
287
+ middleware(req, res, (err) => {
288
+ if (err) {
289
+ let errorMessage = 'Unknown upload error';
290
+ let errorCode = 'UPLOAD_ERROR';
291
+ if (err instanceof MultermateError) {
292
+ // Our custom error
293
+ req.fileValidationError = err.message;
294
+ return next(err);
295
+ }
296
+ else if (err.code === 'LIMIT_FILE_SIZE') {
297
+ errorMessage = `File size limit exceeded. Maximum allowed size: ${options.fileSizeLimit || '50MB'}`;
298
+ errorCode = 'FILE_SIZE_LIMIT_EXCEEDED';
299
+ }
300
+ else if (err.code === 'INVALID_FILE_TYPE') {
301
+ errorMessage = 'Invalid file type. Please check allowed file types.';
302
+ errorCode = 'INVALID_FILE_TYPE';
303
+ }
304
+ else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
305
+ errorMessage = 'Unexpected field';
306
+ errorCode = 'UNEXPECTED_FIELD';
307
+ }
308
+ else {
309
+ errorMessage = err.message || 'Upload failed';
310
+ }
311
+ const multermateError = new MultermateError(errorMessage, errorCode);
312
+ req.fileValidationError = errorMessage;
313
+ return next(multermateError);
314
+ }
315
+ next();
316
+ });
317
+ };
318
+ }
319
+ catch (error) {
320
+ throw new MultermateError('Failed to create upload middleware', 'MIDDLEWARE_CREATION_ERROR');
321
+ }
322
+ }
323
+ /**
324
+ * Function to handle multiple file uploads across multiple fields.
325
+ *
326
+ * @param options - Configuration options for multiple file uploads.
327
+ * @returns Multer middleware configured for multiple file uploads.
328
+ */
329
+ function uploadMultiple(options) {
330
+ try {
331
+ const destination = options.destination || 'uploads';
332
+ // Map fields configuration to multer format
333
+ const fieldConfigs = options.fields.map(field => ({
334
+ name: field.name,
335
+ maxCount: field.maxCount || 10, // Default maxCount is 10 if not specified.
336
+ }));
337
+ // Collect all allowed file types from fields
338
+ let allowedFileTypes = [];
339
+ if (options.customMimeTypes && options.customMimeTypes.length > 0) {
340
+ // Use custom MIME types if provided at the global level
341
+ allowedFileTypes = options.customMimeTypes;
342
+ }
343
+ else {
344
+ // Collect file types from individual fields
345
+ options.fields.forEach((field) => {
346
+ const types = field.fileTypes || [];
347
+ types.forEach((type) => {
348
+ if (ALLOWED_MIME_TYPES[type]) {
349
+ allowedFileTypes = allowedFileTypes.concat(ALLOWED_MIME_TYPES[type]);
350
+ }
351
+ });
352
+ });
353
+ }
354
+ const multerConfig = {
355
+ destination,
356
+ fileTypes: [],
357
+ customMimeTypes: allowedFileTypes.length > 0 ? allowedFileTypes : [],
358
+ fileSizeLimit: options.fileSizeLimit,
359
+ preservePath: options.preservePath
360
+ };
361
+ const multerInstance = configureMulter(multerConfig);
362
+ const middleware = multerInstance.fields(fieldConfigs);
363
+ return (req, res, next) => {
364
+ // Make sure the destination directory exists
365
+ try {
366
+ require('fs').mkdirSync(destination, { recursive: true });
367
+ }
368
+ catch (error) {
369
+ // Directory might already exist, ignore error
370
+ }
371
+ middleware(req, res, (err) => {
372
+ if (err) {
373
+ let errorMessage = 'Unknown upload error';
374
+ let errorCode = 'UPLOAD_ERROR';
375
+ if (err instanceof MultermateError) {
376
+ // Our custom error
377
+ req.fileValidationError = err.message;
378
+ return next(err);
379
+ }
380
+ else if (err.code === 'LIMIT_FILE_SIZE') {
381
+ errorMessage = `File size limit exceeded. Maximum allowed size: ${options.fileSizeLimit || '50MB'}`;
382
+ errorCode = 'FILE_SIZE_LIMIT_EXCEEDED';
383
+ }
384
+ else if (err.code === 'INVALID_FILE_TYPE') {
385
+ errorMessage = 'Invalid file type. Please check allowed file types.';
386
+ errorCode = 'INVALID_FILE_TYPE';
387
+ }
388
+ else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
389
+ errorMessage = 'Unexpected field';
390
+ errorCode = 'UNEXPECTED_FIELD';
391
+ }
392
+ else if (err.code === 'LIMIT_FILE_COUNT') {
393
+ errorMessage = 'Too many files';
394
+ errorCode = 'FILE_COUNT_LIMIT_EXCEEDED';
395
+ }
396
+ else {
397
+ errorMessage = err.message || 'Upload failed';
398
+ }
399
+ const multermateError = new MultermateError(errorMessage, errorCode);
400
+ req.fileValidationError = errorMessage;
401
+ return next(multermateError);
402
+ }
403
+ next();
404
+ });
405
+ };
406
+ }
407
+ catch (error) {
408
+ throw new MultermateError('Failed to create multiple upload middleware', 'MIDDLEWARE_CREATION_ERROR');
409
+ }
410
+ }
411
+ /**
412
+ * Utility function to delete a file from the filesystem
413
+ *
414
+ * @param filePath - The path to the file that needs to be deleted
415
+ * @returns Promise that resolves to true if deletion was successful, false otherwise
416
+ */
417
+ async function deleteFile(filePath) {
418
+ try {
419
+ if (!filePath || typeof filePath !== 'string') {
420
+ throw new MultermateError('Invalid file path provided', 'INVALID_PATH');
421
+ }
422
+ await promises_1.default.unlink(filePath);
423
+ return true;
424
+ }
425
+ catch (error) {
426
+ if (error instanceof MultermateError) {
427
+ throw error;
428
+ }
429
+ if (error.code === 'ENOENT') {
430
+ throw new MultermateError(`File not found: ${filePath}`, 'FILE_NOT_FOUND');
431
+ }
432
+ else if (error.code === 'EACCES') {
433
+ throw new MultermateError(`Permission denied: ${filePath}`, 'PERMISSION_DENIED');
434
+ }
435
+ else {
436
+ throw new MultermateError(`Failed to delete file: ${error.message}`, 'DELETE_ERROR');
437
+ }
438
+ }
439
+ }
440
+ // Export the allowed file types for reference
441
+ exports.ALLOWED_FILE_TYPES = Object.keys(ALLOWED_MIME_TYPES);
442
+ // Export MIME types for external use
443
+ exports.MIME_TYPES = ALLOWED_MIME_TYPES;
444
+ // Export your functions
445
+ exports.default = {
446
+ uploadSingle,
447
+ uploadMultiple,
448
+ deleteFile,
449
+ MultermateError,
450
+ ALLOWED_FILE_TYPES: exports.ALLOWED_FILE_TYPES,
451
+ MIME_TYPES: exports.MIME_TYPES
452
+ };