@solana/web3.js 1.95.3 → 1.95.5

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
@@ -3408,163 +3408,171 @@ var agentkeepalive = {exports: {}};
3408
3408
  * Helpers.
3409
3409
  */
3410
3410
 
3411
- var s = 1000;
3412
- var m = s * 60;
3413
- var h = m * 60;
3414
- var d = h * 24;
3415
- var w = d * 7;
3416
- var y = d * 365.25;
3417
-
3418
- /**
3419
- * Parse or format the given `val`.
3420
- *
3421
- * Options:
3422
- *
3423
- * - `long` verbose formatting [false]
3424
- *
3425
- * @param {String|Number} val
3426
- * @param {Object} [options]
3427
- * @throws {Error} throw an error if val is not a non-empty string or a number
3428
- * @return {String|Number}
3429
- * @api public
3430
- */
3431
-
3432
- var ms$2 = function (val, options) {
3433
- options = options || {};
3434
- var type = typeof val;
3435
- if (type === 'string' && val.length > 0) {
3436
- return parse(val);
3437
- } else if (type === 'number' && isFinite(val)) {
3438
- return options.long ? fmtLong(val) : fmtShort(val);
3439
- }
3440
- throw new Error(
3441
- 'val is not a non-empty string or a valid number. val=' +
3442
- JSON.stringify(val)
3443
- );
3444
- };
3445
-
3446
- /**
3447
- * Parse the given `str` and return milliseconds.
3448
- *
3449
- * @param {String} str
3450
- * @return {Number}
3451
- * @api private
3452
- */
3453
-
3454
- function parse(str) {
3455
- str = String(str);
3456
- if (str.length > 100) {
3457
- return;
3458
- }
3459
- 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(
3460
- str
3461
- );
3462
- if (!match) {
3463
- return;
3464
- }
3465
- var n = parseFloat(match[1]);
3466
- var type = (match[2] || 'ms').toLowerCase();
3467
- switch (type) {
3468
- case 'years':
3469
- case 'year':
3470
- case 'yrs':
3471
- case 'yr':
3472
- case 'y':
3473
- return n * y;
3474
- case 'weeks':
3475
- case 'week':
3476
- case 'w':
3477
- return n * w;
3478
- case 'days':
3479
- case 'day':
3480
- case 'd':
3481
- return n * d;
3482
- case 'hours':
3483
- case 'hour':
3484
- case 'hrs':
3485
- case 'hr':
3486
- case 'h':
3487
- return n * h;
3488
- case 'minutes':
3489
- case 'minute':
3490
- case 'mins':
3491
- case 'min':
3492
- case 'm':
3493
- return n * m;
3494
- case 'seconds':
3495
- case 'second':
3496
- case 'secs':
3497
- case 'sec':
3498
- case 's':
3499
- return n * s;
3500
- case 'milliseconds':
3501
- case 'millisecond':
3502
- case 'msecs':
3503
- case 'msec':
3504
- case 'ms':
3505
- return n;
3506
- default:
3507
- return undefined;
3508
- }
3509
- }
3510
-
3511
- /**
3512
- * Short format for `ms`.
3513
- *
3514
- * @param {Number} ms
3515
- * @return {String}
3516
- * @api private
3517
- */
3411
+ var ms;
3412
+ var hasRequiredMs;
3413
+
3414
+ function requireMs () {
3415
+ if (hasRequiredMs) return ms;
3416
+ hasRequiredMs = 1;
3417
+ var s = 1000;
3418
+ var m = s * 60;
3419
+ var h = m * 60;
3420
+ var d = h * 24;
3421
+ var w = d * 7;
3422
+ var y = d * 365.25;
3423
+
3424
+ /**
3425
+ * Parse or format the given `val`.
3426
+ *
3427
+ * Options:
3428
+ *
3429
+ * - `long` verbose formatting [false]
3430
+ *
3431
+ * @param {String|Number} val
3432
+ * @param {Object} [options]
3433
+ * @throws {Error} throw an error if val is not a non-empty string or a number
3434
+ * @return {String|Number}
3435
+ * @api public
3436
+ */
3437
+
3438
+ ms = function (val, options) {
3439
+ options = options || {};
3440
+ var type = typeof val;
3441
+ if (type === 'string' && val.length > 0) {
3442
+ return parse(val);
3443
+ } else if (type === 'number' && isFinite(val)) {
3444
+ return options.long ? fmtLong(val) : fmtShort(val);
3445
+ }
3446
+ throw new Error(
3447
+ 'val is not a non-empty string or a valid number. val=' +
3448
+ JSON.stringify(val)
3449
+ );
3450
+ };
3518
3451
 
3519
- function fmtShort(ms) {
3520
- var msAbs = Math.abs(ms);
3521
- if (msAbs >= d) {
3522
- return Math.round(ms / d) + 'd';
3523
- }
3524
- if (msAbs >= h) {
3525
- return Math.round(ms / h) + 'h';
3526
- }
3527
- if (msAbs >= m) {
3528
- return Math.round(ms / m) + 'm';
3529
- }
3530
- if (msAbs >= s) {
3531
- return Math.round(ms / s) + 's';
3532
- }
3533
- return ms + 'ms';
3534
- }
3452
+ /**
3453
+ * Parse the given `str` and return milliseconds.
3454
+ *
3455
+ * @param {String} str
3456
+ * @return {Number}
3457
+ * @api private
3458
+ */
3459
+
3460
+ function parse(str) {
3461
+ str = String(str);
3462
+ if (str.length > 100) {
3463
+ return;
3464
+ }
3465
+ 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(
3466
+ str
3467
+ );
3468
+ if (!match) {
3469
+ return;
3470
+ }
3471
+ var n = parseFloat(match[1]);
3472
+ var type = (match[2] || 'ms').toLowerCase();
3473
+ switch (type) {
3474
+ case 'years':
3475
+ case 'year':
3476
+ case 'yrs':
3477
+ case 'yr':
3478
+ case 'y':
3479
+ return n * y;
3480
+ case 'weeks':
3481
+ case 'week':
3482
+ case 'w':
3483
+ return n * w;
3484
+ case 'days':
3485
+ case 'day':
3486
+ case 'd':
3487
+ return n * d;
3488
+ case 'hours':
3489
+ case 'hour':
3490
+ case 'hrs':
3491
+ case 'hr':
3492
+ case 'h':
3493
+ return n * h;
3494
+ case 'minutes':
3495
+ case 'minute':
3496
+ case 'mins':
3497
+ case 'min':
3498
+ case 'm':
3499
+ return n * m;
3500
+ case 'seconds':
3501
+ case 'second':
3502
+ case 'secs':
3503
+ case 'sec':
3504
+ case 's':
3505
+ return n * s;
3506
+ case 'milliseconds':
3507
+ case 'millisecond':
3508
+ case 'msecs':
3509
+ case 'msec':
3510
+ case 'ms':
3511
+ return n;
3512
+ default:
3513
+ return undefined;
3514
+ }
3515
+ }
3535
3516
 
3536
- /**
3537
- * Long format for `ms`.
3538
- *
3539
- * @param {Number} ms
3540
- * @return {String}
3541
- * @api private
3542
- */
3517
+ /**
3518
+ * Short format for `ms`.
3519
+ *
3520
+ * @param {Number} ms
3521
+ * @return {String}
3522
+ * @api private
3523
+ */
3524
+
3525
+ function fmtShort(ms) {
3526
+ var msAbs = Math.abs(ms);
3527
+ if (msAbs >= d) {
3528
+ return Math.round(ms / d) + 'd';
3529
+ }
3530
+ if (msAbs >= h) {
3531
+ return Math.round(ms / h) + 'h';
3532
+ }
3533
+ if (msAbs >= m) {
3534
+ return Math.round(ms / m) + 'm';
3535
+ }
3536
+ if (msAbs >= s) {
3537
+ return Math.round(ms / s) + 's';
3538
+ }
3539
+ return ms + 'ms';
3540
+ }
3543
3541
 
3544
- function fmtLong(ms) {
3545
- var msAbs = Math.abs(ms);
3546
- if (msAbs >= d) {
3547
- return plural(ms, msAbs, d, 'day');
3548
- }
3549
- if (msAbs >= h) {
3550
- return plural(ms, msAbs, h, 'hour');
3551
- }
3552
- if (msAbs >= m) {
3553
- return plural(ms, msAbs, m, 'minute');
3554
- }
3555
- if (msAbs >= s) {
3556
- return plural(ms, msAbs, s, 'second');
3557
- }
3558
- return ms + ' ms';
3559
- }
3542
+ /**
3543
+ * Long format for `ms`.
3544
+ *
3545
+ * @param {Number} ms
3546
+ * @return {String}
3547
+ * @api private
3548
+ */
3549
+
3550
+ function fmtLong(ms) {
3551
+ var msAbs = Math.abs(ms);
3552
+ if (msAbs >= d) {
3553
+ return plural(ms, msAbs, d, 'day');
3554
+ }
3555
+ if (msAbs >= h) {
3556
+ return plural(ms, msAbs, h, 'hour');
3557
+ }
3558
+ if (msAbs >= m) {
3559
+ return plural(ms, msAbs, m, 'minute');
3560
+ }
3561
+ if (msAbs >= s) {
3562
+ return plural(ms, msAbs, s, 'second');
3563
+ }
3564
+ return ms + ' ms';
3565
+ }
3560
3566
 
3561
- /**
3562
- * Pluralization helper.
3563
- */
3567
+ /**
3568
+ * Pluralization helper.
3569
+ */
3564
3570
 
3565
- function plural(ms, msAbs, n, name) {
3566
- var isPlural = msAbs >= n * 1.5;
3567
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
3571
+ function plural(ms, msAbs, n, name) {
3572
+ var isPlural = msAbs >= n * 1.5;
3573
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
3574
+ }
3575
+ return ms;
3568
3576
  }
3569
3577
 
3570
3578
  /*!
@@ -3573,569 +3581,622 @@ function plural(ms, msAbs, n, name) {
3573
3581
  * MIT Licensed
3574
3582
  */
3575
3583
 
3576
- /**
3577
- * Module dependencies.
3578
- */
3584
+ var humanizeMs;
3585
+ var hasRequiredHumanizeMs;
3579
3586
 
3580
- var util = require$$0__default.default;
3581
- var ms$1 = ms$2;
3587
+ function requireHumanizeMs () {
3588
+ if (hasRequiredHumanizeMs) return humanizeMs;
3589
+ hasRequiredHumanizeMs = 1;
3582
3590
 
3583
- var humanizeMs = function (t) {
3584
- if (typeof t === 'number') return t;
3585
- var r = ms$1(t);
3586
- if (r === undefined) {
3587
- var err = new Error(util.format('humanize-ms(%j) result undefined', t));
3588
- console.warn(err.stack);
3589
- }
3590
- return r;
3591
- };
3591
+ /**
3592
+ * Module dependencies.
3593
+ */
3592
3594
 
3593
- var constants = {
3594
- // agent
3595
- CURRENT_ID: Symbol('agentkeepalive#currentId'),
3596
- CREATE_ID: Symbol('agentkeepalive#createId'),
3597
- INIT_SOCKET: Symbol('agentkeepalive#initSocket'),
3598
- CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),
3599
- // socket
3600
- SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),
3601
- SOCKET_NAME: Symbol('agentkeepalive#socketName'),
3602
- SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),
3603
- SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),
3604
- };
3595
+ var util = require$$0__default.default;
3596
+ var ms = /*@__PURE__*/ requireMs();
3605
3597
 
