@solana/web3.js 1.68.1 → 1.70.0-pr-29130

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/lib/index.cjs.js CHANGED
@@ -11,11 +11,16 @@ var sha256 = require('@noble/hashes/sha256');
11
11
  var borsh = require('borsh');
12
12
  var BufferLayout = require('@solana/buffer-layout');
13
13
  var bigintBuffer = require('bigint-buffer');
14
+ var require$$1 = require('tty');
15
+ var require$$0$1 = require('os');
16
+ var require$$0 = require('util');
17
+ var require$$0$2 = require('events');
18
+ var require$$1$1 = require('path');
19
+ var require$$0$3 = require('http');
20
+ var require$$0$4 = require('https');
14
21
  var superstruct = require('superstruct');
15
22
  var rpcWebsockets = require('rpc-websockets');
16
23
  var RpcClient = require('jayson/lib/client/browser');
17
- var http = require('http');
18
- var https = require('https');
19
24
  var nodeFetch = require('node-fetch');
20
25
  var sha3 = require('@noble/hashes/sha3');
21
26
  var hmac = require('@noble/hashes/hmac');
@@ -45,9 +50,14 @@ var ed25519__namespace = /*#__PURE__*/_interopNamespace(ed25519);
45
50
  var BN__default = /*#__PURE__*/_interopDefaultLegacy(BN);
46
51
  var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58);
47
52
  var BufferLayout__namespace = /*#__PURE__*/_interopNamespace(BufferLayout);
53
+ var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
54
+ var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
55
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
56
+ var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
57
+ var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
58
+ var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
59
+ var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
48
60
  var RpcClient__default = /*#__PURE__*/_interopDefaultLegacy(RpcClient);
49
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
50
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
51
61
  var nodeFetch__namespace = /*#__PURE__*/_interopNamespace(nodeFetch);
52
62
  var secp256k1__namespace = /*#__PURE__*/_interopNamespace(secp256k1);
53
63
 
