@leofcoin/workers 1.3.8 → 1.3.10

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 (51) hide show
  1. package/package.json +5 -3
  2. package/src/block-worker.js +1 -10
  3. package/src/machine-worker.js +21 -18
  4. package/src/pool-worker.js +0 -9
  5. package/src/transaction-worker.js +1 -9
  6. package/dist/bundle/commonjs/block-worker-21ad8152.js +0 -45
  7. package/dist/bundle/commonjs/block-worker.js +0 -14
  8. package/dist/bundle/commonjs/machine-worker-70f71351.js +0 -255
  9. package/dist/bundle/commonjs/machine-worker.js +0 -14
  10. package/dist/bundle/commonjs/pool-worker-f450eeff.js +0 -35
  11. package/dist/bundle/commonjs/pool-worker.js +0 -14
  12. package/dist/bundle/commonjs/transaction-d7c6a8ee.js +0 -33
  13. package/dist/bundle/commonjs/transaction-worker-176a5aaa.js +0 -27
  14. package/dist/bundle/commonjs/transaction-worker.js +0 -14
  15. package/dist/bundle/commonjs/utils-6e881be4.js +0 -4139
  16. package/dist/bundle/commonjs/worker-6ace445f.js +0 -4891
  17. package/dist/bundle/commonjs/workers.js +0 -29
  18. package/dist/bundle/module/block-worker-414860e0.js +0 -43
  19. package/dist/bundle/module/block-worker.js +0 -11
  20. package/dist/bundle/module/machine-worker-5896ac08.js +0 -253
  21. package/dist/bundle/module/machine-worker.js +0 -11
  22. package/dist/bundle/module/pool-worker-0d927e3c.js +0 -33
  23. package/dist/bundle/module/pool-worker.js +0 -11
  24. package/dist/bundle/module/transaction-cec98ce8.js +0 -31
  25. package/dist/bundle/module/transaction-worker-548cd200.js +0 -25
  26. package/dist/bundle/module/transaction-worker.js +0 -11
  27. package/dist/bundle/module/utils-ac8c68e6.js +0 -4135
  28. package/dist/bundle/module/worker-def77c26.js +0 -4858
  29. package/dist/bundle/module/workers.js +0 -22
  30. package/dist/commonjs/block-worker-60e4cfa3.js +0 -50
  31. package/dist/commonjs/block-worker.js +0 -11
  32. package/dist/commonjs/machine-worker-b46cac38.js +0 -260
  33. package/dist/commonjs/machine-worker.js +0 -11
  34. package/dist/commonjs/pool-worker-81e8b4c0.js +0 -40
  35. package/dist/commonjs/pool-worker.js +0 -7
  36. package/dist/commonjs/transaction-220a3a15.js +0 -33
  37. package/dist/commonjs/transaction-worker-8eecc7a1.js +0 -32
  38. package/dist/commonjs/transaction-worker.js +0 -7
  39. package/dist/commonjs/utils-1dc37f72.js +0 -352
  40. package/dist/commonjs/workers.js +0 -26
  41. package/dist/module/block-worker-f539b1b2.js +0 -44
  42. package/dist/module/block-worker.js +0 -8
  43. package/dist/module/machine-worker-da95e492.js +0 -254
  44. package/dist/module/machine-worker.js +0 -8
  45. package/dist/module/pool-worker-f65671d7.js +0 -34
  46. package/dist/module/pool-worker.js +0 -4
  47. package/dist/module/transaction-d06dc6c4.js +0 -31
  48. package/dist/module/transaction-worker-105deaa8.js +0 -26
  49. package/dist/module/transaction-worker.js +0 -4
  50. package/dist/module/utils-e87bc63d.js +0 -344
  51. package/dist/module/workers.js +0 -19
