jtcsv 2.1.3 → 2.2.2

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 (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +60 -341
  3. package/bin/jtcsv.js +2462 -1372
  4. package/csv-to-json.js +35 -26
  5. package/dist/jtcsv.cjs.js +807 -133
  6. package/dist/jtcsv.cjs.js.map +1 -1
  7. package/dist/jtcsv.esm.js +800 -134
  8. package/dist/jtcsv.esm.js.map +1 -1
  9. package/dist/jtcsv.umd.js +807 -133
  10. package/dist/jtcsv.umd.js.map +1 -1
  11. package/errors.js +20 -0
  12. package/examples/browser-vanilla.html +37 -0
  13. package/examples/cli-batch-processing.js +38 -0
  14. package/examples/error-handling.js +324 -0
  15. package/examples/ndjson-processing.js +434 -0
  16. package/examples/react-integration.jsx +637 -0
  17. package/examples/schema-validation.js +640 -0
  18. package/examples/simple-usage.js +10 -7
  19. package/examples/typescript-example.ts +486 -0
  20. package/examples/web-workers-advanced.js +28 -0
  21. package/index.d.ts +2 -0
  22. package/json-save.js +2 -1
  23. package/json-to-csv.js +171 -131
  24. package/package.json +20 -4
  25. package/plugins/README.md +41 -467
  26. package/plugins/express-middleware/README.md +32 -274
  27. package/plugins/hono/README.md +16 -13
  28. package/plugins/nestjs/README.md +13 -11
  29. package/plugins/nextjs-api/README.md +28 -423
  30. package/plugins/nextjs-api/index.js +1 -2
  31. package/plugins/nextjs-api/route.js +1 -2
  32. package/plugins/nuxt/README.md +6 -7
  33. package/plugins/remix/README.md +9 -9
  34. package/plugins/sveltekit/README.md +8 -8
  35. package/plugins/trpc/README.md +8 -5
  36. package/src/browser/browser-functions.js +33 -3
  37. package/src/browser/csv-to-json-browser.js +269 -11
  38. package/src/browser/errors-browser.js +19 -1
  39. package/src/browser/index.js +39 -5
  40. package/src/browser/streams.js +393 -0
  41. package/src/browser/workers/csv-parser.worker.js +20 -2
  42. package/src/browser/workers/worker-pool.js +507 -447
  43. package/src/core/plugin-system.js +4 -0
  44. package/src/engines/fast-path-engine.js +31 -23
  45. package/src/errors.js +26 -0
  46. package/src/formats/ndjson-parser.js +54 -5
  47. package/src/formats/tsv-parser.js +4 -1
  48. package/src/utils/schema-validator.js +594 -0
  49. package/src/utils/transform-loader.js +205 -0
  50. package/src/web-server/index.js +683 -0
  51. package/stream-csv-to-json.js +16 -87
  52. package/stream-json-to-csv.js +18 -86
package/errors.js CHANGED
@@ -83,6 +83,23 @@ class ConfigurationError extends JtcsvError {
83
83
  }
84
84
  }
85
85
 
86
+ const ERROR_CODES = {
87
+ JTCSV_ERROR: 'JTCSV_ERROR',
88
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
89
+ SECURITY_ERROR: 'SECURITY_ERROR',
90
+ FILE_SYSTEM_ERROR: 'FILE_SYSTEM_ERROR',
91
+ PARSING_ERROR: 'PARSING_ERROR',
92
+ LIMIT_ERROR: 'LIMIT_ERROR',
93
+ CONFIGURATION_ERROR: 'CONFIGURATION_ERROR',
94
+ INVALID_INPUT: 'INVALID_INPUT',
95
+ SECURITY_VIOLATION: 'SECURITY_VIOLATION',
96
+ FILE_NOT_FOUND: 'FILE_NOT_FOUND',
97
+ PARSE_FAILED: 'PARSE_FAILED',
98
+ SIZE_LIMIT: 'SIZE_LIMIT',
99
+ INVALID_CONFIG: 'INVALID_CONFIG',
100
+ UNKNOWN_ERROR: 'UNKNOWN_ERROR'
101
+ };
102
+
86
103
  /**
87
104
  * Utility function to create standardized error messages
88
105
  */