@@ -2245,6 +2255,7 @@ async function sendAndConfirmTransaction(connection, transaction, signers, optio
2245
2255
 
2246
2256
  if (transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null) {
2247
2257
  status = (await connection.confirmTransaction({
2258
+ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal,
2248
2259
  signature: signature,
2249
2260
  blockhash: transaction.recentBlockhash,
2250
2261
  lastValidBlockHeight: transaction.lastValidBlockHeight
@@ -2255,12 +2266,17 @@ async function sendAndConfirmTransaction(connection, transaction, signers, optio
2255
2266
  } = transaction.nonceInfo;
2256
2267
  const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;
2257
2268
  status = (await connection.confirmTransaction({
2269
+ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal,
2258
2270
  minContextSlot: transaction.minNonceContextSlot,
2259
2271
  nonceAccountPubkey,
2260
2272
  nonceValue: transaction.nonceInfo.nonce,
2261
2273
  signature
2262
2274
  }, options && options.commitment)).value;
2263
2275
  } else {
2276
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) != null) {
2277
+ console.warn('sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' + 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' + 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.');
2278
+ }
2279
+
2264
2280
  status = (await connection.confirmTransaction(signature, options && options.commitment)).value;
2265
2281
  }
2266
2282
 
@@ -3136,190 +3152,2780 @@ class Loader {
3136
3152
  */
3137
3153
 
3138
3154
 
3139
- /**
3140
- * Minimum number of signatures required to load a program not including
3141
- * retries
3142
- *
3143
- * Can be used to calculate transaction fees
3144
- */
3145
- static getMinNumSignatures(dataLength) {
3146
- return 2 * ( // Every transaction requires two signatures (payer + program)
3147
- Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction
3148
- 1) // Add one for Finalize transaction
3149
- ;
3150
- }
3151
- /**
3152
- * Loads a generic program
3153
- *
3154
- * @param connection The connection to use
3155
- * @param payer System account that pays to load the program
3156
- * @param program Account to load the program into
3157
- * @param programId Public key that identifies the loader
3158
- * @param data Program octets
3159
- * @return true if program was loaded successfully, false if program was already loaded
3160
- */
3155
+ /**
3156
+ * Minimum number of signatures required to load a program not including
3157
+ * retries
3158
+ *
3159
+ * Can be used to calculate transaction fees
3160
+ */
3161
+ static getMinNumSignatures(dataLength) {
3162
+ return 2 * ( // Every transaction requires two signatures (payer + program)
3163
+ Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction
3164
+ 1) // Add one for Finalize transaction
3165
+ ;
3166
+ }
3167
+ /**
3168
+ * Loads a generic program
3169
+ *
3170
+ * @param connection The connection to use
3171
+ * @param payer System account that pays to load the program
3172
+ * @param program Account to load the program into
3173
+ * @param programId Public key that identifies the loader
3174
+ * @param data Program octets
3175
+ * @return true if program was loaded successfully, false if program was already loaded
3176
+ */
3177
+
3178
+
3179
+ static async load(connection, payer, program, programId, data) {
3180
+ {
3181
+ const balanceNeeded = await connection.getMinimumBalanceForRentExemption(data.length); // Fetch program account info to check if it has already been created
3182
+
3183
+ const programInfo = await connection.getAccountInfo(program.publicKey, 'confirmed');
3184
+ let transaction = null;
3185
+
3186
+ if (programInfo !== null) {
3187
+ if (programInfo.executable) {
3188
+ console.error('Program load failed, account is already executable');
3189
+ return false;
3190
+ }
3191
+
3192
+ if (programInfo.data.length !== data.length) {
3193
+ transaction = transaction || new Transaction();
3194
+ transaction.add(SystemProgram.allocate({
3195
+ accountPubkey: program.publicKey,
3196
+ space: data.length
3197
+ }));
3198
+ }
3199
+
3200
+ if (!programInfo.owner.equals(programId)) {
3201
+ transaction = transaction || new Transaction();
3202
+ transaction.add(SystemProgram.assign({
3203
+ accountPubkey: program.publicKey,
3204
+ programId
3205
+ }));
3206
+ }
3207
+
3208
+ if (programInfo.lamports < balanceNeeded) {
3209
+ transaction = transaction || new Transaction();
3210
+ transaction.add(SystemProgram.transfer({
3211
+ fromPubkey: payer.publicKey,
3212
+ toPubkey: program.publicKey,
3213
+ lamports: balanceNeeded - programInfo.lamports
3214
+ }));
3215
+ }
3216
+ } else {
3217
+ transaction = new Transaction().add(SystemProgram.createAccount({
3218
+ fromPubkey: payer.publicKey,
3219
+ newAccountPubkey: program.publicKey,
3220
+ lamports: balanceNeeded > 0 ? balanceNeeded : 1,
3221
+ space: data.length,
3222
+ programId
3223
+ }));
3224
+ } // If the account is already created correctly, skip this step
3225
+ // and proceed directly to loading instructions
3226
+
3227
+
3228
+ if (transaction !== null) {
3229
+ await sendAndConfirmTransaction(connection, transaction, [payer, program], {
3230
+ commitment: 'confirmed'
3231
+ });
3232
+ }
3233
+ }
3234
+ const dataLayout = BufferLayout__namespace.struct([BufferLayout__namespace.u32('instruction'), BufferLayout__namespace.u32('offset'), BufferLayout__namespace.u32('bytesLength'), BufferLayout__namespace.u32('bytesLengthPadding'), BufferLayout__namespace.seq(BufferLayout__namespace.u8('byte'), BufferLayout__namespace.offset(BufferLayout__namespace.u32(), -8), 'bytes')]);
3235
+ const chunkSize = Loader.chunkSize;
3236
+ let offset = 0;
3237
+ let array = data;
3238
+ let transactions = [];
3239
+
3240
+ while (array.length > 0) {
3241
+ const bytes = array.slice(0, chunkSize);
3242
+ const data = buffer.Buffer.alloc(chunkSize + 16);
3243
+ dataLayout.encode({
3244
+ instruction: 0,
3245
+ // Load instruction
3246
+ offset,
3247
+ bytes: bytes,
3248
+ bytesLength: 0,
3249
+ bytesLengthPadding: 0
3250
+ }, data);
3251
+ const transaction = new Transaction().add({
3252
+ keys: [{
3253
+ pubkey: program.publicKey,
3254
+ isSigner: true,
3255
+ isWritable: true
3256
+ }],
3257
+ programId,
3258
+ data
3259
+ });
3260
+ transactions.push(sendAndConfirmTransaction(connection, transaction, [payer, program], {
3261
+ commitment: 'confirmed'
3262
+ })); // Delay between sends in an attempt to reduce rate limit errors
3263
+
3264
+ if (connection._rpcEndpoint.includes('solana.com')) {
3265
+ const REQUESTS_PER_SECOND = 4;
3266
+ await sleep(1000 / REQUESTS_PER_SECOND);
3267
+ }
3268
+
3269
+ offset += chunkSize;
3270
+ array = array.slice(chunkSize);
3271
+ }
3272
+
3273
+ await Promise.all(transactions); // Finalize the account loaded with program data for execution
3274
+
3275
+ {
3276
+ const dataLayout = BufferLayout__namespace.struct([BufferLayout__namespace.u32('instruction')]);
3277
+ const data = buffer.Buffer.alloc(dataLayout.span);
3278
+ dataLayout.encode({
3279
+ instruction: 1 // Finalize instruction
3280
+
3281
+ }, data);
3282
+ const transaction = new Transaction().add({
3283
+ keys: [{
3284
+ pubkey: program.publicKey,
3285
+ isSigner: true,
3286
+ isWritable: true
3287
+ }, {
3288
+ pubkey: SYSVAR_RENT_PUBKEY,
3289
+ isSigner: false,
3290
+ isWritable: false
3291
+ }],
3292
+ programId,
3293
+ data
3294
+ });
3295
+ await sendAndConfirmTransaction(connection, transaction, [payer, program], {
3296
+ commitment: 'confirmed'
3297
+ });
3298
+ } // success
3299
+
3300
+ return true;
3301
+ }
3302
+
3303
+ }
3304
+ Loader.chunkSize = CHUNK_SIZE;
3305
+
3306
+ const BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111');
3307
+ /**
3308
+ * Factory class for transactions to interact with a program loader
3309
+ */
3310
+
3311
+ class BpfLoader {
3312
+ /**
3313
+ * Minimum number of signatures required to load a program not including
3314
+ * retries
3315
+ *
3316
+ * Can be used to calculate transaction fees
3317
+ */
3318
+ static getMinNumSignatures(dataLength) {
3319
+ return Loader.getMinNumSignatures(dataLength);
3320
+ }
3321
+ /**
3322
+ * Load a SBF program
3323
+ *
3324
+ * @param connection The connection to use
3325
+ * @param payer Account that will pay program loading fees
3326
+ * @param program Account to load the program into
3327
+ * @param elf The entire ELF containing the SBF program
3328
+ * @param loaderProgramId The program id of the BPF loader to use
3329
+ * @return true if program was loaded successfully, false if program was already loaded
3330
+ */
3331
+
3332
+
3333
+ static load(connection, payer, program, elf, loaderProgramId) {
3334
+ return Loader.load(connection, payer, program, loaderProgramId, elf);
3335
+ }
3336
+
3337
+ }
3338
+
3339
+ function getDefaultExportFromCjs (x) {
3340
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3341
+ }
3342
+
3343
+ var agentkeepalive = {exports: {}};
3344
+
3345
+ /**
3346
+ * Helpers.
3347
+ */
3348
+
3349
+ var s = 1000;
3350
+ var m = s * 60;
3351
+ var h = m * 60;
3352
+ var d = h * 24;
3353
+ var w = d * 7;
3354
+ var y = d * 365.25;
3355
+
3356
+ /**
3357
+ * Parse or format the given `val`.
3358
+ *
3359
+ * Options:
3360
+ *
3361
+ * - `long` verbose formatting [false]
3362
+ *
3363
+ * @param {String|Number} val
3364
+ * @param {Object} [options]
3365
+ * @throws {Error} throw an error if val is not a non-empty string or a number
3366
+ * @return {String|Number}
3367
+ * @api public
3368
+ */
3369
+
3370
+ var ms$3 = function (val, options) {
3371
+ options = options || {};
3372
+ var type = typeof val;
3373
+ if (type === 'string' && val.length > 0) {
3374
+ return parse(val);
3375
+ } else if (type === 'number' && isFinite(val)) {
3376
+ return options.long ? fmtLong(val) : fmtShort(val);
3377
+ }
3378
+ throw new Error(
3379
+ 'val is not a non-empty string or a valid number. val=' +
3380
+ JSON.stringify(val)
3381
+ );
3382
+ };
3383
+
3384
+ /**
3385
+ * Parse the given `str` and return milliseconds.
3386
+ *
3387
+ * @param {String} str
3388
+ * @return {Number}
3389
+ * @api private
3390
+ */
3391
+
3392
+ function parse(str) {
3393
+ str = String(str);
3394
+ if (str.length > 100) {
3395
+ return;
3396
+ }
3397
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
3398
+ str
3399
+ );
3400
+ if (!match) {
3401
+ return;
3402
+ }
3403
+ var n = parseFloat(match[1]);
3404
+ var type = (match[2] || 'ms').toLowerCase();
3405
+ switch (type) {
3406
+ case 'years':
3407
+ case 'year':
3408
+ case 'yrs':
3409
+ case 'yr':
3410
+ case 'y':
3411
+ return n * y;
3412
+ case 'weeks':
3413
+ case 'week':
3414
+ case 'w':
3415
+ return n * w;
3416
+ case 'days':
3417
+ case 'day':
3418
+ case 'd':
3419
+ return n * d;
3420
+ case 'hours':
3421
+ case 'hour':
3422
+ case 'hrs':
3423
+ case 'hr':
3424
+ case 'h':
3425
+ return n * h;
3426
+ case 'minutes':
3427
+ case 'minute':
3428
+ case 'mins':
3429
+ case 'min':
3430
+ case 'm':
3431
+ return n * m;
3432
+ case 'seconds':
3433
+ case 'second':
3434
+ case 'secs':
3435
+ case 'sec':
3436
+ case 's':
3437
+ return n * s;
3438
+ case 'milliseconds':
3439
+ case 'millisecond':
3440
+ case 'msecs':
3441
+ case 'msec':
3442
+ case 'ms':
3443
+ return n;
3444
+ default:
3445
+ return undefined;
3446
+ }
3447
+ }
3448
+
3449
+ /**
3450
+ * Short format for `ms`.
3451
+ *
3452
+ * @param {Number} ms
3453
+ * @return {String}
3454
+ * @api private
3455
+ */
3456
+
3457
+ function fmtShort(ms) {
3458
+ var msAbs = Math.abs(ms);
3459
+ if (msAbs >= d) {
3460
+ return Math.round(ms / d) + 'd';
3461
+ }
3462
+ if (msAbs >= h) {
3463
+ return Math.round(ms / h) + 'h';
3464
+ }
3465
+ if (msAbs >= m) {
3466
+ return Math.round(ms / m) + 'm';
3467
+ }
3468
+ if (msAbs >= s) {
3469
+ return Math.round(ms / s) + 's';
3470
+ }
3471
+ return ms + 'ms';
3472
+ }
3473
+
3474
+ /**
3475
+ * Long format for `ms`.
3476
+ *
3477
+ * @param {Number} ms
3478
+ * @return {String}
3479
+ * @api private
3480
+ */
3481
+
3482
+ function fmtLong(ms) {
3483
+ var msAbs = Math.abs(ms);
3484
+ if (msAbs >= d) {
3485
+ return plural(ms, msAbs, d, 'day');
3486
+ }
3487
+ if (msAbs >= h) {
3488
+ return plural(ms, msAbs, h, 'hour');
3489
+ }
3490
+ if (msAbs >= m) {
3491
+ return plural(ms, msAbs, m, 'minute');
3492
+ }
3493
+ if (msAbs >= s) {
3494
+ return plural(ms, msAbs, s, 'second');
3495
+ }
3496
+ return ms + ' ms';
3497
+ }
3498
+
3499
+ /**
3500
+ * Pluralization helper.
3501
+ */
3502
+
3503
+ function plural(ms, msAbs, n, name) {
3504
+ var isPlural = msAbs >= n * 1.5;
3505
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
3506
+ }
3507
+
3508
+ /*!
3509
+ * humanize-ms - index.js
3510
+ * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
3511
+ * MIT Licensed
3512
+ */
3513
+
3514
+ /**
3515
+ * Module dependencies.
3516
+ */
3517
+
3518
+ var util = require$$0__default["default"];
3519
+ var ms$2 = ms$3;
3520
+
3521
+ var humanizeMs = function (t) {
3522
+ if (typeof t === 'number') return t;
3523
+ var r = ms$2(t);
3524
+ if (r === undefined) {
3525
+ var err = new Error(util.format('humanize-ms(%j) result undefined', t));
3526
+ console.warn(err.stack);
3527
+ }
3528
+ return r;
3529
+ };
3530
+
3531
+ var src = {exports: {}};
3532
+
3533
+ var browser = {exports: {}};
3534
+
3535
+ /**
3536
+ * Helpers.
3537
+ */
3538
+
3539
+ var ms$1;
3540
+ var hasRequiredMs;
3541
+
3542
+ function requireMs () {
3543
+ if (hasRequiredMs) return ms$1;
3544
+ hasRequiredMs = 1;
3545
+ var s = 1000;
3546
+ var m = s * 60;
3547
+ var h = m * 60;
3548
+ var d = h * 24;
3549
+ var w = d * 7;
3550
+ var y = d * 365.25;
3551
+
3552
+ /**
3553
+ * Parse or format the given `val`.
3554
+ *
3555
+ * Options:
3556
+ *
3557
+ * - `long` verbose formatting [false]
3558
+ *
3559
+ * @param {String|Number} val
3560
+ * @param {Object} [options]
3561
+ * @throws {Error} throw an error if val is not a non-empty string or a number
3562
+ * @return {String|Number}
3563
+ * @api public
3564
+ */
3565
+
3566
+ ms$1 = function(val, options) {
3567
+ options = options || {};
3568
+ var type = typeof val;
3569
+ if (type === 'string' && val.length > 0) {
3570
+ return parse(val);
3571
+ } else if (type === 'number' && isFinite(val)) {
3572
+ return options.long ? fmtLong(val) : fmtShort(val);
3573
+ }
3574
+ throw new Error(
3575
+ 'val is not a non-empty string or a valid number. val=' +
3576
+ JSON.stringify(val)
3577
+ );
3578
+ };
3579
+
3580
+ /**
3581
+ * Parse the given `str` and return milliseconds.
3582
+ *
3583
+ * @param {String} str
3584
+ * @return {Number}
3585
+ * @api private
3586
+ */
3587
+
3588
+ function parse(str) {
3589
+ str = String(str);
3590
+ if (str.length > 100) {
3591
+ return;
3592
+ }
3593
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
3594
+ str
3595
+ );
3596
+ if (!match) {
3597
+ return;
3598
+ }
3599
+ var n = parseFloat(match[1]);
3600
+ var type = (match[2] || 'ms').toLowerCase();
3601
+ switch (type) {
3602
+ case 'years':
3603
+ case 'year':
3604
+ case 'yrs':
3605
+ case 'yr':
3606
+ case 'y':
3607
+ return n * y;
3608
+ case 'weeks':
3609
+ case 'week':
3610
+ case 'w':
3611
+ return n * w;
3612
+ case 'days':
3613
+ case 'day':
3614
+ case 'd':
3615
+ return n * d;
3616
+ case 'hours':
3617
+ case 'hour':
3618
+ case 'hrs':
3619
+ case 'hr':
3620
+ case 'h':
3621
+ return n * h;
3622
+ case 'minutes':
3623
+ case 'minute':
3624
+ case 'mins':
3625
+ case 'min':
3626
+ case 'm':
3627
+ return n * m;
3628
+ case 'seconds':
3629
+ case 'second':
3630
+ case 'secs':
3631
+ case 'sec':
3632
+ case 's':
3633
+ return n * s;
3634
+ case 'milliseconds':
3635
+ case 'millisecond':
3636
+ case 'msecs':
3637
+ case 'msec':
3638
+ case 'ms':
3639
+ return n;
3640
+ default:
3641
+ return undefined;
3642
+ }
3643
+ }
3644
+
3645
+ /**
3646
+ * Short format for `ms`.
3647
+ *
3648
+ * @param {Number} ms
3649
+ * @return {String}
3650
+ * @api private
3651
+ */
3652
+
3653
+ function fmtShort(ms) {
3654
+ var msAbs = Math.abs(ms);
3655
+ if (msAbs >= d) {
3656
+ return Math.round(ms / d) + 'd';
3657
+ }
3658
+ if (msAbs >= h) {
3659
+ return Math.round(ms / h) + 'h';
3660
+ }
3661
+ if (msAbs >= m) {
3662
+ return Math.round(ms / m) + 'm';
3663
+ }
3664
+ if (msAbs >= s) {
3665
+ return Math.round(ms / s) + 's';
3666
+ }
3667
+ return ms + 'ms';
3668
+ }
3669
+
3670
+ /**
3671
+ * Long format for `ms`.
3672
+ *
3673
+ * @param {Number} ms
3674
+ * @return {String}
3675
+ * @api private
3676
+ */
3677
+
3678
+ function fmtLong(ms) {
3679
+ var msAbs = Math.abs(ms);
3680
+ if (msAbs >= d) {
3681
+ return plural(ms, msAbs, d, 'day');
3682
+ }
3683
+ if (msAbs >= h) {
3684
+ return plural(ms, msAbs, h, 'hour');
3685
+ }
3686
+ if (msAbs >= m) {
3687
+ return plural(ms, msAbs, m, 'minute');
3688
+ }
3689
+ if (msAbs >= s) {
3690
+ return plural(ms, msAbs, s, 'second');
3691
+ }
3692
+ return ms + ' ms';
3693
+ }
3694
+
3695
+ /**
3696
+ * Pluralization helper.
3697
+ */
3698
+
3699
+ function plural(ms, msAbs, n, name) {
3700
+ var isPlural = msAbs >= n * 1.5;
3701
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
3702
+ }
3703
+ return ms$1;
3704
+ }
3705
+
3706
+ var common;
3707
+ var hasRequiredCommon;
3708
+
3709
+ function requireCommon () {
3710
+ if (hasRequiredCommon) return common;
3711
+ hasRequiredCommon = 1;
3712
+ /**
3713
+ * This is the common logic for both the Node.js and web browser
3714
+ * implementations of `debug()`.
3715
+ */
3716
+
3717
+ function setup(env) {
3718
+ createDebug.debug = createDebug;
3719
+ createDebug.default = createDebug;
3720
+ createDebug.coerce = coerce;
3721
+ createDebug.disable = disable;
3722
+ createDebug.enable = enable;
3723
+ createDebug.enabled = enabled;
3724
+ createDebug.humanize = requireMs();
3725
+ createDebug.destroy = destroy;
3726
+
3727
+ Object.keys(env).forEach(key => {
3728
+ createDebug[key] = env[key];
3729
+ });
3730
+
3731
+ /**
3732
+ * The currently active debug mode names, and names to skip.
3733
+ */
3734
+
3735
+ createDebug.names = [];
3736
+ createDebug.skips = [];
3737
+
3738
+ /**
3739
+ * Map of special "%n" handling functions, for the debug "format" argument.
3740
+ *
3741
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
3742
+ */
3743
+ createDebug.formatters = {};
3744
+
3745
+ /**
3746
+ * Selects a color for a debug namespace
3747
+ * @param {String} namespace The namespace string for the debug instance to be colored
3748
+ * @return {Number|String} An ANSI color code for the given namespace
3749
+ * @api private
3750
+ */
3751
+ function selectColor(namespace) {
3752
+ let hash = 0;
3753
+
3754
+ for (let i = 0; i < namespace.length; i++) {
3755
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
3756
+ hash |= 0; // Convert to 32bit integer
3757
+ }
3758
+
3759
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
3760
+ }
3761
+ createDebug.selectColor = selectColor;
3762
+
3763
+ /**
3764
+ * Create a debugger with the given `namespace`.
3765
+ *
3766
+ * @param {String} namespace
3767
+ * @return {Function}
3768
+ * @api public
3769
+ */
3770
+ function createDebug(namespace) {
3771
+ let prevTime;
3772
+ let enableOverride = null;
3773
+ let namespacesCache;
3774
+ let enabledCache;
3775
+
3776
+ function debug(...args) {
3777
+ // Disabled?
3778
+ if (!debug.enabled) {
3779
+ return;
3780
+ }
3781
+
3782
+ const self = debug;
3783
+
3784
+ // Set `diff` timestamp
3785
+ const curr = Number(new Date());
3786
+ const ms = curr - (prevTime || curr);
3787
+ self.diff = ms;
3788
+ self.prev = prevTime;
3789
+ self.curr = curr;
3790
+ prevTime = curr;
3791
+
3792
+ args[0] = createDebug.coerce(args[0]);
3793
+
3794
+ if (typeof args[0] !== 'string') {
3795
+ // Anything else let's inspect with %O
3796
+ args.unshift('%O');
3797
+ }
3798
+
3799
+ // Apply any `formatters` transformations
3800
+ let index = 0;
3801
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
3802
+ // If we encounter an escaped % then don't increase the array index
3803
+ if (match === '%%') {
3804
+ return '%';
3805
+ }
3806
+ index++;
3807
+ const formatter = createDebug.formatters[format];
3808
+ if (typeof formatter === 'function') {
3809
+ const val = args[index];
3810
+ match = formatter.call(self, val);
3811
+
3812
+ // Now we need to remove `args[index]` since it's inlined in the `format`
3813
+ args.splice(index, 1);
3814
+ index--;
3815
+ }
3816
+ return match;
3817
+ });
3818
+
3819
+ // Apply env-specific formatting (colors, etc.)
3820
+ createDebug.formatArgs.call(self, args);
3821
+
3822
+ const logFn = self.log || createDebug.log;
3823
+ logFn.apply(self, args);
3824
+ }
3825
+
3826
+ debug.namespace = namespace;
3827
+ debug.useColors = createDebug.useColors();
3828
+ debug.color = createDebug.selectColor(namespace);
3829
+ debug.extend = extend;
3830
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
3831
+
3832
+ Object.defineProperty(debug, 'enabled', {
3833
+ enumerable: true,
3834
+ configurable: false,
3835
+ get: () => {
3836
+ if (enableOverride !== null) {
3837
+ return enableOverride;
3838
+ }
3839
+ if (namespacesCache !== createDebug.namespaces) {
3840
+ namespacesCache = createDebug.namespaces;
3841
+ enabledCache = createDebug.enabled(namespace);
3842
+ }
3843
+
3844
+ return enabledCache;
3845
+ },
3846
+ set: v => {
3847
+ enableOverride = v;
3848
+ }
3849
+ });
3850
+
3851
+ // Env-specific initialization logic for debug instances
3852
+ if (typeof createDebug.init === 'function') {
3853
+ createDebug.init(debug);
3854
+ }
3855
+
3856
+ return debug;
3857
+ }
3858
+
3859
+ function extend(namespace, delimiter) {
3860
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
3861
+ newDebug.log = this.log;
3862
+ return newDebug;
3863
+ }
3864
+
3865
+ /**
3866
+ * Enables a debug mode by namespaces. This can include modes
3867
+ * separated by a colon and wildcards.
3868
+ *
3869
+ * @param {String} namespaces
3870
+ * @api public
3871
+ */
3872
+ function enable(namespaces) {
3873
+ createDebug.save(namespaces);
3874
+ createDebug.namespaces = namespaces;
3875
+
3876
+ createDebug.names = [];
3877
+ createDebug.skips = [];
3878
+
3879
+ let i;
3880
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
3881
+ const len = split.length;
3882
+
3883
+ for (i = 0; i < len; i++) {
3884
+ if (!split[i]) {
3885
+ // ignore empty strings
3886
+ continue;
3887
+ }
3888
+
3889
+ namespaces = split[i].replace(/\*/g, '.*?');
3890
+
3891
+ if (namespaces[0] === '-') {
3892
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
3893
+ } else {
3894
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
3895
+ }
3896
+ }
3897
+ }
3898
+
3899
+ /**
3900
+ * Disable debug output.
3901
+ *
3902
+ * @return {String} namespaces
3903
+ * @api public
3904
+ */
3905
+ function disable() {
3906
+ const namespaces = [
3907
+ ...createDebug.names.map(toNamespace),
3908
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
3909
+ ].join(',');
3910
+ createDebug.enable('');
3911
+ return namespaces;
3912
+ }
3913
+
3914
+ /**
3915
+ * Returns true if the given mode name is enabled, false otherwise.
3916
+ *
3917
+ * @param {String} name
3918
+ * @return {Boolean}
3919
+ * @api public
3920
+ */
3921
+ function enabled(name) {
3922
+ if (name[name.length - 1] === '*') {
3923
+ return true;
3924
+ }
3925
+
3926
+ let i;
3927
+ let len;
3928
+
3929
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
3930
+ if (createDebug.skips[i].test(name)) {
3931
+ return false;
3932
+ }
3933
+ }
3934
+
3935
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
3936
+ if (createDebug.names[i].test(name)) {
3937
+ return true;
3938
+ }
3939
+ }
3940
+
3941
+ return false;
3942
+ }
3943
+
3944
+ /**
3945
+ * Convert regexp to namespace
3946
+ *
3947
+ * @param {RegExp} regxep
3948
+ * @return {String} namespace
3949
+ * @api private
3950
+ */
3951
+ function toNamespace(regexp) {
3952
+ return regexp.toString()
3953
+ .substring(2, regexp.toString().length - 2)
3954
+ .replace(/\.\*\?$/, '*');
3955
+ }
3956
+
3957
+ /**
3958
+ * Coerce `val`.
3959
+ *
3960
+ * @param {Mixed} val
3961
+ * @return {Mixed}
3962
+ * @api private
3963
+ */
3964
+ function coerce(val) {
3965
+ if (val instanceof Error) {
3966
+ return val.stack || val.message;
3967
+ }
3968
+ return val;
3969
+ }
3970
+
3971
+ /**
3972
+ * XXX DO NOT USE. This is a temporary stub function.
3973
+ * XXX It WILL be removed in the next major release.
3974
+ */
3975
+ function destroy() {
3976
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
3977
+ }
3978
+
3979
+ createDebug.enable(createDebug.load());
3980
+
3981
+ return createDebug;
3982
+ }
3983
+
3984
+ common = setup;
3985
+ return common;
3986
+ }
3987
+
3988
+ /* eslint-env browser */
3989
+
3990
+ var hasRequiredBrowser;
3991
+
3992
+ function requireBrowser () {
3993
+ if (hasRequiredBrowser) return browser.exports;
3994
+ hasRequiredBrowser = 1;
3995
+ (function (module, exports) {
3996
+ /**
3997
+ * This is the web browser implementation of `debug()`.
3998
+ */
3999
+
4000
+ exports.formatArgs = formatArgs;
4001
+ exports.save = save;
4002
+ exports.load = load;
4003
+ exports.useColors = useColors;
4004
+ exports.storage = localstorage();
4005
+ exports.destroy = (() => {
4006
+ let warned = false;
4007
+
4008
+ return () => {
4009
+ if (!warned) {
4010
+ warned = true;
4011
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
4012
+ }
4013
+ };
4014
+ })();
4015
+
4016
+ /**
4017
+ * Colors.
4018
+ */
4019
+
4020
+ exports.colors = [
4021
+ '#0000CC',
4022
+ '#0000FF',
4023
+ '#0033CC',
4024
+ '#0033FF',
4025
+ '#0066CC',
4026
+ '#0066FF',
4027
+ '#0099CC',
4028
+ '#0099FF',
4029
+ '#00CC00',
4030
+ '#00CC33',
4031
+ '#00CC66',
4032
+ '#00CC99',
4033
+ '#00CCCC',
4034
+ '#00CCFF',
4035
+ '#3300CC',
4036
+ '#3300FF',
4037
+ '#3333CC',
4038
+ '#3333FF',
4039
+ '#3366CC',
4040
+ '#3366FF',
4041
+ '#3399CC',
4042
+ '#3399FF',
4043
+ '#33CC00',
4044
+ '#33CC33',
4045
+ '#33CC66',
4046
+ '#33CC99',
4047
+ '#33CCCC',
4048
+ '#33CCFF',
4049
+ '#6600CC',
4050
+ '#6600FF',
4051
+ '#6633CC',
4052
+ '#6633FF',
4053
+ '#66CC00',
4054
+ '#66CC33',
4055
+ '#9900CC',
4056
+ '#9900FF',
4057
+ '#9933CC',
4058
+ '#9933FF',
4059
+ '#99CC00',
4060
+ '#99CC33',
4061
+ '#CC0000',
4062
+ '#CC0033',
4063
+ '#CC0066',
4064
+ '#CC0099',
4065
+ '#CC00CC',
4066
+ '#CC00FF',
4067
+ '#CC3300',
4068
+ '#CC3333',
4069
+ '#CC3366',
4070
+ '#CC3399',
4071
+ '#CC33CC',
4072
+ '#CC33FF',
4073
+ '#CC6600',
4074
+ '#CC6633',
4075
+ '#CC9900',
4076
+ '#CC9933',
4077
+ '#CCCC00',
4078
+ '#CCCC33',
4079
+ '#FF0000',
4080
+ '#FF0033',
4081
+ '#FF0066',
4082
+ '#FF0099',
4083
+ '#FF00CC',
4084
+ '#FF00FF',
4085
+ '#FF3300',
4086
+ '#FF3333',
4087
+ '#FF3366',
4088
+ '#FF3399',
4089
+ '#FF33CC',
4090
+ '#FF33FF',
4091
+ '#FF6600',
4092
+ '#FF6633',
4093
+ '#FF9900',
4094
+ '#FF9933',
4095
+ '#FFCC00',
4096
+ '#FFCC33'
4097
+ ];
4098
+
4099
+ /**
4100
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
4101
+ * and the Firebug extension (any Firefox version) are known
4102
+ * to support "%c" CSS customizations.
4103
+ *
4104
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
4105
+ */
4106
+
4107
+ // eslint-disable-next-line complexity
4108
+ function useColors() {
4109
+ // NB: In an Electron preload script, document will be defined but not fully
4110
+ // initialized. Since we know we're in Chrome, we'll just detect this case
4111
+ // explicitly
4112
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
4113
+ return true;
4114
+ }
4115
+
4116
+ // Internet Explorer and Edge do not support colors.
4117
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
4118
+ return false;
4119
+ }
4120
+
4121
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
4122
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
4123
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
4124
+ // Is firebug? http://stackoverflow.com/a/398120/376773
4125
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
4126
+ // Is firefox >= v31?
4127
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
4128
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
4129
+ // Double check webkit in userAgent just in case we are in a worker
4130
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
4131
+ }
4132
+
4133
+ /**
4134
+ * Colorize log arguments if enabled.
4135
+ *
4136
+ * @api public
4137
+ */
4138
+
4139
+ function formatArgs(args) {
4140
+ args[0] = (this.useColors ? '%c' : '') +
4141
+ this.namespace +
4142
+ (this.useColors ? ' %c' : ' ') +
4143
+ args[0] +
4144
+ (this.useColors ? '%c ' : ' ') +
4145
+ '+' + module.exports.humanize(this.diff);
4146
+
4147
+ if (!this.useColors) {
4148
+ return;
4149
+ }
4150
+
4151
+ const c = 'color: ' + this.color;
4152
+ args.splice(1, 0, c, 'color: inherit');
4153
+
4154
+ // The final "%c" is somewhat tricky, because there could be other
4155
+ // arguments passed either before or after the %c, so we need to
4156
+ // figure out the correct index to insert the CSS into
4157
+ let index = 0;
4158
+ let lastC = 0;
4159
+ args[0].replace(/%[a-zA-Z%]/g, match => {
4160
+ if (match === '%%') {
4161
+ return;
4162
+ }
4163
+ index++;
4164
+ if (match === '%c') {
4165
+ // We only are interested in the *last* %c
4166
+ // (the user may have provided their own)
4167
+ lastC = index;
4168
+ }
4169
+ });
4170
+
4171
+ args.splice(lastC, 0, c);
4172
+ }
4173
+
4174
+ /**
4175
+ * Invokes `console.debug()` when available.
4176
+ * No-op when `console.debug` is not a "function".
4177
+ * If `console.debug` is not available, falls back
4178
+ * to `console.log`.
4179
+ *
4180
+ * @api public
4181
+ */
4182
+ exports.log = console.debug || console.log || (() => {});
4183
+
4184
+ /**
4185
+ * Save `namespaces`.
4186
+ *
4187
+ * @param {String} namespaces
4188
+ * @api private
4189
+ */
4190
+ function save(namespaces) {
4191
+ try {
4192
+ if (namespaces) {
4193
+ exports.storage.setItem('debug', namespaces);
4194
+ } else {
4195
+ exports.storage.removeItem('debug');
4196
+ }
4197
+ } catch (error) {
4198
+ // Swallow
4199
+ // XXX (@Qix-) should we be logging these?
4200
+ }
4201
+ }
4202
+
4203
+ /**
4204
+ * Load `namespaces`.
4205
+ *
4206
+ * @return {String} returns the previously persisted debug modes
4207
+ * @api private
4208
+ */
4209
+ function load() {
4210
+ let r;
4211
+ try {
4212
+ r = exports.storage.getItem('debug');
4213
+ } catch (error) {
4214
+ // Swallow
4215
+ // XXX (@Qix-) should we be logging these?
4216
+ }
4217
+
4218
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
4219
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
4220
+ r = process.env.DEBUG;
4221
+ }
4222
+
4223
+ return r;
4224
+ }
4225
+
4226
+ /**
4227
+ * Localstorage attempts to return the localstorage.
4228
+ *
4229
+ * This is necessary because safari throws
4230
+ * when a user disables cookies/localstorage
4231
+ * and you attempt to access it.
4232
+ *
4233
+ * @return {LocalStorage}
4234
+ * @api private
4235
+ */
4236
+
4237
+ function localstorage() {
4238
+ try {
4239
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
4240
+ // The Browser also has localStorage in the global context.
4241
+ return localStorage;
4242
+ } catch (error) {
4243
+ // Swallow
4244
+ // XXX (@Qix-) should we be logging these?
4245
+ }
4246
+ }
4247
+
4248
+ module.exports = requireCommon()(exports);
4249
+
4250
+ const {formatters} = module.exports;
4251
+
4252
+ /**
4253
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
4254
+ */
4255
+
4256
+ formatters.j = function (v) {
4257
+ try {
4258
+ return JSON.stringify(v);
4259
+ } catch (error) {
4260
+ return '[UnexpectedJSONParseError]: ' + error.message;
4261
+ }
4262
+ };
4263
+ } (browser, browser.exports));
4264
+ return browser.exports;
4265
+ }
4266
+
4267
+ var node = {exports: {}};
4268
+
4269
+ var hasFlag;
4270
+ var hasRequiredHasFlag;
4271
+
4272
+ function requireHasFlag () {
4273
+ if (hasRequiredHasFlag) return hasFlag;
4274
+ hasRequiredHasFlag = 1;
4275
+
4276
+ hasFlag = (flag, argv = process.argv) => {
4277
+ const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
4278
+ const position = argv.indexOf(prefix + flag);
4279
+ const terminatorPosition = argv.indexOf('--');
4280
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
4281
+ };
4282
+ return hasFlag;
4283
+ }
4284
+
4285
+ var supportsColor_1;
4286
+ var hasRequiredSupportsColor;
4287
+
4288
+ function requireSupportsColor () {
4289
+ if (hasRequiredSupportsColor) return supportsColor_1;
4290
+ hasRequiredSupportsColor = 1;
4291
+ const os = require$$0__default$1["default"];
4292
+ const tty = require$$1__default["default"];
4293
+ const hasFlag = requireHasFlag();
4294
+
4295
+ const {env} = process;
4296
+
4297
+ let forceColor;
4298
+ if (hasFlag('no-color') ||
4299
+ hasFlag('no-colors') ||
4300
+ hasFlag('color=false') ||
4301
+ hasFlag('color=never')) {
4302
+ forceColor = 0;
4303
+ } else if (hasFlag('color') ||
4304
+ hasFlag('colors') ||
4305
+ hasFlag('color=true') ||
4306
+ hasFlag('color=always')) {
4307
+ forceColor = 1;
4308
+ }
4309
+
4310
+ if ('FORCE_COLOR' in env) {
4311
+ if (env.FORCE_COLOR === 'true') {
4312
+ forceColor = 1;
4313
+ } else if (env.FORCE_COLOR === 'false') {
4314
+ forceColor = 0;
4315
+ } else {
4316
+ forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
4317
+ }
4318
+ }
4319
+
4320
+ function translateLevel(level) {
4321
+ if (level === 0) {
4322
+ return false;
4323
+ }
4324
+
4325
+ return {
4326
+ level,
4327
+ hasBasic: true,
4328
+ has256: level >= 2,
4329
+ has16m: level >= 3
4330
+ };
4331
+ }
4332
+
4333
+ function supportsColor(haveStream, streamIsTTY) {
4334
+ if (forceColor === 0) {
4335
+ return 0;
4336
+ }
4337
+
4338
+ if (hasFlag('color=16m') ||
4339
+ hasFlag('color=full') ||
4340
+ hasFlag('color=truecolor')) {
4341
+ return 3;
4342
+ }
4343
+
4344
+ if (hasFlag('color=256')) {
4345
+ return 2;
4346
+ }
4347
+
4348
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
4349
+ return 0;
4350
+ }
4351
+
4352
+ const min = forceColor || 0;
4353
+
4354
+ if (env.TERM === 'dumb') {
4355
+ return min;
4356
+ }
4357
+
4358
+ if (process.platform === 'win32') {
4359
+ // Windows 10 build 10586 is the first Windows release that supports 256 colors.
4360
+ // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
4361
+ const osRelease = os.release().split('.');
4362
+ if (
4363
+ Number(osRelease[0]) >= 10 &&
4364
+ Number(osRelease[2]) >= 10586
4365
+ ) {
4366
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
4367
+ }
4368
+
4369
+ return 1;
4370
+ }
4371
+
4372
+ if ('CI' in env) {
4373
+ if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
4374
+ return 1;
4375
+ }
4376
+
4377
+ return min;
4378
+ }
4379
+
4380
+ if ('TEAMCITY_VERSION' in env) {
4381
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
4382
+ }
4383
+
4384
+ if (env.COLORTERM === 'truecolor') {
4385
+ return 3;
4386
+ }
4387
+
4388
+ if ('TERM_PROGRAM' in env) {
4389
+ const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
4390
+
4391
+ switch (env.TERM_PROGRAM) {
4392
+ case 'iTerm.app':
4393
+ return version >= 3 ? 3 : 2;
4394
+ case 'Apple_Terminal':
4395
+ return 2;
4396
+ // No default
4397
+ }
4398
+ }
4399
+
4400
+ if (/-256(color)?$/i.test(env.TERM)) {
4401
+ return 2;
4402
+ }
4403
+
4404
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
4405
+ return 1;
4406
+ }
4407
+
4408
+ if ('COLORTERM' in env) {
4409
+ return 1;
4410
+ }
4411
+
4412
+ return min;
4413
+ }
4414
+
4415
+ function getSupportLevel(stream) {
4416
+ const level = supportsColor(stream, stream && stream.isTTY);
4417
+ return translateLevel(level);
4418
+ }
4419
+
4420
+ supportsColor_1 = {
4421
+ supportsColor: getSupportLevel,
4422
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
4423
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
4424
+ };
4425
+ return supportsColor_1;
4426
+ }
4427
+
4428
+ /**
4429
+ * Module dependencies.
4430
+ */
4431
+
4432
+ var hasRequiredNode;
4433
+
4434
+ function requireNode () {
4435
+ if (hasRequiredNode) return node.exports;
4436
+ hasRequiredNode = 1;
4437
+ (function (module, exports) {
4438
+ const tty = require$$1__default["default"];
4439
+ const util = require$$0__default["default"];
4440
+
4441
+ /**
4442
+ * This is the Node.js implementation of `debug()`.
4443
+ */
4444
+
4445
+ exports.init = init;
4446
+ exports.log = log;
4447
+ exports.formatArgs = formatArgs;
4448
+ exports.save = save;
4449
+ exports.load = load;
4450
+ exports.useColors = useColors;
4451
+ exports.destroy = util.deprecate(
4452
+ () => {},
4453
+ 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
4454
+ );
4455
+
4456
+ /**
4457
+ * Colors.
4458
+ */
4459
+
4460
+ exports.colors = [6, 2, 3, 4, 5, 1];
4461
+
4462
+ try {
4463
+ // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
4464
+ // eslint-disable-next-line import/no-extraneous-dependencies
4465
+ const supportsColor = requireSupportsColor();
4466
+
4467
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
4468
+ exports.colors = [
4469
+ 20,
4470
+ 21,
4471
+ 26,
4472
+ 27,
4473
+ 32,
4474
+ 33,
4475
+ 38,
4476
+ 39,
4477
+ 40,
4478
+ 41,
4479
+ 42,
4480
+ 43,
4481
+ 44,
4482
+ 45,
4483
+ 56,
4484
+ 57,
4485
+ 62,
4486
+ 63,
4487
+ 68,
4488
+ 69,
4489
+ 74,
4490
+ 75,
4491
+ 76,
4492
+ 77,
4493
+ 78,
4494
+ 79,
4495
+ 80,
4496
+ 81,
4497
+ 92,
4498
+ 93,
4499
+ 98,
4500
+ 99,
4501
+ 112,
4502
+ 113,
4503
+ 128,
4504
+ 129,
4505
+ 134,
4506
+ 135,
4507
+ 148,
4508
+ 149,
4509
+ 160,
4510
+ 161,
4511
+ 162,
4512
+ 163,
4513
+ 164,
4514
+ 165,
4515
+ 166,
4516
+ 167,
4517
+ 168,
4518
+ 169,
4519
+ 170,
4520
+ 171,
4521
+ 172,
4522
+ 173,
4523
+ 178,
4524
+ 179,
4525
+ 184,
4526
+ 185,
4527
+ 196,
4528
+ 197,
4529
+ 198,
4530
+ 199,
4531
+ 200,
4532
+ 201,
4533
+ 202,
4534
+ 203,
4535
+ 204,
4536
+ 205,
4537
+ 206,
4538
+ 207,
4539
+ 208,
4540
+ 209,
4541
+ 214,
4542
+ 215,
4543
+ 220,
4544
+ 221
4545
+ ];
4546
+ }
4547
+ } catch (error) {
4548
+ // Swallow - we only care if `supports-color` is available; it doesn't have to be.
4549
+ }
4550
+
4551
+ /**
4552
+ * Build up the default `inspectOpts` object from the environment variables.
4553
+ *
4554
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
4555
+ */
4556
+
4557
+ exports.inspectOpts = Object.keys(process.env).filter(key => {
4558
+ return /^debug_/i.test(key);
4559
+ }).reduce((obj, key) => {
4560
+ // Camel-case
4561
+ const prop = key
4562
+ .substring(6)
4563
+ .toLowerCase()
4564
+ .replace(/_([a-z])/g, (_, k) => {
4565
+ return k.toUpperCase();
4566
+ });
4567
+
4568
+ // Coerce string value into JS value
4569
+ let val = process.env[key];
4570
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
4571
+ val = true;
4572
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
4573
+ val = false;
4574
+ } else if (val === 'null') {
4575
+ val = null;
4576
+ } else {
4577
+ val = Number(val);
4578
+ }
4579
+
4580
+ obj[prop] = val;
4581
+ return obj;
4582
+ }, {});
4583
+
4584
+ /**
4585
+ * Is stdout a TTY? Colored output is enabled when `true`.
4586
+ */
4587
+
4588
+ function useColors() {
4589
+ return 'colors' in exports.inspectOpts ?
4590
+ Boolean(exports.inspectOpts.colors) :
4591
+ tty.isatty(process.stderr.fd);
4592
+ }
4593
+
4594
+ /**
4595
+ * Adds ANSI color escape codes if enabled.
4596
+ *
4597
+ * @api public
4598
+ */
4599
+
4600
+ function formatArgs(args) {
4601
+ const {namespace: name, useColors} = this;
4602
+
4603
+ if (useColors) {
4604
+ const c = this.color;
4605
+ const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
4606
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
4607
+
4608
+ args[0] = prefix + args[0].split('\n').join('\n' + prefix);
4609
+ args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
4610
+ } else {
4611
+ args[0] = getDate() + name + ' ' + args[0];
4612
+ }
4613
+ }
4614
+
4615
+ function getDate() {
4616
+ if (exports.inspectOpts.hideDate) {
4617
+ return '';
4618
+ }
4619
+ return new Date().toISOString() + ' ';
4620
+ }
4621
+
4622
+ /**
4623
+ * Invokes `util.format()` with the specified arguments and writes to stderr.
4624
+ */
4625
+
4626
+ function log(...args) {
4627
+ return process.stderr.write(util.format(...args) + '\n');
4628
+ }
4629
+
4630
+ /**
4631
+ * Save `namespaces`.
4632
+ *
4633
+ * @param {String} namespaces
4634
+ * @api private
4635
+ */
4636
+ function save(namespaces) {
4637
+ if (namespaces) {
4638
+ process.env.DEBUG = namespaces;
4639
+ } else {
4640
+ // If you set a process.env field to null or undefined, it gets cast to the
4641
+ // string 'null' or 'undefined'. Just delete instead.
4642
+ delete process.env.DEBUG;
4643
+ }
4644
+ }
4645
+
4646
+ /**
4647
+ * Load `namespaces`.
4648
+ *
4649
+ * @return {String} returns the previously persisted debug modes
4650
+ * @api private
4651
+ */
4652
+
4653
+ function load() {
4654
+ return process.env.DEBUG;
4655
+ }
4656
+
4657
+ /**
4658
+ * Init logic for `debug` instances.
4659
+ *
4660
+ * Create a new `inspectOpts` object in case `useColors` is set
4661
+ * differently for a particular `debug` instance.
4662
+ */
4663
+
4664
+ function init(debug) {
4665
+ debug.inspectOpts = {};
4666
+
4667
+ const keys = Object.keys(exports.inspectOpts);
4668
+ for (let i = 0; i < keys.length; i++) {
4669
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
4670
+ }
4671
+ }
4672
+
4673
+ module.exports = requireCommon()(exports);
4674
+
4675
+ const {formatters} = module.exports;
4676
+
4677
+ /**
4678
+ * Map %o to `util.inspect()`, all on a single line.
4679
+ */
4680
+
4681
+ formatters.o = function (v) {
4682
+ this.inspectOpts.colors = this.useColors;
4683
+ return util.inspect(v, this.inspectOpts)
4684
+ .split('\n')
4685
+ .map(str => str.trim())
4686
+ .join(' ');
4687
+ };
4688
+
4689
+ /**
4690
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
4691
+ */
4692
+
4693
+ formatters.O = function (v) {
4694
+ this.inspectOpts.colors = this.useColors;
4695
+ return util.inspect(v, this.inspectOpts);
4696
+ };
4697
+ } (node, node.exports));
4698
+ return node.exports;
4699
+ }
4700
+
4701
+ /**
4702
+ * Detect Electron renderer / nwjs process, which is node, but we should
4703
+ * treat as a browser.
4704
+ */
4705
+
4706
+ (function (module) {
4707
+ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
4708
+ module.exports = requireBrowser();
4709
+ } else {
4710
+ module.exports = requireNode();
4711
+ }
4712
+ } (src));
4713
+
4714
+ var compat = {exports: {}};
4715
+
4716
+ /*!
4717
+ * depd
4718
+ * Copyright(c) 2014 Douglas Christopher Wilson
4719
+ * MIT Licensed
4720
+ */
4721
+
4722
+ var callsiteTostring;
4723
+ var hasRequiredCallsiteTostring;
4724
+
4725
+ function requireCallsiteTostring () {
4726
+ if (hasRequiredCallsiteTostring) return callsiteTostring;
4727
+ hasRequiredCallsiteTostring = 1;
4728
+
4729
+ /**
4730
+ * Module exports.
4731
+ */
4732
+
4733
+ callsiteTostring = callSiteToString;
4734
+
4735
+ /**
4736
+ * Format a CallSite file location to a string.
4737
+ */
4738
+
4739
+ function callSiteFileLocation (callSite) {
4740
+ var fileName;
4741
+ var fileLocation = '';
4742
+
4743
+ if (callSite.isNative()) {
4744
+ fileLocation = 'native';
4745
+ } else if (callSite.isEval()) {
4746
+ fileName = callSite.getScriptNameOrSourceURL();
4747
+ if (!fileName) {
4748
+ fileLocation = callSite.getEvalOrigin();
4749
+ }
4750
+ } else {
4751
+ fileName = callSite.getFileName();
4752
+ }
4753
+
4754
+ if (fileName) {
4755
+ fileLocation += fileName;
4756
+
4757
+ var lineNumber = callSite.getLineNumber();
4758
+ if (lineNumber != null) {
4759
+ fileLocation += ':' + lineNumber;
4760
+
4761
+ var columnNumber = callSite.getColumnNumber();
4762
+ if (columnNumber) {
4763
+ fileLocation += ':' + columnNumber;
4764
+ }
4765
+ }
4766
+ }
4767
+
4768
+ return fileLocation || 'unknown source'
4769
+ }
4770
+
4771
+ /**
4772
+ * Format a CallSite to a string.
4773
+ */
4774
+
4775
+ function callSiteToString (callSite) {
4776
+ var addSuffix = true;
4777
+ var fileLocation = callSiteFileLocation(callSite);
4778
+ var functionName = callSite.getFunctionName();
4779
+ var isConstructor = callSite.isConstructor();
4780
+ var isMethodCall = !(callSite.isToplevel() || isConstructor);
4781
+ var line = '';
4782
+
4783
+ if (isMethodCall) {
4784
+ var methodName = callSite.getMethodName();
4785
+ var typeName = getConstructorName(callSite);
4786
+
4787
+ if (functionName) {
4788
+ if (typeName && functionName.indexOf(typeName) !== 0) {
4789
+ line += typeName + '.';
4790
+ }
4791
+
4792
+ line += functionName;
4793
+
4794
+ if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) {
4795
+ line += ' [as ' + methodName + ']';
4796
+ }
4797
+ } else {
4798
+ line += typeName + '.' + (methodName || '<anonymous>');
4799
+ }
4800
+ } else if (isConstructor) {
4801
+ line += 'new ' + (functionName || '<anonymous>');
4802
+ } else if (functionName) {
4803
+ line += functionName;
4804
+ } else {
4805
+ addSuffix = false;
4806
+ line += fileLocation;
4807
+ }
4808
+
4809
+ if (addSuffix) {
4810
+ line += ' (' + fileLocation + ')';
4811
+ }
4812
+
4813
+ return line
4814
+ }
4815
+
4816
+ /**
4817
+ * Get constructor name of reviver.
4818
+ */
4819
+
4820
+ function getConstructorName (obj) {
4821
+ var receiver = obj.receiver;
4822
+ return (receiver.constructor && receiver.constructor.name) || null
4823
+ }
4824
+ return callsiteTostring;
4825
+ }
4826
+
4827
+ /*!
4828
+ * depd
4829
+ * Copyright(c) 2015 Douglas Christopher Wilson
4830
+ * MIT Licensed
4831
+ */
4832
+
4833
+ var eventListenerCount_1;
4834
+ var hasRequiredEventListenerCount;
4835
+
4836
+ function requireEventListenerCount () {
4837
+ if (hasRequiredEventListenerCount) return eventListenerCount_1;
4838
+ hasRequiredEventListenerCount = 1;
4839
+
4840
+ /**
4841
+ * Module exports.
4842
+ * @public
4843
+ */
4844
+
4845
+ eventListenerCount_1 = eventListenerCount;
4846
+
4847
+ /**
4848
+ * Get the count of listeners on an event emitter of a specific type.
4849
+ */
4850
+
4851
+ function eventListenerCount (emitter, type) {
4852
+ return emitter.listeners(type).length
4853
+ }
4854
+ return eventListenerCount_1;
4855
+ }
4856
+
4857
+ /*!
4858
+ * depd
4859
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
4860
+ * MIT Licensed
4861
+ */
4862
+
4863
+ (function (module) {
4864
+
4865
+ /**
4866
+ * Module dependencies.
4867
+ * @private
4868
+ */
4869
+
4870
+ var EventEmitter = require$$0__default$2["default"].EventEmitter;
4871
+
4872
+ /**
4873
+ * Module exports.
4874
+ * @public
4875
+ */
4876
+
4877
+ lazyProperty(module.exports, 'callSiteToString', function callSiteToString () {
4878
+ var limit = Error.stackTraceLimit;
4879
+ var obj = {};
4880
+ var prep = Error.prepareStackTrace;
4881
+
4882
+ function prepareObjectStackTrace (obj, stack) {
4883
+ return stack
4884
+ }
4885
+
4886
+ Error.prepareStackTrace = prepareObjectStackTrace;
4887
+ Error.stackTraceLimit = 2;
4888
+
4889
+ // capture the stack
4890
+ Error.captureStackTrace(obj);
4891
+
4892
+ // slice the stack
4893
+ var stack = obj.stack.slice();
4894
+
4895
+ Error.prepareStackTrace = prep;
4896
+ Error.stackTraceLimit = limit;
4897
+
4898
+ return stack[0].toString ? toString : requireCallsiteTostring()
4899
+ });
4900
+
4901
+ lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () {
4902
+ return EventEmitter.listenerCount || requireEventListenerCount()
4903
+ });
4904
+
4905
+ /**
4906
+ * Define a lazy property.
4907
+ */
4908
+
4909
+ function lazyProperty (obj, prop, getter) {
4910
+ function get () {
4911
+ var val = getter();
4912
+
4913
+ Object.defineProperty(obj, prop, {
4914
+ configurable: true,
4915
+ enumerable: true,
4916
+ value: val
4917
+ });
4918
+
4919
+ return val
4920
+ }
4921
+
4922
+ Object.defineProperty(obj, prop, {
4923
+ configurable: true,
4924
+ enumerable: true,
4925
+ get: get
4926
+ });
4927
+ }
4928
+
4929
+ /**
4930
+ * Call toString() on the obj
4931
+ */
4932
+
4933
+ function toString (obj) {
4934
+ return obj.toString()
4935
+ }
4936
+ } (compat));
4937
+
4938
+ /*!
4939
+ * depd
4940
+ * Copyright(c) 2014-2017 Douglas Christopher Wilson
4941
+ * MIT Licensed
4942
+ */
4943
+
4944
+ /**
4945
+ * Module dependencies.
4946
+ */
4947
+
4948
+ var callSiteToString = compat.exports.callSiteToString;
4949
+ var eventListenerCount = compat.exports.eventListenerCount;
4950
+ var relative = require$$1__default$1["default"].relative;
4951
+
4952
+ /**
4953
+ * Module exports.
4954
+ */
4955
+
4956
+ var depd_1 = depd;
4957
+
4958
+ /**
4959
+ * Get the path to base files on.
4960
+ */
4961
+
4962
+ var basePath = process.cwd();
4963
+
4964
+ /**
4965
+ * Determine if namespace is contained in the string.
4966
+ */
4967
+
4968
+ function containsNamespace (str, namespace) {
4969
+ var vals = str.split(/[ ,]+/);
4970
+ var ns = String(namespace).toLowerCase();
4971
+
4972
+ for (var i = 0; i < vals.length; i++) {
4973
+ var val = vals[i];
4974
+
4975
+ // namespace contained
4976
+ if (val && (val === '*' || val.toLowerCase() === ns)) {
4977
+ return true
4978
+ }
4979
+ }
4980
+
4981
+ return false
4982
+ }
4983
+
4984
+ /**
4985
+ * Convert a data descriptor to accessor descriptor.
4986
+ */
4987
+
4988
+ function convertDataDescriptorToAccessor (obj, prop, message) {
4989
+ var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
4990
+ var value = descriptor.value;
4991
+
4992
+ descriptor.get = function getter () { return value };
4993
+
4994
+ if (descriptor.writable) {
4995
+ descriptor.set = function setter (val) { return (value = val) };
4996
+ }
4997
+
4998
+ delete descriptor.value;
4999
+ delete descriptor.writable;
5000
+
5001
+ Object.defineProperty(obj, prop, descriptor);
5002
+
5003
+ return descriptor
5004
+ }
5005
+
5006
+ /**
5007
+ * Create arguments string to keep arity.
5008
+ */
5009
+
5010
+ function createArgumentsString (arity) {
5011
+ var str = '';
5012
+
5013
+ for (var i = 0; i < arity; i++) {
5014
+ str += ', arg' + i;
5015
+ }
5016
+
5017
+ return str.substr(2)
5018
+ }
5019
+
5020
+ /**
5021
+ * Create stack string from stack.
5022
+ */
5023
+
5024
+ function createStackString (stack) {
5025
+ var str = this.name + ': ' + this.namespace;
5026
+
5027
+ if (this.message) {
5028
+ str += ' deprecated ' + this.message;
5029
+ }
5030
+
5031
+ for (var i = 0; i < stack.length; i++) {
5032
+ str += '\n at ' + callSiteToString(stack[i]);
5033
+ }
5034
+
5035
+ return str
5036
+ }
5037
+
5038
+ /**
5039
+ * Create deprecate for namespace in caller.
5040
+ */
5041
+
5042
+ function depd (namespace) {
5043
+ if (!namespace) {
5044
+ throw new TypeError('argument namespace is required')
5045
+ }
5046
+
5047
+ var stack = getStack();
5048
+ var site = callSiteLocation(stack[1]);
5049
+ var file = site[0];
5050
+
5051
+ function deprecate (message) {
5052
+ // call to self as log
5053
+ log.call(deprecate, message);
5054
+ }
5055
+
5056
+ deprecate._file = file;
5057
+ deprecate._ignored = isignored(namespace);
5058
+ deprecate._namespace = namespace;
5059
+ deprecate._traced = istraced(namespace);
5060
+ deprecate._warned = Object.create(null);
5061
+
5062
+ deprecate.function = wrapfunction;
5063
+ deprecate.property = wrapproperty;
5064
+
5065
+ return deprecate
5066
+ }
5067
+
5068
+ /**
5069
+ * Determine if namespace is ignored.
5070
+ */
5071
+
5072
+ function isignored (namespace) {
5073
+ /* istanbul ignore next: tested in a child processs */
5074
+ if (process.noDeprecation) {
5075
+ // --no-deprecation support
5076
+ return true
5077
+ }
5078
+
5079
+ var str = process.env.NO_DEPRECATION || '';
5080
+
5081
+ // namespace ignored
5082
+ return containsNamespace(str, namespace)
5083
+ }
5084
+
5085
+ /**
5086
+ * Determine if namespace is traced.
5087
+ */
5088
+
5089
+ function istraced (namespace) {
5090
+ /* istanbul ignore next: tested in a child processs */
5091
+ if (process.traceDeprecation) {
5092
+ // --trace-deprecation support
5093
+ return true
5094
+ }
5095
+
5096
+ var str = process.env.TRACE_DEPRECATION || '';
5097
+
5098
+ // namespace traced
5099
+ return containsNamespace(str, namespace)
5100
+ }
5101
+
5102
+ /**
5103
+ * Display deprecation message.
5104
+ */
5105
+
5106
+ function log (message, site) {
5107
+ var haslisteners = eventListenerCount(process, 'deprecation') !== 0;
5108
+
5109
+ // abort early if no destination
5110
+ if (!haslisteners && this._ignored) {
5111
+ return
5112
+ }
5113
+
5114
+ var caller;
5115
+ var callFile;
5116
+ var callSite;
5117
+ var depSite;
5118
+ var i = 0;
5119
+ var seen = false;
5120
+ var stack = getStack();
5121
+ var file = this._file;
5122
+
5123
+ if (site) {
5124
+ // provided site
5125
+ depSite = site;
5126
+ callSite = callSiteLocation(stack[1]);
5127
+ callSite.name = depSite.name;
5128
+ file = callSite[0];
5129
+ } else {
5130
+ // get call site
5131
+ i = 2;
5132
+ depSite = callSiteLocation(stack[i]);
5133
+ callSite = depSite;
5134
+ }
5135
+
5136
+ // get caller of deprecated thing in relation to file
5137
+ for (; i < stack.length; i++) {
5138
+ caller = callSiteLocation(stack[i]);
5139
+ callFile = caller[0];
5140
+
5141
+ if (callFile === file) {
5142
+ seen = true;
5143
+ } else if (callFile === this._file) {
5144
+ file = this._file;
5145
+ } else if (seen) {
5146
+ break
5147
+ }
5148
+ }
5149
+
5150
+ var key = caller
5151
+ ? depSite.join(':') + '__' + caller.join(':')
5152
+ : undefined;
5153
+
5154
+ if (key !== undefined && key in this._warned) {
5155
+ // already warned
5156
+ return
5157
+ }
5158
+
5159
+ this._warned[key] = true;
5160
+
5161
+ // generate automatic message from call site
5162
+ var msg = message;
5163
+ if (!msg) {
5164
+ msg = callSite === depSite || !callSite.name
5165
+ ? defaultMessage(depSite)
5166
+ : defaultMessage(callSite);
5167
+ }
5168
+
5169
+ // emit deprecation if listeners exist
5170
+ if (haslisteners) {
5171
+ var err = DeprecationError(this._namespace, msg, stack.slice(i));
5172
+ process.emit('deprecation', err);
5173
+ return
5174
+ }
5175
+
5176
+ // format and write message
5177
+ var format = process.stderr.isTTY
5178
+ ? formatColor
5179
+ : formatPlain;
5180
+ var output = format.call(this, msg, caller, stack.slice(i));
5181
+ process.stderr.write(output + '\n', 'utf8');
5182
+ }
5183
+
5184
+ /**
5185
+ * Get call site location as array.
5186
+ */
5187
+
5188
+ function callSiteLocation (callSite) {
5189
+ var file = callSite.getFileName() || '<anonymous>';
5190
+ var line = callSite.getLineNumber();
5191
+ var colm = callSite.getColumnNumber();
5192
+
5193
+ if (callSite.isEval()) {
5194
+ file = callSite.getEvalOrigin() + ', ' + file;
5195
+ }
5196
+
5197
+ var site = [file, line, colm];
5198
+
5199
+ site.callSite = callSite;
5200
+ site.name = callSite.getFunctionName();
5201
+
5202
+ return site
5203
+ }
5204
+
5205
+ /**
5206
+ * Generate a default message from the site.
5207
+ */
5208
+
5209
+ function defaultMessage (site) {
5210
+ var callSite = site.callSite;
5211
+ var funcName = site.name;
5212
+
5213
+ // make useful anonymous name
5214
+ if (!funcName) {
5215
+ funcName = '<anonymous@' + formatLocation(site) + '>';
5216
+ }
5217
+
5218
+ var context = callSite.getThis();
5219
+ var typeName = context && callSite.getTypeName();
5220
+
5221
+ // ignore useless type name
5222
+ if (typeName === 'Object') {
5223
+ typeName = undefined;
5224
+ }
5225
+
5226
+ // make useful type name
5227
+ if (typeName === 'Function') {
5228
+ typeName = context.name || typeName;
5229
+ }
5230
+
5231
+ return typeName && callSite.getMethodName()
5232
+ ? typeName + '.' + funcName
5233
+ : funcName
5234
+ }
5235
+
5236
+ /**
5237
+ * Format deprecation message without color.
5238
+ */
5239
+
5240
+ function formatPlain (msg, caller, stack) {
5241
+ var timestamp = new Date().toUTCString();
5242
+
5243
+ var formatted = timestamp +
5244
+ ' ' + this._namespace +
5245
+ ' deprecated ' + msg;
5246
+
5247
+ // add stack trace
5248
+ if (this._traced) {
5249
+ for (var i = 0; i < stack.length; i++) {
5250
+ formatted += '\n at ' + callSiteToString(stack[i]);
5251
+ }
5252
+
5253
+ return formatted
5254
+ }
5255
+
5256
+ if (caller) {
5257
+ formatted += ' at ' + formatLocation(caller);
5258
+ }
5259
+
5260
+ return formatted
5261
+ }
5262
+
5263
+ /**
5264
+ * Format deprecation message with color.
5265
+ */
5266
+
5267
+ function formatColor (msg, caller, stack) {
5268
+ var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan
5269
+ ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow
5270
+ ' \x1b[0m' + msg + '\x1b[39m'; // reset
5271
+
5272
+ // add stack trace
5273
+ if (this._traced) {
5274
+ for (var i = 0; i < stack.length; i++) {
5275
+ formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m'; // cyan
5276
+ }
5277
+
5278
+ return formatted
5279
+ }
5280
+
5281
+ if (caller) {
5282
+ formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m'; // cyan
5283
+ }
5284
+
5285
+ return formatted
5286
+ }
5287
+
5288
+ /**
5289
+ * Format call site location.
5290
+ */
5291
+
5292
+ function formatLocation (callSite) {
5293
+ return relative(basePath, callSite[0]) +
5294
+ ':' + callSite[1] +
5295
+ ':' + callSite[2]
5296
+ }
5297
+
5298
+ /**
5299
+ * Get the stack as array of call sites.
5300
+ */
5301
+
5302
+ function getStack () {
5303
+ var limit = Error.stackTraceLimit;
5304
+ var obj = {};
5305
+ var prep = Error.prepareStackTrace;
5306
+
5307
+ Error.prepareStackTrace = prepareObjectStackTrace;
5308
+ Error.stackTraceLimit = Math.max(10, limit);
5309
+
5310
+ // capture the stack
5311
+ Error.captureStackTrace(obj);
5312
+
5313
+ // slice this function off the top
5314
+ var stack = obj.stack.slice(1);
5315
+
5316
+ Error.prepareStackTrace = prep;
5317
+ Error.stackTraceLimit = limit;
5318
+
5319
+ return stack
5320
+ }
5321
+
5322
+ /**
5323
+ * Capture call site stack from v8.
5324
+ */
5325
+
5326
+ function prepareObjectStackTrace (obj, stack) {
5327
+ return stack
5328
+ }
5329
+
5330
+ /**
5331
+ * Return a wrapped function in a deprecation message.
5332
+ */
5333
+
5334
+ function wrapfunction (fn, message) {
5335
+ if (typeof fn !== 'function') {
5336
+ throw new TypeError('argument fn must be a function')
5337
+ }
5338
+
5339
+ var args = createArgumentsString(fn.length);
5340
+ var stack = getStack();
5341
+ var site = callSiteLocation(stack[1]);
5342
+
5343
+ site.name = fn.name;
5344
+
5345
+ // eslint-disable-next-line no-eval
5346
+ var deprecatedfn = eval('(function (' + args + ') {\n' +
5347
+ '"use strict"\n' +
5348
+ 'log.call(deprecate, message, site)\n' +
5349
+ 'return fn.apply(this, arguments)\n' +
5350
+ '})');
5351
+
5352
+ return deprecatedfn
5353
+ }
5354
+
5355
+ /**
5356
+ * Wrap property in a deprecation message.
5357
+ */
5358
+
5359
+ function wrapproperty (obj, prop, message) {
5360
+ if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
5361
+ throw new TypeError('argument obj must be object')
5362
+ }
5363
+
5364
+ var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
5365
+
5366
+ if (!descriptor) {
5367
+ throw new TypeError('must call property on owner object')
5368
+ }
5369
+
5370
+ if (!descriptor.configurable) {
5371
+ throw new TypeError('property must be configurable')
5372
+ }
5373
+
5374
+ var deprecate = this;
5375
+ var stack = getStack();
5376
+ var site = callSiteLocation(stack[1]);
5377
+
5378
+ // set site name
5379
+ site.name = prop;
5380
+
5381
+ // convert data descriptor
5382
+ if ('value' in descriptor) {
5383
+ descriptor = convertDataDescriptorToAccessor(obj, prop);
5384
+ }
5385
+
5386
+ var get = descriptor.get;
5387
+ var set = descriptor.set;
5388
+
5389
+ // wrap getter
5390
+ if (typeof get === 'function') {
5391
+ descriptor.get = function getter () {
5392
+ log.call(deprecate, message, site);
5393
+ return get.apply(this, arguments)
5394
+ };
5395
+ }
5396
+
5397
+ // wrap setter
5398
+ if (typeof set === 'function') {
5399
+ descriptor.set = function setter () {
5400
+ log.call(deprecate, message, site);
5401
+ return set.apply(this, arguments)
5402
+ };
5403
+ }
5404
+
5405
+ Object.defineProperty(obj, prop, descriptor);
5406
+ }
5407
+
5408
+ /**
5409
+ * Create DeprecationError for deprecation
5410
+ */
5411
+
5412
+ function DeprecationError (namespace, message, stack) {
5413
+ var error = new Error();
5414
+ var stackString;
5415
+
5416
+ Object.defineProperty(error, 'constructor', {
5417
+ value: DeprecationError
5418
+ });
5419
+
5420
+ Object.defineProperty(error, 'message', {
5421
+ configurable: true,
5422
+ enumerable: false,
5423
+ value: message,
5424
+ writable: true
5425
+ });
5426
+
5427
+ Object.defineProperty(error, 'name', {
5428
+ enumerable: false,
5429
+ configurable: true,
5430
+ value: 'DeprecationError',
5431
+ writable: true
5432
+ });
5433
+
5434
+ Object.defineProperty(error, 'namespace', {
5435
+ configurable: true,
5436
+ enumerable: false,
5437
+ value: namespace,
5438
+ writable: true
5439
+ });
5440
+
5441
+ Object.defineProperty(error, 'stack', {
5442
+ configurable: true,
5443
+ enumerable: false,
5444
+ get: function () {
5445
+ if (stackString !== undefined) {
5446
+ return stackString
5447
+ }
3161
5448
 
5449
+ // prepare stack trace
5450
+ return (stackString = createStackString.call(this, stack))
5451
+ },
5452
+ set: function setter (val) {
5453
+ stackString = val;
5454
+ }
5455
+ });
3162
5456
 
3163
- static async load(connection, payer, program, programId, data) {
3164
- {
3165
- const balanceNeeded = await connection.getMinimumBalanceForRentExemption(data.length); // Fetch program account info to check if it has already been created
5457
+ return error
5458
+ }
3166
5459
 
3167
- const programInfo = await connection.getAccountInfo(program.publicKey, 'confirmed');
3168
- let transaction = null;
5460
+ var constants = {
5461
+ // agent
5462
+ CURRENT_ID: Symbol('agentkeepalive#currentId'),
5463
+ CREATE_ID: Symbol('agentkeepalive#createId'),
5464
+ INIT_SOCKET: Symbol('agentkeepalive#initSocket'),
5465
+ CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),
5466
+ // socket
5467
+ SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),
5468
+ SOCKET_NAME: Symbol('agentkeepalive#socketName'),
5469
+ SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),
5470
+ SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),
5471
+ };
3169
5472
 
