@contrail/cli 3.4.4-alpha.7adb62a → 3.4.4-alpha.e5b7d5d

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 (36) hide show
  1. package/README.md +1 -1
  2. package/node_modules/@contrail/loader/README.md +0 -0
  3. package/node_modules/@contrail/loader/lib/index.d.ts +941 -0
  4. package/node_modules/@contrail/loader/lib/index.js +12492 -0
  5. package/node_modules/@contrail/loader/lib/index.js.map +1 -0
  6. package/node_modules/@contrail/loader/package.json +70 -0
  7. package/node_modules/csv-parse/LICENSE +21 -0
  8. package/node_modules/csv-parse/README.md +86 -0
  9. package/node_modules/csv-parse/dist/cjs/index.cjs +1424 -0
  10. package/node_modules/csv-parse/dist/cjs/index.d.cts +283 -0
  11. package/node_modules/csv-parse/dist/cjs/sync.cjs +1336 -0
  12. package/node_modules/csv-parse/dist/cjs/sync.d.cts +11 -0
  13. package/node_modules/csv-parse/dist/esm/index.d.ts +283 -0
  14. package/node_modules/csv-parse/dist/esm/index.js +6544 -0
  15. package/node_modules/csv-parse/dist/esm/sync.d.ts +11 -0
  16. package/node_modules/csv-parse/dist/esm/sync.js +3305 -0
  17. package/node_modules/csv-parse/dist/iife/index.js +6553 -0
  18. package/node_modules/csv-parse/dist/iife/sync.js +3313 -0
  19. package/node_modules/csv-parse/dist/umd/index.js +6554 -0
  20. package/node_modules/csv-parse/dist/umd/sync.js +3314 -0
  21. package/node_modules/csv-parse/lib/api/CsvError.js +19 -0
  22. package/node_modules/csv-parse/lib/api/index.js +729 -0
  23. package/node_modules/csv-parse/lib/api/init_state.js +58 -0
  24. package/node_modules/csv-parse/lib/api/normalize_columns_array.js +33 -0
  25. package/node_modules/csv-parse/lib/api/normalize_options.js +448 -0
  26. package/node_modules/csv-parse/lib/index.d.ts +283 -0
  27. package/node_modules/csv-parse/lib/index.js +121 -0
  28. package/node_modules/csv-parse/lib/stream.js +27 -0
  29. package/node_modules/csv-parse/lib/sync.d.ts +11 -0
  30. package/node_modules/csv-parse/lib/sync.js +27 -0
  31. package/node_modules/csv-parse/lib/utils/ResizeableBuffer.js +64 -0
  32. package/node_modules/csv-parse/lib/utils/is_object.js +6 -0
  33. package/node_modules/csv-parse/lib/utils/underscore.js +8 -0
  34. package/node_modules/csv-parse/package.json +142 -0
  35. package/oclif.manifest.json +1 -1
  36. package/package.json +3 -1
