@launchdarkly/js-sdk-common 2.28.1 → 2.30.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 (36) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cjs/api/platform/Requests.d.ts +85 -0
  3. package/dist/cjs/api/platform/Requests.d.ts.map +1 -1
  4. package/dist/cjs/datasource/retry/ResetPolicy.d.ts.map +1 -1
  5. package/dist/cjs/index.cjs +1074 -924
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/internal/fetch/StreamingResponse.d.ts +83 -0
  8. package/dist/cjs/internal/fetch/StreamingResponse.d.ts.map +1 -0
  9. package/dist/cjs/internal/fetch/index.d.ts +3 -0
  10. package/dist/cjs/internal/fetch/index.d.ts.map +1 -0
  11. package/dist/cjs/internal/fetch/toRequestInit.d.ts +12 -0
  12. package/dist/cjs/internal/fetch/toRequestInit.d.ts.map +1 -0
  13. package/dist/cjs/internal/index.d.ts +1 -0
  14. package/dist/cjs/internal/index.d.ts.map +1 -1
  15. package/dist/cjs/utils/index.d.ts +2 -1
  16. package/dist/cjs/utils/index.d.ts.map +1 -1
  17. package/dist/cjs/utils/time.d.ts +16 -0
  18. package/dist/cjs/utils/time.d.ts.map +1 -0
  19. package/dist/esm/api/platform/Requests.d.ts +85 -0
  20. package/dist/esm/api/platform/Requests.d.ts.map +1 -1
  21. package/dist/esm/datasource/retry/ResetPolicy.d.ts.map +1 -1
  22. package/dist/esm/index.mjs +1074 -925
  23. package/dist/esm/index.mjs.map +1 -1
  24. package/dist/esm/internal/fetch/StreamingResponse.d.ts +83 -0
  25. package/dist/esm/internal/fetch/StreamingResponse.d.ts.map +1 -0
  26. package/dist/esm/internal/fetch/index.d.ts +3 -0
  27. package/dist/esm/internal/fetch/index.d.ts.map +1 -0
  28. package/dist/esm/internal/fetch/toRequestInit.d.ts +12 -0
  29. package/dist/esm/internal/fetch/toRequestInit.d.ts.map +1 -0
  30. package/dist/esm/internal/index.d.ts +1 -0
  31. package/dist/esm/internal/index.d.ts.map +1 -1
  32. package/dist/esm/utils/index.d.ts +2 -1
  33. package/dist/esm/utils/index.d.ts.map +1 -1
  34. package/dist/esm/utils/time.d.ts +16 -0
  35. package/dist/esm/utils/time.d.ts.map +1 -0
  36. package/package.json +1 -1
@@ -1480,1059 +1480,1076 @@ var DataSourceErrorKind;
1480
1480
  DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
1481
1481
  })(DataSourceErrorKind || (DataSourceErrorKind = {}));
1482
1482
 