3170
- if (programInfo !== null) {
3171
- if (programInfo.executable) {
3172
- console.error('Program load failed, account is already executable');
3173
- return false;
3174
- }
5473
+ const OriginalAgent = require$$0__default$3["default"].Agent;
5474
+ const ms = humanizeMs;
5475
+ const debug = src.exports('agentkeepalive');
5476
+ const deprecate = depd_1('agentkeepalive');
5477
+ const {
5478
+ INIT_SOCKET: INIT_SOCKET$1,
5479
+ CURRENT_ID,
5480
+ CREATE_ID,
5481
+ SOCKET_CREATED_TIME,
5482
+ SOCKET_NAME,
5483
+ SOCKET_REQUEST_COUNT,
5484
+ SOCKET_REQUEST_FINISHED_COUNT,
5485
+ } = constants;
5486
+
5487
+ // OriginalAgent come from
5488
+ // - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js
5489
+ // - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js
5490
+
5491
+ // node <= 10
5492
+ let defaultTimeoutListenerCount = 1;
5493
+ const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));
5494
+ if (majorVersion >= 11 && majorVersion <= 12) {
5495
+ defaultTimeoutListenerCount = 2;
5496
+ } else if (majorVersion >= 13) {
5497
+ defaultTimeoutListenerCount = 3;
5498
+ }
3175
5499
 
