@openfeature/flagd-provider 0.13.2 → 0.13.4

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/index.cjs.js CHANGED
@@ -5,6 +5,7 @@ var grpcJs = require('@grpc/grpc-js');
5
5
  var connectivityState = require('@grpc/grpc-js/build/src/connectivity-state');
6
6
  var lruCache = require('lru-cache');
7
7
  var node_util = require('node:util');
8
+ var node_fs = require('node:fs');
8
9
  var flagdCore = require('@openfeature/flagd-core');
9
10
  var fs = require('fs');
10
11
 
@@ -43,13 +44,23 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
43
44
  const EVENT_CONFIGURATION_CHANGE = 'configuration_change';
44
45
  const EVENT_PROVIDER_READY = 'provider_ready';
45
46
  const DEFAULT_MAX_CACHE_SIZE = 1000;
47
+ const DEFAULT_RETRY_GRACE_PERIOD = 5;
48
+ const DEFAULT_MAX_BACKOFF_MS = 12000;
49
+ const FLAGD_SELECTOR_HEADER = 'flagd-selector';
46
50
 
47
51
  const DEFAULT_CONFIG = {
52
+ deadlineMs: 500,
53
+ streamDeadlineMs: 600000,
48
54
  host: 'localhost',
49
55
  tls: false,
50
56
  selector: '',
51
57
  cache: 'lru',
52
58
  maxCacheSize: DEFAULT_MAX_CACHE_SIZE,
59
+ contextEnricher: (syncContext) => syncContext !== null && syncContext !== void 0 ? syncContext : {},
60
+ retryBackoffMs: 1000,
61
+ retryBackoffMaxMs: DEFAULT_MAX_BACKOFF_MS,
62
+ keepAliveTime: 0,
63
+ retryGracePeriod: DEFAULT_RETRY_GRACE_PERIOD,
53
64
  };
54
65
  const DEFAULT_RPC_CONFIG = Object.assign(Object.assign({}, DEFAULT_CONFIG), { resolverType: 'rpc', port: 8013 });
55
66
  const DEFAULT_IN_PROCESS_CONFIG = Object.assign(Object.assign({}, DEFAULT_CONFIG), { resolverType: 'in-process', port: 8015 });
@@ -57,42 +68,82 @@ var ENV_VAR;
57
68
  (function (ENV_VAR) {
58
69
  ENV_VAR["FLAGD_HOST"] = "FLAGD_HOST";
59
70
  ENV_VAR["FLAGD_PORT"] = "FLAGD_PORT";
71
+ ENV_VAR["FLAGD_SYNC_PORT"] = "FLAGD_SYNC_PORT";
72
+ ENV_VAR["FLAGD_DEADLINE_MS"] = "FLAGD_DEADLINE_MS";
73
+ ENV_VAR["FLAGD_STREAM_DEADLINE_MS"] = "FLAGD_STREAM_DEADLINE_MS";
60
74
  ENV_VAR["FLAGD_TLS"] = "FLAGD_TLS";
61
75
  ENV_VAR["FLAGD_SOCKET_PATH"] = "FLAGD_SOCKET_PATH";
76
+ ENV_VAR["FLAGD_SERVER_CERT_PATH"] = "FLAGD_SERVER_CERT_PATH";
62
77
  ENV_VAR["FLAGD_CACHE"] = "FLAGD_CACHE";
63
78
  ENV_VAR["FLAGD_MAX_CACHE_SIZE"] = "FLAGD_MAX_CACHE_SIZE";
64
79
  ENV_VAR["FLAGD_SOURCE_SELECTOR"] = "FLAGD_SOURCE_SELECTOR";
65
80
  ENV_VAR["FLAGD_RESOLVER"] = "FLAGD_RESOLVER";
66
81
  ENV_VAR["FLAGD_OFFLINE_FLAG_SOURCE_PATH"] = "FLAGD_OFFLINE_FLAG_SOURCE_PATH";
82
+ ENV_VAR["FLAGD_DEFAULT_AUTHORITY"] = "FLAGD_DEFAULT_AUTHORITY";
83
+ ENV_VAR["FLAGD_RETRY_BACKOFF_MS"] = "FLAGD_RETRY_BACKOFF_MS";
84
+ ENV_VAR["FLAGD_RETRY_BACKOFF_MAX_MS"] = "FLAGD_RETRY_BACKOFF_MAX_MS";
85
+ ENV_VAR["FLAGD_KEEP_ALIVE_TIME_MS"] = "FLAGD_KEEP_ALIVE_TIME_MS";
86
+ ENV_VAR["FLAGD_FATAL_STATUS_CODES"] = "FLAGD_FATAL_STATUS_CODES";
87
+ ENV_VAR["FLAGD_RETRY_GRACE_PERIOD"] = "FLAGD_RETRY_GRACE_PERIOD";
67
88
  })(ENV_VAR || (ENV_VAR = {}));
68
- const getEnvVarConfig = () => {
89
+ function getEnvVarConfig() {
69
90
  var _a;
70
- return (Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (process.env[ENV_VAR.FLAGD_HOST] && {
91
+ let provider = undefined;
92
+ if (process.env[ENV_VAR.FLAGD_RESOLVER] &&
93
+ (process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase() === 'rpc' ||
94
+ process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase() === 'in-process')) {
95
+ provider = process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase();
96
+ }
97
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (process.env[ENV_VAR.FLAGD_HOST] && {
71
98
  host: process.env[ENV_VAR.FLAGD_HOST],
72
99
  })), (Number(process.env[ENV_VAR.FLAGD_PORT]) && {
73
100
  port: Number(process.env[ENV_VAR.FLAGD_PORT]),
101
+ })), (Number(process.env[ENV_VAR.FLAGD_SYNC_PORT]) && {
102
+ port: Number(process.env[ENV_VAR.FLAGD_SYNC_PORT]),
103
+ })), (Number(process.env[ENV_VAR.FLAGD_DEADLINE_MS]) && {
104
+ deadlineMs: Number(process.env[ENV_VAR.FLAGD_DEADLINE_MS]),
105
+ })), (Number(process.env[ENV_VAR.FLAGD_STREAM_DEADLINE_MS]) && {
106
+ streamDeadlineMs: Number(process.env[ENV_VAR.FLAGD_STREAM_DEADLINE_MS]),
74
107
  })), (process.env[ENV_VAR.FLAGD_TLS] && {
75
- tls: ((_a = process.env[ENV_VAR.FLAGD_TLS]) === null || _a === undefined ? undefined : _a.toLowerCase()) === 'true',
108
+ tls: ((_a = process.env[ENV_VAR.FLAGD_TLS]) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'true',
76
109
  })), (process.env[ENV_VAR.FLAGD_SOCKET_PATH] && {
77
110
  socketPath: process.env[ENV_VAR.FLAGD_SOCKET_PATH],
111
+ })), (process.env[ENV_VAR.FLAGD_SERVER_CERT_PATH] && {
112
+ certPath: process.env[ENV_VAR.FLAGD_SERVER_CERT_PATH],
78
113
  })), ((process.env[ENV_VAR.FLAGD_CACHE] === 'lru' || process.env[ENV_VAR.FLAGD_CACHE] === 'disabled') && {
79
114
  cache: process.env[ENV_VAR.FLAGD_CACHE],
80
115
  })), (process.env[ENV_VAR.FLAGD_MAX_CACHE_SIZE] && {
81
116
  maxCacheSize: Number(process.env[ENV_VAR.FLAGD_MAX_CACHE_SIZE]),
82
117
  })), (process.env[ENV_VAR.FLAGD_SOURCE_SELECTOR] && {
83
118
  selector: process.env[ENV_VAR.FLAGD_SOURCE_SELECTOR],
84
- })), ((process.env[ENV_VAR.FLAGD_RESOLVER] === 'rpc' || process.env[ENV_VAR.FLAGD_RESOLVER] === 'in-process') && {
85
- resolverType: process.env[ENV_VAR.FLAGD_RESOLVER],
119
+ })), (provider && {
120
+ resolverType: provider,
86
121
  })), (process.env[ENV_VAR.FLAGD_OFFLINE_FLAG_SOURCE_PATH] && {
87
122
  offlineFlagSourcePath: process.env[ENV_VAR.FLAGD_OFFLINE_FLAG_SOURCE_PATH],
88
- })));
89
- };
123
+ })), (process.env[ENV_VAR.FLAGD_DEFAULT_AUTHORITY] && {
124
+ defaultAuthority: process.env[ENV_VAR.FLAGD_DEFAULT_AUTHORITY],
125
+ })), (Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MS]) && {
126
+ retryBackoffMs: Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MS]),
127
+ })), (Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MAX_MS]) && {
128
+ retryBackoffMaxMs: Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MAX_MS]),
129
+ })), (Number(process.env[ENV_VAR.FLAGD_KEEP_ALIVE_TIME_MS]) && {
130
+ keepAliveTime: Number(process.env[ENV_VAR.FLAGD_KEEP_ALIVE_TIME_MS]),
131
+ })), (process.env[ENV_VAR.FLAGD_FATAL_STATUS_CODES] && {
132
+ fatalStatusCodes: process.env[ENV_VAR.FLAGD_FATAL_STATUS_CODES]
133
+ .split(',')
134
+ .map((code) => code.trim())
135
+ .filter((code) => code.length > 0),
136
+ })), (process.env[ENV_VAR.FLAGD_RETRY_GRACE_PERIOD] && {
137
+ retryGracePeriod: Number(process.env[ENV_VAR.FLAGD_RETRY_GRACE_PERIOD]),
138
+ }));
139
+ }
90
140
  function getConfig(options = {}) {
141
+ var _a, _b;
91
142
  const envVarConfig = getEnvVarConfig();
92
143
  const defaultConfig = options.resolverType == 'in-process' || envVarConfig.resolverType == 'in-process'
93
144
  ? DEFAULT_IN_PROCESS_CONFIG
94
145
  : DEFAULT_RPC_CONFIG;
95
- return Object.assign(Object.assign(Object.assign({}, defaultConfig), envVarConfig), options);
146
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, defaultConfig), envVarConfig), options), { streamDeadlineMs: (_b = (_a = options.streamDeadlineMs) !== null && _a !== void 0 ? _a : envVarConfig.streamDeadlineMs) !== null && _b !== void 0 ? _b : DEFAULT_CONFIG.streamDeadlineMs });
96
147
  }
97
148
 
98
149
  /**
@@ -118,10 +169,85 @@ function getConfig(options = {}) {
118
169
  // WebAssembly optimizations to do native i64 multiplication and divide
119
170
  var wasm = null;
120
171
  try {
121
- wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
122
- 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
123
- ])), {}).exports;
124
- } catch (e) {
172
+ wasm = new WebAssembly.Instance(
173
+ new WebAssembly.Module(
174
+ new Uint8Array([
175
+ // \0asm
176
+ 0, 97, 115, 109,
177
+ // version 1
178
+ 1, 0, 0, 0,
179
+
180
+ // section "type"
181
+ 1, 13, 2,
182
+ // 0, () => i32
183
+ 96, 0, 1, 127,
184
+ // 1, (i32, i32, i32, i32) => i32
185
+ 96, 4, 127, 127, 127, 127, 1, 127,
186
+
187
+ // section "function"
188
+ 3, 7, 6,
189
+ // 0, type 0
190
+ 0,
191
+ // 1, type 1
192
+ 1,
193
+ // 2, type 1
194
+ 1,
195
+ // 3, type 1
196
+ 1,
197
+ // 4, type 1
198
+ 1,
199
+ // 5, type 1
200
+ 1,
201
+
202
+ // section "global"
203
+ 6, 6, 1,
204
+ // 0, "high", mutable i32
205
+ 127, 1, 65, 0, 11,
206
+
207
+ // section "export"
208
+ 7, 50, 6,
209
+ // 0, "mul"
210
+ 3, 109, 117, 108, 0, 1,
211
+ // 1, "div_s"
212
+ 5, 100, 105, 118, 95, 115, 0, 2,
213
+ // 2, "div_u"
214
+ 5, 100, 105, 118, 95, 117, 0, 3,
215
+ // 3, "rem_s"
216
+ 5, 114, 101, 109, 95, 115, 0, 4,
217
+ // 4, "rem_u"
218
+ 5, 114, 101, 109, 95, 117, 0, 5,
219
+ // 5, "get_high"
220
+ 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0,
221
+
222
+ // section "code"
223
+ 10, 191, 1, 6,
224
+ // 0, "get_high"
225
+ 4, 0, 35, 0, 11,
226
+ // 1, "mul"
227
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
228
+ 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
229
+ 167, 11,
230
+ // 2, "div_s"
231
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
232
+ 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
233
+ 167, 11,
234
+ // 3, "div_u"
235
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
236
+ 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
237
+ 167, 11,
238
+ // 4, "rem_s"
239
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
240
+ 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
241
+ 167, 11,
242
+ // 5, "rem_u"
243
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
244
+ 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
245
+ 167, 11,
246
+ ]),
247
+ ),
248
+ {},
249
+ ).exports;
250
+ } catch {
125
251
  // no wasm support :(
126
252
  }
127
253
 
@@ -136,7 +262,6 @@ try {
136
262
  * @constructor
137
263
  */