3606
- const OriginalAgent = require$$0__default$1.default.Agent;
3607
- const ms = humanizeMs;
3608
- const debug = require$$0__default.default.debuglog('agentkeepalive');
3609
- const {
3610
- INIT_SOCKET: INIT_SOCKET$1,
3611
- CURRENT_ID,
3612
- CREATE_ID,
3613
- SOCKET_CREATED_TIME,
3614
- SOCKET_NAME,
3615
- SOCKET_REQUEST_COUNT,
3616
- SOCKET_REQUEST_FINISHED_COUNT,
3617
- } = constants;
3618
-
3619
- // OriginalAgent come from
3620
- // - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js
3621
- // - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js
3622
-
3623
- // node <= 10
3624
- let defaultTimeoutListenerCount = 1;
3625
- const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));
3626
- if (majorVersion >= 11 && majorVersion <= 12) {
3627
- defaultTimeoutListenerCount = 2;
3628
- } else if (majorVersion >= 13) {
3629
- defaultTimeoutListenerCount = 3;
3598
+ humanizeMs = function (t) {
3599
+ if (typeof t === 'number') return t;
3600
+ var r = ms(t);
3601
+ if (r === undefined) {
3602
+ var err = new Error(util.format('humanize-ms(%j) result undefined', t));
3603
+ console.warn(err.stack);
3604
+ }
3605
+ return r;
3606
+ };
3607
+ return humanizeMs;
3630
3608
  }
3631
3609
 
3632
- function deprecate(message) {
3633
- console.log('[agentkeepalive:deprecated] %s', message);
3610
+ var constants;
3611
+ var hasRequiredConstants;
3612
+
3613
+ function requireConstants () {
3614
+ if (hasRequiredConstants) return constants;
3615
+ hasRequiredConstants = 1;
3616
+
3617
+ constants = {
3618
+ // agent
3619
+ CURRENT_ID: Symbol('agentkeepalive#currentId'),
3620
+ CREATE_ID: Symbol('agentkeepalive#createId'),
3621
+ INIT_SOCKET: Symbol('agentkeepalive#initSocket'),
3622
+ CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),
3623
+ // socket
3624
+ SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),
3625
+ SOCKET_NAME: Symbol('agentkeepalive#socketName'),
3626
+ SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),
3627
+ SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),
3628
+ };
3629
+ return constants;
3634
3630
  }
3635
3631
 