3176
- if (programInfo.data.length !== data.length) {
3177
- transaction = transaction || new Transaction();
3178
- transaction.add(SystemProgram.allocate({
3179
- accountPubkey: program.publicKey,
3180
- space: data.length
3181
- }));
3182
- }
5500
+ class Agent$1 extends OriginalAgent {
5501
+ constructor(options) {
5502
+ options = options || {};
5503
+ options.keepAlive = options.keepAlive !== false;
5504
+ // default is keep-alive and 4s free socket timeout
5505
+ // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83
5506
+ if (options.freeSocketTimeout === undefined) {
5507
+ options.freeSocketTimeout = 4000;
5508
+ }
5509
+ // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`
5510
+ if (options.keepAliveTimeout) {
5511
+ deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
5512
+ options.freeSocketTimeout = options.keepAliveTimeout;
5513
+ delete options.keepAliveTimeout;
5514
+ }
5515
+ // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`
5516
+ if (options.freeSocketKeepAliveTimeout) {
5517
+ deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
5518
+ options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;
5519
+ delete options.freeSocketKeepAliveTimeout;
5520
+ }
5521
+
5522
+ // Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
5523
+ // By default is double free socket timeout.
5524
+ if (options.timeout === undefined) {
5525
+ // make sure socket default inactivity timeout >= 8s
5526
+ options.timeout = Math.max(options.freeSocketTimeout * 2, 8000);
5527
+ }
5528
+
5529
+ // support humanize format
5530
+ options.timeout = ms(options.timeout);
5531
+ options.freeSocketTimeout = ms(options.freeSocketTimeout);
5532
+ options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;
5533
+
5534
+ super(options);
5535
+
5536
+ this[CURRENT_ID] = 0;
5537
+
5538
+ // create socket success counter
5539
+ this.createSocketCount = 0;
5540
+ this.createSocketCountLastCheck = 0;
5541
+
5542
+ this.createSocketErrorCount = 0;
5543
+ this.createSocketErrorCountLastCheck = 0;
5544
+
5545
+ this.closeSocketCount = 0;
5546
+ this.closeSocketCountLastCheck = 0;
5547
+
5548
+ // socket error event count
5549
+ this.errorSocketCount = 0;
5550
+ this.errorSocketCountLastCheck = 0;
5551
+
5552
+ // request finished counter
5553
+ this.requestCount = 0;
5554
+ this.requestCountLastCheck = 0;
5555
+
5556
+ // including free socket timeout counter
5557
+ this.timeoutSocketCount = 0;
5558
+ this.timeoutSocketCountLastCheck = 0;
5559
+
5560
+ this.on('free', socket => {
5561
+ // https://github.com/nodejs/node/pull/32000
5562
+ // Node.js native agent will check socket timeout eqs agent.options.timeout.
5563
+ // Use the ttl or freeSocketTimeout to overwrite.
5564
+ const timeout = this.calcSocketTimeout(socket);
5565
+ if (timeout > 0 && socket.timeout !== timeout) {
5566
+ socket.setTimeout(timeout);
5567
+ }
5568
+ });
5569
+ }
3183
5570
 
3184
- if (!programInfo.owner.equals(programId)) {
3185
- transaction = transaction || new Transaction();
3186
- transaction.add(SystemProgram.assign({
3187
- accountPubkey: program.publicKey,
3188
- programId
3189
- }));
3190
- }
5571
+ get freeSocketKeepAliveTimeout() {
5572
+ deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');
5573
+ return this.options.freeSocketTimeout;
5574
+ }
3191
5575
 
3192
- if (programInfo.lamports < balanceNeeded) {
3193
- transaction = transaction || new Transaction();
3194
- transaction.add(SystemProgram.transfer({
3195
- fromPubkey: payer.publicKey,
3196
- toPubkey: program.publicKey,
3197
- lamports: balanceNeeded - programInfo.lamports
3198
- }));
3199
- }
3200
- } else {
3201
- transaction = new Transaction().add(SystemProgram.createAccount({
3202
- fromPubkey: payer.publicKey,
3203
- newAccountPubkey: program.publicKey,
3204
- lamports: balanceNeeded > 0 ? balanceNeeded : 1,
3205
- space: data.length,
3206
- programId
3207
- }));
3208
- } // If the account is already created correctly, skip this step
3209
- // and proceed directly to loading instructions
5576
+ get timeout() {
5577
+ deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');
5578
+ return this.options.timeout;
5579
+ }
3210
5580
 