138
264
  function Long(low, high, unsigned) {
139
-
140
265
  /**
141
266
  * The low 32 bits as a signed value.
142
267
  * @type {number}
@@ -236,25 +361,21 @@ function fromInt(value, unsigned) {
236
361
  var obj, cachedObj, cache;
237
362
  if (unsigned) {
238
363
  value >>>= 0;
239
- if (cache = (0 <= value && value < 256)) {
364
+ if ((cache = 0 <= value && value < 256)) {
240
365
  cachedObj = UINT_CACHE[value];
241
- if (cachedObj)
242
- return cachedObj;
366
+ if (cachedObj) return cachedObj;
243
367
  }
244
368
  obj = fromBits(value, 0, true);
245
- if (cache)
246
- UINT_CACHE[value] = obj;
369
+ if (cache) UINT_CACHE[value] = obj;
247
370
  return obj;
248
371
  } else {
249
372
  value |= 0;
250
- if (cache = (-128 <= value && value < 128)) {
373
+ if ((cache = -128 <= value && value < 128)) {
251
374
  cachedObj = INT_CACHE[value];
252
- if (cachedObj)
253
- return cachedObj;
375
+ if (cachedObj) return cachedObj;
254
376
  }
255
377
  obj = fromBits(value, value < 0 ? -1 : 0, false);
256
- if (cache)
257
- INT_CACHE[value] = obj;
378
+ if (cache) INT_CACHE[value] = obj;
258
379
  return obj;
259
380
  }
260
381
  }
@@ -275,22 +396,20 @@ Long.fromInt = fromInt;
275
396
  * @inner
276
397
  */
277
398
  function fromNumber(value, unsigned) {
278
- if (isNaN(value))
279
- return unsigned ? UZERO : ZERO;
399
+ if (isNaN(value)) return unsigned ? UZERO : ZERO;
280
400
  if (unsigned) {
281
- if (value < 0)
282
- return UZERO;
283
- if (value >= TWO_PWR_64_DBL)
284
- return MAX_UNSIGNED_VALUE;
401
+ if (value < 0) return UZERO;
402
+ if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
285
403
  } else {
286
- if (value <= -9223372036854776e3)
287
- return MIN_VALUE;
288
- if (value + 1 >= TWO_PWR_63_DBL)
289
- return MAX_VALUE;
404
+ if (value <= -9223372036854776e3) return MIN_VALUE;
405
+ if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
290
406
  }
291
- if (value < 0)
292
- return fromNumber(-value, unsigned).neg();
293
- return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
407
+ if (value < 0) return fromNumber(-value, unsigned).neg();
408
+ return fromBits(
409
+ value % TWO_PWR_32_DBL | 0,
410
+ (value / TWO_PWR_32_DBL) | 0,
411
+ unsigned,
412
+ );
294
413
  }
295
414
 
296
415
  /**
@@ -341,24 +460,26 @@ var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
341
460
  * @inner
342
461
  */
343
462
  function fromString(str, unsigned, radix) {
344
- if (str.length === 0)
345
- throw Error('empty string');
346
- if (typeof unsigned === 'number') {
463
+ if (str.length === 0) throw Error("empty string");
464
+ if (typeof unsigned === "number") {
347
465
  // For goog.math.long compatibility
348
466
  radix = unsigned;
349
467
  unsigned = false;
350
468
  } else {
351
469
  unsigned = !!unsigned;
352
470
  }
353
- if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
471
+ if (
472
+ str === "NaN" ||
473
+ str === "Infinity" ||
474
+ str === "+Infinity" ||
475
+ str === "-Infinity"
476
+ )
354
477
  return unsigned ? UZERO : ZERO;
355
478
  radix = radix || 10;
356
- if (radix < 2 || 36 < radix)
357
- throw RangeError('radix');
479
+ if (radix < 2 || 36 < radix) throw RangeError("radix");
358
480
 
359
481
  var p;
360
- if ((p = str.indexOf('-')) > 0)
361
- throw Error('interior hyphen');
482
+ if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen");
362
483
  else if (p === 0) {
363
484
  return fromString(str.substring(1), unsigned, radix).neg();
364
485
  }
@@ -401,18 +522,20 @@ Long.fromString = fromString;
401
522
  * @inner
402
523
  */
403
524
  function fromValue(val, unsigned) {
404
- if (typeof val === 'number')
405
- return fromNumber(val, unsigned);
406
- if (typeof val === 'string')
407
- return fromString(val, unsigned);
525
+ if (typeof val === "number") return fromNumber(val, unsigned);
526
+ if (typeof val === "string") return fromString(val, unsigned);
408
527
  // Throws for non-objects, converts non-instanceof Long:
409
- return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
528
+ return fromBits(
529
+ val.low,
530
+ val.high,
531
+ typeof unsigned === "boolean" ? unsigned : val.unsigned,
532
+ );
410
533
  }
411
534
 
412
535
  /**
413
536
  * Converts the specified value to a Long using the appropriate from* function for its type.
414
537
  * @function
415
- * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
538
+ * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value
416
539
  * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
417
540
  * @returns {!Long}
418
541
  */
@@ -527,7 +650,7 @@ Long.NEG_ONE = NEG_ONE;
527
650
  * @type {!Long}
528
651
  * @inner
529
652
  */
530
- var MAX_VALUE = fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0, false);
653
+ var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
531
654
 
532
655
  /**
533
656
  * Maximum signed value.
@@ -539,7 +662,7 @@ Long.MAX_VALUE = MAX_VALUE;
539
662
  * @type {!Long}
540
663
  * @inner
541
664
  */
542
- var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF | 0, 0xFFFFFFFF | 0, true);
665
+ var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true);
543
666
 
544
667
  /**
545
668
  * Maximum unsigned value.
@@ -581,7 +704,7 @@ LongPrototype.toInt = function toInt() {
581
704
  */
582
705
  LongPrototype.toNumber = function toNumber() {
583
706
  if (this.unsigned)
584
- return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
707
+ return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
585
708
  return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
586
709
  };
587
710
 