3636
- class Agent extends OriginalAgent {
3637
- constructor(options) {
3638
- options = options || {};
3639
- options.keepAlive = options.keepAlive !== false;
3640
- // default is keep-alive and 4s free socket timeout
3641
- // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83
3642
- if (options.freeSocketTimeout === undefined) {
3643
- options.freeSocketTimeout = 4000;
3644
- }
3645
- // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`
3646
- if (options.keepAliveTimeout) {
3647
- deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
3648
- options.freeSocketTimeout = options.keepAliveTimeout;
3649
- delete options.keepAliveTimeout;
3650
- }
3651
- // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`
3652
- if (options.freeSocketKeepAliveTimeout) {
3653
- deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
3654
- options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;
3655
- delete options.freeSocketKeepAliveTimeout;
3656
- }
3657
-
3658
- // Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
3659
- // By default is double free socket timeout.
3660
- if (options.timeout === undefined) {
3661
- // make sure socket default inactivity timeout >= 8s
3662
- options.timeout = Math.max(options.freeSocketTimeout * 2, 8000);
3663
- }
3664
-
3665
- // support humanize format
3666
- options.timeout = ms(options.timeout);
3667
- options.freeSocketTimeout = ms(options.freeSocketTimeout);
3668
- options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;
3669
-
3670
- super(options);
3671
-
3672
- this[CURRENT_ID] = 0;
3673
-
3674
- // create socket success counter
3675
- this.createSocketCount = 0;
3676
- this.createSocketCountLastCheck = 0;
3677
-
3678
- this.createSocketErrorCount = 0;
3679
- this.createSocketErrorCountLastCheck = 0;
3680
-
3681
- this.closeSocketCount = 0;
3682
- this.closeSocketCountLastCheck = 0;
3683
-
3684
- // socket error event count
3685
- this.errorSocketCount = 0;
3686
- this.errorSocketCountLastCheck = 0;
3687
-
3688
- // request finished counter
3689
- this.requestCount = 0;
3690
- this.requestCountLastCheck = 0;
3691
-
3692
- // including free socket timeout counter
3693
- this.timeoutSocketCount = 0;
3694
- this.timeoutSocketCountLastCheck = 0;
3695
-
3696
- this.on('free', socket => {
3697
- // https://github.com/nodejs/node/pull/32000
3698
- // Node.js native agent will check socket timeout eqs agent.options.timeout.
3699
- // Use the ttl or freeSocketTimeout to overwrite.
3700
- const timeout = this.calcSocketTimeout(socket);
3701
- if (timeout > 0 && socket.timeout !== timeout) {
3702
- socket.setTimeout(timeout);
3703
- }
3704
- });
3705
- }
3706
-
3707
- get freeSocketKeepAliveTimeout() {
3708
- deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');
3709
- return this.options.freeSocketTimeout;
3710
- }
3711
-
3712
- get timeout() {
3713
- deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');
3714
- return this.options.timeout;
3715
- }
3716
-
3717
- get socketActiveTTL() {
3718
- deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');
3719
- return this.options.socketActiveTTL;
3720
- }
3721
-
3722
- calcSocketTimeout(socket) {
3723
- /**
3724
- * return <= 0: should free socket
3725
- * return > 0: should update socket timeout
3726
- * return undefined: not find custom timeout
3727
- */
3728
- let freeSocketTimeout = this.options.freeSocketTimeout;
3729
- const socketActiveTTL = this.options.socketActiveTTL;
3730
- if (socketActiveTTL) {
3731
- // check socketActiveTTL
3732
- const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
3733
- const diff = socketActiveTTL - aliveTime;
3734
- if (diff <= 0) {
3735
- return diff;
3736
- }
3737
- if (freeSocketTimeout && diff < freeSocketTimeout) {
3738
- freeSocketTimeout = diff;
3739
- }
3740
- }
3741
- // set freeSocketTimeout
3742
- if (freeSocketTimeout) {
3743
- // set free keepalive timer
3744
- // try to use socket custom freeSocketTimeout first, support headers['keep-alive']
3745
- // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498
3746
- const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
3747
- return customFreeSocketTimeout || freeSocketTimeout;
3748
- }
3749
- }
3750
-
3751
- keepSocketAlive(socket) {
3752
- const result = super.keepSocketAlive(socket);
3753
- // should not keepAlive, do nothing
3754
- if (!result) return result;
3755
-
3756
- const customTimeout = this.calcSocketTimeout(socket);
3757
- if (typeof customTimeout === 'undefined') {
3758
- return true;
3759
- }
3760
- if (customTimeout <= 0) {
3761
- debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',
3762
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);
3763
- return false;
3764
- }
3765
- if (socket.timeout !== customTimeout) {
3766
- socket.setTimeout(customTimeout);
3767
- }
3768
- return true;
3769
- }
3770
-
3771
- // only call on addRequest
3772
- reuseSocket(...args) {
3773
- // reuseSocket(socket, req)
3774
- super.reuseSocket(...args);
3775
- const socket = args[0];
3776
- const req = args[1];
3777
- req.reusedSocket = true;
3778
- const agentTimeout = this.options.timeout;
3779
- if (getSocketTimeout(socket) !== agentTimeout) {
3780
- // reset timeout before use
3781
- socket.setTimeout(agentTimeout);
3782
- debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);
3783
- }
3784
- socket[SOCKET_REQUEST_COUNT]++;
3785
- debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',
3786
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
3787
- getSocketTimeout(socket));
3788
- }
3789
-
3790
- [CREATE_ID]() {
3791
- const id = this[CURRENT_ID]++;
3792
- if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
3793
- return id;
3794
- }
3795
-
3796
- [INIT_SOCKET$1](socket, options) {
3797
- // bugfix here.
3798
- // https on node 8, 10 won't set agent.options.timeout by default
3799
- // TODO: need to fix on node itself
3800
- if (options.timeout) {
3801
- const timeout = getSocketTimeout(socket);
3802
- if (!timeout) {
3803
- socket.setTimeout(options.timeout);
3804
- }
3805
- }
3806
-
3807
- if (this.options.keepAlive) {
3808
- // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
3809
- // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html
3810
- socket.setNoDelay(true);
3811
- }
3812
- this.createSocketCount++;
3813
- if (this.options.socketActiveTTL) {
3814
- socket[SOCKET_CREATED_TIME] = Date.now();
3815
- }
3816
- // don't show the hole '-----BEGIN CERTIFICATE----' key string
3817
- socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];
3818
- socket[SOCKET_REQUEST_COUNT] = 1;
3819
- socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
3820
- installListeners(this, socket, options);
3821
- }
3822
-
3823
- createConnection(options, oncreate) {
3824
- let called = false;
3825
- const onNewCreate = (err, socket) => {
3826
- if (called) return;
3827
- called = true;
3632
+ var agent;
3633
+ var hasRequiredAgent;
3634
+
3635
+ function requireAgent () {
3636
+ if (hasRequiredAgent) return agent;
3637
+ hasRequiredAgent = 1;
3638
+
3639
+ const OriginalAgent = require$$0__default$1.default.Agent;
3640
+ const ms = /*@__PURE__*/ requireHumanizeMs();
3641
+ const debug = require$$0__default.default.debuglog('agentkeepalive');
3642
+ const {
3643
+ INIT_SOCKET,
3644
+ CURRENT_ID,
3645
+ CREATE_ID,
3646
+ SOCKET_CREATED_TIME,
3647
+ SOCKET_NAME,
3648
+ SOCKET_REQUEST_COUNT,
3649
+ SOCKET_REQUEST_FINISHED_COUNT,
3650
+ } = /*@__PURE__*/ requireConstants();
3651
+
3652
+ // OriginalAgent come from
3653
+ // - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js
3654
+ // - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js
3655
+
3656
+ // node <= 10
3657
+ let defaultTimeoutListenerCount = 1;
3658
+ const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));
3659
+ if (majorVersion >= 11 && majorVersion <= 12) {
3660
+ defaultTimeoutListenerCount = 2;
3661
+ } else if (majorVersion >= 13) {
3662
+ defaultTimeoutListenerCount = 3;
3663
+ }
3828
3664
 
3829
- if (err) {
3830
- this.createSocketErrorCount++;
3831
- return oncreate(err);
3832
- }
3833
- this[INIT_SOCKET$1](socket, options);
3834
- oncreate(err, socket);
3835
- };
3665
+ function deprecate(message) {
3666
+ console.log('[agentkeepalive:deprecated] %s', message);
3667
+ }
3836
3668
 