5581
+ get socketActiveTTL() {
5582
+ deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');
5583
+ return this.options.socketActiveTTL;
5584
+ }
3211
5585
 
3212
- if (transaction !== null) {
3213
- await sendAndConfirmTransaction(connection, transaction, [payer, program], {
3214
- commitment: 'confirmed'
3215
- });
5586
+ calcSocketTimeout(socket) {
5587
+ /**
5588
+ * return <= 0: should free socket
5589
+ * return > 0: should update socket timeout
5590
+ * return undefined: not find custom timeout
5591
+ */
5592
+ let freeSocketTimeout = this.options.freeSocketTimeout;
5593
+ const socketActiveTTL = this.options.socketActiveTTL;
5594
+ if (socketActiveTTL) {
5595
+ // check socketActiveTTL
5596
+ const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
5597
+ const diff = socketActiveTTL - aliveTime;
5598
+ if (diff <= 0) {
5599
+ return diff;
5600
+ }
5601
+ if (freeSocketTimeout && diff < freeSocketTimeout) {
5602
+ freeSocketTimeout = diff;
3216
5603
  }
3217
5604
  }
3218
- const dataLayout = BufferLayout__namespace.struct([BufferLayout__namespace.u32('instruction'), BufferLayout__namespace.u32('offset'), BufferLayout__namespace.u32('bytesLength'), BufferLayout__namespace.u32('bytesLengthPadding'), BufferLayout__namespace.seq(BufferLayout__namespace.u8('byte'), BufferLayout__namespace.offset(BufferLayout__namespace.u32(), -8), 'bytes')]);
3219
- const chunkSize = Loader.chunkSize;
3220
- let offset = 0;
3221
- let array = data;
3222
- let transactions = [];
5605
+ // set freeSocketTimeout
5606
+ if (freeSocketTimeout) {
5607
+ // set free keepalive timer
5608
+ // try to use socket custom freeSocketTimeout first, support headers['keep-alive']
5609
+ // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498
5610
+ const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
5611
+ return customFreeSocketTimeout || freeSocketTimeout;
5612
+ }
5613
+ }
3223
5614
 
3224
- while (array.length > 0) {
3225
- const bytes = array.slice(0, chunkSize);
3226
- const data = buffer.Buffer.alloc(chunkSize + 16);
3227
- dataLayout.encode({
3228
- instruction: 0,
3229
- // Load instruction
3230
- offset,
3231
- bytes: bytes,
3232
- bytesLength: 0,
3233
- bytesLengthPadding: 0
3234
- }, data);
3235
- const transaction = new Transaction().add({
3236
- keys: [{
3237
- pubkey: program.publicKey,
3238
- isSigner: true,
3239
- isWritable: true
3240
- }],
3241
- programId,
3242
- data
3243
- });
3244
- transactions.push(sendAndConfirmTransaction(connection, transaction, [payer, program], {
3245
- commitment: 'confirmed'
3246
- })); // Delay between sends in an attempt to reduce rate limit errors
5615
+ keepSocketAlive(socket) {
5616
+ const result = super.keepSocketAlive(socket);
5617
+ // should not keepAlive, do nothing
5618
+ if (!result) return result;
3247
5619
 
3248
- if (connection._rpcEndpoint.includes('solana.com')) {
3249
- const REQUESTS_PER_SECOND = 4;
3250
- await sleep(1000 / REQUESTS_PER_SECOND);
5620
+ const customTimeout = this.calcSocketTimeout(socket);
5621
+ if (typeof customTimeout === 'undefined') {
5622
+ return true;
5623
+ }
5624
+ if (customTimeout <= 0) {
5625
+ debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',
5626
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);
5627
+ return false;
5628
+ }
5629
+ if (socket.timeout !== customTimeout) {
5630
+ socket.setTimeout(customTimeout);
5631
+ }
5632
+ return true;
5633
+ }
5634
+
5635
+ // only call on addRequest
5636
+ reuseSocket(...args) {
5637
+ // reuseSocket(socket, req)
5638
+ super.reuseSocket(...args);
5639
+ const socket = args[0];
5640
+ const req = args[1];
5641
+ req.reusedSocket = true;
5642
+ const agentTimeout = this.options.timeout;
5643
+ if (getSocketTimeout(socket) !== agentTimeout) {
5644
+ // reset timeout before use
5645
+ socket.setTimeout(agentTimeout);
5646
+ debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);
5647
+ }
5648
+ socket[SOCKET_REQUEST_COUNT]++;
5649
+ debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',
5650
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
5651
+ getSocketTimeout(socket));
5652
+ }
5653
+
5654
+ [CREATE_ID]() {
5655
+ const id = this[CURRENT_ID]++;
5656
+ if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
5657
+ return id;
5658
+ }
5659
+
5660
+ [INIT_SOCKET$1](socket, options) {
5661
+ // bugfix here.
5662
+ // https on node 8, 10 won't set agent.options.timeout by default
5663
+ // TODO: need to fix on node itself
5664
+ if (options.timeout) {
5665
+ const timeout = getSocketTimeout(socket);
5666
+ if (!timeout) {
5667
+ socket.setTimeout(options.timeout);
3251
5668
  }
5669
+ }
3252
5670
 
3253
- offset += chunkSize;
3254
- array = array.slice(chunkSize);
5671
+ if (this.options.keepAlive) {
5672
+ // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
5673
+ // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html
5674
+ socket.setNoDelay(true);
3255
5675
  }
5676
+ this.createSocketCount++;
5677
+ if (this.options.socketActiveTTL) {
5678
+ socket[SOCKET_CREATED_TIME] = Date.now();
5679
+ }
5680
+ // don't show the hole '-----BEGIN CERTIFICATE----' key string
5681
+ socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];
5682
+ socket[SOCKET_REQUEST_COUNT] = 1;
5683
+ socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
5684
+ installListeners(this, socket, options);
5685
+ }
3256
5686
 