@@ -1,4858 +0,0 @@
1
- import require$$0$1 from 'stream';
2
- import require$$0$2 from 'events';
3
- import require$$2$1 from 'buffer';
4
- import require$$1$1 from 'util';
5
- import require$$10 from 'string_decoder/';
6
- import require$$0$3 from 'fs';
7
- import require$$1$2 from 'path';
8
- import require$$2$2 from 'os';
9
-
10
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
11
-
12
- function getAugmentedNamespace(n) {
13
- var f = n.default;
14
- if (typeof f == "function") {
15
- var a = function () {
16
- return f.apply(this, arguments);
17
- };
18
- a.prototype = f.prototype;
19
- } else a = {};
20
- Object.defineProperty(a, '__esModule', {value: true});
21
- Object.keys(n).forEach(function (k) {
22
- var d = Object.getOwnPropertyDescriptor(n, k);
23
- Object.defineProperty(a, k, d.get ? d : {
24
- enumerable: true,
25
- get: function () {
26
- return n[k];
27
- }
28
- });
29
- });
30
- return a;
31
- }
32
-
33
- var dist = {};
34
-
35
- // base-x encoding / decoding
36
- // Copyright (c) 2018 base-x contributors
37
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
38
- // Distributed under the MIT software license, see the accompanying
39
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
40
- const base = ALPHABET => {
41
- if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
42
- const BASE_MAP = new Uint8Array(256);
43
- for (let j = 0; j < BASE_MAP.length; j++) {
44
- BASE_MAP[j] = 255;
45
- }
46
- for (let i = 0; i < ALPHABET.length; i++) {
47
- const x = ALPHABET.charAt(i);
48
- const xc = x.charCodeAt(0);
49
- if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
50
- BASE_MAP[xc] = i;
51
- }
52
- const BASE = ALPHABET.length;
53
- const LEADER = ALPHABET.charAt(0);
54
- const FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
55
- const iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
56
-
57
- const encode = source => {
58
- if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
59
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
60
- } else if (Array.isArray(source)) {
61
- source = Uint8Array.from(source);
62
- }
63
- if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
64
- if (source.length === 0) { return '' }
65
- // Skip & count leading zeroes.
66
- let zeroes = 0;
67
- let length = 0;
68
- let pbegin = 0;
69
- const pend = source.length;
70
- while (pbegin !== pend && source[pbegin] === 0) {
71
- pbegin++;
72
- zeroes++;
73
- }
74
- // Allocate enough space in big-endian base58 representation.
75
- const size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
76
- const b58 = new Uint8Array(size);
77
- // Process the bytes.
78
- while (pbegin !== pend) {
79
- let carry = source[pbegin];
80
- // Apply "b58 = b58 * 256 + ch".
81
- let i = 0;
82
- for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
83
- carry += (256 * b58[it1]) >>> 0;
84
- b58[it1] = (carry % BASE) >>> 0;
85
- carry = (carry / BASE) >>> 0;
86
- }
87
- if (carry !== 0) { throw new Error('Non-zero carry') }
88
- length = i;
89
- pbegin++;
90
- }
91
- // Skip leading zeroes in base58 result.
92
- let it2 = size - length;
93
- while (it2 !== size && b58[it2] === 0) {
94
- it2++;
95
- }
96
- // Translate the result into a string.
97
- let str = LEADER.repeat(zeroes);
98
- for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
99
- return str
100
- };
101
- const decodeUnsafe = source => {
102
- if (typeof source !== 'string') { throw new TypeError('Expected String') }
103
- if (source.length === 0) { return new Uint8Array() }
104
- let psz = 0;
105
- // Skip and count leading '1's.
106
- let zeroes = 0;
107
- let length = 0;
108
- while (source[psz] === LEADER) {
109
- zeroes++;
110
- psz++;
111
- }
112
- // Allocate enough space in big-endian base256 representation.
113
- const size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
114
- let b256 = new Uint8Array(size);
115
- // Process the characters.
116
- while (source[psz]) {
117
- // Decode character
118
- let carry = BASE_MAP[source.charCodeAt(psz)];
119
- // Invalid character
120
- if (carry === 255) { return }
121
- let i = 0;
122
- for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
123
- carry += (BASE * b256[it3]) >>> 0;
124
- b256[it3] = (carry % 256) >>> 0;
125
- carry = (carry / 256) >>> 0;
126
- }
127
- if (carry !== 0) { throw new Error('Non-zero carry') }
128
- length = i;
129
- psz++;
130
- }
131
- // Skip leading zeroes in b256.
132
- let it4 = size - length;
133
- while (it4 !== size && b256[it4] === 0) {
134
- it4++;
135
- }
136
- let vch = new Uint8Array(zeroes + (size - it4));
137
- let j = zeroes;
138
- while (it4 !== size) {
139
- vch[j++] = b256[it4++];
140
- }
141
- return vch
142
- };
143
- const decode = string => {
144
- const buffer = decodeUnsafe(string);
145
- if (buffer) { return buffer }
146
- throw new Error('Non-base' + BASE + ' character')
147
- };
148
- return {
149
- encode: encode,
150
- decodeUnsafe: decodeUnsafe,
151
- decode: decode
152
- }
153
- };
154
-
155
- const base32 = 'abcdefghijklmnopqrstuvwxyz234567';
156
- const base32Hex = '0123456789abcdefghijklmnopqrstuv';
157
-
158
- const decode$2 = (uint8Array, hex = false) => {
159
- const decoder = hex ? base(base32Hex) : base(base32);
160
- return decoder.decode(uint8Array)
161
- };
162
-
163
- var base32$1 = {
164
- encode: (uint8Array, hex = false) => {
165
- const encoder = hex ? base(base32Hex) : base(base32);
166
- return encoder.encode(uint8Array)
167
- },
168
- decode: decode$2,
169
- isBase32: (uint8Array, hex = false) => {
170
- try {
171
- decode$2(uint8Array, hex);
172
- return true;
173
- } catch (e) {
174
- return false;
175
- }
176
- }
177
- };
178
-
179
- var base32$2 = /*#__PURE__*/Object.freeze({
180
- __proto__: null,
181
- 'default': base32$1
182
- });
183
-
184
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(base32$2);
185
-
186
- const base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
187
-
188
- const decode$1 = uint8Array => base(base58).decode(uint8Array);
189
-
190
- var base58$1 = {
191
- encode: uint8Array => base(base58).encode(uint8Array),
192
- decode: decode$1,
193
- isBase58: uint8Array => {
194
- try {
195
- decode$1(uint8Array);
196
- return true
197
- } catch (e) {
198
- return false
199
- }
200
- }
201
- };
202
-
203
- var base58$2 = /*#__PURE__*/Object.freeze({
204
- __proto__: null,
205
- 'default': base58$1
206
- });
207
-
208
- var require$$1 = /*@__PURE__*/getAugmentedNamespace(base58$2);
209
-
210
- var isHex$1 = string => /^[A-F0-9]+$/i.test(string);
211
-
212
- var isHex$2 = /*#__PURE__*/Object.freeze({
213
- __proto__: null,
214
- 'default': isHex$1
215
- });
216
-
217
- var require$$2 = /*@__PURE__*/getAugmentedNamespace(isHex$2);
218
-
219
- var encode_1 = encode;
220
-
221
- var MSB$1 = 0x80
222
- , REST$1 = 0x7F
223
- , MSBALL = ~REST$1
224
- , INT = Math.pow(2, 31);
225
-
226
- function encode(num, out, offset) {
227
- if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
228
- encode.bytes = 0;
229
- throw new RangeError('Could not encode varint')
230
- }
231
- out = out || [];
232
- offset = offset || 0;
233
- var oldOffset = offset;
234
-
235
- while(num >= INT) {
236
- out[offset++] = (num & 0xFF) | MSB$1;
237
- num /= 128;
238
- }
239
- while(num & MSBALL) {
240
- out[offset++] = (num & 0xFF) | MSB$1;
241
- num >>>= 7;
242
- }
243
- out[offset] = num | 0;
244
-
245
- encode.bytes = offset - oldOffset + 1;
246
-
247
- return out
248
- }
249
-
250
- var decode = read;
251
-
252
- var MSB = 0x80
253
- , REST = 0x7F;
254
-
255
- function read(buf, offset) {
256
- var res = 0
257
- , offset = offset || 0
258
- , shift = 0
259
- , counter = offset
260
- , b
261
- , l = buf.length;
262
-
263
- do {
264
- if (counter >= l || shift > 49) {
265
- read.bytes = 0;
266
- throw new RangeError('Could not decode varint')
267
- }
268
- b = buf[counter++];
269
- res += shift < 28
270
- ? (b & REST) << shift
271
- : (b & REST) * Math.pow(2, shift);
272
- shift += 7;
273
- } while (b >= MSB)
274
-
275
- read.bytes = counter - offset;
276
-
277
- return res
278
- }
279
-
280
- var N1 = Math.pow(2, 7);
281
- var N2 = Math.pow(2, 14);
282
- var N3 = Math.pow(2, 21);
283
- var N4 = Math.pow(2, 28);
284
- var N5 = Math.pow(2, 35);
285
- var N6 = Math.pow(2, 42);
286
- var N7 = Math.pow(2, 49);
287
- var N8 = Math.pow(2, 56);
288
- var N9 = Math.pow(2, 63);
289
-
290
- var length = function (value) {
291
- return (
292
- value < N1 ? 1
293
- : value < N2 ? 2
294
- : value < N3 ? 3
295
- : value < N4 ? 4
296
- : value < N5 ? 5
297
- : value < N6 ? 6
298
- : value < N7 ? 7
299
- : value < N8 ? 8
300
- : value < N9 ? 9
301
- : 10
302
- )
303
- };
304
-
305
- var varint$1 = {
306
- encode: encode_1
307
- , decode: decode
308
- , encodingLength: length
309
- };
310
-
311
- var keccak$2 = {exports: {}};
312
-
313
- var readable = {exports: {}};
314
-
315
- var stream = {exports: {}};
316
-
317
- var hasRequiredStream;
318
-
319
- function requireStream () {
320
- if (hasRequiredStream) return stream.exports;
321
- hasRequiredStream = 1;
322
- (function (module) {
323
- module.exports = require$$0$1;
324
- } (stream));
325
- return stream.exports;
326
- }
327
-
328
- var buffer_list;
329
- var hasRequiredBuffer_list;
330
-
331
- function requireBuffer_list () {
332
- if (hasRequiredBuffer_list) return buffer_list;
333
- hasRequiredBuffer_list = 1;
334
-
335
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
336
-
337
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
338
-
339
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
340
-
341
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
342
-
343
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
344
-
345
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
346
-
347
- var _require = require$$2$1,
348
- Buffer = _require.Buffer;
349
-
350
- var _require2 = require$$1$1,
351
- inspect = _require2.inspect;
352
-
353
- var custom = inspect && inspect.custom || 'inspect';
354
-
355
- function copyBuffer(src, target, offset) {
356
- Buffer.prototype.copy.call(src, target, offset);
357
- }
358
-
359
- buffer_list =
360
- /*#__PURE__*/
361
- function () {
362
- function BufferList() {
363
- _classCallCheck(this, BufferList);
364
-
365
- this.head = null;
366
- this.tail = null;
367
- this.length = 0;
368
- }
369
-
370
- _createClass(BufferList, [{
371
- key: "push",
372
- value: function push(v) {
373
- var entry = {
374
- data: v,
375
- next: null
376
- };
377
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
378
- this.tail = entry;
379
- ++this.length;
380
- }
381
- }, {
382
- key: "unshift",
383
- value: function unshift(v) {
384
- var entry = {
385
- data: v,
386
- next: this.head
387
- };
388
- if (this.length === 0) this.tail = entry;
389
- this.head = entry;
390
- ++this.length;
391
- }
392
- }, {
393
- key: "shift",
394
- value: function shift() {
395
- if (this.length === 0) return;
396
- var ret = this.head.data;
397
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
398
- --this.length;
399
- return ret;
400
- }
401
- }, {
402
- key: "clear",
403
- value: function clear() {
404
- this.head = this.tail = null;
405
- this.length = 0;
406
- }
407
- }, {
408
- key: "join",
409
- value: function join(s) {
410
- if (this.length === 0) return '';
411
- var p = this.head;
412
- var ret = '' + p.data;
413
-
414
- while (p = p.next) {
415
- ret += s + p.data;
416
- }
417
-
418
- return ret;
419
- }
420
- }, {
421
- key: "concat",
422
- value: function concat(n) {
423
- if (this.length === 0) return Buffer.alloc(0);
424
- var ret = Buffer.allocUnsafe(n >>> 0);
425
- var p = this.head;
426
- var i = 0;
427
-
428
- while (p) {
429
- copyBuffer(p.data, ret, i);
430
- i += p.data.length;
431
- p = p.next;
432
- }
433
-
434
- return ret;
435
- } // Consumes a specified amount of bytes or characters from the buffered data.
436
-
437
- }, {
438
- key: "consume",
439
- value: function consume(n, hasStrings) {
440
- var ret;
441
-
442
- if (n < this.head.data.length) {
443
- // `slice` is the same for buffers and strings.
444
- ret = this.head.data.slice(0, n);
445
- this.head.data = this.head.data.slice(n);
446
- } else if (n === this.head.data.length) {
447
- // First chunk is a perfect match.
448
- ret = this.shift();
449
- } else {
450
- // Result spans more than one buffer.
451
- ret = hasStrings ? this._getString(n) : this._getBuffer(n);
452
- }
453
-
454
- return ret;
455
- }
456
- }, {
457
- key: "first",
458
- value: function first() {
459
- return this.head.data;
460
- } // Consumes a specified amount of characters from the buffered data.
461
-
462
- }, {
463
- key: "_getString",
464
- value: function _getString(n) {
465
- var p = this.head;
466
- var c = 1;
467
- var ret = p.data;
468
- n -= ret.length;
469
-
470
- while (p = p.next) {
471
- var str = p.data;
472
- var nb = n > str.length ? str.length : n;
473
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
474
- n -= nb;
475
-
476
- if (n === 0) {
477
- if (nb === str.length) {
478
- ++c;
479
- if (p.next) this.head = p.next;else this.head = this.tail = null;
480
- } else {
481
- this.head = p;
482
- p.data = str.slice(nb);
483
- }
484
-
485
- break;
486
- }
487
-
488
- ++c;
489
- }
490
-
491
- this.length -= c;
492
- return ret;
493
- } // Consumes a specified amount of bytes from the buffered data.
494
-
495
- }, {
496
- key: "_getBuffer",
497
- value: function _getBuffer(n) {
498
- var ret = Buffer.allocUnsafe(n);
499
- var p = this.head;
500
- var c = 1;
501
- p.data.copy(ret);
502
- n -= p.data.length;
503
-
504
- while (p = p.next) {
505
- var buf = p.data;
506
- var nb = n > buf.length ? buf.length : n;
507
- buf.copy(ret, ret.length - n, 0, nb);
508
- n -= nb;
509
-
510
- if (n === 0) {
511
- if (nb === buf.length) {
512
- ++c;
513
- if (p.next) this.head = p.next;else this.head = this.tail = null;
514
- } else {
515
- this.head = p;
516
- p.data = buf.slice(nb);
517
- }
518
-
519
- break;
520
- }
521
-
522
- ++c;
523
- }
524
-
525
- this.length -= c;
526
- return ret;
527
- } // Make sure the linked list only shows the minimal necessary information.
528
-
529
- }, {
530
- key: custom,
531
- value: function value(_, options) {
532
- return inspect(this, _objectSpread({}, options, {
533
- // Only inspect one level.
534
- depth: 0,
535
- // It should not recurse.
536
- customInspect: false
537
- }));
538
- }
539
- }]);
540
-
541
- return BufferList;
542
- }();
543
- return buffer_list;
544
- }
545
-
546
- var destroy_1;
547
- var hasRequiredDestroy;
548
-
549
- function requireDestroy () {
550
- if (hasRequiredDestroy) return destroy_1;
551
- hasRequiredDestroy = 1;
552
-
553
- function destroy(err, cb) {
554
- var _this = this;
555
-
556
- var readableDestroyed = this._readableState && this._readableState.destroyed;
557
- var writableDestroyed = this._writableState && this._writableState.destroyed;
558
-
559
- if (readableDestroyed || writableDestroyed) {
560
- if (cb) {
561
- cb(err);
562
- } else if (err) {
563
- if (!this._writableState) {
564
- process.nextTick(emitErrorNT, this, err);
565
- } else if (!this._writableState.errorEmitted) {
566
- this._writableState.errorEmitted = true;
567
- process.nextTick(emitErrorNT, this, err);
568
- }
569
- }
570
-
571
- return this;
572
- } // we set destroyed to true before firing error callbacks in order
573
- // to make it re-entrance safe in case destroy() is called within callbacks
574
-
575
-
576
- if (this._readableState) {
577
- this._readableState.destroyed = true;
578
- } // if this is a duplex stream mark the writable part as destroyed as well
579
-
580
-
581
- if (this._writableState) {
582
- this._writableState.destroyed = true;
583
- }
584
-
585
- this._destroy(err || null, function (err) {
586
- if (!cb && err) {
587
- if (!_this._writableState) {
588
- process.nextTick(emitErrorAndCloseNT, _this, err);
589
- } else if (!_this._writableState.errorEmitted) {
590
- _this._writableState.errorEmitted = true;
591
- process.nextTick(emitErrorAndCloseNT, _this, err);
592
- } else {
593
- process.nextTick(emitCloseNT, _this);
594
- }
595
- } else if (cb) {
596
- process.nextTick(emitCloseNT, _this);
597
- cb(err);
598
- } else {
599
- process.nextTick(emitCloseNT, _this);
600
- }
601
- });
602
-
603
- return this;
604
- }
605
-
606
- function emitErrorAndCloseNT(self, err) {
607
- emitErrorNT(self, err);
608
- emitCloseNT(self);
609
- }
610
-
611
- function emitCloseNT(self) {
612
- if (self._writableState && !self._writableState.emitClose) return;
613
- if (self._readableState && !self._readableState.emitClose) return;
614
- self.emit('close');
615
- }
616
-
617
- function undestroy() {
618
- if (this._readableState) {
619
- this._readableState.destroyed = false;
620
- this._readableState.reading = false;
621
- this._readableState.ended = false;
622
- this._readableState.endEmitted = false;
623
- }
624
-
625
- if (this._writableState) {
626
- this._writableState.destroyed = false;
627
- this._writableState.ended = false;
628
- this._writableState.ending = false;
629
- this._writableState.finalCalled = false;
630
- this._writableState.prefinished = false;
631
- this._writableState.finished = false;
632
- this._writableState.errorEmitted = false;
633
- }
634
- }
635
-
636
- function emitErrorNT(self, err) {
637
- self.emit('error', err);
638
- }
639
-
640
- function errorOrDestroy(stream, err) {
641
- // We have tests that rely on errors being emitted
642
- // in the same tick, so changing this is semver major.
643
- // For now when you opt-in to autoDestroy we allow
644
- // the error to be emitted nextTick. In a future
645
- // semver major update we should change the default to this.
646
- var rState = stream._readableState;
647
- var wState = stream._writableState;
648
- if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
649
- }
650
-
651
- destroy_1 = {
652
- destroy: destroy,
653
- undestroy: undestroy,
654
- errorOrDestroy: errorOrDestroy
655
- };
656
- return destroy_1;
657
- }
658
-
659
- var errors = {};
660
-
661
- var hasRequiredErrors;
662
-
663
- function requireErrors () {
664
- if (hasRequiredErrors) return errors;
665
- hasRequiredErrors = 1;
666
-
667
- const codes = {};
668
-
669
- function createErrorType(code, message, Base) {
670
- if (!Base) {
671
- Base = Error;
672
- }
673
-
674
- function getMessage (arg1, arg2, arg3) {
675
- if (typeof message === 'string') {
676
- return message
677
- } else {
678
- return message(arg1, arg2, arg3)
679
- }
680
- }
681
-
682
- class NodeError extends Base {
683
- constructor (arg1, arg2, arg3) {
684
- super(getMessage(arg1, arg2, arg3));
685
- }
686
- }
687
-
688
- NodeError.prototype.name = Base.name;
689
- NodeError.prototype.code = code;
690
-
691
- codes[code] = NodeError;
692
- }
693
-
694
- // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
695
- function oneOf(expected, thing) {
696
- if (Array.isArray(expected)) {
697
- const len = expected.length;
698
- expected = expected.map((i) => String(i));
699
- if (len > 2) {
700
- return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
701
- expected[len - 1];
702
- } else if (len === 2) {
703
- return `one of ${thing} ${expected[0]} or ${expected[1]}`;
704
- } else {
705
- return `of ${thing} ${expected[0]}`;
706
- }
707
- } else {
708
- return `of ${thing} ${String(expected)}`;
709
- }
710
- }
711
-
712
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
713
- function startsWith(str, search, pos) {
714
- return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
715
- }
716
-
717
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
718
- function endsWith(str, search, this_len) {
719
- if (this_len === undefined || this_len > str.length) {
720
- this_len = str.length;
721
- }
722
- return str.substring(this_len - search.length, this_len) === search;
723
- }
724
-
725
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
726
- function includes(str, search, start) {
727
- if (typeof start !== 'number') {
728
- start = 0;
729
- }
730
-
731
- if (start + search.length > str.length) {
732
- return false;
733
- } else {
734
- return str.indexOf(search, start) !== -1;
735
- }
736
- }
737
-
738
- createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
739
- return 'The value "' + value + '" is invalid for option "' + name + '"'
740
- }, TypeError);
741
- createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
742
- // determiner: 'must be' or 'must not be'
743
- let determiner;
744
- if (typeof expected === 'string' && startsWith(expected, 'not ')) {
745
- determiner = 'must not be';
746
- expected = expected.replace(/^not /, '');
747
- } else {
748
- determiner = 'must be';
749
- }
750
-
751
- let msg;
752
- if (endsWith(name, ' argument')) {
753
- // For cases like 'first argument'
754
- msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
755
- } else {
756
- const type = includes(name, '.') ? 'property' : 'argument';
757
- msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
758
- }
759
-
760
- msg += `. Received type ${typeof actual}`;
761
- return msg;
762
- }, TypeError);
763
- createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
764
- createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
765
- return 'The ' + name + ' method is not implemented'
766
- });
767
- createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
768
- createErrorType('ERR_STREAM_DESTROYED', function (name) {
769
- return 'Cannot call ' + name + ' after a stream was destroyed';
770
- });
771
- createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
772
- createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
773
- createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
774
- createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
775
- createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
776
- return 'Unknown encoding: ' + arg
777
- }, TypeError);
778
- createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
779
-
780
- errors.codes = codes;
781
- return errors;
782
- }
783
-
784
- var state;
785
- var hasRequiredState;
786
-
787
- function requireState () {
788
- if (hasRequiredState) return state;
789
- hasRequiredState = 1;
790
-
791
- var ERR_INVALID_OPT_VALUE = requireErrors().codes.ERR_INVALID_OPT_VALUE;
792
-
793
- function highWaterMarkFrom(options, isDuplex, duplexKey) {
794
- return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
795
- }
796
-
797
- function getHighWaterMark(state, options, duplexKey, isDuplex) {
798
- var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
799
-
800
- if (hwm != null) {
801
- if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
802
- var name = isDuplex ? duplexKey : 'highWaterMark';
803
- throw new ERR_INVALID_OPT_VALUE(name, hwm);
804
- }
805
-
806
- return Math.floor(hwm);
807
- } // Default value
808
-
809
-
810
- return state.objectMode ? 16 : 16 * 1024;
811
- }
812
-
813
- state = {
814
- getHighWaterMark: getHighWaterMark
815
- };
816
- return state;
817
- }
818
-
819
- var inherits = {exports: {}};
820
-
821
- var inherits_browser = {exports: {}};
822
-
823
- var hasRequiredInherits_browser;
824
-
825
- function requireInherits_browser () {
826
- if (hasRequiredInherits_browser) return inherits_browser.exports;
827
- hasRequiredInherits_browser = 1;
828
- if (typeof Object.create === 'function') {
829
- // implementation from standard node.js 'util' module
830
- inherits_browser.exports = function inherits(ctor, superCtor) {
831
- if (superCtor) {
832
- ctor.super_ = superCtor;
833
- ctor.prototype = Object.create(superCtor.prototype, {
834
- constructor: {
835
- value: ctor,
836
- enumerable: false,
837
- writable: true,
838
- configurable: true
839
- }
840
- });
841
- }
842
- };
843
- } else {
844
- // old school shim for old browsers
845
- inherits_browser.exports = function inherits(ctor, superCtor) {
846
- if (superCtor) {
847
- ctor.super_ = superCtor;
848
- var TempCtor = function () {};
849
- TempCtor.prototype = superCtor.prototype;
850
- ctor.prototype = new TempCtor();
851
- ctor.prototype.constructor = ctor;
852
- }
853
- };
854
- }
855
- return inherits_browser.exports;
856
- }
857
-
858
- var hasRequiredInherits;
859
-
860
- function requireInherits () {
861
- if (hasRequiredInherits) return inherits.exports;
862
- hasRequiredInherits = 1;
863
- (function (module) {
864
- try {
865
- var util = require('util');
866
- /* istanbul ignore next */
867
- if (typeof util.inherits !== 'function') throw '';
868
- module.exports = util.inherits;
869
- } catch (e) {
870
- /* istanbul ignore next */
871
- module.exports = requireInherits_browser();
872
- }
873
- } (inherits));
874
- return inherits.exports;
875
- }
876
-
877
- var node;
878
- var hasRequiredNode;
879
-
880
- function requireNode () {
881
- if (hasRequiredNode) return node;
882
- hasRequiredNode = 1;
883
- /**
884
- * For Node.js, simply re-export the core `util.deprecate` function.
885
- */
886
-
887
- node = require$$1$1.deprecate;
888
- return node;
889
- }
890
-
891
- var _stream_writable;
892
- var hasRequired_stream_writable;
893
-
894
- function require_stream_writable () {
895
- if (hasRequired_stream_writable) return _stream_writable;
896
- hasRequired_stream_writable = 1;
897
-
898
- _stream_writable = Writable;
899
- // there will be only 2 of these for each stream
900
-
901
-
902
- function CorkedRequest(state) {
903
- var _this = this;
904
-
905
- this.next = null;
906
- this.entry = null;
907
-
908
- this.finish = function () {
909
- onCorkedFinish(_this, state);
910
- };
911
- }
912
- /* </replacement> */
913
-
914
- /*<replacement>*/
915
-
916
-
917
- var Duplex;
918
- /*</replacement>*/
919
-
920
- Writable.WritableState = WritableState;
921
- /*<replacement>*/
922
-
923
- var internalUtil = {
924
- deprecate: requireNode()
925
- };
926
- /*</replacement>*/
927
-
928
- /*<replacement>*/
929
-
930
- var Stream = requireStream();
931
- /*</replacement>*/
932
-
933
-
934
- var Buffer = require$$2$1.Buffer;
935
-
936
- var OurUint8Array = commonjsGlobal.Uint8Array || function () {};
937
-
938
- function _uint8ArrayToBuffer(chunk) {
939
- return Buffer.from(chunk);
940
- }
941
-
942
- function _isUint8Array(obj) {
943
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
944
- }
945
-
946
- var destroyImpl = requireDestroy();
947
-
948
- var _require = requireState(),
949
- getHighWaterMark = _require.getHighWaterMark;
950
-
951
- var _require$codes = requireErrors().codes,
952
- ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
953
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
954
- ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
955
- ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
956
- ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
957
- ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
958
- ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
959
- ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
960
-
961
- var errorOrDestroy = destroyImpl.errorOrDestroy;
962
-
963
- requireInherits()(Writable, Stream);
964
-
965
- function nop() {}
966
-
967
- function WritableState(options, stream, isDuplex) {
968
- Duplex = Duplex || require_stream_duplex();
969
- options = options || {}; // Duplex streams are both readable and writable, but share
970
- // the same options object.
971
- // However, some cases require setting options to different
972
- // values for the readable and the writable sides of the duplex stream,
973
- // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
974
-
975
- if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
976
- // contains buffers or objects.
977
-
978
- this.objectMode = !!options.objectMode;
979
- if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
980
- // Note: 0 is a valid value, means that we always return false if
981
- // the entire buffer is not flushed immediately on write()
982
-
983
- this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
984
-
985
- this.finalCalled = false; // drain event flag.
986
-
987
- this.needDrain = false; // at the start of calling end()
988
-
989
- this.ending = false; // when end() has been called, and returned
990
-
991
- this.ended = false; // when 'finish' is emitted
992
-
993
- this.finished = false; // has it been destroyed
994
-
995
- this.destroyed = false; // should we decode strings into buffers before passing to _write?
996
- // this is here so that some node-core streams can optimize string
997
- // handling at a lower level.
998
-
999
- var noDecode = options.decodeStrings === false;
1000
- this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
1001
- // encoding is 'binary' so we have to make this configurable.
1002
- // Everything else in the universe uses 'utf8', though.
1003
-
1004
- this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
1005
- // of how much we're waiting to get pushed to some underlying
1006
- // socket or file.
1007
-
1008
- this.length = 0; // a flag to see when we're in the middle of a write.
1009
-
1010
- this.writing = false; // when true all writes will be buffered until .uncork() call
1011
-
1012
- this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
1013
- // or on a later tick. We set this to true at first, because any
1014
- // actions that shouldn't happen until "later" should generally also
1015
- // not happen before the first write call.
1016
-
1017
- this.sync = true; // a flag to know if we're processing previously buffered items, which
1018
- // may call the _write() callback in the same tick, so that we don't
1019
- // end up in an overlapped onwrite situation.
1020
-
1021
- this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
1022
-
1023
- this.onwrite = function (er) {
1024
- onwrite(stream, er);
1025
- }; // the callback that the user supplies to write(chunk,encoding,cb)
1026
-
1027
-
1028
- this.writecb = null; // the amount that is being written when _write is called.
1029
-
1030
- this.writelen = 0;
1031
- this.bufferedRequest = null;
1032
- this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
1033
- // this must be 0 before 'finish' can be emitted
1034
-
1035
- this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
1036
- // This is relevant for synchronous Transform streams
1037
-
1038
- this.prefinished = false; // True if the error was already emitted and should not be thrown again
1039
-
1040
- this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
1041
-
1042
- this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
1043
-
1044
- this.autoDestroy = !!options.autoDestroy; // count buffered requests
1045
-
1046
- this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
1047
- // one allocated and free to use, and we maintain at most two
1048
-
1049
- this.corkedRequestsFree = new CorkedRequest(this);
1050
- }
1051
-
1052
- WritableState.prototype.getBuffer = function getBuffer() {
1053
- var current = this.bufferedRequest;
1054
- var out = [];
1055
-
1056
- while (current) {
1057
- out.push(current);
1058
- current = current.next;
1059
- }
1060
-
1061
- return out;
1062
- };
1063
-
1064
- (function () {
1065
- try {
1066
- Object.defineProperty(WritableState.prototype, 'buffer', {
1067
- get: internalUtil.deprecate(function writableStateBufferGetter() {
1068
- return this.getBuffer();
1069
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
1070
- });
1071
- } catch (_) {}
1072
- })(); // Test _writableState for inheritance to account for Duplex streams,
1073
- // whose prototype chain only points to Readable.
1074
-
1075
-
1076
- var realHasInstance;
1077
-
1078
- if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
1079
- realHasInstance = Function.prototype[Symbol.hasInstance];
1080
- Object.defineProperty(Writable, Symbol.hasInstance, {
1081
- value: function value(object) {
1082
- if (realHasInstance.call(this, object)) return true;
1083
- if (this !== Writable) return false;
1084
- return object && object._writableState instanceof WritableState;
1085
- }
1086
- });
1087
- } else {
1088
- realHasInstance = function realHasInstance(object) {
1089
- return object instanceof this;
1090
- };
1091
- }
1092
-
1093
- function Writable(options) {
1094
- Duplex = Duplex || require_stream_duplex(); // Writable ctor is applied to Duplexes, too.
1095
- // `realHasInstance` is necessary because using plain `instanceof`
1096
- // would return false, as no `_writableState` property is attached.
1097
- // Trying to use the custom `instanceof` for Writable here will also break the
1098
- // Node.js LazyTransform implementation, which has a non-trivial getter for
1099
- // `_writableState` that would lead to infinite recursion.
1100
- // Checking for a Stream.Duplex instance is faster here instead of inside
1101
- // the WritableState constructor, at least with V8 6.5
1102
-
1103
- var isDuplex = this instanceof Duplex;
1104
- if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
1105
- this._writableState = new WritableState(options, this, isDuplex); // legacy.
1106
-
1107
- this.writable = true;
1108
-
1109
- if (options) {
1110
- if (typeof options.write === 'function') this._write = options.write;
1111
- if (typeof options.writev === 'function') this._writev = options.writev;
1112
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
1113
- if (typeof options.final === 'function') this._final = options.final;
1114
- }
1115
-
1116
- Stream.call(this);
1117
- } // Otherwise people can pipe Writable streams, which is just wrong.
1118
-
1119
-
1120
- Writable.prototype.pipe = function () {
1121
- errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
1122
- };
1123
-
1124
- function writeAfterEnd(stream, cb) {
1125
- var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
1126
-
1127
- errorOrDestroy(stream, er);
1128
- process.nextTick(cb, er);
1129
- } // Checks that a user-supplied chunk is valid, especially for the particular
1130
- // mode the stream is in. Currently this means that `null` is never accepted
1131
- // and undefined/non-string values are only allowed in object mode.
1132
-
1133
-
1134
- function validChunk(stream, state, chunk, cb) {
1135
- var er;
1136
-
1137
- if (chunk === null) {
1138
- er = new ERR_STREAM_NULL_VALUES();
1139
- } else if (typeof chunk !== 'string' && !state.objectMode) {
1140
- er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
1141
- }
1142
-
1143
- if (er) {
1144
- errorOrDestroy(stream, er);
1145
- process.nextTick(cb, er);
1146
- return false;
1147
- }
1148
-
1149
- return true;
1150
- }
1151
-
1152
- Writable.prototype.write = function (chunk, encoding, cb) {
1153
- var state = this._writableState;
1154
- var ret = false;
1155
-
1156
- var isBuf = !state.objectMode && _isUint8Array(chunk);
1157
-
1158
- if (isBuf && !Buffer.isBuffer(chunk)) {
1159
- chunk = _uint8ArrayToBuffer(chunk);
1160
- }
1161
-
1162
- if (typeof encoding === 'function') {
1163
- cb = encoding;
1164
- encoding = null;
1165
- }
1166
-
1167
- if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
1168
- if (typeof cb !== 'function') cb = nop;
1169
- if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
1170
- state.pendingcb++;
1171
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
1172
- }
1173
- return ret;
1174
- };
1175
-
1176
- Writable.prototype.cork = function () {
1177
- this._writableState.corked++;
1178
- };
1179
-
1180
- Writable.prototype.uncork = function () {
1181
- var state = this._writableState;
1182
-
1183
- if (state.corked) {
1184
- state.corked--;
1185
- if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
1186
- }
1187
- };
1188
-
1189
- Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
1190
- // node::ParseEncoding() requires lower case.
1191
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
1192
- if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
1193
- this._writableState.defaultEncoding = encoding;
1194
- return this;
1195
- };
1196
-
1197
- Object.defineProperty(Writable.prototype, 'writableBuffer', {
1198
- // making it explicit this property is not enumerable
1199
- // because otherwise some prototype manipulation in
1200
- // userland will fail
1201
- enumerable: false,
1202
- get: function get() {
1203
- return this._writableState && this._writableState.getBuffer();
1204
- }
1205
- });
1206
-
1207
- function decodeChunk(state, chunk, encoding) {
1208
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
1209
- chunk = Buffer.from(chunk, encoding);
1210
- }
1211
-
1212
- return chunk;
1213
- }
1214
-
1215
- Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
1216
- // making it explicit this property is not enumerable
1217
- // because otherwise some prototype manipulation in
1218
- // userland will fail
1219
- enumerable: false,
1220
- get: function get() {
1221
- return this._writableState.highWaterMark;
1222
- }
1223
- }); // if we're already writing something, then just put this
1224
- // in the queue, and wait our turn. Otherwise, call _write
1225
- // If we return false, then we need a drain event, so set that flag.
1226
-
1227
- function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
1228
- if (!isBuf) {
1229
- var newChunk = decodeChunk(state, chunk, encoding);
1230
-
1231
- if (chunk !== newChunk) {
1232
- isBuf = true;
1233
- encoding = 'buffer';
1234
- chunk = newChunk;
1235
- }
1236
- }
1237
-
1238
- var len = state.objectMode ? 1 : chunk.length;
1239
- state.length += len;
1240
- var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
1241
-
1242
- if (!ret) state.needDrain = true;
1243
-
1244
- if (state.writing || state.corked) {
1245
- var last = state.lastBufferedRequest;
1246
- state.lastBufferedRequest = {
1247
- chunk: chunk,
1248
- encoding: encoding,
1249
- isBuf: isBuf,
1250
- callback: cb,
1251
- next: null
1252
- };
1253
-
1254
- if (last) {
1255
- last.next = state.lastBufferedRequest;
1256
- } else {
1257
- state.bufferedRequest = state.lastBufferedRequest;
1258
- }
1259
-
1260
- state.bufferedRequestCount += 1;
1261
- } else {
1262
- doWrite(stream, state, false, len, chunk, encoding, cb);
1263
- }
1264
-
1265
- return ret;
1266
- }
1267
-
1268
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
1269
- state.writelen = len;
1270
- state.writecb = cb;
1271
- state.writing = true;
1272
- state.sync = true;
1273
- if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
1274
- state.sync = false;
1275
- }
1276
-
1277
- function onwriteError(stream, state, sync, er, cb) {
1278
- --state.pendingcb;
1279
-
1280
- if (sync) {
1281
- // defer the callback if we are being called synchronously
1282
- // to avoid piling up things on the stack
1283
- process.nextTick(cb, er); // this can emit finish, and it will always happen
1284
- // after error
1285
-
1286
- process.nextTick(finishMaybe, stream, state);
1287
- stream._writableState.errorEmitted = true;
1288
- errorOrDestroy(stream, er);
1289
- } else {
1290
- // the caller expect this to happen before if
1291
- // it is async
1292
- cb(er);
1293
- stream._writableState.errorEmitted = true;
1294
- errorOrDestroy(stream, er); // this can emit finish, but finish must
1295
- // always follow error
1296
-
1297
- finishMaybe(stream, state);
1298
- }
1299
- }
1300
-
1301
- function onwriteStateUpdate(state) {
1302
- state.writing = false;
1303
- state.writecb = null;
1304
- state.length -= state.writelen;
1305
- state.writelen = 0;
1306
- }
1307
-
1308
- function onwrite(stream, er) {
1309
- var state = stream._writableState;
1310
- var sync = state.sync;
1311
- var cb = state.writecb;
1312
- if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
1313
- onwriteStateUpdate(state);
1314
- if (er) onwriteError(stream, state, sync, er, cb);else {
1315
- // Check if we're actually ready to finish, but don't emit yet
1316
- var finished = needFinish(state) || stream.destroyed;
1317
-
1318
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
1319
- clearBuffer(stream, state);
1320
- }
1321
-
1322
- if (sync) {
1323
- process.nextTick(afterWrite, stream, state, finished, cb);
1324
- } else {
1325
- afterWrite(stream, state, finished, cb);
1326
- }
1327
- }
1328
- }
1329
-
1330
- function afterWrite(stream, state, finished, cb) {
1331
- if (!finished) onwriteDrain(stream, state);
1332
- state.pendingcb--;
1333
- cb();
1334
- finishMaybe(stream, state);
1335
- } // Must force callback to be called on nextTick, so that we don't
1336
- // emit 'drain' before the write() consumer gets the 'false' return
1337
- // value, and has a chance to attach a 'drain' listener.
1338
-
1339
-
1340
- function onwriteDrain(stream, state) {
1341
- if (state.length === 0 && state.needDrain) {
1342
- state.needDrain = false;
1343
- stream.emit('drain');
1344
- }
1345
- } // if there's something in the buffer waiting, then process it
1346
-
1347
-
1348
- function clearBuffer(stream, state) {
1349
- state.bufferProcessing = true;
1350
- var entry = state.bufferedRequest;
1351
-
1352
- if (stream._writev && entry && entry.next) {
1353
- // Fast case, write everything using _writev()
1354
- var l = state.bufferedRequestCount;
1355
- var buffer = new Array(l);
1356
- var holder = state.corkedRequestsFree;
1357
- holder.entry = entry;
1358
- var count = 0;
1359
- var allBuffers = true;
1360
-
1361
- while (entry) {
1362
- buffer[count] = entry;
1363
- if (!entry.isBuf) allBuffers = false;
1364
- entry = entry.next;
1365
- count += 1;
1366
- }
1367
-
1368
- buffer.allBuffers = allBuffers;
1369
- doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
1370
- // as the hot path ends with doWrite
1371
-
1372
- state.pendingcb++;
1373
- state.lastBufferedRequest = null;
1374
-
1375
- if (holder.next) {
1376
- state.corkedRequestsFree = holder.next;
1377
- holder.next = null;
1378
- } else {
1379
- state.corkedRequestsFree = new CorkedRequest(state);
1380
- }
1381
-
1382
- state.bufferedRequestCount = 0;
1383
- } else {
1384
- // Slow case, write chunks one-by-one
1385
- while (entry) {
1386
- var chunk = entry.chunk;
1387
- var encoding = entry.encoding;
1388
- var cb = entry.callback;
1389
- var len = state.objectMode ? 1 : chunk.length;
1390
- doWrite(stream, state, false, len, chunk, encoding, cb);
1391
- entry = entry.next;
1392
- state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
1393
- // it means that we need to wait until it does.
1394
- // also, that means that the chunk and cb are currently
1395
- // being processed, so move the buffer counter past them.
1396
-
1397
- if (state.writing) {
1398
- break;
1399
- }
1400
- }
1401
-
1402
- if (entry === null) state.lastBufferedRequest = null;
1403
- }
1404
-
1405
- state.bufferedRequest = entry;
1406
- state.bufferProcessing = false;
1407
- }
1408
-
1409
- Writable.prototype._write = function (chunk, encoding, cb) {
1410
- cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
1411
- };
1412
-
1413
- Writable.prototype._writev = null;
1414
-
1415
- Writable.prototype.end = function (chunk, encoding, cb) {
1416
- var state = this._writableState;
1417
-
1418
- if (typeof chunk === 'function') {
1419
- cb = chunk;
1420
- chunk = null;
1421
- encoding = null;
1422
- } else if (typeof encoding === 'function') {
1423
- cb = encoding;
1424
- encoding = null;
1425
- }
1426
-
1427
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
1428
-
1429
- if (state.corked) {
1430
- state.corked = 1;
1431
- this.uncork();
1432
- } // ignore unnecessary end() calls.
1433
-
1434
-
1435
- if (!state.ending) endWritable(this, state, cb);
1436
- return this;
1437
- };
1438
-
1439
- Object.defineProperty(Writable.prototype, 'writableLength', {
1440
- // making it explicit this property is not enumerable
1441
- // because otherwise some prototype manipulation in
1442
- // userland will fail
1443
- enumerable: false,
1444
- get: function get() {
1445
- return this._writableState.length;
1446
- }
1447
- });
1448
-
1449
- function needFinish(state) {
1450
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
1451
- }
1452
-
1453
- function callFinal(stream, state) {
1454
- stream._final(function (err) {
1455
- state.pendingcb--;
1456
-
1457
- if (err) {
1458
- errorOrDestroy(stream, err);
1459
- }
1460
-
1461
- state.prefinished = true;
1462
- stream.emit('prefinish');
1463
- finishMaybe(stream, state);
1464
- });
1465
- }
1466
-
1467
- function prefinish(stream, state) {
1468
- if (!state.prefinished && !state.finalCalled) {
1469
- if (typeof stream._final === 'function' && !state.destroyed) {
1470
- state.pendingcb++;
1471
- state.finalCalled = true;
1472
- process.nextTick(callFinal, stream, state);
1473
- } else {
1474
- state.prefinished = true;
1475
- stream.emit('prefinish');
1476
- }
1477
- }
1478
- }
1479
-
1480
- function finishMaybe(stream, state) {
1481
- var need = needFinish(state);
1482
-
1483
- if (need) {
1484
- prefinish(stream, state);
1485
-
1486
- if (state.pendingcb === 0) {
1487
- state.finished = true;
1488
- stream.emit('finish');
1489
-
1490
- if (state.autoDestroy) {
1491
- // In case of duplex streams we need a way to detect
1492
- // if the readable side is ready for autoDestroy as well
1493
- var rState = stream._readableState;
1494
-
1495
- if (!rState || rState.autoDestroy && rState.endEmitted) {
1496
- stream.destroy();
1497
- }
1498
- }
1499
- }
1500
- }
1501
-
1502
- return need;
1503
- }
1504
-
1505
- function endWritable(stream, state, cb) {
1506
- state.ending = true;
1507
- finishMaybe(stream, state);
1508
-
1509
- if (cb) {
1510
- if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
1511
- }
1512
-
1513
- state.ended = true;
1514
- stream.writable = false;
1515
- }
1516
-
1517
- function onCorkedFinish(corkReq, state, err) {
1518
- var entry = corkReq.entry;
1519
- corkReq.entry = null;
1520
-
1521
- while (entry) {
1522
- var cb = entry.callback;
1523
- state.pendingcb--;
1524
- cb(err);
1525
- entry = entry.next;
1526
- } // reuse the free corkReq.
1527
-
1528
-
1529
- state.corkedRequestsFree.next = corkReq;
1530
- }
1531
-
1532
- Object.defineProperty(Writable.prototype, 'destroyed', {
1533
- // making it explicit this property is not enumerable
1534
- // because otherwise some prototype manipulation in
1535
- // userland will fail
1536
- enumerable: false,
1537
- get: function get() {
1538
- if (this._writableState === undefined) {
1539
- return false;
1540
- }
1541
-
1542
- return this._writableState.destroyed;
1543
- },
1544
- set: function set(value) {
1545
- // we ignore the value if the stream
1546
- // has not been initialized yet
1547
- if (!this._writableState) {
1548
- return;
1549
- } // backward compatibility, the user is explicitly
1550
- // managing destroyed
1551
-
1552
-
1553
- this._writableState.destroyed = value;
1554
- }
1555
- });
1556
- Writable.prototype.destroy = destroyImpl.destroy;
1557
- Writable.prototype._undestroy = destroyImpl.undestroy;
1558
-
1559
- Writable.prototype._destroy = function (err, cb) {
1560
- cb(err);
1561
- };
1562
- return _stream_writable;
1563
- }
1564
-
1565
- var _stream_duplex;
1566
- var hasRequired_stream_duplex;
1567
-
1568
- function require_stream_duplex () {
1569
- if (hasRequired_stream_duplex) return _stream_duplex;
1570
- hasRequired_stream_duplex = 1;
1571
- /*<replacement>*/
1572
-
1573
- var objectKeys = Object.keys || function (obj) {
1574
- var keys = [];
1575
-
1576
- for (var key in obj) {
1577
- keys.push(key);
1578
- }
1579
-
1580
- return keys;
1581
- };
1582
- /*</replacement>*/
1583
-
1584
-
1585
- _stream_duplex = Duplex;
1586
-
1587
- var Readable = require_stream_readable();
1588
-
1589
- var Writable = require_stream_writable();
1590
-
1591
- requireInherits()(Duplex, Readable);
1592
-
1593
- {
1594
- // Allow the keys array to be GC'ed.
1595
- var keys = objectKeys(Writable.prototype);
1596
-
1597
- for (var v = 0; v < keys.length; v++) {
1598
- var method = keys[v];
1599
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
1600
- }
1601
- }
1602
-
1603
- function Duplex(options) {
1604
- if (!(this instanceof Duplex)) return new Duplex(options);
1605
- Readable.call(this, options);
1606
- Writable.call(this, options);
1607
- this.allowHalfOpen = true;
1608
-
1609
- if (options) {
1610
- if (options.readable === false) this.readable = false;
1611
- if (options.writable === false) this.writable = false;
1612
-
1613
- if (options.allowHalfOpen === false) {
1614
- this.allowHalfOpen = false;
1615
- this.once('end', onend);
1616
- }
1617
- }
1618
- }
1619
-
1620
- Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
1621
- // making it explicit this property is not enumerable
1622
- // because otherwise some prototype manipulation in
1623
- // userland will fail
1624
- enumerable: false,
1625
- get: function get() {
1626
- return this._writableState.highWaterMark;
1627
- }
1628
- });
1629
- Object.defineProperty(Duplex.prototype, 'writableBuffer', {
1630
- // making it explicit this property is not enumerable
1631
- // because otherwise some prototype manipulation in
1632
- // userland will fail
1633
- enumerable: false,
1634
- get: function get() {
1635
- return this._writableState && this._writableState.getBuffer();
1636
- }
1637
- });
1638
- Object.defineProperty(Duplex.prototype, 'writableLength', {
1639
- // making it explicit this property is not enumerable
1640
- // because otherwise some prototype manipulation in
1641
- // userland will fail
1642
- enumerable: false,
1643
- get: function get() {
1644
- return this._writableState.length;
1645
- }
1646
- }); // the no-half-open enforcer
1647
-
1648
- function onend() {
1649
- // If the writable side ended, then we're ok.
1650
- if (this._writableState.ended) return; // no more data can be written.
1651
- // But allow more writes to happen in this tick.
1652
-
1653
- process.nextTick(onEndNT, this);
1654
- }
1655
-
1656
- function onEndNT(self) {
1657
- self.end();
1658
- }
1659
-
1660
- Object.defineProperty(Duplex.prototype, 'destroyed', {
1661
- // making it explicit this property is not enumerable
1662
- // because otherwise some prototype manipulation in
1663
- // userland will fail
1664
- enumerable: false,
1665
- get: function get() {
1666
- if (this._readableState === undefined || this._writableState === undefined) {
1667
- return false;
1668
- }
1669
-
1670
- return this._readableState.destroyed && this._writableState.destroyed;
1671
- },
1672
- set: function set(value) {
1673
- // we ignore the value if the stream
1674
- // has not been initialized yet
1675
- if (this._readableState === undefined || this._writableState === undefined) {
1676
- return;
1677
- } // backward compatibility, the user is explicitly
1678
- // managing destroyed
1679
-
1680
-
1681
- this._readableState.destroyed = value;
1682
- this._writableState.destroyed = value;
1683
- }
1684
- });
1685
- return _stream_duplex;
1686
- }
1687
-
1688
- var endOfStream;
1689
- var hasRequiredEndOfStream;
1690
-
1691
- function requireEndOfStream () {
1692
- if (hasRequiredEndOfStream) return endOfStream;
1693
- hasRequiredEndOfStream = 1;
1694
-
1695
- var ERR_STREAM_PREMATURE_CLOSE = requireErrors().codes.ERR_STREAM_PREMATURE_CLOSE;
1696
-
1697
- function once(callback) {
1698
- var called = false;
1699
- return function () {
1700
- if (called) return;
1701
- called = true;
1702
-
1703
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1704
- args[_key] = arguments[_key];
1705
- }
1706
-
1707
- callback.apply(this, args);
1708
- };
1709
- }
1710
-
1711
- function noop() {}
1712
-
1713
- function isRequest(stream) {
1714
- return stream.setHeader && typeof stream.abort === 'function';
1715
- }
1716
-
1717
- function eos(stream, opts, callback) {
1718
- if (typeof opts === 'function') return eos(stream, null, opts);
1719
- if (!opts) opts = {};
1720
- callback = once(callback || noop);
1721
- var readable = opts.readable || opts.readable !== false && stream.readable;
1722
- var writable = opts.writable || opts.writable !== false && stream.writable;
1723
-
1724
- var onlegacyfinish = function onlegacyfinish() {
1725
- if (!stream.writable) onfinish();
1726
- };
1727
-
1728
- var writableEnded = stream._writableState && stream._writableState.finished;
1729
-
1730
- var onfinish = function onfinish() {
1731
- writable = false;
1732
- writableEnded = true;
1733
- if (!readable) callback.call(stream);
1734
- };
1735
-
1736
- var readableEnded = stream._readableState && stream._readableState.endEmitted;
1737
-
1738
- var onend = function onend() {
1739
- readable = false;
1740
- readableEnded = true;
1741
- if (!writable) callback.call(stream);
1742
- };
1743
-
1744
- var onerror = function onerror(err) {
1745
- callback.call(stream, err);
1746
- };
1747
-
1748
- var onclose = function onclose() {
1749
- var err;
1750
-
1751
- if (readable && !readableEnded) {
1752
- if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
1753
- return callback.call(stream, err);
1754
- }
1755
-
1756
- if (writable && !writableEnded) {
1757
- if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
1758
- return callback.call(stream, err);
1759
- }
1760
- };
1761
-
1762
- var onrequest = function onrequest() {
1763
- stream.req.on('finish', onfinish);
1764
- };
1765
-
1766
- if (isRequest(stream)) {
1767
- stream.on('complete', onfinish);
1768
- stream.on('abort', onclose);
1769
- if (stream.req) onrequest();else stream.on('request', onrequest);
1770
- } else if (writable && !stream._writableState) {
1771
- // legacy streams
1772
- stream.on('end', onlegacyfinish);
1773
- stream.on('close', onlegacyfinish);
1774
- }
1775
-
1776
- stream.on('end', onend);
1777
- stream.on('finish', onfinish);
1778
- if (opts.error !== false) stream.on('error', onerror);
1779
- stream.on('close', onclose);
1780
- return function () {
1781
- stream.removeListener('complete', onfinish);
1782
- stream.removeListener('abort', onclose);
1783
- stream.removeListener('request', onrequest);
1784
- if (stream.req) stream.req.removeListener('finish', onfinish);
1785
- stream.removeListener('end', onlegacyfinish);
1786
- stream.removeListener('close', onlegacyfinish);
1787
- stream.removeListener('finish', onfinish);
1788
- stream.removeListener('end', onend);
1789
- stream.removeListener('error', onerror);
1790
- stream.removeListener('close', onclose);
1791
- };
1792
- }
1793
-
1794
- endOfStream = eos;
1795
- return endOfStream;
1796
- }
1797
-
1798
- var async_iterator;
1799
- var hasRequiredAsync_iterator;
1800
-
1801
- function requireAsync_iterator () {
1802
- if (hasRequiredAsync_iterator) return async_iterator;
1803
- hasRequiredAsync_iterator = 1;
1804
-
1805
- var _Object$setPrototypeO;
1806
-
1807
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
1808
-
1809
- var finished = requireEndOfStream();
1810
-
1811
- var kLastResolve = Symbol('lastResolve');
1812
- var kLastReject = Symbol('lastReject');
1813
- var kError = Symbol('error');
1814
- var kEnded = Symbol('ended');
1815
- var kLastPromise = Symbol('lastPromise');
1816
- var kHandlePromise = Symbol('handlePromise');
1817
- var kStream = Symbol('stream');
1818
-
1819
- function createIterResult(value, done) {
1820
- return {
1821
- value: value,
1822
- done: done
1823
- };
1824
- }
1825
-
1826
- function readAndResolve(iter) {
1827
- var resolve = iter[kLastResolve];
1828
-
1829
- if (resolve !== null) {
1830
- var data = iter[kStream].read(); // we defer if data is null
1831
- // we can be expecting either 'end' or
1832
- // 'error'
1833
-
1834
- if (data !== null) {
1835
- iter[kLastPromise] = null;
1836
- iter[kLastResolve] = null;
1837
- iter[kLastReject] = null;
1838
- resolve(createIterResult(data, false));
1839
- }
1840
- }
1841
- }
1842
-
1843
- function onReadable(iter) {
1844
- // we wait for the next tick, because it might
1845
- // emit an error with process.nextTick
1846
- process.nextTick(readAndResolve, iter);
1847
- }
1848
-
1849
- function wrapForNext(lastPromise, iter) {
1850
- return function (resolve, reject) {
1851
- lastPromise.then(function () {
1852
- if (iter[kEnded]) {
1853
- resolve(createIterResult(undefined, true));
1854
- return;
1855
- }
1856
-
1857
- iter[kHandlePromise](resolve, reject);
1858
- }, reject);
1859
- };
1860
- }
1861
-
1862
- var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
1863
- var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
1864
- get stream() {
1865
- return this[kStream];
1866
- },
1867
-
1868
- next: function next() {
1869
- var _this = this;
1870
-
1871
- // if we have detected an error in the meanwhile
1872
- // reject straight away
1873
- var error = this[kError];
1874
-
1875
- if (error !== null) {
1876
- return Promise.reject(error);
1877
- }
1878
-
1879
- if (this[kEnded]) {
1880
- return Promise.resolve(createIterResult(undefined, true));
1881
- }
1882
-
1883
- if (this[kStream].destroyed) {
1884
- // We need to defer via nextTick because if .destroy(err) is
1885
- // called, the error will be emitted via nextTick, and
1886
- // we cannot guarantee that there is no error lingering around
1887
- // waiting to be emitted.
1888
- return new Promise(function (resolve, reject) {
1889
- process.nextTick(function () {
1890
- if (_this[kError]) {
1891
- reject(_this[kError]);
1892
- } else {
1893
- resolve(createIterResult(undefined, true));
1894
- }
1895
- });
1896
- });
1897
- } // if we have multiple next() calls
1898
- // we will wait for the previous Promise to finish
1899
- // this logic is optimized to support for await loops,
1900
- // where next() is only called once at a time
1901
-
1902
-
1903
- var lastPromise = this[kLastPromise];
1904
- var promise;
1905
-
1906
- if (lastPromise) {
1907
- promise = new Promise(wrapForNext(lastPromise, this));
1908
- } else {
1909
- // fast path needed to support multiple this.push()
1910
- // without triggering the next() queue
1911
- var data = this[kStream].read();
1912
-
1913
- if (data !== null) {
1914
- return Promise.resolve(createIterResult(data, false));
1915
- }
1916
-
1917
- promise = new Promise(this[kHandlePromise]);
1918
- }
1919
-
1920
- this[kLastPromise] = promise;
1921
- return promise;
1922
- }
1923
- }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
1924
- return this;
1925
- }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
1926
- var _this2 = this;
1927
-
1928
- // destroy(err, cb) is a private API
1929
- // we can guarantee we have that here, because we control the
1930
- // Readable class this is attached to
1931
- return new Promise(function (resolve, reject) {
1932
- _this2[kStream].destroy(null, function (err) {
1933
- if (err) {
1934
- reject(err);
1935
- return;
1936
- }
1937
-
1938
- resolve(createIterResult(undefined, true));
1939
- });
1940
- });
1941
- }), _Object$setPrototypeO), AsyncIteratorPrototype);
1942
-
1943
- var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
1944
- var _Object$create;
1945
-
1946
- var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
1947
- value: stream,
1948
- writable: true
1949
- }), _defineProperty(_Object$create, kLastResolve, {
1950
- value: null,
1951
- writable: true
1952
- }), _defineProperty(_Object$create, kLastReject, {
1953
- value: null,
1954
- writable: true
1955
- }), _defineProperty(_Object$create, kError, {
1956
- value: null,
1957
- writable: true
1958
- }), _defineProperty(_Object$create, kEnded, {
1959
- value: stream._readableState.endEmitted,
1960
- writable: true
1961
- }), _defineProperty(_Object$create, kHandlePromise, {
1962
- value: function value(resolve, reject) {
1963
- var data = iterator[kStream].read();
1964
-
1965
- if (data) {
1966
- iterator[kLastPromise] = null;
1967
- iterator[kLastResolve] = null;
1968
- iterator[kLastReject] = null;
1969
- resolve(createIterResult(data, false));
1970
- } else {
1971
- iterator[kLastResolve] = resolve;
1972
- iterator[kLastReject] = reject;
1973
- }
1974
- },
1975
- writable: true
1976
- }), _Object$create));
1977
- iterator[kLastPromise] = null;
1978
- finished(stream, function (err) {
1979
- if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
1980
- var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
1981
- // returned by next() and store the error
1982
-
1983
- if (reject !== null) {
1984
- iterator[kLastPromise] = null;
1985
- iterator[kLastResolve] = null;
1986
- iterator[kLastReject] = null;
1987
- reject(err);
1988
- }
1989
-
1990
- iterator[kError] = err;
1991
- return;
1992
- }
1993
-
1994
- var resolve = iterator[kLastResolve];
1995
-
1996
- if (resolve !== null) {
1997
- iterator[kLastPromise] = null;
1998
- iterator[kLastResolve] = null;
1999
- iterator[kLastReject] = null;
2000
- resolve(createIterResult(undefined, true));
2001
- }
2002
-
2003
- iterator[kEnded] = true;
2004
- });
2005
- stream.on('readable', onReadable.bind(null, iterator));
2006
- return iterator;
2007
- };
2008
-
2009
- async_iterator = createReadableStreamAsyncIterator;
2010
- return async_iterator;
2011
- }
2012
-
2013
- var from_1;
2014
- var hasRequiredFrom;
2015
-
2016
- function requireFrom () {
2017
- if (hasRequiredFrom) return from_1;
2018
- hasRequiredFrom = 1;
2019
-
2020
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
2021
-
2022
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
2023
-
2024
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
2025
-
2026
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
2027
-
2028
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2029
-
2030
- var ERR_INVALID_ARG_TYPE = requireErrors().codes.ERR_INVALID_ARG_TYPE;
2031
-
2032
- function from(Readable, iterable, opts) {
2033
- var iterator;
2034
-
2035
- if (iterable && typeof iterable.next === 'function') {
2036
- iterator = iterable;
2037
- } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
2038
-
2039
- var readable = new Readable(_objectSpread({
2040
- objectMode: true
2041
- }, opts)); // Reading boolean to protect against _read
2042
- // being called before last iteration completion.
2043
-
2044
- var reading = false;
2045
-
2046
- readable._read = function () {
2047
- if (!reading) {
2048
- reading = true;
2049
- next();
2050
- }
2051
- };
2052
-
2053
- function next() {
2054
- return _next2.apply(this, arguments);
2055
- }
2056
-
2057
- function _next2() {
2058
- _next2 = _asyncToGenerator(function* () {
2059
- try {
2060
- var _ref = yield iterator.next(),
2061
- value = _ref.value,
2062
- done = _ref.done;
2063
-
2064
- if (done) {
2065
- readable.push(null);
2066
- } else if (readable.push((yield value))) {
2067
- next();
2068
- } else {
2069
- reading = false;
2070
- }
2071
- } catch (err) {
2072
- readable.destroy(err);
2073
- }
2074
- });
2075
- return _next2.apply(this, arguments);
2076
- }
2077
-
2078
- return readable;
2079
- }
2080
-
2081
- from_1 = from;
2082
- return from_1;
2083
- }
2084
-
2085
- var _stream_readable;
2086
- var hasRequired_stream_readable;
2087
-
2088
- function require_stream_readable () {
2089
- if (hasRequired_stream_readable) return _stream_readable;
2090
- hasRequired_stream_readable = 1;
2091
-
2092
- _stream_readable = Readable;
2093
- /*<replacement>*/
2094
-
2095
- var Duplex;
2096
- /*</replacement>*/
2097
-
2098
- Readable.ReadableState = ReadableState;
2099
- /*<replacement>*/
2100
-
2101
- require$$0$2.EventEmitter;
2102
-
2103
- var EElistenerCount = function EElistenerCount(emitter, type) {
2104
- return emitter.listeners(type).length;
2105
- };
2106
- /*</replacement>*/
2107
-
2108
- /*<replacement>*/
2109
-
2110
-
2111
- var Stream = requireStream();
2112
- /*</replacement>*/
2113
-
2114
-
2115
- var Buffer = require$$2$1.Buffer;
2116
-
2117
- var OurUint8Array = commonjsGlobal.Uint8Array || function () {};
2118
-
2119
- function _uint8ArrayToBuffer(chunk) {
2120
- return Buffer.from(chunk);
2121
- }
2122
-
2123
- function _isUint8Array(obj) {
2124
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
2125
- }
2126
- /*<replacement>*/
2127
-
2128
-
2129
- var debugUtil = require$$1$1;
2130
-
2131
- var debug;
2132
-
2133
- if (debugUtil && debugUtil.debuglog) {
2134
- debug = debugUtil.debuglog('stream');
2135
- } else {
2136
- debug = function debug() {};
2137
- }
2138
- /*</replacement>*/
2139
-
2140
-
2141
- var BufferList = requireBuffer_list();
2142
-
2143
- var destroyImpl = requireDestroy();
2144
-
2145
- var _require = requireState(),
2146
- getHighWaterMark = _require.getHighWaterMark;
2147
-
2148
- var _require$codes = requireErrors().codes,
2149
- ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
2150
- ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
2151
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
2152
- ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
2153
-
2154
-
2155
- var StringDecoder;
2156
- var createReadableStreamAsyncIterator;
2157
- var from;
2158
-
2159
- requireInherits()(Readable, Stream);
2160
-
2161
- var errorOrDestroy = destroyImpl.errorOrDestroy;
2162
- var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
2163
-
2164
- function prependListener(emitter, event, fn) {
2165
- // Sadly this is not cacheable as some libraries bundle their own
2166
- // event emitter implementation with them.
2167
- if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
2168
- // userland ones. NEVER DO THIS. This is here only because this code needs
2169
- // to continue to work with older versions of Node.js that do not include
2170
- // the prependListener() method. The goal is to eventually remove this hack.
2171
-
2172
- if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
2173
- }
2174
-
2175
- function ReadableState(options, stream, isDuplex) {
2176
- Duplex = Duplex || require_stream_duplex();
2177
- options = options || {}; // Duplex streams are both readable and writable, but share
2178
- // the same options object.
2179
- // However, some cases require setting options to different
2180
- // values for the readable and the writable sides of the duplex stream.
2181
- // These options can be provided separately as readableXXX and writableXXX.
2182
-
2183
- if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
2184
- // make all the buffer merging and length checks go away
2185
-
2186
- this.objectMode = !!options.objectMode;
2187
- if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
2188
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
2189
-
2190
- this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
2191
- // linked list can remove elements from the beginning faster than
2192
- // array.shift()
2193
-
2194
- this.buffer = new BufferList();
2195
- this.length = 0;
2196
- this.pipes = null;
2197
- this.pipesCount = 0;
2198
- this.flowing = null;
2199
- this.ended = false;
2200
- this.endEmitted = false;
2201
- this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
2202
- // immediately, or on a later tick. We set this to true at first, because
2203
- // any actions that shouldn't happen until "later" should generally also
2204
- // not happen before the first read call.
2205
-
2206
- this.sync = true; // whenever we return null, then we set a flag to say
2207
- // that we're awaiting a 'readable' event emission.
2208
-
2209
- this.needReadable = false;
2210
- this.emittedReadable = false;
2211
- this.readableListening = false;
2212
- this.resumeScheduled = false;
2213
- this.paused = true; // Should close be emitted on destroy. Defaults to true.
2214
-
2215
- this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
2216
-
2217
- this.autoDestroy = !!options.autoDestroy; // has it been destroyed
2218
-
2219
- this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
2220
- // encoding is 'binary' so we have to make this configurable.
2221
- // Everything else in the universe uses 'utf8', though.
2222
-
2223
- this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
2224
-
2225
- this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
2226
-
2227
- this.readingMore = false;
2228
- this.decoder = null;
2229
- this.encoding = null;
2230
-
2231
- if (options.encoding) {
2232
- if (!StringDecoder) StringDecoder = require$$10.StringDecoder;
2233
- this.decoder = new StringDecoder(options.encoding);
2234
- this.encoding = options.encoding;
2235
- }
2236
- }
2237
-
2238
- function Readable(options) {
2239
- Duplex = Duplex || require_stream_duplex();
2240
- if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
2241
- // the ReadableState constructor, at least with V8 6.5
2242
-
2243
- var isDuplex = this instanceof Duplex;
2244
- this._readableState = new ReadableState(options, this, isDuplex); // legacy
2245
-
2246
- this.readable = true;
2247
-
2248
- if (options) {
2249
- if (typeof options.read === 'function') this._read = options.read;
2250
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
2251
- }
2252
-
2253
- Stream.call(this);
2254
- }
2255
-
2256
- Object.defineProperty(Readable.prototype, 'destroyed', {
2257
- // making it explicit this property is not enumerable
2258
- // because otherwise some prototype manipulation in
2259
- // userland will fail
2260
- enumerable: false,
2261
- get: function get() {
2262
- if (this._readableState === undefined) {
2263
- return false;
2264
- }
2265
-
2266
- return this._readableState.destroyed;
2267
- },
2268
- set: function set(value) {
2269
- // we ignore the value if the stream
2270
- // has not been initialized yet
2271
- if (!this._readableState) {
2272
- return;
2273
- } // backward compatibility, the user is explicitly
2274
- // managing destroyed
2275
-
2276
-
2277
- this._readableState.destroyed = value;
2278
- }
2279
- });
2280
- Readable.prototype.destroy = destroyImpl.destroy;
2281
- Readable.prototype._undestroy = destroyImpl.undestroy;
2282
-
2283
- Readable.prototype._destroy = function (err, cb) {
2284
- cb(err);
2285
- }; // Manually shove something into the read() buffer.
2286
- // This returns true if the highWaterMark has not been hit yet,
2287
- // similar to how Writable.write() returns true if you should
2288
- // write() some more.
2289
-
2290
-
2291
- Readable.prototype.push = function (chunk, encoding) {
2292
- var state = this._readableState;
2293
- var skipChunkCheck;
2294
-
2295
- if (!state.objectMode) {
2296
- if (typeof chunk === 'string') {
2297
- encoding = encoding || state.defaultEncoding;
2298
-
2299
- if (encoding !== state.encoding) {
2300
- chunk = Buffer.from(chunk, encoding);
2301
- encoding = '';
2302
- }
2303
-
2304
- skipChunkCheck = true;
2305
- }
2306
- } else {
2307
- skipChunkCheck = true;
2308
- }
2309
-
2310
- return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
2311
- }; // Unshift should *always* be something directly out of read()
2312
-
2313
-
2314
- Readable.prototype.unshift = function (chunk) {
2315
- return readableAddChunk(this, chunk, null, true, false);
2316
- };
2317
-
2318
- function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
2319
- debug('readableAddChunk', chunk);
2320
- var state = stream._readableState;
2321
-
2322
- if (chunk === null) {
2323
- state.reading = false;
2324
- onEofChunk(stream, state);
2325
- } else {
2326
- var er;
2327
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
2328
-
2329
- if (er) {
2330
- errorOrDestroy(stream, er);
2331
- } else if (state.objectMode || chunk && chunk.length > 0) {
2332
- if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
2333
- chunk = _uint8ArrayToBuffer(chunk);
2334
- }
2335
-
2336
- if (addToFront) {
2337
- if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
2338
- } else if (state.ended) {
2339
- errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
2340
- } else if (state.destroyed) {
2341
- return false;
2342
- } else {
2343
- state.reading = false;
2344
-
2345
- if (state.decoder && !encoding) {
2346
- chunk = state.decoder.write(chunk);
2347
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
2348
- } else {
2349
- addChunk(stream, state, chunk, false);
2350
- }
2351
- }
2352
- } else if (!addToFront) {
2353
- state.reading = false;
2354
- maybeReadMore(stream, state);
2355
- }
2356
- } // We can push more data if we are below the highWaterMark.
2357
- // Also, if we have no data yet, we can stand some more bytes.
2358
- // This is to work around cases where hwm=0, such as the repl.
2359
-
2360
-
2361
- return !state.ended && (state.length < state.highWaterMark || state.length === 0);
2362
- }
2363
-
2364
- function addChunk(stream, state, chunk, addToFront) {
2365
- if (state.flowing && state.length === 0 && !state.sync) {
2366
- state.awaitDrain = 0;
2367
- stream.emit('data', chunk);
2368
- } else {
2369
- // update the buffer info.
2370
- state.length += state.objectMode ? 1 : chunk.length;
2371
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
2372
- if (state.needReadable) emitReadable(stream);
2373
- }
2374
-
2375
- maybeReadMore(stream, state);
2376
- }
2377
-
2378
- function chunkInvalid(state, chunk) {
2379
- var er;
2380
-
2381
- if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
2382
- er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
2383
- }
2384
-
2385
- return er;
2386
- }
2387
-
2388
- Readable.prototype.isPaused = function () {
2389
- return this._readableState.flowing === false;
2390
- }; // backwards compatibility.
2391
-
2392
-
2393
- Readable.prototype.setEncoding = function (enc) {
2394
- if (!StringDecoder) StringDecoder = require$$10.StringDecoder;
2395
- var decoder = new StringDecoder(enc);
2396
- this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
2397
-
2398
- this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
2399
-
2400
- var p = this._readableState.buffer.head;
2401
- var content = '';
2402
-
2403
- while (p !== null) {
2404
- content += decoder.write(p.data);
2405
- p = p.next;
2406
- }
2407
-
2408
- this._readableState.buffer.clear();
2409
-
2410
- if (content !== '') this._readableState.buffer.push(content);
2411
- this._readableState.length = content.length;
2412
- return this;
2413
- }; // Don't raise the hwm > 1GB
2414
-
2415
-
2416
- var MAX_HWM = 0x40000000;
2417
-
2418
- function computeNewHighWaterMark(n) {
2419
- if (n >= MAX_HWM) {
2420
- // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
2421
- n = MAX_HWM;
2422
- } else {
2423
- // Get the next highest power of 2 to prevent increasing hwm excessively in
2424
- // tiny amounts
2425
- n--;
2426
- n |= n >>> 1;
2427
- n |= n >>> 2;
2428
- n |= n >>> 4;
2429
- n |= n >>> 8;
2430
- n |= n >>> 16;
2431
- n++;
2432
- }
2433
-
2434
- return n;
2435
- } // This function is designed to be inlinable, so please take care when making
2436
- // changes to the function body.
2437
-
2438
-
2439
- function howMuchToRead(n, state) {
2440
- if (n <= 0 || state.length === 0 && state.ended) return 0;
2441
- if (state.objectMode) return 1;
2442
-
2443
- if (n !== n) {
2444
- // Only flow one buffer at a time
2445
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
2446
- } // If we're asking for more than the current hwm, then raise the hwm.
2447
-
2448
-
2449
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
2450
- if (n <= state.length) return n; // Don't have enough
2451
-
2452
- if (!state.ended) {
2453
- state.needReadable = true;
2454
- return 0;
2455
- }
2456
-
2457
- return state.length;
2458
- } // you can override either this method, or the async _read(n) below.
2459
-
2460
-
2461
- Readable.prototype.read = function (n) {
2462
- debug('read', n);
2463
- n = parseInt(n, 10);
2464
- var state = this._readableState;
2465
- var nOrig = n;
2466
- if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
2467
- // already have a bunch of data in the buffer, then just trigger
2468
- // the 'readable' event and move on.
2469
-
2470
- if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
2471
- debug('read: emitReadable', state.length, state.ended);
2472
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
2473
- return null;
2474
- }
2475
-
2476
- n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
2477
-
2478
- if (n === 0 && state.ended) {
2479
- if (state.length === 0) endReadable(this);
2480
- return null;
2481
- } // All the actual chunk generation logic needs to be
2482
- // *below* the call to _read. The reason is that in certain
2483
- // synthetic stream cases, such as passthrough streams, _read
2484
- // may be a completely synchronous operation which may change
2485
- // the state of the read buffer, providing enough data when
2486
- // before there was *not* enough.
2487
- //
2488
- // So, the steps are:
2489
- // 1. Figure out what the state of things will be after we do
2490
- // a read from the buffer.
2491
- //
2492
- // 2. If that resulting state will trigger a _read, then call _read.
2493
- // Note that this may be asynchronous, or synchronous. Yes, it is
2494
- // deeply ugly to write APIs this way, but that still doesn't mean
2495
- // that the Readable class should behave improperly, as streams are
2496
- // designed to be sync/async agnostic.
2497
- // Take note if the _read call is sync or async (ie, if the read call
2498
- // has returned yet), so that we know whether or not it's safe to emit
2499
- // 'readable' etc.
2500
- //
2501
- // 3. Actually pull the requested chunks out of the buffer and return.
2502
- // if we need a readable event, then we need to do some reading.
2503
-
2504
-
2505
- var doRead = state.needReadable;
2506
- debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
2507
-
2508
- if (state.length === 0 || state.length - n < state.highWaterMark) {
2509
- doRead = true;
2510
- debug('length less than watermark', doRead);
2511
- } // however, if we've ended, then there's no point, and if we're already
2512
- // reading, then it's unnecessary.
2513
-
2514
-
2515
- if (state.ended || state.reading) {
2516
- doRead = false;
2517
- debug('reading or ended', doRead);
2518
- } else if (doRead) {
2519
- debug('do read');
2520
- state.reading = true;
2521
- state.sync = true; // if the length is currently zero, then we *need* a readable event.
2522
-
2523
- if (state.length === 0) state.needReadable = true; // call internal read method
2524
-
2525
- this._read(state.highWaterMark);
2526
-
2527
- state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
2528
- // and we need to re-evaluate how much data we can return to the user.
2529
-
2530
- if (!state.reading) n = howMuchToRead(nOrig, state);
2531
- }
2532
-
2533
- var ret;
2534
- if (n > 0) ret = fromList(n, state);else ret = null;
2535
-
2536
- if (ret === null) {
2537
- state.needReadable = state.length <= state.highWaterMark;
2538
- n = 0;
2539
- } else {
2540
- state.length -= n;
2541
- state.awaitDrain = 0;
2542
- }
2543
-
2544
- if (state.length === 0) {
2545
- // If we have nothing in the buffer, then we want to know
2546
- // as soon as we *do* get something into the buffer.
2547
- if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
2548
-
2549
- if (nOrig !== n && state.ended) endReadable(this);
2550
- }
2551
-
2552
- if (ret !== null) this.emit('data', ret);
2553
- return ret;
2554
- };
2555
-
2556
- function onEofChunk(stream, state) {
2557
- debug('onEofChunk');
2558
- if (state.ended) return;
2559
-
2560
- if (state.decoder) {
2561
- var chunk = state.decoder.end();
2562
-
2563
- if (chunk && chunk.length) {
2564
- state.buffer.push(chunk);
2565
- state.length += state.objectMode ? 1 : chunk.length;
2566
- }
2567
- }
2568
-
2569
- state.ended = true;
2570
-
2571
- if (state.sync) {
2572
- // if we are sync, wait until next tick to emit the data.
2573
- // Otherwise we risk emitting data in the flow()
2574
- // the readable code triggers during a read() call
2575
- emitReadable(stream);
2576
- } else {
2577
- // emit 'readable' now to make sure it gets picked up.
2578
- state.needReadable = false;
2579
-
2580
- if (!state.emittedReadable) {
2581
- state.emittedReadable = true;
2582
- emitReadable_(stream);
2583
- }
2584
- }
2585
- } // Don't emit readable right away in sync mode, because this can trigger
2586
- // another read() call => stack overflow. This way, it might trigger
2587
- // a nextTick recursion warning, but that's not so bad.
2588
-
2589
-
2590
- function emitReadable(stream) {
2591
- var state = stream._readableState;
2592
- debug('emitReadable', state.needReadable, state.emittedReadable);
2593
- state.needReadable = false;
2594
-
2595
- if (!state.emittedReadable) {
2596
- debug('emitReadable', state.flowing);
2597
- state.emittedReadable = true;
2598
- process.nextTick(emitReadable_, stream);
2599
- }
2600
- }
2601
-
2602
- function emitReadable_(stream) {
2603
- var state = stream._readableState;
2604
- debug('emitReadable_', state.destroyed, state.length, state.ended);
2605
-
2606
- if (!state.destroyed && (state.length || state.ended)) {
2607
- stream.emit('readable');
2608
- state.emittedReadable = false;
2609
- } // The stream needs another readable event if
2610
- // 1. It is not flowing, as the flow mechanism will take
2611
- // care of it.
2612
- // 2. It is not ended.
2613
- // 3. It is below the highWaterMark, so we can schedule
2614
- // another readable later.
2615
-
2616
-
2617
- state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
2618
- flow(stream);
2619
- } // at this point, the user has presumably seen the 'readable' event,
2620
- // and called read() to consume some data. that may have triggered
2621
- // in turn another _read(n) call, in which case reading = true if
2622
- // it's in progress.
2623
- // However, if we're not ended, or reading, and the length < hwm,
2624
- // then go ahead and try to read some more preemptively.
2625
-
2626
-
2627
- function maybeReadMore(stream, state) {
2628
- if (!state.readingMore) {
2629
- state.readingMore = true;
2630
- process.nextTick(maybeReadMore_, stream, state);
2631
- }
2632
- }
2633
-
2634
- function maybeReadMore_(stream, state) {
2635
- // Attempt to read more data if we should.
2636
- //
2637
- // The conditions for reading more data are (one of):
2638
- // - Not enough data buffered (state.length < state.highWaterMark). The loop
2639
- // is responsible for filling the buffer with enough data if such data
2640
- // is available. If highWaterMark is 0 and we are not in the flowing mode
2641
- // we should _not_ attempt to buffer any extra data. We'll get more data
2642
- // when the stream consumer calls read() instead.
2643
- // - No data in the buffer, and the stream is in flowing mode. In this mode
2644
- // the loop below is responsible for ensuring read() is called. Failing to
2645
- // call read here would abort the flow and there's no other mechanism for
2646
- // continuing the flow if the stream consumer has just subscribed to the
2647
- // 'data' event.
2648
- //
2649
- // In addition to the above conditions to keep reading data, the following
2650
- // conditions prevent the data from being read:
2651
- // - The stream has ended (state.ended).
2652
- // - There is already a pending 'read' operation (state.reading). This is a
2653
- // case where the the stream has called the implementation defined _read()
2654
- // method, but they are processing the call asynchronously and have _not_
2655
- // called push() with new data. In this case we skip performing more
2656
- // read()s. The execution ends in this method again after the _read() ends
2657
- // up calling push() with more data.
2658
- while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
2659
- var len = state.length;
2660
- debug('maybeReadMore read 0');
2661
- stream.read(0);
2662
- if (len === state.length) // didn't get any data, stop spinning.
2663
- break;
2664
- }
2665
-
2666
- state.readingMore = false;
2667
- } // abstract method. to be overridden in specific implementation classes.
2668
- // call cb(er, data) where data is <= n in length.
2669
- // for virtual (non-string, non-buffer) streams, "length" is somewhat
2670
- // arbitrary, and perhaps not very meaningful.
2671
-
2672
-
2673
- Readable.prototype._read = function (n) {
2674
- errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
2675
- };
2676
-
2677
- Readable.prototype.pipe = function (dest, pipeOpts) {
2678
- var src = this;
2679
- var state = this._readableState;
2680
-
2681
- switch (state.pipesCount) {
2682
- case 0:
2683
- state.pipes = dest;
2684
- break;
2685
-
2686
- case 1:
2687
- state.pipes = [state.pipes, dest];
2688
- break;
2689
-
2690
- default:
2691
- state.pipes.push(dest);
2692
- break;
2693
- }
2694
-
2695
- state.pipesCount += 1;
2696
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
2697
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
2698
- var endFn = doEnd ? onend : unpipe;
2699
- if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
2700
- dest.on('unpipe', onunpipe);
2701
-
2702
- function onunpipe(readable, unpipeInfo) {
2703
- debug('onunpipe');
2704
-
2705
- if (readable === src) {
2706
- if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
2707
- unpipeInfo.hasUnpiped = true;
2708
- cleanup();
2709
- }
2710
- }
2711
- }
2712
-
2713
- function onend() {
2714
- debug('onend');
2715
- dest.end();
2716
- } // when the dest drains, it reduces the awaitDrain counter
2717
- // on the source. This would be more elegant with a .once()
2718
- // handler in flow(), but adding and removing repeatedly is
2719
- // too slow.
2720
-
2721
-
2722
- var ondrain = pipeOnDrain(src);
2723
- dest.on('drain', ondrain);
2724
- var cleanedUp = false;
2725
-
2726
- function cleanup() {
2727
- debug('cleanup'); // cleanup event handlers once the pipe is broken
2728
-
2729
- dest.removeListener('close', onclose);
2730
- dest.removeListener('finish', onfinish);
2731
- dest.removeListener('drain', ondrain);
2732
- dest.removeListener('error', onerror);
2733
- dest.removeListener('unpipe', onunpipe);
2734
- src.removeListener('end', onend);
2735
- src.removeListener('end', unpipe);
2736
- src.removeListener('data', ondata);
2737
- cleanedUp = true; // if the reader is waiting for a drain event from this
2738
- // specific writer, then it would cause it to never start
2739
- // flowing again.
2740
- // So, if this is awaiting a drain, then we just call it now.
2741
- // If we don't know, then assume that we are waiting for one.
2742
-
2743
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
2744
- }
2745
-
2746
- src.on('data', ondata);
2747
-
2748
- function ondata(chunk) {
2749
- debug('ondata');
2750
- var ret = dest.write(chunk);
2751
- debug('dest.write', ret);
2752
-
2753
- if (ret === false) {
2754
- // If the user unpiped during `dest.write()`, it is possible
2755
- // to get stuck in a permanently paused state if that write
2756
- // also returned false.
2757
- // => Check whether `dest` is still a piping destination.
2758
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
2759
- debug('false write response, pause', state.awaitDrain);
2760
- state.awaitDrain++;
2761
- }
2762
-
2763
- src.pause();
2764
- }
2765
- } // if the dest has an error, then stop piping into it.
2766
- // however, don't suppress the throwing behavior for this.
2767
-
2768
-
2769
- function onerror(er) {
2770
- debug('onerror', er);
2771
- unpipe();
2772
- dest.removeListener('error', onerror);
2773
- if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
2774
- } // Make sure our error handler is attached before userland ones.
2775
-
2776
-
2777
- prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
2778
-
2779
- function onclose() {
2780
- dest.removeListener('finish', onfinish);
2781
- unpipe();
2782
- }
2783
-
2784
- dest.once('close', onclose);
2785
-
2786
- function onfinish() {
2787
- debug('onfinish');
2788
- dest.removeListener('close', onclose);
2789
- unpipe();
2790
- }
2791
-
2792
- dest.once('finish', onfinish);
2793
-
2794
- function unpipe() {
2795
- debug('unpipe');
2796
- src.unpipe(dest);
2797
- } // tell the dest that it's being piped to
2798
-
2799
-
2800
- dest.emit('pipe', src); // start the flow if it hasn't been started already.
2801
-
2802
- if (!state.flowing) {
2803
- debug('pipe resume');
2804
- src.resume();
2805
- }
2806
-
2807
- return dest;
2808
- };
2809
-
2810
- function pipeOnDrain(src) {
2811
- return function pipeOnDrainFunctionResult() {
2812
- var state = src._readableState;
2813
- debug('pipeOnDrain', state.awaitDrain);
2814
- if (state.awaitDrain) state.awaitDrain--;
2815
-
2816
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
2817
- state.flowing = true;
2818
- flow(src);
2819
- }
2820
- };
2821
- }
2822
-
2823
- Readable.prototype.unpipe = function (dest) {
2824
- var state = this._readableState;
2825
- var unpipeInfo = {
2826
- hasUnpiped: false
2827
- }; // if we're not piping anywhere, then do nothing.
2828
-
2829
- if (state.pipesCount === 0) return this; // just one destination. most common case.
2830
-
2831
- if (state.pipesCount === 1) {
2832
- // passed in one, but it's not the right one.
2833
- if (dest && dest !== state.pipes) return this;
2834
- if (!dest) dest = state.pipes; // got a match.
2835
-
2836
- state.pipes = null;
2837
- state.pipesCount = 0;
2838
- state.flowing = false;
2839
- if (dest) dest.emit('unpipe', this, unpipeInfo);
2840
- return this;
2841
- } // slow case. multiple pipe destinations.
2842
-
2843
-
2844
- if (!dest) {
2845
- // remove all.
2846
- var dests = state.pipes;
2847
- var len = state.pipesCount;
2848
- state.pipes = null;
2849
- state.pipesCount = 0;
2850
- state.flowing = false;
2851
-
2852
- for (var i = 0; i < len; i++) {
2853
- dests[i].emit('unpipe', this, {
2854
- hasUnpiped: false
2855
- });
2856
- }
2857
-
2858
- return this;
2859
- } // try to find the right one.
2860
-
2861
-
2862
- var index = indexOf(state.pipes, dest);
2863
- if (index === -1) return this;
2864
- state.pipes.splice(index, 1);
2865
- state.pipesCount -= 1;
2866
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
2867
- dest.emit('unpipe', this, unpipeInfo);
2868
- return this;
2869
- }; // set up data events if they are asked for
2870
- // Ensure readable listeners eventually get something
2871
-
2872
-
2873
- Readable.prototype.on = function (ev, fn) {
2874
- var res = Stream.prototype.on.call(this, ev, fn);
2875
- var state = this._readableState;
2876
-
2877
- if (ev === 'data') {
2878
- // update readableListening so that resume() may be a no-op
2879
- // a few lines down. This is needed to support once('readable').
2880
- state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
2881
-
2882
- if (state.flowing !== false) this.resume();
2883
- } else if (ev === 'readable') {
2884
- if (!state.endEmitted && !state.readableListening) {
2885
- state.readableListening = state.needReadable = true;
2886
- state.flowing = false;
2887
- state.emittedReadable = false;
2888
- debug('on readable', state.length, state.reading);
2889
-
2890
- if (state.length) {
2891
- emitReadable(this);
2892
- } else if (!state.reading) {
2893
- process.nextTick(nReadingNextTick, this);
2894
- }
2895
- }
2896
- }
2897
-
2898
- return res;
2899
- };
2900
-
2901
- Readable.prototype.addListener = Readable.prototype.on;
2902
-
2903
- Readable.prototype.removeListener = function (ev, fn) {
2904
- var res = Stream.prototype.removeListener.call(this, ev, fn);
2905
-
2906
- if (ev === 'readable') {
2907
- // We need to check if there is someone still listening to
2908
- // readable and reset the state. However this needs to happen
2909
- // after readable has been emitted but before I/O (nextTick) to
2910
- // support once('readable', fn) cycles. This means that calling
2911
- // resume within the same tick will have no
2912
- // effect.
2913
- process.nextTick(updateReadableListening, this);
2914
- }
2915
-
2916
- return res;
2917
- };
2918
-
2919
- Readable.prototype.removeAllListeners = function (ev) {
2920
- var res = Stream.prototype.removeAllListeners.apply(this, arguments);
2921
-
2922
- if (ev === 'readable' || ev === undefined) {
2923
- // We need to check if there is someone still listening to
2924
- // readable and reset the state. However this needs to happen
2925
- // after readable has been emitted but before I/O (nextTick) to
2926
- // support once('readable', fn) cycles. This means that calling
2927
- // resume within the same tick will have no
2928
- // effect.
2929
- process.nextTick(updateReadableListening, this);
2930
- }
2931
-
2932
- return res;
2933
- };
2934
-
2935
- function updateReadableListening(self) {
2936
- var state = self._readableState;
2937
- state.readableListening = self.listenerCount('readable') > 0;
2938
-
2939
- if (state.resumeScheduled && !state.paused) {
2940
- // flowing needs to be set to true now, otherwise
2941
- // the upcoming resume will not flow.
2942
- state.flowing = true; // crude way to check if we should resume
2943
- } else if (self.listenerCount('data') > 0) {
2944
- self.resume();
2945
- }
2946
- }
2947
-
2948
- function nReadingNextTick(self) {
2949
- debug('readable nexttick read 0');
2950
- self.read(0);
2951
- } // pause() and resume() are remnants of the legacy readable stream API
2952
- // If the user uses them, then switch into old mode.
2953
-
2954
-
2955
- Readable.prototype.resume = function () {
2956
- var state = this._readableState;
2957
-
2958
- if (!state.flowing) {
2959
- debug('resume'); // we flow only if there is no one listening
2960
- // for readable, but we still have to call
2961
- // resume()
2962
-
2963
- state.flowing = !state.readableListening;
2964
- resume(this, state);
2965
- }
2966
-
2967
- state.paused = false;
2968
- return this;
2969
- };
2970
-
2971
- function resume(stream, state) {
2972
- if (!state.resumeScheduled) {
2973
- state.resumeScheduled = true;
2974
- process.nextTick(resume_, stream, state);
2975
- }
2976
- }
2977
-
2978
- function resume_(stream, state) {
2979
- debug('resume', state.reading);
2980
-
2981
- if (!state.reading) {
2982
- stream.read(0);
2983
- }
2984
-
2985
- state.resumeScheduled = false;
2986
- stream.emit('resume');
2987
- flow(stream);
2988
- if (state.flowing && !state.reading) stream.read(0);
2989
- }
2990
-
2991
- Readable.prototype.pause = function () {
2992
- debug('call pause flowing=%j', this._readableState.flowing);
2993
-
2994
- if (this._readableState.flowing !== false) {
2995
- debug('pause');
2996
- this._readableState.flowing = false;
2997
- this.emit('pause');
2998
- }
2999
-
3000
- this._readableState.paused = true;
3001
- return this;
3002
- };
3003
-
3004
- function flow(stream) {
3005
- var state = stream._readableState;
3006
- debug('flow', state.flowing);
3007
-
3008
- while (state.flowing && stream.read() !== null) {
3009
- }
3010
- } // wrap an old-style stream as the async data source.
3011
- // This is *not* part of the readable stream interface.
3012
- // It is an ugly unfortunate mess of history.
3013
-
3014
-
3015
- Readable.prototype.wrap = function (stream) {
3016
- var _this = this;
3017
-
3018
- var state = this._readableState;
3019
- var paused = false;
3020
- stream.on('end', function () {
3021
- debug('wrapped end');
3022
-
3023
- if (state.decoder && !state.ended) {
3024
- var chunk = state.decoder.end();
3025
- if (chunk && chunk.length) _this.push(chunk);
3026
- }
3027
-
3028
- _this.push(null);
3029
- });
3030
- stream.on('data', function (chunk) {
3031
- debug('wrapped data');
3032
- if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
3033
-
3034
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
3035
-
3036
- var ret = _this.push(chunk);
3037
-
3038
- if (!ret) {
3039
- paused = true;
3040
- stream.pause();
3041
- }
3042
- }); // proxy all the other methods.
3043
- // important when wrapping filters and duplexes.
3044
-
3045
- for (var i in stream) {
3046
- if (this[i] === undefined && typeof stream[i] === 'function') {
3047
- this[i] = function methodWrap(method) {
3048
- return function methodWrapReturnFunction() {
3049
- return stream[method].apply(stream, arguments);
3050
- };
3051
- }(i);
3052
- }
3053
- } // proxy certain important events.
3054
-
3055
-
3056
- for (var n = 0; n < kProxyEvents.length; n++) {
3057
- stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
3058
- } // when we try to consume some more bytes, simply unpause the
3059
- // underlying stream.
3060
-
3061
-
3062
- this._read = function (n) {
3063
- debug('wrapped _read', n);
3064
-
3065
- if (paused) {
3066
- paused = false;
3067
- stream.resume();
3068
- }
3069
- };
3070
-
3071
- return this;
3072
- };
3073
-
3074
- if (typeof Symbol === 'function') {
3075
- Readable.prototype[Symbol.asyncIterator] = function () {
3076
- if (createReadableStreamAsyncIterator === undefined) {
3077
- createReadableStreamAsyncIterator = requireAsync_iterator();
3078
- }
3079
-
3080
- return createReadableStreamAsyncIterator(this);
3081
- };
3082
- }
3083
-
3084
- Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
3085
- // making it explicit this property is not enumerable
3086
- // because otherwise some prototype manipulation in
3087
- // userland will fail
3088
- enumerable: false,
3089
- get: function get() {
3090
- return this._readableState.highWaterMark;
3091
- }
3092
- });
3093
- Object.defineProperty(Readable.prototype, 'readableBuffer', {
3094
- // making it explicit this property is not enumerable
3095
- // because otherwise some prototype manipulation in
3096
- // userland will fail
3097
- enumerable: false,
3098
- get: function get() {
3099
- return this._readableState && this._readableState.buffer;
3100
- }
3101
- });
3102
- Object.defineProperty(Readable.prototype, 'readableFlowing', {
3103
- // making it explicit this property is not enumerable
3104
- // because otherwise some prototype manipulation in
3105
- // userland will fail
3106
- enumerable: false,
3107
- get: function get() {
3108
- return this._readableState.flowing;
3109
- },
3110
- set: function set(state) {
3111
- if (this._readableState) {
3112
- this._readableState.flowing = state;
3113
- }
3114
- }
3115
- }); // exposed for testing purposes only.
3116
-
3117
- Readable._fromList = fromList;
3118
- Object.defineProperty(Readable.prototype, 'readableLength', {
3119
- // making it explicit this property is not enumerable
3120
- // because otherwise some prototype manipulation in
3121
- // userland will fail
3122
- enumerable: false,
3123
- get: function get() {
3124
- return this._readableState.length;
3125
- }
3126
- }); // Pluck off n bytes from an array of buffers.
3127
- // Length is the combined lengths of all the buffers in the list.
3128
- // This function is designed to be inlinable, so please take care when making
3129
- // changes to the function body.
3130
-
3131
- function fromList(n, state) {
3132
- // nothing buffered
3133
- if (state.length === 0) return null;
3134
- var ret;
3135
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
3136
- // read it all, truncate the list
3137
- if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
3138
- state.buffer.clear();
3139
- } else {
3140
- // read part of list
3141
- ret = state.buffer.consume(n, state.decoder);
3142
- }
3143
- return ret;
3144
- }
3145
-
3146
- function endReadable(stream) {
3147
- var state = stream._readableState;
3148
- debug('endReadable', state.endEmitted);
3149
-
3150
- if (!state.endEmitted) {
3151
- state.ended = true;
3152
- process.nextTick(endReadableNT, state, stream);
3153
- }
3154
- }
3155
-
3156
- function endReadableNT(state, stream) {
3157
- debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
3158
-
3159
- if (!state.endEmitted && state.length === 0) {
3160
- state.endEmitted = true;
3161
- stream.readable = false;
3162
- stream.emit('end');
3163
-
3164
- if (state.autoDestroy) {
3165
- // In case of duplex streams we need a way to detect
3166
- // if the writable side is ready for autoDestroy as well
3167
- var wState = stream._writableState;
3168
-
3169
- if (!wState || wState.autoDestroy && wState.finished) {
3170
- stream.destroy();
3171
- }
3172
- }
3173
- }
3174
- }
3175
-
3176
- if (typeof Symbol === 'function') {
3177
- Readable.from = function (iterable, opts) {
3178
- if (from === undefined) {
3179
- from = requireFrom();
3180
- }
3181
-
3182
- return from(Readable, iterable, opts);
3183
- };
3184
- }
3185
-
3186
- function indexOf(xs, x) {
3187
- for (var i = 0, l = xs.length; i < l; i++) {
3188
- if (xs[i] === x) return i;
3189
- }
3190
-
3191
- return -1;
3192
- }
3193
- return _stream_readable;
3194
- }
3195
-
3196
- var _stream_transform;
3197
- var hasRequired_stream_transform;
3198
-
3199
- function require_stream_transform () {
3200
- if (hasRequired_stream_transform) return _stream_transform;
3201
- hasRequired_stream_transform = 1;
3202
-
3203
- _stream_transform = Transform;
3204
-
3205
- var _require$codes = requireErrors().codes,
3206
- ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
3207
- ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
3208
- ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
3209
- ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
3210
-
3211
- var Duplex = require_stream_duplex();
3212
-
3213
- requireInherits()(Transform, Duplex);
3214
-
3215
- function afterTransform(er, data) {
3216
- var ts = this._transformState;
3217
- ts.transforming = false;
3218
- var cb = ts.writecb;
3219
-
3220
- if (cb === null) {
3221
- return this.emit('error', new ERR_MULTIPLE_CALLBACK());
3222
- }
3223
-
3224
- ts.writechunk = null;
3225
- ts.writecb = null;
3226
- if (data != null) // single equals check for both `null` and `undefined`
3227
- this.push(data);
3228
- cb(er);
3229
- var rs = this._readableState;
3230
- rs.reading = false;
3231
-
3232
- if (rs.needReadable || rs.length < rs.highWaterMark) {
3233
- this._read(rs.highWaterMark);
3234
- }
3235
- }
3236
-
3237
- function Transform(options) {
3238
- if (!(this instanceof Transform)) return new Transform(options);
3239
- Duplex.call(this, options);
3240
- this._transformState = {
3241
- afterTransform: afterTransform.bind(this),
3242
- needTransform: false,
3243
- transforming: false,
3244
- writecb: null,
3245
- writechunk: null,
3246
- writeencoding: null
3247
- }; // start out asking for a readable event once data is transformed.
3248
-
3249
- this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
3250
- // that Readable wants before the first _read call, so unset the
3251
- // sync guard flag.
3252
-
3253
- this._readableState.sync = false;
3254
-
3255
- if (options) {
3256
- if (typeof options.transform === 'function') this._transform = options.transform;
3257
- if (typeof options.flush === 'function') this._flush = options.flush;
3258
- } // When the writable side finishes, then flush out anything remaining.
3259
-
3260
-
3261
- this.on('prefinish', prefinish);
3262
- }
3263
-
3264
- function prefinish() {
3265
- var _this = this;
3266
-
3267
- if (typeof this._flush === 'function' && !this._readableState.destroyed) {
3268
- this._flush(function (er, data) {
3269
- done(_this, er, data);
3270
- });
3271
- } else {
3272
- done(this, null, null);
3273
- }
3274
- }
3275
-
3276
- Transform.prototype.push = function (chunk, encoding) {
3277
- this._transformState.needTransform = false;
3278
- return Duplex.prototype.push.call(this, chunk, encoding);
3279
- }; // This is the part where you do stuff!
3280
- // override this function in implementation classes.
3281
- // 'chunk' is an input chunk.
3282
- //
3283
- // Call `push(newChunk)` to pass along transformed output
3284
- // to the readable side. You may call 'push' zero or more times.
3285
- //
3286
- // Call `cb(err)` when you are done with this chunk. If you pass
3287
- // an error, then that'll put the hurt on the whole operation. If you
3288
- // never call cb(), then you'll never get another chunk.
3289
-
3290
-
3291
- Transform.prototype._transform = function (chunk, encoding, cb) {
3292
- cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
3293
- };
3294
-
3295
- Transform.prototype._write = function (chunk, encoding, cb) {
3296
- var ts = this._transformState;
3297
- ts.writecb = cb;
3298
- ts.writechunk = chunk;
3299
- ts.writeencoding = encoding;
3300
-
3301
- if (!ts.transforming) {
3302
- var rs = this._readableState;
3303
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
3304
- }
3305
- }; // Doesn't matter what the args are here.
3306
- // _transform does all the work.
3307
- // That we got here means that the readable side wants more data.
3308
-
3309
-
3310
- Transform.prototype._read = function (n) {
3311
- var ts = this._transformState;
3312
-
3313
- if (ts.writechunk !== null && !ts.transforming) {
3314
- ts.transforming = true;
3315
-
3316
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
3317
- } else {
3318
- // mark that we need a transform, so that any data that comes in
3319
- // will get processed, now that we've asked for it.
3320
- ts.needTransform = true;
3321
- }
3322
- };
3323
-
3324
- Transform.prototype._destroy = function (err, cb) {
3325
- Duplex.prototype._destroy.call(this, err, function (err2) {
3326
- cb(err2);
3327
- });
3328
- };
3329
-
3330
- function done(stream, er, data) {
3331
- if (er) return stream.emit('error', er);
3332
- if (data != null) // single equals check for both `null` and `undefined`
3333
- stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
3334
- // if there's nothing in the write buffer, then that means
3335
- // that nothing more will ever be provided
3336
-
3337
- if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
3338
- if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
3339
- return stream.push(null);
3340
- }
3341
- return _stream_transform;
3342
- }
3343
-
3344
- var _stream_passthrough;
3345
- var hasRequired_stream_passthrough;
3346
-
3347
- function require_stream_passthrough () {
3348
- if (hasRequired_stream_passthrough) return _stream_passthrough;
3349
- hasRequired_stream_passthrough = 1;
3350
-
3351
- _stream_passthrough = PassThrough;
3352
-
3353
- var Transform = require_stream_transform();
3354
-
3355
- requireInherits()(PassThrough, Transform);
3356
-
3357
- function PassThrough(options) {
3358
- if (!(this instanceof PassThrough)) return new PassThrough(options);
3359
- Transform.call(this, options);
3360
- }
3361
-
3362
- PassThrough.prototype._transform = function (chunk, encoding, cb) {
3363
- cb(null, chunk);
3364
- };
3365
- return _stream_passthrough;
3366
- }
3367
-
3368
- var pipeline_1;
3369
- var hasRequiredPipeline;
3370
-
3371
- function requirePipeline () {
3372
- if (hasRequiredPipeline) return pipeline_1;
3373
- hasRequiredPipeline = 1;
3374
-
3375
- var eos;
3376
-
3377
- function once(callback) {
3378
- var called = false;
3379
- return function () {
3380
- if (called) return;
3381
- called = true;
3382
- callback.apply(void 0, arguments);
3383
- };
3384
- }
3385
-
3386
- var _require$codes = requireErrors().codes,
3387
- ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
3388
- ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
3389
-
3390
- function noop(err) {
3391
- // Rethrow the error if it exists to avoid swallowing it
3392
- if (err) throw err;
3393
- }
3394
-
3395
- function isRequest(stream) {
3396
- return stream.setHeader && typeof stream.abort === 'function';
3397
- }
3398
-
3399
- function destroyer(stream, reading, writing, callback) {
3400
- callback = once(callback);
3401
- var closed = false;
3402
- stream.on('close', function () {
3403
- closed = true;
3404
- });
3405
- if (eos === undefined) eos = requireEndOfStream();
3406
- eos(stream, {
3407
- readable: reading,
3408
- writable: writing
3409
- }, function (err) {
3410
- if (err) return callback(err);
3411
- closed = true;
3412
- callback();
3413
- });
3414
- var destroyed = false;
3415
- return function (err) {
3416
- if (closed) return;
3417
- if (destroyed) return;
3418
- destroyed = true; // request.destroy just do .end - .abort is what we want
3419
-
3420
- if (isRequest(stream)) return stream.abort();
3421
- if (typeof stream.destroy === 'function') return stream.destroy();
3422
- callback(err || new ERR_STREAM_DESTROYED('pipe'));
3423
- };
3424
- }
3425
-
3426
- function call(fn) {
3427
- fn();
3428
- }
3429
-
3430
- function pipe(from, to) {
3431
- return from.pipe(to);
3432
- }
3433
-
3434
- function popCallback(streams) {
3435
- if (!streams.length) return noop;
3436
- if (typeof streams[streams.length - 1] !== 'function') return noop;
3437
- return streams.pop();
3438
- }
3439
-
3440
- function pipeline() {
3441
- for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
3442
- streams[_key] = arguments[_key];
3443
- }
3444
-
3445
- var callback = popCallback(streams);
3446
- if (Array.isArray(streams[0])) streams = streams[0];
3447
-
3448
- if (streams.length < 2) {
3449
- throw new ERR_MISSING_ARGS('streams');
3450
- }
3451
-
3452
- var error;
3453
- var destroys = streams.map(function (stream, i) {
3454
- var reading = i < streams.length - 1;
3455
- var writing = i > 0;
3456
- return destroyer(stream, reading, writing, function (err) {
3457
- if (!error) error = err;
3458
- if (err) destroys.forEach(call);
3459
- if (reading) return;
3460
- destroys.forEach(call);
3461
- callback(error);
3462
- });
3463
- });
3464
- return streams.reduce(pipe);
3465
- }
3466
-
3467
- pipeline_1 = pipeline;
3468
- return pipeline_1;
3469
- }
3470
-
3471
- var hasRequiredReadable;
3472
-
3473
- function requireReadable () {
3474
- if (hasRequiredReadable) return readable.exports;
3475
- hasRequiredReadable = 1;
3476
- (function (module, exports) {
3477
- var Stream = require$$0$1;
3478
- if (process.env.READABLE_STREAM === 'disable' && Stream) {
3479
- module.exports = Stream.Readable;
3480
- Object.assign(module.exports, Stream);
3481
- module.exports.Stream = Stream;
3482
- } else {
3483
- exports = module.exports = require_stream_readable();
3484
- exports.Stream = Stream || exports;
3485
- exports.Readable = exports;
3486
- exports.Writable = require_stream_writable();
3487
- exports.Duplex = require_stream_duplex();
3488
- exports.Transform = require_stream_transform();
3489
- exports.PassThrough = require_stream_passthrough();
3490
- exports.finished = requireEndOfStream();
3491
- exports.pipeline = requirePipeline();
3492
- }
3493
- } (readable, readable.exports));
3494
- return readable.exports;
3495
- }
3496
-
3497
- var keccak$1;
3498
- var hasRequiredKeccak$1;
3499
-
3500
- function requireKeccak$1 () {
3501
- if (hasRequiredKeccak$1) return keccak$1;
3502
- hasRequiredKeccak$1 = 1;
3503
- const { Transform } = requireReadable();
3504
-
3505
- keccak$1 = (KeccakState) => class Keccak extends Transform {
3506
- constructor (rate, capacity, delimitedSuffix, hashBitLength, options) {
3507
- super(options);
3508
-
3509
- this._rate = rate;
3510
- this._capacity = capacity;
3511
- this._delimitedSuffix = delimitedSuffix;
3512
- this._hashBitLength = hashBitLength;
3513
- this._options = options;
3514
-
3515
- this._state = new KeccakState();
3516
- this._state.initialize(rate, capacity);
3517
- this._finalized = false;
3518
- }
3519
-
3520
- _transform (chunk, encoding, callback) {
3521
- let error = null;
3522
- try {
3523
- this.update(chunk, encoding);
3524
- } catch (err) {
3525
- error = err;
3526
- }
3527
-
3528
- callback(error);
3529
- }
3530
-
3531
- _flush (callback) {
3532
- let error = null;
3533
- try {
3534
- this.push(this.digest());
3535
- } catch (err) {
3536
- error = err;
3537
- }
3538
-
3539
- callback(error);
3540
- }
3541
-
3542
- update (data, encoding) {
3543
- if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
3544
- if (this._finalized) throw new Error('Digest already called')
3545
- if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding);
3546
-
3547
- this._state.absorb(data);
3548
-
3549
- return this
3550
- }
3551
-
3552
- digest (encoding) {
3553
- if (this._finalized) throw new Error('Digest already called')
3554
- this._finalized = true;
3555
-
3556
- if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix);
3557
- let digest = this._state.squeeze(this._hashBitLength / 8);
3558
- if (encoding !== undefined) digest = digest.toString(encoding);
3559
-
3560
- this._resetState();
3561
-
3562
- return digest
3563
- }
3564
-
3565
- // remove result from memory
3566
- _resetState () {
3567
- this._state.initialize(this._rate, this._capacity);
3568
- return this
3569
- }
3570
-
3571
- // because sometimes we need hash right now and little later
3572
- _clone () {
3573
- const clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options);
3574
- this._state.copy(clone._state);
3575
- clone._finalized = this._finalized;
3576
-
3577
- return clone
3578
- }
3579
- };
3580
- return keccak$1;
3581
- }
3582
-
3583
- var shake;
3584
- var hasRequiredShake;
3585
-
3586
- function requireShake () {
3587
- if (hasRequiredShake) return shake;
3588
- hasRequiredShake = 1;
3589
- const { Transform } = requireReadable();
3590
-
3591
- shake = (KeccakState) => class Shake extends Transform {
3592
- constructor (rate, capacity, delimitedSuffix, options) {
3593
- super(options);
3594
-
3595
- this._rate = rate;
3596
- this._capacity = capacity;
3597
- this._delimitedSuffix = delimitedSuffix;
3598
- this._options = options;
3599
-
3600
- this._state = new KeccakState();
3601
- this._state.initialize(rate, capacity);
3602
- this._finalized = false;
3603
- }
3604
-
3605
- _transform (chunk, encoding, callback) {
3606
- let error = null;
3607
- try {
3608
- this.update(chunk, encoding);
3609
- } catch (err) {
3610
- error = err;
3611
- }
3612
-
3613
- callback(error);
3614
- }
3615
-
3616
- _flush () {}
3617
-
3618
- _read (size) {
3619
- this.push(this.squeeze(size));
3620
- }
3621
-
3622
- update (data, encoding) {
3623
- if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
3624
- if (this._finalized) throw new Error('Squeeze already called')
3625
- if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding);
3626
-
3627
- this._state.absorb(data);
3628
-
3629
- return this
3630
- }
3631
-
3632
- squeeze (dataByteLength, encoding) {
3633
- if (!this._finalized) {
3634
- this._finalized = true;
3635
- this._state.absorbLastFewBits(this._delimitedSuffix);
3636
- }
3637
-
3638
- let data = this._state.squeeze(dataByteLength);
3639
- if (encoding !== undefined) data = data.toString(encoding);
3640
-
3641
- return data
3642
- }
3643
-
3644
- _resetState () {
3645
- this._state.initialize(this._rate, this._capacity);
3646
- return this
3647
- }
3648
-
3649
- _clone () {
3650
- const clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options);
3651
- this._state.copy(clone._state);
3652
- clone._finalized = this._finalized;
3653
-
3654
- return clone
3655
- }
3656
- };
3657
- return shake;
3658
- }
3659
-
3660
- var api;
3661
- var hasRequiredApi;
3662
-
3663
- function requireApi () {
3664
- if (hasRequiredApi) return api;
3665
- hasRequiredApi = 1;
3666
- const createKeccak = requireKeccak$1();
3667
- const createShake = requireShake();
3668
-
3669
- api = function (KeccakState) {
3670
- const Keccak = createKeccak(KeccakState);
3671
- const Shake = createShake(KeccakState);
3672
-
3673
- return function (algorithm, options) {
3674
- const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm;
3675
- switch (hash) {
3676
- case 'keccak224': return new Keccak(1152, 448, null, 224, options)
3677
- case 'keccak256': return new Keccak(1088, 512, null, 256, options)
3678
- case 'keccak384': return new Keccak(832, 768, null, 384, options)
3679
- case 'keccak512': return new Keccak(576, 1024, null, 512, options)
3680
-
3681
- case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)
3682
- case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)
3683
- case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)
3684
- case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)
3685
-
3686
- case 'shake128': return new Shake(1344, 256, 0x1f, options)
3687
- case 'shake256': return new Shake(1088, 512, 0x1f, options)
3688
-
3689
- default: throw new Error('Invald algorithm: ' + algorithm)
3690
- }
3691
- }
3692
- };
3693
- return api;
3694
- }
3695
-
3696
- function commonjsRequire(path) {
3697
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
3698
- }
3699
-
3700
- var nodeGypBuild;
3701
- var hasRequiredNodeGypBuild;
3702
-
3703
- function requireNodeGypBuild () {
3704
- if (hasRequiredNodeGypBuild) return nodeGypBuild;
3705
- hasRequiredNodeGypBuild = 1;
3706
- var fs = require$$0$3;
3707
- var path = require$$1$2;
3708
- var os = require$$2$2;
3709
-
3710
- // Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'
3711
- var runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : commonjsRequire; // eslint-disable-line
3712
-
3713
- var vars = (process.config && process.config.variables) || {};
3714
- var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
3715
- var abi = process.versions.modules; // TODO: support old node where this is undef
3716
- var runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node');
3717
-
3718
- var arch = process.env.npm_config_arch || os.arch();
3719
- var platform = process.env.npm_config_platform || os.platform();
3720
- var libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc');
3721
- var armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || '';
3722
- var uv = (process.versions.uv || '').split('.')[0];
3723
-
3724
- nodeGypBuild = load;
3725
-
3726
- function load (dir) {
3727
- return runtimeRequire(load.path(dir))
3728
- }
3729
-
3730
- load.path = function (dir) {
3731
- dir = path.resolve(dir || '.');
3732
-
3733
- try {
3734
- var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_');
3735
- if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD'];
3736
- } catch (err) {}
3737
-
3738
- if (!prebuildsOnly) {
3739
- var release = getFirst(path.join(dir, 'build/Release'), matchBuild);
3740
- if (release) return release
3741
-
3742
- var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild);
3743
- if (debug) return debug
3744
- }
3745
-
3746
- var prebuild = resolve(dir);
3747
- if (prebuild) return prebuild
3748
-
3749
- var nearby = resolve(path.dirname(process.execPath));
3750
- if (nearby) return nearby
3751
-
3752
- var target = [
3753
- 'platform=' + platform,
3754
- 'arch=' + arch,
3755
- 'runtime=' + runtime,
3756
- 'abi=' + abi,
3757
- 'uv=' + uv,
3758
- armv ? 'armv=' + armv : '',
3759
- 'libc=' + libc,
3760
- 'node=' + process.versions.node,
3761
- process.versions.electron ? 'electron=' + process.versions.electron : '',
3762
- typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line
3763
- ].filter(Boolean).join(' ');
3764
-
3765
- throw new Error('No native build was found for ' + target + '\n loaded from: ' + dir + '\n')
3766
-
3767
- function resolve (dir) {
3768
- // Find matching "prebuilds/<platform>-<arch>" directory
3769
- var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple);
3770
- var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
3771
- if (!tuple) return
3772
-
3773
- // Find most specific flavor first
3774
- var prebuilds = path.join(dir, 'prebuilds', tuple.name);
3775
- var parsed = readdirSync(prebuilds).map(parseTags);
3776
- var candidates = parsed.filter(matchTags(runtime, abi));
3777
- var winner = candidates.sort(compareTags(runtime))[0];
3778
- if (winner) return path.join(prebuilds, winner.file)
3779
- }
3780
- };
3781
-
3782
- function readdirSync (dir) {
3783
- try {
3784
- return fs.readdirSync(dir)
3785
- } catch (err) {
3786
- return []
3787
- }
3788
- }
3789
-
3790
- function getFirst (dir, filter) {
3791
- var files = readdirSync(dir).filter(filter);
3792
- return files[0] && path.join(dir, files[0])
3793
- }
3794
-
3795
- function matchBuild (name) {
3796
- return /\.node$/.test(name)
3797
- }
3798
-
3799
- function parseTuple (name) {
3800
- // Example: darwin-x64+arm64
3801
- var arr = name.split('-');
3802
- if (arr.length !== 2) return
3803
-
3804
- var platform = arr[0];
3805
- var architectures = arr[1].split('+');
3806
-
3807
- if (!platform) return
3808
- if (!architectures.length) return
3809
- if (!architectures.every(Boolean)) return
3810
-
3811
- return { name, platform, architectures }
3812
- }
3813
-
3814
- function matchTuple (platform, arch) {
3815
- return function (tuple) {
3816
- if (tuple == null) return false
3817
- if (tuple.platform !== platform) return false
3818
- return tuple.architectures.includes(arch)
3819
- }
3820
- }
3821
-
3822
- function compareTuples (a, b) {
3823
- // Prefer single-arch prebuilds over multi-arch
3824
- return a.architectures.length - b.architectures.length
3825
- }
3826
-
3827
- function parseTags (file) {
3828
- var arr = file.split('.');
3829
- var extension = arr.pop();
3830
- var tags = { file: file, specificity: 0 };
3831
-
3832
- if (extension !== 'node') return
3833
-
3834
- for (var i = 0; i < arr.length; i++) {
3835
- var tag = arr[i];
3836
-
3837
- if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {
3838
- tags.runtime = tag;
3839
- } else if (tag === 'napi') {
3840
- tags.napi = true;
3841
- } else if (tag.slice(0, 3) === 'abi') {
3842
- tags.abi = tag.slice(3);
3843
- } else if (tag.slice(0, 2) === 'uv') {
3844
- tags.uv = tag.slice(2);
3845
- } else if (tag.slice(0, 4) === 'armv') {
3846
- tags.armv = tag.slice(4);
3847
- } else if (tag === 'glibc' || tag === 'musl') {
3848
- tags.libc = tag;
3849
- } else {
3850
- continue
3851
- }
3852
-
3853
- tags.specificity++;
3854
- }
3855
-
3856
- return tags
3857
- }
3858
-
3859
- function matchTags (runtime, abi) {
3860
- return function (tags) {
3861
- if (tags == null) return false
3862
- if (tags.runtime !== runtime && !runtimeAgnostic(tags)) return false
3863
- if (tags.abi !== abi && !tags.napi) return false
3864
- if (tags.uv && tags.uv !== uv) return false
3865
- if (tags.armv && tags.armv !== armv) return false
3866
- if (tags.libc && tags.libc !== libc) return false
3867
-
3868
- return true
3869
- }
3870
- }
3871
-
3872
- function runtimeAgnostic (tags) {
3873
- return tags.runtime === 'node' && tags.napi
3874
- }
3875
-
3876
- function compareTags (runtime) {
3877
- // Precedence: non-agnostic runtime, abi over napi, then by specificity.
3878
- return function (a, b) {
3879
- if (a.runtime !== b.runtime) {
3880
- return a.runtime === runtime ? -1 : 1
3881
- } else if (a.abi !== b.abi) {
3882
- return a.abi ? -1 : 1
3883
- } else if (a.specificity !== b.specificity) {
3884
- return a.specificity > b.specificity ? -1 : 1
3885
- } else {
3886
- return 0
3887
- }
3888
- }
3889
- }
3890
-
3891
- function isNwjs () {
3892
- return !!(process.versions && process.versions.nw)
3893
- }
3894
-
3895
- function isElectron () {
3896
- if (process.versions && process.versions.electron) return true
3897
- if (process.env.ELECTRON_RUN_AS_NODE) return true
3898
- return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'
3899
- }
3900
-
3901
- function isAlpine (platform) {
3902
- return platform === 'linux' && fs.existsSync('/etc/alpine-release')
3903
- }
3904
-
3905
- // Exposed for unit tests
3906
- // TODO: move to lib
3907
- load.parseTags = parseTags;
3908
- load.matchTags = matchTags;
3909
- load.compareTags = compareTags;
3910
- load.parseTuple = parseTuple;
3911
- load.matchTuple = matchTuple;
3912
- load.compareTuples = compareTuples;
3913
- return nodeGypBuild;
3914
- }
3915
-
3916
- var bindings;
3917
- var hasRequiredBindings;
3918
-
3919
- function requireBindings () {
3920
- if (hasRequiredBindings) return bindings;
3921
- hasRequiredBindings = 1;
3922
- bindings = requireApi()(requireNodeGypBuild()(__dirname));
3923
- return bindings;
3924
- }
3925
-
3926
- var keccakStateUnroll = {};
3927
-
3928
- var hasRequiredKeccakStateUnroll;
3929
-
3930
- function requireKeccakStateUnroll () {
3931
- if (hasRequiredKeccakStateUnroll) return keccakStateUnroll;
3932
- hasRequiredKeccakStateUnroll = 1;
3933
- const P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
3934
-
3935
- keccakStateUnroll.p1600 = function (s) {
3936
- for (let round = 0; round < 24; ++round) {
3937
- // theta
3938
- const lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
3939
- const hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
3940
- const lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
3941
- const hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
3942
- const lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
3943
- const hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
3944
- const lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
3945
- const hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
3946
- const lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
3947
- const hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
3948
-
3949
- let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31);
3950
- let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31);
3951
- const t1slo0 = s[0] ^ lo;
3952
- const t1shi0 = s[1] ^ hi;
3953
- const t1slo5 = s[10] ^ lo;
3954
- const t1shi5 = s[11] ^ hi;
3955
- const t1slo10 = s[20] ^ lo;
3956
- const t1shi10 = s[21] ^ hi;
3957
- const t1slo15 = s[30] ^ lo;
3958
- const t1shi15 = s[31] ^ hi;
3959
- const t1slo20 = s[40] ^ lo;
3960
- const t1shi20 = s[41] ^ hi;
3961
- lo = lo0 ^ (lo2 << 1 | hi2 >>> 31);
3962
- hi = hi0 ^ (hi2 << 1 | lo2 >>> 31);
3963
- const t1slo1 = s[2] ^ lo;
3964
- const t1shi1 = s[3] ^ hi;
3965
- const t1slo6 = s[12] ^ lo;
3966
- const t1shi6 = s[13] ^ hi;
3967
- const t1slo11 = s[22] ^ lo;
3968
- const t1shi11 = s[23] ^ hi;
3969
- const t1slo16 = s[32] ^ lo;
3970
- const t1shi16 = s[33] ^ hi;
3971
- const t1slo21 = s[42] ^ lo;
3972
- const t1shi21 = s[43] ^ hi;
3973
- lo = lo1 ^ (lo3 << 1 | hi3 >>> 31);
3974
- hi = hi1 ^ (hi3 << 1 | lo3 >>> 31);
3975
- const t1slo2 = s[4] ^ lo;
3976
- const t1shi2 = s[5] ^ hi;
3977
- const t1slo7 = s[14] ^ lo;
3978
- const t1shi7 = s[15] ^ hi;
3979
- const t1slo12 = s[24] ^ lo;
3980
- const t1shi12 = s[25] ^ hi;
3981
- const t1slo17 = s[34] ^ lo;
3982
- const t1shi17 = s[35] ^ hi;
3983
- const t1slo22 = s[44] ^ lo;
3984
- const t1shi22 = s[45] ^ hi;
3985
- lo = lo2 ^ (lo4 << 1 | hi4 >>> 31);
3986
- hi = hi2 ^ (hi4 << 1 | lo4 >>> 31);
3987
- const t1slo3 = s[6] ^ lo;
3988
- const t1shi3 = s[7] ^ hi;
3989
- const t1slo8 = s[16] ^ lo;
3990
- const t1shi8 = s[17] ^ hi;
3991
- const t1slo13 = s[26] ^ lo;
3992
- const t1shi13 = s[27] ^ hi;
3993
- const t1slo18 = s[36] ^ lo;
3994
- const t1shi18 = s[37] ^ hi;
3995
- const t1slo23 = s[46] ^ lo;
3996
- const t1shi23 = s[47] ^ hi;
3997
- lo = lo3 ^ (lo0 << 1 | hi0 >>> 31);
3998
- hi = hi3 ^ (hi0 << 1 | lo0 >>> 31);
3999
- const t1slo4 = s[8] ^ lo;
4000
- const t1shi4 = s[9] ^ hi;
4001
- const t1slo9 = s[18] ^ lo;
4002
- const t1shi9 = s[19] ^ hi;
4003
- const t1slo14 = s[28] ^ lo;
4004
- const t1shi14 = s[29] ^ hi;
4005
- const t1slo19 = s[38] ^ lo;
4006
- const t1shi19 = s[39] ^ hi;
4007
- const t1slo24 = s[48] ^ lo;
4008
- const t1shi24 = s[49] ^ hi;
4009
-
4010
- // rho & pi
4011
- const t2slo0 = t1slo0;
4012
- const t2shi0 = t1shi0;
4013
- const t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28);
4014
- const t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28);
4015
- const t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29);
4016
- const t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29);
4017
- const t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23);
4018
- const t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23);
4019
- const t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14);
4020
- const t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14);
4021
- const t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31);
4022
- const t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31);
4023
- const t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20);
4024
- const t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20);
4025
- const t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22);
4026
- const t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22);
4027
- const t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19);
4028
- const t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19);
4029
- const t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30);
4030
- const t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30);
4031
- const t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2);
4032
- const t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2);
4033
- const t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26);
4034
- const t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26);
4035
- const t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21);
4036
- const t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21);
4037
- const t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17);
4038
- const t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17);
4039
- const t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3);
4040
- const t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3);
4041
- const t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4);
4042
- const t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4);
4043
- const t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9);
4044
- const t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9);
4045
- const t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7);
4046
- const t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7);
4047
- const t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11);
4048
- const t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11);
4049
- const t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8);
4050
- const t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8);
4051
- const t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5);
4052
- const t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5);
4053
- const t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12);
4054
- const t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12);
4055
- const t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25);
4056
- const t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25);
4057
- const t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24);
4058
- const t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24);
4059
- const t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18);
4060
- const t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18);
4061
-
4062
- // chi
4063
- s[0] = t2slo0 ^ (~t2slo1 & t2slo2);
4064
- s[1] = t2shi0 ^ (~t2shi1 & t2shi2);
4065
- s[10] = t2slo5 ^ (~t2slo6 & t2slo7);
4066
- s[11] = t2shi5 ^ (~t2shi6 & t2shi7);
4067
- s[20] = t2slo10 ^ (~t2slo11 & t2slo12);
4068
- s[21] = t2shi10 ^ (~t2shi11 & t2shi12);
4069
- s[30] = t2slo15 ^ (~t2slo16 & t2slo17);
4070
- s[31] = t2shi15 ^ (~t2shi16 & t2shi17);
4071
- s[40] = t2slo20 ^ (~t2slo21 & t2slo22);
4072
- s[41] = t2shi20 ^ (~t2shi21 & t2shi22);
4073
- s[2] = t2slo1 ^ (~t2slo2 & t2slo3);
4074
- s[3] = t2shi1 ^ (~t2shi2 & t2shi3);
4075
- s[12] = t2slo6 ^ (~t2slo7 & t2slo8);
4076
- s[13] = t2shi6 ^ (~t2shi7 & t2shi8);
4077
- s[22] = t2slo11 ^ (~t2slo12 & t2slo13);
4078
- s[23] = t2shi11 ^ (~t2shi12 & t2shi13);
4079
- s[32] = t2slo16 ^ (~t2slo17 & t2slo18);
4080
- s[33] = t2shi16 ^ (~t2shi17 & t2shi18);
4081
- s[42] = t2slo21 ^ (~t2slo22 & t2slo23);
4082
- s[43] = t2shi21 ^ (~t2shi22 & t2shi23);
4083
- s[4] = t2slo2 ^ (~t2slo3 & t2slo4);
4084
- s[5] = t2shi2 ^ (~t2shi3 & t2shi4);
4085
- s[14] = t2slo7 ^ (~t2slo8 & t2slo9);
4086
- s[15] = t2shi7 ^ (~t2shi8 & t2shi9);
4087
- s[24] = t2slo12 ^ (~t2slo13 & t2slo14);
4088
- s[25] = t2shi12 ^ (~t2shi13 & t2shi14);
4089
- s[34] = t2slo17 ^ (~t2slo18 & t2slo19);
4090
- s[35] = t2shi17 ^ (~t2shi18 & t2shi19);
4091
- s[44] = t2slo22 ^ (~t2slo23 & t2slo24);
4092
- s[45] = t2shi22 ^ (~t2shi23 & t2shi24);
4093
- s[6] = t2slo3 ^ (~t2slo4 & t2slo0);
4094
- s[7] = t2shi3 ^ (~t2shi4 & t2shi0);
4095
- s[16] = t2slo8 ^ (~t2slo9 & t2slo5);
4096
- s[17] = t2shi8 ^ (~t2shi9 & t2shi5);
4097
- s[26] = t2slo13 ^ (~t2slo14 & t2slo10);
4098
- s[27] = t2shi13 ^ (~t2shi14 & t2shi10);
4099
- s[36] = t2slo18 ^ (~t2slo19 & t2slo15);
4100
- s[37] = t2shi18 ^ (~t2shi19 & t2shi15);
4101
- s[46] = t2slo23 ^ (~t2slo24 & t2slo20);
4102
- s[47] = t2shi23 ^ (~t2shi24 & t2shi20);
4103
- s[8] = t2slo4 ^ (~t2slo0 & t2slo1);
4104
- s[9] = t2shi4 ^ (~t2shi0 & t2shi1);
4105
- s[18] = t2slo9 ^ (~t2slo5 & t2slo6);
4106
- s[19] = t2shi9 ^ (~t2shi5 & t2shi6);
4107
- s[28] = t2slo14 ^ (~t2slo10 & t2slo11);
4108
- s[29] = t2shi14 ^ (~t2shi10 & t2shi11);
4109
- s[38] = t2slo19 ^ (~t2slo15 & t2slo16);
4110
- s[39] = t2shi19 ^ (~t2shi15 & t2shi16);
4111
- s[48] = t2slo24 ^ (~t2slo20 & t2slo21);
4112
- s[49] = t2shi24 ^ (~t2shi20 & t2shi21);
4113
-
4114
- // iota
4115
- s[0] ^= P1600_ROUND_CONSTANTS[round * 2];
4116
- s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1];
4117
- }
4118
- };
4119
- return keccakStateUnroll;
4120
- }
4121
-
4122
- var keccak;
4123
- var hasRequiredKeccak;
4124
-
4125
- function requireKeccak () {
4126
- if (hasRequiredKeccak) return keccak;
4127
- hasRequiredKeccak = 1;
4128
- const keccakState = requireKeccakStateUnroll();
4129
-
4130
- function Keccak () {
4131
- // much faster than `new Array(50)`
4132
- this.state = [
4133
- 0, 0, 0, 0, 0,
4134
- 0, 0, 0, 0, 0,
4135
- 0, 0, 0, 0, 0,
4136
- 0, 0, 0, 0, 0,
4137
- 0, 0, 0, 0, 0
4138
- ];
4139
-
4140
- this.blockSize = null;
4141
- this.count = 0;
4142
- this.squeezing = false;
4143
- }
4144
-
4145
- Keccak.prototype.initialize = function (rate, capacity) {
4146
- for (let i = 0; i < 50; ++i) this.state[i] = 0;
4147
- this.blockSize = rate / 8;
4148
- this.count = 0;
4149
- this.squeezing = false;
4150
- };
4151
-
4152
- Keccak.prototype.absorb = function (data) {
4153
- for (let i = 0; i < data.length; ++i) {
4154
- this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4));
4155
- this.count += 1;
4156
- if (this.count === this.blockSize) {
4157
- keccakState.p1600(this.state);
4158
- this.count = 0;
4159
- }
4160
- }
4161
- };
4162
-
4163
- Keccak.prototype.absorbLastFewBits = function (bits) {
4164
- this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4));
4165
- if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state);
4166
- this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4));
4167
- keccakState.p1600(this.state);
4168
- this.count = 0;
4169
- this.squeezing = true;
4170
- };
4171
-
4172
- Keccak.prototype.squeeze = function (length) {
4173
- if (!this.squeezing) this.absorbLastFewBits(0x01);
4174
-
4175
- const output = Buffer.alloc(length);
4176
- for (let i = 0; i < length; ++i) {
4177
- output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff;
4178
- this.count += 1;
4179
- if (this.count === this.blockSize) {
4180
- keccakState.p1600(this.state);
4181
- this.count = 0;
4182
- }
4183
- }
4184
-
4185
- return output
4186
- };
4187
-
4188
- Keccak.prototype.copy = function (dest) {
4189
- for (let i = 0; i < 50; ++i) dest.state[i] = this.state[i];
4190
- dest.blockSize = this.blockSize;
4191
- dest.count = this.count;
4192
- dest.squeezing = this.squeezing;
4193
- };
4194
-
4195
- keccak = Keccak;
4196
- return keccak;
4197
- }
4198
-
4199
- var js;
4200
- var hasRequiredJs;
4201
-
4202
- function requireJs () {
4203
- if (hasRequiredJs) return js;
4204
- hasRequiredJs = 1;
4205
- js = requireApi()(requireKeccak());
4206
- return js;
4207
- }
4208
-
4209
- (function (module) {
4210
- try {
4211
- module.exports = requireBindings();
4212
- } catch (err) {
4213
- module.exports = requireJs();
4214
- }
4215
- } (keccak$2));
4216
-
4217
- Object.defineProperty(dist, '__esModule', { value: true });
4218
-
4219
- var bs32 = require$$0;
4220
- var bs58 = require$$1;
4221
- var isHex = require$$2;
4222
- var varint = varint$1;
4223
- var createKeccakHash = keccak$2.exports;
4224
-
4225
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
4226
-
4227
- var bs32__default = /*#__PURE__*/_interopDefaultLegacy(bs32);
4228
- var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58);
4229
- var isHex__default = /*#__PURE__*/_interopDefaultLegacy(isHex);
4230
- var varint__default = /*#__PURE__*/_interopDefaultLegacy(varint);
4231
- var createKeccakHash__default = /*#__PURE__*/_interopDefaultLegacy(createKeccakHash);
4232
-
4233
- class BasicInterface$1 {
4234
- handleDecode() {
4235
- if (!this.decode) throw new Error('bad implementation: needs decode func')
4236
- return this.decode()
4237
- }
4238
-
4239
- handleEncode() {
4240
- if (!this.encode) throw new Error('bad implementation: needs encode func')
4241
- return this.encode()
4242
- }
4243
- isHex(string) {
4244
- return isHex__default["default"](string)
4245
- }
4246
- isBase32(string) {
4247
- return bs32__default["default"].isBase32(string)
4248
- }
4249
- isBase58(string) {
4250
- return bs58__default["default"].isBase58(string)
4251
- }
4252
- /**
4253
- * @param {String} encoded
4254
- */
4255
- fromBs32(encoded) {
4256
- this.encoded = bs32__default["default"].decode(encoded);
4257
- return this.handleDecode()
4258
- }
4259
-
4260
- /**
4261
- * @param {String} encoded
4262
- */
4263
- fromBs58(encoded) {
4264
- this.encoded = bs58__default["default"].decode(encoded);
4265
- return this.handleDecode()
4266
- }
4267
-
4268
- async toArray() {
4269
- const array = [];
4270
- for await (const value of this.encoded.values()) {
4271
- array.push(value);
4272
- }
4273
- return array
4274
- }
4275
-
4276
- fromString(string) {
4277
- this.encoded = new Uint8Array(string.split(','));
4278
- return this.handleDecode()
4279
- }
4280
-
4281
- fromArray(array) {
4282
- this.encoded = new Uint8Array([...array]);
4283
- return this.handleDecode()
4284
- }
4285
-
4286
- /**
4287
- * @param {Buffer} encoded
4288
- */
4289
- fromEncoded(encoded) {
4290
- this.encoded = encoded;
4291
- return this.handleDecode()
4292
- }
4293
-
4294
- /**
4295
- * @param {String} encoded
4296
- */
4297
- fromHex(encoded) {
4298
- this.encoded = Buffer.from(encoded, 'hex');
4299
- return this.handleDecode()
4300
- }
4301
-
4302
- async toString(encoding = 'utf8') {
4303
- if (!this.encoded) await this.handleEncode();
4304
- return this.encoded.toString(encoding)
4305
- }
4306
-
4307
- /**
4308
- * @return {String} encoded
4309
- */
4310
- toHex() {
4311
- return this.toString('hex')
4312
- }
4313
-
4314
- /**
4315
- * @return {String} encoded
4316
- */
4317
- async toBs32() {
4318
- if (!this.encoded) await this.handleEncode();
4319
- return bs32__default["default"].encode(this.encoded)
4320
- }
4321
-
4322
- /**
4323
- * @return {String} encoded
4324
- */
4325
- async toBs58() {
4326
- if (!this.encoded) await this.handleEncode();
4327
- return bs58__default["default"].encode(this.encoded)
4328
- }
4329
-
4330
- /**
4331
- * @param {Object} data
4332
- */
4333
- create(data) {
4334
- const decoded = {};
4335
- if (this.keys?.length > 0) {
4336
- for (const key of this.keys) {
4337
- Object.defineProperties(decoded, {
4338
- [key]: {
4339
- enumerable: true,
4340
- configurable: true,
4341
- set: (val) => value = data[key],
4342
- get: () => data[key]
4343
- }
4344
- });
4345
- }
4346
-
4347
- this.decoded = decoded;
4348
- return this.encode()
4349
- }
4350
- }
4351
- }
4352
-
4353
- var codecs = {
4354
- // just a hash
4355
- 'disco-hash': {
4356
- codec: parseInt('30', 16),
4357
- hashAlg: 'dbl-keccak-256', // ,
4358
- // testnet: 'olivia'
4359
- },
4360
- 'peernet-peer-response': {
4361
- codec: parseInt('707072', 16),
4362
- hashAlg: 'keccak-256',
4363
- },
4364
- 'peernet-peer': {
4365
- codec: parseInt('7070', 16),
4366
- hashAlg: 'keccak-256',
4367
- },
4368
- 'peernet-dht': {
4369
- codec: parseInt('706468', 16),
4370
- hashAlg: 'keccak-256',
4371
- },
4372
- 'peernet-dht-response': {
4373
- codec: parseInt('706472', 16),
4374
- hashAlg: 'keccak-256',
4375
- },
4376
- // data
4377
- 'peernet-data': {
4378
- codec: parseInt('706461', 16),
4379
- hashAlg: 'keccak-256',
4380
- },
4381
- 'peernet-data-response': {
4382
- codec: parseInt('70646172', 16),
4383
- hashAlg: 'keccak-256',
4384
- },
4385
- // message
4386
- 'peernet-message': {
4387
- codec: parseInt('706d65', 16),
4388
- hashAlg: 'keccak-256',
4389
- },
4390
- // pubsub
4391
- 'peernet-ps': {
4392
- codec: parseInt('707073', 16),
4393
- hashAlg: 'keccak-256',
4394
- },
4395
- 'peernet-response': {
4396
- codec: parseInt('7072', 16),
4397
- hashAlg: 'keccak-256',
4398
- },
4399
- 'peernet-request': {
4400
- codec: parseInt('707271', 16),
4401
- hashAlg: 'keccak-256',
4402
- },
4403
- // normal block
4404
- 'leofcoin-block': {
4405
- codec: parseInt('6c62', 16),
4406
- hashAlg: 'dbl-keccak-512', // ,
4407
- // testnet: 'olivia'
4408
- },
4409
- 'leofcoin-tx': {
4410
- codec: parseInt('6c74', 16),
4411
- hashAlg: 'dbl-keccak-512', // ,
4412
- // testnet: 'olivia'
4413
- },
4414
- // itx
4415
- 'leofcoin-itx': {
4416
- codec: parseInt('6c69', 16),
4417
- hashAlg: 'keccak-512', // ,
4418
- // testnet: 'olivia'
4419
- },
4420
- // peer reputation
4421
- 'leofcoin-pr': {
4422
- codec: parseInt('6c70', 16),
4423
- hashAlg: 'keccak-256', // ,
4424
- // testnet: 'olivia'
4425
- },
4426
- // chat message
4427
- 'chat-message': {
4428
- codec: parseInt('636d', 16),
4429
- hashAlg: 'dbl-keccak-256',
4430
- },
4431
- 'peernet-file' : {
4432
- codec: parseInt('7066', 16),
4433
- hashAlg: 'keccak-256',
4434
- },
4435
- 'peernet-file-response' : {
4436
- codec: parseInt('706672', 16),
4437
- hashAlg: 'keccak-256',
4438
- }
4439
- };
4440
-
4441
- class PeernetCodec extends BasicInterface$1 {
4442
- get codecs() {
4443
- return {...globalThis.peernet.codecs, ...codecs}
4444
- }
4445
- constructor(buffer) {
4446
- super();
4447
- if (buffer) {
4448
- if (buffer instanceof Uint8Array) {
4449
- const codec = varint__default["default"].decode(buffer);
4450
- const name = this.getCodecName(codec);
4451
- if (name) {
4452
- this.name = name;
4453
- this.encoded = buffer;
4454
- this.decode(buffer);
4455
- } else {
4456
- this.encode(buffer);
4457
- }
4458
- } else if (buffer instanceof ArrayBuffer) {
4459
- const encoded = new Uint8Array(buffer.byteLength);
4460
-
4461
- for (let i = 0; i < buffer.byteLength; i++) {
4462
- encoded[i] = buffer[i];
4463
- }
4464
- this.encoded = encoded;
4465
- // this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength)
4466
- this.decode(buffer);
4467
- return
4468
- }
4469
- if (typeof buffer === 'string') {
4470
- if (this.codecs[buffer]) this.fromName(buffer);
4471
- else if (this.isHex(buffer)) this.fromHex(buffer);
4472
- else if (this.isBase32(buffer)) this.fromBs32(buffer);
4473
- else if (this.isBase58(buffer)) this.fromBs58(buffer);
4474
- else throw new Error(`unsupported string ${buffer}`)
4475
- }
4476
- if (!isNaN(buffer)) if (this.codecs[this.getCodecName(buffer)]) this.fromCodec(buffer);
4477
- }
4478
- }
4479
-
4480
- fromEncoded(encoded) {
4481
- const codec = varint__default["default"].decode(encoded);
4482
- const name = this.getCodecName(codec);
4483
- this.name = name;
4484
- this.encoded = encoded;
4485
- this.decode(encoded);
4486
- }
4487
-
4488
- getCodec(name) {
4489
- return this.codecs[name].codec
4490
- }
4491
-
4492
- getCodecName(codec) {
4493
- return Object.keys(this.codecs).reduce((p, c) => {
4494
- const item = this.codecs[c];
4495
- if (item.codec === codec) return c;
4496
- else return p;
4497
- }, undefined)
4498
- }
4499
-
4500
- getHashAlg(name) {
4501
- return this.codecs[name].hashAlg
4502
- }
4503
-
4504
- fromCodec(codec) {
4505
- this.name = this.getCodecName(codec);
4506
- this.hashAlg = this.getHashAlg(this.name);
4507
-
4508
- this.codec = this.getCodec(this.name);
4509
- this.codecBuffer = varint__default["default"].encode(codec);
4510
- }
4511
-
4512
- fromName(name) {
4513
- const codec = this.getCodec(name);
4514
- this.name = name;
4515
- this.codec = codec;
4516
- this.hashAlg = this.getHashAlg(name);
4517
- this.codecBuffer = varint__default["default"].encode(codec);
4518
- }
4519
-
4520
- decode() {
4521
- const codec = varint__default["default"].decode(this.encoded);
4522
- this.fromCodec(codec);
4523
- }
4524
-
4525
- encode() {
4526
- const codec = varint__default["default"].encode(this.decoded);
4527
- this.encoded = codec;
4528
- return this.encoded
4529
- }
4530
- }
4531
-
4532
- class CodecHash$1 extends BasicInterface$1 {
4533
- constructor(buffer, options = {}) {
4534
- super();
4535
- if (options.name) this.name = options.name;
4536
- else this.name = 'disco-hash';
4537
- if (options.codecs) this.codecs = options.codecs;
4538
- if (buffer) {
4539
- if (buffer instanceof Uint8Array) {
4540
- this.discoCodec = new PeernetCodec(buffer, this.codecs);
4541
- const name = this.discoCodec.name;
4542
-
4543
- if (name) {
4544
- this.name = name;
4545
- this.decode(buffer);
4546
- } else {
4547
- this.encode(buffer);
4548
- }
4549
- }
4550
-
4551
- if (typeof buffer === 'string') {
4552
- if (this.isHex(buffer)) this.fromHex(buffer);
4553
- if (this.isBase32(buffer)) this.fromBs32(buffer);
4554
- else if (this.isBase58(buffer)) this.fromBs58(buffer);
4555
- else throw new Error(`unsupported string ${buffer}`)
4556
- } else if (typeof buffer === 'object') this.fromJSON(buffer);
4557
- }
4558
- }
4559
-
4560
- get prefix() {
4561
- const length = this.length;
4562
- const uint8Array = new Uint8Array(length.length + this.discoCodec.codecBuffer.length);
4563
- uint8Array.set(length);
4564
- uint8Array.set(this.discoCodec.codecBuffer, length.length);
4565
-
4566
- return uint8Array
4567
- }
4568
-
4569
- get length() {
4570
- return varint__default["default"].encode(this.size)
4571
- }
4572
-
4573
- get buffer() {
4574
- return this.encoded
4575
- }
4576
-
4577
- get hash() {
4578
- return this.encoded
4579
- }
4580
-
4581
- fromJSON(json) {
4582
- return this.encode(Buffer.from(JSON.stringify(json)))
4583
- }
4584
-
4585
- encode(buffer, name) {
4586
- if (!this.name && name) this.name = name;
4587
- if (!buffer) buffer = this.buffer;
4588
- this.discoCodec = new PeernetCodec(this.name, this.codecs);
4589
- this.discoCodec.fromName(this.name);
4590
- let hashAlg = this.discoCodec.hashAlg;
4591
- if (hashAlg.includes('dbl')) {
4592
- hashAlg = hashAlg.replace('dbl-', '');
4593
- buffer = createKeccakHash__default["default"](hashAlg.replace('-', '')).update(buffer).digest();
4594
- }
4595
- this.digest = createKeccakHash__default["default"](hashAlg.replace('-', '')).update(buffer).digest();
4596
- this.size = this.digest.length;
4597
-
4598
- this.codec = this.discoCodec.encode();
4599
- this.codec = this.discoCodec.codecBuffer;
4600
- const uint8Array = new Uint8Array(this.digest.length + this.prefix.length);
4601
- uint8Array.set(this.prefix);
4602
- uint8Array.set(this.digest, this.prefix.length);
4603
-
4604
- this.encoded = uint8Array;
4605
-
4606
- return this.encoded
4607
- }
4608
-
4609
- validate(buffer) {
4610
- if (Buffer.isBuffer(buffer)) {
4611
- const codec = varint__default["default"].decode(buffer);
4612
- if (this.codecs[codec]) {
4613
- this.decode(buffer);
4614
- } else {
4615
- this.encode(buffer);
4616
- }
4617
- }
4618
- if (typeof buffer === 'string') {
4619
- if (this.isHex(buffer)) this.fromHex(buffer);
4620
- if (this.isBase32(buffer)) this.fromBs32(buffer);
4621
- }
4622
- if (typeof buffer === 'object') this.fromJSON(buffer);
4623
- }
4624
-
4625
- decode(buffer) {
4626
- this.encoded = buffer;
4627
- const codec = varint__default["default"].decode(buffer);
4628
-
4629
- this.discoCodec = new PeernetCodec(codec, this.codecs);
4630
- // TODO: validate codec
4631
- buffer = buffer.slice(varint__default["default"].decode.bytes);
4632
- this.size = varint__default["default"].decode(buffer);
4633
- this.digest = buffer.slice(varint__default["default"].decode.bytes);
4634
- if (this.digest.length !== this.size) {
4635
- throw new Error(`hash length inconsistent: 0x${this.encoded.toString('hex')}`)
4636
- }
4637
-
4638
- // const discoCodec = new Codec(codec, this.codecs)
4639
-
4640
- this.name = this.discoCodec.name;
4641
-
4642
-
4643
- this.size = this.digest.length;
4644
-
4645
- return {
4646
- codec: this.codec,
4647
- name: this.name,
4648
- size: this.size,
4649
- length: this.length,
4650
- digest: this.digest,
4651
- }
4652
- }
4653
- }
4654
-
4655
- class FormatInterface$1 extends BasicInterface$1 {
4656
-
4657
- async protoEncode(data) {
4658
- // check schema
4659
- return new TextEncoder().encode(data)
4660
- }
4661
-
4662
- async protoDecode(data) {
4663
- // check schema
4664
- return new TextDecoder().decode(data)
4665
- }
4666
-
4667
- async init(buffer) {
4668
- if (buffer instanceof Uint8Array) await this.fromUint8Array(buffer);
4669
- else if (buffer instanceof ArrayBuffer) await this.fromArrayBuffer(buffer);
4670
- else if (buffer?.name === this.name) return buffer
4671
- else if (buffer instanceof String) {
4672
- if (this.isHex(buffer)) await this.fromHex(buffer);
4673
- else if (this.isBase32(buffer)) await this.fromBs32(buffer);
4674
- else if (this.isBase58(buffer)) await this.fromBs58(buffer);
4675
- else throw new Error(`unsupported string ${buffer}`)
4676
- } else {
4677
- await this.create(buffer);
4678
- }
4679
- return this
4680
- }
4681
-
4682
- /**
4683
- * @param {Buffer|String|Object} buffer - data - The data needed to create the desired message
4684
- * @param {Object} proto - {encode, decode}
4685
- * @param {Object} options - {hashFormat, name}
4686
- */
4687
- constructor(buffer, proto, options = {}) {
4688
- super();
4689
- this.proto = proto;
4690
- this.hashFormat = options.hashFormat || 'bs32';
4691
- if (options.name) this.name = options.name;
4692
- return this.init(buffer)
4693
- }
4694
-
4695
- /**
4696
- * @return {PeernetHash}
4697
- */
4698
- get peernetHash() {
4699
- return new CodecHash$1(this.decoded, {name: this.name})
4700
- }
4701
-
4702
- /**
4703
- * @return {peernetHash}
4704
- */
4705
- get hash() {
4706
- const upper = this.hashFormat.charAt(0).toUpperCase();
4707
- const format = `${upper}${this.hashFormat.substring(1, this.hashFormat.length)}`;
4708
- return this.peernetHash[`to${format}`]()
4709
- }
4710
-
4711
- /**
4712
- * @return {Object}
4713
- */
4714
- async decode() {
4715
- let encoded = this.encoded;
4716
- const discoCodec = new PeernetCodec(this.encoded);
4717
- encoded = encoded.slice(discoCodec.codecBuffer.length);
4718
- this.name = discoCodec.name;
4719
- this.decoded = await this.protoDecode(encoded);
4720
- try {
4721
- this.decoded = JSON.parse(this.decoded);
4722
- } catch {
4723
-
4724
- }
4725
- return this.decoded
4726
- }
4727
-
4728
- /**
4729
- * @return {Buffer}
4730
- */
4731
- async encode(decoded) {
4732
- let encoded;
4733
- if (!decoded) decoded = this.decoded;
4734
- const codec = new PeernetCodec(this.name);
4735
-
4736
- if (decoded instanceof Uint8Array) encoded = decoded;
4737
- else encoded = await this.protoEncode(typeof decoded === 'object' ? JSON.stringify(decoded) : decoded);
4738
-
4739
- const uint8Array = new Uint8Array(encoded.length + codec.codecBuffer.length);
4740
- uint8Array.set(codec.codecBuffer);
4741
- uint8Array.set(encoded, codec.codecBuffer.length);
4742
-
4743
- this.encoded = uint8Array;
4744
- return this.encoded
4745
- }
4746
-
4747
- hasCodec() {
4748
- if (!this.encoded) return false
4749
- const codec = new PeernetCodec(this.encoded);
4750
- if (codec.name) return true
4751
- }
4752
-
4753
- fromUint8Array(buffer) {
4754
- this.encoded = buffer;
4755
- return this.hasCodec() ? this.decode() : this.create(
4756
- JSON.parse(new TextDecoder().decode(this.encoded))
4757
- )
4758
- }
4759
-
4760
- fromArrayBuffer(buffer) {
4761
- this.encoded = new Uint8Array(buffer, buffer.byteOffset, buffer.byteLength);
4762
- return this.hasCodec() ? this.decode() : this.create(
4763
- JSON.parse(new TextDecoder().decode(this.encoded))
4764
- )
4765
- }
4766
- }
4767
-
4768
- const BasicInterface = BasicInterface$1;
4769
- const FormatInterface = FormatInterface$1;
4770
- const CodecHash = CodecHash$1;
4771
- const Codec = PeernetCodec;
4772
- const Codecs = codecs;
4773
-
4774
- dist.BasicInterface = BasicInterface;
4775
- dist.Codec = Codec;
4776
- dist.CodecHash = CodecHash;
4777
- dist.Codecs = Codecs;
4778
- var FormatInterface_1 = dist.FormatInterface = FormatInterface;
4779
-
4780
- class EasyWorker {
4781
- #messageEvent = 'message'
4782
- #errorEvent = 'error'
4783
- #isBrowser = false
4784
- #isWorker = false
4785
-
4786
- get isWorker() {
4787
- return this.#isWorker
4788
- }
4789
- constructor(url, options) {
4790
- return this.#init(url, options)
4791
- }
4792
-
4793
- #init(url, options = {}) {
4794
- if (url) {
4795
- if (globalThis.Worker) {
4796
- this.#isBrowser = true;
4797
- this.worker = new Worker(url, {...options});
4798
- } else {
4799
- return new Promise(async (resolve, reject) => {
4800
- const {fork} = await import('child_process');
4801
- this.worker = fork(url, ['easy-worker-child'], options);
4802
- resolve(this);
4803
- })
4804
- }
4805
- } else {
4806
- this.#isWorker = true;
4807
- if (globalThis.process?.argv[2] === 'easy-worker-child') {
4808
- this.worker = process;
4809
- } else {
4810
- this.#isBrowser = true;
4811
- this.worker = globalThis;
4812
- }
4813
- }
4814
-
4815
- return this
4816
- }
4817
-
4818
- onmessage(fn) {
4819
- if (this.#isBrowser) this.worker.onmessage = ({data}) => fn(data);
4820
- else this.worker.on(this.#messageEvent, fn);
4821
- }
4822
-
4823
- postMessage(message) {
4824
- if (this.#isBrowser) this.worker.postMessage(message);
4825
- else this.worker.send(message);
4826
- }
4827
-
4828
- terminate() {
4829
- if (this.#isBrowser) this.worker.terminate();
4830
- else this.worker.kill();
4831
- }
4832
-
4833
- onerror(fn) {
4834
- if (this.#isBrowser) this.worker.onerror = fn;
4835
- else this.worker.on(this.#errorEvent, fn);
4836
- }
4837
-
4838
- /**
4839
- *
4840
- * @param {*} data
4841
- * @returns {Promise} resolves result onmessage & rejects on error
4842
- */
4843
- once(data) {
4844
- return new Promise((resolve, reject) => {
4845
- this.onmessage(message => {
4846
- resolve(message);
4847
- this.terminate();
4848
- });
4849
- this.onerror(error => {
4850
- reject(error);
4851
- this.terminate();
4852
- });
4853
- this.postMessage(data);
4854
- })
4855
- }
4856
- }
4857
-
4858
- export { EasyWorker as E, FormatInterface_1 as F, commonjsGlobal as c };