3837
- const newSocket = super.createConnection(options, onNewCreate);
3838
- if (newSocket) onNewCreate(null, newSocket);
3839
- return newSocket;
3840
- }
3669
+ class Agent extends OriginalAgent {
3670
+ constructor(options) {
3671
+ options = options || {};
3672
+ options.keepAlive = options.keepAlive !== false;
3673
+ // default is keep-alive and 4s free socket timeout
3674
+ // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83
3675
+ if (options.freeSocketTimeout === undefined) {
3676
+ options.freeSocketTimeout = 4000;
3677
+ }
3678
+ // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`
3679
+ if (options.keepAliveTimeout) {
3680
+ deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
3681
+ options.freeSocketTimeout = options.keepAliveTimeout;
3682
+ delete options.keepAliveTimeout;
3683
+ }
3684
+ // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`
3685
+ if (options.freeSocketKeepAliveTimeout) {
3686
+ deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');
3687
+ options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;
3688
+ delete options.freeSocketKeepAliveTimeout;
3689
+ }
3690
+
3691
+ // Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
3692
+ // By default is double free socket timeout.
3693
+ if (options.timeout === undefined) {
3694
+ // make sure socket default inactivity timeout >= 8s
3695
+ options.timeout = Math.max(options.freeSocketTimeout * 2, 8000);
3696
+ }
3697
+
3698
+ // support humanize format
3699
+ options.timeout = ms(options.timeout);
3700
+ options.freeSocketTimeout = ms(options.freeSocketTimeout);
3701
+ options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;
3702
+
3703
+ super(options);
3704
+
3705
+ this[CURRENT_ID] = 0;
3706
+
3707
+ // create socket success counter
3708
+ this.createSocketCount = 0;
3709
+ this.createSocketCountLastCheck = 0;
3710
+
3711
+ this.createSocketErrorCount = 0;
3712
+ this.createSocketErrorCountLastCheck = 0;
3713
+
3714
+ this.closeSocketCount = 0;
3715
+ this.closeSocketCountLastCheck = 0;
3716
+
3717
+ // socket error event count
3718
+ this.errorSocketCount = 0;
3719
+ this.errorSocketCountLastCheck = 0;
3720
+
3721
+ // request finished counter
3722
+ this.requestCount = 0;
3723
+ this.requestCountLastCheck = 0;
3724
+
3725
+ // including free socket timeout counter
3726
+ this.timeoutSocketCount = 0;
3727
+ this.timeoutSocketCountLastCheck = 0;
3728
+
3729
+ this.on('free', socket => {
3730
+ // https://github.com/nodejs/node/pull/32000
3731
+ // Node.js native agent will check socket timeout eqs agent.options.timeout.
3732
+ // Use the ttl or freeSocketTimeout to overwrite.
3733
+ const timeout = this.calcSocketTimeout(socket);
3734
+ if (timeout > 0 && socket.timeout !== timeout) {
3735
+ socket.setTimeout(timeout);
3736
+ }
3737
+ });
3738
+ }
3739
+
3740
+ get freeSocketKeepAliveTimeout() {
3741
+ deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');
3742
+ return this.options.freeSocketTimeout;
3743
+ }
3744
+
3745
+ get timeout() {
3746
+ deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');
3747
+ return this.options.timeout;
3748
+ }
3749
+
3750
+ get socketActiveTTL() {
3751
+ deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');
3752
+ return this.options.socketActiveTTL;
3753
+ }
3754
+
3755
+ calcSocketTimeout(socket) {
3756
+ /**
3757
+ * return <= 0: should free socket
3758
+ * return > 0: should update socket timeout
3759
+ * return undefined: not find custom timeout
3760
+ */
3761
+ let freeSocketTimeout = this.options.freeSocketTimeout;
3762
+ const socketActiveTTL = this.options.socketActiveTTL;
3763
+ if (socketActiveTTL) {
3764
+ // check socketActiveTTL
3765
+ const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];
3766
+ const diff = socketActiveTTL - aliveTime;
3767
+ if (diff <= 0) {
3768
+ return diff;
3769
+ }
3770
+ if (freeSocketTimeout && diff < freeSocketTimeout) {
3771
+ freeSocketTimeout = diff;
3772
+ }
3773
+ }
3774
+ // set freeSocketTimeout
3775
+ if (freeSocketTimeout) {
3776
+ // set free keepalive timer
3777
+ // try to use socket custom freeSocketTimeout first, support headers['keep-alive']
3778
+ // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498
3779
+ const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;
3780
+ return customFreeSocketTimeout || freeSocketTimeout;
3781
+ }
3782
+ }
3783
+
3784
+ keepSocketAlive(socket) {
3785
+ const result = super.keepSocketAlive(socket);
3786
+ // should not keepAlive, do nothing
3787
+ if (!result) return result;
3788
+
3789
+ const customTimeout = this.calcSocketTimeout(socket);
3790
+ if (typeof customTimeout === 'undefined') {
3791
+ return true;
3792
+ }
3793
+ if (customTimeout <= 0) {
3794
+ debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',
3795
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);
3796
+ return false;
3797
+ }
3798
+ if (socket.timeout !== customTimeout) {
3799
+ socket.setTimeout(customTimeout);
3800
+ }
3801
+ return true;
3802
+ }
3803
+
3804
+ // only call on addRequest
3805
+ reuseSocket(...args) {
3806
+ // reuseSocket(socket, req)
3807
+ super.reuseSocket(...args);
3808
+ const socket = args[0];
3809
+ const req = args[1];
3810
+ req.reusedSocket = true;
3811
+ const agentTimeout = this.options.timeout;
3812
+ if (getSocketTimeout(socket) !== agentTimeout) {
3813
+ // reset timeout before use
3814
+ socket.setTimeout(agentTimeout);
3815
+ debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);
3816
+ }
3817
+ socket[SOCKET_REQUEST_COUNT]++;
3818
+ debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',
3819
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
3820
+ getSocketTimeout(socket));
3821
+ }
3822
+
3823
+ [CREATE_ID]() {
3824
+ const id = this[CURRENT_ID]++;
3825
+ if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;
3826
+ return id;
3827
+ }
3828
+
3829
+ [INIT_SOCKET](socket, options) {
3830
+ // bugfix here.
3831
+ // https on node 8, 10 won't set agent.options.timeout by default
3832
+ // TODO: need to fix on node itself
3833
+ if (options.timeout) {
3834
+ const timeout = getSocketTimeout(socket);
3835
+ if (!timeout) {
3836
+ socket.setTimeout(options.timeout);
3837
+ }
3838
+ }
3839
+
3840
+ if (this.options.keepAlive) {
3841
+ // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/
3842
+ // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html
3843
+ socket.setNoDelay(true);
3844
+ }
3845
+ this.createSocketCount++;
3846
+ if (this.options.socketActiveTTL) {
3847
+ socket[SOCKET_CREATED_TIME] = Date.now();
3848
+ }
3849
+ // don't show the hole '-----BEGIN CERTIFICATE----' key string
3850
+ socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];
3851
+ socket[SOCKET_REQUEST_COUNT] = 1;
3852
+ socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;
3853
+ installListeners(this, socket, options);
3854
+ }
3855
+
3856
+ createConnection(options, oncreate) {
3857
+ let called = false;
3858
+ const onNewCreate = (err, socket) => {
3859
+ if (called) return;
3860
+ called = true;
3861
+
3862
+ if (err) {
3863
+ this.createSocketErrorCount++;
3864
+ return oncreate(err);
3865
+ }
3866
+ this[INIT_SOCKET](socket, options);
3867
+ oncreate(err, socket);
3868
+ };
3869
+
3870
+ const newSocket = super.createConnection(options, onNewCreate);
3871
+ if (newSocket) onNewCreate(null, newSocket);
3872
+ return newSocket;
3873
+ }
3874
+
3875
+ get statusChanged() {
3876
+ const changed = this.createSocketCount !== this.createSocketCountLastCheck ||
3877
+ this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||
3878
+ this.closeSocketCount !== this.closeSocketCountLastCheck ||
3879
+ this.errorSocketCount !== this.errorSocketCountLastCheck ||
3880
+ this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||
3881
+ this.requestCount !== this.requestCountLastCheck;
3882
+ if (changed) {
3883
+ this.createSocketCountLastCheck = this.createSocketCount;
3884
+ this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
3885
+ this.closeSocketCountLastCheck = this.closeSocketCount;
3886
+ this.errorSocketCountLastCheck = this.errorSocketCount;
3887
+ this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
3888
+ this.requestCountLastCheck = this.requestCount;
3889
+ }
3890
+ return changed;
3891
+ }
3892
+
3893
+ getCurrentStatus() {
3894
+ return {
3895
+ createSocketCount: this.createSocketCount,
3896
+ createSocketErrorCount: this.createSocketErrorCount,
3897
+ closeSocketCount: this.closeSocketCount,
3898
+ errorSocketCount: this.errorSocketCount,
3899
+ timeoutSocketCount: this.timeoutSocketCount,
3900
+ requestCount: this.requestCount,
3901
+ freeSockets: inspect(this.freeSockets),
3902
+ sockets: inspect(this.sockets),
3903
+ requests: inspect(this.requests),
3904
+ };
3905
+ }
3906
+ }
3841
3907
 
