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