@@ -595,11 +718,10 @@ LongPrototype.toNumber = function toNumber() {
595
718
  */
596
719
  LongPrototype.toString = function toString(radix) {
597
720
  radix = radix || 10;
598
- if (radix < 2 || 36 < radix)
599
- throw RangeError('radix');
600
- if (this.isZero())
601
- return '0';
602
- if (this.isNegative()) { // Unsigned Longs are never negative
721
+ if (radix < 2 || 36 < radix) throw RangeError("radix");
722
+ if (this.isZero()) return "0";
723
+ if (this.isNegative()) {
724
+ // Unsigned Longs are never negative
603
725
  if (this.eq(MIN_VALUE)) {
604
726
  // We need to change the Long value before it can be negated, so we remove
605
727
  // the bottom-most digit in this base and then recurse to do the rest.
@@ -607,26 +729,23 @@ LongPrototype.toString = function toString(radix) {
607
729
  div = this.div(radixLong),
608
730
  rem1 = div.mul(radixLong).sub(this);
609
731
  return div.toString(radix) + rem1.toInt().toString(radix);
610
- } else
611
- return '-' + this.neg().toString(radix);
732
+ } else return "-" + this.neg().toString(radix);
612
733
  }
613
734
 
614
735
  // Do several (6) digits each time through the loop, so as to
615
736
  // minimize the calls to the very expensive emulated div.
616
737
  var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
617
738
  rem = this;
618
- var result = '';
739
+ var result = "";
619
740
  while (true) {
620
741
  var remDiv = rem.div(radixToPower),
621
742
  intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
622
743
  digits = intval.toString(radix);
623
744
  rem = remDiv;
624
- if (rem.isZero())
625
- return digits + result;
745
+ if (rem.isZero()) return digits + result;
626
746
  else {
627
- while (digits.length < 6)
628
- digits = '0' + digits;
629
- result = '' + digits + result;
747
+ while (digits.length < 6) digits = "0" + digits;
748
+ result = "" + digits + result;
630
749
  }
631
750
  }
632
751
  };
@@ -673,15 +792,30 @@ LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
673
792
  * @returns {number}
674
793
  */
675
794
  LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
676
- if (this.isNegative()) // Unsigned Longs are never negative
795
+ if (this.isNegative())
796
+ // Unsigned Longs are never negative
677
797
  return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
678
798
  var val = this.high != 0 ? this.high : this.low;
679
- for (var bit = 31; bit > 0; bit--)
680
- if ((val & (1 << bit)) != 0)
681
- break;
799
+ for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break;
682
800
  return this.high != 0 ? bit + 33 : bit + 1;
683
801
  };
684
802
 
803
+ /**
804
+ * Tests if this Long can be safely represented as a JavaScript number.
805
+ * @this {!Long}
806
+ * @returns {boolean}
807
+ */
808
+ LongPrototype.isSafeInteger = function isSafeInteger() {
809
+ // 2^53-1 is the maximum safe value
810
+ var top11Bits = this.high >> 21;
811
+ // [0, 2^53-1]
812
+ if (!top11Bits) return true;
813
+ // > 2^53-1
814
+ if (this.unsigned) return false;
815
+ // [-2^53, -1] except -2^53
816
+ return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
817
+ };
818
+
685
819
  /**
686
820
  * Tests if this Long's value equals zero.
687
821
  * @this {!Long}
@@ -736,13 +870,16 @@ LongPrototype.isEven = function isEven() {
736
870
  /**
737
871
  * Tests if this Long's value equals the specified's.
738
872
  * @this {!Long}
739
- * @param {!Long|number|string} other Other value
873
+ * @param {!Long|number|bigint|string} other Other value
740
874
  * @returns {boolean}
741
875
  */
742
876
  LongPrototype.equals = function equals(other) {
743
- if (!isLong(other))
744
- other = fromValue(other);
745
- if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
877
+ if (!isLong(other)) other = fromValue(other);
878
+ if (
879
+ this.unsigned !== other.unsigned &&
880
+ this.high >>> 31 === 1 &&
881
+ other.high >>> 31 === 1
882
+ )
746
883
  return false;
747
884
  return this.high === other.high && this.low === other.low;
748
885
  };
@@ -750,7 +887,7 @@ LongPrototype.equals = function equals(other) {
750
887
  /**
751
888
  * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
752
889
  * @function
753
- * @param {!Long|number|string} other Other value
890
+ * @param {!Long|number|bigint|string} other Other value
754
891
  * @returns {boolean}
755
892
  */
756
893
  LongPrototype.eq = LongPrototype.equals;
@@ -758,7 +895,7 @@ LongPrototype.eq = LongPrototype.equals;
758
895
  /**
759
896
  * Tests if this Long's value differs from the specified's.
760
897
  * @this {!Long}
761
- * @param {!Long|number|string} other Other value
898
+ * @param {!Long|number|bigint|string} other Other value
762
899
  * @returns {boolean}
763
900
  */
764
901
  LongPrototype.notEquals = function notEquals(other) {
@@ -768,7 +905,7 @@ LongPrototype.notEquals = function notEquals(other) {
768
905
  /**
769
906
  * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
770
907
  * @function
771
- * @param {!Long|number|string} other Other value
908
+ * @param {!Long|number|bigint|string} other Other value
772
909
  * @returns {boolean}
773
910
  */
774
911
  LongPrototype.neq = LongPrototype.notEquals;
@@ -776,7 +913,7 @@ LongPrototype.neq = LongPrototype.notEquals;
776
913
  /**
777
914
  * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
778
915
  * @function
779
- * @param {!Long|number|string} other Other value
916
+ * @param {!Long|number|bigint|string} other Other value
780
917
  * @returns {boolean}
781
918
  */
782
919
  LongPrototype.ne = LongPrototype.notEquals;
@@ -784,7 +921,7 @@ LongPrototype.ne = LongPrototype.notEquals;
784
921
  /**
785
922
  * Tests if this Long's value is less than the specified's.
786
923
  * @this {!Long}
787
- * @param {!Long|number|string} other Other value
924
+ * @param {!Long|number|bigint|string} other Other value
788
925
  * @returns {boolean}
789
926
  */
790
927
  LongPrototype.lessThan = function lessThan(other) {
@@ -794,7 +931,7 @@ LongPrototype.lessThan = function lessThan(other) {
794
931
  /**
795
932
  * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
796
933
  * @function
797
- * @param {!Long|number|string} other Other value
934
+ * @param {!Long|number|bigint|string} other Other value
798
935
  * @returns {boolean}
799
936
  */
800
937
  LongPrototype.lt = LongPrototype.lessThan;
@@ -802,7 +939,7 @@ LongPrototype.lt = LongPrototype.lessThan;
802
939
  /**
803
940
  * Tests if this Long's value is less than or equal the specified's.
804
941
  * @this {!Long}
805
- * @param {!Long|number|string} other Other value
942
+ * @param {!Long|number|bigint|string} other Other value
806
943
  * @returns {boolean}
807
944
  */
808
945
  LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
@@ -812,7 +949,7 @@ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
812
949
  /**
813
950
  * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
814
951
  * @function
815
- * @param {!Long|number|string} other Other value
952
+ * @param {!Long|number|bigint|string} other Other value
816
953
  * @returns {boolean}
817
954
  */
818
955
  LongPrototype.lte = LongPrototype.lessThanOrEqual;
@@ -820,7 +957,7 @@ LongPrototype.lte = LongPrototype.lessThanOrEqual;
820
957
  /**
821
958
  * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
822
959
  * @function
823
- * @param {!Long|number|string} other Other value
960
+ * @param {!Long|number|bigint|string} other Other value
824
961
  * @returns {boolean}
825
962
  */
826
963
  LongPrototype.le = LongPrototype.lessThanOrEqual;
@@ -828,7 +965,7 @@ LongPrototype.le = LongPrototype.lessThanOrEqual;
828
965
  /**
829
966
  * Tests if this Long's value is greater than the specified's.
830
967
  * @this {!Long}
831
- * @param {!Long|number|string} other Other value
968
+ * @param {!Long|number|bigint|string} other Other value
832
969
  * @returns {boolean}
833
970
  */
834
971
  LongPrototype.greaterThan = function greaterThan(other) {
@@ -838,7 +975,7 @@ LongPrototype.greaterThan = function greaterThan(other) {
838
975
  /**
839
976
  * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
840
977
  * @function
841
- * @param {!Long|number|string} other Other value
978
+ * @param {!Long|number|bigint|string} other Other value
842
979
  * @returns {boolean}
843
980
  */
844
981
  LongPrototype.gt = LongPrototype.greaterThan;
@@ -846,7 +983,7 @@ LongPrototype.gt = LongPrototype.greaterThan;
846
983
  /**
847
984
  * Tests if this Long's value is greater than or equal the specified's.
848
985
  * @this {!Long}
849
- * @param {!Long|number|string} other Other value
986
+ * @param {!Long|number|bigint|string} other Other value
850
987
  * @returns {boolean}
851
988
  */
852
989
  LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
@@ -856,7 +993,7 @@ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
856
993
  /**
857
994
  * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
858
995
  * @function
859
- * @param {!Long|number|string} other Other value
996
+ * @param {!Long|number|bigint|string} other Other value
860
997
  * @returns {boolean}
861
998
  */
862
999
  LongPrototype.gte = LongPrototype.greaterThanOrEqual;
@@ -864,7 +1001,7 @@ LongPrototype.gte = LongPrototype.greaterThanOrEqual;
864
1001
  /**
865
1002
  * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
866
1003
  * @function
867
- * @param {!Long|number|string} other Other value
1004
+ * @param {!Long|number|bigint|string} other Other value
868
1005
  * @returns {boolean}
869
1006
  */
870
1007
  LongPrototype.ge = LongPrototype.greaterThanOrEqual;
@@ -872,32 +1009,30 @@ LongPrototype.ge = LongPrototype.greaterThanOrEqual;
872
1009
  /**
873
1010
  * Compares this Long's value with the specified's.
874
1011
  * @this {!Long}
875
- * @param {!Long|number|string} other Other value
1012
+ * @param {!Long|number|bigint|string} other Other value
876
1013
  * @returns {number} 0 if they are the same, 1 if the this is greater and -1
877
1014
  * if the given one is greater
878
1015
  */
879
1016
  LongPrototype.compare = function compare(other) {
880
- if (!isLong(other))
881
- other = fromValue(other);
882
- if (this.eq(other))
883
- return 0;
1017
+ if (!isLong(other)) other = fromValue(other);
1018
+ if (this.eq(other)) return 0;
884
1019
  var thisNeg = this.isNegative(),
885
1020
  otherNeg = other.isNegative();
886
- if (thisNeg && !otherNeg)
887
- return -1;
888
- if (!thisNeg && otherNeg)
889
- return 1;
1021
+ if (thisNeg && !otherNeg) return -1;
1022
+ if (!thisNeg && otherNeg) return 1;
890
1023
  // At this point the sign bits are the same
891
- if (!this.unsigned)
892
- return this.sub(other).isNegative() ? -1 : 1;
1024
+ if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;
893
1025
  // Both are positive if at least one is unsigned
894
- return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
1026
+ return other.high >>> 0 > this.high >>> 0 ||
1027
+ (other.high === this.high && other.low >>> 0 > this.low >>> 0)
1028
+ ? -1
1029
+ : 1;
895
1030
  };
896
1031
 
897
1032
  /**
898
1033
  * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
899
1034
  * @function
900
- * @param {!Long|number|string} other Other value
1035
+ * @param {!Long|number|bigint|string} other Other value
901
1036
  * @returns {number} 0 if they are the same, 1 if the this is greater and -1
902
1037
  * if the given one is greater
903
1038
  */
@@ -909,8 +1044,7 @@ LongPrototype.comp = LongPrototype.compare;
909
1044
  * @returns {!Long} Negated Long
910
1045
  */
911
1046
  LongPrototype.negate = function negate() {
912
- if (!this.unsigned && this.eq(MIN_VALUE))
913
- return MIN_VALUE;
1047
+ if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE;
914
1048
  return this.not().add(ONE);
915
1049
  };
916
1050
 
@@ -924,56 +1058,57 @@ LongPrototype.neg = LongPrototype.negate;
924
1058
  /**
925
1059
  * Returns the sum of this and the specified Long.
926
1060
  * @this {!Long}
927
- * @param {!Long|number|string} addend Addend
1061
+ * @param {!Long|number|bigint|string} addend Addend
928
1062
  * @returns {!Long} Sum
929
1063
  */
930
1064
  LongPrototype.add = function add(addend) {
931
- if (!isLong(addend))
932
- addend = fromValue(addend);
1065
+ if (!isLong(addend)) addend = fromValue(addend);
933
1066
 
934
1067
  // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
935
1068
 
936
1069
  var a48 = this.high >>> 16;
937
- var a32 = this.high & 0xFFFF;
1070
+ var a32 = this.high & 0xffff;
938
1071
  var a16 = this.low >>> 16;
939
- var a00 = this.low & 0xFFFF;
1072
+ var a00 = this.low & 0xffff;
940
1073
 
941
1074
  var b48 = addend.high >>> 16;
942
- var b32 = addend.high & 0xFFFF;
1075
+ var b32 = addend.high & 0xffff;
943
1076
  var b16 = addend.low >>> 16;
944
- var b00 = addend.low & 0xFFFF;
1077
+ var b00 = addend.low & 0xffff;
945
1078
 
946
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
1079
+ var c48 = 0,
1080
+ c32 = 0,
1081
+ c16 = 0,
1082
+ c00 = 0;
947
1083
  c00 += a00 + b00;
948
1084
  c16 += c00 >>> 16;
949
- c00 &= 0xFFFF;
1085
+ c00 &= 0xffff;
950
1086
  c16 += a16 + b16;
951
1087
  c32 += c16 >>> 16;
952
- c16 &= 0xFFFF;
1088
+ c16 &= 0xffff;
953
1089
  c32 += a32 + b32;
954
1090
  c48 += c32 >>> 16;
955
- c32 &= 0xFFFF;
1091
+ c32 &= 0xffff;
956
1092
  c48 += a48 + b48;
957
- c48 &= 0xFFFF;
1093
+ c48 &= 0xffff;
958
1094
  return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
959
1095
  };
960
1096
 
961
1097
  /**
962
1098
  * Returns the difference of this and the specified Long.
963
1099
  * @this {!Long}
964
- * @param {!Long|number|string} subtrahend Subtrahend
1100
+ * @param {!Long|number|bigint|string} subtrahend Subtrahend
965
1101
  * @returns {!Long} Difference
966
1102
  */
967
1103
  LongPrototype.subtract = function subtract(subtrahend) {
968
- if (!isLong(subtrahend))
969
- subtrahend = fromValue(subtrahend);
1104
+ if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend);
970
1105
  return this.add(subtrahend.neg());
971
1106
  };
972
1107
 
973
1108
  /**
974
1109
  * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
975
1110
  * @function
976
- * @param {!Long|number|string} subtrahend Subtrahend
1111
+ * @param {!Long|number|bigint|string} subtrahend Subtrahend
977
1112
  * @returns {!Long} Difference
978
1113
  */
979
1114
  LongPrototype.sub = LongPrototype.subtract;
@@ -981,38 +1116,27 @@ LongPrototype.sub = LongPrototype.subtract;
981
1116
  /**
982
1117
  * Returns the product of this and the specified Long.
983
1118
  * @this {!Long}
984
- * @param {!Long|number|string} multiplier Multiplier
1119
+ * @param {!Long|number|bigint|string} multiplier Multiplier
985
1120
  * @returns {!Long} Product
986
1121
  */
987
1122
  LongPrototype.multiply = function multiply(multiplier) {
988
- if (this.isZero())
989
- return this;
990
- if (!isLong(multiplier))
991
- multiplier = fromValue(multiplier);
1123
+ if (this.isZero()) return this;
1124
+ if (!isLong(multiplier)) multiplier = fromValue(multiplier);
992
1125
 
993
1126
  // use wasm support if present
994
1127
  if (wasm) {
995
- var low = wasm["mul"](this.low,
996
- this.high,
997
- multiplier.low,
998
- multiplier.high);
1128
+ var low = wasm["mul"](this.low, this.high, multiplier.low, multiplier.high);
999
1129
  return fromBits(low, wasm["get_high"](), this.unsigned);
1000
1130
  }
1001
1131
 
1002
- if (multiplier.isZero())
1003
- return this.unsigned ? UZERO : ZERO;
1004
- if (this.eq(MIN_VALUE))
1005
- return multiplier.isOdd() ? MIN_VALUE : ZERO;
1006
- if (multiplier.eq(MIN_VALUE))
1007
- return this.isOdd() ? MIN_VALUE : ZERO;
1132
+ if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO;
1133
+ if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO;
1134
+ if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO;
1008
1135
 
1009
1136
  if (this.isNegative()) {
1010
- if (multiplier.isNegative())
1011
- return this.neg().mul(multiplier.neg());
1012
- else
1013
- return this.neg().mul(multiplier).neg();
1014
- } else if (multiplier.isNegative())
1015
- return this.mul(multiplier.neg()).neg();
1137
+ if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
1138
+ else return this.neg().mul(multiplier).neg();
1139
+ } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg();
1016
1140
 
1017
1141
  // If both longs are small, use float multiplication
1018
1142
  if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
@@ -1022,43 +1146,46 @@ LongPrototype.multiply = function multiply(multiplier) {
1022
1146
  // We can skip products that would overflow.
1023
1147
 
1024
1148
  var a48 = this.high >>> 16;
1025
- var a32 = this.high & 0xFFFF;
1149
+ var a32 = this.high & 0xffff;
1026
1150
  var a16 = this.low >>> 16;
1027
- var a00 = this.low & 0xFFFF;
1151
+ var a00 = this.low & 0xffff;
1028
1152
 
1029
1153
  var b48 = multiplier.high >>> 16;
1030
- var b32 = multiplier.high & 0xFFFF;
1154
+ var b32 = multiplier.high & 0xffff;
1031
1155
  var b16 = multiplier.low >>> 16;
1032
- var b00 = multiplier.low & 0xFFFF;
1156
+ var b00 = multiplier.low & 0xffff;
1033
1157
 
1034
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
1158
+ var c48 = 0,
1159
+ c32 = 0,
1160
+ c16 = 0,
1161
+ c00 = 0;
1035
1162
  c00 += a00 * b00;
1036
1163
  c16 += c00 >>> 16;
1037
- c00 &= 0xFFFF;
1164
+ c00 &= 0xffff;
1038
1165
  c16 += a16 * b00;
1039
1166
  c32 += c16 >>> 16;
1040
- c16 &= 0xFFFF;
1167
+ c16 &= 0xffff;
1041
1168
  c16 += a00 * b16;
1042
1169
  c32 += c16 >>> 16;
1043
- c16 &= 0xFFFF;
1170
+ c16 &= 0xffff;
1044
1171
  c32 += a32 * b00;
1045
1172
  c48 += c32 >>> 16;
1046
- c32 &= 0xFFFF;
1173
+ c32 &= 0xffff;
1047
1174
  c32 += a16 * b16;
1048
1175
  c48 += c32 >>> 16;
1049
- c32 &= 0xFFFF;
1176
+ c32 &= 0xffff;
1050
1177
  c32 += a00 * b32;
1051
1178
  c48 += c32 >>> 16;
1052
- c32 &= 0xFFFF;
1179
+ c32 &= 0xffff;
1053
1180
  c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
1054
- c48 &= 0xFFFF;
1181
+ c48 &= 0xffff;
1055
1182
  return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
1056
1183
  };
1057
1184
 
1058
1185
  /**
1059
1186
  * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
1060
1187
  * @function
1061
- * @param {!Long|number|string} multiplier Multiplier
1188
+ * @param {!Long|number|bigint|string} multiplier Multiplier
1062
1189
  * @returns {!Long} Product
1063
1190
  */
1064
1191
  LongPrototype.mul = LongPrototype.multiply;
@@ -1067,23 +1194,24 @@ LongPrototype.mul = LongPrototype.multiply;
1067
1194
  * Returns this Long divided by the specified. The result is signed if this Long is signed or
1068
1195
  * unsigned if this Long is unsigned.
1069
1196
  * @this {!Long}
1070
- * @param {!Long|number|string} divisor Divisor
1197
+ * @param {!Long|number|bigint|string} divisor Divisor
1071
1198
  * @returns {!Long} Quotient
1072
1199
  */
1073
1200
  LongPrototype.divide = function divide(divisor) {
1074
- if (!isLong(divisor))
1075
- divisor = fromValue(divisor);
1076
- if (divisor.isZero())
1077
- throw Error('division by zero');
1201
+ if (!isLong(divisor)) divisor = fromValue(divisor);
1202
+ if (divisor.isZero()) throw Error("division by zero");
1078
1203
 
1079
1204
  // use wasm support if present
1080
1205
  if (wasm) {
1081
1206
  // guard against signed division overflow: the largest
1082
1207
  // negative number / -1 would be 1 larger than the largest
1083
1208
  // positive number, due to two's complement.
1084
- if (!this.unsigned &&
1209
+ if (
1210
+ !this.unsigned &&
1085
1211
  this.high === -2147483648 &&
1086
- divisor.low === -1 && divisor.high === -1) {
1212
+ divisor.low === -1 &&
1213
+ divisor.high === -1
1214
+ ) {
1087
1215
  // be consistent with non-wasm code path
1088
1216
  return this;
1089
1217
  }
@@ -1091,22 +1219,20 @@ LongPrototype.divide = function divide(divisor) {
1091
1219
  this.low,
1092
1220
  this.high,
1093
1221
  divisor.low,
1094
- divisor.high
1222
+ divisor.high,
1095
1223
  );
1096
1224
  return fromBits(low, wasm["get_high"](), this.unsigned);
1097
1225
  }
1098
1226
 
1099
- if (this.isZero())
1100
- return this.unsigned ? UZERO : ZERO;
1227
+ if (this.isZero()) return this.unsigned ? UZERO : ZERO;
1101
1228
  var approx, rem, res;
1102
1229
  if (!this.unsigned) {
1103
1230
  // This section is only relevant for signed longs and is derived from the
1104
1231
  // closure library as a whole.
1105
1232
  if (this.eq(MIN_VALUE)) {
1106
1233
  if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
1107
- return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
1108
- else if (divisor.eq(MIN_VALUE))
1109
- return ONE;
1234
+ return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
1235
+ else if (divisor.eq(MIN_VALUE)) return ONE;
1110
1236
  else {
1111
1237
  // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
1112
1238
  var halfThis = this.shr(1);
@@ -1119,23 +1245,19 @@ LongPrototype.divide = function divide(divisor) {
1119
1245
  return res;
1120
1246
  }
1121
1247
  }
1122
- } else if (divisor.eq(MIN_VALUE))
1123
- return this.unsigned ? UZERO : ZERO;
1248
+ } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO;
1124
1249
  if (this.isNegative()) {
1125
- if (divisor.isNegative())
1126
- return this.neg().div(divisor.neg());
1250
+ if (divisor.isNegative()) return this.neg().div(divisor.neg());
1127
1251
  return this.neg().div(divisor).neg();
1128
- } else if (divisor.isNegative())
1129
- return this.div(divisor.neg()).neg();
1252
+ } else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
1130
1253
  res = ZERO;
1131
1254
  } else {
1132
1255
  // The algorithm below has not been made for unsigned longs. It's therefore
1133
1256
  // required to take special care of the MSB prior to running it.
1134
- if (!divisor.unsigned)
1135
- divisor = divisor.toUnsigned();
1136
- if (divisor.gt(this))
1137
- return UZERO;
1138
- if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
1257
+ if (!divisor.unsigned) divisor = divisor.toUnsigned();
1258
+ if (divisor.gt(this)) return UZERO;
1259
+ if (divisor.gt(this.shru(1)))
1260
+ // 15 >>> 1 = 7 ; with divisor = 8 ; true
1139
1261
  return UONE;
1140
1262
  res = UZERO;
1141
1263
  }
@@ -1154,8 +1276,7 @@ LongPrototype.divide = function divide(divisor) {
1154
1276
  // We will tweak the approximate result by changing it in the 48-th digit or
1155
1277
  // the smallest non-fractional digit, whichever is larger.
1156
1278
  var log2 = Math.ceil(Math.log(approx) / Math.LN2),
1157
- delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
1158
-
1279
+ delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48),
1159
1280
  // Decrease the approximation until it is smaller than the remainder. Note
1160
1281
  // that if it is too large, the product overflows and is negative.
1161
1282
  approxRes = fromNumber(approx),
@@ -1168,8 +1289,7 @@ LongPrototype.divide = function divide(divisor) {
1168
1289
 
1169
1290
  // We know the answer can't be zero... and actually, zero would cause
1170
1291
  // infinite recursion since we would make no progress.
1171
- if (approxRes.isZero())
1172
- approxRes = ONE;
1292
+ if (approxRes.isZero()) approxRes = ONE;
1173
1293
 
1174
1294
  res = res.add(approxRes);
1175
1295
  rem = rem.sub(approxRem);
@@ -1180,7 +1300,7 @@ LongPrototype.divide = function divide(divisor) {
1180
1300
  /**
1181
1301
  * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
1182
1302
  * @function
1183
- * @param {!Long|number|string} divisor Divisor
1303
+ * @param {!Long|number|bigint|string} divisor Divisor
1184
1304
  * @returns {!Long} Quotient
1185
1305
  */
1186
1306
  LongPrototype.div = LongPrototype.divide;
@@ -1188,12 +1308,11 @@ LongPrototype.div = LongPrototype.divide;
1188
1308
  /**
1189
1309
  * Returns this Long modulo the specified.
1190
1310
  * @this {!Long}
1191
- * @param {!Long|number|string} divisor Divisor
1311
+ * @param {!Long|number|bigint|string} divisor Divisor
1192
1312
  * @returns {!Long} Remainder
1193
1313
  */
1194
1314
  LongPrototype.modulo = function modulo(divisor) {
1195
- if (!isLong(divisor))
1196
- divisor = fromValue(divisor);
1315
+ if (!isLong(divisor)) divisor = fromValue(divisor);
1197
1316
 
1198
1317
  // use wasm support if present
1199
1318
  if (wasm) {
@@ -1201,7 +1320,7 @@ LongPrototype.modulo = function modulo(divisor) {
1201
1320
  this.low,
1202
1321
  this.high,
1203
1322
  divisor.low,
1204
- divisor.high
1323
+ divisor.high,
1205
1324
  );
1206
1325
  return fromBits(low, wasm["get_high"](), this.unsigned);
1207
1326
  }
@@ -1212,7 +1331,7 @@ LongPrototype.modulo = function modulo(divisor) {
1212
1331
  /**
1213
1332
  * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
1214
1333
  * @function
1215
- * @param {!Long|number|string} divisor Divisor
1334
+ * @param {!Long|number|bigint|string} divisor Divisor
1216
1335
  * @returns {!Long} Remainder
1217
1336
  */
1218
1337
  LongPrototype.mod = LongPrototype.modulo;
@@ -1220,7 +1339,7 @@ LongPrototype.mod = LongPrototype.modulo;
1220
1339
  /**
1221
1340
  * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
1222
1341
  * @function
1223
- * @param {!Long|number|string} divisor Divisor
1342
+ * @param {!Long|number|bigint|string} divisor Divisor
1224
1343
  * @returns {!Long} Remainder
1225
1344
  */
1226
1345
  LongPrototype.rem = LongPrototype.modulo;
@@ -1271,36 +1390,33 @@ LongPrototype.ctz = LongPrototype.countTrailingZeros;
1271
1390
  /**
1272
1391
  * Returns the bitwise AND of this Long and the specified.
1273
1392
  * @this {!Long}
1274
- * @param {!Long|number|string} other Other Long
1393
+ * @param {!Long|number|bigint|string} other Other Long
1275
1394
  * @returns {!Long}
1276
1395
  */
1277
1396
  LongPrototype.and = function and(other) {
1278
- if (!isLong(other))
1279
- other = fromValue(other);
1397
+ if (!isLong(other)) other = fromValue(other);
1280
1398
  return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
1281
1399
  };
1282
1400
 
1283
1401
  /**
1284
1402
  * Returns the bitwise OR of this Long and the specified.
1285
1403
  * @this {!Long}
1286
- * @param {!Long|number|string} other Other Long
1404
+ * @param {!Long|number|bigint|string} other Other Long
1287
1405
  * @returns {!Long}
1288
1406
  */
1289
1407
  LongPrototype.or = function or(other) {
1290
- if (!isLong(other))
1291
- other = fromValue(other);
1408
+ if (!isLong(other)) other = fromValue(other);
1292
1409
  return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
1293
1410
  };
1294
1411
 
1295
1412
  /**
1296
1413
  * Returns the bitwise XOR of this Long and the given one.
1297
1414
  * @this {!Long}
1298
- * @param {!Long|number|string} other Other Long
1415
+ * @param {!Long|number|bigint|string} other Other Long
1299
1416
  * @returns {!Long}
1300
1417
  */
1301
1418
  LongPrototype.xor = function xor(other) {
1302
- if (!isLong(other))
1303
- other = fromValue(other);
1419
+ if (!isLong(other)) other = fromValue(other);
1304
1420
  return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
1305
1421
  };
1306
1422
 
@@ -1311,14 +1427,15 @@ LongPrototype.xor = function xor(other) {
1311
1427
  * @returns {!Long} Shifted Long
1312
1428
  */
1313
1429
  LongPrototype.shiftLeft = function shiftLeft(numBits) {
1314
- if (isLong(numBits))
1315
- numBits = numBits.toInt();
1316
- if ((numBits &= 63) === 0)
1317
- return this;
1430
+ if (isLong(numBits)) numBits = numBits.toInt();
1431
+ if ((numBits &= 63) === 0) return this;
1318
1432
  else if (numBits < 32)
1319
- return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
1320
- else
1321
- return fromBits(0, this.low << (numBits - 32), this.unsigned);
1433
+ return fromBits(
1434
+ this.low << numBits,
1435
+ (this.high << numBits) | (this.low >>> (32 - numBits)),
1436
+ this.unsigned,
1437
+ );
1438
+ else return fromBits(0, this.low << (numBits - 32), this.unsigned);
1322
1439
  };
1323
1440
 
1324
1441
  /**
@@ -1336,14 +1453,20 @@ LongPrototype.shl = LongPrototype.shiftLeft;
1336
1453
  * @returns {!Long} Shifted Long
1337
1454
  */
1338
1455
  LongPrototype.shiftRight = function shiftRight(numBits) {
1339
- if (isLong(numBits))
1340
- numBits = numBits.toInt();
1341
- if ((numBits &= 63) === 0)
1342
- return this;
1456
+ if (isLong(numBits)) numBits = numBits.toInt();
1457
+ if ((numBits &= 63) === 0) return this;
1343
1458
  else if (numBits < 32)
1344
- return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
1459
+ return fromBits(
1460
+ (this.low >>> numBits) | (this.high << (32 - numBits)),
1461
+ this.high >> numBits,
1462
+ this.unsigned,
1463
+ );
1345
1464
  else
1346
- return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
1465
+ return fromBits(
1466
+ this.high >> (numBits - 32),
1467
+ this.high >= 0 ? 0 : -1,
1468
+ this.unsigned,
1469
+ );
1347
1470
  };
1348
1471
 
1349
1472
  /**
@@ -1363,7 +1486,12 @@ LongPrototype.shr = LongPrototype.shiftRight;
1363
1486
  LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
1364
1487
  if (isLong(numBits)) numBits = numBits.toInt();
1365
1488
  if ((numBits &= 63) === 0) return this;
1366
- if (numBits < 32) return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >>> numBits, this.unsigned);
1489
+ if (numBits < 32)
1490
+ return fromBits(
1491
+ (this.low >>> numBits) | (this.high << (32 - numBits)),
1492
+ this.high >>> numBits,
1493
+ this.unsigned,
1494
+ );
1367
1495
  if (numBits === 32) return fromBits(this.high, 0, this.unsigned);
1368
1496
  return fromBits(this.high >>> (numBits - 32), 0, this.unsigned);
1369
1497
  };
@@ -1396,12 +1524,20 @@ LongPrototype.rotateLeft = function rotateLeft(numBits) {
1396
1524
  if ((numBits &= 63) === 0) return this;
1397
1525
  if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
1398
1526
  if (numBits < 32) {
1399
- b = (32 - numBits);
1400
- return fromBits(((this.low << numBits) | (this.high >>> b)), ((this.high << numBits) | (this.low >>> b)), this.unsigned);
1527
+ b = 32 - numBits;
1528
+ return fromBits(
1529
+ (this.low << numBits) | (this.high >>> b),
1530
+ (this.high << numBits) | (this.low >>> b),
1531
+ this.unsigned,
1532
+ );
1401
1533
  }
1402
1534
  numBits -= 32;
1403
- b = (32 - numBits);
1404
- return fromBits(((this.high << numBits) | (this.low >>> b)), ((this.low << numBits) | (this.high >>> b)), this.unsigned);
1535
+ b = 32 - numBits;
1536
+ return fromBits(
1537
+ (this.high << numBits) | (this.low >>> b),
1538
+ (this.low << numBits) | (this.high >>> b),
1539
+ this.unsigned,
1540
+ );
1405
1541
  };
1406
1542
  /**
1407
1543
  * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}.
@@ -1423,12 +1559,20 @@ LongPrototype.rotateRight = function rotateRight(numBits) {
1423
1559
  if ((numBits &= 63) === 0) return this;
1424
1560
  if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
1425
1561
  if (numBits < 32) {
1426
- b = (32 - numBits);
1427
- return fromBits(((this.high << b) | (this.low >>> numBits)), ((this.low << b) | (this.high >>> numBits)), this.unsigned);
1562
+ b = 32 - numBits;
1563
+ return fromBits(
1564
+ (this.high << b) | (this.low >>> numBits),
1565
+ (this.low << b) | (this.high >>> numBits),
1566
+ this.unsigned,
1567
+ );
1428
1568
  }
1429
1569
  numBits -= 32;
1430
- b = (32 - numBits);
1431
- return fromBits(((this.low << b) | (this.high >>> numBits)), ((this.high << b) | (this.low >>> numBits)), this.unsigned);
1570
+ b = 32 - numBits;
1571
+ return fromBits(
1572
+ (this.low << b) | (this.high >>> numBits),
1573
+ (this.high << b) | (this.low >>> numBits),
1574
+ this.unsigned,
1575
+ );
1432
1576
  };
1433
1577
  /**
1434
1578
  * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}.
@@ -1444,8 +1588,7 @@ LongPrototype.rotr = LongPrototype.rotateRight;
1444
1588
  * @returns {!Long} Signed long
1445
1589
  */
1446
1590
  LongPrototype.toSigned = function toSigned() {
1447
- if (!this.unsigned)
1448
- return this;
1591
+ if (!this.unsigned) return this;
1449
1592
  return fromBits(this.low, this.high, false);
1450
1593
  };
1451
1594
 
@@ -1455,8 +1598,7 @@ LongPrototype.toSigned = function toSigned() {
1455
1598
  * @returns {!Long} Unsigned long
1456
1599
  */
1457
1600
  LongPrototype.toUnsigned = function toUnsigned() {
1458
- if (this.unsigned)
1459
- return this;
1601
+ if (this.unsigned) return this;
1460
1602
  return fromBits(this.low, this.high, true);
1461
1603
  };
1462
1604
 
@@ -1480,13 +1622,13 @@ LongPrototype.toBytesLE = function toBytesLE() {
1480
1622
  lo = this.low;
1481
1623
  return [
1482
1624
  lo & 0xff,
1483
- lo >>> 8 & 0xff,
1484
- lo >>> 16 & 0xff,
1625
+ (lo >>> 8) & 0xff,
1626
+ (lo >>> 16) & 0xff,
1485
1627
  lo >>> 24,
1486
1628
  hi & 0xff,
1487
- hi >>> 8 & 0xff,
1488
- hi >>> 16 & 0xff,
1489
- hi >>> 24
1629
+ (hi >>> 8) & 0xff,
1630
+ (hi >>> 16) & 0xff,
1631
+ hi >>> 24,
1490
1632
  ];
1491
1633
  };
1492
1634
 
@@ -1500,13 +1642,13 @@ LongPrototype.toBytesBE = function toBytesBE() {
1500
1642
  lo = this.low;
1501
1643
  return [
1502
1644
  hi >>> 24,
1503
- hi >>> 16 & 0xff,
1504
- hi >>> 8 & 0xff,
1645
+ (hi >>> 16) & 0xff,
1646
+ (hi >>> 8) & 0xff,
1505
1647
  hi & 0xff,
1506
1648
  lo >>> 24,
1507
- lo >>> 16 & 0xff,
1508
- lo >>> 8 & 0xff,
1509
- lo & 0xff
1649
+ (lo >>> 16) & 0xff,
1650
+ (lo >>> 8) & 0xff,
1651
+ lo & 0xff,
1510
1652
  ];
1511
1653
  };
1512
1654
 
@@ -1518,7 +1660,9 @@ LongPrototype.toBytesBE = function toBytesBE() {
1518
1660
  * @returns {Long} The corresponding Long value
1519
1661
  */
1520
1662
  Long.fromBytes = function fromBytes(bytes, unsigned, le) {
1521
- return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
1663
+ return le
1664
+ ? Long.fromBytesLE(bytes, unsigned)
1665
+ : Long.fromBytesBE(bytes, unsigned);
1522
1666
  };
1523
1667
 
1524
1668
  /**
@@ -1529,15 +1673,9 @@ Long.fromBytes = function fromBytes(bytes, unsigned, le) {
1529
1673
  */
1530
1674
  Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
1531
1675
  return new Long(
1532
- bytes[0] |
1533
- bytes[1] << 8 |
1534
- bytes[2] << 16 |
1535
- bytes[3] << 24,
1536
- bytes[4] |
1537
- bytes[5] << 8 |
1538
- bytes[6] << 16 |
1539
- bytes[7] << 24,
1540
- unsigned
1676
+ bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24),
1677
+ bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24),
1678
+ unsigned,
1541
1679
  );
1542
1680
  };
1543
1681
 
@@ -1549,18 +1687,45 @@ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
1549
1687
  */
1550
1688
  Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
1551
1689
  return new Long(
1552
- bytes[4] << 24 |
1553
- bytes[5] << 16 |
1554
- bytes[6] << 8 |
1555
- bytes[7],
1556
- bytes[0] << 24 |
1557
- bytes[1] << 16 |
1558
- bytes[2] << 8 |
1559
- bytes[3],
1560
- unsigned
1690
+ (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7],
1691
+ (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],
1692
+ unsigned,
1561
1693
  );
1562
1694
  };
1563
1695
 
1696
+ // Support conversion to/from BigInt where available
1697
+ if (typeof BigInt === "function") {
1698
+ /**
1699
+ * Returns a Long representing the given big integer.
1700
+ * @function
1701
+ * @param {number} value The big integer value
1702
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
1703
+ * @returns {!Long} The corresponding Long value
1704
+ */
1705
+ Long.fromBigInt = function fromBigInt(value, unsigned) {
1706
+ var lowBits = Number(BigInt.asIntN(32, value));
1707
+ var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
1708
+ return fromBits(lowBits, highBits, unsigned);
1709
+ };
1710
+
1711
+ // Override
1712
+ Long.fromValue = function fromValueWithBigInt(value, unsigned) {
1713
+ if (typeof value === "bigint") return fromBigInt(value, unsigned);
1714
+ return fromValue(value, unsigned);
1715
+ };
1716
+
1717
+ /**
1718
+ * Converts the Long to its big integer representation.
1719
+ * @this {!Long}
1720
+ * @returns {bigint}
1721
+ */
1722
+ LongPrototype.toBigInt = function toBigInt() {
1723
+ var lowBigInt = BigInt(this.low >>> 0);
1724
+ var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
1725
+ return (highBigInt << BigInt(32)) | lowBigInt;
1726
+ };
1727
+ }
1728
+
1564
1729
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1565
1730
 
1566
1731
  function getDefaultExportFromCjs (x) {
@@ -4396,12 +4561,12 @@ const Struct = {
4396
4561
  return obj;
4397
4562
  },
4398
4563
  create(base) {
4399
- return Struct.fromPartial(base !== null && base !== undefined ? base : {});
4564
+ return Struct.fromPartial(base !== null && base !== void 0 ? base : {});
4400
4565
  },
4401
4566
  fromPartial(object) {
4402
4567
  var _a;
4403
4568
  const message = createBaseStruct();
4404
- message.fields = Object.entries((_a = object.fields) !== null && _a !== undefined ? _a : {}).reduce((acc, [key, value]) => {
4569
+ message.fields = Object.entries((_a = object.fields) !== null && _a !== void 0 ? _a : {}).reduce((acc, [key, value]) => {
4405
4570
  if (value !== undefined) {
4406
4571
  acc[key] = value;
4407
4572
  }
@@ -4469,7 +4634,7 @@ const Struct_FieldsEntry = {
4469
4634
  return message;
4470
4635
  },
4471
4636
  fromJSON(object) {
4472
- return { key: isSet$2(object.key) ? String(object.key) : "", value: isSet$2(object === null || object === undefined ? undefined : object.value) ? object.value : undefined };
4637
+ return { key: isSet$2(object.key) ? String(object.key) : "", value: isSet$2(object === null || object === void 0 ? void 0 : object.value) ? object.value : undefined };
4473
4638
  },
4474
4639
  toJSON(message) {
4475
4640
  const obj = {};
@@ -4482,13 +4647,13 @@ const Struct_FieldsEntry = {
4482
4647
  return obj;
4483
4648
  },
4484
4649
  create(base) {
4485
- return Struct_FieldsEntry.fromPartial(base !== null && base !== undefined ? base : {});
4650
+ return Struct_FieldsEntry.fromPartial(base !== null && base !== void 0 ? base : {});
4486
4651
  },
4487
4652
  fromPartial(object) {
4488
4653
  var _a, _b;
4489
4654
  const message = createBaseStruct_FieldsEntry();
4490
- message.key = (_a = object.key) !== null && _a !== undefined ? _a : "";
4491
- message.value = (_b = object.value) !== null && _b !== undefined ? _b : undefined;
4655
+ message.key = (_a = object.key) !== null && _a !== void 0 ? _a : "";
4656
+ message.value = (_b = object.value) !== null && _b !== void 0 ? _b : undefined;
4492
4657
  return message;
4493
4658
  },
4494
4659
  };
@@ -4608,17 +4773,17 @@ const Value = {
4608
4773
  return obj;
4609
4774
  },
4610
4775
  create(base) {
4611
- return Value.fromPartial(base !== null && base !== undefined ? base : {});
4776
+ return Value.fromPartial(base !== null && base !== void 0 ? base : {});
4612
4777
  },
4613
4778
  fromPartial(object) {
4614
4779
  var _a, _b, _c, _d, _e, _f;
4615
4780
  const message = createBaseValue();
4616
- message.nullValue = (_a = object.nullValue) !== null && _a !== undefined ? _a : undefined;
4617
- message.numberValue = (_b = object.numberValue) !== null && _b !== undefined ? _b : undefined;
4618
- message.stringValue = (_c = object.stringValue) !== null && _c !== undefined ? _c : undefined;
4619
- message.boolValue = (_d = object.boolValue) !== null && _d !== undefined ? _d : undefined;
4620
- message.structValue = (_e = object.structValue) !== null && _e !== undefined ? _e : undefined;
4621
- message.listValue = (_f = object.listValue) !== null && _f !== undefined ? _f : undefined;
4781
+ message.nullValue = (_a = object.nullValue) !== null && _a !== void 0 ? _a : undefined;
4782
+ message.numberValue = (_b = object.numberValue) !== null && _b !== void 0 ? _b : undefined;
4783
+ message.stringValue = (_c = object.stringValue) !== null && _c !== void 0 ? _c : undefined;
4784
+ message.boolValue = (_d = object.boolValue) !== null && _d !== void 0 ? _d : undefined;
4785
+ message.structValue = (_e = object.structValue) !== null && _e !== void 0 ? _e : undefined;
4786
+ message.listValue = (_f = object.listValue) !== null && _f !== void 0 ? _f : undefined;
4622
4787
  return message;
4623
4788
  },
4624
4789
  wrap(value) {
@@ -4650,19 +4815,19 @@ const Value = {
4650
4815
  if (message.stringValue !== undefined) {
4651
4816
  return message.stringValue;
4652
4817
  }
4653
- else if ((message === null || message === undefined ? undefined : message.numberValue) !== undefined) {
4818
+ else if ((message === null || message === void 0 ? void 0 : message.numberValue) !== undefined) {
4654
4819
  return message.numberValue;
4655
4820
  }
4656
- else if ((message === null || message === undefined ? undefined : message.boolValue) !== undefined) {
4821
+ else if ((message === null || message === void 0 ? void 0 : message.boolValue) !== undefined) {
4657
4822
  return message.boolValue;
4658
4823
  }
4659
- else if ((message === null || message === undefined ? undefined : message.structValue) !== undefined) {
4824
+ else if ((message === null || message === void 0 ? void 0 : message.structValue) !== undefined) {
4660
4825
  return message.structValue;
4661
4826
  }
4662
- else if ((message === null || message === undefined ? undefined : message.listValue) !== undefined) {
4827
+ else if ((message === null || message === void 0 ? void 0 : message.listValue) !== undefined) {
4663
4828
  return message.listValue;
4664
4829
  }
4665
- else if ((message === null || message === undefined ? undefined : message.nullValue) !== undefined) {
4830
+ else if ((message === null || message === void 0 ? void 0 : message.nullValue) !== undefined) {
4666
4831
  return null;
4667
4832
  }
4668
4833
  return undefined;
@@ -4700,32 +4865,32 @@ const ListValue = {
4700
4865
  return message;
4701
4866
  },
4702
4867
  fromJSON(object) {
4703
- return { values: Array.isArray(object === null || object === undefined ? undefined : object.values) ? [...object.values] : [] };
4868
+ return { values: Array.isArray(object === null || object === void 0 ? void 0 : object.values) ? [...object.values] : [] };
4704
4869
  },
4705
4870
  toJSON(message) {
4706
4871
  var _a;
4707
4872
  const obj = {};
4708
- if ((_a = message.values) === null || _a === undefined ? undefined : _a.length) {
4873
+ if ((_a = message.values) === null || _a === void 0 ? void 0 : _a.length) {
4709
4874
  obj.values = message.values;
4710
4875
  }
4711
4876
  return obj;
4712
4877
  },
4713
4878
  create(base) {
4714
- return ListValue.fromPartial(base !== null && base !== undefined ? base : {});
4879
+ return ListValue.fromPartial(base !== null && base !== void 0 ? base : {});
4715
4880
  },
4716
4881
  fromPartial(object) {
4717
4882
  var _a;
4718
4883
  const message = createBaseListValue();
4719
- message.values = ((_a = object.values) === null || _a === undefined ? undefined : _a.map((e) => e)) || [];
4884
+ message.values = ((_a = object.values) === null || _a === void 0 ? void 0 : _a.map((e) => e)) || [];
4720
4885
  return message;
4721
4886
  },
4722
4887
  wrap(array) {
4723
4888
  const result = createBaseListValue();
4724
- result.values = array !== null && array !== undefined ? array : [];
4889
+ result.values = array !== null && array !== void 0 ? array : [];
4725
4890
  return result;
4726
4891
  },
4727
4892
  unwrap(message) {
4728
- if ((message === null || message === undefined ? undefined : message.hasOwnProperty("values")) && Array.isArray(message.values)) {
4893
+ if ((message === null || message === void 0 ? void 0 : message.hasOwnProperty("values")) && Array.isArray(message.values)) {
4729
4894
  return message.values;
4730
4895
  }
4731
4896
  else {
@@ -4783,23 +4948,26 @@ const ResolveAllRequest = {
4783
4948
  return obj;
4784
4949
  },
4785
4950
  create(base) {
4786
- return ResolveAllRequest.fromPartial(base !== null && base !== undefined ? base : {});
4951
+ return ResolveAllRequest.fromPartial(base !== null && base !== void 0 ? base : {});
4787
4952
  },
4788
4953
  fromPartial(object) {
4789
4954
  var _a;
4790
4955
  const message = createBaseResolveAllRequest();
4791
- message.context = (_a = object.context) !== null && _a !== undefined ? _a : undefined;
4956
+ message.context = (_a = object.context) !== null && _a !== void 0 ? _a : undefined;
4792
4957
  return message;
4793
4958
  },
4794
4959
  };
4795
4960
  function createBaseResolveAllResponse() {
4796
- return { flags: {} };
4961
+ return { flags: {}, metadata: undefined };
4797
4962
  }
4798
4963
  const ResolveAllResponse = {
4799
4964
  encode(message, writer = _m0.Writer.create()) {
4800
4965
  Object.entries(message.flags).forEach(([key, value]) => {
4801
4966
  ResolveAllResponse_FlagsEntry.encode({ key: key, value }, writer.uint32(10).fork()).ldelim();
4802
4967
  });
4968
+ if (message.metadata !== undefined) {
4969
+ Struct.encode(Struct.wrap(message.metadata), writer.uint32(18).fork()).ldelim();
4970
+ }
4803
4971
  return writer;
4804
4972
  },
4805
4973
  decode(input, length) {
@@ -4818,6 +4986,12 @@ const ResolveAllResponse = {
4818
4986
  message.flags[entry1.key] = entry1.value;
4819
4987
  }
4820
4988
  continue;
4989
+ case 2:
4990
+ if (tag !== 18) {
4991
+ break;
4992
+ }
4993
+ message.metadata = Struct.unwrap(Struct.decode(reader, reader.uint32()));
4994
+ continue;
4821
4995
  }
4822
4996
  if ((tag & 7) === 4 || tag === 0) {
4823
4997
  break;
@@ -4834,6 +5008,7 @@ const ResolveAllResponse = {
4834
5008
  return acc;
4835
5009
  }, {})
4836
5010
  : {},
5011
+ metadata: isObject$1(object.metadata) ? object.metadata : undefined,
4837
5012
  };
4838
5013
  },
4839
5014
  toJSON(message) {
@@ -4847,20 +5022,24 @@ const ResolveAllResponse = {
4847
5022
  });
4848
5023
  }
4849
5024
  }
5025
+ if (message.metadata !== undefined) {
5026
+ obj.metadata = message.metadata;
5027
+ }
4850
5028
  return obj;
4851
5029
  },
4852
5030
  create(base) {
4853
- return ResolveAllResponse.fromPartial(base !== null && base !== undefined ? base : {});
5031
+ return ResolveAllResponse.fromPartial(base !== null && base !== void 0 ? base : {});
4854
5032
  },
4855
5033
  fromPartial(object) {
4856
- var _a;
5034
+ var _a, _b;
4857
5035
  const message = createBaseResolveAllResponse();
4858
- message.flags = Object.entries((_a = object.flags) !== null && _a !== undefined ? _a : {}).reduce((acc, [key, value]) => {
5036
+ message.flags = Object.entries((_a = object.flags) !== null && _a !== void 0 ? _a : {}).reduce((acc, [key, value]) => {
4859
5037
  if (value !== undefined) {
4860
5038
  acc[key] = AnyFlag.fromPartial(value);
4861
5039
  }
4862
5040
  return acc;
4863
5041
  }, {});
5042
+ message.metadata = (_b = object.metadata) !== null && _b !== void 0 ? _b : undefined;
4864
5043
  return message;
4865
5044
  },
4866
5045
  };
@@ -4921,12 +5100,12 @@ const ResolveAllResponse_FlagsEntry = {
4921
5100
  return obj;
4922
5101
  },
4923
5102
  create(base) {
4924
- return ResolveAllResponse_FlagsEntry.fromPartial(base !== null && base !== undefined ? base : {});
5103
+ return ResolveAllResponse_FlagsEntry.fromPartial(base !== null && base !== void 0 ? base : {});
4925
5104
  },
4926
5105
  fromPartial(object) {
4927
5106
  var _a;
4928
5107
  const message = createBaseResolveAllResponse_FlagsEntry();
4929
- message.key = (_a = object.key) !== null && _a !== undefined ? _a : "";
5108
+ message.key = (_a = object.key) !== null && _a !== void 0 ? _a : "";
4930
5109
  message.value = (object.value !== undefined && object.value !== null)
4931
5110
  ? AnyFlag.fromPartial(object.value)
4932
5111
  : undefined;
@@ -5063,18 +5242,18 @@ const AnyFlag = {
5063
5242
  return obj;
5064
5243
  },
5065
5244
  create(base) {
5066
- return AnyFlag.fromPartial(base !== null && base !== undefined ? base : {});
5245
+ return AnyFlag.fromPartial(base !== null && base !== void 0 ? base : {});
5067
5246
  },
5068
5247
  fromPartial(object) {
5069
5248
  var _a, _b, _c, _d, _e, _f, _g;
5070
5249
  const message = createBaseAnyFlag();
5071
- message.reason = (_a = object.reason) !== null && _a !== undefined ? _a : "";
5072
- message.variant = (_b = object.variant) !== null && _b !== undefined ? _b : "";
5073
- message.boolValue = (_c = object.boolValue) !== null && _c !== undefined ? _c : undefined;
5074
- message.stringValue = (_d = object.stringValue) !== null && _d !== undefined ? _d : undefined;
5075
- message.doubleValue = (_e = object.doubleValue) !== null && _e !== undefined ? _e : undefined;
5076
- message.objectValue = (_f = object.objectValue) !== null && _f !== undefined ? _f : undefined;
5077
- message.metadata = (_g = object.metadata) !== null && _g !== undefined ? _g : undefined;
5250
+ message.reason = (_a = object.reason) !== null && _a !== void 0 ? _a : "";
5251
+ message.variant = (_b = object.variant) !== null && _b !== void 0 ? _b : "";
5252
+ message.boolValue = (_c = object.boolValue) !== null && _c !== void 0 ? _c : undefined;
5253
+ message.stringValue = (_d = object.stringValue) !== null && _d !== void 0 ? _d : undefined;
5254
+ message.doubleValue = (_e = object.doubleValue) !== null && _e !== void 0 ? _e : undefined;
5255
+ message.objectValue = (_f = object.objectValue) !== null && _f !== void 0 ? _f : undefined;
5256
+ message.metadata = (_g = object.metadata) !== null && _g !== void 0 ? _g : undefined;
5078
5257
  return message;
5079
5258
  },
5080
5259
  };
@@ -5135,13 +5314,13 @@ const ResolveBooleanRequest = {
5135
5314
  return obj;
5136
5315
  },
5137
5316
  create(base) {
5138
- return ResolveBooleanRequest.fromPartial(base !== null && base !== undefined ? base : {});
5317
+ return ResolveBooleanRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5139
5318
  },
5140
5319
  fromPartial(object) {
5141
5320
  var _a, _b;
5142
5321
  const message = createBaseResolveBooleanRequest();
5143
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5144
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5322
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5323
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5145
5324
  return message;
5146
5325
  },
5147
5326
  };
@@ -5228,15 +5407,15 @@ const ResolveBooleanResponse = {
5228
5407
  return obj;
5229
5408
  },
5230
5409
  create(base) {
5231
- return ResolveBooleanResponse.fromPartial(base !== null && base !== undefined ? base : {});
5410
+ return ResolveBooleanResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5232
5411
  },
5233
5412
  fromPartial(object) {
5234
5413
  var _a, _b, _c, _d;
5235
5414
  const message = createBaseResolveBooleanResponse();
5236
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : false;
5237
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5238
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5239
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5415
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : false;
5416
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5417
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5418
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5240
5419
  return message;
5241
5420
  },
5242
5421
  };
@@ -5297,13 +5476,13 @@ const ResolveStringRequest = {
5297
5476
  return obj;
5298
5477
  },
5299
5478
  create(base) {
5300
- return ResolveStringRequest.fromPartial(base !== null && base !== undefined ? base : {});
5479
+ return ResolveStringRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5301
5480
  },
5302
5481
  fromPartial(object) {
5303
5482
  var _a, _b;
5304
5483
  const message = createBaseResolveStringRequest();
5305
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5306
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5484
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5485
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5307
5486
  return message;
5308
5487
  },
5309
5488
  };
@@ -5390,15 +5569,15 @@ const ResolveStringResponse = {
5390
5569
  return obj;
5391
5570
  },
5392
5571
  create(base) {
5393
- return ResolveStringResponse.fromPartial(base !== null && base !== undefined ? base : {});
5572
+ return ResolveStringResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5394
5573
  },
5395
5574
  fromPartial(object) {
5396
5575
  var _a, _b, _c, _d;
5397
5576
  const message = createBaseResolveStringResponse();
5398
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : "";
5399
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5400
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5401
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5577
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : "";
5578
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5579
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5580
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5402
5581
  return message;
5403
5582
  },
5404
5583
  };
@@ -5459,13 +5638,13 @@ const ResolveFloatRequest = {
5459
5638
  return obj;
5460
5639
  },
5461
5640
  create(base) {
5462
- return ResolveFloatRequest.fromPartial(base !== null && base !== undefined ? base : {});
5641
+ return ResolveFloatRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5463
5642
  },
5464
5643
  fromPartial(object) {
5465
5644
  var _a, _b;
5466
5645
  const message = createBaseResolveFloatRequest();
5467
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5468
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5646
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5647
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5469
5648
  return message;
5470
5649
  },
5471
5650
  };
@@ -5552,15 +5731,15 @@ const ResolveFloatResponse = {
5552
5731
  return obj;
5553
5732
  },
5554
5733
  create(base) {
5555
- return ResolveFloatResponse.fromPartial(base !== null && base !== undefined ? base : {});
5734
+ return ResolveFloatResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5556
5735
  },
5557
5736
  fromPartial(object) {
5558
5737
  var _a, _b, _c, _d;
5559
5738
  const message = createBaseResolveFloatResponse();
5560
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : 0;
5561
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5562
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5563
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5739
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : 0;
5740
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5741
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5742
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5564
5743
  return message;
5565
5744
  },
5566
5745
  };
@@ -5621,13 +5800,13 @@ const ResolveIntRequest = {
5621
5800
  return obj;
5622
5801
  },
5623
5802
  create(base) {
5624
- return ResolveIntRequest.fromPartial(base !== null && base !== undefined ? base : {});
5803
+ return ResolveIntRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5625
5804
  },
5626
5805
  fromPartial(object) {
5627
5806
  var _a, _b;
5628
5807
  const message = createBaseResolveIntRequest();
5629
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5630
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5808
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5809
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5631
5810
  return message;
5632
5811
  },
5633
5812
  };
@@ -5714,15 +5893,15 @@ const ResolveIntResponse = {
5714
5893
  return obj;
5715
5894
  },
5716
5895
  create(base) {
5717
- return ResolveIntResponse.fromPartial(base !== null && base !== undefined ? base : {});
5896
+ return ResolveIntResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5718
5897
  },
5719
5898
  fromPartial(object) {
5720
5899
  var _a, _b, _c, _d;
5721
5900
  const message = createBaseResolveIntResponse();
5722
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : "0";
5723
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5724
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5725
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5901
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : "0";
5902
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5903
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5904
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5726
5905
  return message;
5727
5906
  },
5728
5907
  };
@@ -5783,13 +5962,13 @@ const ResolveObjectRequest = {
5783
5962
  return obj;
5784
5963
  },
5785
5964
  create(base) {
5786
- return ResolveObjectRequest.fromPartial(base !== null && base !== undefined ? base : {});
5965
+ return ResolveObjectRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5787
5966
  },
5788
5967
  fromPartial(object) {
5789
5968
  var _a, _b;
5790
5969
  const message = createBaseResolveObjectRequest();
5791
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5792
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5970
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5971
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5793
5972
  return message;
5794
5973
  },
5795
5974
  };
@@ -5876,15 +6055,15 @@ const ResolveObjectResponse = {
5876
6055
  return obj;
5877
6056
  },
5878
6057
  create(base) {
5879
- return ResolveObjectResponse.fromPartial(base !== null && base !== undefined ? base : {});
6058
+ return ResolveObjectResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5880
6059
  },
5881
6060
  fromPartial(object) {
5882
6061
  var _a, _b, _c, _d;
5883
6062
  const message = createBaseResolveObjectResponse();
5884
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : undefined;
5885
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5886
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5887
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
6063
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : undefined;
6064
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
6065
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
6066
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5888
6067
  return message;
5889
6068
  },
5890
6069
  };
@@ -5945,13 +6124,13 @@ const EventStreamResponse = {
5945
6124
  return obj;
5946
6125
  },
5947
6126
  create(base) {
5948
- return EventStreamResponse.fromPartial(base !== null && base !== undefined ? base : {});
6127
+ return EventStreamResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5949
6128
  },
5950
6129
  fromPartial(object) {
5951
6130
  var _a, _b;
5952
6131
  const message = createBaseEventStreamResponse();
5953
- message.type = (_a = object.type) !== null && _a !== undefined ? _a : "";
5954
- message.data = (_b = object.data) !== null && _b !== undefined ? _b : undefined;
6132
+ message.type = (_a = object.type) !== null && _a !== void 0 ? _a : "";
6133
+ message.data = (_b = object.data) !== null && _b !== void 0 ? _b : undefined;
5955
6134
  return message;
5956
6135
  },
5957
6136
  };
@@ -5983,7 +6162,7 @@ const EventStreamRequest = {
5983
6162
  return obj;
5984
6163
  },
5985
6164
  create(base) {
5986
- return EventStreamRequest.fromPartial(base !== null && base !== undefined ? base : {});
6165
+ return EventStreamRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5987
6166
  },
5988
6167
  fromPartial(_) {
5989
6168
  const message = createBaseEventStreamRequest();
@@ -6070,6 +6249,10 @@ function isSet$1(value) {
6070
6249
  return value !== null && value !== undefined;
6071
6250
  }
6072
6251
 
6252
+ /**
6253
+ * Get the string name of a gRPC status code.
6254
+ */
6255
+ const statusName = (code) => grpcJs.status[code];
6073
6256
  const closeStreamIfDefined = (stream) => {
6074
6257
  /**
6075
6258
  * cancel() is necessary to prevent calls from hanging the process, so we need to we need to remove all the
@@ -6084,6 +6267,122 @@ const closeStreamIfDefined = (stream) => {
6084
6267
  stream.destroy();
6085
6268
  }
6086
6269
  };
6270
+ /**
6271
+ * Creates gRPC channel credentials based on TLS and certificate path configuration.
6272
+ * @returns Channel credentials for gRPC connection
6273
+ */
6274
+ const createChannelCredentials = (tls, certPath) => {
6275
+ if (!tls) {
6276
+ return grpcJs.credentials.createInsecure();
6277
+ }
6278
+ if (certPath && node_fs.existsSync(certPath)) {
6279
+ const rootCerts = node_fs.readFileSync(certPath);
6280
+ return grpcJs.credentials.createSsl(rootCerts);
6281
+ }
6282
+ return grpcJs.credentials.createSsl();
6283
+ };
6284
+ /**
6285
+ * Mapping of configuration options to gRPC client options.
6286
+ */
6287
+ const CONFIG_TO_GRPC_OPTIONS = [
6288
+ { configKey: 'defaultAuthority', grpcKey: 'grpc.default_authority' },
6289
+ { configKey: 'keepAliveTime', grpcKey: 'grpc.keepalive_time_ms', condition: (time) => Number(time) > 0 },
6290
+ ];
6291
+ /**
6292
+ * Builds gRPC client options from config.
6293
+ */
6294
+ function buildClientOptions(config) {
6295
+ const options = {
6296
+ 'grpc.service_config': buildRetryPolicy(['flagd.evaluation.v1.Service', 'flagd.sync.v1.FlagSyncService'], config.retryBackoffMs, config.retryBackoffMaxMs),
6297
+ };
6298
+ for (const { configKey, grpcKey, condition } of CONFIG_TO_GRPC_OPTIONS) {
6299
+ const value = config[configKey];
6300
+ if (value !== undefined && (!condition || condition(value))) {
6301
+ options[grpcKey] = value;
6302
+ }
6303
+ }
6304
+ return options;
6305
+ }
6306
+ /**
6307
+ * Builds RetryPolicy for gRPC client options.
6308
+ * @param serviceNames Array of service names to configure retry policy for
6309
+ * @param retryBackoffMs Initial backoff duration in milliseconds
6310
+ * @param retryBackoffMaxMs Maximum backoff duration in milliseconds
6311
+ * @returns gRPC client options with retry policy
6312
+ */
6313
+ const buildRetryPolicy = (serviceNames, retryBackoffMs, retryBackoffMaxMs) => {
6314
+ const initialBackoff = retryBackoffMs !== null && retryBackoffMs !== void 0 ? retryBackoffMs : 1000;
6315
+ const maxBackoff = retryBackoffMaxMs !== null && retryBackoffMaxMs !== void 0 ? retryBackoffMaxMs : 120000;
6316
+ const retryPolicy = {
6317
+ maxAttempts: 3,
6318
+ initialBackoff: `${Math.round(initialBackoff / 1000).toFixed(2)}s`,
6319
+ maxBackoff: `${Math.round(maxBackoff / 1000).toFixed(2)}s`,
6320
+ backoffMultiplier: 2,
6321
+ retryableStatusCodes: [statusName(grpcJs.status.UNAVAILABLE), statusName(grpcJs.status.UNKNOWN)],
6322
+ };
6323
+ return JSON.stringify({
6324
+ loadBalancingConfig: [],
6325
+ methodConfig: [
6326
+ {
6327
+ name: serviceNames.map((serviceName) => ({ service: serviceName })),
6328
+ retryPolicy,
6329
+ },
6330
+ ],
6331
+ });
6332
+ };
6333
+ /**
6334
+ * Converts an array of gRPC status code strings to a Set of numeric codes.
6335
+ * @param fatalStatusCodes Array of status code strings.
6336
+ * @param logger Optional logger for warning about unknown codes
6337
+ * @returns Set of numeric status codes
6338
+ */
6339
+ const createFatalStatusCodesSet = (fatalStatusCodes, logger) => {
6340
+ if (!(fatalStatusCodes === null || fatalStatusCodes === void 0 ? void 0 : fatalStatusCodes.length)) {
6341
+ return new Set();
6342
+ }
6343
+ return fatalStatusCodes.reduce((codes, codeStr) => {
6344
+ const numericCode = grpcJs.status[codeStr];
6345
+ if (typeof numericCode === 'number') {
6346
+ codes.add(numericCode);
6347
+ }
6348
+ else {
6349
+ logger === null || logger === void 0 ? void 0 : logger.warn(`Unknown gRPC status code: "${codeStr}"`);
6350
+ }
6351
+ return codes;
6352
+ }, new Set());
6353
+ };
6354
+ /**
6355
+ * Checks if an error is a fatal gRPC status code that should not be retried.
6356
+ * This should only be checked on the first connection attempt.
6357
+ *
6358
+ * @param err The error to check
6359
+ * @param initialized Whether the connection has been successfully initialized
6360
+ * @param fatalStatusCodes Set of numeric status codes considered fatal
6361
+ * @returns True if the error is fatal and should not be retried
6362
+ */
6363
+ const isFatalStatusCodeError = (err, initialized, fatalStatusCodes) => {
6364
+ if (initialized) {
6365
+ return false;
6366
+ }
6367
+ const serviceError = err;
6368
+ return (serviceError === null || serviceError === void 0 ? void 0 : serviceError.code) !== undefined && fatalStatusCodes.has(serviceError.code);
6369
+ };
6370
+ /**
6371
+ * Handles a fatal gRPC status code error by logging it.
6372
+ * Should only be called when isFatalStatusCodeError returns true.
6373
+ *
6374
+ * @param err The error to handle
6375
+ * @param logger Optional logger for error logging
6376
+ * @param disconnectCallback Callback to invoke with the error message
6377
+ * @param rejectConnect Optional callback to reject the connection promise
6378
+ */
6379
+ const handleFatalStatusCodeError = (err, logger, disconnectCallback, rejectConnect) => {
6380
+ const serviceError = err;
6381
+ logger === null || logger === void 0 ? void 0 : logger.error(`Encountered fatal status code ${serviceError.code} (${serviceError.message}) on first connection, will not retry`);
6382
+ const errorMessage = `PROVIDER_FATAL: ${serviceError.message}`;
6383
+ disconnectCallback(errorMessage);
6384
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(new serverSdk.ProviderFatalError(serviceError.message));
6385
+ };
6087
6386
 
6088
6387
  class GRPCService {
6089
6388
  get _cacheActive() {
@@ -6094,9 +6393,11 @@ class GRPCService {
6094
6393
  this.logger = logger;
6095
6394
  this._cacheEnabled = false;
6096
6395
  this._eventStream = undefined;
6396
+ this._initialized = false;
6397
+ this._errorThrottled = false;
6097
6398
  this.onRejected = (err) => {
6098
6399
  // map the errors
6099
- switch (err === null || err === undefined ? undefined : err.code) {
6400
+ switch (err === null || err === void 0 ? void 0 : err.code) {
6100
6401
  case grpcJs.status.DATA_LOSS:
6101
6402
  throw new serverSdk.ParseError(err.details);
6102
6403
  case grpcJs.status.INVALID_ARGUMENT:
@@ -6106,89 +6407,128 @@ class GRPCService {
6106
6407
  case grpcJs.status.UNAVAILABLE:
6107
6408
  throw new serverSdk.FlagNotFoundError(err.details);
6108
6409
  default:
6109
- throw new serverSdk.GeneralError(err === null || err === undefined ? undefined : err.details);
6410
+ throw new serverSdk.GeneralError(err === null || err === void 0 ? void 0 : err.details);
6110
6411
  }
6111
6412
  };
6112
- const { host, port, tls, socketPath } = config;
6413
+ const { host, port, tls, socketPath, certPath } = config;
6414
+ const clientOptions = buildClientOptions(config);
6415
+ const channelCredentials = createChannelCredentials(tls, certPath);
6416
+ this._maxBackoffMs = config.retryBackoffMaxMs || DEFAULT_MAX_BACKOFF_MS;
6113
6417
  this._client = client
6114
6418
  ? client
6115
- : new ServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, tls ? grpcJs.credentials.createSsl() : grpcJs.credentials.createInsecure());
6419
+ : new ServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, channelCredentials, clientOptions);
6420
+ this._deadline = config.deadlineMs;
6421
+ this._streamDeadline = config.streamDeadlineMs;
6116
6422
  if (config.cache === 'lru') {
6117
6423
  this._cacheEnabled = true;
6118
6424
  this._cache = new lruCache.LRUCache({ maxSize: config.maxCacheSize || DEFAULT_MAX_CACHE_SIZE, sizeCalculation: () => 1 });
6119
6425
  }
6426
+ this._fatalStatusCodes = createFatalStatusCodesSet(config.fatalStatusCodes, logger);
6427
+ // create metadata with the flagd-selector header if selector is configured
6428
+ this._metadata = new grpcJs.Metadata();
6429
+ if (config.selector) {
6430
+ this._metadata.set(FLAGD_SELECTOR_HEADER, config.selector);
6431
+ }
6432
+ }
6433
+ clearCache() {
6434
+ var _a;
6435
+ (_a = this._cache) === null || _a === void 0 ? void 0 : _a.clear();
6120
6436
  }
6121
6437
  connect(reconnectCallback, changedCallback, disconnectCallback) {
6122
6438
  return new Promise((resolve, reject) => this.listen(reconnectCallback, changedCallback, disconnectCallback, resolve, reject));
6123
6439
  }
6124
6440
  disconnect() {
6125
- return __awaiter(this, undefined, undefined, function* () {
6441
+ return __awaiter(this, void 0, void 0, function* () {
6126
6442
  closeStreamIfDefined(this._eventStream);
6127
6443
  this._client.close();
6128
6444
  });
6129
6445
  }
6130
6446
  resolveBoolean(flagKey, _, context, logger) {
6131
- return __awaiter(this, undefined, undefined, function* () {
6447
+ return __awaiter(this, void 0, void 0, function* () {
6132
6448
  return this.resolve(this._client.resolveBoolean, flagKey, context, logger);
6133
6449
  });
6134
6450
  }
6135
6451
  resolveString(flagKey, _, context, logger) {
6136
- return __awaiter(this, undefined, undefined, function* () {
6452
+ return __awaiter(this, void 0, void 0, function* () {
6137
6453
  return this.resolve(this._client.resolveString, flagKey, context, logger);
6138
6454
  });
6139
6455
  }
6140
6456
  resolveNumber(flagKey, _, context, logger) {
6141
- return __awaiter(this, undefined, undefined, function* () {
6457
+ return __awaiter(this, void 0, void 0, function* () {
6142
6458
  return this.resolve(this._client.resolveFloat, flagKey, context, logger);
6143
6459
  });
6144
6460
  }
6145
6461
  resolveObject(flagKey, _, context, logger) {
6146
- return __awaiter(this, undefined, undefined, function* () {
6462
+ return __awaiter(this, void 0, void 0, function* () {
6147
6463
  return this.resolve(this._client.resolveObject, flagKey, context, logger);
6148
6464
  });
6149
6465
  }
6150
6466
  listen(reconnectCallback, changedCallback, disconnectCallback, resolveConnect, rejectConnect) {
6151
6467
  var _a;
6152
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: connecting stream...`);
6468
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: connecting stream...`);
6153
6469
  // close the previous stream if we're reconnecting
6154
6470
  closeStreamIfDefined(this._eventStream);
6155
- const stream = this._client.eventStream({}, {});
6156
- stream.on('error', (err) => {
6157
- rejectConnect === null || rejectConnect === undefined ? undefined : rejectConnect(err);
6158
- this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6159
- });
6160
- stream.on('data', (message) => {
6161
- var _a;
6162
- if (message.type === EVENT_PROVIDER_READY) {
6163
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: streaming connection established with flagd`);
6164
- // if resolveConnect is undefined, this is a reconnection; we only want to fire the reconnect callback in that case
6165
- if (resolveConnect) {
6166
- resolveConnect();
6167
- }
6168
- else {
6169
- reconnectCallback();
6471
+ // wait for connection to be stable
6472
+ this._client.waitForReady(Date.now() + this._deadline, (err) => {
6473
+ if (err) {
6474
+ // Check if error is a fatal status code on first connection only
6475
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
6476
+ handleFatalStatusCodeError(err, this.logger, disconnectCallback, rejectConnect);
6477
+ return;
6170
6478
  }
6479
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(err);
6480
+ this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6171
6481
  }
6172
- else if (message.type === EVENT_CONFIGURATION_CHANGE) {
6173
- this.handleFlagsChanged(message, changedCallback);
6482
+ else {
6483
+ const streamDeadline = this._streamDeadline != 0 ? Date.now() + this._streamDeadline : undefined;
6484
+ const stream = this._client.eventStream({}, { deadline: streamDeadline });
6485
+ stream.on('error', (err) => {
6486
+ // In cases where we get an explicit error status, we add a delay.
6487
+ // This prevents tight loops when errors are returned immediately, typically by intervening proxies like Envoy.
6488
+ this._errorThrottled = true;
6489
+ // Check if error is a fatal status code on first connection only
6490
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
6491
+ handleFatalStatusCodeError(err, this.logger, disconnectCallback, rejectConnect);
6492
+ return;
6493
+ }
6494
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(err);
6495
+ this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6496
+ });
6497
+ stream.on('data', (message) => {
6498
+ var _a;
6499
+ if (message.type === EVENT_PROVIDER_READY) {
6500
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: streaming connection established with flagd`);
6501
+ this._initialized = true;
6502
+ // if resolveConnect is undefined, this is a reconnection; we only want to fire the reconnect callback in that case
6503
+ if (resolveConnect) {
6504
+ resolveConnect();
6505
+ }
6506
+ else {
6507
+ reconnectCallback();
6508
+ }
6509
+ }
6510
+ else if (message.type === EVENT_CONFIGURATION_CHANGE) {
6511
+ this.handleFlagsChanged(message, changedCallback);
6512
+ }
6513
+ });
6514
+ this._eventStream = stream;
6174
6515
  }
6175
6516
  });
6176
- this._eventStream = stream;
6177
6517
  }
6178
6518
  handleFlagsChanged(message, changedCallback) {
6179
6519
  var _a;
6180
6520
  if (message.data) {
6181
6521
  const data = message.data;
6182
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: got message: ${JSON.stringify(data, undefined, 2)}`);
6183
- if (data && typeof data === 'object' && 'flags' in data && (data === null || data === undefined ? undefined : data['flags'])) {
6522
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: got message: ${JSON.stringify(data, undefined, 2)}`);
6523
+ if (data && typeof data === 'object' && 'flags' in data && (data === null || data === void 0 ? void 0 : data['flags'])) {
6184
6524
  const flagChangeMessage = data;
6185
6525
  const flagsChanged = Object.keys(flagChangeMessage.flags || []);
6186
6526
  if (this._cacheEnabled) {
6187
6527
  // remove each changed key from cache
6188
6528
  flagsChanged.forEach((key) => {
6189
6529
  var _a, _b;
6190
- if ((_a = this._cache) === null || _a === undefined ? undefined : _a.delete(key)) {
6191
- (_b = this.logger) === null || _b === undefined ? undefined : _b.debug(`${FlagdProvider.name}: evicted key: ${key} from cache.`);
6530
+ if ((_a = this._cache) === null || _a === void 0 ? void 0 : _a.delete(key)) {
6531
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(`${FlagdProvider.name}: evicted key: ${key} from cache.`);
6192
6532
  }
6193
6533
  });
6194
6534
  }
@@ -6197,31 +6537,29 @@ class GRPCService {
6197
6537
  }
6198
6538
  }
6199
6539
  reconnect(reconnectCallback, changedCallback, disconnectCallback) {
6200
- const channel = this._client.getChannel();
6201
- channel.watchConnectivityState(channel.getConnectivityState(true), Infinity, () => {
6202
- this.listen(reconnectCallback, changedCallback, disconnectCallback);
6203
- });
6540
+ setTimeout(() => this.listen(reconnectCallback, changedCallback, disconnectCallback), this._errorThrottled ? this._maxBackoffMs : 0);
6541
+ this._errorThrottled = false;
6204
6542
  }
6205
6543
  handleError(reconnectCallback, changedCallback, disconnectCallback) {
6206
6544
  var _a, _b;
6207
6545
  disconnectCallback('streaming connection error, will attempt reconnect...');
6208
- (_a = this.logger) === null || _a === undefined ? undefined : _a.error(`${FlagdProvider.name}: streaming connection error, will attempt reconnect...`);
6209
- (_b = this._cache) === null || _b === undefined ? undefined : _b.clear();
6546
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`${FlagdProvider.name}: streaming connection error, will attempt reconnect...`);
6547
+ (_b = this._cache) === null || _b === void 0 ? void 0 : _b.clear();
6210
6548
  this.reconnect(reconnectCallback, changedCallback, disconnectCallback);
6211
6549
  }
6212
6550
  resolve(promise, flagKey, context, logger) {
6213
- return __awaiter(this, undefined, undefined, function* () {
6551
+ return __awaiter(this, void 0, void 0, function* () {
6214
6552
  var _a, _b;
6215
6553
  const resolver = node_util.promisify(promise);
6216
6554
  if (this._cacheActive) {
6217
- const cached = (_a = this._cache) === null || _a === undefined ? undefined : _a.get(flagKey);
6555
+ const cached = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(flagKey);
6218
6556
  if (cached) {
6219
6557
  return Object.assign(Object.assign({}, cached), { reason: serverSdk.StandardResolutionReasons.CACHED });
6220
6558
  }
6221
6559
  }
6222
- // invoke the passed resolver method
6560
+ // invoke the passed resolver method with metadata for selector support
6223
6561
  const response = yield resolver
6224
- .call(this._client, { flagKey, context })
6562
+ .call(this._client, { flagKey, context }, this._metadata)
6225
6563
  .then((resolved) => resolved, this.onRejected);
6226
6564
  const resolved = {
6227
6565
  value: response.value,
@@ -6232,7 +6570,7 @@ class GRPCService {
6232
6570
  logger.debug(`${FlagdProvider.name}: resolved flag with key: ${resolved.value}, variant: ${response.variant}, reason: ${response.reason}`);
6233
6571
  if (this._cacheActive && response.reason === serverSdk.StandardResolutionReasons.STATIC) {
6234
6572
  // cache this static value
6235
- (_b = this._cache) === null || _b === undefined ? undefined : _b.set(flagKey, resolved);
6573
+ (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(flagKey, resolved);
6236
6574
  }
6237
6575
  return resolved;
6238
6576
  });
@@ -6246,9 +6584,9 @@ class FileFetch {
6246
6584
  this._logger = logger;
6247
6585
  }
6248
6586
  connect(dataFillCallback, _, changedCallback) {
6249
- return __awaiter(this, undefined, undefined, function* () {
6587
+ return __awaiter(this, void 0, void 0, function* () {
6250
6588
  var _a, _b;
6251
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Starting file sync connection');
6589
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Starting file sync connection');
6252
6590
  try {
6253
6591
  const output = yield fs.promises.readFile(this._filename, encoding);
6254
6592
  // Don't emit the change event for the initial read
@@ -6273,13 +6611,13 @@ class FileFetch {
6273
6611
  throw err;
6274
6612
  }
6275
6613
  else {
6276
- switch (err === null || err === undefined ? undefined : err.code) {
6614
+ switch (err === null || err === void 0 ? void 0 : err.code) {
6277
6615
  case 'ENOENT':
6278
6616
  throw new serverSdk.GeneralError(`File not found: ${this._filename}`);
6279
6617
  case 'EACCES':
6280
6618
  throw new serverSdk.GeneralError(`File not accessible: ${this._filename}`);
6281
6619
  default:
6282
- (_b = this._logger) === null || _b === undefined ? undefined : _b.debug(`Error reading file: ${err}`);
6620
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Error reading file: ${err}`);
6283
6621
  throw new serverSdk.GeneralError();
6284
6622
  }
6285
6623
  }
@@ -6287,7 +6625,7 @@ class FileFetch {
6287
6625
  });
6288
6626
  }
6289
6627
  disconnect() {
6290
- return __awaiter(this, undefined, undefined, function* () {
6628
+ return __awaiter(this, void 0, void 0, function* () {
6291
6629
  fs.unwatchFile(this._filename);
6292
6630
  });
6293
6631
  }
@@ -6351,24 +6689,27 @@ const SyncFlagsRequest = {
6351
6689
  return obj;
6352
6690
  },
6353
6691
  create(base) {
6354
- return SyncFlagsRequest.fromPartial(base !== null && base !== undefined ? base : {});
6692
+ return SyncFlagsRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6355
6693
  },
6356
6694
  fromPartial(object) {
6357
6695
  var _a, _b;
6358
6696
  const message = createBaseSyncFlagsRequest();
6359
- message.providerId = (_a = object.providerId) !== null && _a !== undefined ? _a : "";
6360
- message.selector = (_b = object.selector) !== null && _b !== undefined ? _b : "";
6697
+ message.providerId = (_a = object.providerId) !== null && _a !== void 0 ? _a : "";
6698
+ message.selector = (_b = object.selector) !== null && _b !== void 0 ? _b : "";
6361
6699
  return message;
6362
6700
  },
6363
6701
  };
6364
6702
  function createBaseSyncFlagsResponse() {
6365
- return { flagConfiguration: "" };
6703
+ return { flagConfiguration: "", syncContext: undefined };
6366
6704
  }
6367
6705
  const SyncFlagsResponse = {
6368
6706
  encode(message, writer = _m0.Writer.create()) {
6369
6707
  if (message.flagConfiguration !== "") {
6370
6708
  writer.uint32(10).string(message.flagConfiguration);
6371
6709
  }
6710
+ if (message.syncContext !== undefined) {
6711
+ Struct.encode(Struct.wrap(message.syncContext), writer.uint32(18).fork()).ldelim();
6712
+ }
6372
6713
  return writer;
6373
6714
  },
6374
6715
  decode(input, length) {
@@ -6384,6 +6725,12 @@ const SyncFlagsResponse = {
6384
6725
  }
6385
6726
  message.flagConfiguration = reader.string();
6386
6727
  continue;
6728
+ case 2:
6729
+ if (tag !== 18) {
6730
+ break;
6731
+ }
6732
+ message.syncContext = Struct.unwrap(Struct.decode(reader, reader.uint32()));
6733
+ continue;
6387
6734
  }
6388
6735
  if ((tag & 7) === 4 || tag === 0) {
6389
6736
  break;
@@ -6393,22 +6740,29 @@ const SyncFlagsResponse = {
6393
6740
  return message;
6394
6741
  },
6395
6742
  fromJSON(object) {
6396
- return { flagConfiguration: isSet(object.flagConfiguration) ? String(object.flagConfiguration) : "" };
6743
+ return {
6744
+ flagConfiguration: isSet(object.flagConfiguration) ? String(object.flagConfiguration) : "",
6745
+ syncContext: isObject(object.syncContext) ? object.syncContext : undefined,
6746
+ };
6397
6747
  },
6398
6748
  toJSON(message) {
6399
6749
  const obj = {};
6400
6750
  if (message.flagConfiguration !== "") {
6401
6751
  obj.flagConfiguration = message.flagConfiguration;
6402
6752
  }
6753
+ if (message.syncContext !== undefined) {
6754
+ obj.syncContext = message.syncContext;
6755
+ }
6403
6756
  return obj;
6404
6757
  },
6405
6758
  create(base) {
6406
- return SyncFlagsResponse.fromPartial(base !== null && base !== undefined ? base : {});
6759
+ return SyncFlagsResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6407
6760
  },
6408
6761
  fromPartial(object) {
6409
- var _a;
6762
+ var _a, _b;
6410
6763
  const message = createBaseSyncFlagsResponse();
6411
- message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== undefined ? _a : "";
6764
+ message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== void 0 ? _a : "";
6765
+ message.syncContext = (_b = object.syncContext) !== null && _b !== void 0 ? _b : undefined;
6412
6766
  return message;
6413
6767
  },
6414
6768
  };
@@ -6469,13 +6823,13 @@ const FetchAllFlagsRequest = {
6469
6823
  return obj;
6470
6824
  },
6471
6825
  create(base) {
6472
- return FetchAllFlagsRequest.fromPartial(base !== null && base !== undefined ? base : {});
6826
+ return FetchAllFlagsRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6473
6827
  },
6474
6828
  fromPartial(object) {
6475
6829
  var _a, _b;
6476
6830
  const message = createBaseFetchAllFlagsRequest();
6477
- message.providerId = (_a = object.providerId) !== null && _a !== undefined ? _a : "";
6478
- message.selector = (_b = object.selector) !== null && _b !== undefined ? _b : "";
6831
+ message.providerId = (_a = object.providerId) !== null && _a !== void 0 ? _a : "";
6832
+ message.selector = (_b = object.selector) !== null && _b !== void 0 ? _b : "";
6479
6833
  return message;
6480
6834
  },
6481
6835
  };
@@ -6521,12 +6875,12 @@ const FetchAllFlagsResponse = {
6521
6875
  return obj;
6522
6876
  },
6523
6877
  create(base) {
6524
- return FetchAllFlagsResponse.fromPartial(base !== null && base !== undefined ? base : {});
6878
+ return FetchAllFlagsResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6525
6879
  },
6526
6880
  fromPartial(object) {
6527
6881
  var _a;
6528
6882
  const message = createBaseFetchAllFlagsResponse();
6529
- message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== undefined ? _a : "";
6883
+ message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== void 0 ? _a : "";
6530
6884
  return message;
6531
6885
  },
6532
6886
  };
@@ -6558,7 +6912,7 @@ const GetMetadataRequest = {
6558
6912
  return obj;
6559
6913
  },
6560
6914
  create(base) {
6561
- return GetMetadataRequest.fromPartial(base !== null && base !== undefined ? base : {});
6915
+ return GetMetadataRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6562
6916
  },
6563
6917
  fromPartial(_) {
6564
6918
  const message = createBaseGetMetadataRequest();
@@ -6607,12 +6961,12 @@ const GetMetadataResponse = {
6607
6961
  return obj;
6608
6962
  },
6609
6963
  create(base) {
6610
- return GetMetadataResponse.fromPartial(base !== null && base !== undefined ? base : {});
6964
+ return GetMetadataResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6611
6965
  },
6612
6966
  fromPartial(object) {
6613
6967
  var _a;
6614
6968
  const message = createBaseGetMetadataResponse();
6615
- message.metadata = (_a = object.metadata) !== null && _a !== undefined ? _a : undefined;
6969
+ message.metadata = (_a = object.metadata) !== null && _a !== void 0 ? _a : undefined;
6616
6970
  return message;
6617
6971
  },
6618
6972
  };
@@ -6635,6 +6989,7 @@ const FlagSyncServiceService = {
6635
6989
  responseSerialize: (value) => Buffer.from(FetchAllFlagsResponse.encode(value).finish()),
6636
6990
  responseDeserialize: (value) => FetchAllFlagsResponse.decode(value),
6637
6991
  },
6992
+ /** @deprecated */
6638
6993
  getMetadata: {
6639
6994
  path: "/flagd.sync.v1.FlagSyncService/GetMetadata",
6640
6995
  requestStream: false,
@@ -6657,7 +7012,8 @@ function isSet(value) {
6657
7012
  * Implements the gRPC sync contract to fetch flag data.
6658
7013
  */
6659
7014
  class GrpcFetch {
6660
- constructor(config, syncServiceClient, logger) {
7015
+ constructor(config, setSyncContext, syncServiceClient, logger) {
7016
+ this._errorThrottled = false;
6661
7017
  /**
6662
7018
  * Initialized will be set to true once the initial connection is successful
6663
7019
  * and the first payload has been received. Subsequent reconnects will not
@@ -6670,57 +7026,88 @@ class GrpcFetch {
6670
7026
  * false if the connection is lost.
6671
7027
  */
6672
7028
  this._isConnected = false;
6673
- const { host, port, tls, socketPath, selector } = config;
7029
+ const { host, port, tls, socketPath, certPath, selector } = config;
7030
+ const clientOptions = buildClientOptions(config);
7031
+ const channelCredentials = createChannelCredentials(tls, certPath);
6674
7032
  this._syncClient = syncServiceClient
6675
7033
  ? syncServiceClient
6676
- : new FlagSyncServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, tls ? grpcJs.credentials.createSsl() : grpcJs.credentials.createInsecure());
7034
+ : new FlagSyncServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, channelCredentials, clientOptions);
7035
+ this._deadlineMs = config.deadlineMs;
7036
+ this._maxBackoffMs = config.retryBackoffMaxMs || DEFAULT_MAX_BACKOFF_MS;
7037
+ this._streamDeadlineMs = config.streamDeadlineMs;
7038
+ this._setSyncContext = setSyncContext;
6677
7039
  this._logger = logger;
7040
+ // For backward compatibility during the deprecation period, we send the selector in both:
7041
+ // 1. The request field (deprecated, for older flagd versions)
7042
+ // 2. The gRPC metadata header 'flagd-selector' (new standard)
6678
7043
  this._request = { providerId: '', selector: selector ? selector : '' };
7044
+ this._fatalStatusCodes = createFatalStatusCodesSet(config.fatalStatusCodes, logger);
7045
+ // Create metadata with the flagd-selector header
7046
+ this._metadata = new grpcJs.Metadata();
7047
+ if (selector) {
7048
+ this._metadata.set(FLAGD_SELECTOR_HEADER, selector);
7049
+ }
6679
7050
  }
6680
7051
  connect(dataCallback, reconnectCallback, changedCallback, disconnectCallback) {
6681
- return __awaiter(this, undefined, undefined, function* () {
7052
+ return __awaiter(this, void 0, void 0, function* () {
6682
7053
  yield new Promise((resolve, reject) => this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback, resolve, reject));
6683
7054
  this._initialized = true;
6684
7055
  });
6685
7056
  }
6686
7057
  disconnect() {
6687
- return __awaiter(this, undefined, undefined, function* () {
7058
+ return __awaiter(this, void 0, void 0, function* () {
6688
7059
  var _a;
6689
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Disconnecting gRPC sync connection');
7060
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Disconnecting gRPC sync connection');
6690
7061
  closeStreamIfDefined(this._syncStream);
6691
7062
  this._syncClient.close();
6692
7063
  });
6693
7064
  }
6694
7065
  listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback, resolveConnect, rejectConnect) {
6695
7066
  var _a;
6696
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Starting gRPC sync connection');
7067
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Starting gRPC sync connection');
6697
7068
  closeStreamIfDefined(this._syncStream);
6698
7069
  try {
6699
- this._syncStream = this._syncClient.syncFlags(this._request);
6700
- this._syncStream.on('data', (data) => {
6701
- var _a, _b, _c, _d;
6702
- (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received sync payload`);
6703
- try {
6704
- const changes = dataCallback(data.flagConfiguration);
6705
- if (this._initialized && changes.length > 0) {
6706
- changedCallback(changes);
6707
- }
6708
- }
6709
- catch (err) {
6710
- (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug('Error processing sync payload: ', (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'unknown error');
6711
- }
6712
- if (resolveConnect) {
6713
- resolveConnect();
7070
+ // wait for connection to be stable
7071
+ this._syncClient.waitForReady(Date.now() + this._deadlineMs, (err) => {
7072
+ if (err) {
7073
+ this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
6714
7074
  }
6715
- else if (!this._isConnected) {
6716
- // Not the first connection and there's no active connection.
6717
- (_d = this._logger) === null || _d === void 0 ? void 0 : _d.debug('Reconnected to gRPC sync');
6718
- reconnectCallback();
7075
+ else {
7076
+ const streamDeadline = this._streamDeadlineMs != 0 ? Date.now() + this._streamDeadlineMs : undefined;
7077
+ const stream = this._syncClient.syncFlags(this._request, this._metadata, { deadline: streamDeadline });
7078
+ stream.on('data', (data) => {
7079
+ var _a, _b, _c, _d;
7080
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received sync payload`);
7081
+ try {
7082
+ if (data.syncContext) {
7083
+ this._setSyncContext(data.syncContext);
7084
+ }
7085
+ const changes = dataCallback(data.flagConfiguration);
7086
+ if (this._initialized && changes.length > 0) {
7087
+ changedCallback(changes);
7088
+ }
7089
+ }
7090
+ catch (err) {
7091
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug('Error processing sync payload: ', (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'unknown error');
7092
+ }
7093
+ if (resolveConnect) {
7094
+ resolveConnect();
7095
+ }
7096
+ else if (!this._isConnected) {
7097
+ // Not the first connection and there's no active connection.
7098
+ (_d = this._logger) === null || _d === void 0 ? void 0 : _d.debug('Reconnected to gRPC sync');
7099
+ reconnectCallback();
7100
+ }
7101
+ this._isConnected = true;
7102
+ });
7103
+ stream.on('error', (err) => {
7104
+ // In cases where we get an explicit error status, we add a delay.
7105
+ // This prevents tight loops when errors are returned immediately, typically by intervening proxies like Envoy.
7106
+ this._errorThrottled = true;
7107
+ this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
7108
+ });
7109
+ this._syncStream = stream;
6719
7110
  }
6720
- this._isConnected = true;
6721
- });
6722
- this._syncStream.on('error', (err) => {
6723
- this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
6724
7111
  });
6725
7112
  }
6726
7113
  catch (err) {
@@ -6729,57 +7116,64 @@ class GrpcFetch {
6729
7116
  }
6730
7117
  handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect) {
6731
7118
  var _a, _b, _c;
6732
- (_a = this._logger) === null || _a === undefined ? undefined : _a.error('Connection error, attempting to reconnect');
6733
- (_b = this._logger) === null || _b === undefined ? undefined : _b.debug(err);
7119
+ // Check if error is a fatal status code on first connection only
7120
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
7121
+ this._isConnected = false;
7122
+ handleFatalStatusCodeError(err, this._logger, disconnectCallback, rejectConnect);
7123
+ return;
7124
+ }
7125
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Connection error, attempting to reconnect');
7126
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(err);
6734
7127
  this._isConnected = false;
6735
- const errorMessage = (_c = err === null || err === undefined ? undefined : err.message) !== null && _c !== undefined ? _c : 'Failed to connect to syncFlags stream';
7128
+ const errorMessage = (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'Failed to connect to syncFlags stream';
6736
7129
  disconnectCallback(errorMessage);
6737
- rejectConnect === null || rejectConnect === undefined ? undefined : rejectConnect(new serverSdk.GeneralError(errorMessage));
7130
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(new serverSdk.GeneralError(errorMessage));
6738
7131
  this.reconnect(dataCallback, reconnectCallback, changedCallback, disconnectCallback);
6739
7132
  }
6740
7133
  reconnect(dataCallback, reconnectCallback, changedCallback, disconnectCallback) {
6741
- const channel = this._syncClient.getChannel();
6742
- channel.watchConnectivityState(channel.getConnectivityState(true), Infinity, () => {
6743
- this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback);
6744
- });
7134
+ setTimeout(() => this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback), this._errorThrottled ? this._maxBackoffMs : 0);
7135
+ this._errorThrottled = false;
6745
7136
  }
6746
7137
  }
6747
7138
 
6748
7139
  class InProcessService {
6749
- constructor(config, dataFetcher, logger) {
7140
+ constructor(config, setSyncContext, dataFetcher, logger) {
6750
7141
  this.config = config;
6751
7142
  this._flagdCore = new flagdCore.FlagdCore(undefined, logger);
6752
7143
  this._dataFetcher = dataFetcher
6753
7144
  ? dataFetcher
6754
7145
  : config.offlineFlagSourcePath
6755
7146
  ? new FileFetch(config.offlineFlagSourcePath, logger)
6756
- : new GrpcFetch(config, undefined, logger);
7147
+ : new GrpcFetch(config, setSyncContext, undefined, logger);
7148
+ }
7149
+ clearCache() {
7150
+ // in-process service does not cache flags
6757
7151
  }
6758
7152
  connect(reconnectCallback, changedCallback, disconnectCallback) {
6759
7153
  return this._dataFetcher.connect(this.setFlagConfiguration.bind(this), reconnectCallback, changedCallback, disconnectCallback);
6760
7154
  }
6761
7155
  disconnect() {
6762
- return __awaiter(this, undefined, undefined, function* () {
7156
+ return __awaiter(this, void 0, void 0, function* () {
6763
7157
  this._dataFetcher.disconnect();
6764
7158
  });
6765
7159
  }
6766
7160
  resolveBoolean(flagKey, defaultValue, context, logger) {
6767
- return __awaiter(this, undefined, undefined, function* () {
7161
+ return __awaiter(this, void 0, void 0, function* () {
6768
7162
  return this.evaluate('boolean', flagKey, defaultValue, context, logger);
6769
7163
  });
6770
7164
  }
6771
7165
  resolveNumber(flagKey, defaultValue, context, logger) {
6772
- return __awaiter(this, undefined, undefined, function* () {
7166
+ return __awaiter(this, void 0, void 0, function* () {
6773
7167
  return this.evaluate('number', flagKey, defaultValue, context, logger);
6774
7168
  });
6775
7169
  }
6776
7170
  resolveString(flagKey, defaultValue, context, logger) {
6777
- return __awaiter(this, undefined, undefined, function* () {
7171
+ return __awaiter(this, void 0, void 0, function* () {
6778
7172
  return this.evaluate('string', flagKey, defaultValue, context, logger);
6779
7173
  });
6780
7174
  }
6781
7175
  resolveObject(flagKey, defaultValue, context, logger) {
6782
- return __awaiter(this, undefined, undefined, function* () {
7176
+ return __awaiter(this, void 0, void 0, function* () {
6783
7177
  return this.evaluate('object', flagKey, defaultValue, context, logger);
6784
7178
  });
6785
7179
  }
@@ -6802,6 +7196,15 @@ class InProcessService {
6802
7196
  }
6803
7197
  }
6804
7198
 
7199
+ class SyncMetadataHook {
7200
+ constructor(enrichedContext) {
7201
+ this.enrichedContext = enrichedContext;
7202
+ }
7203
+ before(hookContext, hookHints) {
7204
+ return this.enrichedContext();
7205
+ }
7206
+ }
7207
+
6805
7208
  class FlagdProvider {
6806
7209
  /**
6807
7210
  * Construct a new flagd provider.
@@ -6811,36 +7214,58 @@ class FlagdProvider {
6811
7214
  * @param service optional internal service implementation, should not be needed for production
6812
7215
  */
6813
7216
  constructor(options, logger, service) {
7217
+ var _a;
6814
7218
  this.logger = logger;
6815
7219
  this.metadata = {
6816
7220
  name: 'flagd',
6817
7221
  };
6818
7222
  this.runsOn = 'server';
6819
7223
  this.events = new serverSdk.OpenFeatureEventEmitter();
7224
+ this.syncContext = null;
7225
+ this._isErrorState = false;
6820
7226
  const config = getConfig(options);
6821
- this._service = service
6822
- ? service
6823
- : config.resolverType === 'in-process'
6824
- ? new InProcessService(config, undefined, logger)
6825
- : new GRPCService(config, undefined, logger);
7227
+ this._retryGracePeriod = (_a = config.retryGracePeriod) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_GRACE_PERIOD;
7228
+ if (service === undefined) {
7229
+ if (config.resolverType === 'in-process') {
7230
+ this._service = new InProcessService(config, this.setSyncContext.bind(this), undefined, logger);
7231
+ if ((config === null || config === void 0 ? void 0 : config.offlineFlagSourcePath) === undefined) {
7232
+ this.hooks = [new SyncMetadataHook(() => config.contextEnricher(this.getSyncContext()))];
7233
+ }
7234
+ }
7235
+ else {
7236
+ this._service = new GRPCService(config, undefined, logger);
7237
+ }
7238
+ }
7239
+ else {
7240
+ this._service = service;
7241
+ }
7242
+ }
7243
+ setSyncContext(context) {
7244
+ this.syncContext = context;
7245
+ }
7246
+ getSyncContext() {
7247
+ return this.syncContext;
6826
7248
  }
6827
7249
  initialize() {
6828
- return __awaiter(this, undefined, undefined, function* () {
7250
+ return __awaiter(this, void 0, void 0, function* () {
6829
7251
  var _a, _b, _c;
6830
7252
  try {
6831
7253
  yield this._service.connect(this.handleReconnect.bind(this), this.handleChanged.bind(this), this.handleError.bind(this));
7254
+ this.clearErrorTimer();
7255
+ this._isErrorState = false;
6832
7256
  (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name}: ready`);
6833
7257
  }
6834
7258
  catch (err) {
6835
- (_b = this.logger) === null || _b === undefined ? undefined : _b.error(`${this.metadata.name}: error during initialization: ${err === null || err === undefined ? undefined : err.message}`);
6836
- (_c = this.logger) === null || _c === undefined ? undefined : _c.debug(err);
7259
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(`${this.metadata.name}: error during initialization: ${err === null || err === void 0 ? void 0 : err.message}`);
7260
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug(err);
6837
7261
  throw err;
6838
7262
  }
6839
7263
  });
6840
7264
  }
6841
7265
  onClose() {
6842
7266
  var _a;
6843
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${this.metadata.name}: shutting down`);
7267
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name}: shutting down`);
7268
+ this.clearErrorTimer();
6844
7269
  return this._service.disconnect();
6845
7270
  }
6846
7271
  resolveBooleanEvaluation(flagKey, defaultValue, transformedContext, logger) {
@@ -6856,14 +7281,35 @@ class FlagdProvider {
6856
7281
  return this._service.resolveObject(flagKey, defaultValue, transformedContext, logger);
6857
7282
  }
6858
7283
  handleReconnect() {
7284
+ this.clearErrorTimer();
7285
+ this._isErrorState = false;
6859
7286
  this.events.emit(serverSdk.ProviderEvents.Ready);
6860
7287
  }
6861
7288
  handleError(message) {
6862
- this.events.emit(serverSdk.ProviderEvents.Error, { message });
7289
+ if (this._isErrorState) {
7290
+ return;
7291
+ }
7292
+ this._isErrorState = true;
7293
+ this.events.emit(serverSdk.ProviderEvents.Stale, { message });
7294
+ this._errorTimer = setTimeout(() => {
7295
+ var _a;
7296
+ if (this._isErrorState) {
7297
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`${this.metadata.name}: not reconnected within ${this._retryGracePeriod}s grace period, emitting ERROR`);
7298
+ this._service.clearCache();
7299
+ this.events.emit(serverSdk.ProviderEvents.Error, { message });
7300
+ }
7301
+ this._errorTimer = undefined;
7302
+ }, this._retryGracePeriod * 1000);
6863
7303
  }
6864
7304
  handleChanged(flagsChanged) {
6865
7305
  this.events.emit(serverSdk.ProviderEvents.ConfigurationChanged, { flagsChanged });
6866
7306
  }
7307
+ clearErrorTimer() {
7308
+ if (this._errorTimer) {
7309
+ clearTimeout(this._errorTimer);
7310
+ this._errorTimer = undefined;
7311
+ }
7312
+ }
6867
7313
  }
6868
7314
 
6869
7315
  exports.FlagdProvider = FlagdProvider;