grpc-libp2p-client 0.0.2 → 0.0.3

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.
package/dist/grpc.js ADDED
@@ -0,0 +1,3377 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.GrpcLibp2pClient = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ var global = typeof window !== 'undefined' ? window : this;
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
24
+
25
+
26
+ var __assign = function() {
27
+ __assign = Object.assign || function __assign(t) {
28
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
29
+ s = arguments[i];
30
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
31
+ }
32
+ return t;
33
+ };
34
+ return __assign.apply(this, arguments);
35
+ };
36
+
37
+ function __awaiter(thisArg, _arguments, P, generator) {
38
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
39
+ return new (P || (P = Promise))(function (resolve, reject) {
40
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
41
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
42
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
43
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
44
+ });
45
+ }
46
+
47
+ function __generator(thisArg, body) {
48
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
49
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
50
+ function verb(n) { return function (v) { return step([n, v]); }; }
51
+ function step(op) {
52
+ if (f) throw new TypeError("Generator is already executing.");
53
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
54
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
55
+ if (y = 0, t) op = [op[0] & 2, t.value];
56
+ switch (op[0]) {
57
+ case 0: case 1: t = op; break;
58
+ case 4: _.label++; return { value: op[1], done: false };
59
+ case 5: _.label++; y = op[1]; op = [0]; continue;
60
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
61
+ default:
62
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
63
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
64
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
65
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
66
+ if (t[2]) _.ops.pop();
67
+ _.trys.pop(); continue;
68
+ }
69
+ op = body.call(thisArg, _);
70
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
71
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
72
+ }
73
+ }
74
+
75
+ function __values(o) {
76
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
77
+ if (m) return m.call(o);
78
+ if (o && typeof o.length === "number") return {
79
+ next: function () {
80
+ if (o && i >= o.length) o = void 0;
81
+ return { value: o && o[i++], done: !o };
82
+ }
83
+ };
84
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
85
+ }
86
+
87
+ function __spreadArray(to, from, pack) {
88
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
+ if (ar || !(i in from)) {
90
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
+ ar[i] = from[i];
92
+ }
93
+ }
94
+ return to.concat(ar || Array.prototype.slice.call(from));
95
+ }
96
+
97
+ function __await(v) {
98
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
99
+ }
100
+
101
+ function __asyncGenerator(thisArg, _arguments, generator) {
102
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
103
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
104
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
105
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
106
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
107
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
108
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
109
+ function fulfill(value) { resume("next", value); }
110
+ function reject(value) { resume("throw", value); }
111
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
112
+ }
113
+
114
+ function __asyncValues(o) {
115
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
116
+ var m = o[Symbol.asyncIterator], i;
117
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
118
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
119
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
120
+ }
121
+
122
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
123
+ var e = new Error(message);
124
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
125
+ };
126
+
127
+ var FRAME_TYPES = {
128
+ DATA: 0x0, // 传输 HTTP 消息的主体
129
+ HEADERS: 0x1, // 压缩的 HTTP 头部
130
+ RST_STREAM: 0x3, // 终止流
131
+ SETTINGS: 0x4, // 设置连接参数
132
+ PING: 0x6, // 测量RTT和活性检查
133
+ WINDOW_UPDATE: 0x8};
134
+ var FRAME_FLAGS = {
135
+ ACK: 0x1,
136
+ END_STREAM: 0x1};
137
+
138
+ function coerce(o) {
139
+ if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
140
+ return o;
141
+ if (o instanceof ArrayBuffer)
142
+ return new Uint8Array(o);
143
+ if (ArrayBuffer.isView(o)) {
144
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
145
+ }
146
+ throw new Error('Unknown type, must be binary type');
147
+ }
148
+ function fromString(str) {
149
+ return new TextEncoder().encode(str);
150
+ }
151
+ function toString$1(b) {
152
+ return new TextDecoder().decode(b);
153
+ }
154
+
155
+ /* eslint-disable */
156
+ // base-x encoding / decoding
157
+ // Copyright (c) 2018 base-x contributors
158
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
159
+ // Distributed under the MIT software license, see the accompanying
160
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
161
+ /**
162
+ * @param {string} ALPHABET
163
+ * @param {any} name
164
+ */
165
+ function base(ALPHABET, name) {
166
+ if (ALPHABET.length >= 255) {
167
+ throw new TypeError('Alphabet too long');
168
+ }
169
+ var BASE_MAP = new Uint8Array(256);
170
+ for (var j = 0; j < BASE_MAP.length; j++) {
171
+ BASE_MAP[j] = 255;
172
+ }
173
+ for (var i = 0; i < ALPHABET.length; i++) {
174
+ var x = ALPHABET.charAt(i);
175
+ var xc = x.charCodeAt(0);
176
+ if (BASE_MAP[xc] !== 255) {
177
+ throw new TypeError(x + ' is ambiguous');
178
+ }
179
+ BASE_MAP[xc] = i;
180
+ }
181
+ var BASE = ALPHABET.length;
182
+ var LEADER = ALPHABET.charAt(0);
183
+ var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
184
+ var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
185
+ /**
186
+ * @param {any[] | Iterable<number>} source
187
+ */
188
+ function encode(source) {
189
+ // @ts-ignore
190
+ if (source instanceof Uint8Array)
191
+ ;
192
+ else if (ArrayBuffer.isView(source)) {
193
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
194
+ }
195
+ else if (Array.isArray(source)) {
196
+ source = Uint8Array.from(source);
197
+ }
198
+ if (!(source instanceof Uint8Array)) {
199
+ throw new TypeError('Expected Uint8Array');
200
+ }
201
+ if (source.length === 0) {
202
+ return '';
203
+ }
204
+ // Skip & count leading zeroes.
205
+ var zeroes = 0;
206
+ var length = 0;
207
+ var pbegin = 0;
208
+ var pend = source.length;
209
+ while (pbegin !== pend && source[pbegin] === 0) {
210
+ pbegin++;
211
+ zeroes++;
212
+ }
213
+ // Allocate enough space in big-endian base58 representation.
214
+ var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
215
+ var b58 = new Uint8Array(size);
216
+ // Process the bytes.
217
+ while (pbegin !== pend) {
218
+ var carry = source[pbegin];
219
+ // Apply "b58 = b58 * 256 + ch".
220
+ var i = 0;
221
+ for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
222
+ carry += (256 * b58[it1]) >>> 0;
223
+ b58[it1] = (carry % BASE) >>> 0;
224
+ carry = (carry / BASE) >>> 0;
225
+ }
226
+ if (carry !== 0) {
227
+ throw new Error('Non-zero carry');
228
+ }
229
+ length = i;
230
+ pbegin++;
231
+ }
232
+ // Skip leading zeroes in base58 result.
233
+ var it2 = size - length;
234
+ while (it2 !== size && b58[it2] === 0) {
235
+ it2++;
236
+ }
237
+ // Translate the result into a string.
238
+ var str = LEADER.repeat(zeroes);
239
+ for (; it2 < size; ++it2) {
240
+ str += ALPHABET.charAt(b58[it2]);
241
+ }
242
+ return str;
243
+ }
244
+ /**
245
+ * @param {string | string[]} source
246
+ */
247
+ function decodeUnsafe(source) {
248
+ if (typeof source !== 'string') {
249
+ throw new TypeError('Expected String');
250
+ }
251
+ if (source.length === 0) {
252
+ return new Uint8Array();
253
+ }
254
+ var psz = 0;
255
+ // Skip leading spaces.
256
+ if (source[psz] === ' ') {
257
+ return;
258
+ }
259
+ // Skip and count leading '1's.
260
+ var zeroes = 0;
261
+ var length = 0;
262
+ while (source[psz] === LEADER) {
263
+ zeroes++;
264
+ psz++;
265
+ }
266
+ // Allocate enough space in big-endian base256 representation.
267
+ var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
268
+ var b256 = new Uint8Array(size);
269
+ // Process the characters.
270
+ while (source[psz]) {
271
+ // Decode character
272
+ var carry = BASE_MAP[source.charCodeAt(psz)];
273
+ // Invalid character
274
+ if (carry === 255) {
275
+ return;
276
+ }
277
+ var i = 0;
278
+ for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
279
+ carry += (BASE * b256[it3]) >>> 0;
280
+ b256[it3] = (carry % 256) >>> 0;
281
+ carry = (carry / 256) >>> 0;
282
+ }
283
+ if (carry !== 0) {
284
+ throw new Error('Non-zero carry');
285
+ }
286
+ length = i;
287
+ psz++;
288
+ }
289
+ // Skip trailing spaces.
290
+ if (source[psz] === ' ') {
291
+ return;
292
+ }
293
+ // Skip leading zeroes in b256.
294
+ var it4 = size - length;
295
+ while (it4 !== size && b256[it4] === 0) {
296
+ it4++;
297
+ }
298
+ var vch = new Uint8Array(zeroes + (size - it4));
299
+ var j = zeroes;
300
+ while (it4 !== size) {
301
+ vch[j++] = b256[it4++];
302
+ }
303
+ return vch;
304
+ }
305
+ /**
306
+ * @param {string | string[]} string
307
+ */
308
+ function decode(string) {
309
+ var buffer = decodeUnsafe(string);
310
+ if (buffer) {
311
+ return buffer;
312
+ }
313
+ throw new Error(`Non-${name} character`);
314
+ }
315
+ return {
316
+ encode: encode,
317
+ decodeUnsafe: decodeUnsafe,
318
+ decode: decode
319
+ };
320
+ }
321
+ var src = base;
322
+ var _brrp__multiformats_scope_baseX = src;
323
+
324
+ /**
325
+ * Class represents both BaseEncoder and MultibaseEncoder meaning it
326
+ * can be used to encode to multibase or base encode without multibase
327
+ * prefix.
328
+ */
329
+ class Encoder {
330
+ name;
331
+ prefix;
332
+ baseEncode;
333
+ constructor(name, prefix, baseEncode) {
334
+ this.name = name;
335
+ this.prefix = prefix;
336
+ this.baseEncode = baseEncode;
337
+ }
338
+ encode(bytes) {
339
+ if (bytes instanceof Uint8Array) {
340
+ return `${this.prefix}${this.baseEncode(bytes)}`;
341
+ }
342
+ else {
343
+ throw Error('Unknown type, must be binary type');
344
+ }
345
+ }
346
+ }
347
+ /**
348
+ * Class represents both BaseDecoder and MultibaseDecoder so it could be used
349
+ * to decode multibases (with matching prefix) or just base decode strings
350
+ * with corresponding base encoding.
351
+ */
352
+ class Decoder {
353
+ name;
354
+ prefix;
355
+ baseDecode;
356
+ prefixCodePoint;
357
+ constructor(name, prefix, baseDecode) {
358
+ this.name = name;
359
+ this.prefix = prefix;
360
+ const prefixCodePoint = prefix.codePointAt(0);
361
+ /* c8 ignore next 3 */
362
+ if (prefixCodePoint === undefined) {
363
+ throw new Error('Invalid prefix character');
364
+ }
365
+ this.prefixCodePoint = prefixCodePoint;
366
+ this.baseDecode = baseDecode;
367
+ }
368
+ decode(text) {
369
+ if (typeof text === 'string') {
370
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
371
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
372
+ }
373
+ return this.baseDecode(text.slice(this.prefix.length));
374
+ }
375
+ else {
376
+ throw Error('Can only multibase decode strings');
377
+ }
378
+ }
379
+ or(decoder) {
380
+ return or(this, decoder);
381
+ }
382
+ }
383
+ class ComposedDecoder {
384
+ decoders;
385
+ constructor(decoders) {
386
+ this.decoders = decoders;
387
+ }
388
+ or(decoder) {
389
+ return or(this, decoder);
390
+ }
391
+ decode(input) {
392
+ const prefix = input[0];
393
+ const decoder = this.decoders[prefix];
394
+ if (decoder != null) {
395
+ return decoder.decode(input);
396
+ }
397
+ else {
398
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
399
+ }
400
+ }
401
+ }
402
+ function or(left, right) {
403
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
404
+ return new ComposedDecoder({
405
+ ...(left.decoders ?? { [left.prefix]: left }),
406
+ ...(right.decoders ?? { [right.prefix]: right })
407
+ });
408
+ }
409
+ class Codec {
410
+ name;
411
+ prefix;
412
+ baseEncode;
413
+ baseDecode;
414
+ encoder;
415
+ decoder;
416
+ constructor(name, prefix, baseEncode, baseDecode) {
417
+ this.name = name;
418
+ this.prefix = prefix;
419
+ this.baseEncode = baseEncode;
420
+ this.baseDecode = baseDecode;
421
+ this.encoder = new Encoder(name, prefix, baseEncode);
422
+ this.decoder = new Decoder(name, prefix, baseDecode);
423
+ }
424
+ encode(input) {
425
+ return this.encoder.encode(input);
426
+ }
427
+ decode(input) {
428
+ return this.decoder.decode(input);
429
+ }
430
+ }
431
+ function from({ name, prefix, encode, decode }) {
432
+ return new Codec(name, prefix, encode, decode);
433
+ }
434
+ function baseX({ name, prefix, alphabet }) {
435
+ const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
436
+ return from({
437
+ prefix,
438
+ name,
439
+ encode,
440
+ decode: (text) => coerce(decode(text))
441
+ });
442
+ }
443
+ function decode$1(string, alphabet, bitsPerChar, name) {
444
+ // Build the character lookup table:
445
+ const codes = {};
446
+ for (let i = 0; i < alphabet.length; ++i) {
447
+ codes[alphabet[i]] = i;
448
+ }
449
+ // Count the padding bytes:
450
+ let end = string.length;
451
+ while (string[end - 1] === '=') {
452
+ --end;
453
+ }
454
+ // Allocate the output:
455
+ const out = new Uint8Array((end * bitsPerChar / 8) | 0);
456
+ // Parse the data:
457
+ let bits = 0; // Number of bits currently in the buffer
458
+ let buffer = 0; // Bits waiting to be written out, MSB first
459
+ let written = 0; // Next byte to write
460
+ for (let i = 0; i < end; ++i) {
461
+ // Read one character from the string:
462
+ const value = codes[string[i]];
463
+ if (value === undefined) {
464
+ throw new SyntaxError(`Non-${name} character`);
465
+ }
466
+ // Append the bits to the buffer:
467
+ buffer = (buffer << bitsPerChar) | value;
468
+ bits += bitsPerChar;
469
+ // Write out some bits if the buffer has a byte's worth:
470
+ if (bits >= 8) {
471
+ bits -= 8;
472
+ out[written++] = 0xff & (buffer >> bits);
473
+ }
474
+ }
475
+ // Verify that we have received just enough bits:
476
+ if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
477
+ throw new SyntaxError('Unexpected end of data');
478
+ }
479
+ return out;
480
+ }
481
+ function encode$1(data, alphabet, bitsPerChar) {
482
+ const pad = alphabet[alphabet.length - 1] === '=';
483
+ const mask = (1 << bitsPerChar) - 1;
484
+ let out = '';
485
+ let bits = 0; // Number of bits currently in the buffer
486
+ let buffer = 0; // Bits waiting to be written out, MSB first
487
+ for (let i = 0; i < data.length; ++i) {
488
+ // Slurp data into the buffer:
489
+ buffer = (buffer << 8) | data[i];
490
+ bits += 8;
491
+ // Write out as much as we can:
492
+ while (bits > bitsPerChar) {
493
+ bits -= bitsPerChar;
494
+ out += alphabet[mask & (buffer >> bits)];
495
+ }
496
+ }
497
+ // Partial character:
498
+ if (bits !== 0) {
499
+ out += alphabet[mask & (buffer << (bitsPerChar - bits))];
500
+ }
501
+ // Add padding characters until we hit a byte boundary:
502
+ if (pad) {
503
+ while (((out.length * bitsPerChar) & 7) !== 0) {
504
+ out += '=';
505
+ }
506
+ }
507
+ return out;
508
+ }
509
+ /**
510
+ * RFC4648 Factory
511
+ */
512
+ function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
513
+ return from({
514
+ prefix,
515
+ name,
516
+ encode(input) {
517
+ return encode$1(input, alphabet, bitsPerChar);
518
+ },
519
+ decode(input) {
520
+ return decode$1(input, alphabet, bitsPerChar, name);
521
+ }
522
+ });
523
+ }
524
+
525
+ const base10 = baseX({
526
+ prefix: '9',
527
+ name: 'base10',
528
+ alphabet: '0123456789'
529
+ });
530
+
531
+ var base10$1 = /*#__PURE__*/Object.freeze({
532
+ __proto__: null,
533
+ base10: base10
534
+ });
535
+
536
+ const base16 = rfc4648({
537
+ prefix: 'f',
538
+ name: 'base16',
539
+ alphabet: '0123456789abcdef',
540
+ bitsPerChar: 4
541
+ });
542
+ const base16upper = rfc4648({
543
+ prefix: 'F',
544
+ name: 'base16upper',
545
+ alphabet: '0123456789ABCDEF',
546
+ bitsPerChar: 4
547
+ });
548
+
549
+ var base16$1 = /*#__PURE__*/Object.freeze({
550
+ __proto__: null,
551
+ base16: base16,
552
+ base16upper: base16upper
553
+ });
554
+
555
+ const base2 = rfc4648({
556
+ prefix: '0',
557
+ name: 'base2',
558
+ alphabet: '01',
559
+ bitsPerChar: 1
560
+ });
561
+
562
+ var base2$1 = /*#__PURE__*/Object.freeze({
563
+ __proto__: null,
564
+ base2: base2
565
+ });
566
+
567
+ const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
568
+ const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
569
+ const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
570
+ const codePoint = c.codePointAt(0);
571
+ if (codePoint == null) {
572
+ throw new Error(`Invalid character: ${c}`);
573
+ }
574
+ p[codePoint] = i;
575
+ return p;
576
+ }, ([])));
577
+ function encode(data) {
578
+ return data.reduce((p, c) => {
579
+ p += alphabetBytesToChars[c];
580
+ return p;
581
+ }, '');
582
+ }
583
+ function decode(str) {
584
+ const byts = [];
585
+ for (const char of str) {
586
+ const codePoint = char.codePointAt(0);
587
+ if (codePoint == null) {
588
+ throw new Error(`Invalid character: ${char}`);
589
+ }
590
+ const byt = alphabetCharsToBytes[codePoint];
591
+ if (byt == null) {
592
+ throw new Error(`Non-base256emoji character: ${char}`);
593
+ }
594
+ byts.push(byt);
595
+ }
596
+ return new Uint8Array(byts);
597
+ }
598
+ const base256emoji = from({
599
+ prefix: '🚀',
600
+ name: 'base256emoji',
601
+ encode,
602
+ decode
603
+ });
604
+
605
+ var base256emoji$1 = /*#__PURE__*/Object.freeze({
606
+ __proto__: null,
607
+ base256emoji: base256emoji
608
+ });
609
+
610
+ const base32 = rfc4648({
611
+ prefix: 'b',
612
+ name: 'base32',
613
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
614
+ bitsPerChar: 5
615
+ });
616
+ const base32upper = rfc4648({
617
+ prefix: 'B',
618
+ name: 'base32upper',
619
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
620
+ bitsPerChar: 5
621
+ });
622
+ const base32pad = rfc4648({
623
+ prefix: 'c',
624
+ name: 'base32pad',
625
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
626
+ bitsPerChar: 5
627
+ });
628
+ const base32padupper = rfc4648({
629
+ prefix: 'C',
630
+ name: 'base32padupper',
631
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
632
+ bitsPerChar: 5
633
+ });
634
+ const base32hex = rfc4648({
635
+ prefix: 'v',
636
+ name: 'base32hex',
637
+ alphabet: '0123456789abcdefghijklmnopqrstuv',
638
+ bitsPerChar: 5
639
+ });
640
+ const base32hexupper = rfc4648({
641
+ prefix: 'V',
642
+ name: 'base32hexupper',
643
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
644
+ bitsPerChar: 5
645
+ });
646
+ const base32hexpad = rfc4648({
647
+ prefix: 't',
648
+ name: 'base32hexpad',
649
+ alphabet: '0123456789abcdefghijklmnopqrstuv=',
650
+ bitsPerChar: 5
651
+ });
652
+ const base32hexpadupper = rfc4648({
653
+ prefix: 'T',
654
+ name: 'base32hexpadupper',
655
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
656
+ bitsPerChar: 5
657
+ });
658
+ const base32z = rfc4648({
659
+ prefix: 'h',
660
+ name: 'base32z',
661
+ alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
662
+ bitsPerChar: 5
663
+ });
664
+
665
+ var base32$1 = /*#__PURE__*/Object.freeze({
666
+ __proto__: null,
667
+ base32: base32,
668
+ base32hex: base32hex,
669
+ base32hexpad: base32hexpad,
670
+ base32hexpadupper: base32hexpadupper,
671
+ base32hexupper: base32hexupper,
672
+ base32pad: base32pad,
673
+ base32padupper: base32padupper,
674
+ base32upper: base32upper,
675
+ base32z: base32z
676
+ });
677
+
678
+ const base36 = baseX({
679
+ prefix: 'k',
680
+ name: 'base36',
681
+ alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
682
+ });
683
+ const base36upper = baseX({
684
+ prefix: 'K',
685
+ name: 'base36upper',
686
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
687
+ });
688
+
689
+ var base36$1 = /*#__PURE__*/Object.freeze({
690
+ __proto__: null,
691
+ base36: base36,
692
+ base36upper: base36upper
693
+ });
694
+
695
+ const base58btc = baseX({
696
+ name: 'base58btc',
697
+ prefix: 'z',
698
+ alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
699
+ });
700
+ const base58flickr = baseX({
701
+ name: 'base58flickr',
702
+ prefix: 'Z',
703
+ alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
704
+ });
705
+
706
+ var base58 = /*#__PURE__*/Object.freeze({
707
+ __proto__: null,
708
+ base58btc: base58btc,
709
+ base58flickr: base58flickr
710
+ });
711
+
712
+ const base64 = rfc4648({
713
+ prefix: 'm',
714
+ name: 'base64',
715
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
716
+ bitsPerChar: 6
717
+ });
718
+ const base64pad = rfc4648({
719
+ prefix: 'M',
720
+ name: 'base64pad',
721
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
722
+ bitsPerChar: 6
723
+ });
724
+ const base64url = rfc4648({
725
+ prefix: 'u',
726
+ name: 'base64url',
727
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
728
+ bitsPerChar: 6
729
+ });
730
+ const base64urlpad = rfc4648({
731
+ prefix: 'U',
732
+ name: 'base64urlpad',
733
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
734
+ bitsPerChar: 6
735
+ });
736
+
737
+ var base64$1 = /*#__PURE__*/Object.freeze({
738
+ __proto__: null,
739
+ base64: base64,
740
+ base64pad: base64pad,
741
+ base64url: base64url,
742
+ base64urlpad: base64urlpad
743
+ });
744
+
745
+ const base8 = rfc4648({
746
+ prefix: '7',
747
+ name: 'base8',
748
+ alphabet: '01234567',
749
+ bitsPerChar: 3
750
+ });
751
+
752
+ var base8$1 = /*#__PURE__*/Object.freeze({
753
+ __proto__: null,
754
+ base8: base8
755
+ });
756
+
757
+ const identity = from({
758
+ prefix: '\x00',
759
+ name: 'identity',
760
+ encode: (buf) => toString$1(buf),
761
+ decode: (str) => fromString(str)
762
+ });
763
+
764
+ var identityBase = /*#__PURE__*/Object.freeze({
765
+ __proto__: null,
766
+ identity: identity
767
+ });
768
+
769
+ new TextEncoder();
770
+ new TextDecoder();
771
+
772
+ const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
773
+
774
+ /**
775
+ * Returns a `Uint8Array` of the requested size. Referenced memory will
776
+ * be initialized to 0.
777
+ */
778
+ /**
779
+ * Where possible returns a Uint8Array of the requested size that references
780
+ * uninitialized memory. Only use if you are certain you will immediately
781
+ * overwrite every value in the returned `Uint8Array`.
782
+ */
783
+ function allocUnsafe(size = 0) {
784
+ return new Uint8Array(size);
785
+ }
786
+
787
+ function createCodec(name, prefix, encode, decode) {
788
+ return {
789
+ name,
790
+ prefix,
791
+ encoder: {
792
+ name,
793
+ prefix,
794
+ encode
795
+ },
796
+ decoder: {
797
+ decode
798
+ }
799
+ };
800
+ }
801
+ const string = createCodec('utf8', 'u', (buf) => {
802
+ const decoder = new TextDecoder('utf8');
803
+ return 'u' + decoder.decode(buf);
804
+ }, (str) => {
805
+ const encoder = new TextEncoder();
806
+ return encoder.encode(str.substring(1));
807
+ });
808
+ const ascii = createCodec('ascii', 'a', (buf) => {
809
+ let string = 'a';
810
+ for (let i = 0; i < buf.length; i++) {
811
+ string += String.fromCharCode(buf[i]);
812
+ }
813
+ return string;
814
+ }, (str) => {
815
+ str = str.substring(1);
816
+ const buf = allocUnsafe(str.length);
817
+ for (let i = 0; i < str.length; i++) {
818
+ buf[i] = str.charCodeAt(i);
819
+ }
820
+ return buf;
821
+ });
822
+ const BASES = {
823
+ utf8: string,
824
+ 'utf-8': string,
825
+ hex: bases.base16,
826
+ latin1: ascii,
827
+ ascii,
828
+ binary: ascii,
829
+ ...bases
830
+ };
831
+
832
+ /**
833
+ * Turns a `Uint8Array` into a string.
834
+ *
835
+ * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
836
+ *
837
+ * Also `ascii` which is similar to node's 'binary' encoding.
838
+ */
839
+ function toString(array, encoding = 'utf8') {
840
+ const base = BASES[encoding];
841
+ if (base == null) {
842
+ throw new Error(`Unsupported encoding "${encoding}"`);
843
+ }
844
+ // strip multibase prefix
845
+ return base.encoder.encode(array).substring(1);
846
+ }
847
+
848
+ // HPACK Implementation
849
+ var HPACK = /** @class */ (function () {
850
+ function HPACK(maxDynamicTableSize) {
851
+ if (maxDynamicTableSize === void 0) { maxDynamicTableSize = 4096; }
852
+ // 初始化动态表
853
+ this.dynamicTable = [];
854
+ this.dynamicTableSize = 0;
855
+ this.maxDynamicTableSize = maxDynamicTableSize;
856
+ // 初始化静态表
857
+ this.staticTable = [
858
+ ['', ''], // Index 0 is not used
859
+ [':authority', ''],
860
+ [':method', 'GET'],
861
+ [':method', 'POST'],
862
+ [':path', '/'],
863
+ [':path', '/index.html'],
864
+ [':scheme', 'http'],
865
+ [':scheme', 'https'],
866
+ [':status', '200'],
867
+ [':status', '204'],
868
+ [':status', '206'],
869
+ [':status', '304'],
870
+ [':status', '400'],
871
+ [':status', '404'],
872
+ [':status', '500'],
873
+ ['accept-charset', ''],
874
+ ['accept-encoding', 'gzip, deflate'],
875
+ ['accept-language', ''],
876
+ ['accept-ranges', ''],
877
+ ['accept', ''],
878
+ ['access-control-allow-origin', ''],
879
+ ['age', ''],
880
+ ['allow', ''],
881
+ ['authorization', ''],
882
+ ['cache-control', ''],
883
+ ['content-disposition', ''],
884
+ ['content-encoding', ''],
885
+ ['content-language', ''],
886
+ ['content-length', ''],
887
+ ['content-location', ''],
888
+ ['content-range', ''],
889
+ ['content-type', ''],
890
+ ['cookie', ''],
891
+ ['date', ''],
892
+ ['etag', ''],
893
+ ['expect', ''],
894
+ ['expires', ''],
895
+ ['from', ''],
896
+ ['host', ''],
897
+ ['if-match', ''],
898
+ ['if-modified-since', ''],
899
+ ['if-none-match', ''],
900
+ ['if-range', ''],
901
+ ['if-unmodified-since', ''],
902
+ ['last-modified', ''],
903
+ ['link', ''],
904
+ ['location', ''],
905
+ ['max-forwards', ''],
906
+ ['proxy-authenticate', ''],
907
+ ['proxy-authorization', ''],
908
+ ['range', ''],
909
+ ['referer', ''],
910
+ ['refresh', ''],
911
+ ['retry-after', ''],
912
+ ['server', ''],
913
+ ['set-cookie', ''],
914
+ ['strict-transport-security', ''],
915
+ ['transfer-encoding', ''],
916
+ ['user-agent', ''],
917
+ ['vary', ''],
918
+ ['via', ''],
919
+ ['www-authenticate', '']
920
+ ];
921
+ // Huffman编码表
922
+ this.huffmanTable = this.buildHuffmanTable();
923
+ }
924
+ // 编码headers
925
+ HPACK.prototype.encode = function (headers) {
926
+ var buffer = [];
927
+ for (var _i = 0, _a = Object.entries(headers); _i < _a.length; _i++) {
928
+ var _b = _a[_i], name_1 = _b[0], value = _b[1];
929
+ // 查找静态表索引
930
+ var staticIndex = this.findInStaticTable(name_1, value);
931
+ if (staticIndex !== -1) {
932
+ // 使用索引编码
933
+ buffer.push.apply(buffer, this.encodeInteger(staticIndex, 7, 0x80));
934
+ continue;
935
+ }
936
+ // 查找动态表索引
937
+ var dynamicIndex = this.findInDynamicTable(name_1, value);
938
+ if (dynamicIndex !== -1) {
939
+ buffer.push.apply(buffer, this.encodeInteger(dynamicIndex + this.staticTable.length, 7, 0x80));
940
+ continue;
941
+ }
942
+ // 字面量编码
943
+ this.encodeLiteral(buffer, name_1, value);
944
+ }
945
+ return new Uint8Array(buffer);
946
+ };
947
+ // // 解码二进制数据
948
+ // decode(buffer: Uint8Array): { [key: string]: string } {
949
+ // const headers: { [key: string]: string } = {};
950
+ // let pos = 0;
951
+ // while (pos < buffer.length) {
952
+ // const firstByte = buffer[pos];
953
+ // // 检查是否是索引头部字段
954
+ // if ((firstByte & 0x80) === 0x80) {
955
+ // const { value: index, bytesRead } = this.decodeInteger(
956
+ // buffer.slice(pos),
957
+ // 7
958
+ // );
959
+ // pos += bytesRead;
960
+ // const [name, value] = this.getIndexedHeader(index);
961
+ // if (name !== undefined && value !== undefined) {
962
+ // headers[name] = value;
963
+ // }
964
+ // }
965
+ // // 字面量头部字段
966
+ // else {
967
+ // const { name, value, bytesRead } = this.decodeLiteral(
968
+ // buffer.slice(pos)
969
+ // );
970
+ // pos += bytesRead;
971
+ // headers[name] = value;
972
+ // }
973
+ // }
974
+ // return headers;
975
+ // }
976
+ // 编码整数
977
+ HPACK.prototype.encodeInteger = function (value, prefixBits, prefix) {
978
+ if (prefix === void 0) { prefix = 0; }
979
+ var buffer = [];
980
+ var mask = (1 << prefixBits) - 1;
981
+ if (value < mask) {
982
+ buffer.push(prefix | value);
983
+ return buffer;
984
+ }
985
+ buffer.push(prefix | mask);
986
+ value -= mask;
987
+ while (value >= 128) {
988
+ buffer.push((value & 127) | 128);
989
+ value = value >> 7;
990
+ }
991
+ buffer.push(value);
992
+ return buffer;
993
+ };
994
+ // // 解码整数
995
+ // decodeInteger(buffer: Uint8Array, prefixBits: number) {
996
+ // let value = buffer[0] & ((1 << prefixBits) - 1);
997
+ // let bytesRead = 1;
998
+ // if (value === (1 << prefixBits) - 1) {
999
+ // let shift = 0;
1000
+ // do {
1001
+ // value += (buffer[bytesRead] & 127) << shift;
1002
+ // shift += 7;
1003
+ // bytesRead++;
1004
+ // } while (buffer[bytesRead - 1] & 128);
1005
+ // }
1006
+ // return { value, bytesRead };
1007
+ // }
1008
+ // 编码字符串
1009
+ HPACK.prototype.encodeString = function (str) {
1010
+ var buffer = [];
1011
+ var bytes = new TextEncoder().encode(str);
1012
+ // 尝试Huffman编码
1013
+ var huffmanEncoded = this.huffmanEncode(bytes);
1014
+ if (huffmanEncoded.length < bytes.length) {
1015
+ // 使用Huffman编码
1016
+ buffer.push.apply(buffer, this.encodeInteger(huffmanEncoded.length, 7, 0x80));
1017
+ buffer.push.apply(buffer, huffmanEncoded);
1018
+ }
1019
+ else {
1020
+ // 不使用Huffman编码
1021
+ buffer.push.apply(buffer, this.encodeInteger(bytes.length, 7, 0x00));
1022
+ buffer.push.apply(buffer, bytes);
1023
+ }
1024
+ return buffer;
1025
+ };
1026
+ // 在静态表中查找
1027
+ HPACK.prototype.findInStaticTable = function (name, value) {
1028
+ for (var i = 1; i < this.staticTable.length; i++) {
1029
+ if (this.staticTable[i][0] === name &&
1030
+ this.staticTable[i][1] === value) {
1031
+ return i;
1032
+ }
1033
+ }
1034
+ return -1;
1035
+ };
1036
+ // 在动态表中查找
1037
+ HPACK.prototype.findInDynamicTable = function (name, value) {
1038
+ for (var i = 0; i < this.dynamicTable.length; i++) {
1039
+ if (this.dynamicTable[i][0] === name &&
1040
+ this.dynamicTable[i][1] === value) {
1041
+ return i;
1042
+ }
1043
+ }
1044
+ return -1;
1045
+ };
1046
+ // 编码字面量头部字段
1047
+ HPACK.prototype.encodeLiteral = function (buffer, name, value) {
1048
+ var nameIndex = this.findInStaticTable(name, '');
1049
+ if (nameIndex !== -1) {
1050
+ // 名称索引存在
1051
+ buffer.push.apply(buffer, this.encodeInteger(nameIndex, 6, 0x40));
1052
+ }
1053
+ else {
1054
+ // 名称需要字面量编码
1055
+ buffer.push(0x40);
1056
+ buffer.push.apply(buffer, this.encodeString(name));
1057
+ }
1058
+ // 值总是需要字面量编码
1059
+ buffer.push.apply(buffer, this.encodeString(value));
1060
+ // 添加到动态表
1061
+ this.addToDynamicTable(name, value);
1062
+ };
1063
+ // 添加到动态表
1064
+ HPACK.prototype.addToDynamicTable = function (name, value) {
1065
+ var size = name.length + value.length + 32; // 32 bytes overhead
1066
+ // 确保不超过最大大小
1067
+ while (this.dynamicTableSize + size > this.maxDynamicTableSize &&
1068
+ this.dynamicTable.length > 0) {
1069
+ var entry = this.dynamicTable.pop();
1070
+ if (entry) {
1071
+ this.dynamicTableSize -= entry[0].length + entry[1].length + 32;
1072
+ }
1073
+ }
1074
+ if (size <= this.maxDynamicTableSize) {
1075
+ this.dynamicTable.unshift([name, value]);
1076
+ this.dynamicTableSize += size;
1077
+ }
1078
+ this.dynamicTable.push([name, value]);
1079
+ };
1080
+ // 获取索引的头部
1081
+ HPACK.prototype.getIndexedHeader = function (index) {
1082
+ if (index <= this.staticTable.length - 1) {
1083
+ return this.staticTable[index];
1084
+ }
1085
+ return this.dynamicTable[index - this.staticTable.length];
1086
+ };
1087
+ HPACK.prototype.buildHuffmanTable = function () {
1088
+ // HTTP/2规范中定义的完整Huffman编码表
1089
+ return {
1090
+ codes: new Uint32Array([
1091
+ 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7,
1092
+ 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec,
1093
+ 0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3,
1094
+ 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb,
1095
+ 0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa,
1096
+ 0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18,
1097
+ 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
1098
+ 0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc,
1099
+ 0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
1100
+ 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
1101
+ 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,
1102
+ 0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22,
1103
+ 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26,
1104
+ 0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7,
1105
+ 0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78,
1106
+ 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc,
1107
+ 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9,
1108
+ 0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf,
1109
+ 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3,
1110
+ 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef,
1111
+ 0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde,
1112
+ 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec,
1113
+ 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef,
1114
+ 0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1,
1115
+ 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec,
1116
+ 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed,
1117
+ 0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2,
1118
+ 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5,
1119
+ 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3,
1120
+ 0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4,
1121
+ 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea,
1122
+ 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee
1123
+ ]),
1124
+ lengths: new Uint8Array([
1125
+ 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28,
1126
+ 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28,
1127
+ 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6,
1128
+ 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10,
1129
+ 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
1130
+ 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6,
1131
+ 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5,
1132
+ 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28,
1133
+ 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23,
1134
+ 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24,
1135
+ 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23,
1136
+ 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23,
1137
+ 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25,
1138
+ 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27,
1139
+ 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23,
1140
+ 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26
1141
+ ])
1142
+ };
1143
+ };
1144
+ /**
1145
+ * 解码Uint8Array为字符串
1146
+ * @param input 编码后的Uint8Array
1147
+ * @returns 解码后的字符串
1148
+ */
1149
+ HPACK.prototype.decode = function (input) {
1150
+ var result = '';
1151
+ var accumulator = 0;
1152
+ var bits = 0;
1153
+ for (var i = 0; i < input.length; i++) {
1154
+ var byte = input[i];
1155
+ accumulator = (accumulator << 8) | byte;
1156
+ bits += 8;
1157
+ while (bits >= 5) {
1158
+ var decoded = this.findSymbol(accumulator, bits);
1159
+ if (!decoded) {
1160
+ break;
1161
+ }
1162
+ var symbol = decoded[0], length_1 = decoded[1];
1163
+ result += String.fromCharCode(symbol);
1164
+ accumulator &= (1 << (bits - length_1)) - 1;
1165
+ bits -= length_1;
1166
+ }
1167
+ }
1168
+ // 验证填充
1169
+ if (bits > 0) {
1170
+ var mask = (1 << bits) - 1;
1171
+ if ((accumulator & mask) !== mask) {
1172
+ throw new Error('Invalid Huffman padding');
1173
+ }
1174
+ }
1175
+ return result;
1176
+ };
1177
+ /**
1178
+ * 在Huffman树中查找符号
1179
+ */
1180
+ HPACK.prototype.findSymbol = function (value, bits) {
1181
+ for (var i = 0; i < this.huffmanTable.codes.length; i++) {
1182
+ var length_2 = this.huffmanTable.lengths[i];
1183
+ if (bits < length_2)
1184
+ continue;
1185
+ var code = (value >> (bits - length_2)) & ((1 << length_2) - 1);
1186
+ if (code === this.huffmanTable.codes[i]) {
1187
+ return [i, length_2];
1188
+ }
1189
+ }
1190
+ return null;
1191
+ };
1192
+ // Huffman编码实现
1193
+ HPACK.prototype.huffmanEncode = function (bytes) {
1194
+ var result = [];
1195
+ var current = 0;
1196
+ var bits = 0;
1197
+ for (var i = 0; i < bytes.length; i++) {
1198
+ var b = bytes[i];
1199
+ var code = this.huffmanTable.codes[b];
1200
+ var length_3 = this.huffmanTable.lengths[b];
1201
+ bits += length_3;
1202
+ current = (current << length_3) | code;
1203
+ while (bits >= 8) {
1204
+ bits -= 8;
1205
+ result.push((current >> bits) & 0xFF);
1206
+ }
1207
+ }
1208
+ // 处理剩余的位
1209
+ if (bits > 0) {
1210
+ current = (current << (8 - bits)) | ((1 << (8 - bits)) - 1);
1211
+ result.push(current & 0xFF);
1212
+ }
1213
+ return new Uint8Array(result);
1214
+ };
1215
+ HPACK.prototype.decodeHeaderFields = function (buffer) {
1216
+ var headers = new Map();
1217
+ var index = 0;
1218
+ while (index < buffer.length) {
1219
+ var firstByte = buffer[index];
1220
+ // 检查首字节的类型
1221
+ if ((firstByte & 0x80) !== 0) { // 1xxxxxxx - Indexed Header Field
1222
+ var _a = this.decodeIndexedHeader(buffer, index), name_2 = _a[0], value = _a[1], newIndex = _a[2];
1223
+ if (name_2 && value)
1224
+ headers.set(name_2, value);
1225
+ index = newIndex;
1226
+ }
1227
+ else if ((firstByte & 0x40) !== 0) { // 01xxxxxx - Literal Header Field with Incremental Indexing
1228
+ var _b = this.decodeLiteralHeaderWithIndexing(buffer, index), name_3 = _b[0], value = _b[1], newIndex = _b[2];
1229
+ if (name_3 && value)
1230
+ headers.set(name_3, value);
1231
+ index = newIndex;
1232
+ }
1233
+ else if ((firstByte & 0x20) !== 0) { // 001xxxxx - Dynamic Table Size Update
1234
+ index++; // 简单跳过,实际应该更新动态表大小
1235
+ }
1236
+ else if ((firstByte & 0x10) !== 0) { // 0001xxxx - Literal Header Field Never Indexed
1237
+ var _c = this.decodeLiteralHeaderWithoutIndexing(buffer, index), name_4 = _c[0], value = _c[1], newIndex = _c[2];
1238
+ if (name_4 && value)
1239
+ headers.set(name_4, value);
1240
+ index = newIndex;
1241
+ }
1242
+ else { // 0000xxxx - Literal Header Field without Indexing
1243
+ var _d = this.decodeLiteralHeaderWithoutIndexing(buffer, index), name_5 = _d[0], value = _d[1], newIndex = _d[2];
1244
+ if (name_5 && value)
1245
+ headers.set(name_5, value);
1246
+ index = newIndex;
1247
+ }
1248
+ }
1249
+ return headers;
1250
+ };
1251
+ HPACK.prototype.decodeInteger = function (buffer, startIndex, prefixBits) {
1252
+ var prefix = (1 << prefixBits) - 1;
1253
+ var firstByte = buffer[startIndex];
1254
+ var index = startIndex;
1255
+ var value = firstByte & prefix;
1256
+ if (value < prefix) {
1257
+ return [value, index + 1];
1258
+ }
1259
+ index++;
1260
+ var shift = 0;
1261
+ while (index < buffer.length) {
1262
+ var byte = buffer[index++];
1263
+ value += (byte & 0x7F) << shift;
1264
+ shift += 7;
1265
+ if ((byte & 0x80) === 0) {
1266
+ break;
1267
+ }
1268
+ }
1269
+ return [value, index];
1270
+ };
1271
+ HPACK.prototype.decodeLiteralString = function (buffer, startIndex) {
1272
+ if (startIndex >= buffer.length) {
1273
+ return ['', startIndex];
1274
+ }
1275
+ var firstByte = buffer[startIndex];
1276
+ var isHuffman = (firstByte & 0x80) !== 0;
1277
+ var _a = this.decodeInteger(buffer, startIndex, 7), length = _a[0], index = _a[1];
1278
+ if (index + length > buffer.length) {
1279
+ return ['', index];
1280
+ }
1281
+ var bytes = buffer.slice(index, index + length);
1282
+ var result;
1283
+ if (isHuffman) {
1284
+ try {
1285
+ result = this.decode(bytes);
1286
+ }
1287
+ catch (e) {
1288
+ result = '';
1289
+ }
1290
+ }
1291
+ else {
1292
+ try {
1293
+ // result = new TextDecoder().decode(bytes);
1294
+ result = toString(bytes);
1295
+ }
1296
+ catch (e) {
1297
+ result = '';
1298
+ }
1299
+ }
1300
+ return [result, index + length];
1301
+ };
1302
+ HPACK.prototype.decodeIndexedHeader = function (buffer, index) {
1303
+ var _a = this.decodeInteger(buffer, index, 7), staticIndex = _a[0], newIndex = _a[1];
1304
+ if (staticIndex <= 0) {
1305
+ return ['', '', newIndex];
1306
+ }
1307
+ var headerField = this.staticTable[staticIndex];
1308
+ if (!headerField) {
1309
+ return ['', '', newIndex];
1310
+ }
1311
+ return [headerField[0], headerField[1], newIndex];
1312
+ };
1313
+ HPACK.prototype.decodeLiteralHeaderWithIndexing = function (buffer, index) {
1314
+ var _a = this.decodeInteger(buffer, index, 6), staticIndex = _a[0], nameIndex = _a[1];
1315
+ index = nameIndex;
1316
+ var name;
1317
+ if (staticIndex > 0) {
1318
+ var headerField = this.staticTable[staticIndex];
1319
+ name = headerField ? headerField[0] : '';
1320
+ }
1321
+ else {
1322
+ var _b = this.decodeLiteralString(buffer, index), decodedName = _b[0], newIndex = _b[1];
1323
+ name = decodedName;
1324
+ index = newIndex;
1325
+ }
1326
+ var _c = this.decodeLiteralString(buffer, index), value = _c[0], finalIndex = _c[1];
1327
+ return [name, value, finalIndex];
1328
+ };
1329
+ HPACK.prototype.decodeLiteralHeaderWithoutIndexing = function (buffer, index) {
1330
+ return this.decodeLiteralHeaderWithIndexing(buffer, index);
1331
+ };
1332
+ // 直接转换为字符串的方法
1333
+ HPACK.prototype.huffmanDecodeToString = function (bytes) {
1334
+ return this.decode(bytes);
1335
+ };
1336
+ return HPACK;
1337
+ }());
1338
+
1339
+ var FrameEncoder = /** @class */ (function () {
1340
+ function FrameEncoder() {
1341
+ }
1342
+ // 编码SETTINGS帧
1343
+ FrameEncoder.encodeSettingsFrame = function (frame) {
1344
+ // 计算payload总长度:每个设置项占6字节
1345
+ var payloadLength = frame.payload.length * 6;
1346
+ // 分配缓冲区:9字节头部 + payload长度
1347
+ var buffer = new Uint8Array(9 + payloadLength);
1348
+ // 编码帧头部(前9个字节)
1349
+ _encodeFrameHeader(buffer, {
1350
+ length: payloadLength,
1351
+ type: frame.type,
1352
+ flags: frame.flags,
1353
+ streamId: frame.streamId
1354
+ });
1355
+ // 编码payload
1356
+ _encodeSettingsPayload(buffer, frame.payload);
1357
+ return buffer;
1358
+ };
1359
+ // 编码SETTINGS ACK帧
1360
+ FrameEncoder.encodeSettingsAckFrame = function () {
1361
+ var buffer = new Uint8Array(9); // ACK帧只有头部
1362
+ _encodeFrameHeader(buffer, {
1363
+ length: 0,
1364
+ type: 0x4, // SETTINGS
1365
+ flags: 0x1, // ACK
1366
+ streamId: 0
1367
+ });
1368
+ return buffer;
1369
+ };
1370
+ return FrameEncoder;
1371
+ }());
1372
+ // 编码帧头部(9字节)
1373
+ function _encodeFrameHeader(buffer, header) {
1374
+ var _a;
1375
+ // Length: 3 bytes
1376
+ var length = (_a = header.length) !== null && _a !== void 0 ? _a : 0;
1377
+ buffer[0] = (length >> 16) & 0xFF;
1378
+ buffer[1] = (length >> 8) & 0xFF;
1379
+ buffer[2] = length & 0xFF;
1380
+ // Type: 1 byte
1381
+ buffer[3] = header.type;
1382
+ // Flags: 1 byte
1383
+ buffer[4] = header.flags;
1384
+ // Stream Identifier: 4 bytes
1385
+ _writeUInt32BE(buffer, header.streamId & 0x7FFFFFFF, 5);
1386
+ }
1387
+ // 编码SETTINGS payload
1388
+ function _encodeSettingsPayload(buffer, payload) {
1389
+ var offset = 9; // 从第9个字节开始
1390
+ payload.forEach(function (setting) {
1391
+ // 写入2字节的标识符
1392
+ _writeUInt16BE(buffer, setting.identifier, offset);
1393
+ offset += 2;
1394
+ // 写入4字节的值
1395
+ _writeUInt32BE(buffer, setting.value, offset);
1396
+ offset += 4;
1397
+ });
1398
+ }
1399
+ // 写入16位无符号整数(大端序)
1400
+ function _writeUInt16BE(buffer, value, offset) {
1401
+ buffer[offset] = (value >> 8) & 0xFF;
1402
+ buffer[offset + 1] = value & 0xFF;
1403
+ }
1404
+ // 写入32位无符号整数(大端序)
1405
+ function _writeUInt32BE(buffer, value, offset) {
1406
+ buffer[offset] = (value >> 24) & 0xFF;
1407
+ buffer[offset + 1] = (value >> 16) & 0xFF;
1408
+ buffer[offset + 2] = (value >> 8) & 0xFF;
1409
+ buffer[offset + 3] = value & 0xFF;
1410
+ }
1411
+
1412
+ var _a;
1413
+ var SETTINGS_PARAMETERS = {
1414
+ HEADER_TABLE_SIZE: 0x1,
1415
+ ENABLE_PUSH: 0x2,
1416
+ MAX_CONCURRENT_STREAMS: 0x3,
1417
+ INITIAL_WINDOW_SIZE: 0x4,
1418
+ MAX_FRAME_SIZE: 0x5,
1419
+ MAX_HEADER_LIST_SIZE: 0x6
1420
+ };
1421
+ var defaultSettings = (_a = {},
1422
+ _a[SETTINGS_PARAMETERS.HEADER_TABLE_SIZE] = 4096,
1423
+ _a[SETTINGS_PARAMETERS.ENABLE_PUSH] = 1,
1424
+ _a[SETTINGS_PARAMETERS.MAX_CONCURRENT_STREAMS] = 100,
1425
+ _a[SETTINGS_PARAMETERS.INITIAL_WINDOW_SIZE] = 4 << 20,
1426
+ _a[SETTINGS_PARAMETERS.MAX_FRAME_SIZE] = 4 << 20,
1427
+ _a[SETTINGS_PARAMETERS.MAX_HEADER_LIST_SIZE] = 8192,
1428
+ _a);
1429
+ var HTTP2_PREFACE = 'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n';
1430
+ var Http2Frame = /** @class */ (function () {
1431
+ function Http2Frame() {
1432
+ }
1433
+ // 创建并编码PREFACE帧
1434
+ Http2Frame.createPreface = function () {
1435
+ return new TextEncoder().encode(HTTP2_PREFACE);
1436
+ };
1437
+ Http2Frame.createPongFrame = function (payload) {
1438
+ return Http2Frame.createFrame(0x6, 0x1, 0, payload);
1439
+ };
1440
+ // 创建并编码SETTINGS帧
1441
+ Http2Frame.createSettingsFrame = function (settings) {
1442
+ if (settings === void 0) { settings = {}; }
1443
+ // 先创建帧对象
1444
+ var frame = Http2Frame.createOriginSettingsFrame(settings);
1445
+ // 然后编码
1446
+ return FrameEncoder.encodeSettingsFrame(frame);
1447
+ };
1448
+ // 创建并编码SETTINGS ACK帧
1449
+ Http2Frame.createSettingsAckFrame = function () {
1450
+ return FrameEncoder.encodeSettingsAckFrame();
1451
+ };
1452
+ Http2Frame.createDataFrames = function (streamId, data, shouldEnd, maxFrameSize) {
1453
+ if (shouldEnd === void 0) { shouldEnd = false; }
1454
+ if (maxFrameSize === void 0) { maxFrameSize = 1024; }
1455
+ var frames = [];
1456
+ var offset = 0;
1457
+ while (offset < data.length) {
1458
+ var chunkSize = Math.min(maxFrameSize, data.length - offset);
1459
+ var chunk = data.slice(offset, offset + chunkSize);
1460
+ var isEndStream = shouldEnd && (offset + chunkSize >= data.length); // 最后一帧设置 END_STREAM
1461
+ var frame = Http2Frame.createDataFrame(streamId, chunk, isEndStream);
1462
+ frames.push(frame);
1463
+ offset += chunkSize;
1464
+ }
1465
+ return frames;
1466
+ };
1467
+ Http2Frame.createDataFrame = function (streamId, data, endStream) {
1468
+ if (endStream === void 0) { endStream = true; }
1469
+ // gRPC 消息格式: 压缩标志(1字节) + 消息长度(4字节) + 消息内容
1470
+ var messageLen = data.length;
1471
+ var framedData = new Uint8Array(5 + messageLen);
1472
+ // Compression flag (0 = 不压缩)
1473
+ framedData[0] = 0;
1474
+ // Message length (4 bytes)
1475
+ framedData[1] = (messageLen >> 24) & 0xFF;
1476
+ framedData[2] = (messageLen >> 16) & 0xFF;
1477
+ framedData[3] = (messageLen >> 8) & 0xFF;
1478
+ framedData[4] = messageLen & 0xFF;
1479
+ // Message content
1480
+ framedData.set(data, 5);
1481
+ var flags = endStream ? 0x01 : 0x0; // END_STREAM flag
1482
+ return Http2Frame.createFrame(0x0, flags, streamId, framedData);
1483
+ };
1484
+ Http2Frame.createHeadersFrame = function (streamId, path, endHeaders, token) {
1485
+ if (endHeaders === void 0) { endHeaders = true; }
1486
+ // gRPC-Web 需要的标准 headers
1487
+ var headersList = {
1488
+ ':path': path,
1489
+ ':method': 'POST',
1490
+ ':scheme': 'http',
1491
+ ':authority': 'localhost',
1492
+ 'content-type': 'application/grpc+proto',
1493
+ 'user-agent': 'grpc-web-client/0.1',
1494
+ 'accept': 'application/grpc+proto',
1495
+ 'grpc-timeout': '3600S'
1496
+ };
1497
+ if (token) {
1498
+ headersList['authorization'] = "Bearer ".concat(token);
1499
+ }
1500
+ // 将 headers 编码为 HPACK 格式
1501
+ var hpack = new HPACK();
1502
+ var encodedHeaders = hpack.encode(headersList);
1503
+ console.log('Encoded:', encodedHeaders);
1504
+ // HEADERS frame flags: END_HEADERS | END_STREAM
1505
+ var flags = endHeaders ? 0x04 : 0x00;
1506
+ return Http2Frame.createFrame(0x01, flags, streamId, encodedHeaders);
1507
+ };
1508
+ Http2Frame.createResponseHeadersFrame = function (streamId, headersList, endHeaders) {
1509
+ if (endHeaders === void 0) { endHeaders = true; }
1510
+ // 将 headers 编码为 HPACK 格式
1511
+ var hpack = new HPACK();
1512
+ var encodedHeaders = hpack.encode(headersList);
1513
+ console.log('Encoded:', encodedHeaders);
1514
+ // HEADERS frame flags: END_HEADERS | END_STREAM
1515
+ var flags = endHeaders ? 0x04 : 0x00;
1516
+ return Http2Frame.createFrame(0x01, flags, streamId, encodedHeaders);
1517
+ };
1518
+ Http2Frame.createTrailersFrame = function (streamId, trailers) {
1519
+ // 将 trailers 编码为 HPACK 格式
1520
+ var hpack = new HPACK();
1521
+ var encodedTrailers = hpack.encode(trailers);
1522
+ // HEADERS frame flags: END_HEADERS | END_STREAM
1523
+ var flags = 0x05; // 0x04 (END_HEADERS) | 0x01 (END_STREAM)
1524
+ return Http2Frame.createFrame(0x01, flags, streamId, encodedTrailers);
1525
+ };
1526
+ // 创建 SETTINGS 帧
1527
+ Http2Frame.createOriginSettingsFrame = function (settings) {
1528
+ if (settings === void 0) { settings = {}; }
1529
+ // 合并默认值和用户提供的设置
1530
+ var finalSettings = __assign(__assign({}, defaultSettings), settings);
1531
+ // 验证设置值
1532
+ _validateSettings(finalSettings);
1533
+ // 创建帧
1534
+ var frame = {
1535
+ type: 0x4, // SETTINGS frame type
1536
+ flags: 0x0, // 无标志
1537
+ streamId: 0, // SETTINGS 总是在 stream 0 上发送
1538
+ payload: _createPayload(finalSettings)
1539
+ };
1540
+ return frame;
1541
+ };
1542
+ // 创建确认帧(SETTINGS ACK)
1543
+ Http2Frame.createOriginSettingsAckFrame = function () {
1544
+ return {
1545
+ type: 0x4, // SETTINGS frame type
1546
+ flags: 0x1, // ACK flag
1547
+ streamId: 0,
1548
+ payload: [] // ACK 帧没有payload
1549
+ };
1550
+ };
1551
+ Http2Frame.createFrame = function (type, flags, streamId, payload) {
1552
+ var length = payload ? payload.length : 0;
1553
+ var frame = new Uint8Array(9 + length); // 9 bytes for header + payload
1554
+ // Length (24 bits)
1555
+ frame[0] = (length >> 16) & 0xFF;
1556
+ frame[1] = (length >> 8) & 0xFF;
1557
+ frame[2] = length & 0xFF;
1558
+ // Type (8 bits)
1559
+ frame[3] = type;
1560
+ // Flags (8 bits)
1561
+ frame[4] = flags;
1562
+ // Stream Identifier (32 bits)
1563
+ frame[5] = (streamId >> 24) & 0xFF;
1564
+ frame[6] = (streamId >> 16) & 0xFF;
1565
+ frame[7] = (streamId >> 8) & 0xFF;
1566
+ frame[8] = streamId & 0xFF;
1567
+ if (payload && length > 0) {
1568
+ frame.set(payload, 9);
1569
+ }
1570
+ return frame;
1571
+ };
1572
+ return Http2Frame;
1573
+ }());
1574
+ // 验证设置值
1575
+ function _validateSettings(settings) {
1576
+ for (var _i = 0, _a = Object.entries(settings); _i < _a.length; _i++) {
1577
+ var _b = _a[_i], id = _b[0], value = _b[1];
1578
+ switch (Number(id)) {
1579
+ case SETTINGS_PARAMETERS.HEADER_TABLE_SIZE:
1580
+ if (value < 0) {
1581
+ throw new Error('HEADER_TABLE_SIZE must be non-negative');
1582
+ }
1583
+ break;
1584
+ case SETTINGS_PARAMETERS.ENABLE_PUSH:
1585
+ if (value !== 0 && value !== 1) {
1586
+ throw new Error('ENABLE_PUSH must be 0 or 1');
1587
+ }
1588
+ break;
1589
+ case SETTINGS_PARAMETERS.INITIAL_WINDOW_SIZE:
1590
+ if (value < 0 || value > 2147483647) { // 2^31 - 1
1591
+ throw new Error('INITIAL_WINDOW_SIZE must be between 0 and 2^31-1');
1592
+ }
1593
+ break;
1594
+ case SETTINGS_PARAMETERS.MAX_FRAME_SIZE:
1595
+ if (value < 16384 || value > 16777215) { // 2^14 to 2^24-1
1596
+ throw new Error('MAX_FRAME_SIZE must be between 16,384 and 16,777,215');
1597
+ }
1598
+ break;
1599
+ case SETTINGS_PARAMETERS.MAX_CONCURRENT_STREAMS:
1600
+ case SETTINGS_PARAMETERS.MAX_HEADER_LIST_SIZE:
1601
+ if (value < 0) {
1602
+ throw new Error("Parameter ".concat(id, " must be non-negative"));
1603
+ }
1604
+ break;
1605
+ default:
1606
+ console.warn("Unknown settings parameter: ".concat(id));
1607
+ }
1608
+ }
1609
+ }
1610
+ // 创建payload
1611
+ function _createPayload(settings) {
1612
+ var payload = [];
1613
+ for (var _i = 0, _a = Object.entries(settings); _i < _a.length; _i++) {
1614
+ var _b = _a[_i], id = _b[0], value = _b[1];
1615
+ payload.push({
1616
+ identifier: Number(id),
1617
+ value: value
1618
+ });
1619
+ }
1620
+ return payload;
1621
+ }
1622
+
1623
+ var HTTP2Parser = /** @class */ (function () {
1624
+ function HTTP2Parser(writer) {
1625
+ this.buffer = new Uint8Array(0);
1626
+ this.settingsAckReceived = false;
1627
+ // 初始化连接级别的流控制窗口大小(默认值:65,535)
1628
+ this.connectionWindowSize = 4 << 20;
1629
+ // 存储流的Map
1630
+ this.streams = new Map();
1631
+ // 默认的流级别初始窗口大小
1632
+ this.defaultStreamWindowSize = 4 << 20;
1633
+ // 结束标志
1634
+ this.endFlag = false;
1635
+ this.writer = writer;
1636
+ }
1637
+ // 持续处理流数据
1638
+ HTTP2Parser.prototype.processStream = function (stream) {
1639
+ return __awaiter(this, void 0, void 0, function () {
1640
+ var _a, _b, _c, chunk, newData, newBuffer, settingFrme, frameHeader, totalFrameLength, frameData, e_1_1, error_1;
1641
+ var _d, e_1, _e, _f;
1642
+ return __generator(this, function (_g) {
1643
+ switch (_g.label) {
1644
+ case 0:
1645
+ _g.trys.push([0, 15, , 16]);
1646
+ _g.label = 1;
1647
+ case 1:
1648
+ _g.trys.push([1, 8, 9, 14]);
1649
+ _a = true, _b = __asyncValues(stream.source);
1650
+ _g.label = 2;
1651
+ case 2: return [4 /*yield*/, _b.next()];
1652
+ case 3:
1653
+ if (!(_c = _g.sent(), _d = _c.done, !_d)) return [3 /*break*/, 7];
1654
+ _f = _c.value;
1655
+ _a = false;
1656
+ chunk = _f;
1657
+ newData = chunk.subarray();
1658
+ newBuffer = new Uint8Array(this.buffer.length + newData.length);
1659
+ newBuffer.set(this.buffer);
1660
+ newBuffer.set(newData, this.buffer.length);
1661
+ this.buffer = newBuffer;
1662
+ _g.label = 4;
1663
+ case 4:
1664
+ if (!(this.buffer.length >= 9)) return [3 /*break*/, 6];
1665
+ // 判断是否有HTTP/2前导
1666
+ if (this.buffer.length >= 24 && this.isHttp2Preface(this.buffer)) {
1667
+ console.log("HTTP/2 preface detected");
1668
+ this.buffer = this.buffer.slice(24);
1669
+ settingFrme = Http2Frame.createSettingsFrame();
1670
+ this.writer.write(settingFrme);
1671
+ return [3 /*break*/, 6];
1672
+ }
1673
+ frameHeader = this._parseFrameHeader(this.buffer);
1674
+ totalFrameLength = 9 + frameHeader.length;
1675
+ // 检查是否有完整的帧
1676
+ if (this.buffer.length < totalFrameLength) {
1677
+ return [3 /*break*/, 6];
1678
+ }
1679
+ frameData = this.buffer.slice(0, totalFrameLength);
1680
+ // 处理不同类型的帧
1681
+ return [4 /*yield*/, this._handleFrame(frameHeader, frameData)];
1682
+ case 5:
1683
+ // 处理不同类型的帧
1684
+ _g.sent();
1685
+ // 移除已处理的帧
1686
+ this.buffer = this.buffer.slice(totalFrameLength);
1687
+ return [3 /*break*/, 4];
1688
+ case 6:
1689
+ _a = true;
1690
+ return [3 /*break*/, 2];
1691
+ case 7: return [3 /*break*/, 14];
1692
+ case 8:
1693
+ e_1_1 = _g.sent();
1694
+ e_1 = { error: e_1_1 };
1695
+ return [3 /*break*/, 14];
1696
+ case 9:
1697
+ _g.trys.push([9, , 12, 13]);
1698
+ if (!(!_a && !_d && (_e = _b.return))) return [3 /*break*/, 11];
1699
+ return [4 /*yield*/, _e.call(_b)];
1700
+ case 10:
1701
+ _g.sent();
1702
+ _g.label = 11;
1703
+ case 11: return [3 /*break*/, 13];
1704
+ case 12:
1705
+ if (e_1) throw e_1.error;
1706
+ return [7 /*endfinally*/];
1707
+ case 13: return [7 /*endfinally*/];
1708
+ case 14: return [3 /*break*/, 16];
1709
+ case 15:
1710
+ error_1 = _g.sent();
1711
+ console.error("Error processing stream:", error_1);
1712
+ throw error_1;
1713
+ case 16: return [2 /*return*/];
1714
+ }
1715
+ });
1716
+ });
1717
+ };
1718
+ HTTP2Parser.prototype.isHttp2Preface = function (buffer) {
1719
+ var PREFACE = new TextEncoder().encode("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
1720
+ if (buffer.length < PREFACE.length)
1721
+ return false;
1722
+ for (var i = 0; i < PREFACE.length; i++) {
1723
+ if (buffer[i] !== PREFACE[i])
1724
+ return false;
1725
+ }
1726
+ return true;
1727
+ };
1728
+ // 等待SETTINGS ACK
1729
+ HTTP2Parser.prototype.waitForSettingsAck = function () {
1730
+ var _this = this;
1731
+ return new Promise(function (resolve, reject) {
1732
+ if (_this.settingsAckReceived) {
1733
+ resolve();
1734
+ return;
1735
+ }
1736
+ var interval = setInterval(function () {
1737
+ if (_this.settingsAckReceived) {
1738
+ clearInterval(interval);
1739
+ clearTimeout(timeout);
1740
+ resolve();
1741
+ }
1742
+ }, 100);
1743
+ var timeout = setTimeout(function () {
1744
+ clearInterval(interval);
1745
+ reject(new Error("Settings ACK timeout"));
1746
+ }, 30000);
1747
+ });
1748
+ };
1749
+ // 处理单个帧
1750
+ HTTP2Parser.prototype._handleFrame = function (frameHeader, frameData) {
1751
+ return __awaiter(this, void 0, void 0, function () {
1752
+ var settingsPayload, settings, i, id, value;
1753
+ return __generator(this, function (_a) {
1754
+ switch (frameHeader.type) {
1755
+ case FRAME_TYPES.SETTINGS:
1756
+ if ((frameHeader.flags & FRAME_FLAGS.ACK) === FRAME_FLAGS.ACK) {
1757
+ this.settingsAckReceived = true;
1758
+ console.log("Received SETTINGS ACK");
1759
+ }
1760
+ else {
1761
+ settingsPayload = frameData.slice(9);
1762
+ settings = {};
1763
+ for (i = 0; i < settingsPayload.length; i += 6) {
1764
+ id = settingsPayload[i];
1765
+ value = (settingsPayload[i + 1] << 16) |
1766
+ (settingsPayload[i + 2] << 8) |
1767
+ settingsPayload[i + 3];
1768
+ settings[id] = value;
1769
+ }
1770
+ console.log("Received SETTINGS:", settings);
1771
+ //发送ACK
1772
+ if (this.onSettings) {
1773
+ this.onSettings(frameHeader);
1774
+ }
1775
+ }
1776
+ break;
1777
+ case FRAME_TYPES.DATA:
1778
+ // 处理数据帧
1779
+ if (this.onData) {
1780
+ this.onData(frameData.slice(9), frameHeader); // 跳过帧头
1781
+ }
1782
+ //判断是否是最后一个帧
1783
+ if ((frameHeader.flags & FRAME_FLAGS.END_STREAM) ===
1784
+ FRAME_FLAGS.END_STREAM) {
1785
+ this.endFlag = true;
1786
+ if (this.onEnd) {
1787
+ this.onEnd();
1788
+ }
1789
+ return [2 /*return*/];
1790
+ }
1791
+ break;
1792
+ case FRAME_TYPES.HEADERS:
1793
+ // 处理头部帧
1794
+ if (this.onHeaders) {
1795
+ this.onHeaders(frameData.slice(9), frameHeader);
1796
+ }
1797
+ //判断是否是最后一个帧
1798
+ if ((frameHeader.flags & FRAME_FLAGS.END_STREAM) ===
1799
+ FRAME_FLAGS.END_STREAM) {
1800
+ this.endFlag = true;
1801
+ if (this.onEnd) {
1802
+ this.onEnd();
1803
+ }
1804
+ return [2 /*return*/];
1805
+ }
1806
+ break;
1807
+ case FRAME_TYPES.WINDOW_UPDATE:
1808
+ // 处理窗口更新帧
1809
+ this.handleWindowUpdateFrame(frameHeader, frameData, frameHeader.streamId);
1810
+ break;
1811
+ case FRAME_TYPES.PING:
1812
+ // 处理PING帧
1813
+ this._handlePingFrame(frameHeader, frameData);
1814
+ break;
1815
+ // case FRAME_TYPES.PUSH_PROMISE:
1816
+ // // 处理服务器推送承诺帧
1817
+ // this.handlePushPromiseFrame(frameHeader, frameData);
1818
+ // break;
1819
+ case FRAME_TYPES.RST_STREAM:
1820
+ this.endFlag = true;
1821
+ if (this.onEnd) {
1822
+ this.onEnd();
1823
+ }
1824
+ break;
1825
+ default:
1826
+ console.debug("Unknown frame type:", frameHeader.type);
1827
+ }
1828
+ return [2 /*return*/];
1829
+ });
1830
+ });
1831
+ };
1832
+ HTTP2Parser.prototype._parseFrameHeader = function (buffer) {
1833
+ var length = (buffer[0] << 16) | (buffer[1] << 8) | buffer[2];
1834
+ var type = buffer[3];
1835
+ var flags = buffer[4];
1836
+ var streamId = (buffer[5] << 24) | (buffer[6] << 16) | (buffer[7] << 8) | buffer[8];
1837
+ return {
1838
+ length: length,
1839
+ type: type,
1840
+ flags: flags,
1841
+ streamId: streamId,
1842
+ payload: buffer.slice(0, 9),
1843
+ };
1844
+ };
1845
+ // 解析PING帧
1846
+ HTTP2Parser.prototype._handlePingFrame = function (frameHeader, frameData) {
1847
+ // PING帧的payload固定为8字节
1848
+ if (frameHeader.length !== 8) {
1849
+ throw new Error("PING frame must have a length of 8 bytes");
1850
+ }
1851
+ // 反馈PONG帧
1852
+ var pongFrame = Http2Frame.createPongFrame(frameData.slice(9));
1853
+ try {
1854
+ this.writer.write(pongFrame);
1855
+ }
1856
+ catch (error) {
1857
+ console.error("Error sending PONG frame:", error);
1858
+ throw error;
1859
+ }
1860
+ };
1861
+ //等待流结束
1862
+ HTTP2Parser.prototype.waitForEndOfStream = function (waitTime) {
1863
+ var _this = this;
1864
+ return new Promise(function (resolve, reject) {
1865
+ // If the stream has already ended, resolve immediately
1866
+ if (_this.endFlag) {
1867
+ resolve();
1868
+ return;
1869
+ }
1870
+ // 如果是0 ,则不设置超时
1871
+ var timeout = null;
1872
+ if (waitTime > 0) {
1873
+ timeout = setTimeout(function () {
1874
+ clearInterval(interval);
1875
+ reject(new Error("End of stream timeout"));
1876
+ }, waitTime);
1877
+ }
1878
+ // Check interval for real-time endFlag monitoring
1879
+ var checkInterval = 100; // Check every 100 milliseconds
1880
+ // Set an interval to check the endFlag regularly
1881
+ var interval = setInterval(function () {
1882
+ if (_this.endFlag) {
1883
+ if (timeout !== null) {
1884
+ clearTimeout(timeout);
1885
+ }
1886
+ clearInterval(interval);
1887
+ resolve();
1888
+ }
1889
+ }, checkInterval);
1890
+ // If the onEnd is triggered externally, it should now be marked manually
1891
+ var originalOnEnd = _this.onEnd;
1892
+ _this.onEnd = function () {
1893
+ if (!_this.endFlag) {
1894
+ // The external trigger may set endFlag; if not, handle here
1895
+ _this.endFlag = true;
1896
+ }
1897
+ if (timeout !== null) {
1898
+ clearTimeout(timeout);
1899
+ }
1900
+ clearInterval(interval);
1901
+ resolve();
1902
+ if (originalOnEnd) {
1903
+ originalOnEnd(); // Call the original onEnd function if set
1904
+ }
1905
+ };
1906
+ });
1907
+ };
1908
+ // 解析 WINDOW_UPDATE 帧
1909
+ HTTP2Parser.prototype.parseWindowUpdateFrame = function (frameBuffer, frameHeader) {
1910
+ // WINDOW_UPDATE帧的payload固定为4字节
1911
+ if (frameHeader.length !== 4) {
1912
+ throw new Error("WINDOW_UPDATE frame must have a length of 4 bytes");
1913
+ }
1914
+ // 确保frameBuffer是Uint8Array类型
1915
+ var buffer = new Uint8Array(frameBuffer);
1916
+ // 读取window size increment (4字节,大端序)
1917
+ // 手动计算32位无符号整数,确保最高位为0
1918
+ var windowSizeIncrement = ((buffer[0] & 0x7f) << 24) |
1919
+ (buffer[1] << 16) |
1920
+ (buffer[2] << 8) |
1921
+ buffer[3];
1922
+ // 验证window size increment
1923
+ if (windowSizeIncrement === 0) {
1924
+ throw new Error("WINDOW_UPDATE increment must not be zero");
1925
+ }
1926
+ return {
1927
+ windowSizeIncrement: windowSizeIncrement,
1928
+ };
1929
+ };
1930
+ // 处理 WINDOW_UPDATE 帧
1931
+ HTTP2Parser.prototype.handleWindowUpdateFrame = function (frameHeader, payload, streamId) {
1932
+ try {
1933
+ var windowUpdate = this.parseWindowUpdateFrame(payload, frameHeader);
1934
+ this.connectionWindowSize += windowUpdate.windowSizeIncrement;
1935
+ console.log("Connection window size increased by ".concat(windowUpdate.windowSizeIncrement));
1936
+ return windowUpdate;
1937
+ }
1938
+ catch (error) {
1939
+ // 处理错误情况
1940
+ console.error("Error handling WINDOW_UPDATE frame:", error);
1941
+ throw error;
1942
+ }
1943
+ };
1944
+ return HTTP2Parser;
1945
+ }());
1946
+
1947
+ function pDefer() {
1948
+ const deferred = {};
1949
+
1950
+ deferred.promise = new Promise((resolve, reject) => {
1951
+ deferred.resolve = resolve;
1952
+ deferred.reject = reject;
1953
+ });
1954
+
1955
+ return deferred;
1956
+ }
1957
+
1958
+ // ported from https://www.npmjs.com/package/fast-fifo
1959
+ class FixedFIFO {
1960
+ buffer;
1961
+ mask;
1962
+ top;
1963
+ btm;
1964
+ next;
1965
+ constructor(hwm) {
1966
+ if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {
1967
+ throw new Error('Max size for a FixedFIFO should be a power of two');
1968
+ }
1969
+ this.buffer = new Array(hwm);
1970
+ this.mask = hwm - 1;
1971
+ this.top = 0;
1972
+ this.btm = 0;
1973
+ this.next = null;
1974
+ }
1975
+ push(data) {
1976
+ if (this.buffer[this.top] !== undefined) {
1977
+ return false;
1978
+ }
1979
+ this.buffer[this.top] = data;
1980
+ this.top = (this.top + 1) & this.mask;
1981
+ return true;
1982
+ }
1983
+ shift() {
1984
+ const last = this.buffer[this.btm];
1985
+ if (last === undefined) {
1986
+ return undefined;
1987
+ }
1988
+ this.buffer[this.btm] = undefined;
1989
+ this.btm = (this.btm + 1) & this.mask;
1990
+ return last;
1991
+ }
1992
+ isEmpty() {
1993
+ return this.buffer[this.btm] === undefined;
1994
+ }
1995
+ }
1996
+ class FIFO {
1997
+ size;
1998
+ hwm;
1999
+ head;
2000
+ tail;
2001
+ constructor(options = {}) {
2002
+ this.hwm = options.splitLimit ?? 16;
2003
+ this.head = new FixedFIFO(this.hwm);
2004
+ this.tail = this.head;
2005
+ this.size = 0;
2006
+ }
2007
+ calculateSize(obj) {
2008
+ if (obj?.byteLength != null) {
2009
+ return obj.byteLength;
2010
+ }
2011
+ return 1;
2012
+ }
2013
+ push(val) {
2014
+ if (val?.value != null) {
2015
+ this.size += this.calculateSize(val.value);
2016
+ }
2017
+ if (!this.head.push(val)) {
2018
+ const prev = this.head;
2019
+ this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
2020
+ this.head.push(val);
2021
+ }
2022
+ }
2023
+ shift() {
2024
+ let val = this.tail.shift();
2025
+ if (val === undefined && (this.tail.next != null)) {
2026
+ const next = this.tail.next;
2027
+ this.tail.next = null;
2028
+ this.tail = next;
2029
+ val = this.tail.shift();
2030
+ }
2031
+ if (val?.value != null) {
2032
+ this.size -= this.calculateSize(val.value);
2033
+ }
2034
+ return val;
2035
+ }
2036
+ isEmpty() {
2037
+ return this.head.isEmpty();
2038
+ }
2039
+ }
2040
+
2041
+ /**
2042
+ * @packageDocumentation
2043
+ *
2044
+ * An iterable that you can push values into.
2045
+ *
2046
+ * @example
2047
+ *
2048
+ * ```js
2049
+ * import { pushable } from 'it-pushable'
2050
+ *
2051
+ * const source = pushable()
2052
+ *
2053
+ * setTimeout(() => source.push('hello'), 100)
2054
+ * setTimeout(() => source.push('world'), 200)
2055
+ * setTimeout(() => source.end(), 300)
2056
+ *
2057
+ * const start = Date.now()
2058
+ *
2059
+ * for await (const value of source) {
2060
+ * console.log(`got "${value}" after ${Date.now() - start}ms`)
2061
+ * }
2062
+ * console.log(`done after ${Date.now() - start}ms`)
2063
+ *
2064
+ * // Output:
2065
+ * // got "hello" after 105ms
2066
+ * // got "world" after 207ms
2067
+ * // done after 309ms
2068
+ * ```
2069
+ *
2070
+ * @example
2071
+ *
2072
+ * ```js
2073
+ * import { pushableV } from 'it-pushable'
2074
+ * import all from 'it-all'
2075
+ *
2076
+ * const source = pushableV()
2077
+ *
2078
+ * source.push(1)
2079
+ * source.push(2)
2080
+ * source.push(3)
2081
+ * source.end()
2082
+ *
2083
+ * console.info(await all(source))
2084
+ *
2085
+ * // Output:
2086
+ * // [ [1, 2, 3] ]
2087
+ * ```
2088
+ */
2089
+ let AbortError$1 = class AbortError extends Error {
2090
+ type;
2091
+ code;
2092
+ constructor(message, code) {
2093
+ super(message ?? 'The operation was aborted');
2094
+ this.type = 'aborted';
2095
+ this.code = code ?? 'ABORT_ERR';
2096
+ }
2097
+ };
2098
+ function pushable(options = {}) {
2099
+ const getNext = (buffer) => {
2100
+ const next = buffer.shift();
2101
+ if (next == null) {
2102
+ return { done: true };
2103
+ }
2104
+ if (next.error != null) {
2105
+ throw next.error;
2106
+ }
2107
+ return {
2108
+ done: next.done === true,
2109
+ // @ts-expect-error if done is false, value will be present
2110
+ value: next.value
2111
+ };
2112
+ };
2113
+ return _pushable(getNext, options);
2114
+ }
2115
+ function _pushable(getNext, options) {
2116
+ options = options ?? {};
2117
+ let onEnd = options.onEnd;
2118
+ let buffer = new FIFO();
2119
+ let pushable;
2120
+ let onNext;
2121
+ let ended;
2122
+ let drain = pDefer();
2123
+ const waitNext = async () => {
2124
+ try {
2125
+ if (!buffer.isEmpty()) {
2126
+ return getNext(buffer);
2127
+ }
2128
+ if (ended) {
2129
+ return { done: true };
2130
+ }
2131
+ return await new Promise((resolve, reject) => {
2132
+ onNext = (next) => {
2133
+ onNext = null;
2134
+ buffer.push(next);
2135
+ try {
2136
+ resolve(getNext(buffer));
2137
+ }
2138
+ catch (err) {
2139
+ reject(err);
2140
+ }
2141
+ return pushable;
2142
+ };
2143
+ });
2144
+ }
2145
+ finally {
2146
+ if (buffer.isEmpty()) {
2147
+ // settle promise in the microtask queue to give consumers a chance to
2148
+ // await after calling .push
2149
+ queueMicrotask(() => {
2150
+ drain.resolve();
2151
+ drain = pDefer();
2152
+ });
2153
+ }
2154
+ }
2155
+ };
2156
+ const bufferNext = (next) => {
2157
+ if (onNext != null) {
2158
+ return onNext(next);
2159
+ }
2160
+ buffer.push(next);
2161
+ return pushable;
2162
+ };
2163
+ const bufferError = (err) => {
2164
+ buffer = new FIFO();
2165
+ if (onNext != null) {
2166
+ return onNext({ error: err });
2167
+ }
2168
+ buffer.push({ error: err });
2169
+ return pushable;
2170
+ };
2171
+ const push = (value) => {
2172
+ if (ended) {
2173
+ return pushable;
2174
+ }
2175
+ // @ts-expect-error `byteLength` is not declared on PushType
2176
+ if (options?.objectMode !== true && value?.byteLength == null) {
2177
+ throw new Error('objectMode was not true but tried to push non-Uint8Array value');
2178
+ }
2179
+ return bufferNext({ done: false, value });
2180
+ };
2181
+ const end = (err) => {
2182
+ if (ended)
2183
+ return pushable;
2184
+ ended = true;
2185
+ return (err != null) ? bufferError(err) : bufferNext({ done: true });
2186
+ };
2187
+ const _return = () => {
2188
+ buffer = new FIFO();
2189
+ end();
2190
+ return { done: true };
2191
+ };
2192
+ const _throw = (err) => {
2193
+ end(err);
2194
+ return { done: true };
2195
+ };
2196
+ pushable = {
2197
+ [Symbol.asyncIterator]() { return this; },
2198
+ next: waitNext,
2199
+ return: _return,
2200
+ throw: _throw,
2201
+ push,
2202
+ end,
2203
+ get readableLength() {
2204
+ return buffer.size;
2205
+ },
2206
+ onEmpty: async (options) => {
2207
+ const signal = options?.signal;
2208
+ signal?.throwIfAborted();
2209
+ if (buffer.isEmpty()) {
2210
+ return;
2211
+ }
2212
+ let cancel;
2213
+ let listener;
2214
+ if (signal != null) {
2215
+ cancel = new Promise((resolve, reject) => {
2216
+ listener = () => {
2217
+ reject(new AbortError$1());
2218
+ };
2219
+ signal.addEventListener('abort', listener);
2220
+ });
2221
+ }
2222
+ try {
2223
+ await Promise.race([
2224
+ drain.promise,
2225
+ cancel
2226
+ ]);
2227
+ }
2228
+ finally {
2229
+ if (listener != null && signal != null) {
2230
+ signal?.removeEventListener('abort', listener);
2231
+ }
2232
+ }
2233
+ }
2234
+ };
2235
+ if (onEnd == null) {
2236
+ return pushable;
2237
+ }
2238
+ const _pushable = pushable;
2239
+ pushable = {
2240
+ [Symbol.asyncIterator]() { return this; },
2241
+ next() {
2242
+ return _pushable.next();
2243
+ },
2244
+ throw(err) {
2245
+ _pushable.throw(err);
2246
+ if (onEnd != null) {
2247
+ onEnd(err);
2248
+ onEnd = undefined;
2249
+ }
2250
+ return { done: true };
2251
+ },
2252
+ return() {
2253
+ _pushable.return();
2254
+ if (onEnd != null) {
2255
+ onEnd();
2256
+ onEnd = undefined;
2257
+ }
2258
+ return { done: true };
2259
+ },
2260
+ push,
2261
+ end(err) {
2262
+ _pushable.end(err);
2263
+ if (onEnd != null) {
2264
+ onEnd(err);
2265
+ onEnd = undefined;
2266
+ }
2267
+ return pushable;
2268
+ },
2269
+ get readableLength() {
2270
+ return _pushable.readableLength;
2271
+ },
2272
+ onEmpty: (opts) => {
2273
+ return _pushable.onEmpty(opts);
2274
+ }
2275
+ };
2276
+ return pushable;
2277
+ }
2278
+
2279
+ /**
2280
+ * An abort error class that extends error
2281
+ */
2282
+ class AbortError extends Error {
2283
+ type;
2284
+ code;
2285
+ constructor(message, code, name) {
2286
+ super(message ?? 'The operation was aborted');
2287
+ this.type = 'aborted';
2288
+ this.name = name ?? 'AbortError';
2289
+ this.code = code ?? 'ABORT_ERR';
2290
+ }
2291
+ }
2292
+ /**
2293
+ * Race a promise against an abort signal
2294
+ */
2295
+ async function raceSignal(promise, signal, opts) {
2296
+ if (signal == null) {
2297
+ return promise;
2298
+ }
2299
+ if (signal.aborted) {
2300
+ // the passed promise may yet resolve or reject but the use has signalled
2301
+ // they are no longer interested so smother the error
2302
+ promise.catch(() => { });
2303
+ return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName));
2304
+ }
2305
+ let listener;
2306
+ // create the error here so we have more context in the stack trace
2307
+ const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName);
2308
+ try {
2309
+ return await Promise.race([
2310
+ promise,
2311
+ new Promise((resolve, reject) => {
2312
+ listener = () => {
2313
+ reject(error);
2314
+ };
2315
+ signal.addEventListener('abort', listener);
2316
+ })
2317
+ ]);
2318
+ }
2319
+ finally {
2320
+ if (listener != null) {
2321
+ signal.removeEventListener('abort', listener);
2322
+ }
2323
+ }
2324
+ }
2325
+
2326
+ /**
2327
+ * @packageDocumentation
2328
+ *
2329
+ * A pushable async generator that waits until the current value is consumed
2330
+ * before allowing a new value to be pushed.
2331
+ *
2332
+ * Useful for when you don't want to keep memory usage under control and/or
2333
+ * allow a downstream consumer to dictate how fast data flows through a pipe,
2334
+ * but you want to be able to apply a transform to that data.
2335
+ *
2336
+ * @example
2337
+ *
2338
+ * ```typescript
2339
+ * import { queuelessPushable } from 'it-queueless-pushable'
2340
+ *
2341
+ * const pushable = queuelessPushable<string>()
2342
+ *
2343
+ * // run asynchronously
2344
+ * Promise.resolve().then(async () => {
2345
+ * // push a value - the returned promise will not resolve until the value is
2346
+ * // read from the pushable
2347
+ * await pushable.push('hello')
2348
+ * })
2349
+ *
2350
+ * // read a value
2351
+ * const result = await pushable.next()
2352
+ * console.info(result) // { done: false, value: 'hello' }
2353
+ * ```
2354
+ */
2355
+ class QueuelessPushable {
2356
+ readNext;
2357
+ haveNext;
2358
+ ended;
2359
+ nextResult;
2360
+ error;
2361
+ constructor() {
2362
+ this.ended = false;
2363
+ this.readNext = pDefer();
2364
+ this.haveNext = pDefer();
2365
+ }
2366
+ [Symbol.asyncIterator]() {
2367
+ return this;
2368
+ }
2369
+ async next() {
2370
+ if (this.nextResult == null) {
2371
+ // wait for the supplier to push a value
2372
+ await this.haveNext.promise;
2373
+ }
2374
+ if (this.nextResult == null) {
2375
+ throw new Error('HaveNext promise resolved but nextResult was undefined');
2376
+ }
2377
+ const nextResult = this.nextResult;
2378
+ this.nextResult = undefined;
2379
+ // signal to the supplier that we read the value
2380
+ this.readNext.resolve();
2381
+ this.readNext = pDefer();
2382
+ return nextResult;
2383
+ }
2384
+ async throw(err) {
2385
+ this.ended = true;
2386
+ this.error = err;
2387
+ if (err != null) {
2388
+ // this can cause unhandled promise rejections if nothing is awaiting the
2389
+ // next value so attach a dummy catch listener to the promise
2390
+ this.haveNext.promise.catch(() => { });
2391
+ this.haveNext.reject(err);
2392
+ }
2393
+ const result = {
2394
+ done: true,
2395
+ value: undefined
2396
+ };
2397
+ return result;
2398
+ }
2399
+ async return() {
2400
+ const result = {
2401
+ done: true,
2402
+ value: undefined
2403
+ };
2404
+ this.ended = true;
2405
+ this.nextResult = result;
2406
+ // let the consumer know we have a new value
2407
+ this.haveNext.resolve();
2408
+ return result;
2409
+ }
2410
+ async push(value, options) {
2411
+ await this._push(value, options);
2412
+ }
2413
+ async end(err, options) {
2414
+ if (err != null) {
2415
+ await this.throw(err);
2416
+ }
2417
+ else {
2418
+ // abortable return
2419
+ await this._push(undefined, options);
2420
+ }
2421
+ }
2422
+ async _push(value, options) {
2423
+ if (value != null && this.ended) {
2424
+ throw this.error ?? new Error('Cannot push value onto an ended pushable');
2425
+ }
2426
+ // wait for all values to be read
2427
+ while (this.nextResult != null) {
2428
+ await this.readNext.promise;
2429
+ }
2430
+ if (value != null) {
2431
+ this.nextResult = { done: false, value };
2432
+ }
2433
+ else {
2434
+ this.ended = true;
2435
+ this.nextResult = { done: true, value: undefined };
2436
+ }
2437
+ // let the consumer know we have a new value
2438
+ this.haveNext.resolve();
2439
+ this.haveNext = pDefer();
2440
+ // wait for the consumer to have finished processing the value and requested
2441
+ // the next one or for the passed signal to abort the waiting
2442
+ await raceSignal(this.readNext.promise, options?.signal, options);
2443
+ }
2444
+ }
2445
+ function queuelessPushable() {
2446
+ return new QueuelessPushable();
2447
+ }
2448
+
2449
+ /**
2450
+ * @packageDocumentation
2451
+ *
2452
+ * Merge several (async)iterables into one, yield values as they arrive.
2453
+ *
2454
+ * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.
2455
+ *
2456
+ * @example
2457
+ *
2458
+ * ```javascript
2459
+ * import merge from 'it-merge'
2460
+ * import all from 'it-all'
2461
+ *
2462
+ * // This can also be an iterator, generator, etc
2463
+ * const values1 = [0, 1, 2, 3, 4]
2464
+ * const values2 = [5, 6, 7, 8, 9]
2465
+ *
2466
+ * const arr = all(merge(values1, values2))
2467
+ *
2468
+ * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2469
+ * ```
2470
+ *
2471
+ * Async sources must be awaited:
2472
+ *
2473
+ * ```javascript
2474
+ * import merge from 'it-merge'
2475
+ * import all from 'it-all'
2476
+ *
2477
+ * // This can also be an iterator, async iterator, generator, etc
2478
+ * const values1 = async function * () {
2479
+ * yield * [0, 1, 2, 3, 4]
2480
+ * }
2481
+ * const values2 = async function * () {
2482
+ * yield * [5, 6, 7, 8, 9]
2483
+ * }
2484
+ *
2485
+ * const arr = await all(merge(values1(), values2()))
2486
+ *
2487
+ * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed
2488
+ * ```
2489
+ */
2490
+ function isAsyncIterable$1(thing) {
2491
+ return thing[Symbol.asyncIterator] != null;
2492
+ }
2493
+ async function addAllToPushable(sources, output) {
2494
+ try {
2495
+ await Promise.all(sources.map(async (source) => {
2496
+ for await (const item of source) {
2497
+ await output.push(item);
2498
+ }
2499
+ }));
2500
+ await output.end();
2501
+ }
2502
+ catch (err) {
2503
+ await output.end(err)
2504
+ .catch(() => { });
2505
+ }
2506
+ }
2507
+ async function* mergeSources(sources) {
2508
+ const output = queuelessPushable();
2509
+ addAllToPushable(sources, output)
2510
+ .catch(() => { });
2511
+ yield* output;
2512
+ }
2513
+ function* mergeSyncSources(syncSources) {
2514
+ for (const source of syncSources) {
2515
+ yield* source;
2516
+ }
2517
+ }
2518
+ function merge(...sources) {
2519
+ const syncSources = [];
2520
+ for (const source of sources) {
2521
+ if (!isAsyncIterable$1(source)) {
2522
+ syncSources.push(source);
2523
+ }
2524
+ }
2525
+ if (syncSources.length === sources.length) {
2526
+ // all sources are synchronous
2527
+ return mergeSyncSources(syncSources);
2528
+ }
2529
+ return mergeSources(sources);
2530
+ }
2531
+
2532
+ function pipe(first, ...rest) {
2533
+ if (first == null) {
2534
+ throw new Error('Empty pipeline');
2535
+ }
2536
+ // Duplex at start: wrap in function and return duplex source
2537
+ if (isDuplex(first)) {
2538
+ const duplex = first;
2539
+ first = () => duplex.source;
2540
+ // Iterable at start: wrap in function
2541
+ }
2542
+ else if (isIterable(first) || isAsyncIterable(first)) {
2543
+ const source = first;
2544
+ first = () => source;
2545
+ }
2546
+ const fns = [first, ...rest];
2547
+ if (fns.length > 1) {
2548
+ // Duplex at end: use duplex sink
2549
+ if (isDuplex(fns[fns.length - 1])) {
2550
+ fns[fns.length - 1] = fns[fns.length - 1].sink;
2551
+ }
2552
+ }
2553
+ if (fns.length > 2) {
2554
+ // Duplex in the middle, consume source with duplex sink and return duplex source
2555
+ for (let i = 1; i < fns.length - 1; i++) {
2556
+ if (isDuplex(fns[i])) {
2557
+ fns[i] = duplexPipelineFn(fns[i]);
2558
+ }
2559
+ }
2560
+ }
2561
+ return rawPipe(...fns);
2562
+ }
2563
+ const rawPipe = (...fns) => {
2564
+ let res;
2565
+ while (fns.length > 0) {
2566
+ res = fns.shift()(res);
2567
+ }
2568
+ return res;
2569
+ };
2570
+ const isAsyncIterable = (obj) => {
2571
+ return obj?.[Symbol.asyncIterator] != null;
2572
+ };
2573
+ const isIterable = (obj) => {
2574
+ return obj?.[Symbol.iterator] != null;
2575
+ };
2576
+ const isDuplex = (obj) => {
2577
+ if (obj == null) {
2578
+ return false;
2579
+ }
2580
+ return obj.sink != null && obj.source != null;
2581
+ };
2582
+ const duplexPipelineFn = (duplex) => {
2583
+ return (source) => {
2584
+ const p = duplex.sink(source);
2585
+ if (p?.then != null) {
2586
+ const stream = pushable({
2587
+ objectMode: true
2588
+ });
2589
+ p.then(() => {
2590
+ stream.end();
2591
+ }, (err) => {
2592
+ stream.end(err);
2593
+ });
2594
+ let sourceWrap;
2595
+ const source = duplex.source;
2596
+ if (isAsyncIterable(source)) {
2597
+ sourceWrap = async function* () {
2598
+ yield* source;
2599
+ stream.end();
2600
+ };
2601
+ }
2602
+ else if (isIterable(source)) {
2603
+ sourceWrap = function* () {
2604
+ yield* source;
2605
+ stream.end();
2606
+ };
2607
+ }
2608
+ else {
2609
+ throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable');
2610
+ }
2611
+ return merge(stream, sourceWrap());
2612
+ }
2613
+ return duplex.source;
2614
+ };
2615
+ };
2616
+
2617
+ var MaxChunkSize = 4 * 1024 - 5;
2618
+ var StreamWriter = /** @class */ (function () {
2619
+ function StreamWriter(sink, options) {
2620
+ if (options === void 0) { options = {}; }
2621
+ var _this = this;
2622
+ var _a, _b, _c;
2623
+ this.sink = sink;
2624
+ this.options = options;
2625
+ //private p = pushable({ objectMode: false })
2626
+ this.bytesWritten = 0;
2627
+ this.abortController = new AbortController();
2628
+ // 背压控制相关属性
2629
+ this.backpressureHistory = [];
2630
+ this.isBackpressure = false;
2631
+ this.writeQueue = [];
2632
+ this.isProcessingQueue = false;
2633
+ // 事件系统
2634
+ this.listeners = new Map();
2635
+ if (options) {
2636
+ this.options = {
2637
+ chunkSize: (_a = options.chunkSize) !== null && _a !== void 0 ? _a : MaxChunkSize,
2638
+ bufferSize: (_b = options.bufferSize) !== null && _b !== void 0 ? _b : 5 * 1024 * 1024,
2639
+ retries: (_c = options.retries) !== null && _c !== void 0 ? _c : 3
2640
+ };
2641
+ }
2642
+ else {
2643
+ this.options = {
2644
+ chunkSize: MaxChunkSize,
2645
+ bufferSize: 5 * 1024 * 1024,
2646
+ retries: 3
2647
+ };
2648
+ }
2649
+ if (this.options.chunkSize && this.options.chunkSize > MaxChunkSize) {
2650
+ this.options.chunkSize = MaxChunkSize;
2651
+ }
2652
+ var basePushable = pushable({ objectMode: false });
2653
+ // 保留原始方法引用
2654
+ basePushable._originalPush = basePushable.push.bind(basePushable);
2655
+ basePushable._originalNext = basePushable.next.bind(basePushable);
2656
+ basePushable._queueSize = 0;
2657
+ // 重写 next 方法
2658
+ Object.defineProperty(basePushable, 'next', {
2659
+ value: function () { return __awaiter(_this, void 0, void 0, function () {
2660
+ var result;
2661
+ return __generator(this, function (_a) {
2662
+ switch (_a.label) {
2663
+ case 0: return [4 /*yield*/, basePushable._originalNext()];
2664
+ case 1:
2665
+ result = _a.sent();
2666
+ if (!result.done && result.value) {
2667
+ basePushable._queueSize -= result.value.byteLength;
2668
+ }
2669
+ return [2 /*return*/, result];
2670
+ }
2671
+ });
2672
+ }); },
2673
+ writable: false,
2674
+ configurable: false
2675
+ });
2676
+ // 安全重写 push 方法
2677
+ Object.defineProperty(basePushable, 'push', {
2678
+ value: function (chunk) {
2679
+ basePushable._queueSize += chunk.byteLength;
2680
+ return basePushable._originalPush(chunk);
2681
+ },
2682
+ writable: false,
2683
+ configurable: false
2684
+ });
2685
+ this.p = basePushable;
2686
+ this.startPipeline();
2687
+ }
2688
+ Object.defineProperty(StreamWriter.prototype, "queueSize", {
2689
+ get: function () {
2690
+ return this.p._queueSize;
2691
+ },
2692
+ enumerable: false,
2693
+ configurable: true
2694
+ });
2695
+ // 在 next() 操作时更新队列大小
2696
+ StreamWriter.prototype.safeNext = function () {
2697
+ return __awaiter(this, void 0, void 0, function () {
2698
+ var result;
2699
+ return __generator(this, function (_a) {
2700
+ switch (_a.label) {
2701
+ case 0: return [4 /*yield*/, this.p.next()];
2702
+ case 1:
2703
+ result = _a.sent();
2704
+ if (!result.done) {
2705
+ this.p._queueSize -= result.value.byteLength;
2706
+ }
2707
+ return [2 /*return*/, result];
2708
+ }
2709
+ });
2710
+ });
2711
+ };
2712
+ StreamWriter.prototype.handleError = function (err) {
2713
+ this.dispatchEvent(new CustomEvent('error', { detail: err }));
2714
+ this.abort(err.message);
2715
+ };
2716
+ StreamWriter.prototype.startPipeline = function () {
2717
+ var _this = this;
2718
+ pipe(this.p, this.createTransform(), this.sink).catch(function (err) { return _this.handleError(err); }); // 正确绑定this
2719
+ };
2720
+ StreamWriter.prototype.createTransform = function () {
2721
+ return function (source) {
2722
+ return __asyncGenerator(this, arguments, function () {
2723
+ var _a, source_1, source_1_1, chunk, e_1_1;
2724
+ var _b, e_1, _c, _d;
2725
+ return __generator(this, function (_e) {
2726
+ switch (_e.label) {
2727
+ case 0:
2728
+ _e.trys.push([0, 7, 8, 13]);
2729
+ _a = true, source_1 = __asyncValues(source);
2730
+ _e.label = 1;
2731
+ case 1: return [4 /*yield*/, __await(source_1.next())];
2732
+ case 2:
2733
+ if (!(source_1_1 = _e.sent(), _b = source_1_1.done, !_b)) return [3 /*break*/, 6];
2734
+ _d = source_1_1.value;
2735
+ _a = false;
2736
+ chunk = _d;
2737
+ return [4 /*yield*/, __await(chunk)];
2738
+ case 3: return [4 /*yield*/, _e.sent()];
2739
+ case 4:
2740
+ _e.sent();
2741
+ _e.label = 5;
2742
+ case 5:
2743
+ _a = true;
2744
+ return [3 /*break*/, 1];
2745
+ case 6: return [3 /*break*/, 13];
2746
+ case 7:
2747
+ e_1_1 = _e.sent();
2748
+ e_1 = { error: e_1_1 };
2749
+ return [3 /*break*/, 13];
2750
+ case 8:
2751
+ _e.trys.push([8, , 11, 12]);
2752
+ if (!(!_a && !_b && (_c = source_1.return))) return [3 /*break*/, 10];
2753
+ return [4 /*yield*/, __await(_c.call(source_1))];
2754
+ case 9:
2755
+ _e.sent();
2756
+ _e.label = 10;
2757
+ case 10: return [3 /*break*/, 12];
2758
+ case 11:
2759
+ if (e_1) throw e_1.error;
2760
+ return [7 /*endfinally*/];
2761
+ case 12: return [7 /*endfinally*/];
2762
+ case 13: return [2 /*return*/];
2763
+ }
2764
+ });
2765
+ });
2766
+ };
2767
+ };
2768
+ StreamWriter.prototype.write = function (data) {
2769
+ return __awaiter(this, void 0, void 0, function () {
2770
+ var _this = this;
2771
+ return __generator(this, function (_a) {
2772
+ if (this.abortController.signal.aborted)
2773
+ return [2 /*return*/];
2774
+ return [2 /*return*/, new Promise(function (resolve, reject) {
2775
+ var task = function () { return __awaiter(_this, void 0, void 0, function () {
2776
+ var buffer, err_1;
2777
+ return __generator(this, function (_a) {
2778
+ switch (_a.label) {
2779
+ case 0:
2780
+ _a.trys.push([0, 3, , 4]);
2781
+ return [4 /*yield*/, this.convertToBuffer(data)];
2782
+ case 1:
2783
+ buffer = _a.sent();
2784
+ return [4 /*yield*/, this.writeChunks(buffer)];
2785
+ case 2:
2786
+ _a.sent();
2787
+ resolve();
2788
+ return [3 /*break*/, 4];
2789
+ case 3:
2790
+ err_1 = _a.sent();
2791
+ reject(err_1);
2792
+ return [3 /*break*/, 4];
2793
+ case 4: return [2 /*return*/];
2794
+ }
2795
+ });
2796
+ }); };
2797
+ _this.writeQueue.push(task);
2798
+ _this.processQueue();
2799
+ })];
2800
+ });
2801
+ });
2802
+ };
2803
+ StreamWriter.prototype.convertToBuffer = function (data) {
2804
+ return __awaiter(this, void 0, void 0, function () {
2805
+ return __generator(this, function (_a) {
2806
+ if (data instanceof Blob)
2807
+ return [2 /*return*/, data.arrayBuffer()];
2808
+ if (typeof data === 'string')
2809
+ return [2 /*return*/, new TextEncoder().encode(data).buffer];
2810
+ return [2 /*return*/, data];
2811
+ });
2812
+ });
2813
+ };
2814
+ StreamWriter.prototype.writeChunks = function (buffer) {
2815
+ return __awaiter(this, void 0, void 0, function () {
2816
+ var offset, end, chunk;
2817
+ return __generator(this, function (_a) {
2818
+ switch (_a.label) {
2819
+ case 0:
2820
+ offset = 0;
2821
+ _a.label = 1;
2822
+ case 1:
2823
+ if (!(offset < buffer.byteLength)) return [3 /*break*/, 4];
2824
+ end = Math.min(offset + this.options.chunkSize, buffer.byteLength);
2825
+ chunk = new Uint8Array(end - offset);
2826
+ chunk.set(new Uint8Array(buffer.slice(offset, end)));
2827
+ return [4 /*yield*/, this.retryableWrite(chunk)];
2828
+ case 2:
2829
+ _a.sent();
2830
+ this.updateProgress(chunk.byteLength);
2831
+ _a.label = 3;
2832
+ case 3:
2833
+ offset += this.options.chunkSize;
2834
+ return [3 /*break*/, 1];
2835
+ case 4: return [2 /*return*/];
2836
+ }
2837
+ });
2838
+ });
2839
+ };
2840
+ StreamWriter.prototype.retryableWrite = function (chunk_1) {
2841
+ return __awaiter(this, arguments, void 0, function (chunk, attempt) {
2842
+ var err_2, delay_1;
2843
+ var _this = this;
2844
+ if (attempt === void 0) { attempt = 0; }
2845
+ return __generator(this, function (_a) {
2846
+ switch (_a.label) {
2847
+ case 0:
2848
+ _a.trys.push([0, 3, , 6]);
2849
+ return [4 /*yield*/, this.monitorBackpressure()];
2850
+ case 1:
2851
+ _a.sent();
2852
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
2853
+ try {
2854
+ _this.p.push(chunk);
2855
+ }
2856
+ catch (err) {
2857
+ reject(err);
2858
+ }
2859
+ resolve();
2860
+ })];
2861
+ case 2:
2862
+ _a.sent();
2863
+ return [3 /*break*/, 6];
2864
+ case 3:
2865
+ err_2 = _a.sent();
2866
+ if (!(attempt < this.options.retries)) return [3 /*break*/, 5];
2867
+ delay_1 = this.calculateRetryDelay(attempt);
2868
+ return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, delay_1); })];
2869
+ case 4:
2870
+ _a.sent();
2871
+ return [2 /*return*/, this.retryableWrite(chunk, attempt + 1)];
2872
+ case 5: throw err_2;
2873
+ case 6: return [2 /*return*/];
2874
+ }
2875
+ });
2876
+ });
2877
+ };
2878
+ StreamWriter.prototype.monitorBackpressure = function () {
2879
+ return __awaiter(this, void 0, void 0, function () {
2880
+ var checkInterval, historySize, _loop_1, this_1, state_1;
2881
+ return __generator(this, function (_a) {
2882
+ switch (_a.label) {
2883
+ case 0:
2884
+ checkInterval = 50;
2885
+ historySize = 10;
2886
+ _loop_1 = function () {
2887
+ var currentSize, avg, dynamicThreshold, waitTime;
2888
+ return __generator(this, function (_b) {
2889
+ switch (_b.label) {
2890
+ case 0:
2891
+ currentSize = this_1.queueSize // 空值合并运算符
2892
+ ;
2893
+ if (currentSize > 0) {
2894
+ this_1.backpressureHistory.push(currentSize);
2895
+ }
2896
+ if (this_1.backpressureHistory.length > historySize) {
2897
+ this_1.backpressureHistory.shift();
2898
+ }
2899
+ avg = this_1.backpressureHistory.reduce(function (a, b) { return a + b; }, 0) / historySize;
2900
+ dynamicThreshold = Math.min(this_1.options.bufferSize * 0.8, avg * 1.5);
2901
+ if (currentSize < dynamicThreshold || currentSize === 0) {
2902
+ if (this_1.isBackpressure) {
2903
+ this_1.isBackpressure = false;
2904
+ this_1.dispatchEvent(new CustomEvent('backpressure', {
2905
+ detail: {
2906
+ currentSize: currentSize,
2907
+ averageSize: avg,
2908
+ threshold: dynamicThreshold,
2909
+ waitingTime: 0
2910
+ }
2911
+ }));
2912
+ }
2913
+ return [2 /*return*/, { value: void 0 }];
2914
+ }
2915
+ if (!this_1.isBackpressure) {
2916
+ this_1.isBackpressure = true;
2917
+ this_1.dispatchEvent(new CustomEvent('backpressure', {
2918
+ detail: {
2919
+ currentSize: currentSize,
2920
+ averageSize: avg,
2921
+ threshold: dynamicThreshold,
2922
+ waitingTime: 0
2923
+ }
2924
+ }));
2925
+ }
2926
+ waitTime = Math.min(10, checkInterval * Math.pow(2, currentSize / dynamicThreshold));
2927
+ return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, waitTime); })];
2928
+ case 1:
2929
+ _b.sent();
2930
+ if (this_1.abortController.signal.aborted)
2931
+ return [2 /*return*/, "break"];
2932
+ return [2 /*return*/];
2933
+ }
2934
+ });
2935
+ };
2936
+ this_1 = this;
2937
+ _a.label = 1;
2938
+ case 1:
2939
+ return [5 /*yield**/, _loop_1()];
2940
+ case 2:
2941
+ state_1 = _a.sent();
2942
+ if (typeof state_1 === "object")
2943
+ return [2 /*return*/, state_1.value];
2944
+ if (state_1 === "break")
2945
+ return [3 /*break*/, 3];
2946
+ return [3 /*break*/, 1];
2947
+ case 3: return [2 /*return*/];
2948
+ }
2949
+ });
2950
+ });
2951
+ };
2952
+ StreamWriter.prototype.calculateRetryDelay = function (attempt) {
2953
+ var baseDelay = 10;
2954
+ var maxDelay = 100;
2955
+ return Math.min(baseDelay * Math.pow(2, attempt) + Math.random() * 100, maxDelay);
2956
+ };
2957
+ StreamWriter.prototype.processQueue = function () {
2958
+ return __awaiter(this, void 0, void 0, function () {
2959
+ var task;
2960
+ return __generator(this, function (_a) {
2961
+ switch (_a.label) {
2962
+ case 0:
2963
+ if (this.isProcessingQueue || this.abortController.signal.aborted)
2964
+ return [2 /*return*/];
2965
+ this.isProcessingQueue = true;
2966
+ _a.label = 1;
2967
+ case 1:
2968
+ if (!(this.writeQueue.length > 0)) return [3 /*break*/, 4];
2969
+ if (this.abortController.signal.aborted)
2970
+ return [3 /*break*/, 4];
2971
+ return [4 /*yield*/, this.monitorBackpressure()];
2972
+ case 2:
2973
+ _a.sent();
2974
+ task = this.writeQueue.shift();
2975
+ return [4 /*yield*/, task()];
2976
+ case 3:
2977
+ _a.sent();
2978
+ return [3 /*break*/, 1];
2979
+ case 4:
2980
+ this.isProcessingQueue = false;
2981
+ return [2 /*return*/];
2982
+ }
2983
+ });
2984
+ });
2985
+ };
2986
+ StreamWriter.prototype.updateProgress = function (bytes) {
2987
+ this.bytesWritten += bytes;
2988
+ this.dispatchEvent(new CustomEvent('progress', {
2989
+ detail: { loaded: this.bytesWritten }
2990
+ }));
2991
+ };
2992
+ StreamWriter.prototype.end = function () {
2993
+ return __awaiter(this, void 0, void 0, function () {
2994
+ var _a, _b;
2995
+ return __generator(this, function (_c) {
2996
+ switch (_c.label) {
2997
+ case 0:
2998
+ this.p.end();
2999
+ return [4 /*yield*/, ((_b = (_a = this.sink).return) === null || _b === void 0 ? void 0 : _b.call(_a))];
3000
+ case 1:
3001
+ _c.sent();
3002
+ this.cleanup();
3003
+ return [2 /*return*/];
3004
+ }
3005
+ });
3006
+ });
3007
+ };
3008
+ StreamWriter.prototype.abort = function (reason) {
3009
+ if (reason === void 0) { reason = 'User aborted'; }
3010
+ this.abortController.abort(reason);
3011
+ this.cleanup();
3012
+ this.dispatchEvent(new CustomEvent('abort', { detail: reason }));
3013
+ };
3014
+ StreamWriter.prototype.cleanup = function () {
3015
+ this.p.end();
3016
+ this.abortController.abort();
3017
+ this.writeQueue = [];
3018
+ };
3019
+ StreamWriter.prototype.addEventListener = function (type, callback) {
3020
+ var handlers = this.listeners.get(type) || [];
3021
+ handlers.push(callback);
3022
+ this.listeners.set(type, handlers);
3023
+ };
3024
+ // 修复后的代码片段
3025
+ StreamWriter.prototype.dispatchEvent = function (event) {
3026
+ var handlers = this.listeners.get(event.type) || [];
3027
+ handlers.forEach(function (handler) { return handler(event); });
3028
+ };
3029
+ // 明确指定事件类型
3030
+ StreamWriter.prototype.dispatchBackpressureEvent = function (detail) {
3031
+ this.dispatchEvent(new CustomEvent('backpressure', {
3032
+ detail: detail
3033
+ }));
3034
+ };
3035
+ return StreamWriter;
3036
+ }());
3037
+
3038
+ console.log("ASDDSDS");
3039
+ var StreamManager = /** @class */ (function () {
3040
+ function StreamManager() {
3041
+ this.currentStreamId = 1; // 从 1 开始,以模拟奇数 ID
3042
+ }
3043
+ StreamManager.prototype.getNextAppLevelStreamId = function () {
3044
+ var id = this.currentStreamId;
3045
+ this.currentStreamId += 2; // 确保奇数步进
3046
+ return id;
3047
+ };
3048
+ return StreamManager;
3049
+ }());
3050
+ var Libp2pGrpcClient = /** @class */ (function () {
3051
+ function Libp2pGrpcClient(node, peerAddr, token, protocol) {
3052
+ this.node = node;
3053
+ this.peerAddr = peerAddr;
3054
+ if (protocol) {
3055
+ this.protocol = protocol;
3056
+ }
3057
+ else {
3058
+ this.protocol = '/dc/thread/0.0.1';
3059
+ }
3060
+ this.steamManager = new StreamManager();
3061
+ this.token = token;
3062
+ }
3063
+ Libp2pGrpcClient.prototype.setToken = function (token) {
3064
+ this.token = token;
3065
+ };
3066
+ Libp2pGrpcClient.prototype.unaryCall = function (method, requestData, timeout) {
3067
+ return __awaiter(this, void 0, void 0, function () {
3068
+ var stream, responseData, hpack, exitFlag, errMsg, connection, streamId, writer_1, parser, preface, settingFrme, headerFrame, dataFrame, err_1;
3069
+ return __generator(this, function (_a) {
3070
+ switch (_a.label) {
3071
+ case 0:
3072
+ stream = null;
3073
+ responseData = null;
3074
+ hpack = new HPACK();
3075
+ exitFlag = false;
3076
+ errMsg = '';
3077
+ _a.label = 1;
3078
+ case 1:
3079
+ _a.trys.push([1, 11, 12, 15]);
3080
+ return [4 /*yield*/, this.node.dial(this.peerAddr)];
3081
+ case 2:
3082
+ connection = _a.sent();
3083
+ return [4 /*yield*/, connection.newStream(this.protocol, {
3084
+ maxOutboundStreams: 5
3085
+ })];
3086
+ case 3:
3087
+ stream = _a.sent();
3088
+ streamId = this.steamManager.getNextAppLevelStreamId();
3089
+ writer_1 = new StreamWriter(stream.sink);
3090
+ parser = new HTTP2Parser(writer_1);
3091
+ parser.onData = function (payload, frameHeader) {
3092
+ responseData = payload.subarray(5);
3093
+ };
3094
+ parser.onSettings = function () {
3095
+ console.log('Settings received');
3096
+ var ackSettingFrame = Http2Frame.createSettingsAckFrame();
3097
+ writer_1.write(ackSettingFrame);
3098
+ };
3099
+ parser.onHeaders = function (headers, header) {
3100
+ var plainHeaders = hpack.decodeHeaderFields(headers);
3101
+ console.log('Received headers:', plainHeaders);
3102
+ if (plainHeaders.get('grpc-status') === '0') {
3103
+ console.log('gRPC call success');
3104
+ }
3105
+ else if (plainHeaders.get('grpc-status') !== undefined) {
3106
+ exitFlag = true;
3107
+ errMsg = plainHeaders.get('grpc-message') || 'gRPC call failed';
3108
+ }
3109
+ };
3110
+ parser.processStream(stream);
3111
+ preface = Http2Frame.createPreface();
3112
+ return [4 /*yield*/, writer_1.write(preface)
3113
+ // 发送Settings请求
3114
+ ];
3115
+ case 4:
3116
+ _a.sent();
3117
+ settingFrme = Http2Frame.createSettingsFrame();
3118
+ return [4 /*yield*/, writer_1.write(settingFrme)];
3119
+ case 5:
3120
+ _a.sent();
3121
+ return [4 /*yield*/, parser.waitForSettingsAck()
3122
+ // 创建头部帧
3123
+ ];
3124
+ case 6:
3125
+ _a.sent();
3126
+ headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token);
3127
+ return [4 /*yield*/, writer_1.write(headerFrame)
3128
+ // 创建数据帧
3129
+ ];
3130
+ case 7:
3131
+ _a.sent();
3132
+ dataFrame = Http2Frame.createDataFrame(streamId, requestData, true);
3133
+ // 发送请求
3134
+ return [4 /*yield*/, writer_1.write(dataFrame)
3135
+ // 等待responseData 不为空,或超时
3136
+ ];
3137
+ case 8:
3138
+ // 发送请求
3139
+ _a.sent();
3140
+ // 等待responseData 不为空,或超时
3141
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
3142
+ var t = setTimeout(function () {
3143
+ reject(new Error('gRPC response timeout'));
3144
+ }, timeout);
3145
+ var checkResponse = function () {
3146
+ if (responseData || exitFlag) {
3147
+ clearTimeout(t);
3148
+ resolve(responseData);
3149
+ }
3150
+ else {
3151
+ setTimeout(checkResponse, 50);
3152
+ }
3153
+ };
3154
+ checkResponse();
3155
+ })];
3156
+ case 9:
3157
+ // 等待responseData 不为空,或超时
3158
+ _a.sent();
3159
+ return [4 /*yield*/, writer_1.end()];
3160
+ case 10:
3161
+ _a.sent();
3162
+ return [3 /*break*/, 15];
3163
+ case 11:
3164
+ err_1 = _a.sent();
3165
+ console.error('unaryCall error:', err_1);
3166
+ throw err_1;
3167
+ case 12:
3168
+ if (!stream) return [3 /*break*/, 14];
3169
+ return [4 /*yield*/, stream.close()];
3170
+ case 13:
3171
+ _a.sent();
3172
+ _a.label = 14;
3173
+ case 14: return [7 /*endfinally*/];
3174
+ case 15:
3175
+ if (exitFlag) {
3176
+ throw new Error(errMsg);
3177
+ }
3178
+ if (!responseData) {
3179
+ responseData = new Uint8Array();
3180
+ }
3181
+ return [2 /*return*/, responseData];
3182
+ }
3183
+ });
3184
+ });
3185
+ };
3186
+ Libp2pGrpcClient.prototype.Call = function (method, requestData, timeout, mode, onDataCallback, dataSourceCallback, onEndCallback, onErrorCallback) {
3187
+ return __awaiter(this, void 0, void 0, function () {
3188
+ var timeoutHandle, timeoutPromise, hpack, operationPromise;
3189
+ var _this = this;
3190
+ return __generator(this, function (_a) {
3191
+ timeoutPromise = new Promise(function (_, reject) {
3192
+ return timeoutHandle = setTimeout(function () { return reject(new Error('Operation timed out')); }, timeout);
3193
+ });
3194
+ hpack = new HPACK();
3195
+ operationPromise = (function () { return __awaiter(_this, void 0, void 0, function () {
3196
+ var stream, connection, streamId, writer_2, parser, preface, settingFrame, ackSettingFrame, headerFrame, dataFrame, dataFrame, _a, _b, _c, chunk, dataFrame, e_1_1, finalFrame, err_2;
3197
+ var _this = this;
3198
+ var _d, e_1, _e, _f;
3199
+ return __generator(this, function (_g) {
3200
+ switch (_g.label) {
3201
+ case 0:
3202
+ stream = null;
3203
+ _g.label = 1;
3204
+ case 1:
3205
+ _g.trys.push([1, 29, 30, 33]);
3206
+ return [4 /*yield*/, this.node.dial(this.peerAddr)];
3207
+ case 2:
3208
+ connection = _g.sent();
3209
+ return [4 /*yield*/, connection.newStream(this.protocol)];
3210
+ case 3:
3211
+ stream = _g.sent();
3212
+ streamId = this.steamManager.getNextAppLevelStreamId();
3213
+ writer_2 = new StreamWriter(stream.sink);
3214
+ parser = new HTTP2Parser(writer_2);
3215
+ clearTimeout(timeoutHandle);
3216
+ // Define the onData method to utilize the provided callback
3217
+ parser.onData = function (payload, frameHeader) { return __awaiter(_this, void 0, void 0, function () {
3218
+ return __generator(this, function (_a) {
3219
+ try {
3220
+ onDataCallback(payload.subarray(5));
3221
+ }
3222
+ catch (error) {
3223
+ if (onErrorCallback) {
3224
+ onErrorCallback(error);
3225
+ }
3226
+ else {
3227
+ throw error;
3228
+ }
3229
+ }
3230
+ return [2 /*return*/];
3231
+ });
3232
+ }); };
3233
+ parser.onSettings = function () {
3234
+ console.log('Settings received');
3235
+ var ackSettingFrame = Http2Frame.createSettingsAckFrame();
3236
+ writer_2.write(ackSettingFrame);
3237
+ };
3238
+ parser.onHeaders = function (headers, header) {
3239
+ var plainHeaders = hpack.decodeHeaderFields(headers);
3240
+ console.log('Received headers:', plainHeaders);
3241
+ if (plainHeaders.get('grpc-status') === '0') {
3242
+ console.log('gRPC call success');
3243
+ }
3244
+ else if (plainHeaders.get('grpc-status') !== undefined) {
3245
+ var errMsg = plainHeaders.get('grpc-message') || 'gRPC call failed';
3246
+ var err = new Error(errMsg);
3247
+ if (onErrorCallback) {
3248
+ onErrorCallback(err);
3249
+ }
3250
+ else {
3251
+ throw err;
3252
+ }
3253
+ }
3254
+ };
3255
+ parser.processStream(stream);
3256
+ preface = Http2Frame.createPreface();
3257
+ return [4 /*yield*/, writer_2.write(preface)];
3258
+ case 4:
3259
+ _g.sent();
3260
+ settingFrame = Http2Frame.createSettingsFrame();
3261
+ return [4 /*yield*/, writer_2.write(settingFrame)];
3262
+ case 5:
3263
+ _g.sent();
3264
+ // Wait for the acknowledgement of SETTINGS
3265
+ return [4 /*yield*/, parser.waitForSettingsAck()];
3266
+ case 6:
3267
+ // Wait for the acknowledgement of SETTINGS
3268
+ _g.sent();
3269
+ ackSettingFrame = Http2Frame.createSettingsAckFrame();
3270
+ return [4 /*yield*/, writer_2.write(ackSettingFrame)];
3271
+ case 7:
3272
+ _g.sent();
3273
+ headerFrame = Http2Frame.createHeadersFrame(streamId, method, true, this.token);
3274
+ if (!(mode === 'unary' || mode === 'server-streaming')) return [3 /*break*/, 9];
3275
+ dataFrame = Http2Frame.createDataFrame(streamId, requestData, true);
3276
+ return [4 /*yield*/, writer_2.write(new Uint8Array(__spreadArray(__spreadArray([], headerFrame, true), dataFrame, true)))];
3277
+ case 8:
3278
+ _g.sent();
3279
+ return [3 /*break*/, 27];
3280
+ case 9:
3281
+ if (!((mode === 'client-streaming' || mode === 'bidirectional') && dataSourceCallback)) return [3 /*break*/, 27];
3282
+ return [4 /*yield*/, writer_2.write(headerFrame)];
3283
+ case 10:
3284
+ _g.sent();
3285
+ if (!(requestData.length > 0)) return [3 /*break*/, 12];
3286
+ dataFrame = Http2Frame.createDataFrame(streamId, requestData, false);
3287
+ return [4 /*yield*/, writer_2.write(dataFrame)];
3288
+ case 11:
3289
+ _g.sent();
3290
+ _g.label = 12;
3291
+ case 12:
3292
+ _g.trys.push([12, 18, 19, 24]);
3293
+ _a = true, _b = __asyncValues(dataSourceCallback());
3294
+ _g.label = 13;
3295
+ case 13: return [4 /*yield*/, _b.next()];
3296
+ case 14:
3297
+ if (!(_c = _g.sent(), _d = _c.done, !_d)) return [3 /*break*/, 17];
3298
+ _f = _c.value;
3299
+ _a = false;
3300
+ chunk = _f;
3301
+ dataFrame = Http2Frame.createDataFrame(streamId, chunk, false);
3302
+ return [4 /*yield*/, writer_2.write(dataFrame)];
3303
+ case 15:
3304
+ _g.sent();
3305
+ _g.label = 16;
3306
+ case 16:
3307
+ _a = true;
3308
+ return [3 /*break*/, 13];
3309
+ case 17: return [3 /*break*/, 24];
3310
+ case 18:
3311
+ e_1_1 = _g.sent();
3312
+ e_1 = { error: e_1_1 };
3313
+ return [3 /*break*/, 24];
3314
+ case 19:
3315
+ _g.trys.push([19, , 22, 23]);
3316
+ if (!(!_a && !_d && (_e = _b.return))) return [3 /*break*/, 21];
3317
+ return [4 /*yield*/, _e.call(_b)];
3318
+ case 20:
3319
+ _g.sent();
3320
+ _g.label = 21;
3321
+ case 21: return [3 /*break*/, 23];
3322
+ case 22:
3323
+ if (e_1) throw e_1.error;
3324
+ return [7 /*endfinally*/];
3325
+ case 23: return [7 /*endfinally*/];
3326
+ case 24:
3327
+ finalFrame = Http2Frame.createDataFrame(streamId, new Uint8Array(), true);
3328
+ return [4 /*yield*/, writer_2.write(finalFrame)];
3329
+ case 25:
3330
+ _g.sent();
3331
+ return [4 /*yield*/, writer_2.end()];
3332
+ case 26:
3333
+ _g.sent();
3334
+ _g.label = 27;
3335
+ case 27: return [4 /*yield*/, parser.waitForEndOfStream(0)];
3336
+ case 28:
3337
+ _g.sent();
3338
+ if (onEndCallback) {
3339
+ onEndCallback();
3340
+ }
3341
+ return [3 /*break*/, 33];
3342
+ case 29:
3343
+ err_2 = _g.sent();
3344
+ if (onErrorCallback) {
3345
+ onErrorCallback(err_2);
3346
+ }
3347
+ else {
3348
+ if (err_2 instanceof Error) {
3349
+ console.error('asyncCall error:', err_2.message);
3350
+ }
3351
+ else {
3352
+ console.error('asyncCall error:', err_2);
3353
+ }
3354
+ }
3355
+ return [3 /*break*/, 33];
3356
+ case 30:
3357
+ if (!stream) return [3 /*break*/, 32];
3358
+ return [4 /*yield*/, stream.close()];
3359
+ case 31:
3360
+ _g.sent();
3361
+ _g.label = 32;
3362
+ case 32: return [7 /*endfinally*/];
3363
+ case 33: return [2 /*return*/];
3364
+ }
3365
+ });
3366
+ }); })();
3367
+ return [2 /*return*/, Promise.race([operationPromise, timeoutPromise])];
3368
+ });
3369
+ });
3370
+ };
3371
+ return Libp2pGrpcClient;
3372
+ }());
3373
+
3374
+ exports.Libp2pGrpcClient = Libp2pGrpcClient;
3375
+
3376
+ }));
3377
+ //# sourceMappingURL=grpc.js.map