3842
- get statusChanged() {
3843
- const changed = this.createSocketCount !== this.createSocketCountLastCheck ||
3844
- this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||
3845
- this.closeSocketCount !== this.closeSocketCountLastCheck ||
3846
- this.errorSocketCount !== this.errorSocketCountLastCheck ||
3847
- this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||
3848
- this.requestCount !== this.requestCountLastCheck;
3849
- if (changed) {
3850
- this.createSocketCountLastCheck = this.createSocketCount;
3851
- this.createSocketErrorCountLastCheck = this.createSocketErrorCount;
3852
- this.closeSocketCountLastCheck = this.closeSocketCount;
3853
- this.errorSocketCountLastCheck = this.errorSocketCount;
3854
- this.timeoutSocketCountLastCheck = this.timeoutSocketCount;
3855
- this.requestCountLastCheck = this.requestCount;
3856
- }
3857
- return changed;
3858
- }
3908
+ // node 8 don't has timeout attribute on socket
3909
+ // https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408
3910
+ function getSocketTimeout(socket) {
3911
+ return socket.timeout || socket._idleTimeout;
3912
+ }
3859
3913
 
3860
- getCurrentStatus() {
3861
- return {
3862
- createSocketCount: this.createSocketCount,
3863
- createSocketErrorCount: this.createSocketErrorCount,
3864
- closeSocketCount: this.closeSocketCount,
3865
- errorSocketCount: this.errorSocketCount,
3866
- timeoutSocketCount: this.timeoutSocketCount,
3867
- requestCount: this.requestCount,
3868
- freeSockets: inspect(this.freeSockets),
3869
- sockets: inspect(this.sockets),
3870
- requests: inspect(this.requests),
3871
- };
3872
- }
3873
- }
3914
+ function installListeners(agent, socket, options) {
3915
+ debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));
3916
+
3917
+ // listener socket events: close, timeout, error, free
3918
+ function onFree() {
3919
+ // create and socket.emit('free') logic
3920
+ // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311
3921
+ // no req on the socket, it should be the new socket
3922
+ if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
3923
+
3924
+ socket[SOCKET_REQUEST_FINISHED_COUNT]++;
3925
+ agent.requestCount++;
3926
+ debug('%s(requests: %s, finished: %s) free',
3927
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
3928
+
3929
+ // should reuse on pedding requests?
3930
+ const name = agent.getName(options);
3931
+ if (socket.writable && agent.requests[name] && agent.requests[name].length) {
3932
+ // will be reuse on agent free listener
3933
+ socket[SOCKET_REQUEST_COUNT]++;
3934
+ debug('%s(requests: %s, finished: %s) will be reuse on agent free event',
3935
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
3936
+ }
3937
+ }
3938
+ socket.on('free', onFree);
3939
+
3940
+ function onClose(isError) {
3941
+ debug('%s(requests: %s, finished: %s) close, isError: %s',
3942
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);
3943
+ agent.closeSocketCount++;
3944
+ }
3945
+ socket.on('close', onClose);
3946
+
3947
+ // start socket timeout handler
3948
+ function onTimeout() {
3949
+ // onTimeout and emitRequestTimeout(_http_client.js)
3950
+ // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711
3951
+ const listenerCount = socket.listeners('timeout').length;
3952
+ // node <= 10, default listenerCount is 1, onTimeout
3953
+ // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout
3954
+ // node >= 13, default listenerCount is 3, onTimeout,
3955
+ // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)
3956
+ // and emitRequestTimeout
3957
+ const timeout = getSocketTimeout(socket);
3958
+ const req = socket._httpMessage;
3959
+ const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;
3960
+ debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',
3961
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
3962
+ timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);
3963
+ if (debug.enabled) {
3964
+ debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));
3965
+ }
3966
+ agent.timeoutSocketCount++;
3967
+ const name = agent.getName(options);
3968
+ if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
3969
+ // free socket timeout, destroy quietly
3970
+ socket.destroy();
3971
+ // Remove it from freeSockets list immediately to prevent new requests
3972
+ // from being sent through this socket.
3973
+ agent.removeSocket(socket, options);
3974
+ debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
3975
+ } else {
3976
+ // if there is no any request socket timeout handler,
3977
+ // agent need to handle socket timeout itself.
3978
+ //
3979
+ // custom request socket timeout handle logic must follow these rules:
3980
+ // 1. Destroy socket first
3981
+ // 2. Must emit socket 'agentRemove' event tell agent remove socket
3982
+ // from freeSockets list immediately.
3983
+ // Otherise you may be get 'socket hang up' error when reuse
3984
+ // free socket and timeout happen in the same time.
3985
+ if (reqTimeoutListenerCount === 0) {
3986
+ const error = new Error('Socket timeout');
3987
+ error.code = 'ERR_SOCKET_TIMEOUT';
3988
+ error.timeout = timeout;
3989
+ // must manually call socket.end() or socket.destroy() to end the connection.
3990
+ // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
3991
+ socket.destroy(error);
3992
+ agent.removeSocket(socket, options);
3993
+ debug('%s destroy with timeout error', socket[SOCKET_NAME]);
3994
+ }
3995
+ }
3996
+ }
3997
+ socket.on('timeout', onTimeout);
3998
+
3999
+ function onError(err) {
4000
+ const listenerCount = socket.listeners('error').length;
4001
+ debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',
4002
+ socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
4003
+ err, listenerCount);
4004
+ agent.errorSocketCount++;
4005
+ if (listenerCount === 1) {
4006
+ // if socket don't contain error event handler, don't catch it, emit it again
4007
+ debug('%s emit uncaught error event', socket[SOCKET_NAME]);
4008
+ socket.removeListener('error', onError);
4009
+ socket.emit('error', err);
4010
+ }
4011
+ }
4012
+ socket.on('error', onError);
4013
+
4014
+ function onRemove() {
4015
+ debug('%s(requests: %s, finished: %s) agentRemove',
4016
+ socket[SOCKET_NAME],
4017
+ socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
4018
+ // We need this function for cases like HTTP 'upgrade'
4019
+ // (defined by WebSockets) where we need to remove a socket from the
4020
+ // pool because it'll be locked up indefinitely
4021
+ socket.removeListener('close', onClose);
4022
+ socket.removeListener('error', onError);
4023
+ socket.removeListener('free', onFree);
4024
+ socket.removeListener('timeout', onTimeout);
4025
+ socket.removeListener('agentRemove', onRemove);
4026
+ }
4027
+ socket.on('agentRemove', onRemove);
4028
+ }
3874
4029
 
