jtcsv 2.2.7 → 3.0.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.
Files changed (140) hide show
  1. package/README.md +31 -1
  2. package/bin/jtcsv.js +891 -821
  3. package/bin/jtcsv.ts +2534 -0
  4. package/csv-to-json.js +168 -145
  5. package/dist/jtcsv-core.cjs.js +1407 -0
  6. package/dist/jtcsv-core.cjs.js.map +1 -0
  7. package/dist/jtcsv-core.esm.js +1379 -0
  8. package/dist/jtcsv-core.esm.js.map +1 -0
  9. package/dist/jtcsv-core.umd.js +1413 -0
  10. package/dist/jtcsv-core.umd.js.map +1 -0
  11. package/dist/jtcsv-full.cjs.js +1912 -0
  12. package/dist/jtcsv-full.cjs.js.map +1 -0
  13. package/dist/jtcsv-full.esm.js +1880 -0
  14. package/dist/jtcsv-full.esm.js.map +1 -0
  15. package/dist/jtcsv-full.umd.js +1918 -0
  16. package/dist/jtcsv-full.umd.js.map +1 -0
  17. package/dist/jtcsv-workers.esm.js +759 -0
  18. package/dist/jtcsv-workers.esm.js.map +1 -0
  19. package/dist/jtcsv-workers.umd.js +773 -0
  20. package/dist/jtcsv-workers.umd.js.map +1 -0
  21. package/dist/jtcsv.cjs.js +61 -19
  22. package/dist/jtcsv.cjs.js.map +1 -1
  23. package/dist/jtcsv.esm.js +61 -19
  24. package/dist/jtcsv.esm.js.map +1 -1
  25. package/dist/jtcsv.umd.js +61 -19
  26. package/dist/jtcsv.umd.js.map +1 -1
  27. package/errors.js +188 -2
  28. package/examples/advanced/conditional-transformations.js +446 -0
  29. package/examples/advanced/conditional-transformations.ts +446 -0
  30. package/examples/advanced/csv-parser.worker.js +89 -0
  31. package/examples/advanced/csv-parser.worker.ts +89 -0
  32. package/examples/advanced/nested-objects-example.js +306 -0
  33. package/examples/advanced/nested-objects-example.ts +306 -0
  34. package/examples/advanced/performance-optimization.js +504 -0
  35. package/examples/advanced/performance-optimization.ts +504 -0
  36. package/examples/advanced/run-demo-server.js +116 -0
  37. package/examples/advanced/run-demo-server.ts +116 -0
  38. package/examples/advanced/web-worker-usage.html +874 -0
  39. package/examples/async-multithreaded-example.ts +335 -0
  40. package/examples/cli-advanced-usage.md +288 -0
  41. package/examples/cli-batch-processing.ts +38 -0
  42. package/examples/cli-tool.js +0 -3
  43. package/examples/cli-tool.ts +183 -0
  44. package/examples/error-handling.js +21 -7
  45. package/examples/error-handling.ts +356 -0
  46. package/examples/express-api.js +0 -3
  47. package/examples/express-api.ts +164 -0
  48. package/examples/large-dataset-example.js +0 -3
  49. package/examples/large-dataset-example.ts +204 -0
  50. package/examples/ndjson-processing.js +1 -1
  51. package/examples/ndjson-processing.ts +456 -0
  52. package/examples/plugin-excel-exporter.js +3 -4
  53. package/examples/plugin-excel-exporter.ts +406 -0
  54. package/examples/react-integration.tsx +637 -0
  55. package/examples/schema-validation.ts +640 -0
  56. package/examples/simple-usage.js +254 -254
  57. package/examples/simple-usage.ts +194 -0
  58. package/examples/streaming-example.js +4 -5
  59. package/examples/streaming-example.ts +419 -0
  60. package/examples/web-workers-advanced.ts +28 -0
  61. package/index.d.ts +1 -3
  62. package/index.js +15 -1
  63. package/json-save.js +9 -3
  64. package/json-to-csv.js +168 -21
  65. package/package.json +69 -10
  66. package/plugins/express-middleware/README.md +21 -2
  67. package/plugins/express-middleware/example.js +3 -4
  68. package/plugins/express-middleware/example.ts +135 -0
  69. package/plugins/express-middleware/index.d.ts +1 -1
  70. package/plugins/express-middleware/index.js +270 -118
  71. package/plugins/express-middleware/index.ts +557 -0
  72. package/plugins/fastify-plugin/index.js +2 -4
  73. package/plugins/fastify-plugin/index.ts +443 -0
  74. package/plugins/hono/index.ts +226 -0
  75. package/plugins/nestjs/index.ts +201 -0
  76. package/plugins/nextjs-api/examples/ConverterComponent.tsx +386 -0
  77. package/plugins/nextjs-api/examples/api-convert.js +0 -2
  78. package/plugins/nextjs-api/examples/api-convert.ts +67 -0
  79. package/plugins/nextjs-api/index.tsx +339 -0
  80. package/plugins/nextjs-api/route.js +2 -3
  81. package/plugins/nextjs-api/route.ts +370 -0
  82. package/plugins/nuxt/index.ts +94 -0
  83. package/plugins/nuxt/runtime/composables/useJtcsv.ts +100 -0
  84. package/plugins/nuxt/runtime/plugin.ts +71 -0
  85. package/plugins/remix/index.js +1 -1
  86. package/plugins/remix/index.ts +260 -0
  87. package/plugins/sveltekit/index.js +1 -1
  88. package/plugins/sveltekit/index.ts +301 -0
  89. package/plugins/trpc/index.ts +267 -0
  90. package/src/browser/browser-functions.ts +402 -0
  91. package/src/browser/core.js +92 -0
  92. package/src/browser/core.ts +152 -0
  93. package/src/browser/csv-to-json-browser.d.ts +3 -0
  94. package/src/browser/csv-to-json-browser.js +36 -14
  95. package/src/browser/csv-to-json-browser.ts +264 -0
  96. package/src/browser/errors-browser.ts +303 -0
  97. package/src/browser/extensions/plugins.js +92 -0
  98. package/src/browser/extensions/plugins.ts +93 -0
  99. package/src/browser/extensions/workers.js +39 -0
  100. package/src/browser/extensions/workers.ts +39 -0
  101. package/src/browser/globals.d.ts +5 -0
  102. package/src/browser/index.ts +192 -0
  103. package/src/browser/json-to-csv-browser.d.ts +3 -0
  104. package/src/browser/json-to-csv-browser.js +13 -3
  105. package/src/browser/json-to-csv-browser.ts +262 -0
  106. package/src/browser/streams.js +12 -2
  107. package/src/browser/streams.ts +336 -0
  108. package/src/browser/workers/csv-parser.worker.ts +377 -0
  109. package/src/browser/workers/worker-pool.ts +548 -0
  110. package/src/core/delimiter-cache.js +22 -8
  111. package/src/core/delimiter-cache.ts +310 -0
  112. package/src/core/node-optimizations.ts +449 -0
  113. package/src/core/plugin-system.js +29 -11
  114. package/src/core/plugin-system.ts +400 -0
  115. package/src/core/transform-hooks.ts +558 -0
  116. package/src/engines/fast-path-engine-new.ts +347 -0
  117. package/src/engines/fast-path-engine.ts +854 -0
  118. package/src/errors.ts +72 -0
  119. package/src/formats/ndjson-parser.ts +469 -0
  120. package/src/formats/tsv-parser.ts +334 -0
  121. package/src/index-with-plugins.js +16 -9
  122. package/src/index-with-plugins.ts +395 -0
  123. package/src/types/index.ts +255 -0
  124. package/src/utils/bom-utils.js +259 -0
  125. package/src/utils/bom-utils.ts +373 -0
  126. package/src/utils/encoding-support.js +124 -0
  127. package/src/utils/encoding-support.ts +155 -0
  128. package/src/utils/schema-validator.js +19 -19
  129. package/src/utils/schema-validator.ts +819 -0
  130. package/src/utils/transform-loader.js +1 -1
  131. package/src/utils/transform-loader.ts +389 -0
  132. package/src/utils/zod-adapter.js +170 -0
  133. package/src/utils/zod-adapter.ts +280 -0
  134. package/src/web-server/index.js +10 -10
  135. package/src/web-server/index.ts +683 -0
  136. package/src/workers/csv-multithreaded.ts +310 -0
  137. package/src/workers/csv-parser.worker.ts +227 -0
  138. package/src/workers/worker-pool.ts +409 -0
  139. package/stream-csv-to-json.js +26 -8
  140. package/stream-json-to-csv.js +1 -0
