@launchdarkly/js-client-sdk-common 1.22.0 → 1.23.0

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/cjs/DataManager.d.ts +24 -0
  3. package/dist/cjs/DataManager.d.ts.map +1 -1
  4. package/dist/cjs/api/datasource/DataSourceEntry.d.ts +11 -0
  5. package/dist/cjs/api/datasource/DataSourceEntry.d.ts.map +1 -1
  6. package/dist/cjs/api/datasource/LDClientDataSystemOptions.d.ts +22 -0
  7. package/dist/cjs/api/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  8. package/dist/cjs/api/datasource/ModeDefinition.d.ts +3 -3
  9. package/dist/cjs/api/datasource/ModeDefinition.d.ts.map +1 -1
  10. package/dist/cjs/api/datasource/index.d.ts +1 -1
  11. package/dist/cjs/api/datasource/index.d.ts.map +1 -1
  12. package/dist/cjs/datasource/ConnectionModeConfig.d.ts.map +1 -1
  13. package/dist/cjs/datasource/LDClientDataSystemOptions.d.ts +1 -0
  14. package/dist/cjs/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  15. package/dist/cjs/datasource/SourceFactoryProvider.d.ts +77 -0
  16. package/dist/cjs/datasource/SourceFactoryProvider.d.ts.map +1 -0
  17. package/dist/cjs/datasource/fdv2/FDv2DataSource.d.ts.map +1 -1
  18. package/dist/cjs/flag-manager/FlagManager.d.ts +16 -1
  19. package/dist/cjs/flag-manager/FlagManager.d.ts.map +1 -1
  20. package/dist/cjs/flag-manager/FlagPersistence.d.ts +13 -1
  21. package/dist/cjs/flag-manager/FlagPersistence.d.ts.map +1 -1
  22. package/dist/cjs/flag-manager/FlagStore.d.ts +10 -0
  23. package/dist/cjs/flag-manager/FlagStore.d.ts.map +1 -1
  24. package/dist/cjs/flag-manager/FlagUpdater.d.ts +13 -1
  25. package/dist/cjs/flag-manager/FlagUpdater.d.ts.map +1 -1
  26. package/dist/cjs/index.cjs +1130 -3
  27. package/dist/cjs/index.cjs.map +1 -1
  28. package/dist/cjs/index.d.ts +6 -1
  29. package/dist/cjs/index.d.ts.map +1 -1
  30. package/dist/cjs/types/index.d.ts +2 -2
  31. package/dist/esm/DataManager.d.ts +24 -0
  32. package/dist/esm/DataManager.d.ts.map +1 -1
  33. package/dist/esm/api/datasource/DataSourceEntry.d.ts +11 -0
  34. package/dist/esm/api/datasource/DataSourceEntry.d.ts.map +1 -1
  35. package/dist/esm/api/datasource/LDClientDataSystemOptions.d.ts +22 -0
  36. package/dist/esm/api/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  37. package/dist/esm/api/datasource/ModeDefinition.d.ts +3 -3
  38. package/dist/esm/api/datasource/ModeDefinition.d.ts.map +1 -1
  39. package/dist/esm/api/datasource/index.d.ts +1 -1
  40. package/dist/esm/api/datasource/index.d.ts.map +1 -1
  41. package/dist/esm/datasource/ConnectionModeConfig.d.ts.map +1 -1
  42. package/dist/esm/datasource/LDClientDataSystemOptions.d.ts +1 -0
  43. package/dist/esm/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  44. package/dist/esm/datasource/SourceFactoryProvider.d.ts +77 -0
  45. package/dist/esm/datasource/SourceFactoryProvider.d.ts.map +1 -0
  46. package/dist/esm/datasource/fdv2/FDv2DataSource.d.ts.map +1 -1
  47. package/dist/esm/flag-manager/FlagManager.d.ts +16 -1
  48. package/dist/esm/flag-manager/FlagManager.d.ts.map +1 -1
  49. package/dist/esm/flag-manager/FlagPersistence.d.ts +13 -1
  50. package/dist/esm/flag-manager/FlagPersistence.d.ts.map +1 -1
  51. package/dist/esm/flag-manager/FlagStore.d.ts +10 -0
  52. package/dist/esm/flag-manager/FlagStore.d.ts.map +1 -1
  53. package/dist/esm/flag-manager/FlagUpdater.d.ts +13 -1
  54. package/dist/esm/flag-manager/FlagUpdater.d.ts.map +1 -1
  55. package/dist/esm/index.d.ts +6 -1
  56. package/dist/esm/index.d.ts.map +1 -1
  57. package/dist/esm/index.mjs +1128 -4
  58. package/dist/esm/index.mjs.map +1 -1
  59. package/dist/esm/types/index.d.ts +2 -2
  60. package/package.json +2 -2
@@ -292,6 +292,62 @@ function validatorOf(validators, builtInDefaults) {
292
292
  },
293
293
  };
294
294
  }