3875
- // node 8 don't has timeout attribute on socket
3876
- // https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408
3877
- function getSocketTimeout(socket) {
3878
- return socket.timeout || socket._idleTimeout;
3879
- }
4030
+ agent = Agent;
3880
4031
 
3881
- function installListeners(agent, socket, options) {
3882
- debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));
3883
-
3884
- // listener socket events: close, timeout, error, free
3885
- function onFree() {
3886
- // create and socket.emit('free') logic
3887
- // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311
3888
- // no req on the socket, it should be the new socket
3889
- if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;
3890
-
3891
- socket[SOCKET_REQUEST_FINISHED_COUNT]++;
3892
- agent.requestCount++;
3893
- debug('%s(requests: %s, finished: %s) free',
3894
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
3895
-
3896
- // should reuse on pedding requests?
3897
- const name = agent.getName(options);
3898
- if (socket.writable && agent.requests[name] && agent.requests[name].length) {
3899
- // will be reuse on agent free listener
3900
- socket[SOCKET_REQUEST_COUNT]++;
3901
- debug('%s(requests: %s, finished: %s) will be reuse on agent free event',
3902
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
3903
- }
3904
- }
3905
- socket.on('free', onFree);
3906
-
3907
- function onClose(isError) {
3908
- debug('%s(requests: %s, finished: %s) close, isError: %s',
3909
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);
3910
- agent.closeSocketCount++;
3911
- }
3912
- socket.on('close', onClose);
3913
-
3914
- // start socket timeout handler
3915
- function onTimeout() {
3916
- // onTimeout and emitRequestTimeout(_http_client.js)
3917
- // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711
3918
- const listenerCount = socket.listeners('timeout').length;
3919
- // node <= 10, default listenerCount is 1, onTimeout
3920
- // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout
3921
- // node >= 13, default listenerCount is 3, onTimeout,
3922
- // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)
3923
- // and emitRequestTimeout
3924
- const timeout = getSocketTimeout(socket);
3925
- const req = socket._httpMessage;
3926
- const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;
3927
- debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',
3928
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
3929
- timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);
3930
- if (debug.enabled) {
3931
- debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));
3932
- }
3933
- agent.timeoutSocketCount++;
3934
- const name = agent.getName(options);
3935
- if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {
3936
- // free socket timeout, destroy quietly
3937
- socket.destroy();
3938
- // Remove it from freeSockets list immediately to prevent new requests
3939
- // from being sent through this socket.
3940
- agent.removeSocket(socket, options);
3941
- debug('%s is free, destroy quietly', socket[SOCKET_NAME]);
3942
- } else {
3943
- // if there is no any request socket timeout handler,
3944
- // agent need to handle socket timeout itself.
3945
- //
3946
- // custom request socket timeout handle logic must follow these rules:
3947
- // 1. Destroy socket first
3948
- // 2. Must emit socket 'agentRemove' event tell agent remove socket
3949
- // from freeSockets list immediately.
3950
- // Otherise you may be get 'socket hang up' error when reuse
3951
- // free socket and timeout happen in the same time.
3952
- if (reqTimeoutListenerCount === 0) {
3953
- const error = new Error('Socket timeout');
3954
- error.code = 'ERR_SOCKET_TIMEOUT';
3955
- error.timeout = timeout;
3956
- // must manually call socket.end() or socket.destroy() to end the connection.
3957
- // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback
3958
- socket.destroy(error);
3959
- agent.removeSocket(socket, options);
3960
- debug('%s destroy with timeout error', socket[SOCKET_NAME]);
3961
- }
3962
- }
3963
- }
3964
- socket.on('timeout', onTimeout);
3965
-
3966
- function onError(err) {
3967
- const listenerCount = socket.listeners('error').length;
3968
- debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',
3969
- socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],
3970
- err, listenerCount);
3971
- agent.errorSocketCount++;
3972
- if (listenerCount === 1) {
3973
- // if socket don't contain error event handler, don't catch it, emit it again
3974
- debug('%s emit uncaught error event', socket[SOCKET_NAME]);
3975
- socket.removeListener('error', onError);
3976
- socket.emit('error', err);
3977
- }
3978
- }
3979
- socket.on('error', onError);
3980
-
3981
- function onRemove() {
3982
- debug('%s(requests: %s, finished: %s) agentRemove',
3983
- socket[SOCKET_NAME],
3984
- socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);
3985
- // We need this function for cases like HTTP 'upgrade'
3986
- // (defined by WebSockets) where we need to remove a socket from the
3987
- // pool because it'll be locked up indefinitely
3988
- socket.removeListener('close', onClose);
3989
- socket.removeListener('error', onError);
3990
- socket.removeListener('free', onFree);
3991
- socket.removeListener('timeout', onTimeout);
3992
- socket.removeListener('agentRemove', onRemove);
3993
- }
3994
- socket.on('agentRemove', onRemove);
4032
+ function inspect(obj) {
4033
+ const res = {};
4034
+ for (const key in obj) {
4035
+ res[key] = obj[key].length;
4036
+ }
4037
+ return res;
4038
+ }
4039
+ return agent;
3995
4040
  }