3257
- await Promise.all(transactions); // Finalize the account loaded with program data for execution
5687
+ createConnection(options, oncreate) {
5688
+ let called = false;
5689
+ const onNewCreate = (err, socket) => {
5690
+ if (called) return;
5691
+ called = true;
3258
5692
 
3259
- {
3260
- const dataLayout = BufferLayout__namespace.struct([BufferLayout__namespace.u32('instruction')]);
3261
- const data = buffer.Buffer.alloc(dataLayout.span);
3262
- dataLayout.encode({
3263
- instruction: 1 // Finalize instruction
5693
+ if (err) {
5694
+ this.createSocketErrorCount++;
5695
+ return oncreate(err);
5696
+ }
5697
+ this[INIT_SOCKET$1](socket, options);
5698
+ oncreate(err, socket);
5699
+ };
3264
5700
 
3265
- }, data);
3266
- const transaction = new Transaction().add({
3267
- keys: [{
3268
- pubkey: program.publicKey,
3269
- isSigner: true,
3270
- isWritable: true
3271
- }, {
3272
- pubkey: SYSVAR_RENT_PUBKEY,
3273
- isSigner: false,
3274
- isWritable: false
3275
- }],
3276
- programId,
3277
- data
3278
- });
3279
- await sendAndConfirmTransaction(connection, transaction, [payer, program], {
3280
- commitment: 'confirmed'
3281
- });
3282
- } // success
5701
+ const newSocket = super.createConnection(options, onNewCreate);
5702
+ if (newSocket) onNewCreate(null, newSocket);
5703
+ }
3283
5704
 