295
+ /**
296
+ * Creates a validator for arrays of discriminated objects. Each item in the
297
+ * array must be an object containing a `discriminant` field whose value
298
+ * selects which validator map to apply. The valid discriminant values are
299
+ * the keys of `validatorsByType`. Items that are not objects, or whose
300
+ * discriminant value is missing or unrecognized, are filtered out with a
301
+ * warning.
302
+ *
303
+ * @param discriminant - The field name used to determine each item's type.
304
+ * @param validatorsByType - A mapping from discriminant values to the
305
+ * validator maps used to validate items of that type. Each validator map
306
+ * should include a validator for the discriminant field itself.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * // Validates an array like:
311
+ * // [{ type: 'polling', pollInterval: 60 }, { type: 'cache' }]
312
+ *
313
+ * const validator = arrayOf('type', {
314
+ * cache: { type: TypeValidators.String },
315
+ * polling: { type: TypeValidators.String, pollInterval: TypeValidators.numberWithMin(30) },
316
+ * streaming: { type: TypeValidators.String, initialReconnectDelay: TypeValidators.numberWithMin(1) },
317
+ * });
318
+ * ```
319
+ */
320
+ function arrayOf(discriminant, validatorsByType) {
321
+ return {
322
+ is: (u) => Array.isArray(u),
323
+ getType: () => 'array',
324
+ validate(value, name, logger) {
325
+ if (!Array.isArray(value)) {
326
+ logger?.warn(OptionMessages.wrongOptionType(name, 'array', typeof value));
327
+ return undefined;
328
+ }
329
+ const results = [];
330
+ value.forEach((item, i) => {
331
+ const itemPath = `${name}[${i}]`;
332
+ if (isNullish(item) || !TypeValidators.Object.is(item)) {
333
+ logger?.warn(OptionMessages.wrongOptionType(itemPath, 'object', typeof item));
334
+ return;
335
+ }
336
+ const obj = item;
337
+ const typeValue = obj[discriminant];
338
+ const validators = typeof typeValue === 'string' ? validatorsByType[typeValue] : undefined;
339
+ if (!validators) {
340
+ const expected = Object.keys(validatorsByType).join(' | ');
341
+ const received = typeof typeValue === 'string' ? typeValue : typeof typeValue;
342
+ logger?.warn(OptionMessages.wrongOptionType(`${itemPath}.${discriminant}`, expected, received));
343
+ return;
344
+ }
345
+ results.push(validateOptions(obj, validators, {}, logger, itemPath));
346
+ });
347
+ return { value: results };
348
+ },
349
+ };
350
+ }
295
351
  /**
296
352
  * Creates a validator that tries each provided validator in order and uses the
297
353
  * first one whose `is()` check passes. For compound validators the value is
@@ -321,23 +377,115 @@ function anyOf(...validators) {
321
377
  },
322
378
  };
323
379
  }
380
+ /**
381
+ * Creates a validator for objects with dynamic keys. Each key in the input
382
+ * object is checked against `keyValidator`; unrecognized keys produce a
383
+ * warning. Each value is validated by `valueValidator`. Defaults for
384
+ * individual entries are passed through from the parent so partial overrides
385
+ * preserve non-overridden entries.
386
+ *
387
+ * @param keyValidator - Validates that each key is an allowed value.
388
+ * @param valueValidator - Validates each value in the record.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * // Validates a record like { streaming: { ... }, polling: { ... } }
393
+ * // where keys must be valid connection modes:
394
+ * recordOf(
395
+ * TypeValidators.oneOf('streaming', 'polling', 'offline'),
396
+ * validatorOf({ initializers: arrayValidator, synchronizers: arrayValidator }),
397
+ * )
398
+ * ```
399
+ */
400
+ function recordOf(keyValidator, valueValidator) {
401
+ return {
402
+ is: (u) => TypeValidators.Object.is(u),
403
+ getType: () => 'object',
404
+ validate(value, name, logger, defaults) {
405
+ if (isNullish(value)) {
406
+ return undefined;
407
+ }
408
+ if (!TypeValidators.Object.is(value)) {
409
+ logger?.warn(OptionMessages.wrongOptionType(name, 'object', typeof value));
410
+ return undefined;
411
+ }
412
+ // Filter invalid keys, then delegate to validateOptions.
413
+ const obj = value;
414
+ const filtered = {};
415
+ const validatorMap = {};
416
+ Object.keys(obj).forEach((key) => {
417
+ if (keyValidator.is(key)) {
418
+ filtered[key] = obj[key];
419
+ validatorMap[key] = valueValidator;
420
+ }
421
+ else {
422
+ logger?.warn(OptionMessages.wrongOptionType(name, keyValidator.getType(), key));
423
+ }
424
+ });
425
+ const recordDefaults = TypeValidators.Object.is(defaults)
426
+ ? defaults
427
+ : {};
428
+ return { value: validateOptions(filtered, validatorMap, recordDefaults, logger, name) };
429
+ },
430
+ };
431
+ }
324
432
 
433
+ const BACKGROUND_POLL_INTERVAL_SECONDS = 3600;
325
434
  const dataSourceTypeValidator = TypeValidators.oneOf('cache', 'polling', 'streaming');
326
435
  const connectionModeValidator = TypeValidators.oneOf('streaming', 'polling', 'offline', 'one-shot', 'background');
327
436
  const endpointValidators = {
328
437
  pollingBaseUri: TypeValidators.String,
329
438
  streamingBaseUri: TypeValidators.String,
330
439
  };
