@contrail/cli 3.4.4-alpha.7adb62a → 3.4.4-alpha.9fbce6b

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