3284
- return true;
5705
+ get statusChanged() {
5706
+ const changed = this.createSocketCount !== this.createSocketCountLastCheck ||
5707
+ this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||
5708
+ this.closeSocketCount !== this.closeSocketCountLastCheck ||
5709
+ this.errorSocketCount !== this.errorSocketCountLastCheck ||
5710
+ this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||
5711
+ this.requestCount !== this.requestCountLastCheck;
5712
+ if (changed) {
5713
+ this.createSocketCountLastCheck = this.createSocketCount;
5714
+ this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
5715
+ this.closeSocketCountLastCheck = this.closeSocketCount;
5716
+ this.errorSocketCountLastCheck = this.errorSocketCount;
5717
+ this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
5718
+ this.requestCountLastCheck = this.requestCount;
5719
+ }
5720
+ return changed;
3285
5721
  }
3286
5722
 
5723
+ getCurrentStatus() {
5724
+ return {
5725
+ createSocketCount: this.createSocketCount,
5726
+ createSocketErrorCount: this.createSocketErrorCount,
5727
+ closeSocketCount: this.closeSocketCount,
5728
+ errorSocketCount: this.errorSocketCount,
5729
+ timeoutSocketCount: this.timeoutSocketCount,
5730
+ requestCount: this.requestCount,
5731
+ freeSockets: inspect(this.freeSockets),
5732
+ sockets: inspect(this.sockets),
5733
+ requests: inspect(this.requests),
5734
+ };
5735
+ }
3287
5736
  }
3288
- Loader.chunkSize = CHUNK_SIZE;
3289
5737
 
3290
- const BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111');
3291
- /**
3292
- * Factory class for transactions to interact with a program loader
3293
- */
5738
+ // node 8 don't has timeout attribute on socket
5739
+ // https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408
5740
+ function getSocketTimeout(socket) {
5741
+ return socket.timeout || socket._idleTimeout;
5742
+ }
3294
5743
 
3295
- class BpfLoader {
3296
- /**
3297
- * Minimum number of signatures required to load a program not including
3298
- * retries
3299
- *
3300
- * Can be used to calculate transaction fees
3301
- */
3302
- static getMinNumSignatures(dataLength) {
3303
- return Loader.getMinNumSignatures(dataLength);
5744
+ function installListeners(agent, socket, options) {
5745
+ debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));
5746
+
5747
+ // listener socket events: close, timeout, error, free
5748
+ function onFree() {
5749
+ // create and socket.emit('free') logic
5750
+ // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311
5751
+ // no req on the socket, it should be the new socket
5752
+ if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
5753
+
5754
+ socket[SOCKET_REQUEST_FINISHED_COUNT]++;
5755
+ agent.requestCount++;
5756
+ debug('%s(requests: %s, finished: %s) free',
5757
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
5758
+
5759
+ // should reuse on pedding requests?
5760
+ const name = agent.getName(options);
5761
+ if (socket.writable && agent.requests[name] && agent.requests[name].length) {
5762
+ // will be reuse on agent free listener
5763
+ socket[SOCKET_REQUEST_COUNT]++;
5764
+ debug('%s(requests: %s, finished: %s) will be reuse on agent free event',
5765
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
5766
+ }
5767
+ }
5768
+ socket.on('free', onFree);
5769
+
5770
+ function onClose(isError) {
5771
+ debug('%s(requests: %s, finished: %s) close, isError: %s',
5772
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);
5773
+ agent.closeSocketCount++;
5774
+ }
5775
+ socket.on('close', onClose);
5776
+
5777
+ // start socket timeout handler
5778
+ function onTimeout() {
5779
+ // onTimeout and emitRequestTimeout(_http_client.js)
5780
+ // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711
5781
+ const listenerCount = socket.listeners('timeout').length;
5782
+ // node <= 10, default listenerCount is 1, onTimeout
5783
+ // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout
5784
+ // node >= 13, default listenerCount is 3, onTimeout,
5785
+ // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)
5786
+ // and emitRequestTimeout
5787
+ const timeout = getSocketTimeout(socket);
5788
+ const req = socket._httpMessage;
5789
+ const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;
5790
+ debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',
5791
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
5792
+ timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);
5793
+ if (debug.enabled) {
5794
+ debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));
5795
+ }
5796
+ agent.timeoutSocketCount++;
5797
+ const name = agent.getName(options);
5798
+ if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
5799
+ // free socket timeout, destroy quietly
5800
+ socket.destroy();
5801
+ // Remove it from freeSockets list immediately to prevent new requests
5802
+ // from being sent through this socket.
5803
+ agent.removeSocket(socket, options);
5804
+ debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
5805
+ } else {
5806
+ // if there is no any request socket timeout handler,
5807
+ // agent need to handle socket timeout itself.
5808
+ //
5809
+ // custom request socket timeout handle logic must follow these rules:
5810
+ // 1. Destroy socket first
5811
+ // 2. Must emit socket 'agentRemove' event tell agent remove socket
5812
+ // from freeSockets list immediately.
5813
+ // Otherise you may be get 'socket hang up' error when reuse
5814
+ // free socket and timeout happen in the same time.
5815
+ if (reqTimeoutListenerCount === 0) {
5816
+ const error = new Error('Socket timeout');
5817
+ error.code = 'ERR_SOCKET_TIMEOUT';
5818
+ error.timeout = timeout;
5819
+ // must manually call socket.end() or socket.destroy() to end the connection.
5820
+ // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
5821
+ socket.destroy(error);
5822
+ agent.removeSocket(socket, options);
5823
+ debug('%s destroy with timeout error', socket[SOCKET_NAME]);
5824
+ }
5825
+ }
3304
5826
  }