1483
- function defaultClock() {
1484
- const perf = globalThis?.performance;
1485
- if (perf && typeof perf.now === 'function') {
1486
- return () => perf.now();
1483
+ // These classes are of trivial complexity. If they become
1484
+ // more complex, then they could be independent files.
1485
+ class LDUnexpectedResponseError extends Error {
1486
+ constructor(message) {
1487
+ super(message);
1488
+ this.name = 'LaunchDarklyUnexpectedResponseError';
1489
+ }
1490
+ }
1491
+ class LDClientError extends Error {
1492
+ constructor(message) {
1493
+ super(message);
1494
+ this.name = 'LaunchDarklyClientError';
1495
+ }
1496
+ }
1497
+ class LDTimeoutError extends Error {
1498
+ constructor(message) {
1499
+ super(message);
1500
+ this.name = 'LaunchDarklyTimeoutError';
1487
1501
  }
1488
- return () => Date.now();
1489
1502
  }
1503
+ // HTTP statuses in the 4xx range that are still normal failures. Every other
1504
+ // 4xx is unexpected.
1505
+ const NORMAL_4XX_STATUSES = [400, 408, 429];
1490
1506
  /**
1491
- * Creates a policy that resets once the component has operated without failing
1492
- * for the given duration. Repeated healthy reports do not move the starting
1493
- * point; only a failure clears it.
1507
+ * Classifies an HTTP status.
1494
1508
  *
1495
- * @param healthyForMs How long the component must operate without failing,
1496
- * in milliseconds; must be a positive, finite number.
1497
- * @param clock The time source used to measure the healthy stretch; defaults
1498
- * to a monotonic clock. Primarily for testing.
1509
+ * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
1510
+ * and 403, is unexpected. Anything outside the error ranges, including 0 for
1511
+ * "no response", is normal.
1499
1512
  */
1500
- function createAfterHealthyFor(healthyForMs, clock = defaultClock()) {
1501
- let healthySinceMs;
1502
- return {
1503
- noteHealthy() {
1504
- if (healthySinceMs === undefined) {
1505
- healthySinceMs = clock();
1506
- }
1507
- },
1508
- noteFailure() {
1509
- healthySinceMs = undefined;
1510
- },
1511
- isSatisfied() {
1512
- return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1513
- },
1514
- };
1513
+ function classifyHttpStatus(status) {
1514
+ if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
1515
+ return 'unexpected';
1516
+ }
1517
+ return 'normal';
1515
1518
  }
1516
1519
  /**
1517
- * Creates a policy that resets once the given number of operations in a row
1518
- * have succeeded.
1520
+ * Classifies a transport-level failure (connection refused or dropped, DNS
1521
+ * failure, timeout, TLS negotiation failure).
1519
1522
  *
1520
- * @param count How many operations in a row must succeed; must be a positive
1521
- * integer.
1523
+ * Always normal: in an all-HTTPS system every transport error surfaces through
1524
+ * the TLS layer, so a certificate misconfiguration cannot be reliably
1525
+ * distinguished from a transient network fault, and treating transient faults
1526
+ * as unexpected would hold ordinary recoveries to multi-minute waits.
1522
1527
  */
1523
- function createAfterConsecutiveSuccesses(count) {
1524
- let successes = 0;
1525
- return {
1526
- noteHealthy() {
1527
- successes += 1;
1528
- },
1529
- noteFailure() {
1530
- successes = 0;
1531
- },
1532
- isSatisfied() {
1533
- return successes >= count;
1534
- },
1535
- };
1536
- }
1537
-
1538
- // The delay bounds of the extended regime, in milliseconds. A component enters
1539
- // the extended regime after an unexpected failure and leaves it when its reset
1540
- // policy is satisfied.
1541
- const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
1542
- const EXTENDED_CEILING_MS = 60 * 60 * 1000;
1543
- // The bounds, reset window, and default initial delay of streaming's normal regime.
1544
- const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
1545
- const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
1546
- const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
1547
- // Polling's reset condition and default cadence.
1548
- const POLLING_RESET_SUCCESSES = 2;
1549
- const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
1550
- function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
1551
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1552
- return value;
1553
- }
1554
- logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1555
- return defaultValueMs;
1528
+ function classifyTransportFailure() {
1529
+ return 'normal';
1556
1530
  }
1557
1531
  /**
1558
- * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1559
- * the contract on the values.
1532
+ * Check if the HTTP error is recoverable. This will return false if a request
1533
+ * made with any payload could not recover. If the reason for the failure
1534
+ * is payload specific, for instance a payload that is too large, then
1535
+ * it could recover with a different payload.
1536
+ *
1537
+ * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
1538
+ * retained for the event-delivery pathway and is expected to be deprecated
1539
+ * once that pathway migrates to failure classification.
1560
1540
  */
1561
- function createRetryState(config) {
1562
- const normalInitialDelayMs = config.normalInitialDelayMs;
1563
- const normalCeilingMs = config.normalCeilingMs;
1564
- const extendedInitialDelayMs = config.extendedInitialDelayMs;
1565
- const extendedCeilingMs = config.extendedCeilingMs;
1566
- const operatingCadenceMs = config.operatingCadenceMs ?? 0;
1567
- const { resetPolicy } = config;
1568
- const random = config.random ?? Math.random;
1569
- let attempts = 0;
1570
- let extended = false;
1571
- let minDelayMs = normalInitialDelayMs;
1572
- let maxDelayMs = normalCeilingMs;
1573
- let serverDirectedBaseMs;
1574
- // Before any outcome is recorded, the next wait is the ordinary interval.
1575
- let nextDelayMs = operatingCadenceMs;
1576
- function resetIfDue() {
1577
- if (!resetPolicy.isSatisfied()) {
1578
- return;
1579
- }
1580
- attempts = 0;
1581
- extended = false;
1582
- minDelayMs = normalInitialDelayMs;
1583
- maxDelayMs = normalCeilingMs;
1584
- }
1585
- return {
1586
- get nextDelay() {
1587
- return nextDelayMs;
1588
- },
1589
- recordFailure(kind) {
1590
- // A reset that fell due during healthy operation is applied before the
1591
- // new failure is counted, so the failure computes from a fresh sequence.
1592
- resetIfDue();
1593
- resetPolicy.noteFailure();
1594
- if (kind === 'unexpected' && !extended) {
1595
- // Moving to the extended regime raises both bounds and starts the delay
1596
- // sequence over. Only the move does this: a later unexpected failure
1597
- // keeps counting up rather than re-pinning the initial delay.
1598
- extended = true;
1599
- minDelayMs = extendedInitialDelayMs;
1600
- maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
1601
- attempts = 1;
1602
- }
1603
- else {
1604
- attempts += 1;
1605
- }
1606
- const base = serverDirectedBaseMs ?? minDelayMs;
1607
- // Compare against the ceiling scaled down rather than the base scaled up, so
1608
- // the computed value can never overflow the ceiling. A base of zero doubles
1609
- // to zero forever, so it short-circuits.
1610
- let target = 0;
1611
- if (base > 0) {
1612
- const exponent = attempts - 1;
1613
- target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
1614
- }
1615
- const jitter = (random() * target) / 2;
1616
- nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
1617
- },
1618
- recordSuccess() {
1619
- resetPolicy.noteHealthy();
1620
- resetIfDue();
1621
- // A backoff wait applies to a retry, not to every operation, so after a
1622
- // success the next wait is the ordinary interval even while the retry
1623
- // state is raised.
1624
- nextDelayMs = operatingCadenceMs;
1625
- },
1626
- applyServerDirectedRetry(delayMs) {
1627
- if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
1628
- return;
1629
- }
1630
- serverDirectedBaseMs = delayMs;
1631
- attempts = 0;
1632
- },
1633
- };
1541
+ function isHttpRecoverable(status) {
1542
+ return classifyHttpStatus(status) === 'normal';
1634
1543
  }
1635
1544
  /**
1636
- * Builds the retry state for a streaming data source: no wait during healthy
1637
- * operation, a normal regime running from the configured initial delay up to
1638
- * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
1639
- * reset once a connection has been healthy for 60 seconds.
1545
+ * Returns true if the status could recover for a different payload.
1640
1546
  *
1641
- * The initial delay is validated here; the documented default of 1 second
1642
- * stands in for anything that is not a positive, finite number. A configured
1643
- * delay above the normal ceiling is clamped to it, while the extended regime
1644
- * never starts below the configured delay.
1547
+ * When used with event processing this indicates that we should discard
1548
+ * the payload, but that a subsequent payload may succeed. Therefore we should
1549
+ * not stop event processing.
1645
1550
  */
1646
- function forStreaming(initialReconnectDelayMs, logger) {
1647
- const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
1648
- return createRetryState({
1649
- normalInitialDelayMs: validated,
1650
- normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
1651
- extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1652
- extendedCeilingMs: EXTENDED_CEILING_MS,
1653
- resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
1654
- operatingCadenceMs: 0,
1655
- });
1551
+ function isHttpLocallyRecoverable(status) {
1552
+ if (status === 413) {
1553
+ return true;
1554
+ }
1555
+ return isHttpRecoverable(status);
1656
1556
  }
1557
+
1657
1558
  /**
1658
- * Builds the retry state for a polling data source: the poll interval is the
1659
- * operating cadence, so no wait is ever shorter than it; in the normal regime
1660
- * both bounds are the interval itself, so a normal failure simply polls again
1661
- * on schedule; the extended regime runs from 5 minutes (or the interval, if
1662
- * longer) up to 1 hour (or the interval, if longer); and the state resets
1663
- * after two successful polls in a row.
1559
+ * Returns a promise which errors after t seconds.
1664
1560
  *
1665
- * The poll interval is validated here; the documented default of 30 seconds
1666
- * stands in for anything that is not a positive, finite number.
1561
+ * @param t Timeout in seconds.
1562
+ * @param taskName Name of task being timed for logging and error reporting.
1667
1563
  */
1668
- function forPolling(pollIntervalMs, logger) {
1669
- const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
1670
- return createRetryState({
1671
- normalInitialDelayMs: validated,
1672
- normalCeilingMs: validated,
1673
- extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1674
- extendedCeilingMs: EXTENDED_CEILING_MS,
1675
- resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
1676
- operatingCadenceMs: validated,
1564
+ function cancelableTimedPromise(t, taskName) {
1565
+ let timeout;
1566
+ let resolve;
1567
+ const promise = new Promise((_res, reject) => {
1568
+ resolve = _res;
1569
+ timeout = setTimeout(() => {
1570
+ const e = `${taskName} timed out after ${t} seconds.`;
1571
+ reject(new LDTimeoutError(e));
1572
+ }, t * 1000);
1677
1573
  });
1574
+ return {
1575
+ promise,
1576
+ cancel: () => {
1577
+ resolve();
1578
+ clearTimeout(timeout);
1579
+ },
1580
+ };
1581
+ }
1582
+
1583
+ function clone(obj) {
1584
+ if (obj === undefined || obj === null) {
1585
+ return obj;
1586
+ }
1587
+ return JSON.parse(JSON.stringify(obj));
1588
+ }
1589
+
1590
+ function secondsToMillis(sec) {
1591
+ return Math.trunc(sec * 1000);
1678
1592
  }
1679
1593
 
1680
1594
  /**
1681
- * Enable / disable Auto environment attributes. When enabled, the SDK will automatically
1682
- * provide data about the mobile environment where the application is running. This data makes it simpler to target
1683
- * your mobile customers based on application name or version, or on device characteristics including manufacturer,
1684
- * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,
1685
- * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).
1686
- * for more documentation.
1595
+ * Wait before calling the same function. Useful for expensive calls.
1596
+ * Adapted from https://amitd.co/code/typescript/debounce.
1597
+ *
1598
+ * @return The debounced function.
1599
+ *
1600
+ * @example
1601
+ *
1602
+ * ```js
1603
+ * const debouncedFunction = debounce(e => {
1604
+ * console.log(e);
1605
+ * }, 5000);
1606
+ *
1607
+ * // Console logs 'Hello world again ' after 5 seconds
1608
+ * debouncedFunction('Hello world');
1609
+ * debouncedFunction('Hello world again');
1610
+ * ```
1611
+ * @param fn The function to be debounced.
1612
+ * @param delayMs Defaults to 5 seconds.
1687
1613
  */
1688
- var AutoEnvAttributes;
1689
- (function (AutoEnvAttributes) {
1690
- AutoEnvAttributes[AutoEnvAttributes["Disabled"] = 0] = "Disabled";
1691
- AutoEnvAttributes[AutoEnvAttributes["Enabled"] = 1] = "Enabled";
1692
- })(AutoEnvAttributes || (AutoEnvAttributes = {}));
1693
-
1694
- var LDEventType;
1695
- (function (LDEventType) {
1696
- LDEventType[LDEventType["AnalyticsEvents"] = 0] = "AnalyticsEvents";
1697
- LDEventType[LDEventType["DiagnosticEvent"] = 1] = "DiagnosticEvent";
1698
- })(LDEventType || (LDEventType = {}));
1699
- var LDDeliveryStatus;
1700
- (function (LDDeliveryStatus) {
1701
- LDDeliveryStatus[LDDeliveryStatus["Succeeded"] = 0] = "Succeeded";
1702
- LDDeliveryStatus[LDDeliveryStatus["Failed"] = 1] = "Failed";
1703
- LDDeliveryStatus[LDDeliveryStatus["FailedAndMustShutDown"] = 2] = "FailedAndMustShutDown";
1704
- })(LDDeliveryStatus || (LDDeliveryStatus = {}));
1614
+ const debounce = (fn, delayMs = 5000) => {
1615
+ let timer;
1616
+ return (...args) => {
1617
+ clearTimeout(timer);
1618
+ timer = setTimeout(() => {
1619
+ fn(...args);
1620
+ }, delayMs);
1621
+ };
1622
+ };
1705
1623
 
1706
- var index$1 = /*#__PURE__*/Object.freeze({
1707
- __proto__: null,
1708
- get DataSourceState () { return DataSourceState; },
1709
- get LDDeliveryStatus () { return LDDeliveryStatus; },
1710
- get LDEventType () { return LDEventType; }
1711
- });
1624
+ const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
1712
1625
 
1713
1626
  /**
1714
- * Attempt to produce a string representation of a value.
1715
- * The format should be roughly comparable to `util.format`
1716
- * aside from object which will be JSON versus the `util.inspect`
1717
- * format.
1718
- * @param val
1719
- * @returns A string representation of the value if possible.
1627
+ * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.
1628
+ * Sourced from below but modified to include checks for empty object and ignoring keys.
1629
+ * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
1630
+ *
1631
+ * @param obj
1632
+ * @param ignoreKeys
1720
1633
  */
1721
- function tryStringify(val) {
1722
- if (typeof val === 'string') {
1723
- return val;
1724
- }
1725
- if (val === undefined) {
1726
- return 'undefined';
1727
- }
1728
- if (val === null) {
1729
- return 'null';
1634
+ const deepCompact = (obj, ignoreKeys) => {
1635
+ if (!obj) {
1636
+ return obj;
1730
1637
  }
1731
- if (Object.prototype.hasOwnProperty.call(val, 'toString')) {
1732
- try {
1733
- return val.toString();
1638
+ return Object.entries(obj).reduce((acc, [key, value]) => {
1639
+ if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {
1640
+ acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;
1734
1641
  }
1735
- catch {
1736
- /* Keep going */
1642
+ return acc;
1643
+ }, {});
1644
+ };
1645
+
1646
+ /* eslint-disable */
1647
+ // Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual
1648
+ // {{? it.es6 }}
1649
+ // var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
1650
+ // {{?}}
1651
+ function fastDeepEqual(a, b) {
1652
+ if (a === b)
1653
+ return true;
1654
+ if (a && b && typeof a == 'object' && typeof b == 'object') {
1655
+ if (a.constructor !== b.constructor)
1656
+ return false;
1657
+ var length, i, keys;
1658
+ if (Array.isArray(a)) {
1659
+ length = a.length;
1660
+ if (length != b.length)
1661
+ return false;
1662
+ for (i = length; i-- !== 0;)
1663
+ if (!fastDeepEqual(a[i], b[i]))
1664
+ return false;
1665
+ return true;
1737
1666
  }
1738
- }
1739
- if (typeof val === 'bigint') {
1740
- return `${val}n`;
1741
- }
1742
- try {
1743
- return JSON.stringify(val);
1744
- }
1745
- catch (error) {
1746
- if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {
1747
- return '[Circular]';
1667
+ // {{? it.es6 }}
1668
+ if (a instanceof Map && b instanceof Map) {
1669
+ if (a.size !== b.size)
1670
+ return false;
1671
+ for (i of a.entries())
1672
+ if (!b.has(i[0]))
1673
+ return false;
1674
+ for (i of a.entries())
1675
+ if (!fastDeepEqual(i[1], b.get(i[0])))
1676
+ return false;
1677
+ return true;
1748
1678
  }
1749
- return '[Not Stringifiable]';
1679
+ if (a instanceof Set && b instanceof Set) {
1680
+ if (a.size !== b.size)
1681
+ return false;
1682
+ for (i of a.entries())
1683
+ if (!b.has(i[0]))
1684
+ return false;
1685
+ return true;
1686
+ }
1687
+ if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
1688
+ // @ts-ignore
1689
+ length = a.length;
1690
+ // @ts-ignore
1691
+ if (length != b.length)
1692
+ return false;
1693
+ for (i = length; i-- !== 0;) {
1694
+ // @ts-ignore
1695
+ if (a[i] !== b[i])
1696
+ return false;
1697
+ }
1698
+ return true;
1699
+ }
1700
+ // {{?}}
1701
+ if (a.constructor === RegExp)
1702
+ return a.source === b.source && a.flags === b.flags;
1703
+ if (a.valueOf !== Object.prototype.valueOf)
1704
+ return a.valueOf() === b.valueOf();
1705
+ if (a.toString !== Object.prototype.toString)
1706
+ return a.toString() === b.toString();
1707
+ keys = Object.keys(a);
1708
+ length = keys.length;
1709
+ if (length !== Object.keys(b).length)
1710
+ return false;
1711
+ for (i = length; i-- !== 0;)
1712
+ if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
1713
+ return false;
1714
+ for (i = length; i-- !== 0;) {
1715
+ var key = keys[i];
1716
+ // {{? it.react }}
1717
+ // if (key === '_owner' && a.$$typeof) {
1718
+ // // React-specific: avoid traversing React elements' _owner.
1719
+ // // _owner contains circular references
1720
+ // // and is not needed when comparing the actual elements (and not their owners)
1721
+ // continue;
1722
+ // }
1723
+ // {{?}}
1724
+ if (!fastDeepEqual(a[key], b[key]))
1725
+ return false;
1726
+ }
1727
+ return true;
1750
1728
  }
1729
+ // true if both NaN, false otherwise
1730
+ return a !== a && b !== b;
1751
1731
  }
1752
- /**
1753
- * Attempt to produce a numeric representation.
1754
- * BigInts have an `n` suffix.
1755
- * @param val
1756
- * @returns The numeric representation or 'NaN' if not numeric.
1757
- */
1758
- function toNumber(val) {
1759
- // Symbol has to be treated special because it will
1760
- // throw an exception if an attempt is made to convert it.
1761
- if (typeof val === 'symbol') {
1762
- return 'NaN';
1732
+
1733
+ function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent', instanceId) {
1734
+ const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();
1735
+ const headers = {
1736
+ [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
1737
+ };
1738
+ // edge sdks sets this to false because they use the clientSideID
1739
+ // and they don't need the authorization header
1740
+ if (includeAuthorizationHeader) {
1741
+ headers.authorization = sdkKey;
1763
1742
  }
1764
- if (typeof val === 'bigint') {
1765
- return `${val}n`;
1743
+ if (wrapperName) {
1744
+ headers['x-launchdarkly-wrapper'] = wrapperVersion
1745
+ ? `${wrapperName}/${wrapperVersion}`
1746
+ : wrapperName;
1766
1747
  }
1767
- return String(Number(val));
1768
- }
1769
- /**
1770
- * Attempt to produce an integer representation.
1771
- * BigInts have an `n` suffix.
1772
- * @param val
1773
- * @returns The integer representation or 'NaN' if not numeric.
1774
- */
1775
- function toInt(val) {
1776
- if (typeof val === 'symbol') {
1777
- return 'NaN';
1748
+ if (tags?.value) {
1749
+ headers['x-launchdarkly-tags'] = tags.value;
1778
1750
  }
1779
- if (typeof val === 'bigint') {
1780
- return `${val}n`;
1751
+ // Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
1752
+ // per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
1753
+ // for generating the GUID once per SDK instance and passing it here, so that it rides on
1754
+ // every outbound request via this shared default-headers map. Client/edge SDKs do not pass
1755
+ // this value, so the header is omitted for them.
1756
+ if (instanceId) {
1757
+ headers['x-launchdarkly-instance-id'] = instanceId;
1781
1758
  }
1782
- return String(parseInt(val, 10));
1759
+ return headers;
1783
1760
  }
1784
- /**
1785
- * Attempt to produce a float representation.
1786
- * BigInts have an `n` suffix.
1787
- * @param val
1788
- * @returns The integer representation or 'NaN' if not numeric.
1789
- */
1790
- function toFloat(val) {
1791
- if (typeof val === 'symbol') {
1792
- return 'NaN';
1761
+ function httpErrorMessage(err, context, retryMessage) {
1762
+ let desc;
1763
+ if (err.status) {
1764
+ desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;
1793
1765
  }
1794
- return String(parseFloat(val));
1766
+ else {
1767
+ desc = `I/O error (${err.message || 'unknown error'})`;
1768
+ }
1769
+ const action = retryMessage ?? 'giving up permanently';
1770
+ return `Received ${desc} for ${context} - ${action}`;
1771
+ }
1772
+ function shouldRetry({ status }) {
1773
+ return status ? isHttpRecoverable(status) : true;
1795
1774
  }
1796
- // Based on:
1797
- // https://nodejs.org/api/util.html#utilformatformat-args
1798
- // The result will not match node exactly, but it should get the
1799
- // right information through.
1800
- const escapes = {
1801
- s: (val) => tryStringify(val),
1802
- d: (val) => toNumber(val),
1803
- i: (val) => toInt(val),
1804
- f: (val) => toFloat(val),
1805
- j: (val) => tryStringify(val),
1806
- o: (val) => tryStringify(val),
1807
- // eslint-disable-next-line @typescript-eslint/naming-convention
1808
- O: (val) => tryStringify(val),
1809
- c: () => '',
1810
- };
1811
1775
  /**
1812
- * A basic formatted for use where `util.format` is not available.
1813
- * This will not be as performant, but it will produce formatted
1814
- * messages.
1776
+ * In react-native use base64-js to polyfill btoa. This is safe
1777
+ * because the react-native repo uses it too. Set the global.btoa to the encode
1778
+ * function of base64-js.
1779
+ * https://github.com/beatgammit/base64-js
1780
+ * https://github.com/axios/axios/issues/2235#issuecomment-512204616
1815
1781
  *
1816
- * @internal
1782
+ * Ripped from https://thewoods.blog/base64url/
1783
+ */
1784
+ const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1785
+
1786
+ var noop = () => { };
1787
+
1788
+ const sleep = async (delayMillis = 1000) => new Promise((resolve) => {
1789
+ setTimeout(resolve, delayMillis);
1790
+ });
1791
+
1792
+ let useWallClock;
1793
+ /**
1794
+ * Milliseconds from a monotonic clock when the runtime provides one.
1817
1795
  *
1818
- * @param args
1819
- * @returns Formatted string.
1796
+ * Deadlines and embargoes compare differences of these values. A wall clock can
1797
+ * step backward, for example through an NTP correction, and a deadline armed
1798
+ * against it would then never pass. Values from this function are not epoch
1799
+ * times and must only be compared with each other.
1800
+ *
1801
+ * The time source is selected on the first call and never changes after that.
1802
+ * Monotonic values and wall-clock values have different origins, so a switch
1803
+ * between sources would corrupt in-flight measurements. A runtime without a
1804
+ * performance global at the first call uses the wall clock from then on, even
1805
+ * if a polyfill appears later.
1820
1806
  */
1821
- function format(...args) {
1822
- const formatString = args[0];
1823
- if (TypeValidators.String.is(formatString)) {
1824
- args.shift();
1825
- let out = '';
1826
- let i = 0;
1827
- while (i < formatString.length) {
1828
- const char = formatString.charAt(i);
1829
- if (char === '%') {
1830
- const nextIndex = i + 1;
1831
- if (nextIndex < formatString.length) {
1832
- const nextChar = formatString.charAt(i + 1);
1833
- if (nextChar in escapes && args.length) {
1834
- const value = args.shift();
1835
- // This rule is for math.
1836
- out += escapes[nextChar]?.(value);
1837
- }
1838
- else if (nextChar === '%') {
1839
- out += '%';
1840
- }
1841
- else {
1842
- out += `%${nextChar}`;
1843
- }
1844
- i += 2;
1845
- }
1846
- else {
1847
- // A trailing '%' has nothing to escape, so keep it as-is.
1848
- out += '%';
1849
- i += 1;
1850
- }
1851
- }
1852
- else {
1853
- out += char;
1854
- i += 1;
1855
- }
1856
- }
1857
- // If there are any args left after we exhaust the format string
1858
- // then just stick those on the end.
1859
- if (args.length) {
1860
- if (out.length) {
1861
- out += ' ';
1862
- }
1863
- out += args.map(tryStringify).join(' ');
1864
- }
1865
- return out;
1807
+ // eslint-disable-next-line import/prefer-default-export
1808
+ function monotonicNow() {
1809
+ if (useWallClock === undefined) {
1810
+ const perf = globalThis?.performance;
1811
+ useWallClock = !(perf && typeof perf.now === 'function');
1866
1812
  }
1867
- return args.map(tryStringify).join(' ');
1813
+ return useWallClock ? Date.now() : globalThis.performance.now();
1868
1814
  }
1869
1815
 
1870
- var LogPriority;
1871
- (function (LogPriority) {
1872
- LogPriority[LogPriority["debug"] = 0] = "debug";
1873
- LogPriority[LogPriority["info"] = 1] = "info";
1874
- LogPriority[LogPriority["warn"] = 2] = "warn";
1875
- LogPriority[LogPriority["error"] = 3] = "error";
1876
- LogPriority[LogPriority["none"] = 4] = "none";
1877
- })(LogPriority || (LogPriority = {}));
1878
- const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
1879
1816
  /**
1880
- * A basic logger which handles filtering by level.
1817
+ * Returns a promise which errors after t seconds.
1881
1818
  *
1882
- * With the default options it will write to `console.error`
1883
- * and it will use the formatting provided by `console.error`.
1884
- * If the destination is overwritten, then it will use an included
1885
- * formatter similar to `util.format`.
1819
+ * @param t Timeout in seconds.
1820
+ * @param taskName Name of task being timed for logging and error reporting.
1821
+ */
1822
+ const timedPromise = (t, taskName) => new Promise((_res, reject) => {
1823
+ setTimeout(() => {
1824
+ const e = `${taskName} timed out after ${t} seconds.`;
1825
+ reject(new LDTimeoutError(e));
1826
+ }, t * 1000);
1827
+ });
1828
+
1829
+ /**
1830
+ * Creates a policy that resets once the component has operated without failing
1831
+ * for the given duration. Repeated healthy reports do not move the starting
1832
+ * point; only a failure clears it.
1886
1833
  *
1887
- * If a formatter is available, then that should be overridden
1888
- * as well for performance.
1834
+ * @param healthyForMs How long the component must operate without failing,
1835
+ * in milliseconds; must be a positive, finite number.
1836
+ * @param clock The time source used to measure the healthy stretch; defaults
1837
+ * to a monotonic clock. Primarily for testing.
1889
1838
  */
1890
- class BasicLogger {
1891
- /**
1892
- * This should only be used as a default fallback and not as a convenient
1893
- * solution. In most cases you should construct a new instance with the
1894
- * appropriate options for your specific needs.
1895
- */
1896
- static get() {
1897
- return new BasicLogger({});
1898
- }
1899
- constructor(options) {
1900
- this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
1901
- this._name = options.name ?? 'LaunchDarkly';
1902
- this._formatter = options.formatter;
1903
- if (typeof options.destination === 'object') {
1904
- this._destinations = {
1905
- [LogPriority.debug]: options.destination.debug,
1906
- [LogPriority.info]: options.destination.info,
1907
- [LogPriority.warn]: options.destination.warn,
1908
- [LogPriority.error]: options.destination.error,
1909
- };
1910
- }
1911
- else if (typeof options.destination === 'function') {
1912
- const { destination } = options;
1913
- this._destinations = {
1914
- [LogPriority.debug]: destination,
1915
- [LogPriority.info]: destination,
1916
- [LogPriority.warn]: destination,
1917
- [LogPriority.error]: destination,
1918
- };
1919
- }
1920
- }
1921
- _tryFormat(...args) {
1922
- try {
1923
- if (this._formatter) {
1924
- // In case the provided formatter fails.
1925
- return this._formatter?.(...args);
1926
- }
1927
- return format(...args);
1928
- }
1929
- catch {
1930
- return format(...args);
1931
- }
1932
- }
1933
- _tryWrite(destination, msg) {
1934
- try {
1935
- destination(msg);
1936
- }
1937
- catch {
1938
- // eslint-disable-next-line no-console
1939
- console.error(msg);
1940
- }
1941
- }
1942
- _log(level, args) {
1943
- if (level >= this._logLevel) {
1944
- const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;
1945
- try {
1946
- const destination = this._destinations?.[level];
1947
- if (destination) {
1948
- this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
1949
- }
1950
- else {
1951
- // `console.error` has its own formatter.
1952
- // So we don't need to do anything.
1953
- // eslint-disable-next-line no-console
1954
- console.error(...args);
1955
- }
1956
- }
1957
- catch {
1958
- // If all else fails do not break.
1959
- // eslint-disable-next-line no-console
1960
- console.error(...args);
1839
+ function createAfterHealthyFor(healthyForMs, clock = monotonicNow) {
1840
+ let healthySinceMs;
1841
+ return {
1842
+ noteHealthy() {
1843
+ if (healthySinceMs === undefined) {
1844
+ healthySinceMs = clock();
1961
1845
  }
1962
- }
1963
- }
1964
- error(...args) {
1965
- this._log(LogPriority.error, args);
1966
- }
1967
- warn(...args) {
1968
- this._log(LogPriority.warn, args);
1969
- }
1970
- info(...args) {
1971
- this._log(LogPriority.info, args);
1972
- }
1973
- debug(...args) {
1974
- this._log(LogPriority.debug, args);
1975
- }
1846
+ },
1847
+ noteFailure() {
1848
+ healthySinceMs = undefined;
1849
+ },
1850
+ isSatisfied() {
1851
+ return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1852
+ },
1853
+ };
1976
1854
  }
1977
-
1978
- const loggerRequirements = {
1979
- error: TypeValidators.Function,
1980
- warn: TypeValidators.Function,
1981
- info: TypeValidators.Function,
1982
- debug: TypeValidators.Function,
1983
- };
1984
1855
  /**
1985
- * The safeLogger logic exists because we allow the application to pass in a custom logger, but
1986
- * there is no guarantee that the logger works correctly and if it ever throws exceptions there
1987
- * could be serious consequences (e.g. an uncaught exception within an error event handler, due
1988
- * to the SDK trying to log the error, can terminate the application). An exception could result
1989
- * from faulty logic in the logger implementation, or it could be that this is not a logger at
1990
- * all but some other kind of object; the former is handled by a catch block that logs an error
1991
- * message to the SDK's default logger, and we can at least partly guard against the latter by
1992
- * checking for the presence of required methods at configuration time.
1856
+ * Creates a policy that resets once the given number of operations in a row
1857
+ * have succeeded.
1858
+ *
1859
+ * @param count How many operations in a row must succeed; must be a positive
1860
+ * integer.
1993
1861
  */
1994
- class SafeLogger {
1995
- /**
1996
- * Construct a safe logger with the specified logger.
1997
- * @param logger The logger to use.
1998
- * @param fallback A fallback logger to use in case an issue is encountered using
1999
- * the provided logger.
2000
- */
2001
- constructor(logger, fallback) {
2002
- Object.entries(loggerRequirements).forEach(([level, validator]) => {
2003
- if (!validator.is(logger[level])) {
2004
- throw new Error(`Provided logger instance must support logger.${level}(...) method`);
2005
- // Note that the SDK normally does not throw exceptions to the application, but that rule
2006
- // does not apply to LDClient.init() which will throw an exception if the parameters are so
2007
- // invalid that we cannot proceed with creating the client. An invalid logger meets those
2008
- // criteria since the SDK calls the logger during nearly all of its operations.
2009
- }
2010
- });
2011
- this._logger = logger;
2012
- this._fallback = fallback;
1862
+ function createAfterConsecutiveSuccesses(count) {
1863
+ let successes = 0;
1864
+ return {
1865
+ noteHealthy() {
1866
+ successes += 1;
1867
+ },
1868
+ noteFailure() {
1869
+ successes = 0;
1870
+ },
1871
+ isSatisfied() {
1872
+ return successes >= count;
1873
+ },
1874
+ };
1875
+ }
1876
+
1877
+ // The delay bounds of the extended regime, in milliseconds. A component enters
1878
+ // the extended regime after an unexpected failure and leaves it when its reset
1879
+ // policy is satisfied.
1880
+ const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
1881
+ const EXTENDED_CEILING_MS = 60 * 60 * 1000;
1882
+ // The bounds, reset window, and default initial delay of streaming's normal regime.
1883
+ const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
1884
+ const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
1885
+ const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
1886
+ // Polling's reset condition and default cadence.
1887
+ const POLLING_RESET_SUCCESSES = 2;
1888
+ const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
1889
+ function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
1890
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1891
+ return value;
2013
1892
  }
2014
- _log(level, args) {
2015
- try {
2016
- this._logger[level](...args);
2017
- }
2018
- catch {
2019
- // If all else fails do not break.
2020
- this._fallback[level](...args);
1893
+ logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1894
+ return defaultValueMs;
1895
+ }
1896
+ /**
1897
+ * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1898
+ * the contract on the values.
1899
+ */
1900
+ function createRetryState(config) {
1901
+ const normalInitialDelayMs = config.normalInitialDelayMs;
1902
+ const normalCeilingMs = config.normalCeilingMs;
1903
+ const extendedInitialDelayMs = config.extendedInitialDelayMs;
1904
+ const extendedCeilingMs = config.extendedCeilingMs;
1905
+ const operatingCadenceMs = config.operatingCadenceMs ?? 0;
1906
+ const { resetPolicy } = config;
1907
+ const random = config.random ?? Math.random;
1908
+ let attempts = 0;
1909
+ let extended = false;
1910
+ let minDelayMs = normalInitialDelayMs;
1911
+ let maxDelayMs = normalCeilingMs;
1912
+ let serverDirectedBaseMs;
1913
+ // Before any outcome is recorded, the next wait is the ordinary interval.
1914
+ let nextDelayMs = operatingCadenceMs;
1915
+ function resetIfDue() {
1916
+ if (!resetPolicy.isSatisfied()) {
1917
+ return;
2021
1918
  }
1919
+ attempts = 0;
1920
+ extended = false;
1921
+ minDelayMs = normalInitialDelayMs;
1922
+ maxDelayMs = normalCeilingMs;
2022
1923
  }
2023
- error(...args) {
2024
- this._log('error', args);
2025
- }
2026
- warn(...args) {
2027
- this._log('warn', args);
2028
- }
2029
- info(...args) {
2030
- this._log('info', args);
2031
- }
2032
- debug(...args) {
2033
- this._log('debug', args);
2034
- }
1924
+ return {
1925
+ get nextDelay() {
1926
+ return nextDelayMs;
1927
+ },
1928
+ recordFailure(kind) {
1929
+ // A reset that fell due during healthy operation is applied before the
1930
+ // new failure is counted, so the failure computes from a fresh sequence.
1931
+ resetIfDue();
1932
+ resetPolicy.noteFailure();
1933
+ if (kind === 'unexpected' && !extended) {
1934
+ // Moving to the extended regime raises both bounds and starts the delay
1935
+ // sequence over. Only the move does this: a later unexpected failure
1936
+ // keeps counting up rather than re-pinning the initial delay.
1937
+ extended = true;
1938
+ minDelayMs = extendedInitialDelayMs;
1939
+ maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
1940
+ attempts = 1;
1941
+ }
1942
+ else {
1943
+ attempts += 1;
1944
+ }
1945
+ const base = serverDirectedBaseMs ?? minDelayMs;
1946
+ // Compare against the ceiling scaled down rather than the base scaled up, so
1947
+ // the computed value can never overflow the ceiling. A base of zero doubles
1948
+ // to zero forever, so it short-circuits.
1949
+ let target = 0;
1950
+ if (base > 0) {
1951
+ const exponent = attempts - 1;
1952
+ target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
1953
+ }
1954
+ const jitter = (random() * target) / 2;
1955
+ nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
1956
+ },
1957
+ recordSuccess() {
1958
+ resetPolicy.noteHealthy();
1959
+ resetIfDue();
1960
+ // A backoff wait applies to a retry, not to every operation, so after a
1961
+ // success the next wait is the ordinary interval even while the retry
1962
+ // state is raised.
1963
+ nextDelayMs = operatingCadenceMs;
1964
+ },
1965
+ applyServerDirectedRetry(delayMs) {
1966
+ if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
1967
+ return;
1968
+ }
1969
+ serverDirectedBaseMs = delayMs;
1970
+ attempts = 0;
1971
+ },
1972
+ };
2035
1973
  }
2036
-
2037
- const createSafeLogger = (logger) => {
2038
- const basicLogger = new BasicLogger({
2039
- level: 'info',
2040
- // eslint-disable-next-line no-console
2041
- destination: console.error,
2042
- formatter: format,
1974
+ /**
1975
+ * Builds the retry state for a streaming data source: no wait during healthy
1976
+ * operation, a normal regime running from the configured initial delay up to
1977
+ * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
1978
+ * reset once a connection has been healthy for 60 seconds.
1979
+ *
1980
+ * The initial delay is validated here; the documented default of 1 second
1981
+ * stands in for anything that is not a positive, finite number. A configured
1982
+ * delay above the normal ceiling is clamped to it, while the extended regime
1983
+ * never starts below the configured delay.
1984
+ */
1985
+ function forStreaming(initialReconnectDelayMs, logger) {
1986
+ const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
1987
+ return createRetryState({
1988
+ normalInitialDelayMs: validated,
1989
+ normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
1990
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1991
+ extendedCeilingMs: EXTENDED_CEILING_MS,
1992
+ resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
1993
+ operatingCadenceMs: 0,
2043
1994
  });
2044
- return logger ? new SafeLogger(logger, basicLogger) : basicLogger;
2045
- };
2046
-
1995
+ }
2047
1996
  /**
2048
- * Messages for issues which can be encountered from processing the configuration options.
1997
+ * Builds the retry state for a polling data source: the poll interval is the
1998
+ * operating cadence, so no wait is ever shorter than it; in the normal regime
1999
+ * both bounds are the interval itself, so a normal failure simply polls again
2000
+ * on schedule; the extended regime runs from 5 minutes (or the interval, if
2001
+ * longer) up to 1 hour (or the interval, if longer); and the state resets
2002
+ * after two successful polls in a row.
2003
+ *
2004
+ * The poll interval is validated here; the documented default of 30 seconds
2005
+ * stands in for anything that is not a positive, finite number.
2049
2006
  */
2050
- class OptionMessages {
2051
- static deprecated(oldName, newName) {
2052
- return `"${oldName}" is deprecated, please use "${newName}"`;
2053
- }
2054
- static optionBelowMinimum(name, value, min) {
2055
- return `Config option "${name}" had invalid value of ${value}, using minimum of ${min} instead`;
2056
- }
2057
- static unknownOption(name) {
2058
- return `Ignoring unknown config option "${name}"`;
2059
- }
2060
- static wrongOptionType(name, expectedType, actualType) {
2061
- return `Config option "${name}" should be of type ${expectedType}, got ${actualType}, using default value`;
2062
- }
2063
- static wrongOptionTypeBoolean(name, actualType) {
2064
- return `Config option "${name}" should be a boolean, got ${actualType}, converting to boolean`;
2065
- }
2066
- static invalidTagValue(name) {
2067
- return `Config option "${name}" must only contain letters, numbers, ., _ or -.`;
2068
- }
2069
- static tagValueTooLong(name) {
2070
- return `Value of "${name}" was longer than 64 characters and was discarded.`;
2071
- }
2072
- static partialEndpoint(name) {
2073
- return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;
2074
- }
2007
+ function forPolling(pollIntervalMs, logger) {
2008
+ const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
2009
+ return createRetryState({
2010
+ normalInitialDelayMs: validated,
2011
+ normalCeilingMs: validated,
2012
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
2013
+ extendedCeilingMs: EXTENDED_CEILING_MS,
2014
+ resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
2015
+ operatingCadenceMs: validated,
2016
+ });
2075
2017
  }
2076
2018
 
2077
2019
  /**
2078
- * Expression to validate characters that are allowed in tag keys and values.
2020
+ * Enable / disable Auto environment attributes. When enabled, the SDK will automatically
2021
+ * provide data about the mobile environment where the application is running. This data makes it simpler to target
2022
+ * your mobile customers based on application name or version, or on device characteristics including manufacturer,
2023
+ * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,
2024
+ * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).
2025
+ * for more documentation.
2079
2026
  */
2080
- const allowedTagCharacters = /^(\w|\.|-)+$/;
2081
- const regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);
2082
- const tagValidator = {
2083
- is: (u, name) => {
2084
- if (regexValidator.is(u)) {
2085
- if (u.length > 64) {
2086
- return { valid: false, message: OptionMessages.tagValueTooLong(name) };
2087
- }
2088
- return { valid: true };
2089
- }
2090
- return { valid: false, message: OptionMessages.invalidTagValue(name) };
2091
- },
2092
- };
2027
+ var AutoEnvAttributes;
2028
+ (function (AutoEnvAttributes) {
2029
+ AutoEnvAttributes[AutoEnvAttributes["Disabled"] = 0] = "Disabled";
2030
+ AutoEnvAttributes[AutoEnvAttributes["Enabled"] = 1] = "Enabled";
2031
+ })(AutoEnvAttributes || (AutoEnvAttributes = {}));
2032
+
2033
+ var LDEventType;
2034
+ (function (LDEventType) {
2035
+ LDEventType[LDEventType["AnalyticsEvents"] = 0] = "AnalyticsEvents";
2036
+ LDEventType[LDEventType["DiagnosticEvent"] = 1] = "DiagnosticEvent";
2037
+ })(LDEventType || (LDEventType = {}));
2038
+ var LDDeliveryStatus;
2039
+ (function (LDDeliveryStatus) {
2040
+ LDDeliveryStatus[LDDeliveryStatus["Succeeded"] = 0] = "Succeeded";
2041
+ LDDeliveryStatus[LDDeliveryStatus["Failed"] = 1] = "Failed";
2042
+ LDDeliveryStatus[LDDeliveryStatus["FailedAndMustShutDown"] = 2] = "FailedAndMustShutDown";
2043
+ })(LDDeliveryStatus || (LDDeliveryStatus = {}));
2044
+
2045
+ var index$1 = /*#__PURE__*/Object.freeze({
2046
+ __proto__: null,
2047
+ get DataSourceState () { return DataSourceState; },
2048
+ get LDDeliveryStatus () { return LDDeliveryStatus; },
2049
+ get LDEventType () { return LDEventType; }
2050
+ });
2051
+
2093
2052
  /**
2094
- * Class for managing tags.
2053
+ * Attempt to produce a string representation of a value.
2054
+ * The format should be roughly comparable to `util.format`
2055
+ * aside from object which will be JSON versus the `util.inspect`
2056
+ * format.
2057
+ * @param val
2058
+ * @returns A string representation of the value if possible.
2095
2059
  */
2096
- class ApplicationTags {
2097
- constructor(options) {
2098
- const tags = {};
2099
- const application = options?.application;
2100
- const logger = options?.logger;
2101
- if (application) {
2102
- Object.entries(application).forEach(([key, value]) => {
2103
- if (value !== null && value !== undefined) {
2104
- const { valid, message } = tagValidator.is(value, `application.${key}`);
2105
- if (!valid) {
2106
- logger?.warn(message);
2107
- }
2108
- else if (key === 'versionName') {
2109
- tags[`application-version-name`] = [value];
2110
- }
2111
- else {
2112
- tags[`application-${key}`] = [value];
2113
- }
2114
- }
2115
- });
2060
+ function tryStringify(val) {
2061
+ if (typeof val === 'string') {
2062
+ return val;
2063
+ }
2064
+ if (val === undefined) {
2065
+ return 'undefined';
2066
+ }
2067
+ if (val === null) {
2068
+ return 'null';
2069
+ }
2070
+ if (Object.prototype.hasOwnProperty.call(val, 'toString')) {
2071
+ try {
2072
+ return val.toString();
2116
2073
  }
2117
- const tagKeys = Object.keys(tags);
2118
- if (tagKeys.length) {
2119
- this.value = tagKeys
2120
- .sort()
2121
- .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
2122
- .join(' ');
2074
+ catch {
2075
+ /* Keep going */
2123
2076
  }
2124
2077
  }
2078
+ if (typeof val === 'bigint') {
2079
+ return `${val}n`;
2080
+ }
2081
+ try {
2082
+ return JSON.stringify(val);
2083
+ }
2084
+ catch (error) {
2085
+ if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {
2086
+ return '[Circular]';
2087
+ }
2088
+ return '[Not Stringifiable]';
2089
+ }
2125
2090
  }
2126
-
2127
2091
  /**
2128
- * The client context provides basic configuration and platform support which are required
2129
- * when building SDK components.
2092
+ * Attempt to produce a numeric representation.
2093
+ * BigInts have an `n` suffix.
2094
+ * @param val
2095
+ * @returns The numeric representation or 'NaN' if not numeric.
2130
2096
  */
2131
- class ClientContext {
2132
- constructor(sdkKey, configuration, platform) {
2133
- this.platform = platform;
2134
- this.basicConfiguration = {
2135
- tags: configuration.tags,
2136
- logger: configuration.logger,
2137
- offline: configuration.offline,
2138
- serviceEndpoints: configuration.serviceEndpoints,
2139
- sdkKey,
2140
- };
2097
+ function toNumber(val) {
2098
+ // Symbol has to be treated special because it will
2099
+ // throw an exception if an attempt is made to convert it.
2100
+ if (typeof val === 'symbol') {
2101
+ return 'NaN';
2141
2102
  }
2142
- }
2143
-
2144
- function canonicalizeUri(uri) {
2145
- return uri.replace(/\/+$/, '');
2146
- }
2147
- function canonicalizePath(path) {
2148
- return path.replace(/^\/+/, '').replace(/\?$/, '');
2103
+ if (typeof val === 'bigint') {
2104
+ return `${val}n`;
2105
+ }
2106
+ return String(Number(val));
2149
2107
  }
2150
2108
  /**
2151
- * Specifies the base service URIs used by SDK components.
2109
+ * Attempt to produce an integer representation.
2110
+ * BigInts have an `n` suffix.
2111
+ * @param val
2112
+ * @returns The integer representation or 'NaN' if not numeric.
2152
2113
  */
2153
- class ServiceEndpoints {
2154
- constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {
2155
- this.streaming = canonicalizeUri(streaming);
2156
- this.polling = canonicalizeUri(polling);
2157
- this.events = canonicalizeUri(events);
2158
- this.analyticsEventPath = analyticsEventPath;
2159
- this.diagnosticEventPath = diagnosticEventPath;
2160
- this.includeAuthorizationHeader = includeAuthorizationHeader;
2161
- this.payloadFilterKey = payloadFilterKey;
2114
+ function toInt(val) {
2115
+ if (typeof val === 'symbol') {
2116
+ return 'NaN';
2162
2117
  }
2163
- }
2164
- // eslint-disable-next-line @typescript-eslint/naming-convention
2165
- ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
2166
- function getWithParams(uri, parameters = []) {
2167
- if (parameters.length === 0) {
2168
- return uri;
2118
+ if (typeof val === 'bigint') {
2119
+ return `${val}n`;
2169
2120
  }
2170
- const parts = parameters.map(({ key, value }) => `${key}=${value}`);
2171
- return `${uri}?${parts.join('&')}`;
2121
+ return String(parseInt(val, 10));
2172
2122
  }
2173
2123
  /**
2174
- * Get the URI for the streaming endpoint.
2175
- *
2176
- * @param endpoints The service endpoints.
2177
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2178
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2124
+ * Attempt to produce a float representation.
2125
+ * BigInts have an `n` suffix.
2126
+ * @param val
2127
+ * @returns The integer representation or 'NaN' if not numeric.
2179
2128
  */
2180
- function getStreamingUri(endpoints, path, parameters) {
2181
- const canonicalizedPath = canonicalizePath(path);
2182
- const combinedParameters = [...parameters];
2183
- if (endpoints.payloadFilterKey) {
2184
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2129
+ function toFloat(val) {
2130
+ if (typeof val === 'symbol') {
2131
+ return 'NaN';
2185
2132
  }
2186
- return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);
2133
+ return String(parseFloat(val));
2187
2134
  }
2135
+ // Based on:
2136
+ // https://nodejs.org/api/util.html#utilformatformat-args
2137
+ // The result will not match node exactly, but it should get the
2138
+ // right information through.
2139
+ const escapes = {
2140
+ s: (val) => tryStringify(val),
2141
+ d: (val) => toNumber(val),
2142
+ i: (val) => toInt(val),
2143
+ f: (val) => toFloat(val),
2144
+ j: (val) => tryStringify(val),
2145
+ o: (val) => tryStringify(val),
2146
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2147
+ O: (val) => tryStringify(val),
2148
+ c: () => '',
2149
+ };
2188
2150
  /**
2189
- * Get the URI for the polling endpoint.
2151
+ * A basic formatted for use where `util.format` is not available.
2152
+ * This will not be as performant, but it will produce formatted
2153
+ * messages.
2190
2154
  *
2191
- * @param endpoints The service endpoints.
2192
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2193
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2155
+ * @internal
2156
+ *
2157
+ * @param args
2158
+ * @returns Formatted string.
2194
2159
  */
2195
- function getPollingUri(endpoints, path, parameters = []) {
2196
- const canonicalizedPath = canonicalizePath(path);
2197
- const combinedParameters = [...parameters];
2198
- if (endpoints.payloadFilterKey) {
2199
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2160
+ function format(...args) {
2161
+ const formatString = args[0];
2162
+ if (TypeValidators.String.is(formatString)) {
2163
+ args.shift();
2164
+ let out = '';
2165
+ let i = 0;
2166
+ while (i < formatString.length) {
2167
+ const char = formatString.charAt(i);
2168
+ if (char === '%') {
2169
+ const nextIndex = i + 1;
2170
+ if (nextIndex < formatString.length) {
2171
+ const nextChar = formatString.charAt(i + 1);
2172
+ if (nextChar in escapes && args.length) {
2173
+ const value = args.shift();
2174
+ // This rule is for math.
2175
+ out += escapes[nextChar]?.(value);
2176
+ }
2177
+ else if (nextChar === '%') {
2178
+ out += '%';
2179
+ }
2180
+ else {
2181
+ out += `%${nextChar}`;
2182
+ }
2183
+ i += 2;
2184
+ }
2185
+ else {
2186
+ // A trailing '%' has nothing to escape, so keep it as-is.
2187
+ out += '%';
2188
+ i += 1;
2189
+ }
2190
+ }
2191
+ else {
2192
+ out += char;
2193
+ i += 1;
2194
+ }
2195
+ }
2196
+ // If there are any args left after we exhaust the format string
2197
+ // then just stick those on the end.
2198
+ if (args.length) {
2199
+ if (out.length) {
2200
+ out += ' ';
2201
+ }
2202
+ out += args.map(tryStringify).join(' ');
2203
+ }
2204
+ return out;
2200
2205
  }
2201
- return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);
2206
+ return args.map(tryStringify).join(' ');
2202
2207
  }
2208
+
2209
+ var LogPriority;
2210
+ (function (LogPriority) {
2211
+ LogPriority[LogPriority["debug"] = 0] = "debug";
2212
+ LogPriority[LogPriority["info"] = 1] = "info";
2213
+ LogPriority[LogPriority["warn"] = 2] = "warn";
2214
+ LogPriority[LogPriority["error"] = 3] = "error";
2215
+ LogPriority[LogPriority["none"] = 4] = "none";
2216
+ })(LogPriority || (LogPriority = {}));
2217
+ const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
2203
2218
  /**
2204
- * Get the URI for the events endpoint.
2219
+ * A basic logger which handles filtering by level.
2205
2220
  *
2206
- * @param endpoints The service endpoints.
2207
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2208
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2221
+ * With the default options it will write to `console.error`
2222
+ * and it will use the formatting provided by `console.error`.
2223
+ * If the destination is overwritten, then it will use an included
2224
+ * formatter similar to `util.format`.
2225
+ *
2226
+ * If a formatter is available, then that should be overridden
2227
+ * as well for performance.
2209
2228
  */
2210
- function getEventsUri(endpoints, path, parameters = []) {
2211
- const canonicalizedPath = canonicalizePath(path);
2212
- return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
2213
- }
2214
-
2215
- // These classes are of trivial complexity. If they become
2216
- // more complex, then they could be independent files.
2217
- class LDUnexpectedResponseError extends Error {
2218
- constructor(message) {
2219
- super(message);
2220
- this.name = 'LaunchDarklyUnexpectedResponseError';
2229
+ class BasicLogger {
2230
+ /**
2231
+ * This should only be used as a default fallback and not as a convenient
2232
+ * solution. In most cases you should construct a new instance with the
2233
+ * appropriate options for your specific needs.
2234
+ */
2235
+ static get() {
2236
+ return new BasicLogger({});
2221
2237
  }
2222
- }
2223
- class LDClientError extends Error {
2224
- constructor(message) {
2225
- super(message);
2226
- this.name = 'LaunchDarklyClientError';
2238
+ constructor(options) {
2239
+ this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
2240
+ this._name = options.name ?? 'LaunchDarkly';
2241
+ this._formatter = options.formatter;
2242
+ if (typeof options.destination === 'object') {
2243
+ this._destinations = {
2244
+ [LogPriority.debug]: options.destination.debug,
2245
+ [LogPriority.info]: options.destination.info,
2246
+ [LogPriority.warn]: options.destination.warn,
2247
+ [LogPriority.error]: options.destination.error,
2248
+ };
2249
+ }
2250
+ else if (typeof options.destination === 'function') {
2251
+ const { destination } = options;
2252
+ this._destinations = {
2253
+ [LogPriority.debug]: destination,
2254
+ [LogPriority.info]: destination,
2255
+ [LogPriority.warn]: destination,
2256
+ [LogPriority.error]: destination,
2257
+ };
2258
+ }
2227
2259
  }
2228
- }
2229
- class LDTimeoutError extends Error {
2230
- constructor(message) {
2231
- super(message);
2232
- this.name = 'LaunchDarklyTimeoutError';
2260
+ _tryFormat(...args) {
2261
+ try {
2262
+ if (this._formatter) {
2263
+ // In case the provided formatter fails.
2264
+ return this._formatter?.(...args);
2265
+ }
2266
+ return format(...args);
2267
+ }
2268
+ catch {
2269
+ return format(...args);
2270
+ }
2233
2271
  }
2234
- }
2235
- // HTTP statuses in the 4xx range that are still normal failures. Every other
2236
- // 4xx is unexpected.
2237
- const NORMAL_4XX_STATUSES = [400, 408, 429];
2238
- /**
2239
- * Classifies an HTTP status.
2240
- *
2241
- * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
2242
- * and 403, is unexpected. Anything outside the error ranges, including 0 for
2243
- * "no response", is normal.
2244
- */
2245
- function classifyHttpStatus(status) {
2246
- if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
2247
- return 'unexpected';
2272
+ _tryWrite(destination, msg) {
2273
+ try {
2274
+ destination(msg);
2275
+ }
2276
+ catch {
2277
+ // eslint-disable-next-line no-console
2278
+ console.error(msg);
2279
+ }
2280
+ }
2281
+ _log(level, args) {
2282
+ if (level >= this._logLevel) {
2283
+ const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;
2284
+ try {
2285
+ const destination = this._destinations?.[level];
2286
+ if (destination) {
2287
+ this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
2288
+ }
2289
+ else {
2290
+ // `console.error` has its own formatter.
2291
+ // So we don't need to do anything.
2292
+ // eslint-disable-next-line no-console
2293
+ console.error(...args);
2294
+ }
2295
+ }
2296
+ catch {
2297
+ // If all else fails do not break.
2298
+ // eslint-disable-next-line no-console
2299
+ console.error(...args);
2300
+ }
2301
+ }
2302
+ }
2303
+ error(...args) {
2304
+ this._log(LogPriority.error, args);
2248
2305
  }
2249
- return 'normal';
2250
- }
2251
- /**
2252
- * Classifies a transport-level failure (connection refused or dropped, DNS
2253
- * failure, timeout, TLS negotiation failure).
2254
- *
2255
- * Always normal: in an all-HTTPS system every transport error surfaces through
2256
- * the TLS layer, so a certificate misconfiguration cannot be reliably
2257
- * distinguished from a transient network fault, and treating transient faults
2258
- * as unexpected would hold ordinary recoveries to multi-minute waits.
2259
- */
2260
- function classifyTransportFailure() {
2261
- return 'normal';
2262
- }
2263
- /**
2264
- * Check if the HTTP error is recoverable. This will return false if a request
2265
- * made with any payload could not recover. If the reason for the failure
2266
- * is payload specific, for instance a payload that is too large, then
2267
- * it could recover with a different payload.
2268
- *
2269
- * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
2270
- * retained for the event-delivery pathway and is expected to be deprecated
2271
- * once that pathway migrates to failure classification.
2272
- */
2273
- function isHttpRecoverable(status) {
2274
- return classifyHttpStatus(status) === 'normal';
2275
- }
2276
- /**
2277
- * Returns true if the status could recover for a different payload.
2278
- *
2279
- * When used with event processing this indicates that we should discard
2280
- * the payload, but that a subsequent payload may succeed. Therefore we should
2281
- * not stop event processing.
2282
- */
2283
- function isHttpLocallyRecoverable(status) {
2284
- if (status === 413) {
2285
- return true;
2306
+ warn(...args) {
2307
+ this._log(LogPriority.warn, args);
2308
+ }
2309
+ info(...args) {
2310
+ this._log(LogPriority.info, args);
2311
+ }
2312
+ debug(...args) {
2313
+ this._log(LogPriority.debug, args);
2286
2314
  }
2287
- return isHttpRecoverable(status);
2288
2315
  }
2289
2316
 
2317
+ const loggerRequirements = {
2318
+ error: TypeValidators.Function,
2319
+ warn: TypeValidators.Function,
2320
+ info: TypeValidators.Function,
2321
+ debug: TypeValidators.Function,
2322
+ };
2290
2323
  /**
2291
- * Returns a promise which errors after t seconds.
2292
- *
2293
- * @param t Timeout in seconds.
2294
- * @param taskName Name of task being timed for logging and error reporting.
2324
+ * The safeLogger logic exists because we allow the application to pass in a custom logger, but
2325
+ * there is no guarantee that the logger works correctly and if it ever throws exceptions there
2326
+ * could be serious consequences (e.g. an uncaught exception within an error event handler, due
2327
+ * to the SDK trying to log the error, can terminate the application). An exception could result
2328
+ * from faulty logic in the logger implementation, or it could be that this is not a logger at
2329
+ * all but some other kind of object; the former is handled by a catch block that logs an error
2330
+ * message to the SDK's default logger, and we can at least partly guard against the latter by
2331
+ * checking for the presence of required methods at configuration time.
2295
2332
  */
2296
- function cancelableTimedPromise(t, taskName) {
2297
- let timeout;
2298
- let resolve;
2299
- const promise = new Promise((_res, reject) => {
2300
- resolve = _res;
2301
- timeout = setTimeout(() => {
2302
- const e = `${taskName} timed out after ${t} seconds.`;
2303
- reject(new LDTimeoutError(e));
2304
- }, t * 1000);
2305
- });
2306
- return {
2307
- promise,
2308
- cancel: () => {
2309
- resolve();
2310
- clearTimeout(timeout);
2311
- },
2312
- };
2313
- }
2314
-
2315
- function clone(obj) {
2316
- if (obj === undefined || obj === null) {
2317
- return obj;
2333
+ class SafeLogger {
2334
+ /**
2335
+ * Construct a safe logger with the specified logger.
2336
+ * @param logger The logger to use.
2337
+ * @param fallback A fallback logger to use in case an issue is encountered using
2338
+ * the provided logger.
2339
+ */
2340
+ constructor(logger, fallback) {
2341
+ Object.entries(loggerRequirements).forEach(([level, validator]) => {
2342
+ if (!validator.is(logger[level])) {
2343
+ throw new Error(`Provided logger instance must support logger.${level}(...) method`);
2344
+ // Note that the SDK normally does not throw exceptions to the application, but that rule
2345
+ // does not apply to LDClient.init() which will throw an exception if the parameters are so
2346
+ // invalid that we cannot proceed with creating the client. An invalid logger meets those
2347
+ // criteria since the SDK calls the logger during nearly all of its operations.
2348
+ }
2349
+ });
2350
+ this._logger = logger;
2351
+ this._fallback = fallback;
2352
+ }
2353
+ _log(level, args) {
2354
+ try {
2355
+ this._logger[level](...args);
2356
+ }
2357
+ catch {
2358
+ // If all else fails do not break.
2359
+ this._fallback[level](...args);
2360
+ }
2361
+ }
2362
+ error(...args) {
2363
+ this._log('error', args);
2364
+ }
2365
+ warn(...args) {
2366
+ this._log('warn', args);
2367
+ }
2368
+ info(...args) {
2369
+ this._log('info', args);
2370
+ }
2371
+ debug(...args) {
2372
+ this._log('debug', args);
2318
2373
  }
2319
- return JSON.parse(JSON.stringify(obj));
2320
- }
2321
-
2322
- function secondsToMillis(sec) {
2323
- return Math.trunc(sec * 1000);
2324
2374
  }
2325
2375
 
2326
- /**
2327
- * Wait before calling the same function. Useful for expensive calls.
2328
- * Adapted from https://amitd.co/code/typescript/debounce.
2329
- *
2330
- * @return The debounced function.
2331
- *
2332
- * @example
2333
- *
2334
- * ```js
2335
- * const debouncedFunction = debounce(e => {
2336
- * console.log(e);
2337
- * }, 5000);
2338
- *
2339
- * // Console logs 'Hello world again ' after 5 seconds
2340
- * debouncedFunction('Hello world');
2341
- * debouncedFunction('Hello world again');
2342
- * ```
2343
- * @param fn The function to be debounced.
2344
- * @param delayMs Defaults to 5 seconds.
2345
- */
2346
- const debounce = (fn, delayMs = 5000) => {
2347
- let timer;
2348
- return (...args) => {
2349
- clearTimeout(timer);
2350
- timer = setTimeout(() => {
2351
- fn(...args);
2352
- }, delayMs);
2353
- };
2376
+ const createSafeLogger = (logger) => {
2377
+ const basicLogger = new BasicLogger({
2378
+ level: 'info',
2379
+ // eslint-disable-next-line no-console
2380
+ destination: console.error,
2381
+ formatter: format,
2382
+ });
2383
+ return logger ? new SafeLogger(logger, basicLogger) : basicLogger;
2354
2384
  };
2355
2385
 
2356
- const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
2357
-
2358
2386
  /**
2359
- * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.
2360
- * Sourced from below but modified to include checks for empty object and ignoring keys.
2361
- * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
2362
- *
2363
- * @param obj
2364
- * @param ignoreKeys
2387
+ * Messages for issues which can be encountered from processing the configuration options.
2365
2388
  */
2366
- const deepCompact = (obj, ignoreKeys) => {
2367
- if (!obj) {
2368
- return obj;
2389
+ class OptionMessages {
2390
+ static deprecated(oldName, newName) {
2391
+ return `"${oldName}" is deprecated, please use "${newName}"`;
2369
2392
  }
2370
- return Object.entries(obj).reduce((acc, [key, value]) => {
2371
- if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {
2372
- acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;
2373
- }
2374
- return acc;
2375
- }, {});
2376
- };
2377
-
2378
- /* eslint-disable */
2379
- // Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual
2380
- // {{? it.es6 }}
2381
- // var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
2382
- // {{?}}
2383
- function fastDeepEqual(a, b) {
2384
- if (a === b)
2385
- return true;
2386
- if (a && b && typeof a == 'object' && typeof b == 'object') {
2387
- if (a.constructor !== b.constructor)
2388
- return false;
2389
- var length, i, keys;
2390
- if (Array.isArray(a)) {
2391
- length = a.length;
2392
- if (length != b.length)
2393
- return false;
2394
- for (i = length; i-- !== 0;)
2395
- if (!fastDeepEqual(a[i], b[i]))
2396
- return false;
2397
- return true;
2398
- }
2399
- // {{? it.es6 }}
2400
- if (a instanceof Map && b instanceof Map) {
2401
- if (a.size !== b.size)
2402
- return false;
2403
- for (i of a.entries())
2404
- if (!b.has(i[0]))
2405
- return false;
2406
- for (i of a.entries())
2407
- if (!fastDeepEqual(i[1], b.get(i[0])))
2408
- return false;
2409
- return true;
2410
- }
2411
- if (a instanceof Set && b instanceof Set) {
2412
- if (a.size !== b.size)
2413
- return false;
2414
- for (i of a.entries())
2415
- if (!b.has(i[0]))
2416
- return false;
2417
- return true;
2418
- }
2419
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
2420
- // @ts-ignore
2421
- length = a.length;
2422
- // @ts-ignore
2423
- if (length != b.length)
2424
- return false;
2425
- for (i = length; i-- !== 0;) {
2426
- // @ts-ignore
2427
- if (a[i] !== b[i])
2428
- return false;
2393
+ static optionBelowMinimum(name, value, min) {
2394
+ return `Config option "${name}" had invalid value of ${value}, using minimum of ${min} instead`;
2395
+ }
2396
+ static unknownOption(name) {
2397
+ return `Ignoring unknown config option "${name}"`;
2398
+ }
2399
+ static wrongOptionType(name, expectedType, actualType) {
2400
+ return `Config option "${name}" should be of type ${expectedType}, got ${actualType}, using default value`;
2401
+ }
2402
+ static wrongOptionTypeBoolean(name, actualType) {
2403
+ return `Config option "${name}" should be a boolean, got ${actualType}, converting to boolean`;
2404
+ }
2405
+ static invalidTagValue(name) {
2406
+ return `Config option "${name}" must only contain letters, numbers, ., _ or -.`;
2407
+ }
2408
+ static tagValueTooLong(name) {
2409
+ return `Value of "${name}" was longer than 64 characters and was discarded.`;
2410
+ }
2411
+ static partialEndpoint(name) {
2412
+ return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;
2413
+ }
2414
+ }
2415
+
2416
+ /**
2417
+ * Expression to validate characters that are allowed in tag keys and values.
2418
+ */
2419
+ const allowedTagCharacters = /^(\w|\.|-)+$/;
2420
+ const regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);
2421
+ const tagValidator = {
2422
+ is: (u, name) => {
2423
+ if (regexValidator.is(u)) {
2424
+ if (u.length > 64) {
2425
+ return { valid: false, message: OptionMessages.tagValueTooLong(name) };
2429
2426
  }
2430
- return true;
2427
+ return { valid: true };
2431
2428
  }
2432
- // {{?}}
2433
- if (a.constructor === RegExp)
2434
- return a.source === b.source && a.flags === b.flags;
2435
- if (a.valueOf !== Object.prototype.valueOf)
2436
- return a.valueOf() === b.valueOf();
2437
- if (a.toString !== Object.prototype.toString)
2438
- return a.toString() === b.toString();
2439
- keys = Object.keys(a);
2440
- length = keys.length;
2441
- if (length !== Object.keys(b).length)
2442
- return false;
2443
- for (i = length; i-- !== 0;)
2444
- if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
2445
- return false;
2446
- for (i = length; i-- !== 0;) {
2447
- var key = keys[i];
2448
- // {{? it.react }}
2449
- // if (key === '_owner' && a.$$typeof) {
2450
- // // React-specific: avoid traversing React elements' _owner.
2451
- // // _owner contains circular references
2452
- // // and is not needed when comparing the actual elements (and not their owners)
2453
- // continue;
2454
- // }
2455
- // {{?}}
2456
- if (!fastDeepEqual(a[key], b[key]))
2457
- return false;
2429
+ return { valid: false, message: OptionMessages.invalidTagValue(name) };
2430
+ },
2431
+ };
2432
+ /**
2433
+ * Class for managing tags.
2434
+ */
2435
+ class ApplicationTags {
2436
+ constructor(options) {
2437
+ const tags = {};
2438
+ const application = options?.application;
2439
+ const logger = options?.logger;
2440
+ if (application) {
2441
+ Object.entries(application).forEach(([key, value]) => {
2442
+ if (value !== null && value !== undefined) {
2443
+ const { valid, message } = tagValidator.is(value, `application.${key}`);
2444
+ if (!valid) {
2445
+ logger?.warn(message);
2446
+ }
2447
+ else if (key === 'versionName') {
2448
+ tags[`application-version-name`] = [value];
2449
+ }
2450
+ else {
2451
+ tags[`application-${key}`] = [value];
2452
+ }
2453
+ }
2454
+ });
2455
+ }
2456
+ const tagKeys = Object.keys(tags);
2457
+ if (tagKeys.length) {
2458
+ this.value = tagKeys
2459
+ .sort()
2460
+ .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
2461
+ .join(' ');
2458
2462
  }
2459
- return true;
2460
2463
  }
2461
- // true if both NaN, false otherwise
2462
- return a !== a && b !== b;
2463
2464
  }
2464
2465
 
2465
- function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent', instanceId) {
2466
- const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();
2467
- const headers = {
2468
- [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
2469
- };
2470
- // edge sdks sets this to false because they use the clientSideID
2471
- // and they don't need the authorization header
2472
- if (includeAuthorizationHeader) {
2473
- headers.authorization = sdkKey;
2474
- }
2475
- if (wrapperName) {
2476
- headers['x-launchdarkly-wrapper'] = wrapperVersion
2477
- ? `${wrapperName}/${wrapperVersion}`
2478
- : wrapperName;
2479
- }
2480
- if (tags?.value) {
2481
- headers['x-launchdarkly-tags'] = tags.value;
2482
- }
2483
- // Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
2484
- // per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
2485
- // for generating the GUID once per SDK instance and passing it here, so that it rides on
2486
- // every outbound request via this shared default-headers map. Client/edge SDKs do not pass
2487
- // this value, so the header is omitted for them.
2488
- if (instanceId) {
2489
- headers['x-launchdarkly-instance-id'] = instanceId;
2466
+ /**
2467
+ * The client context provides basic configuration and platform support which are required
2468
+ * when building SDK components.
2469
+ */
2470
+ class ClientContext {
2471
+ constructor(sdkKey, configuration, platform) {
2472
+ this.platform = platform;
2473
+ this.basicConfiguration = {
2474
+ tags: configuration.tags,
2475
+ logger: configuration.logger,
2476
+ offline: configuration.offline,
2477
+ serviceEndpoints: configuration.serviceEndpoints,
2478
+ sdkKey,
2479
+ };
2490
2480
  }
2491
- return headers;
2492
2481
  }
2493
- function httpErrorMessage(err, context, retryMessage) {
2494
- let desc;
2495
- if (err.status) {
2496
- desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;
2482
+
2483
+ function canonicalizeUri(uri) {
2484
+ return uri.replace(/\/+$/, '');
2485
+ }
2486
+ function canonicalizePath(path) {
2487
+ return path.replace(/^\/+/, '').replace(/\?$/, '');
2488
+ }
2489
+ /**
2490
+ * Specifies the base service URIs used by SDK components.
2491
+ */
2492
+ class ServiceEndpoints {
2493
+ constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {
2494
+ this.streaming = canonicalizeUri(streaming);
2495
+ this.polling = canonicalizeUri(polling);
2496
+ this.events = canonicalizeUri(events);
2497
+ this.analyticsEventPath = analyticsEventPath;
2498
+ this.diagnosticEventPath = diagnosticEventPath;
2499
+ this.includeAuthorizationHeader = includeAuthorizationHeader;
2500
+ this.payloadFilterKey = payloadFilterKey;
2497
2501
  }
2498
- else {
2499
- desc = `I/O error (${err.message || 'unknown error'})`;
2502
+ }
2503
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2504
+ ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
2505
+ function getWithParams(uri, parameters = []) {
2506
+ if (parameters.length === 0) {
2507
+ return uri;
2500
2508
  }
2501
- const action = retryMessage ?? 'giving up permanently';
2502
- return `Received ${desc} for ${context} - ${action}`;
2509
+ const parts = parameters.map(({ key, value }) => `${key}=${value}`);
2510
+ return `${uri}?${parts.join('&')}`;
2503
2511
  }
2504
- function shouldRetry({ status }) {
2505
- return status ? isHttpRecoverable(status) : true;
2512
+ /**
2513
+ * Get the URI for the streaming endpoint.
2514
+ *
2515
+ * @param endpoints The service endpoints.
2516
+ * @param path The path to the resource, devoid of any query parameters or hrefs.
2517
+ * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2518
+ */
2519
+ function getStreamingUri(endpoints, path, parameters) {
2520
+ const canonicalizedPath = canonicalizePath(path);
2521
+ const combinedParameters = [...parameters];
2522
+ if (endpoints.payloadFilterKey) {
2523
+ combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2524
+ }
2525
+ return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);
2506
2526
  }
2507
2527
  /**
2508
- * In react-native use base64-js to polyfill btoa. This is safe
2509
- * because the react-native repo uses it too. Set the global.btoa to the encode
2510
- * function of base64-js.
2511
- * https://github.com/beatgammit/base64-js
2512
- * https://github.com/axios/axios/issues/2235#issuecomment-512204616
2528
+ * Get the URI for the polling endpoint.
2513
2529
  *
2514
- * Ripped from https://thewoods.blog/base64url/
2530
+ * @param endpoints The service endpoints.
2531
+ * @param path The path to the resource, devoid of any query parameters or hrefs.
2532
+ * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2515
2533
  */
2516
- const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
2517
-
2518
- var noop = () => { };
2519
-
2520
- const sleep = async (delayMillis = 1000) => new Promise((resolve) => {
2521
- setTimeout(resolve, delayMillis);
2522
- });
2523
-
2534
+ function getPollingUri(endpoints, path, parameters = []) {
2535
+ const canonicalizedPath = canonicalizePath(path);
2536
+ const combinedParameters = [...parameters];
2537
+ if (endpoints.payloadFilterKey) {
2538
+ combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2539
+ }
2540
+ return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);
2541
+ }
2524
2542
  /**
2525
- * Returns a promise which errors after t seconds.
2543
+ * Get the URI for the events endpoint.
2526
2544
  *
2527
- * @param t Timeout in seconds.
2528
- * @param taskName Name of task being timed for logging and error reporting.
2545
+ * @param endpoints The service endpoints.
2546
+ * @param path The path to the resource, devoid of any query parameters or hrefs.
2547
+ * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2529
2548
  */
2530
- const timedPromise = (t, taskName) => new Promise((_res, reject) => {
2531
- setTimeout(() => {
2532
- const e = `${taskName} timed out after ${t} seconds.`;
2533
- reject(new LDTimeoutError(e));
2534
- }, t * 1000);
2535
- });
2549
+ function getEventsUri(endpoints, path, parameters = []) {
2550
+ const canonicalizedPath = canonicalizePath(path);
2551
+ return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
2552
+ }
2536
2553
 
2537
2554
  class DiagnosticsManager {
2538
2555
  constructor(sdkKey, _platform, _diagnosticInitConfig) {
@@ -3642,6 +3659,136 @@ class PayloadStreamReader {
3642
3659
  }
3643
3660
  }
3644
3661
 
3662
+ /**
3663
+ * Wraps the raw headers in the fetch `Headers` shape. Lookups are case-insensitive.
3664
+ * Multi-value headers are joined with ", ", names that differ only by case merge into one
3665
+ * joined value, and names without a value are skipped.
3666
+ */
3667
+ function wrapRawHeaders(headers) {
3668
+ const normalized = new Map();
3669
+ Object.keys(headers).forEach((key) => {
3670
+ const val = headers[key];
3671
+ if (val !== undefined && val !== null) {
3672
+ const name = key.toLowerCase();
3673
+ const joined = Array.isArray(val) ? val.join(', ') : val;
3674
+ const existing = normalized.get(name);
3675
+ normalized.set(name, existing === undefined ? joined : `${existing}, ${joined}`);
3676
+ }
3677
+ });
3678
+ return {
3679
+ get: (name) => normalized.get(name.toLowerCase()) ?? null,
3680
+ keys: () => normalized.keys(),
3681
+ values: () => normalized.values(),
3682
+ entries: () => normalized.entries(),
3683
+ forEach: (callback) => {
3684
+ normalized.forEach((value, key) => callback(value, key));
3685
+ },
3686
+ has: (name) => normalized.has(name.toLowerCase()),
3687
+ };
3688
+ }
3689
+ /**
3690
+ * Creates a response for a streaming request. The response does not buffer the body. Each
3691
+ * read hands out the next chunk from the source iterator. The body does not enforce a
3692
+ * consumer lock: every `getReader`, `text`, and `json` call reads from the same iterator,
3693
+ * so the caller uses one consumer per response. The `cancel` methods on the body and the
3694
+ * reader call every release function the source provides: they destroy the source when it
3695
+ * has a `destroy` method, and they also call the iterator's `return` method when one
3696
+ * exists. The body passes through as-is, so the caller decodes any content encoding first.
3697
+ *
3698
+ * @param source The raw platform response, for example a Node `IncomingMessage`. A missing
3699
+ * status code maps to 0, and a missing status message maps to an empty string.
3700
+ */
3701
+ function createStreamingResponse(source) {
3702
+ // A consumer compiled without `Symbol.asyncIterator` in its lib can pass a source that
3703
+ // lacks the iterator without a compile error. The check turns that mistake into a named
3704
+ // failure instead of a bare member-access TypeError.
3705
+ if (typeof source[Symbol.asyncIterator] !== 'function') {
3706
+ throw new TypeError('the streaming response source does not provide an async iterator');
3707
+ }
3708
+ const iterator = source[Symbol.asyncIterator]();
3709
+ const cancel = async () => {
3710
+ // Destroy the stream first. That rejects a pending read and unblocks a queued return
3711
+ // call. A Node readable iterator queues the return call behind a pending read, and on
3712
+ // a stream that was never read it completes without a destroy, so the return call
3713
+ // alone cannot release the connection. Do not await it for the same reason. Each
3714
+ // release call is guarded on its own, so a release function that throws, or a return
3715
+ // that resolves synchronously, does not skip the other release path or reject cancel.
3716
+ try {
3717
+ source.destroy?.();
3718
+ }
3719
+ catch {
3720
+ // A throwing destroy has nothing left to release.
3721
+ }
3722
+ try {
3723
+ Promise.resolve(iterator.return?.()).catch(() => { });
3724
+ }
3725
+ catch {
3726
+ // A throwing return has nothing left to release.
3727
+ }
3728
+ };
3729
+ async function text() {
3730
+ const decoder = new TextDecoder();
3731
+ let result = '';
3732
+ try {
3733
+ let next = await iterator.next();
3734
+ while (!next.done) {
3735
+ if (next.value !== undefined) {
3736
+ try {
3737
+ result += decoder.decode(next.value, { stream: true });
3738
+ }
3739
+ catch {
3740
+ // decode() rejects a chunk that is not a BufferSource. The fixed message keeps
3741
+ // chunk contents out of error messages.
3742
+ throw new TypeError('the source supplied a chunk that is not a BufferSource');
3743
+ }
3744
+ }
3745
+ // The stream provides the chunks in sequence, so the reads cannot run in parallel.
3746
+ // oxlint-disable-next-line no-await-in-loop
3747
+ next = await iterator.next();
3748
+ }
3749
+ }
3750
+ catch (err) {
3751
+ // text() owns the body, so any failed read must release the source itself. This
3752
+ // covers a rejecting next() as well as a bad chunk.
3753
+ cancel();
3754
+ throw err;
3755
+ }
3756
+ // The final decode flushes a trailing partial multi-byte sequence.
3757
+ return result + decoder.decode();
3758
+ }
3759
+ return {
3760
+ headers: wrapRawHeaders(source.headers),
3761
+ status: source.statusCode ?? 0,
3762
+ statusText: source.statusMessage ?? '',
3763
+ body: {
3764
+ getReader: () => ({
3765
+ read: async () => {
3766
+ const next = await iterator.next();
3767
+ if (next.done) {
3768
+ return { done: true };
3769
+ }
3770
+ return { done: false, value: next.value };
3771
+ },
3772
+ cancel,
3773
+ }),
3774
+ cancel,
3775
+ },
3776
+ text,
3777
+ json: async () => JSON.parse(await text()),
3778
+ };
3779
+ }
3780
+
3781
+ /**
3782
+ * Converts the request options into the init shape a platform's native `fetch` accepts. A
3783
+ * platform can declare its `AbortSignal` as a lexical class, which `AbortSignalLike`
3784
+ * cannot resolve to, so the `signal` member widens here. The caller must pass a signal
3785
+ * created by the running platform. The widening then only restores the type the runtime
3786
+ * already has.
3787
+ */
3788
+ function toRequestInit(options) {
3789
+ return options;
3790
+ }
3791
+
3645
3792
  /**
3646
3793
  * Creates an InitMetadata object from initialization headers.
3647
3794
  *
@@ -3717,6 +3864,7 @@ var index = /*#__PURE__*/Object.freeze({
3717
3864
  PayloadStreamReader: PayloadStreamReader,
3718
3865
  canonicalize: canonicalize,
3719
3866
  createProtocolHandler: createProtocolHandler,
3867
+ createStreamingResponse: createStreamingResponse,
3720
3868
  initMetadataFromHeaders: initMetadataFromHeaders,
3721
3869
  isLegacyUser: isLegacyUser,
3722
3870
  isMultiKind: isMultiKind,
@@ -3726,8 +3874,9 @@ var index = /*#__PURE__*/Object.freeze({
3726
3874
  safeGetHooks: safeGetHooks,
3727
3875
  safeGetName: safeGetName,
3728
3876
  safeRegisterPlugins: safeRegisterPlugins,
3729
- shouldSample: shouldSample
3877
+ shouldSample: shouldSample,
3878
+ toRequestInit: toRequestInit
3730
3879
  });
3731
3880
 
3732
- export { ApplicationTags, AttributeReference, AutoEnvAttributes, BasicLogger, ClientContext, CompositeDataSource, Context, ContextFilter, DataSourceErrorKind, DateValidator, DefaultBackoff, FactoryOrInstance, Function, KindValidator, LDClientError, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, LDTimeoutError, LDUnexpectedResponseError, NullableBoolean, NumberWithMinimum, OneOf, OptionMessages, SafeLogger, ServiceEndpoints, StringMatchingRegex, Type, TypeArray, TypeValidators, base64UrlEncode, cancelableTimedPromise, classifyHttpStatus, classifyTransportFailure, clone, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, createSafeLogger, debounce, deepCompact, defaultHeaders, fastDeepEqual, forPolling, forStreaming, getEventsUri, getPollingUri, getStreamingUri, httpErrorMessage, index as internal, isHttpLocallyRecoverable, isHttpRecoverable, isNullish, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };
3881
+ export { ApplicationTags, AttributeReference, AutoEnvAttributes, BasicLogger, ClientContext, CompositeDataSource, Context, ContextFilter, DataSourceErrorKind, DateValidator, DefaultBackoff, FactoryOrInstance, Function, KindValidator, LDClientError, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, LDTimeoutError, LDUnexpectedResponseError, NullableBoolean, NumberWithMinimum, OneOf, OptionMessages, SafeLogger, ServiceEndpoints, StringMatchingRegex, Type, TypeArray, TypeValidators, base64UrlEncode, cancelableTimedPromise, classifyHttpStatus, classifyTransportFailure, clone, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, createSafeLogger, debounce, deepCompact, defaultHeaders, fastDeepEqual, forPolling, forStreaming, getEventsUri, getPollingUri, getStreamingUri, httpErrorMessage, index as internal, isHttpLocallyRecoverable, isHttpRecoverable, isNullish, monotonicNow, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };
3733
3882
  //# sourceMappingURL=index.mjs.map