@contrail/cli 3.4.4-alpha.03728c1 → 3.4.4-alpha.3b13bd5

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,3314 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_parse_sync = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ var global$1 = (typeof global !== "undefined" ? global :
8
+ typeof self !== "undefined" ? self :
9
+ typeof window !== "undefined" ? window : {});
10
+
11
+ var lookup = [];
12
+ var revLookup = [];
13
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
14
+ var inited = false;
15
+ function init () {
16
+ inited = true;
17
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
18
+ for (var i = 0, len = code.length; i < len; ++i) {
19
+ lookup[i] = code[i];
20
+ revLookup[code.charCodeAt(i)] = i;
21
+ }
22
+
23
+ revLookup['-'.charCodeAt(0)] = 62;
24
+ revLookup['_'.charCodeAt(0)] = 63;
25
+ }
26
+
27
+ function toByteArray (b64) {
28
+ if (!inited) {
29
+ init();
30
+ }
31
+ var i, j, l, tmp, placeHolders, arr;
32
+ var len = b64.length;
33
+
34
+ if (len % 4 > 0) {
35
+ throw new Error('Invalid string. Length must be a multiple of 4')
36
+ }
37
+
38
+ // the number of equal signs (place holders)
39
+ // if there are two placeholders, than the two characters before it
40
+ // represent one byte
41
+ // if there is only one, then the three characters before it represent 2 bytes
42
+ // this is just a cheap hack to not do indexOf twice
43
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
44
+
45
+ // base64 is 4/3 + up to two characters of the original data
46
+ arr = new Arr(len * 3 / 4 - placeHolders);
47
+
48
+ // if there are placeholders, only get up to the last complete 4 chars
49
+ l = placeHolders > 0 ? len - 4 : len;
50
+
51
+ var L = 0;
52
+
53
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
54
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
55
+ arr[L++] = (tmp >> 16) & 0xFF;
56
+ arr[L++] = (tmp >> 8) & 0xFF;
57
+ arr[L++] = tmp & 0xFF;
58
+ }
59
+
60
+ if (placeHolders === 2) {
61
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
62
+ arr[L++] = tmp & 0xFF;
63
+ } else if (placeHolders === 1) {
64
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
65
+ arr[L++] = (tmp >> 8) & 0xFF;
66
+ arr[L++] = tmp & 0xFF;
67
+ }
68
+
69
+ return arr
70
+ }
71
+
72
+ function tripletToBase64 (num) {
73
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
74
+ }
75
+
76
+ function encodeChunk (uint8, start, end) {
77
+ var tmp;
78
+ var output = [];
79
+ for (var i = start; i < end; i += 3) {
80
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
81
+ output.push(tripletToBase64(tmp));
82
+ }
83
+ return output.join('')
84
+ }
85
+
86
+ function fromByteArray (uint8) {
87
+ if (!inited) {
88
+ init();
89
+ }
90
+ var tmp;
91
+ var len = uint8.length;
92
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
93
+ var output = '';
94
+ var parts = [];
95
+ var maxChunkLength = 16383; // must be multiple of 3
96
+
97
+ // go through the array every three bytes, we'll deal with trailing stuff later
98
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
99
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
100
+ }
101
+
102
+ // pad the end with zeros, but make sure to not forget the extra bytes
103
+ if (extraBytes === 1) {
104
+ tmp = uint8[len - 1];
105
+ output += lookup[tmp >> 2];
106
+ output += lookup[(tmp << 4) & 0x3F];
107
+ output += '==';
108
+ } else if (extraBytes === 2) {
109
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
110
+ output += lookup[tmp >> 10];
111
+ output += lookup[(tmp >> 4) & 0x3F];
112
+ output += lookup[(tmp << 2) & 0x3F];
113
+ output += '=';
114
+ }
115
+
116
+ parts.push(output);
117
+
118
+ return parts.join('')
119
+ }
120
+
121
+ function read (buffer, offset, isLE, mLen, nBytes) {
122
+ var e, m;
123
+ var eLen = nBytes * 8 - mLen - 1;
124
+ var eMax = (1 << eLen) - 1;
125
+ var eBias = eMax >> 1;
126
+ var nBits = -7;
127
+ var i = isLE ? (nBytes - 1) : 0;
128
+ var d = isLE ? -1 : 1;
129
+ var s = buffer[offset + i];
130
+
131
+ i += d;
132
+
133
+ e = s & ((1 << (-nBits)) - 1);
134
+ s >>= (-nBits);
135
+ nBits += eLen;
136
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
137
+
138
+ m = e & ((1 << (-nBits)) - 1);
139
+ e >>= (-nBits);
140
+ nBits += mLen;
141
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
142
+
143
+ if (e === 0) {
144
+ e = 1 - eBias;
145
+ } else if (e === eMax) {
146
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
147
+ } else {
148
+ m = m + Math.pow(2, mLen);
149
+ e = e - eBias;
150
+ }
151
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
152
+ }
153
+
154
+ function write (buffer, value, offset, isLE, mLen, nBytes) {
155
+ var e, m, c;
156
+ var eLen = nBytes * 8 - mLen - 1;
157
+ var eMax = (1 << eLen) - 1;
158
+ var eBias = eMax >> 1;
159
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
160
+ var i = isLE ? 0 : (nBytes - 1);
161
+ var d = isLE ? 1 : -1;
162
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
163
+
164
+ value = Math.abs(value);
165
+
166
+ if (isNaN(value) || value === Infinity) {
167
+ m = isNaN(value) ? 1 : 0;
168
+ e = eMax;
169
+ } else {
170
+ e = Math.floor(Math.log(value) / Math.LN2);
171
+ if (value * (c = Math.pow(2, -e)) < 1) {
172
+ e--;
173
+ c *= 2;
174
+ }
175
+ if (e + eBias >= 1) {
176
+ value += rt / c;
177
+ } else {
178
+ value += rt * Math.pow(2, 1 - eBias);
179
+ }
180
+ if (value * c >= 2) {
181
+ e++;
182
+ c /= 2;
183
+ }
184
+
185
+ if (e + eBias >= eMax) {
186
+ m = 0;
187
+ e = eMax;
188
+ } else if (e + eBias >= 1) {
189
+ m = (value * c - 1) * Math.pow(2, mLen);
190
+ e = e + eBias;
191
+ } else {
192
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
193
+ e = 0;
194
+ }
195
+ }
196
+
197
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
198
+
199
+ e = (e << mLen) | m;
200
+ eLen += mLen;
201
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
202
+
203
+ buffer[offset + i - d] |= s * 128;
204
+ }
205
+
206
+ var toString = {}.toString;
207
+
208
+ var isArray = Array.isArray || function (arr) {
209
+ return toString.call(arr) == '[object Array]';
210
+ };
211
+
212
+ var INSPECT_MAX_BYTES = 50;
213
+
214
+ /**
215
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
216
+ * === true Use Uint8Array implementation (fastest)
217
+ * === false Use Object implementation (most compatible, even IE6)
218
+ *
219
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
220
+ * Opera 11.6+, iOS 4.2+.
221
+ *
222
+ * Due to various browser bugs, sometimes the Object implementation will be used even
223
+ * when the browser supports typed arrays.
224
+ *
225
+ * Note:
226
+ *
227
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
228
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
229
+ *
230
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
231
+ *
232
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
233
+ * incorrect length in some situations.
234
+
235
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
236
+ * get the Object implementation, which is slower but behaves correctly.
237
+ */
238
+ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
239
+ ? global$1.TYPED_ARRAY_SUPPORT
240
+ : true;
241
+
242
+ /*
243
+ * Export kMaxLength after typed array support is determined.
244
+ */
245
+ kMaxLength();
246
+
247
+ function kMaxLength () {
248
+ return Buffer.TYPED_ARRAY_SUPPORT
249
+ ? 0x7fffffff
250
+ : 0x3fffffff
251
+ }
252
+
253
+ function createBuffer (that, length) {
254
+ if (kMaxLength() < length) {
255
+ throw new RangeError('Invalid typed array length')
256
+ }
257
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
258
+ // Return an augmented `Uint8Array` instance, for best performance
259
+ that = new Uint8Array(length);
260
+ that.__proto__ = Buffer.prototype;
261
+ } else {
262
+ // Fallback: Return an object instance of the Buffer class
263
+ if (that === null) {
264
+ that = new Buffer(length);
265
+ }
266
+ that.length = length;
267
+ }
268
+
269
+ return that
270
+ }
271
+
272
+ /**
273
+ * The Buffer constructor returns instances of `Uint8Array` that have their
274
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
275
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
276
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
277
+ * returns a single octet.
278
+ *
279
+ * The `Uint8Array` prototype remains unmodified.
280
+ */
281
+
282
+ function Buffer (arg, encodingOrOffset, length) {
283
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
284
+ return new Buffer(arg, encodingOrOffset, length)
285
+ }
286
+
287
+ // Common case.
288
+ if (typeof arg === 'number') {
289
+ if (typeof encodingOrOffset === 'string') {
290
+ throw new Error(
291
+ 'If encoding is specified then the first argument must be a string'
292
+ )
293
+ }
294
+ return allocUnsafe(this, arg)
295
+ }
296
+ return from(this, arg, encodingOrOffset, length)
297
+ }
298
+
299
+ Buffer.poolSize = 8192; // not used by this implementation
300
+
301
+ // TODO: Legacy, not needed anymore. Remove in next major version.
302
+ Buffer._augment = function (arr) {
303
+ arr.__proto__ = Buffer.prototype;
304
+ return arr
305
+ };
306
+
307
+ function from (that, value, encodingOrOffset, length) {
308
+ if (typeof value === 'number') {
309
+ throw new TypeError('"value" argument must not be a number')
310
+ }
311
+
312
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
313
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
314
+ }
315
+
316
+ if (typeof value === 'string') {
317
+ return fromString(that, value, encodingOrOffset)
318
+ }
319
+
320
+ return fromObject(that, value)
321
+ }
322
+
323
+ /**
324
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
325
+ * if value is a number.
326
+ * Buffer.from(str[, encoding])
327
+ * Buffer.from(array)
328
+ * Buffer.from(buffer)
329
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
330
+ **/
331
+ Buffer.from = function (value, encodingOrOffset, length) {
332
+ return from(null, value, encodingOrOffset, length)
333
+ };
334
+
335
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
336
+ Buffer.prototype.__proto__ = Uint8Array.prototype;
337
+ Buffer.__proto__ = Uint8Array;
338
+ if (typeof Symbol !== 'undefined' && Symbol.species &&
339
+ Buffer[Symbol.species] === Buffer) ;
340
+ }
341
+
342
+ function assertSize (size) {
343
+ if (typeof size !== 'number') {
344
+ throw new TypeError('"size" argument must be a number')
345
+ } else if (size < 0) {
346
+ throw new RangeError('"size" argument must not be negative')
347
+ }
348
+ }
349
+
350
+ function alloc (that, size, fill, encoding) {
351
+ assertSize(size);
352
+ if (size <= 0) {
353
+ return createBuffer(that, size)
354
+ }
355
+ if (fill !== undefined) {
356
+ // Only pay attention to encoding if it's a string. This
357
+ // prevents accidentally sending in a number that would
358
+ // be interpretted as a start offset.
359
+ return typeof encoding === 'string'
360
+ ? createBuffer(that, size).fill(fill, encoding)
361
+ : createBuffer(that, size).fill(fill)
362
+ }
363
+ return createBuffer(that, size)
364
+ }
365
+
366
+ /**
367
+ * Creates a new filled Buffer instance.
368
+ * alloc(size[, fill[, encoding]])
369
+ **/
370
+ Buffer.alloc = function (size, fill, encoding) {
371
+ return alloc(null, size, fill, encoding)
372
+ };
373
+
374
+ function allocUnsafe (that, size) {
375
+ assertSize(size);
376
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
377
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
378
+ for (var i = 0; i < size; ++i) {
379
+ that[i] = 0;
380
+ }
381
+ }
382
+ return that
383
+ }
384
+
385
+ /**
386
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
387
+ * */
388
+ Buffer.allocUnsafe = function (size) {
389
+ return allocUnsafe(null, size)
390
+ };
391
+ /**
392
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
393
+ */
394
+ Buffer.allocUnsafeSlow = function (size) {
395
+ return allocUnsafe(null, size)
396
+ };
397
+
398
+ function fromString (that, string, encoding) {
399
+ if (typeof encoding !== 'string' || encoding === '') {
400
+ encoding = 'utf8';
401
+ }
402
+
403
+ if (!Buffer.isEncoding(encoding)) {
404
+ throw new TypeError('"encoding" must be a valid string encoding')
405
+ }
406
+
407
+ var length = byteLength(string, encoding) | 0;
408
+ that = createBuffer(that, length);
409
+
410
+ var actual = that.write(string, encoding);
411
+
412
+ if (actual !== length) {
413
+ // Writing a hex string, for example, that contains invalid characters will
414
+ // cause everything after the first invalid character to be ignored. (e.g.
415
+ // 'abxxcd' will be treated as 'ab')
416
+ that = that.slice(0, actual);
417
+ }
418
+
419
+ return that
420
+ }
421
+
422
+ function fromArrayLike (that, array) {
423
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
424
+ that = createBuffer(that, length);
425
+ for (var i = 0; i < length; i += 1) {
426
+ that[i] = array[i] & 255;
427
+ }
428
+ return that
429
+ }
430
+
431
+ function fromArrayBuffer (that, array, byteOffset, length) {
432
+ array.byteLength; // this throws if `array` is not a valid ArrayBuffer
433
+
434
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
435
+ throw new RangeError('\'offset\' is out of bounds')
436
+ }
437
+
438
+ if (array.byteLength < byteOffset + (length || 0)) {
439
+ throw new RangeError('\'length\' is out of bounds')
440
+ }
441
+
442
+ if (byteOffset === undefined && length === undefined) {
443
+ array = new Uint8Array(array);
444
+ } else if (length === undefined) {
445
+ array = new Uint8Array(array, byteOffset);
446
+ } else {
447
+ array = new Uint8Array(array, byteOffset, length);
448
+ }
449
+
450
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
451
+ // Return an augmented `Uint8Array` instance, for best performance
452
+ that = array;
453
+ that.__proto__ = Buffer.prototype;
454
+ } else {
455
+ // Fallback: Return an object instance of the Buffer class
456
+ that = fromArrayLike(that, array);
457
+ }
458
+ return that
459
+ }
460
+
461
+ function fromObject (that, obj) {
462
+ if (internalIsBuffer(obj)) {
463
+ var len = checked(obj.length) | 0;
464
+ that = createBuffer(that, len);
465
+
466
+ if (that.length === 0) {
467
+ return that
468
+ }
469
+
470
+ obj.copy(that, 0, 0, len);
471
+ return that
472
+ }
473
+
474
+ if (obj) {
475
+ if ((typeof ArrayBuffer !== 'undefined' &&
476
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
477
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
478
+ return createBuffer(that, 0)
479
+ }
480
+ return fromArrayLike(that, obj)
481
+ }
482
+
483
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
484
+ return fromArrayLike(that, obj.data)
485
+ }
486
+ }
487
+
488
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
489
+ }
490
+
491
+ function checked (length) {
492
+ // Note: cannot use `length < kMaxLength()` here because that fails when
493
+ // length is NaN (which is otherwise coerced to zero.)
494
+ if (length >= kMaxLength()) {
495
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
496
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
497
+ }
498
+ return length | 0
499
+ }
500
+ Buffer.isBuffer = isBuffer;
501
+ function internalIsBuffer (b) {
502
+ return !!(b != null && b._isBuffer)
503
+ }
504
+
505
+ Buffer.compare = function compare (a, b) {
506
+ if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
507
+ throw new TypeError('Arguments must be Buffers')
508
+ }
509
+
510
+ if (a === b) return 0
511
+
512
+ var x = a.length;
513
+ var y = b.length;
514
+
515
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
516
+ if (a[i] !== b[i]) {
517
+ x = a[i];
518
+ y = b[i];
519
+ break
520
+ }
521
+ }
522
+
523
+ if (x < y) return -1
524
+ if (y < x) return 1
525
+ return 0
526
+ };
527
+
528
+ Buffer.isEncoding = function isEncoding (encoding) {
529
+ switch (String(encoding).toLowerCase()) {
530
+ case 'hex':
531
+ case 'utf8':
532
+ case 'utf-8':
533
+ case 'ascii':
534
+ case 'latin1':
535
+ case 'binary':
536
+ case 'base64':
537
+ case 'ucs2':
538
+ case 'ucs-2':
539
+ case 'utf16le':
540
+ case 'utf-16le':
541
+ return true
542
+ default:
543
+ return false
544
+ }
545
+ };
546
+
547
+ Buffer.concat = function concat (list, length) {
548
+ if (!isArray(list)) {
549
+ throw new TypeError('"list" argument must be an Array of Buffers')
550
+ }
551
+
552
+ if (list.length === 0) {
553
+ return Buffer.alloc(0)
554
+ }
555
+
556
+ var i;
557
+ if (length === undefined) {
558
+ length = 0;
559
+ for (i = 0; i < list.length; ++i) {
560
+ length += list[i].length;
561
+ }
562
+ }
563
+
564
+ var buffer = Buffer.allocUnsafe(length);
565
+ var pos = 0;
566
+ for (i = 0; i < list.length; ++i) {
567
+ var buf = list[i];
568
+ if (!internalIsBuffer(buf)) {
569
+ throw new TypeError('"list" argument must be an Array of Buffers')
570
+ }
571
+ buf.copy(buffer, pos);
572
+ pos += buf.length;
573
+ }
574
+ return buffer
575
+ };
576
+
577
+ function byteLength (string, encoding) {
578
+ if (internalIsBuffer(string)) {
579
+ return string.length
580
+ }
581
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
582
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
583
+ return string.byteLength
584
+ }
585
+ if (typeof string !== 'string') {
586
+ string = '' + string;
587
+ }
588
+
589
+ var len = string.length;
590
+ if (len === 0) return 0
591
+
592
+ // Use a for loop to avoid recursion
593
+ var loweredCase = false;
594
+ for (;;) {
595
+ switch (encoding) {
596
+ case 'ascii':
597
+ case 'latin1':
598
+ case 'binary':
599
+ return len
600
+ case 'utf8':
601
+ case 'utf-8':
602
+ case undefined:
603
+ return utf8ToBytes(string).length
604
+ case 'ucs2':
605
+ case 'ucs-2':
606
+ case 'utf16le':
607
+ case 'utf-16le':
608
+ return len * 2
609
+ case 'hex':
610
+ return len >>> 1
611
+ case 'base64':
612
+ return base64ToBytes(string).length
613
+ default:
614
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
615
+ encoding = ('' + encoding).toLowerCase();
616
+ loweredCase = true;
617
+ }
618
+ }
619
+ }
620
+ Buffer.byteLength = byteLength;
621
+
622
+ function slowToString (encoding, start, end) {
623
+ var loweredCase = false;
624
+
625
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
626
+ // property of a typed array.
627
+
628
+ // This behaves neither like String nor Uint8Array in that we set start/end
629
+ // to their upper/lower bounds if the value passed is out of range.
630
+ // undefined is handled specially as per ECMA-262 6th Edition,
631
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
632
+ if (start === undefined || start < 0) {
633
+ start = 0;
634
+ }
635
+ // Return early if start > this.length. Done here to prevent potential uint32
636
+ // coercion fail below.
637
+ if (start > this.length) {
638
+ return ''
639
+ }
640
+
641
+ if (end === undefined || end > this.length) {
642
+ end = this.length;
643
+ }
644
+
645
+ if (end <= 0) {
646
+ return ''
647
+ }
648
+
649
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
650
+ end >>>= 0;
651
+ start >>>= 0;
652
+
653
+ if (end <= start) {
654
+ return ''
655
+ }
656
+
657
+ if (!encoding) encoding = 'utf8';
658
+
659
+ while (true) {
660
+ switch (encoding) {
661
+ case 'hex':
662
+ return hexSlice(this, start, end)
663
+
664
+ case 'utf8':
665
+ case 'utf-8':
666
+ return utf8Slice(this, start, end)
667
+
668
+ case 'ascii':
669
+ return asciiSlice(this, start, end)
670
+
671
+ case 'latin1':
672
+ case 'binary':
673
+ return latin1Slice(this, start, end)
674
+
675
+ case 'base64':
676
+ return base64Slice(this, start, end)
677
+
678
+ case 'ucs2':
679
+ case 'ucs-2':
680
+ case 'utf16le':
681
+ case 'utf-16le':
682
+ return utf16leSlice(this, start, end)
683
+
684
+ default:
685
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
686
+ encoding = (encoding + '').toLowerCase();
687
+ loweredCase = true;
688
+ }
689
+ }
690
+ }
691
+
692
+ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
693
+ // Buffer instances.
694
+ Buffer.prototype._isBuffer = true;
695
+
696
+ function swap (b, n, m) {
697
+ var i = b[n];
698
+ b[n] = b[m];
699
+ b[m] = i;
700
+ }
701
+
702
+ Buffer.prototype.swap16 = function swap16 () {
703
+ var len = this.length;
704
+ if (len % 2 !== 0) {
705
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
706
+ }
707
+ for (var i = 0; i < len; i += 2) {
708
+ swap(this, i, i + 1);
709
+ }
710
+ return this
711
+ };
712
+
713
+ Buffer.prototype.swap32 = function swap32 () {
714
+ var len = this.length;
715
+ if (len % 4 !== 0) {
716
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
717
+ }
718
+ for (var i = 0; i < len; i += 4) {
719
+ swap(this, i, i + 3);
720
+ swap(this, i + 1, i + 2);
721
+ }
722
+ return this
723
+ };
724
+
725
+ Buffer.prototype.swap64 = function swap64 () {
726
+ var len = this.length;
727
+ if (len % 8 !== 0) {
728
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
729
+ }
730
+ for (var i = 0; i < len; i += 8) {
731
+ swap(this, i, i + 7);
732
+ swap(this, i + 1, i + 6);
733
+ swap(this, i + 2, i + 5);
734
+ swap(this, i + 3, i + 4);
735
+ }
736
+ return this
737
+ };
738
+
739
+ Buffer.prototype.toString = function toString () {
740
+ var length = this.length | 0;
741
+ if (length === 0) return ''
742
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
743
+ return slowToString.apply(this, arguments)
744
+ };
745
+
746
+ Buffer.prototype.equals = function equals (b) {
747
+ if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
748
+ if (this === b) return true
749
+ return Buffer.compare(this, b) === 0
750
+ };
751
+
752
+ Buffer.prototype.inspect = function inspect () {
753
+ var str = '';
754
+ var max = INSPECT_MAX_BYTES;
755
+ if (this.length > 0) {
756
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
757
+ if (this.length > max) str += ' ... ';
758
+ }
759
+ return '<Buffer ' + str + '>'
760
+ };
761
+
762
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
763
+ if (!internalIsBuffer(target)) {
764
+ throw new TypeError('Argument must be a Buffer')
765
+ }
766
+
767
+ if (start === undefined) {
768
+ start = 0;
769
+ }
770
+ if (end === undefined) {
771
+ end = target ? target.length : 0;
772
+ }
773
+ if (thisStart === undefined) {
774
+ thisStart = 0;
775
+ }
776
+ if (thisEnd === undefined) {
777
+ thisEnd = this.length;
778
+ }
779
+
780
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
781
+ throw new RangeError('out of range index')
782
+ }
783
+
784
+ if (thisStart >= thisEnd && start >= end) {
785
+ return 0
786
+ }
787
+ if (thisStart >= thisEnd) {
788
+ return -1
789
+ }
790
+ if (start >= end) {
791
+ return 1
792
+ }
793
+
794
+ start >>>= 0;
795
+ end >>>= 0;
796
+ thisStart >>>= 0;
797
+ thisEnd >>>= 0;
798
+
799
+ if (this === target) return 0
800
+
801
+ var x = thisEnd - thisStart;
802
+ var y = end - start;
803
+ var len = Math.min(x, y);
804
+
805
+ var thisCopy = this.slice(thisStart, thisEnd);
806
+ var targetCopy = target.slice(start, end);
807
+
808
+ for (var i = 0; i < len; ++i) {
809
+ if (thisCopy[i] !== targetCopy[i]) {
810
+ x = thisCopy[i];
811
+ y = targetCopy[i];
812
+ break
813
+ }
814
+ }
815
+
816
+ if (x < y) return -1
817
+ if (y < x) return 1
818
+ return 0
819
+ };
820
+
821
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
822
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
823
+ //
824
+ // Arguments:
825
+ // - buffer - a Buffer to search
826
+ // - val - a string, Buffer, or number
827
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
828
+ // - encoding - an optional encoding, relevant is val is a string
829
+ // - dir - true for indexOf, false for lastIndexOf
830
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
831
+ // Empty buffer means no match
832
+ if (buffer.length === 0) return -1
833
+
834
+ // Normalize byteOffset
835
+ if (typeof byteOffset === 'string') {
836
+ encoding = byteOffset;
837
+ byteOffset = 0;
838
+ } else if (byteOffset > 0x7fffffff) {
839
+ byteOffset = 0x7fffffff;
840
+ } else if (byteOffset < -0x80000000) {
841
+ byteOffset = -0x80000000;
842
+ }
843
+ byteOffset = +byteOffset; // Coerce to Number.
844
+ if (isNaN(byteOffset)) {
845
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
846
+ byteOffset = dir ? 0 : (buffer.length - 1);
847
+ }
848
+
849
+ // Normalize byteOffset: negative offsets start from the end of the buffer
850
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
851
+ if (byteOffset >= buffer.length) {
852
+ if (dir) return -1
853
+ else byteOffset = buffer.length - 1;
854
+ } else if (byteOffset < 0) {
855
+ if (dir) byteOffset = 0;
856
+ else return -1
857
+ }
858
+
859
+ // Normalize val
860
+ if (typeof val === 'string') {
861
+ val = Buffer.from(val, encoding);
862
+ }
863
+
864
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
865
+ if (internalIsBuffer(val)) {
866
+ // Special case: looking for empty string/buffer always fails
867
+ if (val.length === 0) {
868
+ return -1
869
+ }
870
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
871
+ } else if (typeof val === 'number') {
872
+ val = val & 0xFF; // Search for a byte value [0-255]
873
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
874
+ typeof Uint8Array.prototype.indexOf === 'function') {
875
+ if (dir) {
876
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
877
+ } else {
878
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
879
+ }
880
+ }
881
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
882
+ }
883
+
884
+ throw new TypeError('val must be string, number or Buffer')
885
+ }
886
+
887
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
888
+ var indexSize = 1;
889
+ var arrLength = arr.length;
890
+ var valLength = val.length;
891
+
892
+ if (encoding !== undefined) {
893
+ encoding = String(encoding).toLowerCase();
894
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
895
+ encoding === 'utf16le' || encoding === 'utf-16le') {
896
+ if (arr.length < 2 || val.length < 2) {
897
+ return -1
898
+ }
899
+ indexSize = 2;
900
+ arrLength /= 2;
901
+ valLength /= 2;
902
+ byteOffset /= 2;
903
+ }
904
+ }
905
+
906
+ function read (buf, i) {
907
+ if (indexSize === 1) {
908
+ return buf[i]
909
+ } else {
910
+ return buf.readUInt16BE(i * indexSize)
911
+ }
912
+ }
913
+
914
+ var i;
915
+ if (dir) {
916
+ var foundIndex = -1;
917
+ for (i = byteOffset; i < arrLength; i++) {
918
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
919
+ if (foundIndex === -1) foundIndex = i;
920
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
921
+ } else {
922
+ if (foundIndex !== -1) i -= i - foundIndex;
923
+ foundIndex = -1;
924
+ }
925
+ }
926
+ } else {
927
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
928
+ for (i = byteOffset; i >= 0; i--) {
929
+ var found = true;
930
+ for (var j = 0; j < valLength; j++) {
931
+ if (read(arr, i + j) !== read(val, j)) {
932
+ found = false;
933
+ break
934
+ }
935
+ }
936
+ if (found) return i
937
+ }
938
+ }
939
+
940
+ return -1
941
+ }
942
+
943
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
944
+ return this.indexOf(val, byteOffset, encoding) !== -1
945
+ };
946
+
947
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
948
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
949
+ };
950
+
951
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
952
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
953
+ };
954
+
955
+ function hexWrite (buf, string, offset, length) {
956
+ offset = Number(offset) || 0;
957
+ var remaining = buf.length - offset;
958
+ if (!length) {
959
+ length = remaining;
960
+ } else {
961
+ length = Number(length);
962
+ if (length > remaining) {
963
+ length = remaining;
964
+ }
965
+ }
966
+
967
+ // must be an even number of digits
968
+ var strLen = string.length;
969
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
970
+
971
+ if (length > strLen / 2) {
972
+ length = strLen / 2;
973
+ }
974
+ for (var i = 0; i < length; ++i) {
975
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
976
+ if (isNaN(parsed)) return i
977
+ buf[offset + i] = parsed;
978
+ }
979
+ return i
980
+ }
981
+
982
+ function utf8Write (buf, string, offset, length) {
983
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
984
+ }
985
+
986
+ function asciiWrite (buf, string, offset, length) {
987
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
988
+ }
989
+
990
+ function latin1Write (buf, string, offset, length) {
991
+ return asciiWrite(buf, string, offset, length)
992
+ }
993
+
994
+ function base64Write (buf, string, offset, length) {
995
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
996
+ }
997
+
998
+ function ucs2Write (buf, string, offset, length) {
999
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1000
+ }
1001
+
1002
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
1003
+ // Buffer#write(string)
1004
+ if (offset === undefined) {
1005
+ encoding = 'utf8';
1006
+ length = this.length;
1007
+ offset = 0;
1008
+ // Buffer#write(string, encoding)
1009
+ } else if (length === undefined && typeof offset === 'string') {
1010
+ encoding = offset;
1011
+ length = this.length;
1012
+ offset = 0;
1013
+ // Buffer#write(string, offset[, length][, encoding])
1014
+ } else if (isFinite(offset)) {
1015
+ offset = offset | 0;
1016
+ if (isFinite(length)) {
1017
+ length = length | 0;
1018
+ if (encoding === undefined) encoding = 'utf8';
1019
+ } else {
1020
+ encoding = length;
1021
+ length = undefined;
1022
+ }
1023
+ // legacy write(string, encoding, offset, length) - remove in v0.13
1024
+ } else {
1025
+ throw new Error(
1026
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1027
+ )
1028
+ }
1029
+
1030
+ var remaining = this.length - offset;
1031
+ if (length === undefined || length > remaining) length = remaining;
1032
+
1033
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1034
+ throw new RangeError('Attempt to write outside buffer bounds')
1035
+ }
1036
+
1037
+ if (!encoding) encoding = 'utf8';
1038
+
1039
+ var loweredCase = false;
1040
+ for (;;) {
1041
+ switch (encoding) {
1042
+ case 'hex':
1043
+ return hexWrite(this, string, offset, length)
1044
+
1045
+ case 'utf8':
1046
+ case 'utf-8':
1047
+ return utf8Write(this, string, offset, length)
1048
+
1049
+ case 'ascii':
1050
+ return asciiWrite(this, string, offset, length)
1051
+
1052
+ case 'latin1':
1053
+ case 'binary':
1054
+ return latin1Write(this, string, offset, length)
1055
+
1056
+ case 'base64':
1057
+ // Warning: maxLength not taken into account in base64Write
1058
+ return base64Write(this, string, offset, length)
1059
+
1060
+ case 'ucs2':
1061
+ case 'ucs-2':
1062
+ case 'utf16le':
1063
+ case 'utf-16le':
1064
+ return ucs2Write(this, string, offset, length)
1065
+
1066
+ default:
1067
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1068
+ encoding = ('' + encoding).toLowerCase();
1069
+ loweredCase = true;
1070
+ }
1071
+ }
1072
+ };
1073
+
1074
+ Buffer.prototype.toJSON = function toJSON () {
1075
+ return {
1076
+ type: 'Buffer',
1077
+ data: Array.prototype.slice.call(this._arr || this, 0)
1078
+ }
1079
+ };
1080
+
1081
+ function base64Slice (buf, start, end) {
1082
+ if (start === 0 && end === buf.length) {
1083
+ return fromByteArray(buf)
1084
+ } else {
1085
+ return fromByteArray(buf.slice(start, end))
1086
+ }
1087
+ }
1088
+
1089
+ function utf8Slice (buf, start, end) {
1090
+ end = Math.min(buf.length, end);
1091
+ var res = [];
1092
+
1093
+ var i = start;
1094
+ while (i < end) {
1095
+ var firstByte = buf[i];
1096
+ var codePoint = null;
1097
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
1098
+ : (firstByte > 0xDF) ? 3
1099
+ : (firstByte > 0xBF) ? 2
1100
+ : 1;
1101
+
1102
+ if (i + bytesPerSequence <= end) {
1103
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
1104
+
1105
+ switch (bytesPerSequence) {
1106
+ case 1:
1107
+ if (firstByte < 0x80) {
1108
+ codePoint = firstByte;
1109
+ }
1110
+ break
1111
+ case 2:
1112
+ secondByte = buf[i + 1];
1113
+ if ((secondByte & 0xC0) === 0x80) {
1114
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
1115
+ if (tempCodePoint > 0x7F) {
1116
+ codePoint = tempCodePoint;
1117
+ }
1118
+ }
1119
+ break
1120
+ case 3:
1121
+ secondByte = buf[i + 1];
1122
+ thirdByte = buf[i + 2];
1123
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1124
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
1125
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1126
+ codePoint = tempCodePoint;
1127
+ }
1128
+ }
1129
+ break
1130
+ case 4:
1131
+ secondByte = buf[i + 1];
1132
+ thirdByte = buf[i + 2];
1133
+ fourthByte = buf[i + 3];
1134
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1135
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
1136
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1137
+ codePoint = tempCodePoint;
1138
+ }
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+ if (codePoint === null) {
1144
+ // we did not generate a valid codePoint so insert a
1145
+ // replacement char (U+FFFD) and advance only 1 byte
1146
+ codePoint = 0xFFFD;
1147
+ bytesPerSequence = 1;
1148
+ } else if (codePoint > 0xFFFF) {
1149
+ // encode to utf16 (surrogate pair dance)
1150
+ codePoint -= 0x10000;
1151
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1152
+ codePoint = 0xDC00 | codePoint & 0x3FF;
1153
+ }
1154
+
1155
+ res.push(codePoint);
1156
+ i += bytesPerSequence;
1157
+ }
1158
+
1159
+ return decodeCodePointsArray(res)
1160
+ }
1161
+
1162
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1163
+ // the lowest limit is Chrome, with 0x10000 args.
1164
+ // We go 1 magnitude less, for safety
1165
+ var MAX_ARGUMENTS_LENGTH = 0x1000;
1166
+
1167
+ function decodeCodePointsArray (codePoints) {
1168
+ var len = codePoints.length;
1169
+ if (len <= MAX_ARGUMENTS_LENGTH) {
1170
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1171
+ }
1172
+
1173
+ // Decode in chunks to avoid "call stack size exceeded".
1174
+ var res = '';
1175
+ var i = 0;
1176
+ while (i < len) {
1177
+ res += String.fromCharCode.apply(
1178
+ String,
1179
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1180
+ );
1181
+ }
1182
+ return res
1183
+ }
1184
+
1185
+ function asciiSlice (buf, start, end) {
1186
+ var ret = '';
1187
+ end = Math.min(buf.length, end);
1188
+
1189
+ for (var i = start; i < end; ++i) {
1190
+ ret += String.fromCharCode(buf[i] & 0x7F);
1191
+ }
1192
+ return ret
1193
+ }
1194
+
1195
+ function latin1Slice (buf, start, end) {
1196
+ var ret = '';
1197
+ end = Math.min(buf.length, end);
1198
+
1199
+ for (var i = start; i < end; ++i) {
1200
+ ret += String.fromCharCode(buf[i]);
1201
+ }
1202
+ return ret
1203
+ }
1204
+
1205
+ function hexSlice (buf, start, end) {
1206
+ var len = buf.length;
1207
+
1208
+ if (!start || start < 0) start = 0;
1209
+ if (!end || end < 0 || end > len) end = len;
1210
+
1211
+ var out = '';
1212
+ for (var i = start; i < end; ++i) {
1213
+ out += toHex(buf[i]);
1214
+ }
1215
+ return out
1216
+ }
1217
+
1218
+ function utf16leSlice (buf, start, end) {
1219
+ var bytes = buf.slice(start, end);
1220
+ var res = '';
1221
+ for (var i = 0; i < bytes.length; i += 2) {
1222
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1223
+ }
1224
+ return res
1225
+ }
1226
+
1227
+ Buffer.prototype.slice = function slice (start, end) {
1228
+ var len = this.length;
1229
+ start = ~~start;
1230
+ end = end === undefined ? len : ~~end;
1231
+
1232
+ if (start < 0) {
1233
+ start += len;
1234
+ if (start < 0) start = 0;
1235
+ } else if (start > len) {
1236
+ start = len;
1237
+ }
1238
+
1239
+ if (end < 0) {
1240
+ end += len;
1241
+ if (end < 0) end = 0;
1242
+ } else if (end > len) {
1243
+ end = len;
1244
+ }
1245
+
1246
+ if (end < start) end = start;
1247
+
1248
+ var newBuf;
1249
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1250
+ newBuf = this.subarray(start, end);
1251
+ newBuf.__proto__ = Buffer.prototype;
1252
+ } else {
1253
+ var sliceLen = end - start;
1254
+ newBuf = new Buffer(sliceLen, undefined);
1255
+ for (var i = 0; i < sliceLen; ++i) {
1256
+ newBuf[i] = this[i + start];
1257
+ }
1258
+ }
1259
+
1260
+ return newBuf
1261
+ };
1262
+
1263
+ /*
1264
+ * Need to make sure that buffer isn't trying to write out of bounds.
1265
+ */
1266
+ function checkOffset (offset, ext, length) {
1267
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1268
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1269
+ }
1270
+
1271
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1272
+ offset = offset | 0;
1273
+ byteLength = byteLength | 0;
1274
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
1275
+
1276
+ var val = this[offset];
1277
+ var mul = 1;
1278
+ var i = 0;
1279
+ while (++i < byteLength && (mul *= 0x100)) {
1280
+ val += this[offset + i] * mul;
1281
+ }
1282
+
1283
+ return val
1284
+ };
1285
+
1286
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1287
+ offset = offset | 0;
1288
+ byteLength = byteLength | 0;
1289
+ if (!noAssert) {
1290
+ checkOffset(offset, byteLength, this.length);
1291
+ }
1292
+
1293
+ var val = this[offset + --byteLength];
1294
+ var mul = 1;
1295
+ while (byteLength > 0 && (mul *= 0x100)) {
1296
+ val += this[offset + --byteLength] * mul;
1297
+ }
1298
+
1299
+ return val
1300
+ };
1301
+
1302
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1303
+ if (!noAssert) checkOffset(offset, 1, this.length);
1304
+ return this[offset]
1305
+ };
1306
+
1307
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1308
+ if (!noAssert) checkOffset(offset, 2, this.length);
1309
+ return this[offset] | (this[offset + 1] << 8)
1310
+ };
1311
+
1312
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1313
+ if (!noAssert) checkOffset(offset, 2, this.length);
1314
+ return (this[offset] << 8) | this[offset + 1]
1315
+ };
1316
+
1317
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1318
+ if (!noAssert) checkOffset(offset, 4, this.length);
1319
+
1320
+ return ((this[offset]) |
1321
+ (this[offset + 1] << 8) |
1322
+ (this[offset + 2] << 16)) +
1323
+ (this[offset + 3] * 0x1000000)
1324
+ };
1325
+
1326
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1327
+ if (!noAssert) checkOffset(offset, 4, this.length);
1328
+
1329
+ return (this[offset] * 0x1000000) +
1330
+ ((this[offset + 1] << 16) |
1331
+ (this[offset + 2] << 8) |
1332
+ this[offset + 3])
1333
+ };
1334
+
1335
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1336
+ offset = offset | 0;
1337
+ byteLength = byteLength | 0;
1338
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
1339
+
1340
+ var val = this[offset];
1341
+ var mul = 1;
1342
+ var i = 0;
1343
+ while (++i < byteLength && (mul *= 0x100)) {
1344
+ val += this[offset + i] * mul;
1345
+ }
1346
+ mul *= 0x80;
1347
+
1348
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1349
+
1350
+ return val
1351
+ };
1352
+
1353
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1354
+ offset = offset | 0;
1355
+ byteLength = byteLength | 0;
1356
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
1357
+
1358
+ var i = byteLength;
1359
+ var mul = 1;
1360
+ var val = this[offset + --i];
1361
+ while (i > 0 && (mul *= 0x100)) {
1362
+ val += this[offset + --i] * mul;
1363
+ }
1364
+ mul *= 0x80;
1365
+
1366
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1367
+
1368
+ return val
1369
+ };
1370
+
1371
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1372
+ if (!noAssert) checkOffset(offset, 1, this.length);
1373
+ if (!(this[offset] & 0x80)) return (this[offset])
1374
+ return ((0xff - this[offset] + 1) * -1)
1375
+ };
1376
+
1377
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1378
+ if (!noAssert) checkOffset(offset, 2, this.length);
1379
+ var val = this[offset] | (this[offset + 1] << 8);
1380
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
1381
+ };
1382
+
1383
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1384
+ if (!noAssert) checkOffset(offset, 2, this.length);
1385
+ var val = this[offset + 1] | (this[offset] << 8);
1386
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
1387
+ };
1388
+
1389
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1390
+ if (!noAssert) checkOffset(offset, 4, this.length);
1391
+
1392
+ return (this[offset]) |
1393
+ (this[offset + 1] << 8) |
1394
+ (this[offset + 2] << 16) |
1395
+ (this[offset + 3] << 24)
1396
+ };
1397
+
1398
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1399
+ if (!noAssert) checkOffset(offset, 4, this.length);
1400
+
1401
+ return (this[offset] << 24) |
1402
+ (this[offset + 1] << 16) |
1403
+ (this[offset + 2] << 8) |
1404
+ (this[offset + 3])
1405
+ };
1406
+
1407
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1408
+ if (!noAssert) checkOffset(offset, 4, this.length);
1409
+ return read(this, offset, true, 23, 4)
1410
+ };
1411
+
1412
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1413
+ if (!noAssert) checkOffset(offset, 4, this.length);
1414
+ return read(this, offset, false, 23, 4)
1415
+ };
1416
+
1417
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1418
+ if (!noAssert) checkOffset(offset, 8, this.length);
1419
+ return read(this, offset, true, 52, 8)
1420
+ };
1421
+
1422
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1423
+ if (!noAssert) checkOffset(offset, 8, this.length);
1424
+ return read(this, offset, false, 52, 8)
1425
+ };
1426
+
1427
+ function checkInt (buf, value, offset, ext, max, min) {
1428
+ if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1429
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1430
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1431
+ }
1432
+
1433
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1434
+ value = +value;
1435
+ offset = offset | 0;
1436
+ byteLength = byteLength | 0;
1437
+ if (!noAssert) {
1438
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1439
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
1440
+ }
1441
+
1442
+ var mul = 1;
1443
+ var i = 0;
1444
+ this[offset] = value & 0xFF;
1445
+ while (++i < byteLength && (mul *= 0x100)) {
1446
+ this[offset + i] = (value / mul) & 0xFF;
1447
+ }
1448
+
1449
+ return offset + byteLength
1450
+ };
1451
+
1452
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1453
+ value = +value;
1454
+ offset = offset | 0;
1455
+ byteLength = byteLength | 0;
1456
+ if (!noAssert) {
1457
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1458
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
1459
+ }
1460
+
1461
+ var i = byteLength - 1;
1462
+ var mul = 1;
1463
+ this[offset + i] = value & 0xFF;
1464
+ while (--i >= 0 && (mul *= 0x100)) {
1465
+ this[offset + i] = (value / mul) & 0xFF;
1466
+ }
1467
+
1468
+ return offset + byteLength
1469
+ };
1470
+
1471
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1472
+ value = +value;
1473
+ offset = offset | 0;
1474
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1475
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1476
+ this[offset] = (value & 0xff);
1477
+ return offset + 1
1478
+ };
1479
+
1480
+ function objectWriteUInt16 (buf, value, offset, littleEndian) {
1481
+ if (value < 0) value = 0xffff + value + 1;
1482
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1483
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1484
+ (littleEndian ? i : 1 - i) * 8;
1485
+ }
1486
+ }
1487
+
1488
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1489
+ value = +value;
1490
+ offset = offset | 0;
1491
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1492
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1493
+ this[offset] = (value & 0xff);
1494
+ this[offset + 1] = (value >>> 8);
1495
+ } else {
1496
+ objectWriteUInt16(this, value, offset, true);
1497
+ }
1498
+ return offset + 2
1499
+ };
1500
+
1501
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1502
+ value = +value;
1503
+ offset = offset | 0;
1504
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1505
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1506
+ this[offset] = (value >>> 8);
1507
+ this[offset + 1] = (value & 0xff);
1508
+ } else {
1509
+ objectWriteUInt16(this, value, offset, false);
1510
+ }
1511
+ return offset + 2
1512
+ };
1513
+
1514
+ function objectWriteUInt32 (buf, value, offset, littleEndian) {
1515
+ if (value < 0) value = 0xffffffff + value + 1;
1516
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1517
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
1518
+ }
1519
+ }
1520
+
1521
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1522
+ value = +value;
1523
+ offset = offset | 0;
1524
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1525
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1526
+ this[offset + 3] = (value >>> 24);
1527
+ this[offset + 2] = (value >>> 16);
1528
+ this[offset + 1] = (value >>> 8);
1529
+ this[offset] = (value & 0xff);
1530
+ } else {
1531
+ objectWriteUInt32(this, value, offset, true);
1532
+ }
1533
+ return offset + 4
1534
+ };
1535
+
1536
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1537
+ value = +value;
1538
+ offset = offset | 0;
1539
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1540
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1541
+ this[offset] = (value >>> 24);
1542
+ this[offset + 1] = (value >>> 16);
1543
+ this[offset + 2] = (value >>> 8);
1544
+ this[offset + 3] = (value & 0xff);
1545
+ } else {
1546
+ objectWriteUInt32(this, value, offset, false);
1547
+ }
1548
+ return offset + 4
1549
+ };
1550
+
1551
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1552
+ value = +value;
1553
+ offset = offset | 0;
1554
+ if (!noAssert) {
1555
+ var limit = Math.pow(2, 8 * byteLength - 1);
1556
+
1557
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
1558
+ }
1559
+
1560
+ var i = 0;
1561
+ var mul = 1;
1562
+ var sub = 0;
1563
+ this[offset] = value & 0xFF;
1564
+ while (++i < byteLength && (mul *= 0x100)) {
1565
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1566
+ sub = 1;
1567
+ }
1568
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1569
+ }
1570
+
1571
+ return offset + byteLength
1572
+ };
1573
+
1574
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1575
+ value = +value;
1576
+ offset = offset | 0;
1577
+ if (!noAssert) {
1578
+ var limit = Math.pow(2, 8 * byteLength - 1);
1579
+
1580
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
1581
+ }
1582
+
1583
+ var i = byteLength - 1;
1584
+ var mul = 1;
1585
+ var sub = 0;
1586
+ this[offset + i] = value & 0xFF;
1587
+ while (--i >= 0 && (mul *= 0x100)) {
1588
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1589
+ sub = 1;
1590
+ }
1591
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1592
+ }
1593
+
1594
+ return offset + byteLength
1595
+ };
1596
+
1597
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1598
+ value = +value;
1599
+ offset = offset | 0;
1600
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
1601
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1602
+ if (value < 0) value = 0xff + value + 1;
1603
+ this[offset] = (value & 0xff);
1604
+ return offset + 1
1605
+ };
1606
+
1607
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1608
+ value = +value;
1609
+ offset = offset | 0;
1610
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1611
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1612
+ this[offset] = (value & 0xff);
1613
+ this[offset + 1] = (value >>> 8);
1614
+ } else {
1615
+ objectWriteUInt16(this, value, offset, true);
1616
+ }
1617
+ return offset + 2
1618
+ };
1619
+
1620
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1621
+ value = +value;
1622
+ offset = offset | 0;
1623
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1624
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1625
+ this[offset] = (value >>> 8);
1626
+ this[offset + 1] = (value & 0xff);
1627
+ } else {
1628
+ objectWriteUInt16(this, value, offset, false);
1629
+ }
1630
+ return offset + 2
1631
+ };
1632
+
1633
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1634
+ value = +value;
1635
+ offset = offset | 0;
1636
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1637
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1638
+ this[offset] = (value & 0xff);
1639
+ this[offset + 1] = (value >>> 8);
1640
+ this[offset + 2] = (value >>> 16);
1641
+ this[offset + 3] = (value >>> 24);
1642
+ } else {
1643
+ objectWriteUInt32(this, value, offset, true);
1644
+ }
1645
+ return offset + 4
1646
+ };
1647
+
1648
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1649
+ value = +value;
1650
+ offset = offset | 0;
1651
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1652
+ if (value < 0) value = 0xffffffff + value + 1;
1653
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
1654
+ this[offset] = (value >>> 24);
1655
+ this[offset + 1] = (value >>> 16);
1656
+ this[offset + 2] = (value >>> 8);
1657
+ this[offset + 3] = (value & 0xff);
1658
+ } else {
1659
+ objectWriteUInt32(this, value, offset, false);
1660
+ }
1661
+ return offset + 4
1662
+ };
1663
+
1664
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
1665
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
1666
+ if (offset < 0) throw new RangeError('Index out of range')
1667
+ }
1668
+
1669
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
1670
+ if (!noAssert) {
1671
+ checkIEEE754(buf, value, offset, 4);
1672
+ }
1673
+ write(buf, value, offset, littleEndian, 23, 4);
1674
+ return offset + 4
1675
+ }
1676
+
1677
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1678
+ return writeFloat(this, value, offset, true, noAssert)
1679
+ };
1680
+
1681
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1682
+ return writeFloat(this, value, offset, false, noAssert)
1683
+ };
1684
+
1685
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
1686
+ if (!noAssert) {
1687
+ checkIEEE754(buf, value, offset, 8);
1688
+ }
1689
+ write(buf, value, offset, littleEndian, 52, 8);
1690
+ return offset + 8
1691
+ }
1692
+
1693
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1694
+ return writeDouble(this, value, offset, true, noAssert)
1695
+ };
1696
+
1697
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1698
+ return writeDouble(this, value, offset, false, noAssert)
1699
+ };
1700
+
1701
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1702
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1703
+ if (!start) start = 0;
1704
+ if (!end && end !== 0) end = this.length;
1705
+ if (targetStart >= target.length) targetStart = target.length;
1706
+ if (!targetStart) targetStart = 0;
1707
+ if (end > 0 && end < start) end = start;
1708
+
1709
+ // Copy 0 bytes; we're done
1710
+ if (end === start) return 0
1711
+ if (target.length === 0 || this.length === 0) return 0
1712
+
1713
+ // Fatal error conditions
1714
+ if (targetStart < 0) {
1715
+ throw new RangeError('targetStart out of bounds')
1716
+ }
1717
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1718
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
1719
+
1720
+ // Are we oob?
1721
+ if (end > this.length) end = this.length;
1722
+ if (target.length - targetStart < end - start) {
1723
+ end = target.length - targetStart + start;
1724
+ }
1725
+
1726
+ var len = end - start;
1727
+ var i;
1728
+
1729
+ if (this === target && start < targetStart && targetStart < end) {
1730
+ // descending copy from end
1731
+ for (i = len - 1; i >= 0; --i) {
1732
+ target[i + targetStart] = this[i + start];
1733
+ }
1734
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1735
+ // ascending copy from start
1736
+ for (i = 0; i < len; ++i) {
1737
+ target[i + targetStart] = this[i + start];
1738
+ }
1739
+ } else {
1740
+ Uint8Array.prototype.set.call(
1741
+ target,
1742
+ this.subarray(start, start + len),
1743
+ targetStart
1744
+ );
1745
+ }
1746
+
1747
+ return len
1748
+ };
1749
+
1750
+ // Usage:
1751
+ // buffer.fill(number[, offset[, end]])
1752
+ // buffer.fill(buffer[, offset[, end]])
1753
+ // buffer.fill(string[, offset[, end]][, encoding])
1754
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
1755
+ // Handle string cases:
1756
+ if (typeof val === 'string') {
1757
+ if (typeof start === 'string') {
1758
+ encoding = start;
1759
+ start = 0;
1760
+ end = this.length;
1761
+ } else if (typeof end === 'string') {
1762
+ encoding = end;
1763
+ end = this.length;
1764
+ }
1765
+ if (val.length === 1) {
1766
+ var code = val.charCodeAt(0);
1767
+ if (code < 256) {
1768
+ val = code;
1769
+ }
1770
+ }
1771
+ if (encoding !== undefined && typeof encoding !== 'string') {
1772
+ throw new TypeError('encoding must be a string')
1773
+ }
1774
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1775
+ throw new TypeError('Unknown encoding: ' + encoding)
1776
+ }
1777
+ } else if (typeof val === 'number') {
1778
+ val = val & 255;
1779
+ }
1780
+
1781
+ // Invalid ranges are not set to a default, so can range check early.
1782
+ if (start < 0 || this.length < start || this.length < end) {
1783
+ throw new RangeError('Out of range index')
1784
+ }
1785
+
1786
+ if (end <= start) {
1787
+ return this
1788
+ }
1789
+
1790
+ start = start >>> 0;
1791
+ end = end === undefined ? this.length : end >>> 0;
1792
+
1793
+ if (!val) val = 0;
1794
+
1795
+ var i;
1796
+ if (typeof val === 'number') {
1797
+ for (i = start; i < end; ++i) {
1798
+ this[i] = val;
1799
+ }
1800
+ } else {
1801
+ var bytes = internalIsBuffer(val)
1802
+ ? val
1803
+ : utf8ToBytes(new Buffer(val, encoding).toString());
1804
+ var len = bytes.length;
1805
+ for (i = 0; i < end - start; ++i) {
1806
+ this[i + start] = bytes[i % len];
1807
+ }
1808
+ }
1809
+
1810
+ return this
1811
+ };
1812
+
1813
+ // HELPER FUNCTIONS
1814
+ // ================
1815
+
1816
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
1817
+
1818
+ function base64clean (str) {
1819
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
1820
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '');
1821
+ // Node converts strings with length < 2 to ''
1822
+ if (str.length < 2) return ''
1823
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1824
+ while (str.length % 4 !== 0) {
1825
+ str = str + '=';
1826
+ }
1827
+ return str
1828
+ }
1829
+
1830
+ function stringtrim (str) {
1831
+ if (str.trim) return str.trim()
1832
+ return str.replace(/^\s+|\s+$/g, '')
1833
+ }
1834
+
1835
+ function toHex (n) {
1836
+ if (n < 16) return '0' + n.toString(16)
1837
+ return n.toString(16)
1838
+ }
1839
+
1840
+ function utf8ToBytes (string, units) {
1841
+ units = units || Infinity;
1842
+ var codePoint;
1843
+ var length = string.length;
1844
+ var leadSurrogate = null;
1845
+ var bytes = [];
1846
+
1847
+ for (var i = 0; i < length; ++i) {
1848
+ codePoint = string.charCodeAt(i);
1849
+
1850
+ // is surrogate component
1851
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
1852
+ // last char was a lead
1853
+ if (!leadSurrogate) {
1854
+ // no lead yet
1855
+ if (codePoint > 0xDBFF) {
1856
+ // unexpected trail
1857
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1858
+ continue
1859
+ } else if (i + 1 === length) {
1860
+ // unpaired lead
1861
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1862
+ continue
1863
+ }
1864
+
1865
+ // valid lead
1866
+ leadSurrogate = codePoint;
1867
+
1868
+ continue
1869
+ }
1870
+
1871
+ // 2 leads in a row
1872
+ if (codePoint < 0xDC00) {
1873
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1874
+ leadSurrogate = codePoint;
1875
+ continue
1876
+ }
1877
+
1878
+ // valid surrogate pair
1879
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
1880
+ } else if (leadSurrogate) {
1881
+ // valid bmp char, but last char was a lead
1882
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1883
+ }
1884
+
1885
+ leadSurrogate = null;
1886
+
1887
+ // encode utf8
1888
+ if (codePoint < 0x80) {
1889
+ if ((units -= 1) < 0) break
1890
+ bytes.push(codePoint);
1891
+ } else if (codePoint < 0x800) {
1892
+ if ((units -= 2) < 0) break
1893
+ bytes.push(
1894
+ codePoint >> 0x6 | 0xC0,
1895
+ codePoint & 0x3F | 0x80
1896
+ );
1897
+ } else if (codePoint < 0x10000) {
1898
+ if ((units -= 3) < 0) break
1899
+ bytes.push(
1900
+ codePoint >> 0xC | 0xE0,
1901
+ codePoint >> 0x6 & 0x3F | 0x80,
1902
+ codePoint & 0x3F | 0x80
1903
+ );
1904
+ } else if (codePoint < 0x110000) {
1905
+ if ((units -= 4) < 0) break
1906
+ bytes.push(
1907
+ codePoint >> 0x12 | 0xF0,
1908
+ codePoint >> 0xC & 0x3F | 0x80,
1909
+ codePoint >> 0x6 & 0x3F | 0x80,
1910
+ codePoint & 0x3F | 0x80
1911
+ );
1912
+ } else {
1913
+ throw new Error('Invalid code point')
1914
+ }
1915
+ }
1916
+
1917
+ return bytes
1918
+ }
1919
+
1920
+ function asciiToBytes (str) {
1921
+ var byteArray = [];
1922
+ for (var i = 0; i < str.length; ++i) {
1923
+ // Node's code seems to be doing this and not & 0x7F..
1924
+ byteArray.push(str.charCodeAt(i) & 0xFF);
1925
+ }
1926
+ return byteArray
1927
+ }
1928
+
1929
+ function utf16leToBytes (str, units) {
1930
+ var c, hi, lo;
1931
+ var byteArray = [];
1932
+ for (var i = 0; i < str.length; ++i) {
1933
+ if ((units -= 2) < 0) break
1934
+
1935
+ c = str.charCodeAt(i);
1936
+ hi = c >> 8;
1937
+ lo = c % 256;
1938
+ byteArray.push(lo);
1939
+ byteArray.push(hi);
1940
+ }
1941
+
1942
+ return byteArray
1943
+ }
1944
+
1945
+
1946
+ function base64ToBytes (str) {
1947
+ return toByteArray(base64clean(str))
1948
+ }
1949
+
1950
+ function blitBuffer (src, dst, offset, length) {
1951
+ for (var i = 0; i < length; ++i) {
1952
+ if ((i + offset >= dst.length) || (i >= src.length)) break
1953
+ dst[i + offset] = src[i];
1954
+ }
1955
+ return i
1956
+ }
1957
+
1958
+ function isnan (val) {
1959
+ return val !== val // eslint-disable-line no-self-compare
1960
+ }
1961
+
1962
+
1963
+ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
1964
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
1965
+ // Object.prototype.constructor. Remove this eventually
1966
+ function isBuffer(obj) {
1967
+ return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
1968
+ }
1969
+
1970
+ function isFastBuffer (obj) {
1971
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
1972
+ }
1973
+
1974
+ // For Node v0.10 support. Remove this eventually.
1975
+ function isSlowBuffer (obj) {
1976
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
1977
+ }
1978
+
1979
+ class CsvError extends Error {
1980
+ constructor(code, message, options, ...contexts) {
1981
+ if(Array.isArray(message)) message = message.join(' ').trim();
1982
+ super(message);
1983
+ if(Error.captureStackTrace !== undefined){
1984
+ Error.captureStackTrace(this, CsvError);
1985
+ }
1986
+ this.code = code;
1987
+ for(const context of contexts){
1988
+ for(const key in context){
1989
+ const value = context[key];
1990
+ this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
1991
+ }
1992
+ }
1993
+ }
1994
+ }
1995
+
1996
+ const is_object = function(obj){
1997
+ return (typeof obj === 'object' && obj !== null && !Array.isArray(obj));
1998
+ };
1999
+
2000
+ const normalize_columns_array = function(columns){
2001
+ const normalizedColumns = [];
2002
+ for(let i = 0, l = columns.length; i < l; i++){
2003
+ const column = columns[i];
2004
+ if(column === undefined || column === null || column === false){
2005
+ normalizedColumns[i] = { disabled: true };
2006
+ }else if(typeof column === 'string'){
2007
+ normalizedColumns[i] = { name: column };
2008
+ }else if(is_object(column)){
2009
+ if(typeof column.name !== 'string'){
2010
+ throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [
2011
+ 'Option columns missing name:',
2012
+ `property "name" is required at position ${i}`,
2013
+ 'when column is an object literal'
2014
+ ]);
2015
+ }
2016
+ normalizedColumns[i] = column;
2017
+ }else {
2018
+ throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [
2019
+ 'Invalid column definition:',
2020
+ 'expect a string or a literal object,',
2021
+ `got ${JSON.stringify(column)} at position ${i}`
2022
+ ]);
2023
+ }
2024
+ }
2025
+ return normalizedColumns;
2026
+ };
2027
+
2028
+ class ResizeableBuffer{
2029
+ constructor(size=100){
2030
+ this.size = size;
2031
+ this.length = 0;
2032
+ this.buf = Buffer.allocUnsafe(size);
2033
+ }
2034
+ prepend(val){
2035
+ if(isBuffer(val)){
2036
+ const length = this.length + val.length;
2037
+ if(length >= this.size){
2038
+ this.resize();
2039
+ if(length >= this.size){
2040
+ throw Error('INVALID_BUFFER_STATE');
2041
+ }
2042
+ }
2043
+ const buf = this.buf;
2044
+ this.buf = Buffer.allocUnsafe(this.size);
2045
+ val.copy(this.buf, 0);
2046
+ buf.copy(this.buf, val.length);
2047
+ this.length += val.length;
2048
+ }else {
2049
+ const length = this.length++;
2050
+ if(length === this.size){
2051
+ this.resize();
2052
+ }
2053
+ const buf = this.clone();
2054
+ this.buf[0] = val;
2055
+ buf.copy(this.buf,1, 0, length);
2056
+ }
2057
+ }
2058
+ append(val){
2059
+ const length = this.length++;
2060
+ if(length === this.size){
2061
+ this.resize();
2062
+ }
2063
+ this.buf[length] = val;
2064
+ }
2065
+ clone(){
2066
+ return Buffer.from(this.buf.slice(0, this.length));
2067
+ }
2068
+ resize(){
2069
+ const length = this.length;
2070
+ this.size = this.size * 2;
2071
+ const buf = Buffer.allocUnsafe(this.size);
2072
+ this.buf.copy(buf,0, 0, length);
2073
+ this.buf = buf;
2074
+ }
2075
+ toString(encoding){
2076
+ if(encoding){
2077
+ return this.buf.slice(0, this.length).toString(encoding);
2078
+ }else {
2079
+ return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
2080
+ }
2081
+ }
2082
+ toJSON(){
2083
+ return this.toString('utf8');
2084
+ }
2085
+ reset(){
2086
+ this.length = 0;
2087
+ }
2088
+ }
2089
+
2090
+ // white space characters
2091
+ // https://en.wikipedia.org/wiki/Whitespace_character
2092
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types
2093
+ // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff
2094
+ const np = 12;
2095
+ const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
2096
+ const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
2097
+ const space = 32;
2098
+ const tab = 9;
2099
+
2100
+ const init_state = function(options){
2101
+ return {
2102
+ bomSkipped: false,
2103
+ bufBytesStart: 0,
2104
+ castField: options.cast_function,
2105
+ commenting: false,
2106
+ // Current error encountered by a record
2107
+ error: undefined,
2108
+ enabled: options.from_line === 1,
2109
+ escaping: false,
2110
+ escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
2111
+ // columns can be `false`, `true`, `Array`
2112
+ expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
2113
+ field: new ResizeableBuffer(20),
2114
+ firstLineToHeaders: options.cast_first_line_to_header,
2115
+ needMoreDataSize: Math.max(
2116
+ // Skip if the remaining buffer smaller than comment
2117
+ options.comment !== null ? options.comment.length : 0,
2118
+ // Skip if the remaining buffer can be delimiter
2119
+ ...options.delimiter.map((delimiter) => delimiter.length),
2120
+ // Skip if the remaining buffer can be escape sequence
2121
+ options.quote !== null ? options.quote.length : 0,
2122
+ ),
2123
+ previousBuf: undefined,
2124
+ quoting: false,
2125
+ stop: false,
2126
+ rawBuffer: new ResizeableBuffer(100),
2127
+ record: [],
2128
+ recordHasError: false,
2129
+ record_length: 0,
2130
+ recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
2131
+ trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]],
2132
+ wasQuoting: false,
2133
+ wasRowDelimiter: false,
2134
+ timchars: [
2135
+ Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding),
2136
+ Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding),
2137
+ Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding),
2138
+ Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding),
2139
+ Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding),
2140
+ ]
2141
+ };
2142
+ };
2143
+
2144
+ const underscore = function(str){
2145
+ return str.replace(/([A-Z])/g, function(_, match){
2146
+ return '_' + match.toLowerCase();
2147
+ });
2148
+ };
2149
+
2150
+ const normalize_options = function(opts){
2151
+ const options = {};
2152
+ // Merge with user options
2153
+ for(const opt in opts){
2154
+ options[underscore(opt)] = opts[opt];
2155
+ }
2156
+ // Normalize option `encoding`
2157
+ // Note: defined first because other options depends on it
2158
+ // to convert chars/strings into buffers.
2159
+ if(options.encoding === undefined || options.encoding === true){
2160
+ options.encoding = 'utf8';
2161
+ }else if(options.encoding === null || options.encoding === false){
2162
+ options.encoding = null;
2163
+ }else if(typeof options.encoding !== 'string' && options.encoding !== null){
2164
+ throw new CsvError('CSV_INVALID_OPTION_ENCODING', [
2165
+ 'Invalid option encoding:',
2166
+ 'encoding must be a string or null to return a buffer,',
2167
+ `got ${JSON.stringify(options.encoding)}`
2168
+ ], options);
2169
+ }
2170
+ // Normalize option `bom`
2171
+ if(options.bom === undefined || options.bom === null || options.bom === false){
2172
+ options.bom = false;
2173
+ }else if(options.bom !== true){
2174
+ throw new CsvError('CSV_INVALID_OPTION_BOM', [
2175
+ 'Invalid option bom:', 'bom must be true,',
2176
+ `got ${JSON.stringify(options.bom)}`
2177
+ ], options);
2178
+ }
2179
+ // Normalize option `cast`
2180
+ options.cast_function = null;
2181
+ if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){
2182
+ options.cast = undefined;
2183
+ }else if(typeof options.cast === 'function'){
2184
+ options.cast_function = options.cast;
2185
+ options.cast = true;
2186
+ }else if(options.cast !== true){
2187
+ throw new CsvError('CSV_INVALID_OPTION_CAST', [
2188
+ 'Invalid option cast:', 'cast must be true or a function,',
2189
+ `got ${JSON.stringify(options.cast)}`
2190
+ ], options);
2191
+ }
2192
+ // Normalize option `cast_date`
2193
+ if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){
2194
+ options.cast_date = false;
2195
+ }else if(options.cast_date === true){
2196
+ options.cast_date = function(value){
2197
+ const date = Date.parse(value);
2198
+ return !isNaN(date) ? new Date(date) : value;
2199
+ };
2200
+ }else if (typeof options.cast_date !== 'function'){
2201
+ throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [
2202
+ 'Invalid option cast_date:', 'cast_date must be true or a function,',
2203
+ `got ${JSON.stringify(options.cast_date)}`
2204
+ ], options);
2205
+ }
2206
+ // Normalize option `columns`
2207
+ options.cast_first_line_to_header = null;
2208
+ if(options.columns === true){
2209
+ // Fields in the first line are converted as-is to columns
2210
+ options.cast_first_line_to_header = undefined;
2211
+ }else if(typeof options.columns === 'function'){
2212
+ options.cast_first_line_to_header = options.columns;
2213
+ options.columns = true;
2214
+ }else if(Array.isArray(options.columns)){
2215
+ options.columns = normalize_columns_array(options.columns);
2216
+ }else if(options.columns === undefined || options.columns === null || options.columns === false){
2217
+ options.columns = false;
2218
+ }else {
2219
+ throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [
2220
+ 'Invalid option columns:',
2221
+ 'expect an array, a function or true,',
2222
+ `got ${JSON.stringify(options.columns)}`
2223
+ ], options);
2224
+ }
2225
+ // Normalize option `group_columns_by_name`
2226
+ if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){
2227
+ options.group_columns_by_name = false;
2228
+ }else if(options.group_columns_by_name !== true){
2229
+ throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
2230
+ 'Invalid option group_columns_by_name:',
2231
+ 'expect an boolean,',
2232
+ `got ${JSON.stringify(options.group_columns_by_name)}`
2233
+ ], options);
2234
+ }else if(options.columns === false){
2235
+ throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
2236
+ 'Invalid option group_columns_by_name:',
2237
+ 'the `columns` mode must be activated.'
2238
+ ], options);
2239
+ }
2240
+ // Normalize option `comment`
2241
+ if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){
2242
+ options.comment = null;
2243
+ }else {
2244
+ if(typeof options.comment === 'string'){
2245
+ options.comment = Buffer.from(options.comment, options.encoding);
2246
+ }
2247
+ if(!isBuffer(options.comment)){
2248
+ throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
2249
+ 'Invalid option comment:',
2250
+ 'comment must be a buffer or a string,',
2251
+ `got ${JSON.stringify(options.comment)}`
2252
+ ], options);
2253
+ }
2254
+ }
2255
+ // Normalize option `comment_no_infix`
2256
+ if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){
2257
+ options.comment_no_infix = false;
2258
+ }else if(options.comment_no_infix !== true){
2259
+ throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
2260
+ 'Invalid option comment_no_infix:',
2261
+ 'value must be a boolean,',
2262
+ `got ${JSON.stringify(options.comment_no_infix)}`
2263
+ ], options);
2264
+ }
2265
+ // Normalize option `delimiter`
2266
+ const delimiter_json = JSON.stringify(options.delimiter);
2267
+ if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
2268
+ if(options.delimiter.length === 0){
2269
+ throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
2270
+ 'Invalid option delimiter:',
2271
+ 'delimiter must be a non empty string or buffer or array of string|buffer,',
2272
+ `got ${delimiter_json}`
2273
+ ], options);
2274
+ }
2275
+ options.delimiter = options.delimiter.map(function(delimiter){
2276
+ if(delimiter === undefined || delimiter === null || delimiter === false){
2277
+ return Buffer.from(',', options.encoding);
2278
+ }
2279
+ if(typeof delimiter === 'string'){
2280
+ delimiter = Buffer.from(delimiter, options.encoding);
2281
+ }
2282
+ if(!isBuffer(delimiter) || delimiter.length === 0){
2283
+ throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
2284
+ 'Invalid option delimiter:',
2285
+ 'delimiter must be a non empty string or buffer or array of string|buffer,',
2286
+ `got ${delimiter_json}`
2287
+ ], options);
2288
+ }
2289
+ return delimiter;
2290
+ });
2291
+ // Normalize option `escape`
2292
+ if(options.escape === undefined || options.escape === true){
2293
+ options.escape = Buffer.from('"', options.encoding);
2294
+ }else if(typeof options.escape === 'string'){
2295
+ options.escape = Buffer.from(options.escape, options.encoding);
2296
+ }else if (options.escape === null || options.escape === false){
2297
+ options.escape = null;
2298
+ }
2299
+ if(options.escape !== null){
2300
+ if(!isBuffer(options.escape)){
2301
+ throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
2302
+ }
2303
+ }
2304
+ // Normalize option `from`
2305
+ if(options.from === undefined || options.from === null){
2306
+ options.from = 1;
2307
+ }else {
2308
+ if(typeof options.from === 'string' && /\d+/.test(options.from)){
2309
+ options.from = parseInt(options.from);
2310
+ }
2311
+ if(Number.isInteger(options.from)){
2312
+ if(options.from < 0){
2313
+ throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
2314
+ }
2315
+ }else {
2316
+ throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
2317
+ }
2318
+ }
2319
+ // Normalize option `from_line`
2320
+ if(options.from_line === undefined || options.from_line === null){
2321
+ options.from_line = 1;
2322
+ }else {
2323
+ if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){
2324
+ options.from_line = parseInt(options.from_line);
2325
+ }
2326
+ if(Number.isInteger(options.from_line)){
2327
+ if(options.from_line <= 0){
2328
+ throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
2329
+ }
2330
+ }else {
2331
+ throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
2332
+ }
2333
+ }
2334
+ // Normalize options `ignore_last_delimiters`
2335
+ if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){
2336
+ options.ignore_last_delimiters = false;
2337
+ }else if(typeof options.ignore_last_delimiters === 'number'){
2338
+ options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
2339
+ if(options.ignore_last_delimiters === 0){
2340
+ options.ignore_last_delimiters = false;
2341
+ }
2342
+ }else if(typeof options.ignore_last_delimiters !== 'boolean'){
2343
+ throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [
2344
+ 'Invalid option `ignore_last_delimiters`:',
2345
+ 'the value must be a boolean value or an integer,',
2346
+ `got ${JSON.stringify(options.ignore_last_delimiters)}`
2347
+ ], options);
2348
+ }
2349
+ if(options.ignore_last_delimiters === true && options.columns === false){
2350
+ throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [
2351
+ 'The option `ignore_last_delimiters`',
2352
+ 'requires the activation of the `columns` option'
2353
+ ], options);
2354
+ }
2355
+ // Normalize option `info`
2356
+ if(options.info === undefined || options.info === null || options.info === false){
2357
+ options.info = false;
2358
+ }else if(options.info !== true){
2359
+ throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
2360
+ }
2361
+ // Normalize option `max_record_size`
2362
+ if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){
2363
+ options.max_record_size = 0;
2364
+ }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)){
2365
+ options.max_record_size = parseInt(options.max_record_size);
2366
+ }else {
2367
+ throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
2368
+ }
2369
+ // Normalize option `objname`
2370
+ if(options.objname === undefined || options.objname === null || options.objname === false){
2371
+ options.objname = undefined;
2372
+ }else if(isBuffer(options.objname)){
2373
+ if(options.objname.length === 0){
2374
+ throw new Error(`Invalid Option: objname must be a non empty buffer`);
2375
+ }
2376
+ if(options.encoding === null);else {
2377
+ options.objname = options.objname.toString(options.encoding);
2378
+ }
2379
+ }else if(typeof options.objname === 'string'){
2380
+ if(options.objname.length === 0){
2381
+ throw new Error(`Invalid Option: objname must be a non empty string`);
2382
+ }
2383
+ // Great, nothing to do
2384
+ }else if(typeof options.objname === 'number');else {
2385
+ throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
2386
+ }
2387
+ if(options.objname !== undefined){
2388
+ if(typeof options.objname === 'number'){
2389
+ if(options.columns !== false){
2390
+ throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field');
2391
+ }
2392
+ }else { // A string or a buffer
2393
+ if(options.columns === false){
2394
+ throw Error('Invalid Option: objname field must be combined with columns or be defined as an index');
2395
+ }
2396
+ }
2397
+ }
2398
+ // Normalize option `on_record`
2399
+ if(options.on_record === undefined || options.on_record === null){
2400
+ options.on_record = undefined;
2401
+ }else if(typeof options.on_record !== 'function'){
2402
+ throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [
2403
+ 'Invalid option `on_record`:',
2404
+ 'expect a function,',
2405
+ `got ${JSON.stringify(options.on_record)}`
2406
+ ], options);
2407
+ }
2408
+ // Normalize option `quote`
2409
+ if(options.quote === null || options.quote === false || options.quote === ''){
2410
+ options.quote = null;
2411
+ }else {
2412
+ if(options.quote === undefined || options.quote === true){
2413
+ options.quote = Buffer.from('"', options.encoding);
2414
+ }else if(typeof options.quote === 'string'){
2415
+ options.quote = Buffer.from(options.quote, options.encoding);
2416
+ }
2417
+ if(!isBuffer(options.quote)){
2418
+ throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
2419
+ }
2420
+ }
2421
+ // Normalize option `raw`
2422
+ if(options.raw === undefined || options.raw === null || options.raw === false){
2423
+ options.raw = false;
2424
+ }else if(options.raw !== true){
2425
+ throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
2426
+ }
2427
+ // Normalize option `record_delimiter`
2428
+ if(options.record_delimiter === undefined){
2429
+ options.record_delimiter = [];
2430
+ }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){
2431
+ if(options.record_delimiter.length === 0){
2432
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
2433
+ 'Invalid option `record_delimiter`:',
2434
+ 'value must be a non empty string or buffer,',
2435
+ `got ${JSON.stringify(options.record_delimiter)}`
2436
+ ], options);
2437
+ }
2438
+ options.record_delimiter = [options.record_delimiter];
2439
+ }else if(!Array.isArray(options.record_delimiter)){
2440
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
2441
+ 'Invalid option `record_delimiter`:',
2442
+ 'value must be a string, a buffer or array of string|buffer,',
2443
+ `got ${JSON.stringify(options.record_delimiter)}`
2444
+ ], options);
2445
+ }
2446
+ options.record_delimiter = options.record_delimiter.map(function(rd, i){
2447
+ if(typeof rd !== 'string' && ! isBuffer(rd)){
2448
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
2449
+ 'Invalid option `record_delimiter`:',
2450
+ 'value must be a string, a buffer or array of string|buffer',
2451
+ `at index ${i},`,
2452
+ `got ${JSON.stringify(rd)}`
2453
+ ], options);
2454
+ }else if(rd.length === 0){
2455
+ throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
2456
+ 'Invalid option `record_delimiter`:',
2457
+ 'value must be a non empty string or buffer',
2458
+ `at index ${i},`,
2459
+ `got ${JSON.stringify(rd)}`
2460
+ ], options);
2461
+ }
2462
+ if(typeof rd === 'string'){
2463
+ rd = Buffer.from(rd, options.encoding);
2464
+ }
2465
+ return rd;
2466
+ });
2467
+ // Normalize option `relax_column_count`
2468
+ if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){
2469
+ options.relax_column_count = false;
2470
+ }else {
2471
+ throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
2472
+ }
2473
+ if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){
2474
+ options.relax_column_count_less = false;
2475
+ }else {
2476
+ throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
2477
+ }
2478
+ if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){
2479
+ options.relax_column_count_more = false;
2480
+ }else {
2481
+ throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
2482
+ }
2483
+ // Normalize option `relax_quotes`
2484
+ if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){
2485
+ options.relax_quotes = false;
2486
+ }else {
2487
+ throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
2488
+ }
2489
+ // Normalize option `skip_empty_lines`
2490
+ if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){
2491
+ options.skip_empty_lines = false;
2492
+ }else {
2493
+ throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
2494
+ }
2495
+ // Normalize option `skip_records_with_empty_values`
2496
+ 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){
2497
+ options.skip_records_with_empty_values = false;
2498
+ }else {
2499
+ throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
2500
+ }
2501
+ // Normalize option `skip_records_with_error`
2502
+ if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){
2503
+ options.skip_records_with_error = false;
2504
+ }else {
2505
+ throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
2506
+ }
2507
+ // Normalize option `rtrim`
2508
+ if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){
2509
+ options.rtrim = false;
2510
+ }else if(options.rtrim !== true){
2511
+ throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
2512
+ }
2513
+ // Normalize option `ltrim`
2514
+ if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){
2515
+ options.ltrim = false;
2516
+ }else if(options.ltrim !== true){
2517
+ throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
2518
+ }
2519
+ // Normalize option `trim`
2520
+ if(options.trim === undefined || options.trim === null || options.trim === false){
2521
+ options.trim = false;
2522
+ }else if(options.trim !== true){
2523
+ throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
2524
+ }
2525
+ // Normalize options `trim`, `ltrim` and `rtrim`
2526
+ if(options.trim === true && opts.ltrim !== false){
2527
+ options.ltrim = true;
2528
+ }else if(options.ltrim !== true){
2529
+ options.ltrim = false;
2530
+ }
2531
+ if(options.trim === true && opts.rtrim !== false){
2532
+ options.rtrim = true;
2533
+ }else if(options.rtrim !== true){
2534
+ options.rtrim = false;
2535
+ }
2536
+ // Normalize option `to`
2537
+ if(options.to === undefined || options.to === null){
2538
+ options.to = -1;
2539
+ }else {
2540
+ if(typeof options.to === 'string' && /\d+/.test(options.to)){
2541
+ options.to = parseInt(options.to);
2542
+ }
2543
+ if(Number.isInteger(options.to)){
2544
+ if(options.to <= 0){
2545
+ throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
2546
+ }
2547
+ }else {
2548
+ throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
2549
+ }
2550
+ }
2551
+ // Normalize option `to_line`
2552
+ if(options.to_line === undefined || options.to_line === null){
2553
+ options.to_line = -1;
2554
+ }else {
2555
+ if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){
2556
+ options.to_line = parseInt(options.to_line);
2557
+ }
2558
+ if(Number.isInteger(options.to_line)){
2559
+ if(options.to_line <= 0){
2560
+ throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
2561
+ }
2562
+ }else {
2563
+ throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
2564
+ }
2565
+ }
2566
+ return options;
2567
+ };
2568
+
2569
+ const isRecordEmpty = function(record){
2570
+ return record.every((field) => field == null || field.toString && field.toString().trim() === '');
2571
+ };
2572
+
2573
+ const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
2574
+ const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
2575
+
2576
+ const boms = {
2577
+ // Note, the following are equals:
2578
+ // Buffer.from("\ufeff")
2579
+ // Buffer.from([239, 187, 191])
2580
+ // Buffer.from('EFBBBF', 'hex')
2581
+ 'utf8': Buffer.from([239, 187, 191]),
2582
+ // Note, the following are equals:
2583
+ // Buffer.from "\ufeff", 'utf16le
2584
+ // Buffer.from([255, 254])
2585
+ 'utf16le': Buffer.from([255, 254])
2586
+ };
2587
+
2588
+ const transform = function(original_options = {}) {
2589
+ const info = {
2590
+ bytes: 0,
2591
+ comment_lines: 0,
2592
+ empty_lines: 0,
2593
+ invalid_field_length: 0,
2594
+ lines: 1,
2595
+ records: 0
2596
+ };
2597
+ const options = normalize_options(original_options);
2598
+ return {
2599
+ info: info,
2600
+ original_options: original_options,
2601
+ options: options,
2602
+ state: init_state(options),
2603
+ __needMoreData: function(i, bufLen, end){
2604
+ if(end) return false;
2605
+ const {encoding, escape, quote} = this.options;
2606
+ const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state;
2607
+ const numOfCharLeft = bufLen - i - 1;
2608
+ const requiredLength = Math.max(
2609
+ needMoreDataSize,
2610
+ // Skip if the remaining buffer smaller than record delimiter
2611
+ // If "record_delimiter" is yet to be discovered:
2612
+ // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
2613
+ // 2. We set the length to windows line ending in the current encoding
2614
+ // Note, that encoding is known from user or bom discovery at that point
2615
+ // recordDelimiterMaxLength,
2616
+ recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength,
2617
+ // Skip if remaining buffer can be an escaped quote
2618
+ quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0,
2619
+ // Skip if remaining buffer can be record delimiter following the closing quote
2620
+ quoting ? (quote.length + recordDelimiterMaxLength) : 0,
2621
+ );
2622
+ return numOfCharLeft < requiredLength;
2623
+ },
2624
+ // Central parser implementation
2625
+ parse: function(nextBuf, end, push, close){
2626
+ const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options;
2627
+ let {comment, escape, quote, record_delimiter} = this.options;
2628
+ const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state;
2629
+ let buf;
2630
+ if(previousBuf === undefined){
2631
+ if(nextBuf === undefined){
2632
+ // Handle empty string
2633
+ close();
2634
+ return;
2635
+ }else {
2636
+ buf = nextBuf;
2637
+ }
2638
+ }else if(previousBuf !== undefined && nextBuf === undefined){
2639
+ buf = previousBuf;
2640
+ }else {
2641
+ buf = Buffer.concat([previousBuf, nextBuf]);
2642
+ }
2643
+ // Handle UTF BOM
2644
+ if(bomSkipped === false){
2645
+ if(bom === false){
2646
+ this.state.bomSkipped = true;
2647
+ }else if(buf.length < 3){
2648
+ // No enough data
2649
+ if(end === false){
2650
+ // Wait for more data
2651
+ this.state.previousBuf = buf;
2652
+ return;
2653
+ }
2654
+ }else {
2655
+ for(const encoding in boms){
2656
+ if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){
2657
+ // Skip BOM
2658
+ const bomLength = boms[encoding].length;
2659
+ this.state.bufBytesStart += bomLength;
2660
+ buf = buf.slice(bomLength);
2661
+ // Renormalize original options with the new encoding
2662
+ this.options = normalize_options({...this.original_options, encoding: encoding});
2663
+ // Options will re-evaluate the Buffer with the new encoding
2664
+ ({comment, escape, quote } = this.options);
2665
+ break;
2666
+ }
2667
+ }
2668
+ this.state.bomSkipped = true;
2669
+ }
2670
+ }
2671
+ const bufLen = buf.length;
2672
+ let pos;
2673
+ for(pos = 0; pos < bufLen; pos++){
2674
+ // Ensure we get enough space to look ahead
2675
+ // There should be a way to move this out of the loop
2676
+ if(this.__needMoreData(pos, bufLen, end)){
2677
+ break;
2678
+ }
2679
+ if(this.state.wasRowDelimiter === true){
2680
+ this.info.lines++;
2681
+ this.state.wasRowDelimiter = false;
2682
+ }
2683
+ if(to_line !== -1 && this.info.lines > to_line){
2684
+ this.state.stop = true;
2685
+ close();
2686
+ return;
2687
+ }
2688
+ // Auto discovery of record_delimiter, unix, mac and windows supported
2689
+ if(this.state.quoting === false && record_delimiter.length === 0){
2690
+ const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
2691
+ if(record_delimiterCount){
2692
+ record_delimiter = this.options.record_delimiter;
2693
+ }
2694
+ }
2695
+ const chr = buf[pos];
2696
+ if(raw === true){
2697
+ rawBuffer.append(chr);
2698
+ }
2699
+ if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){
2700
+ this.state.wasRowDelimiter = true;
2701
+ }
2702
+ // Previous char was a valid escape char
2703
+ // treat the current char as a regular char
2704
+ if(this.state.escaping === true){
2705
+ this.state.escaping = false;
2706
+ }else {
2707
+ // Escape is only active inside quoted fields
2708
+ // We are quoting, the char is an escape chr and there is a chr to escape
2709
+ // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){
2710
+ if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){
2711
+ if(escapeIsQuote){
2712
+ if(this.__isQuote(buf, pos+escape.length)){
2713
+ this.state.escaping = true;
2714
+ pos += escape.length - 1;
2715
+ continue;
2716
+ }
2717
+ }else {
2718
+ this.state.escaping = true;
2719
+ pos += escape.length - 1;
2720
+ continue;
2721
+ }
2722
+ }
2723
+ // Not currently escaping and chr is a quote
2724
+ // TODO: need to compare bytes instead of single char
2725
+ if(this.state.commenting === false && this.__isQuote(buf, pos)){
2726
+ if(this.state.quoting === true){
2727
+ const nextChr = buf[pos+quote.length];
2728
+ const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length);
2729
+ const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr);
2730
+ const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr);
2731
+ const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length);
2732
+ // Escape a quote
2733
+ // Treat next char as a regular character
2734
+ if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){
2735
+ pos += escape.length - 1;
2736
+ }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){
2737
+ this.state.quoting = false;
2738
+ this.state.wasQuoting = true;
2739
+ pos += quote.length - 1;
2740
+ continue;
2741
+ }else if(relax_quotes === false){
2742
+ const err = this.__error(
2743
+ new CsvError('CSV_INVALID_CLOSING_QUOTE', [
2744
+ 'Invalid Closing Quote:',
2745
+ `got "${String.fromCharCode(nextChr)}"`,
2746
+ `at line ${this.info.lines}`,
2747
+ 'instead of delimiter, record delimiter, trimable character',
2748
+ '(if activated) or comment',
2749
+ ], this.options, this.__infoField())
2750
+ );
2751
+ if(err !== undefined) return err;
2752
+ }else {
2753
+ this.state.quoting = false;
2754
+ this.state.wasQuoting = true;
2755
+ this.state.field.prepend(quote);
2756
+ pos += quote.length - 1;
2757
+ }
2758
+ }else {
2759
+ if(this.state.field.length !== 0){
2760
+ // In relax_quotes mode, treat opening quote preceded by chrs as regular
2761
+ if(relax_quotes === false){
2762
+ const info = this.__infoField();
2763
+ const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
2764
+ const err = this.__error(
2765
+ new CsvError('INVALID_OPENING_QUOTE', [
2766
+ 'Invalid Opening Quote:',
2767
+ `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
2768
+ bom ? `(${bom} bom)` : undefined
2769
+ ], this.options, info, {
2770
+ field: this.state.field,
2771
+ })
2772
+ );
2773
+ if(err !== undefined) return err;
2774
+ }
2775
+ }else {
2776
+ this.state.quoting = true;
2777
+ pos += quote.length - 1;
2778
+ continue;
2779
+ }
2780
+ }
2781
+ }
2782
+ if(this.state.quoting === false){
2783
+ const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
2784
+ if(recordDelimiterLength !== 0){
2785
+ // Do not emit comments which take a full line
2786
+ const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
2787
+ if(skipCommentLine){
2788
+ this.info.comment_lines++;
2789
+ // Skip full comment line
2790
+ }else {
2791
+ // Activate records emition if above from_line
2792
+ if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){
2793
+ this.state.enabled = true;
2794
+ this.__resetField();
2795
+ this.__resetRecord();
2796
+ pos += recordDelimiterLength - 1;
2797
+ continue;
2798
+ }
2799
+ // Skip if line is empty and skip_empty_lines activated
2800
+ if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){
2801
+ this.info.empty_lines++;
2802
+ pos += recordDelimiterLength - 1;
2803
+ continue;
2804
+ }
2805
+ this.info.bytes = this.state.bufBytesStart + pos;
2806
+ const errField = this.__onField();
2807
+ if(errField !== undefined) return errField;
2808
+ this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
2809
+ const errRecord = this.__onRecord(push);
2810
+ if(errRecord !== undefined) return errRecord;
2811
+ if(to !== -1 && this.info.records >= to){
2812
+ this.state.stop = true;
2813
+ close();
2814
+ return;
2815
+ }
2816
+ }
2817
+ this.state.commenting = false;
2818
+ pos += recordDelimiterLength - 1;
2819
+ continue;
2820
+ }
2821
+ if(this.state.commenting){
2822
+ continue;
2823
+ }
2824
+ if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) {
2825
+ const commentCount = this.__compareBytes(comment, buf, pos, chr);
2826
+ if(commentCount !== 0){
2827
+ this.state.commenting = true;
2828
+ continue;
2829
+ }
2830
+ }
2831
+ const delimiterLength = this.__isDelimiter(buf, pos, chr);
2832
+ if(delimiterLength !== 0){
2833
+ this.info.bytes = this.state.bufBytesStart + pos;
2834
+ const errField = this.__onField();
2835
+ if(errField !== undefined) return errField;
2836
+ pos += delimiterLength - 1;
2837
+ continue;
2838
+ }
2839
+ }
2840
+ }
2841
+ if(this.state.commenting === false){
2842
+ if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){
2843
+ return this.__error(
2844
+ new CsvError('CSV_MAX_RECORD_SIZE', [
2845
+ 'Max Record Size:',
2846
+ 'record exceed the maximum number of tolerated bytes',
2847
+ `of ${max_record_size}`,
2848
+ `at line ${this.info.lines}`,
2849
+ ], this.options, this.__infoField())
2850
+ );
2851
+ }
2852
+ }
2853
+ const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
2854
+ // rtrim in non quoting is handle in __onField
2855
+ const rappend = rtrim === false || this.state.wasQuoting === false;
2856
+ if(lappend === true && rappend === true){
2857
+ this.state.field.append(chr);
2858
+ }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){
2859
+ return this.__error(
2860
+ new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [
2861
+ 'Invalid Closing Quote:',
2862
+ 'found non trimable byte after quote',
2863
+ `at line ${this.info.lines}`,
2864
+ ], this.options, this.__infoField())
2865
+ );
2866
+ }else {
2867
+ if(lappend === false){
2868
+ pos += this.__isCharTrimable(buf, pos) - 1;
2869
+ }
2870
+ continue;
2871
+ }
2872
+ }
2873
+ if(end === true){
2874
+ // Ensure we are not ending in a quoting state
2875
+ if(this.state.quoting === true){
2876
+ const err = this.__error(
2877
+ new CsvError('CSV_QUOTE_NOT_CLOSED', [
2878
+ 'Quote Not Closed:',
2879
+ `the parsing is finished with an opening quote at line ${this.info.lines}`,
2880
+ ], this.options, this.__infoField())
2881
+ );
2882
+ if(err !== undefined) return err;
2883
+ }else {
2884
+ // Skip last line if it has no characters
2885
+ if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){
2886
+ this.info.bytes = this.state.bufBytesStart + pos;
2887
+ const errField = this.__onField();
2888
+ if(errField !== undefined) return errField;
2889
+ const errRecord = this.__onRecord(push);
2890
+ if(errRecord !== undefined) return errRecord;
2891
+ }else if(this.state.wasRowDelimiter === true){
2892
+ this.info.empty_lines++;
2893
+ }else if(this.state.commenting === true){
2894
+ this.info.comment_lines++;
2895
+ }
2896
+ }
2897
+ }else {
2898
+ this.state.bufBytesStart += pos;
2899
+ this.state.previousBuf = buf.slice(pos);
2900
+ }
2901
+ if(this.state.wasRowDelimiter === true){
2902
+ this.info.lines++;
2903
+ this.state.wasRowDelimiter = false;
2904
+ }
2905
+ },
2906
+ __onRecord: function(push){
2907
+ 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;
2908
+ const {enabled, record} = this.state;
2909
+ if(enabled === false){
2910
+ return this.__resetRecord();
2911
+ }
2912
+ // Convert the first line into column names
2913
+ const recordLength = record.length;
2914
+ if(columns === true){
2915
+ if(skip_records_with_empty_values === true && isRecordEmpty(record)){
2916
+ this.__resetRecord();
2917
+ return;
2918
+ }
2919
+ return this.__firstLineToColumns(record);
2920
+ }
2921
+ if(columns === false && this.info.records === 0){
2922
+ this.state.expectedRecordLength = recordLength;
2923
+ }
2924
+ if(recordLength !== this.state.expectedRecordLength){
2925
+ const err = columns === false ?
2926
+ new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [
2927
+ 'Invalid Record Length:',
2928
+ `expect ${this.state.expectedRecordLength},`,
2929
+ `got ${recordLength} on line ${this.info.lines}`,
2930
+ ], this.options, this.__infoField(), {
2931
+ record: record,
2932
+ })
2933
+ :
2934
+ new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [
2935
+ 'Invalid Record Length:',
2936
+ `columns length is ${columns.length},`, // rename columns
2937
+ `got ${recordLength} on line ${this.info.lines}`,
2938
+ ], this.options, this.__infoField(), {
2939
+ record: record,
2940
+ });
2941
+ if(relax_column_count === true ||
2942
+ (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) ||
2943
+ (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){
2944
+ this.info.invalid_field_length++;
2945
+ this.state.error = err;
2946
+ // Error is undefined with skip_records_with_error
2947
+ }else {
2948
+ const finalErr = this.__error(err);
2949
+ if(finalErr) return finalErr;
2950
+ }
2951
+ }
2952
+ if(skip_records_with_empty_values === true && isRecordEmpty(record)){
2953
+ this.__resetRecord();
2954
+ return;
2955
+ }
2956
+ if(this.state.recordHasError === true){
2957
+ this.__resetRecord();
2958
+ this.state.recordHasError = false;
2959
+ return;
2960
+ }
2961
+ this.info.records++;
2962
+ if(from === 1 || this.info.records >= from){
2963
+ const {objname} = this.options;
2964
+ // With columns, records are object
2965
+ if(columns !== false){
2966
+ const obj = {};
2967
+ // Transform record array to an object
2968
+ for(let i = 0, l = record.length; i < l; i++){
2969
+ if(columns[i] === undefined || columns[i].disabled) continue;
2970
+ // Turn duplicate columns into an array
2971
+ if (group_columns_by_name === true && obj[columns[i].name] !== undefined) {
2972
+ if (Array.isArray(obj[columns[i].name])) {
2973
+ obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
2974
+ } else {
2975
+ obj[columns[i].name] = [obj[columns[i].name], record[i]];
2976
+ }
2977
+ } else {
2978
+ obj[columns[i].name] = record[i];
2979
+ }
2980
+ }
2981
+ // Without objname (default)
2982
+ if(raw === true || info === true){
2983
+ const extRecord = Object.assign(
2984
+ {record: obj},
2985
+ (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}),
2986
+ (info === true ? {info: this.__infoRecord()}: {})
2987
+ );
2988
+ const err = this.__push(
2989
+ objname === undefined ? extRecord : [obj[objname], extRecord]
2990
+ , push);
2991
+ if(err){
2992
+ return err;
2993
+ }
2994
+ }else {
2995
+ const err = this.__push(
2996
+ objname === undefined ? obj : [obj[objname], obj]
2997
+ , push);
2998
+ if(err){
2999
+ return err;
3000
+ }
3001
+ }
3002
+ // Without columns, records are array
3003
+ }else {
3004
+ if(raw === true || info === true){
3005
+ const extRecord = Object.assign(
3006
+ {record: record},
3007
+ raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {},
3008
+ info === true ? {info: this.__infoRecord()}: {}
3009
+ );
3010
+ const err = this.__push(
3011
+ objname === undefined ? extRecord : [record[objname], extRecord]
3012
+ , push);
3013
+ if(err){
3014
+ return err;
3015
+ }
3016
+ }else {
3017
+ const err = this.__push(
3018
+ objname === undefined ? record : [record[objname], record]
3019
+ , push);
3020
+ if(err){
3021
+ return err;
3022
+ }
3023
+ }
3024
+ }
3025
+ }
3026
+ this.__resetRecord();
3027
+ },
3028
+ __firstLineToColumns: function(record){
3029
+ const {firstLineToHeaders} = this.state;
3030
+ try{
3031
+ const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
3032
+ if(!Array.isArray(headers)){
3033
+ return this.__error(
3034
+ new CsvError('CSV_INVALID_COLUMN_MAPPING', [
3035
+ 'Invalid Column Mapping:',
3036
+ 'expect an array from column function,',
3037
+ `got ${JSON.stringify(headers)}`
3038
+ ], this.options, this.__infoField(), {
3039
+ headers: headers,
3040
+ })
3041
+ );
3042
+ }
3043
+ const normalizedHeaders = normalize_columns_array(headers);
3044
+ this.state.expectedRecordLength = normalizedHeaders.length;
3045
+ this.options.columns = normalizedHeaders;
3046
+ this.__resetRecord();
3047
+ return;
3048
+ }catch(err){
3049
+ return err;
3050
+ }
3051
+ },
3052
+ __resetRecord: function(){
3053
+ if(this.options.raw === true){
3054
+ this.state.rawBuffer.reset();
3055
+ }
3056
+ this.state.error = undefined;
3057
+ this.state.record = [];
3058
+ this.state.record_length = 0;
3059
+ },
3060
+ __onField: function(){
3061
+ const {cast, encoding, rtrim, max_record_size} = this.options;
3062
+ const {enabled, wasQuoting} = this.state;
3063
+ // Short circuit for the from_line options
3064
+ if(enabled === false){
3065
+ return this.__resetField();
3066
+ }
3067
+ let field = this.state.field.toString(encoding);
3068
+ if(rtrim === true && wasQuoting === false){
3069
+ field = field.trimRight();
3070
+ }
3071
+ if(cast === true){
3072
+ const [err, f] = this.__cast(field);
3073
+ if(err !== undefined) return err;
3074
+ field = f;
3075
+ }
3076
+ this.state.record.push(field);
3077
+ // Increment record length if record size must not exceed a limit
3078
+ if(max_record_size !== 0 && typeof field === 'string'){
3079
+ this.state.record_length += field.length;
3080
+ }
3081
+ this.__resetField();
3082
+ },
3083
+ __resetField: function(){
3084
+ this.state.field.reset();
3085
+ this.state.wasQuoting = false;
3086
+ },
3087
+ __push: function(record, push){
3088
+ const {on_record} = this.options;
3089
+ if(on_record !== undefined){
3090
+ const info = this.__infoRecord();
3091
+ try{
3092
+ record = on_record.call(null, record, info);
3093
+ }catch(err){
3094
+ return err;
3095
+ }
3096
+ if(record === undefined || record === null){ return; }
3097
+ }
3098
+ push(record);
3099
+ },
3100
+ // Return a tuple with the error and the casted value
3101
+ __cast: function(field){
3102
+ const {columns, relax_column_count} = this.options;
3103
+ const isColumns = Array.isArray(columns);
3104
+ // Dont loose time calling cast
3105
+ // because the final record is an object
3106
+ // and this field can't be associated to a key present in columns
3107
+ if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){
3108
+ return [undefined, undefined];
3109
+ }
3110
+ if(this.state.castField !== null){
3111
+ try{
3112
+ const info = this.__infoField();
3113
+ return [undefined, this.state.castField.call(null, field, info)];
3114
+ }catch(err){
3115
+ return [err];
3116
+ }
3117
+ }
3118
+ if(this.__isFloat(field)){
3119
+ return [undefined, parseFloat(field)];
3120
+ }else if(this.options.cast_date !== false){
3121
+ const info = this.__infoField();
3122
+ return [undefined, this.options.cast_date.call(null, field, info)];
3123
+ }
3124
+ return [undefined, field];
3125
+ },
3126
+ // Helper to test if a character is a space or a line delimiter
3127
+ __isCharTrimable: function(buf, pos){
3128
+ const isTrim = (buf, pos) => {
3129
+ const {timchars} = this.state;
3130
+ loop1: for(let i = 0; i < timchars.length; i++){
3131
+ const timchar = timchars[i];
3132
+ for(let j = 0; j < timchar.length; j++){
3133
+ if(timchar[j] !== buf[pos+j]) continue loop1;
3134
+ }
3135
+ return timchar.length;
3136
+ }
3137
+ return 0;
3138
+ };
3139
+ return isTrim(buf, pos);
3140
+ },
3141
+ // Keep it in case we implement the `cast_int` option
3142
+ // __isInt(value){
3143
+ // // return Number.isInteger(parseInt(value))
3144
+ // // return !isNaN( parseInt( obj ) );
3145
+ // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
3146
+ // }
3147
+ __isFloat: function(value){
3148
+ return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery
3149
+ },
3150
+ __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){
3151
+ if(sourceBuf[0] !== firstByte) return 0;
3152
+ const sourceLength = sourceBuf.length;
3153
+ for(let i = 1; i < sourceLength; i++){
3154
+ if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0;
3155
+ }
3156
+ return sourceLength;
3157
+ },
3158
+ __isDelimiter: function(buf, pos, chr){
3159
+ const {delimiter, ignore_last_delimiters} = this.options;
3160
+ if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){
3161
+ return 0;
3162
+ }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){
3163
+ return 0;
3164
+ }
3165
+ loop1: for(let i = 0; i < delimiter.length; i++){
3166
+ const del = delimiter[i];
3167
+ if(del[0] === chr){
3168
+ for(let j = 1; j < del.length; j++){
3169
+ if(del[j] !== buf[pos+j]) continue loop1;
3170
+ }
3171
+ return del.length;
3172
+ }
3173
+ }
3174
+ return 0;
3175
+ },
3176
+ __isRecordDelimiter: function(chr, buf, pos){
3177
+ const {record_delimiter} = this.options;
3178
+ const recordDelimiterLength = record_delimiter.length;
3179
+ loop1: for(let i = 0; i < recordDelimiterLength; i++){
3180
+ const rd = record_delimiter[i];
3181
+ const rdLength = rd.length;
3182
+ if(rd[0] !== chr){
3183
+ continue;
3184
+ }
3185
+ for(let j = 1; j < rdLength; j++){
3186
+ if(rd[j] !== buf[pos+j]){
3187
+ continue loop1;
3188
+ }
3189
+ }
3190
+ return rd.length;
3191
+ }
3192
+ return 0;
3193
+ },
3194
+ __isEscape: function(buf, pos, chr){
3195
+ const {escape} = this.options;
3196
+ if(escape === null) return false;
3197
+ const l = escape.length;
3198
+ if(escape[0] === chr){
3199
+ for(let i = 0; i < l; i++){
3200
+ if(escape[i] !== buf[pos+i]){
3201
+ return false;
3202
+ }
3203
+ }
3204
+ return true;
3205
+ }
3206
+ return false;
3207
+ },
3208
+ __isQuote: function(buf, pos){
3209
+ const {quote} = this.options;
3210
+ if(quote === null) return false;
3211
+ const l = quote.length;
3212
+ for(let i = 0; i < l; i++){
3213
+ if(quote[i] !== buf[pos+i]){
3214
+ return false;
3215
+ }
3216
+ }
3217
+ return true;
3218
+ },
3219
+ __autoDiscoverRecordDelimiter: function(buf, pos){
3220
+ const { encoding } = this.options;
3221
+ // Note, we don't need to cache this information in state,
3222
+ // It is only called on the first line until we find out a suitable
3223
+ // record delimiter.
3224
+ const rds = [
3225
+ // Important, the windows line ending must be before mac os 9
3226
+ Buffer.from('\r\n', encoding),
3227
+ Buffer.from('\n', encoding),
3228
+ Buffer.from('\r', encoding),
3229
+ ];
3230
+ loop: for(let i = 0; i < rds.length; i++){
3231
+ const l = rds[i].length;
3232
+ for(let j = 0; j < l; j++){
3233
+ if(rds[i][j] !== buf[pos + j]){
3234
+ continue loop;
3235
+ }
3236
+ }
3237
+ this.options.record_delimiter.push(rds[i]);
3238
+ this.state.recordDelimiterMaxLength = rds[i].length;
3239
+ return rds[i].length;
3240
+ }
3241
+ return 0;
3242
+ },
3243
+ __error: function(msg){
3244
+ const {encoding, raw, skip_records_with_error} = this.options;
3245
+ const err = typeof msg === 'string' ? new Error(msg) : msg;
3246
+ if(skip_records_with_error){
3247
+ this.state.recordHasError = true;
3248
+ if(this.options.on_skip !== undefined){
3249
+ this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
3250
+ }
3251
+ // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
3252
+ return undefined;
3253
+ }else {
3254
+ return err;
3255
+ }
3256
+ },
3257
+ __infoDataSet: function(){
3258
+ return {
3259
+ ...this.info,
3260
+ columns: this.options.columns
3261
+ };
3262
+ },
3263
+ __infoRecord: function(){
3264
+ const {columns, raw, encoding} = this.options;
3265
+ return {
3266
+ ...this.__infoDataSet(),
3267
+ error: this.state.error,
3268
+ header: columns === true,
3269
+ index: this.state.record.length,
3270
+ raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
3271
+ };
3272
+ },
3273
+ __infoField: function(){
3274
+ const {columns} = this.options;
3275
+ const isColumns = Array.isArray(columns);
3276
+ return {
3277
+ ...this.__infoRecord(),
3278
+ column: isColumns === true ?
3279
+ (columns.length > this.state.record.length ?
3280
+ columns[this.state.record.length].name :
3281
+ null
3282
+ ) :
3283
+ this.state.record.length,
3284
+ quoting: this.state.wasQuoting,
3285
+ };
3286
+ }
3287
+ };
3288
+ };
3289
+
3290
+ const parse = function(data, opts={}){
3291
+ if(typeof data === 'string'){
3292
+ data = Buffer.from(data);
3293
+ }
3294
+ const records = opts && opts.objname ? {} : [];
3295
+ const parser = transform(opts);
3296
+ const push = (record) => {
3297
+ if(parser.options.objname === undefined)
3298
+ records.push(record);
3299
+ else {
3300
+ records[record[0]] = record[1];
3301
+ }
3302
+ };
3303
+ const close = () => {};
3304
+ const err1 = parser.parse(data, false, push, close);
3305
+ if(err1 !== undefined) throw err1;
3306
+ const err2 = parser.parse(undefined, true, push, close);
3307
+ if(err2 !== undefined) throw err2;
3308
+ return records;
3309
+ };
3310
+
3311
+ exports.CsvError = CsvError;
3312
+ exports.parse = parse;
3313
+
3314
+ }));