@leofcoin/workers 1.3.8 → 1.3.9

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