3996
4041
 
3997
- var agent = Agent;
4042
+ var https_agent;
4043
+ var hasRequiredHttps_agent;
4044
+
4045
+ function requireHttps_agent () {
4046
+ if (hasRequiredHttps_agent) return https_agent;
4047
+ hasRequiredHttps_agent = 1;
4048
+
4049
+ const OriginalHttpsAgent = require$$0__default$2.default.Agent;
4050
+ const HttpAgent = /*@__PURE__*/ requireAgent();
4051
+ const {
4052
+ INIT_SOCKET,
4053
+ CREATE_HTTPS_CONNECTION,
4054
+ } = /*@__PURE__*/ requireConstants();
4055
+
4056
+ class HttpsAgent extends HttpAgent {
4057
+ constructor(options) {
4058
+ super(options);
4059
+
4060
+ this.defaultPort = 443;
4061
+ this.protocol = 'https:';
4062
+ this.maxCachedSessions = this.options.maxCachedSessions;
4063
+ /* istanbul ignore next */
4064
+ if (this.maxCachedSessions === undefined) {
4065
+ this.maxCachedSessions = 100;
4066
+ }
4067
+
4068
+ this._sessionCache = {
4069
+ map: {},
4070
+ list: [],
4071
+ };
4072
+ }
4073
+
4074
+ createConnection(options, oncreate) {
4075
+ const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate);
4076
+ this[INIT_SOCKET](socket, options);
4077
+ return socket;
4078
+ }
4079
+ }
3998
4080
 
3999
- function inspect(obj) {
4000
- const res = {};
4001
- for (const key in obj) {
4002
- res[key] = obj[key].length;
4003
- }
4004
- return res;
4081
+ // https://github.com/nodejs/node/blob/master/lib/https.js#L89
4082
+ HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
4083
+
4084
+ [
4085
+ 'getName',
4086
+ '_getSession',
4087
+ '_cacheSession',
4088
+ // https://github.com/nodejs/node/pull/4982
4089
+ '_evictSession',
4090
+ ].forEach(function(method) {
4091
+ /* istanbul ignore next */
4092
+ if (typeof OriginalHttpsAgent.prototype[method] === 'function') {
4093
+ HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];
4094
+ }
4095
+ });
4096
+
4097
+ https_agent = HttpsAgent;
4098
+ return https_agent;
4005
4099
  }
4006
4100
 
4007
- const OriginalHttpsAgent = require$$0__default$2.default.Agent;
4008
- const HttpAgent = agent;
4009
- const {
4010
- INIT_SOCKET,
4011
- CREATE_HTTPS_CONNECTION,
4012
- } = constants;
4013
-
4014
- let HttpsAgent$1 = class HttpsAgent extends HttpAgent {
4015
- constructor(options) {
4016
- super(options);
4017
-
4018
- this.defaultPort = 443;
4019
- this.protocol = 'https:';
4020
- this.maxCachedSessions = this.options.maxCachedSessions;
4021
- /* istanbul ignore next */
4022
- if (this.maxCachedSessions === undefined) {
4023
- this.maxCachedSessions = 100;
4024
- }
4025
-
4026
- this._sessionCache = {
4027
- map: {},
4028
- list: [],
4029
- };
4030
- }
4031
-
4032
- createConnection(options, oncreate) {
4033
- const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate);
4034
- this[INIT_SOCKET](socket, options);
4035
- return socket;
4036
- }
4037
- };
4038
-
4039
- // https://github.com/nodejs/node/blob/master/lib/https.js#L89
4040
- HttpsAgent$1.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
4041
-
4042
- [
4043
- 'getName',
4044
- '_getSession',
4045
- '_cacheSession',
4046
- // https://github.com/nodejs/node/pull/4982
4047
- '_evictSession',
4048
- ].forEach(function(method) {
4049
- /* istanbul ignore next */
4050
- if (typeof OriginalHttpsAgent.prototype[method] === 'function') {
4051
- HttpsAgent$1.prototype[method] = OriginalHttpsAgent.prototype[method];
4052
- }
4053
- });
4101
+ var hasRequiredAgentkeepalive;
4054
4102
 
4055
- var https_agent = HttpsAgent$1;
4103
+ function requireAgentkeepalive () {
4104
+ if (hasRequiredAgentkeepalive) return agentkeepalive.exports;
4105
+ hasRequiredAgentkeepalive = 1;
4056
4106
 
4057
- agentkeepalive.exports = agent;
4058
- var HttpsAgent = agentkeepalive.exports.HttpsAgent = https_agent;
4059
- agentkeepalive.exports.constants = constants;
4107
+ agentkeepalive.exports = /*@__PURE__*/ requireAgent();
4108
+ agentkeepalive.exports.HttpsAgent = /*@__PURE__*/ requireHttps_agent();
4109
+ agentkeepalive.exports.constants = /*@__PURE__*/ requireConstants();
4110
+ return agentkeepalive.exports;
4111
+ }
4060
4112
 
4061
- var agentkeepaliveExports = agentkeepalive.exports;
4113
+ var agentkeepaliveExports = /*@__PURE__*/ requireAgentkeepalive();
4062
4114
  var HttpKeepAliveAgent = /*@__PURE__*/getDefaultExportFromCjs(agentkeepaliveExports);
4063
4115
 
