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