@@ -147,7 +147,7 @@ function createTransformHook(transform) {
147
147
  }
148
148
 
149
149
  // Return a hook function compatible with hooks.perRow
150
- return function(row, index, context) {
150
+ return function (row, index, context) {
151
151
  try {
152
152
  return transformFn(row, index);
153
153
  } catch (error) {
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Transform Loader Utility
3
+ *
4
+ * Utility for loading and applying transform functions from JavaScript files
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as fsPromises from 'fs/promises';
9
+ import * as path from 'path';
10
+ import * as vm from 'vm';
11
+ import {
12
+ ValidationError,
13
+ SecurityError,
14
+ ConfigurationError
15
+ } from '../errors';
16
+
17
+ /**
18
+ * Validates transform function
19
+ */
20
+ function validateTransformFunction(fn: Function): boolean {
21
+ if (typeof fn !== 'function') {
22
+ throw new ValidationError('Transform must export a function');
23
+ }
24
+
25
+ // Check function arity (should accept 1-2 parameters)
26
+ const functionString = fn.toString();
27
+ const paramMatch = functionString.match(/\(([^)]*)\)/);
28
+ if (paramMatch) {
29
+ const params = paramMatch[1].split(',').map(p => p.trim()).filter(p => p);
30
+ if (params.length === 0 || params.length > 2) {
31
+ throw new ValidationError('Transform function should accept 1-2 parameters: (row, index)');
32
+ }
33
+ }
34
+
35
+ return true;
36
+ }
37
+
38
+ /**
39
+ * Loads transform function from a JavaScript file
40
+ *
41
+ * @param transformPath - Path to JavaScript file with transform function
42
+ * @returns Transform function
43
+ *
44
+ * @example
45
+ * // transform.js
46
+ * module.exports = function(row, index) {
47
+ * return { ...row, processed: true, index };
48
+ * };
49
+ *
50
+ * // Usage
51
+ * const transform = loadTransform('./transform.js');
52
+ * const result = transform({ id: 1, name: 'John' }, 0);
53
+ */
54
+ export function loadTransform(transformPath: string): Function {
55
+ if (!transformPath || typeof transformPath !== 'string') {
56
+ throw new ValidationError('Transform path must be a string');
57
+ }
58
+
59
+ // Validate file path
60
+ const safePath = path.resolve(transformPath);
61
+
62
+ // Prevent directory traversal
63
+ const normalizedPath = path.normalize(transformPath);
64
+ if (normalizedPath.includes('..') ||
65
+ /\\\.\.\\|\/\.\.\//.test(transformPath) ||
66
+ transformPath.startsWith('..') ||
67
+ transformPath.includes('/..')) {
68
+ throw new SecurityError('Directory traversal detected in transform file path');
69
+ }
70
+
71
+ // Check file exists and has .js extension
72
+ if (!fs.existsSync(safePath)) {
73
+ throw new ValidationError(`Transform file not found: ${transformPath}`);
74
+ }
75
+
76
+ if (!safePath.toLowerCase().endsWith('.js')) {
77
+ throw new ValidationError('Transform file must have .js extension');
78
+ }
79
+
80
+ try {
81
+ // Read and evaluate the transform file in a safe context
82
+ const transformCode = fs.readFileSync(safePath, 'utf8');
83
+
84
+ // Create a safe context with limited access
85
+ const sandbox = {
86
+ console,
87
+ require,
88
+ module: { exports: {} },
89
+ exports: {},
90
+ __filename: safePath,
91
+ __dirname: path.dirname(safePath),
92
+ Buffer,
93
+ process: {
94
+ env: process.env,
95
+ cwd: process.cwd,
96
+ platform: process.platform
97
+ }
98
+ };
99
+
100
+ // Create a context and run the code
101
+ const context = vm.createContext(sandbox);
102
+ const script = new vm.Script(transformCode, { filename: safePath });
103
+ script.runInContext(context);
104
+
105
+ // Get the exported function
106
+ const transformFn = (context as any).module.exports || (context as any).exports;
107
+
108
+ // Handle default export for ES6 modules
109
+ const finalTransform = transformFn.default || transformFn;
110
+
111
+ // Validate the transform function
112
+ validateTransformFunction(finalTransform);
113
+
114
+ return finalTransform;
115
+ } catch (error: any) {
116
+ if (error instanceof ValidationError || error instanceof SecurityError) {
117
+ throw error;
118
+ }
119
+
120
+ if (error.code === 'EACCES') {
121
+ throw new SecurityError(`Permission denied reading transform file: ${transformPath}`);
122
+ }
123
+
124
+ throw new ValidationError(`Failed to load transform function: ${error.message}`);
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Creates a transform hook for use with csvToJson/jsonToCsv hooks system
130
+ *
131
+ * @param transform - Transform function or path to transform file
132
+ * @returns Transform hook function
133
+ */
134
+ export function createTransformHook(transform: string | Function): (row: any, index: number, context: any) => any {
135
+ let transformFn: Function;
136
+
137
+ if (typeof transform === 'string') {
138
+ // Load transform from file
139
+ transformFn = loadTransform(transform);
140
+ } else if (typeof transform === 'function') {
141
+ // Use provided function
142
+ validateTransformFunction(transform);
143
+ transformFn = transform;
144
+ } else {
145
+ throw new ValidationError('Transform must be a function or a path to a JavaScript file');
146
+ }
147
+
148
+ // Return a hook function compatible with hooks.perRow
149
+ return function (row: any, index: number, context: any): any {
150
+ try {
151
+ return transformFn(row, index);
152
+ } catch (error: any) {
153
+ // Log error but don't crash - return original row
154
+ console.error(`Transform error at row ${index}: ${error.message}`);
155
+ if (process.env['NODE_ENV'] === 'development') {
156
+ console.error(error.stack);
157
+ }
158
+ return row;
159
+ }
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Applies transform to data array
165
+ *
166
+ * @param data - Array of data to transform
167
+ * @param transform - Transform function or path to transform file
168
+ * @returns Transformed data
169
+ */
170
+ export function applyTransform(data: any[], transform: string | Function): any[] {
171
+ if (!Array.isArray(data)) {
172
+ throw new ValidationError('Data must be an array');
173
+ }
174
+
175
+ const transformHook = createTransformHook(transform);
176
+
177
+ return data.map((row, index) => {
178
+ return transformHook(row, index, { operation: 'applyTransform' });
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Creates a TransformHooks instance with transform function
184
+ *
185
+ * @param transform - Transform function or path to transform file
186
+ * @returns TransformHooks instance
187
+ */
188
+ export function createTransformHooksWithTransform(transform: string | Function): any {
189
+ const { TransformHooks } = require('../core/transform-hooks');
190
+ const hooks = new TransformHooks();
191
+
192
+ const transformHook = createTransformHook(transform);
193
+ hooks.perRow(transformHook);
194
+
195
+ return hooks;
196
+ }
197
+
198
+ /**
199
+ * Async version of loadTransform that reads file asynchronously
200
+ *
201
+ * @param transformPath - Path to JavaScript file with transform function
202
+ * @returns Promise with transform function
203
+ */
204
+ export async function loadTransformAsync(transformPath: string): Promise<Function> {
205
+ if (!transformPath || typeof transformPath !== 'string') {
206
+ throw new ValidationError('Transform path must be a string');
207
+ }
208
+
209
+ // Validate file path
210
+ const safePath = path.resolve(transformPath);
211
+
212
+ // Prevent directory traversal
213
+ const normalizedPath = path.normalize(transformPath);
214
+ if (normalizedPath.includes('..') ||
215
+ /\\\.\.\\|\/\.\.\//.test(transformPath) ||
216
+ transformPath.startsWith('..') ||
217
+ transformPath.includes('/..')) {
218
+ throw new SecurityError('Directory traversal detected in transform file path');
219
+ }
220
+
221
+ // Check file exists and has .js extension
222
+ try {
223
+ await fsPromises.access(safePath);
224
+ } catch {
225
+ throw new ValidationError(`Transform file not found: ${transformPath}`);
226
+ }
227
+
228
+ if (!safePath.toLowerCase().endsWith('.js')) {
229
+ throw new ValidationError('Transform file must have .js extension');
230
+ }
231
+
232
+ try {
233
+ // Read and evaluate the transform file in a safe context
234
+ const transformCode = await fsPromises.readFile(safePath, 'utf8');
235
+
236
+ // Create a safe context with limited access
237
+ const sandbox = {
238
+ console,
239
+ require,
240
+ module: { exports: {} },
241
+ exports: {},
242
+ __filename: safePath,
243
+ __dirname: path.dirname(safePath),
244
+ Buffer,
245
+ process: {
246
+ env: process.env,
247
+ cwd: process.cwd,
248
+ platform: process.platform
249
+ }
250
+ };
251
+
252
+ // Create a context and run the code
253
+ const context = vm.createContext(sandbox);
254
+ const script = new vm.Script(transformCode, { filename: safePath });
255
+ script.runInContext(context);
256
+
257
+ // Get the exported function
258
+ const transformFn = (context as any).module.exports || (context as any).exports;
259
+
260
+ // Handle default export for ES6 modules
261
+ const finalTransform = transformFn.default || transformFn;
262
+
263
+ // Validate the transform function
264
+ validateTransformFunction(finalTransform);
265
+
266
+ return finalTransform;
267
+ } catch (error: any) {
268
+ if (error instanceof ValidationError || error instanceof SecurityError) {
269
+ throw error;
270
+ }
271
+
272
+ if (error.code === 'EACCES') {
273
+ throw new SecurityError(`Permission denied reading transform file: ${transformPath}`);
274
+ }
275
+
276
+ throw new ValidationError(`Failed to load transform function: ${error.message}`);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Async version of applyTransform that uses worker threads for parallel transformation
282
+ *
283
+ * @param data - Array of data to transform
284
+ * @param transform - Transform function or path to transform file
285
+ * @returns Promise with transformed data
286
+ */
287
+ export async function applyTransformAsync(data: any[], transform: string | Function): Promise<any[]> {
288
+ if (!Array.isArray(data)) {
289
+ throw new ValidationError('Data must be an array');
290
+ }
291
+
292
+ // For large datasets, use worker pool
293
+ if (data.length > 1000) {
294
+ const { createWorkerPool } = require('../workers/worker-pool');
295
+ const pool = createWorkerPool({
296
+ workerCount: Math.min(4, require('os').cpus().length),
297
+ workerScript: require.resolve('./transform-worker.js')
298
+ });
299
+
300
+ try {
301
+ // Load transform function
302
+ const transformFn = typeof transform === 'string'
303
+ ? await loadTransformAsync(transform)
304
+ : transform;
305
+
306
+ // Execute transforms in parallel
307
+ const transformPromises = data.map((row, index) =>
308
+ pool.execute({ row, index, transform: transformFn.toString() })
309
+ );
310
+
311
+ const results = await Promise.all(transformPromises);
312
+ return results.map(result => result.transformedRow);
313
+ } finally {
314
+ await pool.terminate();
315
+ }
316
+ }
317
+
318
+ // For small datasets, transform synchronously
319
+ return applyTransform(data, transform);
320
+ }
321
+
322
+ /**
323
+ * Creates an async transform hook that can be used with async hooks
324
+ *
325
+ * @param transform - Transform function or path to transform file
326
+ * @returns Async transform hook function
327
+ */
328
+ export function createAsyncTransformHook(transform: string | Function): (row: any, index: number, context: any) => Promise<any> {
329
+ const syncHook = createTransformHook(transform);
330
+
331
+ return async function (row: any, index: number, context: any): Promise<any> {
332
+ return Promise.resolve(syncHook(row, index, context));
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Validates that a transform function can be safely executed
338
+ *
339
+ * @param transformFn - Transform function to validate
340
+ * @returns Validation result
341
+ */
342
+ export function validateTransformSafety(transformFn: Function): { safe: boolean; issues: string[] } {
343
+ const issues: string[] = [];
344
+
345
+ // Check for dangerous patterns
346
+ const functionString = transformFn.toString().toLowerCase();
347
+
348
+ const dangerousPatterns = [
349
+ 'eval(',
350
+ 'new function',
351
+ 'settimeout',
352
+ 'setinterval',
353
+ 'process.exit',
354
+ 'require(',
355
+ 'fs.',
356
+ 'child_process',
357
+ 'exec(',
358
+ 'spawn(',
359
+ 'vm.run'
360
+ ];
361
+
362
+ for (const pattern of dangerousPatterns) {
363
+ if (functionString.includes(pattern)) {
364
+ issues.push(`Potentially dangerous pattern detected: ${pattern}`);
365
+ }
366
+ }
367
+
368
+ // Check for infinite loops
369
+ if (functionString.includes('while(true)') || functionString.includes('for(;;)')) {
370
+ issues.push('Potential infinite loop detected');
371
+ }
372
+
373
+ return {
374
+ safe: issues.length === 0,
375
+ issues
376
+ };
377
+ }
378
+
379
+ export default {
380
+ loadTransform,
381
+ loadTransformAsync,
382
+ createTransformHook,
383
+ createAsyncTransformHook,
384
+ applyTransform,
385
+ applyTransformAsync,
386
+ createTransformHooksWithTransform,
387
+ validateTransformFunction,
388
+ validateTransformSafety
389
+ };
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Zod adapter for JTCSV schema validation.
3
+ *
4
+ * Provides integration with Zod schemas for CSV validation.
5
+ *
6
+ * @example
7
+ * const { z } = require('zod');
8
+ * const { createZodValidationHook } = require('./zod-adapter');
9
+ *
10
+ * const schema = z.object({
11
+ * name: z.string().min(1),
12
+ * age: z.number().int().min(0).max(150),
13
+ * email: z.string().email()
14
+ * });
15
+ *
16
+ * const validationHook = createZodValidationHook(schema);
17
+ *
18
+ * // Use with csvToJson
19
+ * const data = await csvToJson(csv, {
20
+ * hooks: { perRow: validationHook }
21
+ * });
22
+ */
23
+
24
+ const { ValidationError } = require('../errors');
25
+
26
+ /**
27
+ * Creates a validation hook from a Zod schema.
28
+ *
29
+ * @param {import('zod').ZodSchema} zodSchema - Zod schema instance
30
+ * @param {Object} options - Validation options
31
+ * @param {boolean} options.coerce - Whether to coerce values according to Zod's coerce (default: true)
32
+ * @param {string} options.mode - 'strict' (throw on first error) or 'collect' (collect all errors)
33
+ * @returns {Function} Validation hook compatible with JTCSV hooks.perRow
34
+ */
35
+ function createZodValidationHook(zodSchema, options = {}) {
36
+ const { coerce = true, mode = 'strict' } = options;
37
+
38
+ // Check if Zod is available
39
+ let zod;
40
+ try {
41
+ zod = require('zod');
42
+ } catch (error) {
43
+ throw new Error(
44
+ 'Zod is not installed. Please install zod: npm install zod'
45
+ );
46
+ }
47
+
48
+ // Ensure the passed schema is a Zod schema
49
+ if (!zodSchema || typeof zodSchema.safeParse !== 'function') {
50
+ throw new ValidationError('Provided schema is not a valid Zod schema');
51
+ }
52
+
53
+ // Return hook function
54
+ return function (row, index, context) {
55
+ try {
56
+ const result = zodSchema.safeParse(row);
57
+
58
+ if (!result.success) {
59
+ const errors = result.error.errors;
60
+ const firstError = errors[0];
61
+ const path = firstError.path.join('.');
62
+ const message = firstError.message;
63
+
64
+ if (mode === 'strict') {
65
+ throw new ValidationError(
66
+ `Row ${index + 1}: ${path ? `Field "${path}": ` : ''}${message}`
67
+ );
68
+ } else {
69
+ // In collect mode, we attach errors to row metadata
70
+ // For simplicity, we still throw but could be extended
71
+ console.warn(`Row ${index + 1}: ${path ? `Field "${path}": ` : ''}${message}`);
72
+ return row;
73
+ }
74
+ }
75
+
76
+ // Return validated (and possibly coerced) data
77
+ return result.data;
78
+ } catch (error) {
79
+ if (error instanceof ValidationError) {
80
+ throw error;
81
+ }
82
+ // Unexpected error - log and return original row
83
+ console.error(`Zod validation error at row ${index}: ${error.message}`);
84
+ if (process.env.NODE_ENV === 'development') {
85
+ console.error(error.stack);
86
+ }
87
+ return row;
88
+ }
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Creates a Yup validation hook.
94
+ *
95
+ * @param {import('yup').Schema} yupSchema - Yup schema instance
96
+ * @param {Object} options - Validation options
97
+ * @returns {Function} Validation hook
98
+ */
99
+ function createYupValidationHook(yupSchema, options = {}) {
100
+ const { abortEarly = false, stripUnknown = true } = options;
101
+
102
+ // Check if Yup is available
103
+ let yup;
104
+ try {
105
+ yup = require('yup');
106
+ } catch (error) {
107
+ throw new Error(
108
+ 'Yup is not installed. Please install yup: npm install yup'
109
+ );
110
+ }
111
+
112
+ if (!yupSchema || typeof yupSchema.validate !== 'function') {
113
+ throw new ValidationError('Provided schema is not a valid Yup schema');
114
+ }
115
+
116
+ return async function (row, index, context) {
117
+ try {
118
+ const validated = await yupSchema.validate(row, { abortEarly, stripUnknown });
119
+ return validated;
120
+ } catch (error) {
121
+ if (error.name === 'ValidationError') {
122
+ throw new ValidationError(`Row ${index + 1}: ${error.message}`);
123
+ }
124
+ console.error(`Yup validation error at row ${index}: ${error.message}`);
125
+ return row;
126
+ }
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Higher-order function that creates a csvToJson wrapper with schema validation.
132
+ *
133
+ * @param {import('zod').ZodSchema|import('yup').Schema} schema - Zod or Yup schema
134
+ * @param {Object} adapterOptions - Adapter-specific options
135
+ * @returns {Function} Function that takes csv and options, returns validated data
136
+ */
137
+ function createValidatedParser(schema, adapterOptions = {}) {
138
+ const { library = 'zod', ...options } = adapterOptions;
139
+
140
+ let validationHook;
141
+ if (library === 'zod') {
142
+ validationHook = createZodValidationHook(schema, options);
143
+ } else if (library === 'yup') {
144
+ validationHook = createYupValidationHook(schema, options);
145
+ } else {
146
+ throw new ValidationError(`Unsupported validation library: ${library}`);
147
+ }
148
+
149
+ return async function (csv, parseOptions = {}) {
150
+ const { csvToJson } = require('../index');
151
+ const hooks = parseOptions.hooks || {};
152
+ // Merge validation hook with existing perRow hook
153
+ const existingPerRow = hooks.perRow;
154
+ hooks.perRow = function (row, index, context) {
155
+ let validated = row;
156
+ if (existingPerRow) {
157
+ validated = existingPerRow(validated, index, context);
158
+ }
159
+ return validationHook(validated, index, context);
160
+ };
161
+
162
+ return csvToJson(csv, { ...parseOptions, hooks });
163
+ };
164
+ }
165
+
166
+ module.exports = {
167
+ createZodValidationHook,
168
+ createYupValidationHook,
169
+ createValidatedParser
170
+ };