4064
- var objToString = Object.prototype.toString;
4065
- var objKeys = Object.keys || function(obj) {
4066
- var keys = [];
4067
- for (var name in obj) {
4068
- keys.push(name);
4069
- }
4070
- return keys;
4071
- };
4116
+ var fastStableStringify$1;
4117
+ var hasRequiredFastStableStringify;
4118
+
4119
+ function requireFastStableStringify () {
4120
+ if (hasRequiredFastStableStringify) return fastStableStringify$1;
4121
+ hasRequiredFastStableStringify = 1;
4122
+ var objToString = Object.prototype.toString;
4123
+ var objKeys = Object.keys || function(obj) {
4124
+ var keys = [];
4125
+ for (var name in obj) {
4126
+ keys.push(name);
4127
+ }
4128
+ return keys;
4129
+ };
4072
4130
 
4073
- function stringify(val, isArrayProp) {
4074
- var i, max, str, keys, key, propVal, toStr;
4075
- if (val === true) {
4076
- return "true";
4077
- }
4078
- if (val === false) {
4079
- return "false";
4080
- }
4081
- switch (typeof val) {
4082
- case "object":
4083
- if (val === null) {
4084
- return null;
4085
- } else if (val.toJSON && typeof val.toJSON === "function") {
4086
- return stringify(val.toJSON(), isArrayProp);
4087
- } else {
4088
- toStr = objToString.call(val);
4089
- if (toStr === "[object Array]") {
4090
- str = '[';
4091
- max = val.length - 1;
4092
- for(i = 0; i < max; i++) {
4093
- str += stringify(val[i], true) + ',';
4094
- }
4095
- if (max > -1) {
4096
- str += stringify(val[i], true);
4097
- }
4098
- return str + ']';
4099
- } else if (toStr === "[object Object]") {
4100
- // only object is left
4101
- keys = objKeys(val).sort();
4102
- max = keys.length;
4103
- str = "";
4104
- i = 0;
4105
- while (i < max) {
4106
- key = keys[i];
4107
- propVal = stringify(val[key], false);
4108
- if (propVal !== undefined) {
4109
- if (str) {
4110
- str += ',';
4131
+ function stringify(val, isArrayProp) {
4132
+ var i, max, str, keys, key, propVal, toStr;
4133
+ if (val === true) {
4134
+ return "true";
4135
+ }
4136
+ if (val === false) {
4137
+ return "false";
4138
+ }
4139
+ switch (typeof val) {
4140
+ case "object":
4141
+ if (val === null) {
4142
+ return null;
4143
+ } else if (val.toJSON && typeof val.toJSON === "function") {
4144
+ return stringify(val.toJSON(), isArrayProp);
4145
+ } else {
4146
+ toStr = objToString.call(val);
4147
+ if (toStr === "[object Array]") {
4148
+ str = '[';
4149
+ max = val.length - 1;
4150
+ for(i = 0; i < max; i++) {
4151
+ str += stringify(val[i], true) + ',';
4152
+ }
4153
+ if (max > -1) {
4154
+ str += stringify(val[i], true);
4155
+ }
4156
+ return str + ']';
4157
+ } else if (toStr === "[object Object]") {
4158
+ // only object is left
4159
+ keys = objKeys(val).sort();
4160
+ max = keys.length;
4161
+ str = "";
4162
+ i = 0;
4163
+ while (i < max) {
4164
+ key = keys[i];
4165
+ propVal = stringify(val[key], false);
4166
+ if (propVal !== undefined) {
4167
+ if (str) {
4168
+ str += ',';
4169
+ }
4170
+ str += JSON.stringify(key) + ':' + propVal;
4111
4171
  }
4112
- str += JSON.stringify(key) + ':' + propVal;
4172
+ i++;
4113
4173
  }
4114
- i++;
4174
+ return '{' + str + '}';
4175
+ } else {
4176
+ return JSON.stringify(val);
4115
4177
  }
4116
- return '{' + str + '}';
4117
- } else {
4118
- return JSON.stringify(val);
4119
4178
  }
4120
- }
4121
- case "function":
4122
- case "undefined":
4123
- return isArrayProp ? null : undefined;
4124
- case "string":
4125
- return JSON.stringify(val);
4126
- default:
4127
- return isFinite(val) ? val : null;
4179
+ case "function":
4180
+ case "undefined":
4181
+ return isArrayProp ? null : undefined;
4182
+ case "string":
4183
+ return JSON.stringify(val);
4184
+ default:
4185
+ return isFinite(val) ? val : null;
4186
+ }
4128
4187
  }
4129
- }
4130
4188
 
4131
- var fastStableStringify = function(val) {
4132
- var returnVal = stringify(val, false);
4133
- if (returnVal !== undefined) {
4134
- return ''+ returnVal;
4135
- }
4136
- };
4189
+ fastStableStringify$1 = function(val) {
4190
+ var returnVal = stringify(val, false);
4191
+ if (returnVal !== undefined) {
4192
+ return ''+ returnVal;
4193
+ }
4194
+ };
4195
+ return fastStableStringify$1;
4196
+ }
4137
4197
 
4138
- var fastStableStringify$1 = /*@__PURE__*/getDefaultExportFromCjs(fastStableStringify);
4198
+ var fastStableStringifyExports = /*@__PURE__*/ requireFastStableStringify();
4199
+ var fastStableStringify = /*@__PURE__*/getDefaultExportFromCjs(fastStableStringifyExports);
4139
4200
 
4140
4201
  const MINIMUM_SLOT_PER_EPOCH = 32;
4141
4202
 
@@ -4960,7 +5021,7 @@ function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disable
4960
5021
  maxSockets: 25
4961
5022
  };
4962
5023
  if (url.startsWith('https:')) {
4963
- agent = new HttpsAgent(agentOptions);
5024
+ agent = new agentkeepaliveExports.HttpsAgent(agentOptions);
4964
5025
  } else {
4965
5026
  agent = new HttpKeepAliveAgent(agentOptions);
4966
5027
  }
@@ -5491,6 +5552,7 @@ const TokenBalanceResult = superstruct.type({
5491
5552
  accountIndex: superstruct.number(),
5492
5553
  mint: superstruct.string(),
5493
5554
  owner: superstruct.optional(superstruct.string()),
5555
+ programId: superstruct.optional(superstruct.string()),
5494
5556
  uiTokenAmount: TokenAmountResult
5495
5557
  });
5496
5558
  const LoadedAddressesResult = superstruct.type({
@@ -6020,7 +6082,7 @@ class Connection {
6020
6082
  config
6021
6083
  } = extractCommitmentFromConfig(commitmentOrConfig);
6022
6084
  const args = this._buildArgs([], commitment, undefined /* encoding */, config);
6023
- const requestHash = fastStableStringify$1(args);
6085
+ const requestHash = fastStableStringify(args);
6024
6086
  requestPromises[requestHash] = requestPromises[requestHash] ?? (async () => {
6025
6087
  try {
6026
6088
  const unsafeRes = await this._rpcRequest('getBlockHeight', args);
@@ -8339,9 +8401,10 @@ class Connection {
8339
8401
  this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks;
8340
8402
  await this._updateSubscriptions();
8341
8403
  } catch (e) {
8342
- if (e instanceof Error) {
8343
- console.error(`${method} error for argument`, args, e.message);
8344
- }
8404
+ console.error(`Received ${e instanceof Error ? '' : 'JSON-RPC '}error calling \`${method}\``, {
8405
+ args,
8406
+ error: e
8407
+ });
8345
8408
  if (!isCurrentConnectionStillActive()) {
8346
8409
  return;
8347
8410
  }
@@ -8477,7 +8540,7 @@ class Connection {
8477
8540
  */
8478
8541
  args) {
8479
8542
  const clientSubscriptionId = this._nextClientSubscriptionId++;
8480
- const hash = fastStableStringify$1([subscriptionConfig.method, args]);
8543
+ const hash = fastStableStringify([subscriptionConfig.method, args]);
8481
8544
  const existingSubscription = this._subscriptionsByHash[hash];
8482
8545
  if (existingSubscription === undefined) {
8483
8546
  this._subscriptionsByHash[hash] = {