331
- ({
440
+ const cacheEntryValidators = {
441
+ type: dataSourceTypeValidator,
442
+ };
443
+ const pollingEntryValidators = {
332
444
  type: dataSourceTypeValidator,
333
445
  pollInterval: TypeValidators.numberWithMin(30),
334
446
  endpoints: validatorOf(endpointValidators),
335
- });
336
- ({
447
+ };
448
+ const streamingEntryValidators = {
337
449
  type: dataSourceTypeValidator,
338
450
  initialReconnectDelay: TypeValidators.numberWithMin(1),
339
451
  endpoints: validatorOf(endpointValidators),
452
+ };
453
+ const initializerEntryArrayValidator = arrayOf('type', {
454
+ cache: cacheEntryValidators,
455
+ polling: pollingEntryValidators,
456
+ streaming: streamingEntryValidators,
457
+ });
458
+ const synchronizerEntryArrayValidator = arrayOf('type', {
459
+ polling: pollingEntryValidators,
460
+ streaming: streamingEntryValidators,
340
461
  });
462
+ const modeDefinitionValidators = {
463
+ initializers: initializerEntryArrayValidator,
464
+ synchronizers: synchronizerEntryArrayValidator,
465
+ };
466
+ const connectionModesValidator = recordOf(connectionModeValidator, validatorOf(modeDefinitionValidators));
467
+ const MODE_TABLE = {
468
+ streaming: {
469
+ initializers: [{ type: 'cache' }, { type: 'polling' }],
470
+ synchronizers: [{ type: 'streaming' }, { type: 'polling' }],
471
+ },
472
+ polling: {
473
+ initializers: [{ type: 'cache' }],
474
+ synchronizers: [{ type: 'polling' }],
475
+ },
476
+ offline: {
477
+ initializers: [{ type: 'cache' }],
478
+ synchronizers: [],
479
+ },
480
+ 'one-shot': {
481
+ initializers: [{ type: 'cache' }, { type: 'polling' }, { type: 'streaming' }],
482
+ synchronizers: [],
483
+ },
484
+ background: {
485
+ initializers: [{ type: 'cache' }],
486
+ synchronizers: [{ type: 'polling', pollInterval: BACKGROUND_POLL_INTERVAL_SECONDS }],
487
+ },
488
+ };
341
489
 
342
490
  const modeSwitchingValidators = {
343
491
  lifecycle: TypeValidators.Boolean,
@@ -347,6 +495,7 @@ const dataSystemValidators = {
347
495
  initialConnectionMode: connectionModeValidator,
348
496
  backgroundConnectionMode: connectionModeValidator,
349
497
  automaticModeSwitching: anyOf(TypeValidators.Boolean, validatorOf(modeSwitchingValidators)),
498
+ connectionModes: connectionModesValidator,
350
499
  };
351
500
  /**
352
501
  * Default FDv2 data system configuration for browser SDKs.
@@ -818,6 +967,33 @@ async function hashContext(crypto, context) {
818
967
  }
819
968
  return digest(crypto.createHash('sha256').update(json), 'base64');
820
969
  }
970
+ /**
971
+ * Reads the freshness timestamp from storage for the given context.
972
+ *
973
+ * Returns `undefined` if no freshness record exists, the data is corrupt,
974
+ * or the context attributes have changed since the freshness was recorded.
975
+ */
976
+ async function readFreshness(storage, crypto, environmentNamespace, context, logger) {
977
+ const contextStorageKey = await namespaceForContextData(crypto, environmentNamespace, context);
978
+ const json = await storage.get(`${contextStorageKey}${FRESHNESS_SUFFIX}`);
979
+ if (json === null || json === undefined) {
980
+ return undefined;
981
+ }
982
+ try {
983
+ const record = JSON.parse(json);
984
+ const currentHash = await hashContext(crypto, context);
985
+ if (currentHash === undefined || record.contextHash !== currentHash) {
986
+ return undefined;
987
+ }
988
+ return typeof record.timestamp === 'number' && !Number.isNaN(record.timestamp)
989
+ ? record.timestamp
990
+ : undefined;
991
+ }
992
+ catch (e) {
993
+ logger?.warn(`Could not read freshness data from persistent storage: ${e.message}`);
994
+ return undefined;
995
+ }
996
+ }
821
997
 
822
998
  function isValidFlag(value) {
823
999
  return value !== null && typeof value === 'object' && typeof value.version === 'number';
@@ -971,6 +1147,19 @@ class FlagPersistence {
971
1147
  }
972
1148
  return false;
973
1149
  }
1150
+ /**
1151
+ * Applies a changeset to the flag store.
1152
+ * - `'full'`: replaces all flags via {@link FlagUpdater.init}.
1153
+ * - `'partial'`: upserts individual flags via {@link FlagUpdater.upsert}.
1154
+ * - `'none'`: no flag changes, only persists cache to update freshness.
1155
+ *
1156
+ * Always persists to cache afterwards, which updates the freshness timestamp
1157
+ * even when no flags change (e.g., transfer-none).
1158
+ */
1159
+ async applyChanges(context, updates, type) {
1160
+ this._flagUpdater.applyChanges(context, updates, type);
1161
+ await this._storeCache(context);
1162
+ }
974
1163
  /**
975
1164
  * Loads the flags from persistence for the provided context and gives those to the
976
1165
  * {@link FlagUpdater} this {@link FlagPersistence} was constructed with.
@@ -1094,6 +1283,16 @@ function createDefaultFlagStore() {
1094
1283
  getAll() {
1095
1284
  return flags;
1096
1285
  },
1286
+ applyChanges(updates, type) {
1287
+ if (type === 'full') {
1288
+ this.init(updates);
1289
+ }
1290
+ else if (type === 'partial') {
1291
+ Object.entries(updates).forEach(([key, descriptor]) => {
1292
+ flags[key] = descriptor;
1293
+ });
1294
+ }
1295
+ },
1097
1296
  };
1098
1297
  }
1099
1298
 
@@ -1151,6 +1350,24 @@ function createFlagUpdater(_flagStore, _logger) {
1151
1350
  }
1152
1351
  this.init(context, newFlags);
1153
1352
  },
1353
+ applyChanges(context, updates, type) {
1354
+ activeContext = context;
1355
+ const oldFlags = flagStore.getAll();
1356
+ flagStore.applyChanges(updates, type);
1357
+ if (type === 'full') {
1358
+ const changed = calculateChangedKeys(oldFlags, updates);
1359
+ if (changed.length > 0) {
1360
+ this.handleFlagChanges(changed, 'init');
1361
+ }
1362
+ }
1363
+ else if (type === 'partial') {
1364
+ const keys = Object.keys(updates);
1365
+ if (keys.length > 0) {
1366
+ this.handleFlagChanges(keys, 'patch');
1367
+ }
1368
+ }
1369
+ // 'none' — no flag changes, caller handles freshness.
1370
+ },
1154
1371
  upsert(context, key, item) {
1155
1372
  if (activeContext?.canonicalKey !== context.canonicalKey) {
1156
1373
  logger.warn('Received an update for an inactive context.');
@@ -1230,6 +1447,9 @@ class DefaultFlagManager {
1230
1447
  async loadCached(context) {
1231
1448
  return (await this._flagPersistencePromise).loadCached(context);
1232
1449
  }
1450
+ async applyChanges(context, updates, type) {
1451
+ return (await this._flagPersistencePromise).applyChanges(context, updates, type);
1452
+ }
1233
1453
  on(callback) {
1234
1454
  this._flagUpdater.on(callback);
1235
1455
  }
@@ -2826,5 +3046,909 @@ const DESKTOP_TRANSITION_TABLE = [
2826
3046
  { conditions: {}, mode: { configured: 'foreground' } },
2827
3047
  ];
2828
3048
 
2829
- export { BROWSER_DATA_SYSTEM_DEFAULTS, BROWSER_TRANSITION_TABLE, BaseDataManager, DESKTOP_DATA_SYSTEM_DEFAULTS, DESKTOP_TRANSITION_TABLE, DataSourceState, LDClientImpl, MOBILE_DATA_SYSTEM_DEFAULTS, MOBILE_TRANSITION_TABLE, browserFdv1Endpoints, dataSystemValidators, fdv2Endpoints, makeRequestor, mobileFdv1Endpoints, readFlagsFromBootstrap, resolveConnectionMode, safeRegisterDebugOverridePlugins, validateOptions };
3049
+ /**
3050
+ * Creates a change set result containing processed flag data.
3051
+ */
3052
+ function changeSet(payload, fdv1Fallback, environmentId, freshness) {
3053
+ return { type: 'changeSet', payload, fdv1Fallback, environmentId, freshness };
3054
+ }
3055
+ /**
3056
+ * Creates an interrupted status result. Indicates a transient error; the
3057
+ * synchronizer will attempt to recover automatically.
3058
+ *
3059
+ * When used with an initializer, this is still a terminal state.
3060
+ */
3061
+ function interrupted(errorInfo, fdv1Fallback) {
3062
+ return { type: 'status', state: 'interrupted', errorInfo, fdv1Fallback };
3063
+ }
3064
+ /**
3065
+ * Creates a shutdown status result. Indicates the data source was closed
3066
+ * gracefully and will not produce any further results.
3067
+ */
3068
+ function shutdown() {
3069
+ return { type: 'status', state: 'shutdown', fdv1Fallback: false };
3070
+ }
3071
+ /**
3072
+ * Creates a terminal error status result. Indicates an unrecoverable error;
3073
+ * the data source will not produce any further results.
3074
+ */
3075
+ function terminalError(errorInfo, fdv1Fallback) {
3076
+ return { type: 'status', state: 'terminal_error', errorInfo, fdv1Fallback };
3077
+ }
3078
+ /**
3079
+ * Creates a goodbye status result. Indicates the server has instructed the
3080
+ * client to disconnect.
3081
+ */
3082
+ function goodbye(reason, fdv1Fallback) {
3083
+ return { type: 'status', state: 'goodbye', reason, fdv1Fallback };
3084
+ }
3085
+ /**
3086
+ * Helper to create a {@link DataSourceStatusErrorInfo} from an HTTP status code.
3087
+ */
3088
+ function errorInfoFromHttpError(statusCode) {
3089
+ return {
3090
+ kind: DataSourceErrorKind.ErrorResponse,
3091
+ message: `Unexpected status code: ${statusCode}`,
3092
+ statusCode,
3093
+ time: Date.now(),
3094
+ };
3095
+ }
3096
+ /**
3097
+ * Helper to create a {@link DataSourceStatusErrorInfo} from a network error.
3098
+ */
3099
+ function errorInfoFromNetworkError(message) {
3100
+ return {
3101
+ kind: DataSourceErrorKind.NetworkError,
3102
+ message,
3103
+ time: Date.now(),
3104
+ };
3105
+ }
3106
+ /**
3107
+ * Helper to create a {@link DataSourceStatusErrorInfo} from invalid data.
3108
+ */
3109
+ function errorInfoFromInvalidData(message) {
3110
+ return {
3111
+ kind: DataSourceErrorKind.InvalidData,
3112
+ message,
3113
+ time: Date.now(),
3114
+ };
3115
+ }
3116
+ /**
3117
+ * Helper to create a {@link DataSourceStatusErrorInfo} for unknown errors.
3118
+ */
3119
+ function errorInfoFromUnknown(message) {
3120
+ return {
3121
+ kind: DataSourceErrorKind.Unknown,
3122
+ message,
3123
+ time: Date.now(),
3124
+ };
3125
+ }
3126
+
3127
+ /**
3128
+ * Strips the `version` field from a stored {@link Flag} to produce the
3129
+ * `FlagEvaluationResult` shape expected in an FDv2 `Update.object`.
3130
+ *
3131
+ * The version is carried on the `Update` envelope, not on the object itself.
3132
+ */
3133
+ function flagToEvaluationResult(flag) {
3134
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3135
+ const { version, ...evalResult } = flag;
3136
+ return evalResult;
3137
+ }
3138
+ /**
3139
+ * Reads cached flag data and freshness from platform storage and returns
3140
+ * them as an {@link FDv2SourceResult}.
3141
+ */
3142
+ async function loadFromCache(config) {
3143
+ const { storage, crypto, environmentNamespace, context, logger } = config;
3144
+ if (!storage) {
3145
+ logger?.debug('No storage available for cache initializer');
3146
+ return interrupted(errorInfoFromUnknown('No storage available'), false);
3147
+ }
3148
+ const cached = await loadCachedFlags(storage, crypto, environmentNamespace, context, logger);
3149
+ if (!cached) {
3150
+ logger?.debug('Cache miss for context');
3151
+ return interrupted(errorInfoFromUnknown('Cache miss'), false);
3152
+ }
3153
+ const updates = Object.entries(cached.flags).map(([key, flag]) => ({
3154
+ kind: 'flag-eval',
3155
+ key,
3156
+ version: flag.version,
3157
+ object: flagToEvaluationResult(flag),
3158
+ }));
3159
+ const payload = {
3160
+ id: 'cache',
3161
+ version: 0,
3162
+ // No `state` field. The orchestrator sees a changeSet without a selector,
3163
+ // records dataReceived=true, and continues to the next initializer.
3164
+ type: 'full',
3165
+ updates,
3166
+ };
3167
+ const freshness = await readFreshness(storage, crypto, environmentNamespace, context, logger);
3168
+ logger?.debug('Loaded cached flag evaluations via cache initializer');
3169
+ return changeSet(payload, false, undefined, freshness);
3170
+ }
3171
+ /**
3172
+ * Creates an {@link InitializerFactory} that produces cache initializers.
3173
+ *
3174
+ * The cache initializer reads flag data and freshness from persistent storage
3175
+ * for the given context and returns them as a changeSet without a selector.
3176
+ * This allows the orchestrator to provide cached data immediately while
3177
+ * continuing to the next initializer for network-verified data.
3178
+ *
3179
+ * Per spec Requirement 4.1.2, the payload has `persist=false` semantics
3180
+ * (no selector) so the consuming layer should not re-persist it.
3181
+ *
3182
+ * @internal
3183
+ */
3184
+ function createCacheInitializerFactory(config) {
3185
+ // The selectorGetter is ignored — cache data has no selector.
3186
+ return (_selectorGetter) => {
3187
+ let shutdownResolve;
3188
+ const shutdownPromise = new Promise((resolve) => {
3189
+ shutdownResolve = resolve;
3190
+ });
3191
+ return {
3192
+ async run() {
3193
+ return Promise.race([shutdownPromise, loadFromCache(config)]);
3194
+ },
3195
+ close() {
3196
+ shutdownResolve?.(shutdown());
3197
+ shutdownResolve = undefined;
3198
+ },
3199
+ };
3200
+ };
3201
+ }
3202
+
3203
+ /**
3204
+ * Creates an {@link FDv2Requestor} for client-side FDv2 polling.
3205
+ *
3206
+ * @param plainContextString The JSON-serialized evaluation context.
3207
+ * @param serviceEndpoints Service endpoint configuration.
3208
+ * @param paths FDv2 polling endpoint paths.
3209
+ * @param requests Platform HTTP abstraction.
3210
+ * @param encoding Platform encoding abstraction.
3211
+ * @param baseHeaders Default HTTP headers (e.g. authorization).
3212
+ * @param baseQueryParams Additional query parameters to include on every request.
3213
+ * @param usePost If true, use POST with context in body instead of GET with
3214
+ * context in URL path.
3215
+ */
3216
+ function makeFDv2Requestor(plainContextString, serviceEndpoints, paths, requests, encoding, baseHeaders, baseQueryParams, usePost) {
3217
+ const headers = { ...baseHeaders };
3218
+ let body;
3219
+ let method = 'GET';
3220
+ let path;
3221
+ if (usePost) {
3222
+ method = 'POST';
3223
+ headers['content-type'] = 'application/json';
3224
+ body = plainContextString;
3225
+ path = paths.pathPost(encoding, plainContextString);
3226
+ }
3227
+ else {
3228
+ path = paths.pathGet(encoding, plainContextString);
3229
+ }
3230
+ return {
3231
+ async poll(basis) {
3232
+ const parameters = [...(baseQueryParams ?? [])];
3233
+ // Intentionally falsy check: an empty string basis must not be sent as
3234
+ // a query parameter, since it does not represent a valid selector.
3235
+ if (basis) {
3236
+ parameters.push({ key: 'basis', value: basis });
3237
+ }
3238
+ const uri = getPollingUri(serviceEndpoints, path, parameters);
3239
+ const res = await requests.fetch(uri, {
3240
+ method,
3241
+ headers,
3242
+ body,
3243
+ });
3244
+ const responseBody = res.status === 304 ? null : await res.text();
3245
+ return {
3246
+ status: res.status,
3247
+ headers: res.headers,
3248
+ body: responseBody,
3249
+ };
3250
+ },
3251
+ };
3252
+ }
3253
+
3254
+ /**
3255
+ * ObjProcessor for the `flag-eval` object kind. Used by the protocol handler to
3256
+ * process objects received in `put-object` events.
3257
+ *
3258
+ * Client-side evaluation results are already in their final form (pre-evaluated
3259
+ * by the server), so no transformation is needed — this is a passthrough.
3260
+ */
3261
+ function processFlagEval(object) {
3262
+ return object;
3263
+ }
3264
+
3265
+ function getFallback(headers) {
3266
+ const value = headers.get('x-ld-fd-fallback');
3267
+ return value !== null && value.toLowerCase() === 'true';
3268
+ }
3269
+ function getEnvironmentId(headers) {
3270
+ return headers.get('x-ld-envid') ?? undefined;
3271
+ }
3272
+ /**
3273
+ * Process FDv2 events using the protocol handler directly.
3274
+ *
3275
+ * We use `createProtocolHandler` rather than `PayloadProcessor` because
3276
+ * the PayloadProcessor does not surface goodbye/serverError actions —
3277
+ * it only forwards payloads and actionable errors. For polling results,
3278
+ * we need full control over all protocol action types.
3279
+ */
3280
+ function processEvents(events, oneShot, fdv1Fallback, environmentId, logger) {
3281
+ const handler = internal.createProtocolHandler({
3282
+ 'flag-eval': processFlagEval,
3283
+ }, logger);
3284
+ let earlyResult;
3285
+ events.forEach((event) => {
3286
+ if (earlyResult) {
3287
+ return;
3288
+ }
3289
+ const action = handler.processEvent(event);
3290
+ switch (action.type) {
3291
+ case 'payload':
3292
+ earlyResult = changeSet(action.payload, fdv1Fallback, environmentId);
3293
+ break;
3294
+ case 'goodbye':
3295
+ earlyResult = goodbye(action.reason, fdv1Fallback);
3296
+ break;
3297
+ case 'serverError': {
3298
+ const errorInfo = errorInfoFromUnknown(action.reason);
3299
+ logger?.error(`Server error during polling: ${action.reason}`);
3300
+ earlyResult = oneShot
3301
+ ? terminalError(errorInfo, fdv1Fallback)
3302
+ : interrupted(errorInfo, fdv1Fallback);
3303
+ break;
3304
+ }
3305
+ case 'error': {
3306
+ // Actionable protocol errors (MISSING_PAYLOAD, PROTOCOL_ERROR)
3307
+ if (action.kind === 'MISSING_PAYLOAD' || action.kind === 'PROTOCOL_ERROR') {
3308
+ const errorInfo = errorInfoFromInvalidData(action.message);
3309
+ logger?.warn(`Protocol error during polling: ${action.message}`);
3310
+ earlyResult = oneShot
3311
+ ? terminalError(errorInfo, fdv1Fallback)
3312
+ : interrupted(errorInfo, fdv1Fallback);
3313
+ }
3314
+ else {
3315
+ // Non-actionable errors (UNKNOWN_EVENT) are logged but don't stop processing
3316
+ logger?.warn(action.message);
3317
+ }
3318
+ break;
3319
+ }
3320
+ }
3321
+ });
3322
+ if (earlyResult) {
3323
+ return earlyResult;
3324
+ }
3325
+ // Events didn't produce a result
3326
+ const errorInfo = errorInfoFromUnknown('Unexpected end of polling response');
3327
+ logger?.error('Unexpected end of polling response');
3328
+ return oneShot ? terminalError(errorInfo, fdv1Fallback) : interrupted(errorInfo, fdv1Fallback);
3329
+ }
3330
+ /**
3331
+ * Performs a single FDv2 poll request, processes the protocol response, and
3332
+ * returns an {@link FDv2SourceResult}.
3333
+ *
3334
+ * The `oneShot` parameter controls error handling: when true (initializer),
3335
+ * all errors are terminal; when false (synchronizer), recoverable errors
3336
+ * produce interrupted results.
3337
+ *
3338
+ * @internal
3339
+ */
3340
+ async function poll(requestor, basis, oneShot, logger) {
3341
+ let fdv1Fallback = false;
3342
+ let environmentId;
3343
+ try {
3344
+ const response = await requestor.poll(basis);
3345
+ fdv1Fallback = getFallback(response.headers);
3346
+ environmentId = getEnvironmentId(response.headers);
3347
+ // 304 Not Modified: treat as server-intent with intentCode 'none'
3348
+ // (Spec Requirement 10.1.2)
3349
+ if (response.status === 304) {
3350
+ const nonePayload = {
3351
+ id: '',
3352
+ version: 0,
3353
+ type: 'none',
3354
+ updates: [],
3355
+ };
3356
+ return changeSet(nonePayload, fdv1Fallback, environmentId);
3357
+ }
3358
+ // Non-success HTTP status
3359
+ if (response.status < 200 || response.status >= 300) {
3360
+ const errorInfo = errorInfoFromHttpError(response.status);
3361
+ logger?.error(`Polling request failed with HTTP error: ${response.status}`);
3362
+ if (oneShot) {
3363
+ return terminalError(errorInfo, fdv1Fallback);
3364
+ }
3365
+ const recoverable = response.status <= 0 || isHttpRecoverable(response.status);
3366
+ return recoverable
3367
+ ? interrupted(errorInfo, fdv1Fallback)
3368
+ : terminalError(errorInfo, fdv1Fallback);
3369
+ }
3370
+ // Successful response — process FDv2 events
3371
+ if (!response.body) {
3372
+ const errorInfo = errorInfoFromInvalidData('Empty response body');
3373
+ logger?.error('Polling request received empty response body');
3374
+ return oneShot
3375
+ ? terminalError(errorInfo, fdv1Fallback)
3376
+ : interrupted(errorInfo, fdv1Fallback);
3377
+ }
3378
+ let parsed;
3379
+ try {
3380
+ parsed = JSON.parse(response.body);
3381
+ }
3382
+ catch {
3383
+ const errorInfo = errorInfoFromInvalidData('Malformed JSON data in polling response');
3384
+ logger?.error('Polling request received malformed data');
3385
+ return oneShot
3386
+ ? terminalError(errorInfo, fdv1Fallback)
3387
+ : interrupted(errorInfo, fdv1Fallback);
3388
+ }
3389
+ if (!Array.isArray(parsed.events)) {
3390
+ const errorInfo = errorInfoFromInvalidData('Invalid polling response: missing or invalid events array');
3391
+ logger?.error('Polling response does not contain a valid events array');
3392
+ return oneShot
3393
+ ? terminalError(errorInfo, fdv1Fallback)
3394
+ : interrupted(errorInfo, fdv1Fallback);
3395
+ }
3396
+ return processEvents(parsed.events, oneShot, fdv1Fallback, environmentId, logger);
3397
+ }
3398
+ catch (err) {
3399
+ // Network or other I/O error from the fetch itself
3400
+ const message = err?.message ?? String(err);
3401
+ logger?.error(`Polling request failed with network error: ${message}`);
3402
+ const errorInfo = errorInfoFromNetworkError(message);
3403
+ return oneShot ? terminalError(errorInfo, fdv1Fallback) : interrupted(errorInfo, fdv1Fallback);
3404
+ }
3405
+ }
3406
+
3407
+ /**
3408
+ * Creates a one-shot polling initializer that performs a single FDv2 poll
3409
+ * request and returns the result.
3410
+ *
3411
+ * All errors are treated as terminal (oneShot=true). If `close()` is called
3412
+ * before the poll completes, the result will be a shutdown status.
3413
+ *
3414
+ * @internal
3415
+ */
3416
+ function createPollingInitializer(requestor, logger, selectorGetter) {
3417
+ let shutdownResolve;
3418
+ const shutdownPromise = new Promise((resolve) => {
3419
+ shutdownResolve = resolve;
3420
+ });
3421
+ return {
3422
+ async run() {
3423
+ const pollResult = poll(requestor, selectorGetter(), true, logger);
3424
+ // Race the poll against the shutdown signal
3425
+ return Promise.race([shutdownPromise, pollResult]);
3426
+ },
3427
+ close() {
3428
+ shutdownResolve?.(shutdown());
3429
+ shutdownResolve = undefined;
3430
+ },
3431
+ };
3432
+ }
3433
+
3434
+ /**
3435
+ * Creates a new {@link AsyncQueue}.
3436
+ *
3437
+ * @internal
3438
+ */
3439
+ function createAsyncQueue() {
3440
+ const items = [];
3441
+ const waiters = [];
3442
+ return {
3443
+ put(item) {
3444
+ const waiter = waiters.shift();
3445
+ if (waiter) {
3446
+ waiter(item);
3447
+ }
3448
+ else {
3449
+ items.push(item);
3450
+ }
3451
+ },
3452
+ take() {
3453
+ if (items.length > 0) {
3454
+ return Promise.resolve(items.shift());
3455
+ }
3456
+ return new Promise((resolve) => {
3457
+ waiters.push(resolve);
3458
+ });
3459
+ },
3460
+ };
3461
+ }
3462
+
3463
+ /**
3464
+ * Creates a continuous polling synchronizer that periodically polls for FDv2
3465
+ * data and yields results via successive calls to `next()`.
3466
+ *
3467
+ * The first poll fires immediately. Subsequent polls are scheduled using
3468
+ * `setTimeout` after each poll completes, ensuring sequential execution and
3469
+ * preventing overlapping requests on slow networks.
3470
+ *
3471
+ * Results are buffered in an async queue. On terminal errors, polling stops
3472
+ * and the shutdown future is resolved. On `close()`, polling stops and the
3473
+ * next `next()` call returns a shutdown result.
3474
+ *
3475
+ * @internal
3476
+ */
3477
+ function createPollingSynchronizer(requestor, logger, selectorGetter, pollIntervalMs) {
3478
+ const resultQueue = createAsyncQueue();
3479
+ let shutdownResolve;
3480
+ const shutdownPromise = new Promise((resolve) => {
3481
+ shutdownResolve = resolve;
3482
+ });
3483
+ let timeoutHandle;
3484
+ let stopped = false;
3485
+ async function doPoll() {
3486
+ if (stopped) {
3487
+ return;
3488
+ }
3489
+ const startTime = Date.now();
3490
+ try {
3491
+ const result = await poll(requestor, selectorGetter(), false, logger);
3492
+ if (stopped) {
3493
+ return;
3494
+ }
3495
+ let shouldShutdown = false;
3496
+ if (result.type === 'status') {
3497
+ switch (result.state) {
3498
+ case 'terminal_error':
3499
+ stopped = true;
3500
+ shouldShutdown = true;
3501
+ break;
3502
+ case 'interrupted':
3503
+ case 'goodbye':
3504
+ // Continue polling on transient errors and goodbyes
3505
+ break;
3506
+ case 'shutdown':
3507
+ // The base poll function doesn't emit shutdown; we handle it
3508
+ // at this level via close().
3509
+ break;
3510
+ default:
3511
+ break;
3512
+ }
3513
+ }
3514
+ if (shouldShutdown) {
3515
+ shutdownResolve?.(result);
3516
+ shutdownResolve = undefined;
3517
+ }
3518
+ else {
3519
+ resultQueue.put(result);
3520
+ }
3521
+ }
3522
+ catch (err) {
3523
+ logger?.debug(`Polling error: ${err}`);
3524
+ }
3525
+ // Schedule next poll after completion, accounting for elapsed time.
3526
+ // This ensures sequential execution — no overlapping requests.
3527
+ if (!stopped) {
3528
+ const elapsed = Date.now() - startTime;
3529
+ const sleepFor = Math.min(Math.max(pollIntervalMs - elapsed, 0), pollIntervalMs);
3530
+ timeoutHandle = setTimeout(() => {
3531
+ doPoll();
3532
+ }, sleepFor);
3533
+ }
3534
+ }
3535
+ // Start polling immediately
3536
+ doPoll();
3537
+ return {
3538
+ async next() {
3539
+ return Promise.race([shutdownPromise, resultQueue.take()]);
3540
+ },
3541
+ close() {
3542
+ stopped = true;
3543
+ if (timeoutHandle !== undefined) {
3544
+ clearTimeout(timeoutHandle);
3545
+ timeoutHandle = undefined;
3546
+ }
3547
+ shutdownResolve?.(shutdown());
3548
+ shutdownResolve = undefined;
3549
+ },
3550
+ };
3551
+ }
3552
+
3553
+ /**
3554
+ * Creates a {@link SynchronizerSlot}.
3555
+ *
3556
+ * @param factory The synchronizer factory function.
3557
+ * @param options Optional configuration.
3558
+ * @param options.isFDv1Fallback Whether this slot is the FDv1 fallback adapter.
3559
+ * FDv1 slots start `'blocked'` by default.
3560
+ * @param options.initialState Override the initial state (defaults to
3561
+ * `'blocked'` for FDv1 slots, `'available'` otherwise).
3562
+ */
3563
+ function createSynchronizerSlot(factory, options) {
3564
+ const isFDv1Fallback = options?.isFDv1Fallback ?? false;
3565
+ const state = options?.initialState ?? (isFDv1Fallback ? 'blocked' : 'available');
3566
+ return { factory, isFDv1Fallback, state };
3567
+ }
3568
+
3569
+ /**
3570
+ * FDv2 event names to listen for on the EventSource. This must stay in sync
3571
+ * with the `EventType` union defined in `@launchdarkly/js-sdk-common`'s
3572
+ * `internal/fdv2/proto.ts`.
3573
+ */
3574
+ const FDV2_EVENT_NAMES = [
3575
+ 'server-intent',
3576
+ 'put-object',
3577
+ 'delete-object',
3578
+ 'payload-transferred',
3579
+ 'goodbye',
3580
+ 'error',
3581
+ 'heart-beat',
3582
+ ];
3583
+ /**
3584
+ * Creates the core streaming base for FDv2 client-side data sources.
3585
+ *
3586
+ * Manages an EventSource connection, processes FDv2 protocol events using
3587
+ * a protocol handler from the common package, detects FDv1 fallback signals,
3588
+ * handles legacy ping events, and queues results for consumption by
3589
+ * {@link createStreamingInitializer} or {@link createStreamingSynchronizer}.
3590
+ *
3591
+ * @internal
3592
+ */
3593
+ function createStreamingBase(config) {
3594
+ const resultQueue = createAsyncQueue();
3595
+ const protocolHandler = internal.createProtocolHandler({ 'flag-eval': processFlagEval }, config.logger);
3596
+ const headers = { ...config.headers };
3597
+ function buildStreamUri() {
3598
+ const params = [...config.parameters];
3599
+ const basis = config.selectorGetter?.();
3600
+ if (basis) {
3601
+ params.push({ key: 'basis', value: encodeURIComponent(basis) });
3602
+ }
3603
+ return getStreamingUri(config.serviceEndpoints, config.streamUriPath, params);
3604
+ }
3605
+ let eventSource;
3606
+ let connectionAttemptStartTime;
3607
+ let fdv1Fallback = false;
3608
+ let started = false;
3609
+ let stopped = false;
3610
+ function logConnectionAttempt() {
3611
+ connectionAttemptStartTime = Date.now();
3612
+ }
3613
+ function logConnectionResult(success) {
3614
+ if (connectionAttemptStartTime && config.diagnosticsManager) {
3615
+ config.diagnosticsManager.recordStreamInit(connectionAttemptStartTime, !success, Date.now() - connectionAttemptStartTime);
3616
+ }
3617
+ connectionAttemptStartTime = undefined;
3618
+ }
3619
+ function handleAction(action) {
3620
+ switch (action.type) {
3621
+ case 'payload':
3622
+ logConnectionResult(true);
3623
+ resultQueue.put(changeSet(action.payload, fdv1Fallback));
3624
+ break;
3625
+ case 'goodbye':
3626
+ resultQueue.put(goodbye(action.reason, fdv1Fallback));
3627
+ break;
3628
+ case 'serverError':
3629
+ resultQueue.put(interrupted(errorInfoFromUnknown(action.reason), fdv1Fallback));
3630
+ break;
3631
+ case 'error':
3632
+ // Only actionable errors are queued; informational ones (UNKNOWN_EVENT)
3633
+ // are logged by the protocol handler.
3634
+ if (action.kind === 'MISSING_PAYLOAD' || action.kind === 'PROTOCOL_ERROR') {
3635
+ resultQueue.put(interrupted(errorInfoFromInvalidData(action.message), fdv1Fallback));
3636
+ }
3637
+ break;
3638
+ }
3639
+ }
3640
+ function handleError(err) {
3641
+ // Check for FDv1 fallback header.
3642
+ if (err.headers?.['x-ld-fd-fallback'] === 'true') {
3643
+ fdv1Fallback = true;
3644
+ logConnectionResult(false);
3645
+ resultQueue.put(terminalError(errorInfoFromHttpError(err.status ?? 0), true));
3646
+ return false;
3647
+ }
3648
+ if (!shouldRetry(err)) {
3649
+ config.logger?.error(httpErrorMessage(err, 'streaming request'));
3650
+ logConnectionResult(false);
3651
+ resultQueue.put(terminalError(errorInfoFromHttpError(err.status ?? 0), fdv1Fallback));
3652
+ return false;
3653
+ }
3654
+ config.logger?.warn(httpErrorMessage(err, 'streaming request', 'will retry'));
3655
+ logConnectionResult(false);
3656
+ logConnectionAttempt();
3657
+ resultQueue.put(interrupted(errorInfoFromHttpError(err.status ?? 0), fdv1Fallback));
3658
+ return true;
3659
+ }
3660
+ function attachFDv2Listeners(es) {
3661
+ FDV2_EVENT_NAMES.forEach((eventName) => {
3662
+ es.addEventListener(eventName, (event) => {
3663
+ if (stopped) {
3664
+ config.logger?.debug(`Received ${eventName} event after processor was closed. Skipping.`);
3665
+ return;
3666
+ }
3667
+ if (!event?.data) {
3668
+ // Some events (e.g. 'error') may legitimately arrive without a body.
3669
+ if (eventName !== 'error') {
3670
+ config.logger?.warn(`Event from EventStream missing data for "${eventName}".`);
3671
+ }
3672
+ return;
3673
+ }
3674
+ config.logger?.debug(`Received ${eventName} event`);
3675
+ let parsed;
3676
+ try {
3677
+ parsed = JSON.parse(event.data);
3678
+ }
3679
+ catch {
3680
+ config.logger?.error(`Stream received data that was unable to be parsed in "${eventName}" message`);
3681
+ config.logger?.debug(`Data follows: ${event.data}`);
3682
+ resultQueue.put(interrupted(errorInfoFromInvalidData('Malformed JSON in EventStream'), fdv1Fallback));
3683
+ return;
3684
+ }
3685
+ const action = protocolHandler.processEvent({ event: eventName, data: parsed });
3686
+ handleAction(action);
3687
+ });
3688
+ });
3689
+ }
3690
+ function attachPingListener(es) {
3691
+ es.addEventListener('ping', async () => {
3692
+ if (stopped) {
3693
+ config.logger?.debug('Ping received after processor was closed. Skipping.');
3694
+ return;
3695
+ }
3696
+ config.logger?.debug('Got PING, going to poll LaunchDarkly for feature flag updates');
3697
+ if (!config.pingHandler) {
3698
+ config.logger?.warn('Ping event received but no ping handler configured.');
3699
+ return;
3700
+ }
3701
+ try {
3702
+ const result = await config.pingHandler.handlePing();
3703
+ if (stopped) {
3704
+ config.logger?.debug('Ping completed after processor was closed. Skipping processing.');
3705
+ return;
3706
+ }
3707
+ resultQueue.put(result);
3708
+ }
3709
+ catch (err) {
3710
+ if (stopped) {
3711
+ return;
3712
+ }
3713
+ config.logger?.error(`Error handling ping: ${err?.message ?? err}`);
3714
+ resultQueue.put(interrupted(errorInfoFromNetworkError(err?.message ?? 'Error during ping poll'), fdv1Fallback));
3715
+ }
3716
+ });
3717
+ }
3718
+ return {
3719
+ start() {
3720
+ if (started || stopped) {
3721
+ return;
3722
+ }
3723
+ started = true;
3724
+ logConnectionAttempt();
3725
+ const es = config.requests.createEventSource(buildStreamUri(), {
3726
+ headers,
3727
+ errorFilter: (error) => handleError(error),
3728
+ initialRetryDelayMillis: config.initialRetryDelayMillis,
3729
+ readTimeoutMillis: 5 * 60 * 1000,
3730
+ retryResetIntervalMillis: 60 * 1000,
3731
+ });
3732
+ eventSource = es;
3733
+ attachFDv2Listeners(es);
3734
+ attachPingListener(es);
3735
+ es.onclose = () => {
3736
+ config.logger?.info('Closed LaunchDarkly stream connection');
3737
+ };
3738
+ es.onerror = (err) => {
3739
+ if (stopped) {
3740
+ return;
3741
+ }
3742
+ if (err && typeof err.status === 'number') {
3743
+ // This condition will be handled by the error filter.
3744
+ return;
3745
+ }
3746
+ resultQueue.put(interrupted(errorInfoFromNetworkError(err?.message ?? 'IO Error'), fdv1Fallback));
3747
+ };
3748
+ es.onopen = () => {
3749
+ config.logger?.info('Opened LaunchDarkly stream connection');
3750
+ protocolHandler.reset();
3751
+ };
3752
+ es.onretrying = (e) => {
3753
+ config.logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);
3754
+ };
3755
+ },
3756
+ close() {
3757
+ if (stopped) {
3758
+ return;
3759
+ }
3760
+ stopped = true;
3761
+ eventSource?.close();
3762
+ eventSource = undefined;
3763
+ resultQueue.put(shutdown());
3764
+ },
3765
+ takeResult() {
3766
+ return resultQueue.take();
3767
+ },
3768
+ };
3769
+ }
3770
+
3771
+ /**
3772
+ * Creates a one-shot streaming initializer for FDv2.
3773
+ *
3774
+ * Connects to the FDv2 streaming endpoint, waits for the first result
3775
+ * (a change set or an error status), then disconnects. Used in browser
3776
+ * `one-shot` mode where a persistent connection is not desired.
3777
+ *
3778
+ * If `close()` is called before a result arrives, the returned promise
3779
+ * resolves with a shutdown result.
3780
+ *
3781
+ * @param base - The streaming base that manages the EventSource connection.
3782
+ * @internal
3783
+ */
3784
+ function createStreamingInitializer(base) {
3785
+ let closed = false;
3786
+ let shutdownResolve;
3787
+ const shutdownPromise = new Promise((resolve) => {
3788
+ shutdownResolve = resolve;
3789
+ });
3790
+ return {
3791
+ run() {
3792
+ if (closed) {
3793
+ return Promise.resolve(shutdown());
3794
+ }
3795
+ base.start();
3796
+ return Promise.race([
3797
+ base.takeResult().then((result) => {
3798
+ // Got our first result — close the connection.
3799
+ base.close();
3800
+ return result;
3801
+ }),
3802
+ shutdownPromise,
3803
+ ]);
3804
+ },
3805
+ close() {
3806
+ if (closed) {
3807
+ return;
3808
+ }
3809
+ closed = true;
3810
+ base.close();
3811
+ shutdownResolve?.(shutdown());
3812
+ shutdownResolve = undefined;
3813
+ },
3814
+ };
3815
+ }
3816
+
3817
+ /**
3818
+ * Creates a long-lived streaming synchronizer for FDv2.
3819
+ *
3820
+ * Maintains a persistent EventSource connection to the FDv2 streaming
3821
+ * endpoint and produces a stream of results via the pull-based `next()`
3822
+ * method. Used in streaming connection mode.
3823
+ *
3824
+ * The connection is started lazily on the first call to `next()`.
3825
+ * On `close()`, the next call to `next()` returns a shutdown result.
3826
+ *
3827
+ * @param base - The streaming base that manages the EventSource connection.
3828
+ * @internal
3829
+ */
3830
+ function createStreamingSynchronizer(base) {
3831
+ let started = false;
3832
+ let closed = false;
3833
+ let shutdownResolve;
3834
+ const shutdownPromise = new Promise((resolve) => {
3835
+ shutdownResolve = resolve;
3836
+ });
3837
+ return {
3838
+ next() {
3839
+ if (closed) {
3840
+ return Promise.resolve(shutdown());
3841
+ }
3842
+ if (!started) {
3843
+ started = true;
3844
+ base.start();
3845
+ }
3846
+ return Promise.race([base.takeResult(), shutdownPromise]);
3847
+ },
3848
+ close() {
3849
+ if (closed) {
3850
+ return;
3851
+ }
3852
+ closed = true;
3853
+ base.close();
3854
+ shutdownResolve?.(shutdown());
3855
+ shutdownResolve = undefined;
3856
+ },
3857
+ };
3858
+ }
3859
+
3860
+ function createPingHandler(requestor, selectorGetter, logger) {
3861
+ return {
3862
+ handlePing: () => poll(requestor, selectorGetter(), false, logger),
3863
+ };
3864
+ }
3865
+ /**
3866
+ * Create a {@link ServiceEndpoints} with per-entry endpoint overrides applied.
3867
+ * Returns the original endpoints if no overrides are specified.
3868
+ */
3869
+ function resolveEndpoints(ctx, endpoints) {
3870
+ if (!endpoints?.pollingBaseUri && !endpoints?.streamingBaseUri) {
3871
+ return ctx.serviceEndpoints;
3872
+ }
3873
+ return new ServiceEndpoints(endpoints.streamingBaseUri ?? ctx.serviceEndpoints.streaming, endpoints.pollingBaseUri ?? ctx.serviceEndpoints.polling, ctx.serviceEndpoints.events, ctx.serviceEndpoints.analyticsEventPath, ctx.serviceEndpoints.diagnosticEventPath, ctx.serviceEndpoints.includeAuthorizationHeader, ctx.serviceEndpoints.payloadFilterKey);
3874
+ }
3875
+ /**
3876
+ * Get the FDv2 requestor for a polling entry. If the entry has custom
3877
+ * endpoints, creates a new requestor targeting those endpoints. Otherwise
3878
+ * returns the shared requestor from the context.
3879
+ */
3880
+ function resolvePollingRequestor(ctx, endpoints) {
3881
+ if (!endpoints?.pollingBaseUri) {
3882
+ return ctx.requestor;
3883
+ }
3884
+ const overriddenEndpoints = resolveEndpoints(ctx, endpoints);
3885
+ return makeFDv2Requestor(ctx.plainContextString, overriddenEndpoints, ctx.polling.paths, ctx.requests, ctx.encoding, ctx.baseHeaders, ctx.queryParams);
3886
+ }
3887
+ /**
3888
+ * Build a streaming base instance using per-entry config with context defaults
3889
+ * as fallbacks. The `sg` selector getter is the canonical source of truth for
3890
+ * the current selector — both the stream and its ping handler use it.
3891
+ */
3892
+ function buildStreamingBase(entry, ctx, sg) {
3893
+ const entryEndpoints = resolveEndpoints(ctx, entry.endpoints);
3894
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3895
+ const streamUriPath = ctx.streaming.paths.pathGet(ctx.encoding, ctx.plainContextString);
3896
+ return createStreamingBase({
3897
+ requests: ctx.requests,
3898
+ serviceEndpoints: entryEndpoints,
3899
+ streamUriPath,
3900
+ parameters: ctx.queryParams,
3901
+ selectorGetter: sg,
3902
+ headers: ctx.baseHeaders,
3903
+ initialRetryDelayMillis: (entry.initialReconnectDelay ?? ctx.streaming.initialReconnectDelaySeconds) * 1000,
3904
+ logger: ctx.logger,
3905
+ pingHandler: createPingHandler(requestor, sg, ctx.logger),
3906
+ });
3907
+ }
3908
+ /**
3909
+ * Creates a {@link SourceFactoryProvider} that handles `cache`, `polling`,
3910
+ * and `streaming` data source entries.
3911
+ */
3912
+ function createDefaultSourceFactoryProvider() {
3913
+ return {
3914
+ createInitializerFactory(entry, ctx) {
3915
+ switch (entry.type) {
3916
+ case 'polling': {
3917
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3918
+ return (sg) => createPollingInitializer(requestor, ctx.logger, sg);
3919
+ }
3920
+ case 'streaming':
3921
+ return (sg) => createStreamingInitializer(buildStreamingBase(entry, ctx, sg));
3922
+ case 'cache':
3923
+ return createCacheInitializerFactory({
3924
+ storage: ctx.storage,
3925
+ crypto: ctx.crypto,
3926
+ environmentNamespace: ctx.environmentNamespace,
3927
+ context: ctx.context,
3928
+ logger: ctx.logger,
3929
+ });
3930
+ default:
3931
+ return undefined;
3932
+ }
3933
+ },
3934
+ createSynchronizerSlot(entry, ctx) {
3935
+ switch (entry.type) {
3936
+ case 'polling': {
3937
+ const intervalMs = (entry.pollInterval ?? ctx.polling.intervalSeconds) * 1000;
3938
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3939
+ const factory = (sg) => createPollingSynchronizer(requestor, ctx.logger, sg, intervalMs);
3940
+ return createSynchronizerSlot(factory);
3941
+ }
3942
+ case 'streaming': {
3943
+ const factory = (sg) => createStreamingSynchronizer(buildStreamingBase(entry, ctx, sg));
3944
+ return createSynchronizerSlot(factory);
3945
+ }
3946
+ default:
3947
+ return undefined;
3948
+ }
3949
+ },
3950
+ };
3951
+ }
3952
+
3953
+ export { BROWSER_DATA_SYSTEM_DEFAULTS, BROWSER_TRANSITION_TABLE, BaseDataManager, DESKTOP_DATA_SYSTEM_DEFAULTS, DESKTOP_TRANSITION_TABLE, DataSourceState, LDClientImpl, MOBILE_DATA_SYSTEM_DEFAULTS, MOBILE_TRANSITION_TABLE, MODE_TABLE, browserFdv1Endpoints, createDataSourceStatusManager, createDefaultSourceFactoryProvider, dataSystemValidators, fdv2Endpoints, makeRequestor, mobileFdv1Endpoints, readFlagsFromBootstrap, resolveConnectionMode, safeRegisterDebugOverridePlugins, validateOptions };
2830
3954
  //# sourceMappingURL=index.mjs.map