@@ -0,0 +1,1336 @@
1
+ 'use strict';
2
+
3
+ class CsvError extends Error {
4
+ constructor(code, message, options, ...contexts) {
5
+ if(Array.isArray(message)) message = message.join(' ').trim();
6
+ super(message);
7
+ if(Error.captureStackTrace !== undefined){
8
+ Error.captureStackTrace(this, CsvError);
9
+ }
10
+ this.code = code;
11
+ for(const context of contexts){
12
+ for(const key in context){
13
+ const value = context[key];
14
+ this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
15
+ }
16
+ }
17
+ }
18
+ }
19
+
20
+ const is_object = function(obj){
21
+ return (typeof obj === 'object' && obj !== null && !Array.isArray(obj));
22
+ };
23
+
24
+ const normalize_columns_array = function(columns){
25
+ const normalizedColumns = [];
26
+ for(let i = 0, l = columns.length; i < l; i++){
27
+ const column = columns[i];
28
+ if(column === undefined || column === null || column === false){
29
+ normalizedColumns[i] = { disabled: true };
30
+ }else if(typeof column === 'string'){
31
+ normalizedColumns[i] = { name: column };
32
+ }else if(is_object(column)){
33
+ if(typeof column.name !== 'string'){
34
+ throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [
35
+ 'Option columns missing name:',
36
+ `property "name" is required at position ${i}`,
37
+ 'when column is an object literal'
38
+ ]);
39
+ }
40
+ normalizedColumns[i] = column;
41
+ }else {
42
+ throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [
43
+ 'Invalid column definition:',
44
+ 'expect a string or a literal object,',
45
+ `got ${JSON.stringify(column)} at position ${i}`
46
+ ]);
47
+ }
48
+ }
49
+ return normalizedColumns;
50
+ };
51
+
52
+ class ResizeableBuffer{
53
+ constructor(size=100){
54
+ this.size = size;
55
+ this.length = 0;
56
+ this.buf = Buffer.allocUnsafe(size);
57
+ }
58
+ prepend(val){
59
+ if(Buffer.isBuffer(val)){
60
+ const length = this.length + val.length;
61
+ if(length >= this.size){
62
+ this.resize();
63
+ if(length >= this.size){
64
+ throw Error('INVALID_BUFFER_STATE');
65
+ }
66
+ }
67
+ const buf = this.buf;
68
+ this.buf = Buffer.allocUnsafe(this.size);
69
+ val.copy(this.buf, 0);
70
+ buf.copy(this.buf, val.length);
71
+ this.length += val.length;
72
+ }else {
73
+ const length = this.length++;
74
+ if(length === this.size){
75
+ this.resize();
76
+ }
77
+ const buf = this.clone();
78
+ this.buf[0] = val;
79
+ buf.copy(this.buf,1, 0, length);
80
+ }
81
+ }
82
+ append(val){
83
+ const length = this.length++;
84
+ if(length === this.size){
85
+ this.resize();
86
+ }
87
+ this.buf[length] = val;
88
+ }
89
+ clone(){
90
+ return Buffer.from(this.buf.slice(0, this.length));
91
+ }
92
+ resize(){
93
+ const length = this.length;
94
+ this.size = this.size * 2;
95
+ const buf = Buffer.allocUnsafe(this.size);
96
+ this.buf.copy(buf,0, 0, length);
97
+ this.buf = buf;
98
+ }
99
+ toString(encoding){
100
+ if(encoding){
101
+ return this.buf.slice(0, this.length).toString(encoding);
102
+ }else {
103
+ return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
104
+ }
105
+ }
106
+ toJSON(){
107
+ return this.toString('utf8');
108
+ }
109
+ reset(){
110
+ this.length = 0;
111
+ }
112
+ }
113
+
114
+ // white space characters
115
+ // https://en.wikipedia.org/wiki/Whitespace_character
116
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types
117
+ // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff
118
+ const np = 12;
119
+ const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
120
+ const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
121
+ const space = 32;
122
+ const tab = 9;
123
+
124
+ const init_state = function(options){
125
+ return {
126
+ bomSkipped: false,
127
+ bufBytesStart: 0,
128
+ castField: options.cast_function,
129
+ commenting: false,
130
+ // Current error encountered by a record
131
+ error: undefined,
132
+ enabled: options.from_line === 1,
133
+ escaping: false,
134
+ escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
135
+ // columns can be `false`, `true`, `Array`
136
+ expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
137
+ field: new ResizeableBuffer(20),
138
+ firstLineToHeaders: options.cast_first_line_to_header,
139
+ needMoreDataSize: Math.max(
140
+ // Skip if the remaining buffer smaller than comment
141
+ options.comment !== null ? options.comment.length : 0,
142
+ // Skip if the remaining buffer can be delimiter
143
+ ...options.delimiter.map((delimiter) => delimiter.length),
144
+ // Skip if the remaining buffer can be escape sequence
145
+ options.quote !== null ? options.quote.length : 0,
146
+ ),
147
+ previousBuf: undefined,
148
+ quoting: false,
149
+ stop: false,
150
+ rawBuffer: new ResizeableBuffer(100),
151
+ record: [],
152
+ recordHasError: false,
153
+ record_length: 0,
154
+ recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
155
+ trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]],
156
+ wasQuoting: false,
157
+ wasRowDelimiter: false,
158
+ timchars: [
159
+ Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding),
160
+ Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding),
161
+ Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding),
162
+ Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding),
163
+ Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding),
164
+ ]
165
+ };
166
+ };
167
+
168
+ const underscore = function(str){
169
+ return str.replace(/([A-Z])/g, function(_, match){
170
+ return '_' + match.toLowerCase();
171
+ });
172
+ };
173
+
174
+ const normalize_options = function(opts){
175
+ const options = {};
176
+ // Merge with user options
177
+ for(const opt in opts){
178
+ options[underscore(opt)] = opts[opt];
179
+ }
180
+ // Normalize option `encoding`
181
+ // Note: defined first because other options depends on it
182
+ // to convert chars/strings into buffers.
183
+ if(options.encoding === undefined || options.encoding === true){
184
+ options.encoding = 'utf8';
185
+ }else if(options.encoding === null || options.encoding === false){
186
+ options.encoding = null;
187
+ }else if(typeof options.encoding !== 'string' && options.encoding !== null){
188
+ throw new CsvError('CSV_INVALID_OPTION_ENCODING', [
189
+ 'Invalid option encoding:',
190
+ 'encoding must be a string or null to return a buffer,',
191
+ `got ${JSON.stringify(options.encoding)}`
192
+ ], options);
193
+ }
194
+ // Normalize option `bom`
195
+ if(options.bom === undefined || options.bom === null || options.bom === false){
196
+ options.bom = false;
197
+ }else if(options.bom !== true){
198
+ throw new CsvError('CSV_INVALID_OPTION_BOM', [
199
+ 'Invalid option bom:', 'bom must be true,',
200
+ `got ${JSON.stringify(options.bom)}`
201
+ ], options);
202
+ }
203
+ // Normalize option `cast`
204
+ options.cast_function = null;
205
+ if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){
206
+ options.cast = undefined;
207
+ }else if(typeof options.cast === 'function'){
208
+ options.cast_function = options.cast;
209
+ options.cast = true;
210
+ }else if(options.cast !== true){
211
+ throw new CsvError('CSV_INVALID_OPTION_CAST', [
212
+ 'Invalid option cast:', 'cast must be true or a function,',
213
+ `got ${JSON.stringify(options.cast)}`
214
+ ], options);
215
+ }
216
+ // Normalize option `cast_date`
217
+ if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){
218
+ options.cast_date = false;
219
+ }else if(options.cast_date === true){
220
+ options.cast_date = function(value){
221
+ const date = Date.parse(value);
222
+ return !isNaN(date) ? new Date(date) : value;
223
+ };
224
+ }else if (typeof options.cast_date !== 'function'){
225
+ throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [
226
+ 'Invalid option cast_date:', 'cast_date must be true or a function,',
227
+ `got ${JSON.stringify(options.cast_date)}`
228
+ ], options);
229
+ }
230
+ // Normalize option `columns`
231
+ options.cast_first_line_to_header = null;
232
+ if(options.columns === true){
233
+ // Fields in the first line are converted as-is to columns
234
+ options.cast_first_line_to_header = undefined;
235
+ }else if(typeof options.columns === 'function'){
236
+ options.cast_first_line_to_header = options.columns;
237
+ options.columns = true;
238
+ }else if(Array.isArray(options.columns)){
239
+ options.columns = normalize_columns_array(options.columns);
240
+ }else if(options.columns === undefined || options.columns === null || options.columns === false){
241
+ options.columns = false;
242
+ }else {
243
+ throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [
244
+ 'Invalid option columns:',
245
+ 'expect an array, a function or true,',
246
+ `got ${JSON.stringify(options.columns)}`
247
+ ], options);
248
+ }
249
+ // Normalize option `group_columns_by_name`
250
+ if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){
251
+ options.group_columns_by_name = false;
252
+ }else if(options.group_columns_by_name !== true){
253
+ throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
254
+ 'Invalid option group_columns_by_name:',
255
+ 'expect an boolean,',
256
+ `got ${JSON.stringify(options.group_columns_by_name)}`
257
+ ], options);
258
+ }else if(options.columns === false){
259
+ throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
260
+ 'Invalid option group_columns_by_name:',
261
+ 'the `columns` mode must be activated.'
262
+ ], options);
263
+ }
264
+ // Normalize option `comment`
265
+ if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){
266
+ options.comment = null;
267
+ }else {
268
+ if(typeof options.comment === 'string'){
269
+ options.comment = Buffer.from(options.comment, options.encoding);
270
+ }
271
+ if(!Buffer.isBuffer(options.comment)){
272
+ throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
273
+ 'Invalid option comment:',
274
+ 'comment must be a buffer or a string,',
275
+ `got ${JSON.stringify(options.comment)}`
276
+ ], options);
277
+ }
278
+ }
279
+ // Normalize option `comment_no_infix`
280
+ if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){
281
+ options.comment_no_infix = false;
282
+ }else if(options.comment_no_infix !== true){
283
+ throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
284
+ 'Invalid option comment_no_infix:',
285
+ 'value must be a boolean,',
286
+ `got ${JSON.stringify(options.comment_no_infix)}`
287
+ ], options);
288
+ }
289
+ // Normalize option `delimiter`
290
+ const delimiter_json = JSON.stringify(options.delimiter);
291
+ if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
292
+ if(options.delimiter.length === 0){
293
+ throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
294
+ 'Invalid option delimiter:',
295
+ 'delimiter must be a non empty string or buffer or array of string|buffer,',
296
+ `got ${delimiter_json}`
297
+ ], options);
298
+ }
299
+ options.delimiter = options.delimiter.map(function(delimiter){
300
+ if(delimiter === undefined || delimiter === null || delimiter === false){
301
+ return Buffer.from(',', options.encoding);
302
+ }
303
+ if(typeof delimiter === 'string'){
304
+ delimiter = Buffer.from(delimiter, options.encoding);
305
+ }
306
+ if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){
307
+ throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
308
+ 'Invalid option delimiter:',
309
+ 'delimiter must be a non empty string or buffer or array of string|buffer,',
310
+ `got ${delimiter_json}`
311
+ ], options);
312
+ }
313
+ return delimiter;
314
+ });
315
+ // Normalize option `escape`
316
+ if(options.escape === undefined || options.escape === true){
317
+ options.escape = Buffer.from('"', options.encoding);
318
+ }else if(typeof options.escape === 'string'){
319
+ options.escape = Buffer.from(options.escape, options.encoding);
320
+ }else if (options.escape === null || options.escape === false){
321
+ options.escape = null;
322
+ }
323
+ if(options.escape !== null){
324
+ if(!Buffer.isBuffer(options.escape)){
325
+ throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
326
+ }
327
+ }
328
+ // Normalize option `from`
329
+ if(options.from === undefined || options.from === null){
330
+ options.from = 1;
331
+ }else {
332
+ if(typeof options.from === 'string' && /\d+/.test(options.from)){
333
+ options.from = parseInt(options.from);
334
+ }
335
+ if(Number.isInteger(options.from)){
336
+ if(options.from < 0){
337
+ throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
338
+ }
339
+ }else {
340
+ throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
341
+ }
342
+ }
343
+ // Normalize option `from_line`
344
+ if(options.from_line === undefined || options.from_line === null){
345
+ options.from_line = 1;
346
+ }else {
347
+ if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){
348
+ options.from_line = parseInt(options.from_line);
349
+ }
350
+ if(Number.isInteger(options.from_line)){
351
+ if(options.from_line <= 0){
352
+ throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
353
+ }
354
+ }else {
355
+ throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
356
+ }
357
+ }
358
+ // Normalize options `ignore_last_delimiters`
359
+ if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){
360
+ options.ignore_last_delimiters = false;
361
+ }else if(typeof options.ignore_last_delimiters === 'number'){
362
+ options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
363
+ if(options.ignore_last_delimiters === 0){
364
+ options.ignore_last_delimiters = false;
365
+ }
366
+ }else if(typeof options.ignore_last_delimiters !== 'boolean'){
367
+ throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [
368
+ 'Invalid option `ignore_last_delimiters`:',
369
+ 'the value must be a boolean value or an integer,',
370
+ `got ${JSON.stringify(options.ignore_last_delimiters)}`
371
+ ], options);
372
+ }
373
+ if(options.ignore_last_delimiters === true && options.columns === false){
374
+ throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [
375
+ 'The option `ignore_last_delimiters`',
376
+ 'requires the activation of the `columns` option'
377
+ ], options);
378
+ }
379
+ // Normalize option `info`
380
+ if(options.info === undefined || options.info === null || options.info === false){
381
+ options.info = false;
382
+ }else if(options.info !== true){
383
+ throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
384
+ }
385
+ // Normalize option `max_record_size`
386
+ if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){
387
+ options.max_record_size = 0;
388
+ }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){
389
+ options.max_record_size = parseInt(options.max_record_size);
390
+ }else {
391
+ throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
392
+ }
393
+ // Normalize option `objname`
394
+ if(options.objname === undefined || options.objname === null || options.objname === false){
395
+ options.objname = undefined;
396
+ }else if(Buffer.isBuffer(options.objname)){
397
+ if(options.objname.length === 0){
398
+ throw new Error(`Invalid Option: objname must be a non empty buffer`);
399
+ }
400
+ if(options.encoding === null);else {
401
+ options.objname = options.objname.toString(options.encoding);
402
+ }
403
+ }else if(typeof options.objname === 'string'){
404
+ if(options.objname.length === 0){
405
+ throw new Error(`Invalid Option: objname must be a non empty string`);
406
+ }
407
+ // Great, nothing to do
408
+ }else if(typeof options.objname === 'number');else {
409
+ throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
410
+ }
411
+ if(options.objname !== undefined){
412
+ if(typeof options.objname === 'number'){
413
+ if(options.columns !== false){
414
+ throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field');
415
+ }
416
+ }else { // A string or a buffer
417
+ if(options.columns === false){
418
+ throw Error('Invalid Option: objname field must be combined with columns or be defined as an index');
419
+ }
420
+ }
421
+ }
422
+ // Normalize option `on_record`
423
+ if(options.on_record === undefined || options.on_record === null){
424
+ options.on_record = undefined;
425
+ }else if(typeof options.on_record !== 'function'){
426
+ throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [
427
+ 'Invalid option `on_record`:',
428
+ 'expect a function,',
429
+ `got ${JSON.stringify(options.on_record)}`
430
+ ], options);
431
+ }
432
+ // Normalize option `quote`
433
+ if(options.quote === null || options.quote === false || options.quote === ''){
434
+ options.quote = null;
435
+ }else {
436
+ if(options.quote === undefined || options.quote === true){
437
+ options.quote = Buffer.from('"', options.encoding);
438
+ }else if(typeof options.quote === 'string'){
439
+ options.quote = Buffer.from(options.quote, options.encoding);
440
+ }
441
+ if(!Buffer.isBuffer(options.quote)){
442
+ throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
443
+ }
444
+ }
445
+ // Normalize option `raw`
446
+ if(options.raw === undefined || options.raw === null || options.raw === false){
447
+ options.raw = false;
448
+ }else if(options.raw !== true){
449
+ throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
450
+ }
451
+ // Normalize option `record_delimiter`
452
+ if(options.record_delimiter === undefined){
453
+ options.record_delimiter = [];
454
+ }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){
455
+ if(options.record_delimiter.length === 0){
456
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
457
+ 'Invalid option `record_delimiter`:',
458
+ 'value must be a non empty string or buffer,',
459
+ `got ${JSON.stringify(options.record_delimiter)}`
460
+ ], options);
461
+ }
462
+ options.record_delimiter = [options.record_delimiter];
463
+ }else if(!Array.isArray(options.record_delimiter)){
464
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
465
+ 'Invalid option `record_delimiter`:',
466
+ 'value must be a string, a buffer or array of string|buffer,',
467
+ `got ${JSON.stringify(options.record_delimiter)}`
468
+ ], options);
469
+ }
470
+ options.record_delimiter = options.record_delimiter.map(function(rd, i){
471
+ if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){
472
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
473
+ 'Invalid option `record_delimiter`:',
474
+ 'value must be a string, a buffer or array of string|buffer',
475
+ `at index ${i},`,
476
+ `got ${JSON.stringify(rd)}`
477
+ ], options);
478
+ }else if(rd.length === 0){
479
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
480
+ 'Invalid option `record_delimiter`:',
481
+ 'value must be a non empty string or buffer',
482
+ `at index ${i},`,
483
+ `got ${JSON.stringify(rd)}`
484
+ ], options);
485
+ }
486
+ if(typeof rd === 'string'){
487
+ rd = Buffer.from(rd, options.encoding);
488
+ }
489
+ return rd;
490
+ });
491
+ // Normalize option `relax_column_count`
492
+ if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){
493
+ options.relax_column_count = false;
494
+ }else {
495
+ throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
496
+ }
497
+ if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){
498
+ options.relax_column_count_less = false;
499
+ }else {
500
+ throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
501
+ }
502
+ if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){
503
+ options.relax_column_count_more = false;
504
+ }else {
505
+ throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
506
+ }
507
+ // Normalize option `relax_quotes`
508
+ if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){
509
+ options.relax_quotes = false;
510
+ }else {
511
+ throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
512
+ }
513
+ // Normalize option `skip_empty_lines`
514
+ if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){
515
+ options.skip_empty_lines = false;
516
+ }else {
517
+ throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
518
+ }
519
+ // Normalize option `skip_records_with_empty_values`
520
+ if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){
521
+ options.skip_records_with_empty_values = false;
522
+ }else {
523
+ throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
524
+ }
525
+ // Normalize option `skip_records_with_error`
526
+ if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){
527
+ options.skip_records_with_error = false;
528
+ }else {
529
+ throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
530
+ }
531
+ // Normalize option `rtrim`
532
+ if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){
533
+ options.rtrim = false;
534
+ }else if(options.rtrim !== true){
535
+ throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
536
+ }
537
+ // Normalize option `ltrim`
538
+ if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){
539
+ options.ltrim = false;
540
+ }else if(options.ltrim !== true){
541
+ throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
542
+ }
543
+ // Normalize option `trim`
544
+ if(options.trim === undefined || options.trim === null || options.trim === false){
545
+ options.trim = false;
546
+ }else if(options.trim !== true){
547
+ throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
548
+ }
549
+ // Normalize options `trim`, `ltrim` and `rtrim`
550
+ if(options.trim === true && opts.ltrim !== false){
551
+ options.ltrim = true;
552
+ }else if(options.ltrim !== true){
553
+ options.ltrim = false;
554
+ }
555
+ if(options.trim === true && opts.rtrim !== false){
556
+ options.rtrim = true;
557
+ }else if(options.rtrim !== true){
558
+ options.rtrim = false;
559
+ }
560
+ // Normalize option `to`
561
+ if(options.to === undefined || options.to === null){
562
+ options.to = -1;
563
+ }else {
564
+ if(typeof options.to === 'string' && /\d+/.test(options.to)){
565
+ options.to = parseInt(options.to);
566
+ }
567
+ if(Number.isInteger(options.to)){
568
+ if(options.to <= 0){
569
+ throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
570
+ }
571
+ }else {
572
+ throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
573
+ }
574
+ }
575
+ // Normalize option `to_line`
576
+ if(options.to_line === undefined || options.to_line === null){
577
+ options.to_line = -1;
578
+ }else {
579
+ if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){
580
+ options.to_line = parseInt(options.to_line);
581
+ }
582
+ if(Number.isInteger(options.to_line)){
583
+ if(options.to_line <= 0){
584
+ throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
585
+ }
586
+ }else {
587
+ throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
588
+ }
589
+ }
590
+ return options;
591
+ };
592
+
593
+ const isRecordEmpty = function(record){
594
+ return record.every((field) => field == null || field.toString && field.toString().trim() === '');
595
+ };
596
+
597
+ const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
598
+ const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
599
+
600
+ const boms = {
601
+ // Note, the following are equals:
602
+ // Buffer.from("\ufeff")
603
+ // Buffer.from([239, 187, 191])
604
+ // Buffer.from('EFBBBF', 'hex')
605
+ 'utf8': Buffer.from([239, 187, 191]),
606
+ // Note, the following are equals:
607
+ // Buffer.from "\ufeff", 'utf16le
608
+ // Buffer.from([255, 254])
609
+ 'utf16le': Buffer.from([255, 254])
610
+ };
611
+
612
+ const transform = function(original_options = {}) {
613
+ const info = {
614
+ bytes: 0,
615
+ comment_lines: 0,
616
+ empty_lines: 0,
617
+ invalid_field_length: 0,
618
+ lines: 1,
619
+ records: 0
620
+ };
621
+ const options = normalize_options(original_options);
622
+ return {
623
+ info: info,
624
+ original_options: original_options,
625
+ options: options,
626
+ state: init_state(options),
627
+ __needMoreData: function(i, bufLen, end){
628
+ if(end) return false;
629
+ const {encoding, escape, quote} = this.options;
630
+ const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state;
631
+ const numOfCharLeft = bufLen - i - 1;
632
+ const requiredLength = Math.max(
633
+ needMoreDataSize,
634
+ // Skip if the remaining buffer smaller than record delimiter
635
+ // If "record_delimiter" is yet to be discovered:
636
+ // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
637
+ // 2. We set the length to windows line ending in the current encoding
638
+ // Note, that encoding is known from user or bom discovery at that point
639
+ // recordDelimiterMaxLength,
640
+ recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength,
641
+ // Skip if remaining buffer can be an escaped quote
642
+ quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0,
643
+ // Skip if remaining buffer can be record delimiter following the closing quote
644
+ quoting ? (quote.length + recordDelimiterMaxLength) : 0,
645
+ );
646
+ return numOfCharLeft < requiredLength;
647
+ },
648
+ // Central parser implementation
649
+ parse: function(nextBuf, end, push, close){
650
+ const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options;
651
+ let {comment, escape, quote, record_delimiter} = this.options;
652
+ const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state;
653
+ let buf;
654
+ if(previousBuf === undefined){
655
+ if(nextBuf === undefined){
656
+ // Handle empty string
657
+ close();
658
+ return;
659
+ }else {
660
+ buf = nextBuf;
661
+ }
662
+ }else if(previousBuf !== undefined && nextBuf === undefined){
663
+ buf = previousBuf;
664
+ }else {
665
+ buf = Buffer.concat([previousBuf, nextBuf]);
666
+ }
667
+ // Handle UTF BOM
668
+ if(bomSkipped === false){
669
+ if(bom === false){
670
+ this.state.bomSkipped = true;
671
+ }else if(buf.length < 3){
672
+ // No enough data
673
+ if(end === false){
674
+ // Wait for more data
675
+ this.state.previousBuf = buf;
676
+ return;
677
+ }
678
+ }else {
679
+ for(const encoding in boms){
680
+ if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){
681
+ // Skip BOM
682
+ const bomLength = boms[encoding].length;
683
+ this.state.bufBytesStart += bomLength;
684
+ buf = buf.slice(bomLength);
685
+ // Renormalize original options with the new encoding
686
+ this.options = normalize_options({...this.original_options, encoding: encoding});
687
+ // Options will re-evaluate the Buffer with the new encoding
688
+ ({comment, escape, quote } = this.options);
689
+ break;
690
+ }
691
+ }
692
+ this.state.bomSkipped = true;
693
+ }
694
+ }
695
+ const bufLen = buf.length;
696
+ let pos;
697
+ for(pos = 0; pos < bufLen; pos++){
698
+ // Ensure we get enough space to look ahead
699
+ // There should be a way to move this out of the loop
700
+ if(this.__needMoreData(pos, bufLen, end)){
701
+ break;
702
+ }
703
+ if(this.state.wasRowDelimiter === true){
704
+ this.info.lines++;
705
+ this.state.wasRowDelimiter = false;
706
+ }
707
+ if(to_line !== -1 && this.info.lines > to_line){
708
+ this.state.stop = true;
709
+ close();
710
+ return;
711
+ }
712
+ // Auto discovery of record_delimiter, unix, mac and windows supported
713
+ if(this.state.quoting === false && record_delimiter.length === 0){
714
+ const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
715
+ if(record_delimiterCount){
716
+ record_delimiter = this.options.record_delimiter;
717
+ }
718
+ }
719
+ const chr = buf[pos];
720
+ if(raw === true){
721
+ rawBuffer.append(chr);
722
+ }
723
+ if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){
724
+ this.state.wasRowDelimiter = true;
725
+ }
726
+ // Previous char was a valid escape char
727
+ // treat the current char as a regular char
728
+ if(this.state.escaping === true){
729
+ this.state.escaping = false;
730
+ }else {
731
+ // Escape is only active inside quoted fields
732
+ // We are quoting, the char is an escape chr and there is a chr to escape
733
+ // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){
734
+ if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){
735
+ if(escapeIsQuote){
736
+ if(this.__isQuote(buf, pos+escape.length)){
737
+ this.state.escaping = true;
738
+ pos += escape.length - 1;
739
+ continue;
740
+ }
741
+ }else {
742
+ this.state.escaping = true;
743
+ pos += escape.length - 1;
744
+ continue;
745
+ }
746
+ }
747
+ // Not currently escaping and chr is a quote
748
+ // TODO: need to compare bytes instead of single char
749
+ if(this.state.commenting === false && this.__isQuote(buf, pos)){
750
+ if(this.state.quoting === true){
751
+ const nextChr = buf[pos+quote.length];
752
+ const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length);
753
+ const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr);
754
+ const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr);
755
+ const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length);
756
+ // Escape a quote
757
+ // Treat next char as a regular character
758
+ if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){
759
+ pos += escape.length - 1;
760
+ }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){
761
+ this.state.quoting = false;
762
+ this.state.wasQuoting = true;
763
+ pos += quote.length - 1;
764
+ continue;
765
+ }else if(relax_quotes === false){
766
+ const err = this.__error(
767
+ new CsvError('CSV_INVALID_CLOSING_QUOTE', [
768
+ 'Invalid Closing Quote:',
769
+ `got "${String.fromCharCode(nextChr)}"`,
770
+ `at line ${this.info.lines}`,
771
+ 'instead of delimiter, record delimiter, trimable character',
772
+ '(if activated) or comment',
773
+ ], this.options, this.__infoField())
774
+ );
775
+ if(err !== undefined) return err;
776
+ }else {
777
+ this.state.quoting = false;
778
+ this.state.wasQuoting = true;
779
+ this.state.field.prepend(quote);
780
+ pos += quote.length - 1;
781
+ }
782
+ }else {
783
+ if(this.state.field.length !== 0){
784
+ // In relax_quotes mode, treat opening quote preceded by chrs as regular
785
+ if(relax_quotes === false){
786
+ const info = this.__infoField();
787
+ const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
788
+ const err = this.__error(
789
+ new CsvError('INVALID_OPENING_QUOTE', [
790
+ 'Invalid Opening Quote:',
791
+ `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
792
+ bom ? `(${bom} bom)` : undefined
793
+ ], this.options, info, {
794
+ field: this.state.field,
795
+ })
796
+ );
797
+ if(err !== undefined) return err;
798
+ }
799
+ }else {
800
+ this.state.quoting = true;
801
+ pos += quote.length - 1;
802
+ continue;
803
+ }
804
+ }
805
+ }
806
+ if(this.state.quoting === false){
807
+ const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
808
+ if(recordDelimiterLength !== 0){
809
+ // Do not emit comments which take a full line
810
+ const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
811
+ if(skipCommentLine){
812
+ this.info.comment_lines++;
813
+ // Skip full comment line
814
+ }else {
815
+ // Activate records emition if above from_line
816
+ if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){
817
+ this.state.enabled = true;
818
+ this.__resetField();
819
+ this.__resetRecord();
820
+ pos += recordDelimiterLength - 1;
821
+ continue;
822
+ }
823
+ // Skip if line is empty and skip_empty_lines activated
824
+ if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){
825
+ this.info.empty_lines++;
826
+ pos += recordDelimiterLength - 1;
827
+ continue;
828
+ }
829
+ this.info.bytes = this.state.bufBytesStart + pos;
830
+ const errField = this.__onField();
831
+ if(errField !== undefined) return errField;
832
+ this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
833
+ const errRecord = this.__onRecord(push);
834
+ if(errRecord !== undefined) return errRecord;
835
+ if(to !== -1 && this.info.records >= to){
836
+ this.state.stop = true;
837
+ close();
838
+ return;
839
+ }
840
+ }
841
+ this.state.commenting = false;
842
+ pos += recordDelimiterLength - 1;
843
+ continue;
844
+ }
845
+ if(this.state.commenting){
846
+ continue;
847
+ }
848
+ if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) {
849
+ const commentCount = this.__compareBytes(comment, buf, pos, chr);
850
+ if(commentCount !== 0){
851
+ this.state.commenting = true;
852
+ continue;
853
+ }
854
+ }
855
+ const delimiterLength = this.__isDelimiter(buf, pos, chr);
856
+ if(delimiterLength !== 0){
857
+ this.info.bytes = this.state.bufBytesStart + pos;
858
+ const errField = this.__onField();
859
+ if(errField !== undefined) return errField;
860
+ pos += delimiterLength - 1;
861
+ continue;
862
+ }
863
+ }
864
+ }
865
+ if(this.state.commenting === false){
866
+ if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){
867
+ return this.__error(
868
+ new CsvError('CSV_MAX_RECORD_SIZE', [
869
+ 'Max Record Size:',
870
+ 'record exceed the maximum number of tolerated bytes',
871
+ `of ${max_record_size}`,
872
+ `at line ${this.info.lines}`,
873
+ ], this.options, this.__infoField())
874
+ );
875
+ }
876
+ }
877
+ const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
878
+ // rtrim in non quoting is handle in __onField
879
+ const rappend = rtrim === false || this.state.wasQuoting === false;
880
+ if(lappend === true && rappend === true){
881
+ this.state.field.append(chr);
882
+ }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){
883
+ return this.__error(
884
+ new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [
885
+ 'Invalid Closing Quote:',
886
+ 'found non trimable byte after quote',
887
+ `at line ${this.info.lines}`,
888
+ ], this.options, this.__infoField())
889
+ );
890
+ }else {
891
+ if(lappend === false){
892
+ pos += this.__isCharTrimable(buf, pos) - 1;
893
+ }
894
+ continue;
895
+ }
896
+ }
897
+ if(end === true){
898
+ // Ensure we are not ending in a quoting state
899
+ if(this.state.quoting === true){
900
+ const err = this.__error(
901
+ new CsvError('CSV_QUOTE_NOT_CLOSED', [
902
+ 'Quote Not Closed:',
903
+ `the parsing is finished with an opening quote at line ${this.info.lines}`,
904
+ ], this.options, this.__infoField())
905
+ );
906
+ if(err !== undefined) return err;
907
+ }else {
908
+ // Skip last line if it has no characters
909
+ if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){
910
+ this.info.bytes = this.state.bufBytesStart + pos;
911
+ const errField = this.__onField();
912
+ if(errField !== undefined) return errField;
913
+ const errRecord = this.__onRecord(push);
914
+ if(errRecord !== undefined) return errRecord;
915
+ }else if(this.state.wasRowDelimiter === true){
916
+ this.info.empty_lines++;
917
+ }else if(this.state.commenting === true){
918
+ this.info.comment_lines++;
919
+ }
920
+ }
921
+ }else {
922
+ this.state.bufBytesStart += pos;
923
+ this.state.previousBuf = buf.slice(pos);
924
+ }
925
+ if(this.state.wasRowDelimiter === true){
926
+ this.info.lines++;
927
+ this.state.wasRowDelimiter = false;
928
+ }
929
+ },
930
+ __onRecord: function(push){
931
+ const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options;
932
+ const {enabled, record} = this.state;
933
+ if(enabled === false){
934
+ return this.__resetRecord();
935
+ }
936
+ // Convert the first line into column names
937
+ const recordLength = record.length;
938
+ if(columns === true){
939
+ if(skip_records_with_empty_values === true && isRecordEmpty(record)){
940
+ this.__resetRecord();
941
+ return;
942
+ }
943
+ return this.__firstLineToColumns(record);
944
+ }
945
+ if(columns === false && this.info.records === 0){
946
+ this.state.expectedRecordLength = recordLength;
947
+ }
948
+ if(recordLength !== this.state.expectedRecordLength){
949
+ const err = columns === false ?
950
+ new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [
951
+ 'Invalid Record Length:',
952
+ `expect ${this.state.expectedRecordLength},`,
953
+ `got ${recordLength} on line ${this.info.lines}`,
954
+ ], this.options, this.__infoField(), {
955
+ record: record,
956
+ })
957
+ :
958
+ new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [
959
+ 'Invalid Record Length:',
960
+ `columns length is ${columns.length},`, // rename columns
961
+ `got ${recordLength} on line ${this.info.lines}`,
962
+ ], this.options, this.__infoField(), {
963
+ record: record,
964
+ });
965
+ if(relax_column_count === true ||
966
+ (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) ||
967
+ (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){
968
+ this.info.invalid_field_length++;
969
+ this.state.error = err;
970
+ // Error is undefined with skip_records_with_error
971
+ }else {
972
+ const finalErr = this.__error(err);
973
+ if(finalErr) return finalErr;
974
+ }
975
+ }
976
+ if(skip_records_with_empty_values === true && isRecordEmpty(record)){
977
+ this.__resetRecord();
978
+ return;
979
+ }
980
+ if(this.state.recordHasError === true){
981
+ this.__resetRecord();
982
+ this.state.recordHasError = false;
983
+ return;
984
+ }
985
+ this.info.records++;
986
+ if(from === 1 || this.info.records >= from){
987
+ const {objname} = this.options;
988
+ // With columns, records are object
989
+ if(columns !== false){
990
+ const obj = {};
991
+ // Transform record array to an object
992
+ for(let i = 0, l = record.length; i < l; i++){
993
+ if(columns[i] === undefined || columns[i].disabled) continue;
994
+ // Turn duplicate columns into an array
995
+ if (group_columns_by_name === true && obj[columns[i].name] !== undefined) {
996
+ if (Array.isArray(obj[columns[i].name])) {
997
+ obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
998
+ } else {
999
+ obj[columns[i].name] = [obj[columns[i].name], record[i]];
1000
+ }
1001
+ } else {
1002
+ obj[columns[i].name] = record[i];
1003
+ }
1004
+ }
1005
+ // Without objname (default)
1006
+ if(raw === true || info === true){
1007
+ const extRecord = Object.assign(
1008
+ {record: obj},
1009
+ (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}),
1010
+ (info === true ? {info: this.__infoRecord()}: {})
1011
+ );
1012
+ const err = this.__push(
1013
+ objname === undefined ? extRecord : [obj[objname], extRecord]
1014
+ , push);
1015
+ if(err){
1016
+ return err;
1017
+ }
1018
+ }else {
1019
+ const err = this.__push(
1020
+ objname === undefined ? obj : [obj[objname], obj]
1021
+ , push);
1022
+ if(err){
1023
+ return err;
1024
+ }
1025
+ }
1026
+ // Without columns, records are array
1027
+ }else {
1028
+ if(raw === true || info === true){
1029
+ const extRecord = Object.assign(
1030
+ {record: record},
1031
+ raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {},
1032
+ info === true ? {info: this.__infoRecord()}: {}
1033
+ );
1034
+ const err = this.__push(
1035
+ objname === undefined ? extRecord : [record[objname], extRecord]
1036
+ , push);
1037
+ if(err){
1038
+ return err;
1039
+ }
1040
+ }else {
1041
+ const err = this.__push(
1042
+ objname === undefined ? record : [record[objname], record]
1043
+ , push);
1044
+ if(err){
1045
+ return err;
1046
+ }
1047
+ }
1048
+ }
1049
+ }
1050
+ this.__resetRecord();
1051
+ },
1052
+ __firstLineToColumns: function(record){
1053
+ const {firstLineToHeaders} = this.state;
1054
+ try{
1055
+ const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
1056
+ if(!Array.isArray(headers)){
1057
+ return this.__error(
1058
+ new CsvError('CSV_INVALID_COLUMN_MAPPING', [
1059
+ 'Invalid Column Mapping:',
1060
+ 'expect an array from column function,',
1061
+ `got ${JSON.stringify(headers)}`
1062
+ ], this.options, this.__infoField(), {
1063
+ headers: headers,
1064
+ })
1065
+ );
1066
+ }
1067
+ const normalizedHeaders = normalize_columns_array(headers);
1068
+ this.state.expectedRecordLength = normalizedHeaders.length;
1069
+ this.options.columns = normalizedHeaders;
1070
+ this.__resetRecord();
1071
+ return;
1072
+ }catch(err){
1073
+ return err;
1074
+ }
1075
+ },
1076
+ __resetRecord: function(){
1077
+ if(this.options.raw === true){
1078
+ this.state.rawBuffer.reset();
1079
+ }
1080
+ this.state.error = undefined;
1081
+ this.state.record = [];
1082
+ this.state.record_length = 0;
1083
+ },
1084
+ __onField: function(){
1085
+ const {cast, encoding, rtrim, max_record_size} = this.options;
1086
+ const {enabled, wasQuoting} = this.state;
1087
+ // Short circuit for the from_line options
1088
+ if(enabled === false){
1089
+ return this.__resetField();
1090
+ }
1091
+ let field = this.state.field.toString(encoding);
1092
+ if(rtrim === true && wasQuoting === false){
1093
+ field = field.trimRight();
1094
+ }
1095
+ if(cast === true){
1096
+ const [err, f] = this.__cast(field);
1097
+ if(err !== undefined) return err;
1098
+ field = f;
1099
+ }
1100
+ this.state.record.push(field);
1101
+ // Increment record length if record size must not exceed a limit
1102
+ if(max_record_size !== 0 && typeof field === 'string'){
1103
+ this.state.record_length += field.length;
1104
+ }
1105
+ this.__resetField();
1106
+ },
1107
+ __resetField: function(){
1108
+ this.state.field.reset();
1109
+ this.state.wasQuoting = false;
1110
+ },
1111
+ __push: function(record, push){
1112
+ const {on_record} = this.options;
1113
+ if(on_record !== undefined){
1114
+ const info = this.__infoRecord();
1115
+ try{
1116
+ record = on_record.call(null, record, info);
1117
+ }catch(err){
1118
+ return err;
1119
+ }
1120
+ if(record === undefined || record === null){ return; }
1121
+ }
1122
+ push(record);
1123
+ },
1124
+ // Return a tuple with the error and the casted value
1125
+ __cast: function(field){
1126
+ const {columns, relax_column_count} = this.options;
1127
+ const isColumns = Array.isArray(columns);
1128
+ // Dont loose time calling cast
1129
+ // because the final record is an object
1130
+ // and this field can't be associated to a key present in columns
1131
+ if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){
1132
+ return [undefined, undefined];
1133
+ }
1134
+ if(this.state.castField !== null){
1135
+ try{
1136
+ const info = this.__infoField();
1137
+ return [undefined, this.state.castField.call(null, field, info)];
1138
+ }catch(err){
1139
+ return [err];
1140
+ }
1141
+ }
1142
+ if(this.__isFloat(field)){
1143
+ return [undefined, parseFloat(field)];
1144
+ }else if(this.options.cast_date !== false){
1145
+ const info = this.__infoField();
1146
+ return [undefined, this.options.cast_date.call(null, field, info)];
1147
+ }
1148
+ return [undefined, field];
1149
+ },
1150
+ // Helper to test if a character is a space or a line delimiter
1151
+ __isCharTrimable: function(buf, pos){
1152
+ const isTrim = (buf, pos) => {
1153
+ const {timchars} = this.state;
1154
+ loop1: for(let i = 0; i < timchars.length; i++){
1155
+ const timchar = timchars[i];
1156
+ for(let j = 0; j < timchar.length; j++){
1157
+ if(timchar[j] !== buf[pos+j]) continue loop1;
1158
+ }
1159
+ return timchar.length;
1160
+ }
1161
+ return 0;
1162
+ };
1163
+ return isTrim(buf, pos);
1164
+ },
1165
+ // Keep it in case we implement the `cast_int` option
1166
+ // __isInt(value){
1167
+ // // return Number.isInteger(parseInt(value))
1168
+ // // return !isNaN( parseInt( obj ) );
1169
+ // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
1170
+ // }
1171
+ __isFloat: function(value){
1172
+ return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery
1173
+ },
1174
+ __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){
1175
+ if(sourceBuf[0] !== firstByte) return 0;
1176
+ const sourceLength = sourceBuf.length;
1177
+ for(let i = 1; i < sourceLength; i++){
1178
+ if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0;
1179
+ }
1180
+ return sourceLength;
1181
+ },
1182
+ __isDelimiter: function(buf, pos, chr){
1183
+ const {delimiter, ignore_last_delimiters} = this.options;
1184
+ if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){
1185
+ return 0;
1186
+ }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){
1187
+ return 0;
1188
+ }
1189
+ loop1: for(let i = 0; i < delimiter.length; i++){
1190
+ const del = delimiter[i];
1191
+ if(del[0] === chr){
1192
+ for(let j = 1; j < del.length; j++){
1193
+ if(del[j] !== buf[pos+j]) continue loop1;
1194
+ }
1195
+ return del.length;
1196
+ }
1197
+ }
1198
+ return 0;
1199
+ },
1200
+ __isRecordDelimiter: function(chr, buf, pos){
1201
+ const {record_delimiter} = this.options;
1202
+ const recordDelimiterLength = record_delimiter.length;
1203
+ loop1: for(let i = 0; i < recordDelimiterLength; i++){
1204
+ const rd = record_delimiter[i];
1205
+ const rdLength = rd.length;
1206
+ if(rd[0] !== chr){
1207
+ continue;
1208
+ }
1209
+ for(let j = 1; j < rdLength; j++){
1210
+ if(rd[j] !== buf[pos+j]){
1211
+ continue loop1;
1212
+ }
1213
+ }
1214
+ return rd.length;
1215
+ }
1216
+ return 0;
1217
+ },
1218
+ __isEscape: function(buf, pos, chr){
1219
+ const {escape} = this.options;
1220
+ if(escape === null) return false;
1221
+ const l = escape.length;
1222
+ if(escape[0] === chr){
1223
+ for(let i = 0; i < l; i++){
1224
+ if(escape[i] !== buf[pos+i]){
1225
+ return false;
1226
+ }
1227
+ }
1228
+ return true;
1229
+ }
1230
+ return false;
1231
+ },
1232
+ __isQuote: function(buf, pos){
1233
+ const {quote} = this.options;
1234
+ if(quote === null) return false;
1235
+ const l = quote.length;
1236
+ for(let i = 0; i < l; i++){
1237
+ if(quote[i] !== buf[pos+i]){
1238
+ return false;
1239
+ }
1240
+ }
1241
+ return true;
1242
+ },
1243
+ __autoDiscoverRecordDelimiter: function(buf, pos){
1244
+ const { encoding } = this.options;
1245
+ // Note, we don't need to cache this information in state,
1246
+ // It is only called on the first line until we find out a suitable
1247
+ // record delimiter.
1248
+ const rds = [
1249
+ // Important, the windows line ending must be before mac os 9
1250
+ Buffer.from('\r\n', encoding),
1251
+ Buffer.from('\n', encoding),
1252
+ Buffer.from('\r', encoding),
1253
+ ];
1254
+ loop: for(let i = 0; i < rds.length; i++){
1255
+ const l = rds[i].length;
1256
+ for(let j = 0; j < l; j++){
1257
+ if(rds[i][j] !== buf[pos + j]){
1258
+ continue loop;
1259
+ }
1260
+ }
1261
+ this.options.record_delimiter.push(rds[i]);
1262
+ this.state.recordDelimiterMaxLength = rds[i].length;
1263
+ return rds[i].length;
1264
+ }
1265
+ return 0;
1266
+ },
1267
+ __error: function(msg){
1268
+ const {encoding, raw, skip_records_with_error} = this.options;
1269
+ const err = typeof msg === 'string' ? new Error(msg) : msg;
1270
+ if(skip_records_with_error){
1271
+ this.state.recordHasError = true;
1272
+ if(this.options.on_skip !== undefined){
1273
+ this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
1274
+ }
1275
+ // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
1276
+ return undefined;
1277
+ }else {
1278
+ return err;
1279
+ }
1280
+ },
1281
+ __infoDataSet: function(){
1282
+ return {
1283
+ ...this.info,
1284
+ columns: this.options.columns
1285
+ };
1286
+ },
1287
+ __infoRecord: function(){
1288
+ const {columns, raw, encoding} = this.options;
1289
+ return {
1290
+ ...this.__infoDataSet(),
1291
+ error: this.state.error,
1292
+ header: columns === true,
1293
+ index: this.state.record.length,
1294
+ raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
1295
+ };
1296
+ },
1297
+ __infoField: function(){
1298
+ const {columns} = this.options;
1299
+ const isColumns = Array.isArray(columns);
1300
+ return {
1301
+ ...this.__infoRecord(),
1302
+ column: isColumns === true ?
1303
+ (columns.length > this.state.record.length ?
1304
+ columns[this.state.record.length].name :
1305
+ null
1306
+ ) :
1307
+ this.state.record.length,
1308
+ quoting: this.state.wasQuoting,
1309
+ };
1310
+ }
1311
+ };
1312
+ };
1313
+
1314
+ const parse = function(data, opts={}){
1315
+ if(typeof data === 'string'){
1316
+ data = Buffer.from(data);
1317
+ }
1318
+ const records = opts && opts.objname ? {} : [];
1319
+ const parser = transform(opts);
1320
+ const push = (record) => {
1321
+ if(parser.options.objname === undefined)
1322
+ records.push(record);
1323
+ else {
1324
+ records[record[0]] = record[1];
1325
+ }
1326
+ };
1327
+ const close = () => {};
1328
+ const err1 = parser.parse(data, false, push, close);
1329
+ if(err1 !== undefined) throw err1;
1330
+ const err2 = parser.parse(undefined, true, push, close);
1331
+ if(err2 !== undefined) throw err2;
1332
+ return records;
1333
+ };
1334
+
1335
+ exports.CsvError = CsvError;
1336
+ exports.parse = parse;