@solana/web3.js 1.70.1 → 1.70.2

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