3305
- /**
3306
- * Load a SBF program
3307
- *
3308
- * @param connection The connection to use
3309
- * @param payer Account that will pay program loading fees
3310
- * @param program Account to load the program into
3311
- * @param elf The entire ELF containing the SBF program
3312
- * @param loaderProgramId The program id of the BPF loader to use
3313
- * @return true if program was loaded successfully, false if program was already loaded
3314
- */
5827
+ socket.on('timeout', onTimeout);
5828
+
5829
+ function onError(err) {
5830
+ const listenerCount = socket.listeners('error').length;
5831
+ debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',
5832
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
5833
+ err, listenerCount);
5834
+ agent.errorSocketCount++;
5835
+ if (listenerCount === 1) {
5836
+ // if socket don't contain error event handler, don't catch it, emit it again
5837
+ debug('%s emit uncaught error event', socket[SOCKET_NAME]);
5838
+ socket.removeListener('error', onError);
5839
+ socket.emit('error', err);
5840
+ }
5841
+ }
5842
+ socket.on('error', onError);
5843
+
5844
+ function onRemove() {
5845
+ debug('%s(requests: %s, finished: %s) agentRemove',
5846
+ socket[SOCKET_NAME],
5847
+ socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
5848
+ // We need this function for cases like HTTP 'upgrade'
5849
+ // (defined by WebSockets) where we need to remove a socket from the
5850
+ // pool because it'll be locked up indefinitely
5851
+ socket.removeListener('close', onClose);
5852
+ socket.removeListener('error', onError);
5853
+ socket.removeListener('free', onFree);
5854
+ socket.removeListener('timeout', onTimeout);
5855
+ socket.removeListener('agentRemove', onRemove);
5856
+ }
5857
+ socket.on('agentRemove', onRemove);
5858
+ }
3315
5859
 
5860
+ var agent = Agent$1;
3316
5861
 
3317
- static load(connection, payer, program, elf, loaderProgramId) {
3318
- return Loader.load(connection, payer, program, loaderProgramId, elf);
5862
+ function inspect(obj) {
5863
+ const res = {};
5864
+ for (const key in obj) {
5865
+ res[key] = obj[key].length;
5866
+ }
5867
+ return res;
5868
+ }
5869
+
5870
+ const OriginalHttpsAgent = require$$0__default$4["default"].Agent;
5871
+ const HttpAgent = agent;
5872
+ const {
5873
+ INIT_SOCKET,
5874
+ CREATE_HTTPS_CONNECTION,
5875
+ } = constants;
5876
+
5877
+ class HttpsAgent extends HttpAgent {
5878
+ constructor(options) {
5879
+ super(options);
5880
+
5881
+ this.defaultPort = 443;
5882
+ this.protocol = 'https:';
5883
+ this.maxCachedSessions = this.options.maxCachedSessions;
5884
+ /* istanbul ignore next */
5885
+ if (this.maxCachedSessions === undefined) {
5886
+ this.maxCachedSessions = 100;
5887
+ }
5888
+
5889
+ this._sessionCache = {
5890
+ map: {},
5891
+ list: [],
5892
+ };
3319
5893
  }
3320
5894
 
5895
+ createConnection(options) {
5896
+ const socket = this[CREATE_HTTPS_CONNECTION](options);
5897
+ this[INIT_SOCKET](socket, options);
5898
+ return socket;
5899
+ }
3321
5900
  }
3322
5901
 
5902
+ // https://github.com/nodejs/node/blob/master/lib/https.js#L89
5903
+ HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
5904
+
5905
+ [
5906
+ 'getName',
5907
+ '_getSession',
5908
+ '_cacheSession',
5909
+ // https://github.com/nodejs/node/pull/4982
5910
+ '_evictSession',
5911
+ ].forEach(function(method) {
5912
+ /* istanbul ignore next */
5913
+ if (typeof OriginalHttpsAgent.prototype[method] === 'function') {
5914
+ HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];
5915
+ }
5916
+ });
5917
+
5918
+ var https_agent = HttpsAgent;
5919
+
5920
+ (function (module) {
5921
+
5922
+ module.exports = agent;
5923
+ module.exports.HttpsAgent = https_agent;
5924
+ module.exports.constants = constants;
5925
+ } (agentkeepalive));
5926
+
5927
+ var Agent = /*@__PURE__*/getDefaultExportFromCjs(agentkeepalive.exports);
5928
+
3323
5929
  var objToString = Object.prototype.toString;
3324
5930
  var objKeys = Object.keys || function(obj) {
3325
5931
  var keys = [];
@@ -3396,55 +6002,6 @@ var fastStableStringify = function(val) {
3396
6002
 
3397
6003
  var fastStableStringify$1 = fastStableStringify;
3398
6004
 
3399
- const DESTROY_TIMEOUT_MS = 5000;
3400
- class AgentManager {
3401
- static _newAgent(useHttps) {
3402
- const options = {
3403
- keepAlive: true,
3404
- maxSockets: 25
3405
- };
3406
-
3407
- if (useHttps) {
3408
- return new https__default["default"].Agent(options);
3409
- } else {
3410
- return new http__default["default"].Agent(options);
3411
- }
3412
- }
3413
-
3414
- constructor(useHttps) {
3415
- this._agent = void 0;
3416
- this._activeRequests = 0;
3417
- this._destroyTimeout = null;
3418
- this._useHttps = void 0;
3419
- this._useHttps = useHttps === true;
3420
- this._agent = AgentManager._newAgent(this._useHttps);
3421
- }
3422
-
3423
- requestStart() {
3424
- this._activeRequests++;
3425
-
3426
- if (this._destroyTimeout !== null) {
3427
- clearTimeout(this._destroyTimeout);
3428
- this._destroyTimeout = null;
3429
- }
3430
-
3431
- return this._agent;
3432
- }
3433
-
3434
- requestEnd() {
3435
- this._activeRequests--;
3436
-
3437
- if (this._activeRequests === 0 && this._destroyTimeout === null) {
3438
- this._destroyTimeout = setTimeout(() => {
3439
- this._agent.destroy();
3440
-
3441
- this._agent = AgentManager._newAgent(this._useHttps);
3442
- }, DESTROY_TIMEOUT_MS);
3443
- }
3444
- }
3445
-
3446
- }
3447
-
3448
6005
  const MINIMUM_SLOT_PER_EPOCH = 32; // Returns the number of trailing zeros in the binary representation of self.
3449
6006
 
3450
6007
  function trailingZeros(n) {
@@ -3473,7 +6030,7 @@ function nextPowerOfTwo(n) {
3473
6030
  /**
3474
6031
  * Epoch schedule
3475
6032
  * (see https://docs.solana.com/terminology#epoch)
3476
- * Can be retrieved with the {@link connection.getEpochSchedule} method
6033
+ * Can be retrieved with the {@link Connection.getEpochSchedule} method
3477
6034
  */
3478
6035
 
3479
6036
 
@@ -3748,13 +6305,10 @@ function extractCommitmentFromConfig(commitmentOrConfig) {
3748
6305
  };
3749
6306
  }
3750
6307
  /**
3751
- * A strategy for confirming durable nonce transactions.
6308
+ * @internal
3752
6309
  */
3753
6310
 
3754
6311
 
3755
- /**
3756
- * @internal
3757
- */
3758
6312
  function createRpcResult(result) {
3759
6313
  return superstruct.union([superstruct.type({
3760
6314
  jsonrpc: superstruct.literal('2.0'),
@@ -3946,14 +6500,34 @@ const BlockProductionResponseStruct = jsonRpcResultAndContext(superstruct.type({
3946
6500
  * A performance sample
3947
6501
  */
3948
6502
 
3949
- function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit) {
6503
+ function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) {
3950
6504
  const fetch = customFetch ? customFetch : fetchImpl;
3951
- let agentManager;
6505
+ let agent;
3952
6506
 
3953
6507
  {
3954
- agentManager = new AgentManager(url.startsWith('https:')
3955
- /* useHttps */
3956
- );
6508
+ if (httpAgent == null) {
6509
+ {
6510
+ agent = new Agent({
6511
+ // One second fewer than the Solana RPC's keepalive timeout.
6512
+ // Read more: https://github.com/solana-labs/solana/issues/27859#issuecomment-1340097889
6513
+ freeSocketTimeout: 19000,
6514
+ keepAlive: true,
6515
+ maxSockets: 25
6516
+ });
6517
+ }
6518
+ } else {
6519
+ if (httpAgent !== false) {
6520
+ const isHttps = url.startsWith('https:');
6521
+
6522
+ if (isHttps && !(httpAgent instanceof require$$0$4.Agent)) {
6523
+ throw new Error('The endpoint `' + url + '` can only be paired with an `https.Agent`. You have, instead, supplied an ' + '`http.Agent` through `httpAgent`.');
6524
+ } else if (!isHttps && httpAgent instanceof require$$0$4.Agent) {
6525
+ throw new Error('The endpoint `' + url + '` can only be paired with an `http.Agent`. You have, instead, supplied an ' + '`https.Agent` through `httpAgent`.');
6526
+ }
6527
+
6528
+ agent = httpAgent;
6529
+ }
6530
+ }
3957
6531
  }
3958
6532
 
3959
6533
  let fetchWithMiddleware;
@@ -3972,7 +6546,6 @@ function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disable
3972
6546
  }
3973
6547
 
3974
6548
  const clientBrowser = new RpcClient__default["default"](async (request, callback) => {
3975
- const agent = agentManager ? agentManager.requestStart() : undefined;
3976
6549
  const options = {
3977
6550
  method: 'POST',
3978
6551
  body: request,
@@ -4024,8 +6597,6 @@ function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disable
4024
6597
  }
4025
6598
  } catch (err) {
4026
6599
  if (err instanceof Error) callback(err);
4027
- } finally {
4028
- agentManager && agentManager.requestEnd();
4029
6600
  }
4030
6601
  }, {});
4031
6602
  return clientBrowser;
@@ -4863,6 +7434,7 @@ class Connection {
4863
7434
  let fetch;
4864
7435
  let fetchMiddleware;
4865
7436
  let disableRetryOnRateLimit;
7437
+ let httpAgent;
4866
7438
 
4867
7439
  if (commitmentOrConfig && typeof commitmentOrConfig === 'string') {
4868
7440
  this._commitment = commitmentOrConfig;
@@ -4874,11 +7446,12 @@ class Connection {
4874
7446
  fetch = commitmentOrConfig.fetch;
4875
7447
  fetchMiddleware = commitmentOrConfig.fetchMiddleware;
4876
7448
  disableRetryOnRateLimit = commitmentOrConfig.disableRetryOnRateLimit;
7449
+ httpAgent = commitmentOrConfig.httpAgent;
4877
7450
  }
4878
7451
 
4879
7452
  this._rpcEndpoint = assertEndpointUrl(endpoint);
4880
7453
  this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);
4881
- this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit);
7454
+ this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent);
4882
7455
  this._rpcRequest = createRpcRequest(this._rpcClient);
4883
7456
  this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);
4884
7457
  this._rpcWebSocket = new rpcWebsockets.Client(this._rpcWsEndpoint, {
@@ -5369,7 +7942,14 @@ class Connection {
5369
7942
  if (typeof strategy == 'string') {
5370
7943
  rawSignature = strategy;
5371
7944
  } else {
7945
+ var _config$abortSignal;
7946
+
5372
7947
  const config = strategy;
7948
+
7949
+ if ((_config$abortSignal = config.abortSignal) !== null && _config$abortSignal !== void 0 && _config$abortSignal.aborted) {
7950
+ return Promise.reject(config.abortSignal.reason);
7951
+ }
7952
+
5373
7953
  rawSignature = config.signature;
5374
7954
  }
5375
7955
 
@@ -5401,6 +7981,22 @@ class Connection {
5401
7981
  }
5402
7982
  }
5403
7983
 
7984
+ getCancellationPromise(signal) {
7985
+ return new Promise((_, reject) => {
7986
+ if (signal == null) {
7987
+ return;
7988
+ }
7989
+
7990
+ if (signal.aborted) {
7991
+ reject(signal.reason);
7992
+ } else {
7993
+ signal.addEventListener('abort', () => {
7994
+ reject(signal.reason);
7995
+ });
7996
+ }
7997
+ });
7998
+ }
7999
+
5404
8000
  getTransactionConfirmationPromise({
5405
8001
  commitment,
5406
8002
  signature
@@ -5519,6 +8115,7 @@ class Connection {
5519
8115
  async confirmTransactionUsingBlockHeightExceedanceStrategy({
5520
8116
  commitment,
5521
8117
  strategy: {
8118
+ abortSignal,
5522
8119
  lastValidBlockHeight,
5523
8120
  signature
5524
8121
  }
@@ -5557,10 +8154,11 @@ class Connection {
5557
8154
  commitment,
5558
8155
  signature
5559
8156
  });
8157
+ const cancellationPromise = this.getCancellationPromise(abortSignal);
5560
8158
  let result;
5561
8159
 
5562
8160
  try {
5563
- const outcome = await Promise.race([confirmationPromise, expiryPromise]);
8161
+ const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);
5564
8162
 
5565
8163
  if (outcome.__type === exports.TransactionStatus.PROCESSED) {
5566
8164
  result = outcome.response;
@@ -5578,6 +8176,7 @@ class Connection {
5578
8176
  async confirmTransactionUsingDurableNonceStrategy({
5579
8177
  commitment,
5580
8178
  strategy: {
8179
+ abortSignal,
5581
8180
  minContextSlot,
5582
8181
  nonceAccountPubkey,
5583
8182
  nonceValue,
@@ -5635,10 +8234,11 @@ class Connection {
5635
8234
  commitment,
5636
8235
  signature
5637
8236
  });
8237
+ const cancellationPromise = this.getCancellationPromise(abortSignal);
5638
8238
  let result;
5639
8239
 
5640
8240
  try {
5641
- const outcome = await Promise.race([confirmationPromise, expiryPromise]);
8241
+ const outcome = await Promise.race([cancellationPromise, confirmationPromise, expiryPromise]);
5642
8242
 
5643
8243
  if (outcome.__type === exports.TransactionStatus.PROCESSED) {
5644
8244
  result = outcome.response;