@@ -103,6 +120,7 @@ function createErrorMessage(type, details) {
103
120
  /**
104
121
  * Error handler utility
105
122
  */
123
+ /* istanbul ignore next */
106
124
  function handleError(error, context = {}) {
107
125
  // Log error in development
108
126
  if (process.env.NODE_ENV === 'development') {
@@ -121,6 +139,7 @@ function handleError(error, context = {}) {
121
139
  /**
122
140
  * Safe execution wrapper for async functions
123
141
  */
142
+ /* istanbul ignore next */
124
143
  async function safeExecuteAsync(fn, errorType, context = {}) {
125
144
  try {
126
145
  return await fn();
@@ -180,6 +199,7 @@ module.exports = {
180
199
  ParsingError,
181
200
  LimitError,
182
201
  ConfigurationError,
202
+ ERROR_CODES,
183
203
  createErrorMessage,
184
204
  handleError,
185
205
  safeExecute,
@@ -0,0 +1,37 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <title>JTCSV Vanilla Browser Example</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <style>
8
+ body { font-family: Arial, sans-serif; padding: 20px; }
9
+ textarea { width: 100%; height: 160px; margin-top: 8px; }
10
+ .row { margin: 10px 0; }
11
+ </style>
12
+ </head>
13
+ <body>
14
+ <h1>JTCSV Browser Example</h1>
15
+ <div class="row">
16
+ <input type="file" id="csvFile" accept=".csv" />
17
+ <button id="parseBtn">Parse CSV</button>
18
+ </div>
19
+ <div class="row">
20
+ <textarea id="output" placeholder="JSON output..."></textarea>
21
+ </div>
22
+
23
+ <script src="https://cdn.jsdelivr.net/npm/jtcsv@latest/dist/jtcsv.umd.js"></script>
24
+ <script>
25
+ const fileInput = document.getElementById('csvFile');
26
+ const output = document.getElementById('output');
27
+ const parseBtn = document.getElementById('parseBtn');
28
+
29
+ parseBtn.addEventListener('click', async () => {
30
+ const file = fileInput.files[0];
31
+ if (!file) return;
32
+ const json = await window.jtcsv.parseCsvFile(file, { delimiter: ',', parseNumbers: true });
33
+ output.value = JSON.stringify(json, null, 2);
34
+ });
35
+ </script>
36
+ </body>
37
+ </html>
@@ -0,0 +1,38 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const { spawnSync } = require('child_process');
5
+
6
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jtcsv-batch-'));
7
+ const inputDir = path.join(tempDir, 'input');
8
+ const outputDir = path.join(tempDir, 'output');
9
+
10
+ fs.mkdirSync(inputDir, { recursive: true });
11
+ fs.mkdirSync(outputDir, { recursive: true });
12
+
13
+ const sampleData = [
14
+ [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }],
15
+ [{ id: 3, name: 'Max' }, { id: 4, name: 'Eva' }]
16
+ ];
17
+
18
+ sampleData.forEach((data, idx) => {
19
+ const filePath = path.join(inputDir, `data-${idx + 1}.json`);
20
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
21
+ });
22
+
23
+ const cliPath = path.join(__dirname, '..', 'bin', 'jtcsv.js');
24
+
25
+ const result = spawnSync('node', [
26
+ cliPath,
27
+ 'batch',
28
+ 'json-to-csv',
29
+ path.join(inputDir, '*.json'),
30
+ outputDir,
31
+ '--delimiter=,'
32
+ ], { stdio: 'inherit' });
33
+
34
+ if (result.status !== 0) {
35
+ process.exit(result.status);
36
+ }
37
+
38
+ console.log('Output files:', fs.readdirSync(outputDir));
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Error Handling Examples for jtcsv
3
+ *
4
+ * This file demonstrates proper error handling patterns
5
+ * using jtcsv's typed error classes.
6
+ */
7
+
8
+ const {
9
+ csvToJson,
10
+ jsonToCsv,
11
+ saveAsCsv,
12
+ readCsvAsJson,
13
+ // Error classes
14
+ JtcsvError,
15
+ ValidationError,
16
+ SecurityError,
17
+ ParsingError,
18
+ FileSystemError,
19
+ LimitError,
20
+ ConfigurationError
21
+ } = require('jtcsv');
22
+
23
+ // =============================================================================
24
+ // Example 1: Basic Error Handling
25
+ // =============================================================================
26
+
27
+ function basicErrorHandling() {
28
+ console.log('\n=== Basic Error Handling ===\n');
29
+
30
+ // Invalid input type
31
+ try {
32
+ csvToJson(null);
33
+ } catch (error) {
34
+ if (error instanceof ValidationError) {
35
+ console.log('ValidationError caught:', error.message);
36
+ console.log('Error code:', error.code);
37
+ }
38
+ }
39
+
40
+ // Malformed CSV
41
+ const malformedCsv = 'name,age\n"unclosed quote,25';
42
+ try {
43
+ csvToJson(malformedCsv);
44
+ } catch (error) {
45
+ if (error instanceof ParsingError) {
46
+ console.log('ParsingError caught:', error.message);
47
+ console.log('Line number:', error.lineNumber);
48
+ }
49
+ }
50
+ }
51
+
52
+ // =============================================================================
53
+ // Example 2: Comprehensive Error Handling with Type Checks
54
+ // =============================================================================
55
+
56
+ async function comprehensiveErrorHandling() {
57
+ console.log('\n=== Comprehensive Error Handling ===\n');
58
+
59
+ const operations = [
60
+ {
61
+ name: 'Parse invalid CSV',
62
+ action: () => csvToJson(12345) // Not a string
63
+ },
64
+ {
65
+ name: 'Convert non-array to CSV',
66
+ action: () => jsonToCsv('not an array')
67
+ },
68
+ {
69
+ name: 'Read non-existent file',
70
+ action: async () => await readCsvAsJson('./non-existent-file.csv')
71
+ },
72
+ {
73
+ name: 'Exceed row limit',
74
+ action: () => {
75
+ const csv = 'a,b\n' + '1,2\n'.repeat(100);
76
+ return csvToJson(csv, { maxRows: 5 });
77
+ }
78
+ },
79
+ {
80
+ name: 'Path traversal attempt',
81
+ action: async () => await saveAsCsv([], '../../../etc/passwd.csv')
82
+ }
83
+ ];
84
+
85
+ for (const op of operations) {
86
+ try {
87
+ await op.action();
88
+ console.log(`${op.name}: Success (unexpected)`);
89
+ } catch (error) {
90
+ const errorType = getErrorTypeName(error);
91
+ console.log(`${op.name}: ${errorType} - ${error.message}`);
92
+ }
93
+ }
94
+ }
95
+
96
+ function getErrorTypeName(error) {
97
+ if (error instanceof ValidationError) return 'ValidationError';
98
+ if (error instanceof SecurityError) return 'SecurityError';
99
+ if (error instanceof ParsingError) return 'ParsingError';
100
+ if (error instanceof FileSystemError) return 'FileSystemError';
101
+ if (error instanceof LimitError) return 'LimitError';
102
+ if (error instanceof ConfigurationError) return 'ConfigurationError';
103
+ if (error instanceof JtcsvError) return 'JtcsvError';
104
+ return 'UnknownError';
105
+ }
106
+
107
+ // =============================================================================
108
+ // Example 3: Error Recovery Strategies
109
+ // =============================================================================
110
+
111
+ function errorRecoveryStrategies() {
112
+ console.log('\n=== Error Recovery Strategies ===\n');
113
+
114
+ // Strategy 1: Fallback to default delimiter
115
+ function parseWithFallback(csv) {
116
+ const delimiters = [',', ';', '\t', '|'];
117
+
118
+ for (const delimiter of delimiters) {
119
+ try {
120
+ const result = csvToJson(csv, {
121
+ delimiter,
122
+ autoDetect: false
123
+ });
124
+ console.log(`Successfully parsed with delimiter: "${delimiter}"`);
125
+ return result;
126
+ } catch (error) {
127
+ console.log(`Failed with delimiter "${delimiter}": ${error.message}`);
128
+ }
129
+ }
130
+ throw new Error('Could not parse CSV with any known delimiter');
131
+ }
132
+
133
+ const testCsv = 'name|age|city\nJohn|25|NYC\nJane|30|LA';
134
+ const result = parseWithFallback(testCsv);
135
+ console.log('Result:', result);
136
+ }
137
+
138
+ // =============================================================================
139
+ // Example 4: Batch Processing with Error Collection
140
+ // =============================================================================
141
+
142
+ async function batchProcessingWithErrorCollection() {
143
+ console.log('\n=== Batch Processing with Error Collection ===\n');
144
+
145
+ const csvFiles = [
146
+ { name: 'valid.csv', content: 'a,b\n1,2\n3,4' },
147
+ { name: 'invalid.csv', content: 'a,b\n"unclosed' },
148
+ { name: 'empty.csv', content: '' },
149
+ { name: 'valid2.csv', content: 'x,y\n5,6' }
150
+ ];
151
+
152
+ const results = {
153
+ successful: [],
154
+ failed: []
155
+ };
156
+
157
+ for (const file of csvFiles) {
158
+ try {
159
+ const data = csvToJson(file.content);
160
+ results.successful.push({
161
+ name: file.name,
162
+ rowCount: data.length
163
+ });
164
+ } catch (error) {
165
+ results.failed.push({
166
+ name: file.name,
167
+ error: error.message,
168
+ errorType: getErrorTypeName(error)
169
+ });
170
+ }
171
+ }
172
+
173
+ console.log('Processing Results:');
174
+ console.log('Successful:', results.successful);
175
+ console.log('Failed:', results.failed);
176
+ console.log(`\nSuccess rate: ${results.successful.length}/${csvFiles.length}`);
177
+ }
178
+
179
+ // =============================================================================
180
+ // Example 5: Custom Error Handler Wrapper
181
+ // =============================================================================
182
+
183
+ function createSafeParser(options = {}) {
184
+ const { onError, defaultValue = [] } = options;
185
+
186
+ return function safeParse(csv, parseOptions = {}) {
187
+ try {
188
+ return {
189
+ success: true,
190
+ data: csvToJson(csv, parseOptions),
191
+ error: null
192
+ };
193
+ } catch (error) {
194
+ if (onError) {
195
+ onError(error);
196
+ }
197
+ return {
198
+ success: false,
199
+ data: defaultValue,
200
+ error: {
201
+ type: getErrorTypeName(error),
202
+ message: error.message,
203
+ code: error.code
204
+ }
205
+ };
206
+ }
207
+ };
208
+ }
209
+
210
+ function customErrorHandlerDemo() {
211
+ console.log('\n=== Custom Error Handler ===\n');
212
+
213
+ const safeParse = createSafeParser({
214
+ onError: (error) => {
215
+ console.log(`[Logger] Error occurred: ${error.message}`);
216
+ },
217
+ defaultValue: []
218
+ });
219
+
220
+ // Test with valid CSV
221
+ const result1 = safeParse('a,b\n1,2');
222
+ console.log('Valid CSV result:', result1);
223
+
224
+ // Test with invalid CSV
225
+ const result2 = safeParse(null);
226
+ console.log('Invalid CSV result:', result2);
227
+ }
228
+
229
+ // =============================================================================
230
+ // Example 6: Async Error Handling with Retries
231
+ // =============================================================================
232
+
233
+ async function asyncWithRetries() {
234
+ console.log('\n=== Async Error Handling with Retries ===\n');
235
+
236
+ async function readWithRetry(filePath, maxRetries = 3) {
237
+ let lastError;
238
+
239
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
240
+ try {
241
+ console.log(`Attempt ${attempt}: Reading ${filePath}`);
242
+ const data = await readCsvAsJson(filePath);
243
+ return data;
244
+ } catch (error) {
245
+ lastError = error;
246
+ console.log(`Attempt ${attempt} failed: ${error.message}`);
247
+
248
+ if (error instanceof FileSystemError) {
249
+ // File system errors might be transient
250
+ await new Promise(r => setTimeout(r, 100 * attempt));
251
+ } else if (error instanceof ValidationError) {
252
+ // Validation errors won't resolve with retry
253
+ throw error;
254
+ } else if (error instanceof SecurityError) {
255
+ // Security errors should not be retried
256
+ throw error;
257
+ }
258
+ }
259
+ }
260
+
261
+ throw lastError;
262
+ }
263
+
264
+ try {
265
+ await readWithRetry('./test-data.csv');
266
+ } catch (error) {
267
+ console.log(`All retries failed: ${error.message}`);
268
+ }
269
+ }
270
+
271
+ // =============================================================================
272
+ // Example 7: Schema Validation Error Details
273
+ // =============================================================================
274
+
275
+ function schemaValidationErrors() {
276
+ console.log('\n=== Schema Validation Errors ===\n');
277
+
278
+ const schema = {
279
+ type: 'object',
280
+ required: ['name', 'age'],
281
+ properties: {
282
+ name: { type: 'string', minLength: 1 },
283
+ age: { type: 'number', minimum: 0, maximum: 150 }
284
+ }
285
+ };
286
+
287
+ const data = [
288
+ { name: 'John', age: 25 },
289
+ { name: '', age: 30 }, // Invalid: empty name
290
+ { name: 'Jane', age: -5 }, // Invalid: negative age
291
+ { name: 'Bob', age: 200 } // Invalid: age > 150
292
+ ];
293
+
294
+ try {
295
+ jsonToCsv(data, { schema });
296
+ } catch (error) {
297
+ if (error instanceof ValidationError) {
298
+ console.log('Schema validation failed:');
299
+ console.log('Message:', error.message);
300
+ }
301
+ }
302
+ }
303
+
304
+ // =============================================================================
305
+ // Run All Examples
306
+ // =============================================================================
307
+
308
+ async function main() {
309
+ console.log('jtcsv Error Handling Examples\n');
310
+ console.log('='.repeat(60));
311
+
312
+ basicErrorHandling();
313
+ await comprehensiveErrorHandling();
314
+ errorRecoveryStrategies();
315
+ await batchProcessingWithErrorCollection();
316
+ customErrorHandlerDemo();
317
+ await asyncWithRetries();
318
+ schemaValidationErrors();
319
+
320
+ console.log('\n' + '='.repeat(60));
321
+ console.log('All examples completed.');
322
+ }
323
+
324
+ main().catch(console.error);