@launchdarkly/js-sdk-common 2.28.0 → 2.29.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.
@@ -1482,1058 +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.shift();
1825
- if (TypeValidators.String.is(formatString)) {
1826
- let out = '';
1827
- let i = 0;
1828
- while (i < formatString.length) {
1829
- const char = formatString.charAt(i);
1830
- if (char === '%') {
1831
- const nextIndex = i + 1;
1832
- if (nextIndex < formatString.length) {
1833
- const nextChar = formatString.charAt(i + 1);
1834
- if (nextChar in escapes && args.length) {
1835
- const value = args.shift();
1836
- // This rule is for math.
1837
- out += escapes[nextChar]?.(value);
1838
- }
1839
- else if (nextChar === '%') {
1840
- out += '%';
1841
- }
1842
- else {
1843
- out += `%${nextChar}`;
1844
- }
1845
- i += 2;
1846
- }
1847
- else {
1848
- // A trailing '%' has nothing to escape, so keep it as-is.
1849
- out += '%';
1850
- i += 1;
1851
- }
1852
- }
1853
- else {
1854
- out += char;
1855
- i += 1;
1856
- }
1857
- }
1858
- // If there are any args left after we exhaust the format string
1859
- // then just stick those on the end.
1860
- if (args.length) {
1861
- if (out.length) {
1862
- out += ' ';
1863
- }
1864
- out += args.map(tryStringify).join(' ');
1865
- }
1866
- 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');
1867
1814
  }
1868
- return args.map(tryStringify).join(' ');
1815
+ return useWallClock ? Date.now() : globalThis.performance.now();
1869
1816
  }
1870
1817
 
1871
- var LogPriority;
1872
- (function (LogPriority) {
1873
- LogPriority[LogPriority["debug"] = 0] = "debug";
1874
- LogPriority[LogPriority["info"] = 1] = "info";
1875
- LogPriority[LogPriority["warn"] = 2] = "warn";
1876
- LogPriority[LogPriority["error"] = 3] = "error";
1877
- LogPriority[LogPriority["none"] = 4] = "none";
1878
- })(LogPriority || (LogPriority = {}));
1879
- const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
1880
1818
  /**
1881
- * A basic logger which handles filtering by level.
1819
+ * Returns a promise which errors after t seconds.
1882
1820
  *
1883
- * With the default options it will write to `console.error`
1884
- * and it will use the formatting provided by `console.error`.
1885
- * If the destination is overwritten, then it will use an included
1886
- * 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.
1887
1835
  *
1888
- * If a formatter is available, then that should be overridden
1889
- * 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.
1890
1840
  */
1891
- class BasicLogger {
1892
- /**
1893
- * This should only be used as a default fallback and not as a convenient
1894
- * solution. In most cases you should construct a new instance with the
1895
- * appropriate options for your specific needs.
1896
- */
1897
- static get() {
1898
- return new BasicLogger({});
1899
- }
1900
- constructor(options) {
1901
- this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
1902
- this._name = options.name ?? 'LaunchDarkly';
1903
- this._formatter = options.formatter;
1904
- if (typeof options.destination === 'object') {
1905
- this._destinations = {
1906
- [LogPriority.debug]: options.destination.debug,
1907
- [LogPriority.info]: options.destination.info,
1908
- [LogPriority.warn]: options.destination.warn,
1909
- [LogPriority.error]: options.destination.error,
1910
- };
1911
- }
1912
- else if (typeof options.destination === 'function') {
1913
- const { destination } = options;
1914
- this._destinations = {
1915
- [LogPriority.debug]: destination,
1916
- [LogPriority.info]: destination,
1917
- [LogPriority.warn]: destination,
1918
- [LogPriority.error]: destination,
1919
- };
1920
- }
1921
- }
1922
- _tryFormat(...args) {
1923
- try {
1924
- if (this._formatter) {
1925
- // In case the provided formatter fails.
1926
- return this._formatter?.(...args);
1927
- }
1928
- return format(...args);
1929
- }
1930
- catch {
1931
- return format(...args);
1932
- }
1933
- }
1934
- _tryWrite(destination, msg) {
1935
- try {
1936
- destination(msg);
1937
- }
1938
- catch {
1939
- // eslint-disable-next-line no-console
1940
- console.error(msg);
1941
- }
1942
- }
1943
- _log(level, args) {
1944
- if (level >= this._logLevel) {
1945
- const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;
1946
- try {
1947
- const destination = this._destinations?.[level];
1948
- if (destination) {
1949
- this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
1950
- }
1951
- else {
1952
- // `console.error` has its own formatter.
1953
- // So we don't need to do anything.
1954
- // eslint-disable-next-line no-console
1955
- console.error(...args);
1956
- }
1957
- }
1958
- catch {
1959
- // If all else fails do not break.
1960
- // eslint-disable-next-line no-console
1961
- console.error(...args);
1841
+ function createAfterHealthyFor(healthyForMs, clock = monotonicNow) {
1842
+ let healthySinceMs;
1843
+ return {
1844
+ noteHealthy() {
1845
+ if (healthySinceMs === undefined) {
1846
+ healthySinceMs = clock();
1962
1847
  }
1963
- }
1964
- }
1965
- error(...args) {
1966
- this._log(LogPriority.error, args);
1967
- }
1968
- warn(...args) {
1969
- this._log(LogPriority.warn, args);
1970
- }
1971
- info(...args) {
1972
- this._log(LogPriority.info, args);
1973
- }
1974
- debug(...args) {
1975
- this._log(LogPriority.debug, args);
1976
- }
1848
+ },
1849
+ noteFailure() {
1850
+ healthySinceMs = undefined;
1851
+ },
1852
+ isSatisfied() {
1853
+ return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1854
+ },
1855
+ };
1977
1856
  }
1978
-
1979
- const loggerRequirements = {
1980
- error: TypeValidators.Function,
1981
- warn: TypeValidators.Function,
1982
- info: TypeValidators.Function,
1983
- debug: TypeValidators.Function,
1984
- };
1985
1857
  /**
1986
- * The safeLogger logic exists because we allow the application to pass in a custom logger, but
1987
- * there is no guarantee that the logger works correctly and if it ever throws exceptions there
1988
- * could be serious consequences (e.g. an uncaught exception within an error event handler, due
1989
- * to the SDK trying to log the error, can terminate the application). An exception could result
1990
- * from faulty logic in the logger implementation, or it could be that this is not a logger at
1991
- * all but some other kind of object; the former is handled by a catch block that logs an error
1992
- * message to the SDK's default logger, and we can at least partly guard against the latter by
1993
- * 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.
1994
1863
  */
1995
- class SafeLogger {
1996
- /**
1997
- * Construct a safe logger with the specified logger.
1998
- * @param logger The logger to use.
1999
- * @param fallback A fallback logger to use in case an issue is encountered using
2000
- * the provided logger.
2001
- */
2002
- constructor(logger, fallback) {
2003
- Object.entries(loggerRequirements).forEach(([level, validator]) => {
2004
- if (!validator.is(logger[level])) {
2005
- throw new Error(`Provided logger instance must support logger.${level}(...) method`);
2006
- // Note that the SDK normally does not throw exceptions to the application, but that rule
2007
- // does not apply to LDClient.init() which will throw an exception if the parameters are so
2008
- // invalid that we cannot proceed with creating the client. An invalid logger meets those
2009
- // criteria since the SDK calls the logger during nearly all of its operations.
2010
- }
2011
- });
2012
- this._logger = logger;
2013
- this._fallback = fallback;
2014
- }
2015
- _log(level, args) {
2016
- try {
2017
- this._logger[level](...args);
2018
- }
2019
- catch {
2020
- // If all else fails do not break.
2021
- this._fallback[level](...args);
2022
- }
2023
- }
2024
- error(...args) {
2025
- this._log('error', args);
2026
- }
2027
- warn(...args) {
2028
- this._log('warn', args);
2029
- }
2030
- info(...args) {
2031
- this._log('info', args);
2032
- }
2033
- debug(...args) {
2034
- this._log('debug', args);
2035
- }
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
+ };
2036
1877
  }
2037
1878
 
2038
- const createSafeLogger = (logger) => {
2039
- const basicLogger = new BasicLogger({
2040
- level: 'info',
2041
- // eslint-disable-next-line no-console
2042
- destination: console.error,
2043
- formatter: format,
2044
- });
2045
- return logger ? new SafeLogger(logger, basicLogger) : basicLogger;
2046
- };
2047
-
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;
1894
+ }
1895
+ logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1896
+ return defaultValueMs;
1897
+ }
2048
1898
  /**
2049
- * Messages for issues which can be encountered from processing the configuration options.
1899
+ * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1900
+ * the contract on the values.
2050
1901
  */
2051
- class OptionMessages {
2052
- static deprecated(oldName, newName) {
2053
- return `"${oldName}" is deprecated, please use "${newName}"`;
2054
- }
2055
- static optionBelowMinimum(name, value, min) {
2056
- return `Config option "${name}" had invalid value of ${value}, using minimum of ${min} instead`;
2057
- }
2058
- static unknownOption(name) {
2059
- return `Ignoring unknown config option "${name}"`;
2060
- }
2061
- static wrongOptionType(name, expectedType, actualType) {
2062
- return `Config option "${name}" should be of type ${expectedType}, got ${actualType}, using default value`;
2063
- }
2064
- static wrongOptionTypeBoolean(name, actualType) {
2065
- return `Config option "${name}" should be a boolean, got ${actualType}, converting to boolean`;
2066
- }
2067
- static invalidTagValue(name) {
2068
- return `Config option "${name}" must only contain letters, numbers, ., _ or -.`;
2069
- }
2070
- static tagValueTooLong(name) {
2071
- return `Value of "${name}" was longer than 64 characters and was discarded.`;
2072
- }
2073
- static partialEndpoint(name) {
2074
- return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;
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;
1920
+ }
1921
+ attempts = 0;
1922
+ extended = false;
1923
+ minDelayMs = normalInitialDelayMs;
1924
+ maxDelayMs = normalCeilingMs;
2075
1925
  }
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
+ };
2076
1975
  }
2077
-
2078
1976
  /**
2079
- * Expression to validate characters that are allowed in tag keys and values.
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.
2080
1986
  */
2081
- const allowedTagCharacters = /^(\w|\.|-)+$/;
2082
- const regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);
2083
- const tagValidator = {
2084
- is: (u, name) => {
2085
- if (regexValidator.is(u)) {
2086
- if (u.length > 64) {
2087
- return { valid: false, message: OptionMessages.tagValueTooLong(name) };
2088
- }
2089
- return { valid: true };
2090
- }
2091
- return { valid: false, message: OptionMessages.invalidTagValue(name) };
2092
- },
2093
- };
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,
1996
+ });
1997
+ }
2094
1998
  /**
2095
- * Class for managing tags.
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.
2096
2008
  */
2097
- class ApplicationTags {
2098
- constructor(options) {
2099
- const tags = {};
2100
- const application = options?.application;
2101
- const logger = options?.logger;
2102
- if (application) {
2103
- Object.entries(application).forEach(([key, value]) => {
2104
- if (value !== null && value !== undefined) {
2105
- const { valid, message } = tagValidator.is(value, `application.${key}`);
2106
- if (!valid) {
2107
- logger?.warn(message);
2108
- }
2109
- else if (key === 'versionName') {
2110
- tags[`application-version-name`] = [value];
2111
- }
2112
- else {
2113
- tags[`application-${key}`] = [value];
2114
- }
2115
- }
2116
- });
2117
- }
2118
- const tagKeys = Object.keys(tags);
2119
- if (tagKeys.length) {
2120
- this.value = tagKeys
2121
- .sort()
2122
- .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
2123
- .join(' ');
2124
- }
2125
- }
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
+ });
2126
2019
  }
2127
2020
 
2128
2021
  /**
2129
- * The client context provides basic configuration and platform support which are required
2130
- * when building SDK components.
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.
2131
2028
  */
2132
- class ClientContext {
2133
- constructor(sdkKey, configuration, platform) {
2134
- this.platform = platform;
2135
- this.basicConfiguration = {
2136
- tags: configuration.tags,
2137
- logger: configuration.logger,
2138
- offline: configuration.offline,
2139
- serviceEndpoints: configuration.serviceEndpoints,
2140
- sdkKey,
2141
- };
2142
- }
2143
- }
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
+ });
2144
2053
 
2145
- function canonicalizeUri(uri) {
2146
- return uri.replace(/\/+$/, '');
2147
- }
2148
- function canonicalizePath(path) {
2149
- return path.replace(/^\/+/, '').replace(/\?$/, '');
2150
- }
2151
2054
  /**
2152
- * Specifies the base service URIs used by SDK components.
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.
2153
2061
  */
2154
- class ServiceEndpoints {
2155
- constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {
2156
- this.streaming = canonicalizeUri(streaming);
2157
- this.polling = canonicalizeUri(polling);
2158
- this.events = canonicalizeUri(events);
2159
- this.analyticsEventPath = analyticsEventPath;
2160
- this.diagnosticEventPath = diagnosticEventPath;
2161
- this.includeAuthorizationHeader = includeAuthorizationHeader;
2162
- this.payloadFilterKey = payloadFilterKey;
2062
+ function tryStringify(val) {
2063
+ if (typeof val === 'string') {
2064
+ return val;
2163
2065
  }
2164
- }
2165
- // eslint-disable-next-line @typescript-eslint/naming-convention
2166
- ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
2167
- function getWithParams(uri, parameters = []) {
2168
- if (parameters.length === 0) {
2169
- return uri;
2066
+ if (val === undefined) {
2067
+ return 'undefined';
2170
2068
  }
2171
- const parts = parameters.map(({ key, value }) => `${key}=${value}`);
2172
- return `${uri}?${parts.join('&')}`;
2173
- }
2174
- /**
2175
- * Get the URI for the streaming endpoint.
2176
- *
2177
- * @param endpoints The service endpoints.
2178
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2179
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2180
- */
2181
- function getStreamingUri(endpoints, path, parameters) {
2182
- const canonicalizedPath = canonicalizePath(path);
2183
- const combinedParameters = [...parameters];
2184
- if (endpoints.payloadFilterKey) {
2185
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2069
+ if (val === null) {
2070
+ return 'null';
2186
2071
  }
2187
- return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);
2188
- }
2189
- /**
2190
- * Get the URI for the polling endpoint.
2191
- *
2192
- * @param endpoints The service endpoints.
2193
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2194
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2195
- */
2196
- function getPollingUri(endpoints, path, parameters = []) {
2197
- const canonicalizedPath = canonicalizePath(path);
2198
- const combinedParameters = [...parameters];
2199
- if (endpoints.payloadFilterKey) {
2200
- combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
2072
+ if (Object.prototype.hasOwnProperty.call(val, 'toString')) {
2073
+ try {
2074
+ return val.toString();
2075
+ }
2076
+ catch {
2077
+ /* Keep going */
2078
+ }
2201
2079
  }
2202
- return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);
2203
- }
2204
- /**
2205
- * Get the URI for the events endpoint.
2206
- *
2207
- * @param endpoints The service endpoints.
2208
- * @param path The path to the resource, devoid of any query parameters or hrefs.
2209
- * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
2210
- */
2211
- function getEventsUri(endpoints, path, parameters = []) {
2212
- const canonicalizedPath = canonicalizePath(path);
2213
- return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
2214
- }
2215
-
2216
- // These classes are of trivial complexity. If they become
2217
- // more complex, then they could be independent files.
2218
- class LDUnexpectedResponseError extends Error {
2219
- constructor(message) {
2220
- super(message);
2221
- this.name = 'LaunchDarklyUnexpectedResponseError';
2080
+ if (typeof val === 'bigint') {
2081
+ return `${val}n`;
2222
2082
  }
2223
- }
2224
- class LDClientError extends Error {
2225
- constructor(message) {
2226
- super(message);
2227
- this.name = 'LaunchDarklyClientError';
2083
+ try {
2084
+ return JSON.stringify(val);
2228
2085
  }
2229
- }
2230
- class LDTimeoutError extends Error {
2231
- constructor(message) {
2232
- super(message);
2233
- this.name = 'LaunchDarklyTimeoutError';
2086
+ catch (error) {
2087
+ if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {
2088
+ return '[Circular]';
2089
+ }
2090
+ return '[Not Stringifiable]';
2234
2091
  }
2235
2092
  }
2236
- // HTTP statuses in the 4xx range that are still normal failures. Every other
2237
- // 4xx is unexpected.
2238
- const NORMAL_4XX_STATUSES = [400, 408, 429];
2239
2093
  /**
2240
- * Classifies an HTTP status.
2241
- *
2242
- * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
2243
- * and 403, is unexpected. Anything outside the error ranges, including 0 for
2244
- * "no response", is normal.
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.
2245
2098
  */
2246
- function classifyHttpStatus(status) {
2247
- if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
2248
- return 'unexpected';
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';
2249
2104
  }
2250
- return 'normal';
2251
- }
2252
- /**
2253
- * Classifies a transport-level failure (connection refused or dropped, DNS
2254
- * failure, timeout, TLS negotiation failure).
2255
- *
2256
- * Always normal: in an all-HTTPS system every transport error surfaces through
2257
- * the TLS layer, so a certificate misconfiguration cannot be reliably
2258
- * distinguished from a transient network fault, and treating transient faults
2259
- * as unexpected would hold ordinary recoveries to multi-minute waits.
2260
- */
2261
- function classifyTransportFailure() {
2262
- return 'normal';
2105
+ if (typeof val === 'bigint') {
2106
+ return `${val}n`;
2107
+ }
2108
+ return String(Number(val));
2263
2109
  }
2264
2110
  /**
2265
- * Check if the HTTP error is recoverable. This will return false if a request
2266
- * made with any payload could not recover. If the reason for the failure
2267
- * is payload specific, for instance a payload that is too large, then
2268
- * it could recover with a different payload.
2269
- *
2270
- * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
2271
- * retained for the event-delivery pathway and is expected to be deprecated
2272
- * once that pathway migrates to failure classification.
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.
2273
2115
  */
2274
- function isHttpRecoverable(status) {
2275
- return classifyHttpStatus(status) === 'normal';
2116
+ function toInt(val) {
2117
+ if (typeof val === 'symbol') {
2118
+ return 'NaN';
2119
+ }
2120
+ if (typeof val === 'bigint') {
2121
+ return `${val}n`;
2122
+ }
2123
+ return String(parseInt(val, 10));
2276
2124
  }
2277
2125
  /**
2278
- * Returns true if the status could recover for a different payload.
2279
- *
2280
- * When used with event processing this indicates that we should discard
2281
- * the payload, but that a subsequent payload may succeed. Therefore we should
2282
- * not stop event processing.
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.
2283
2130
  */
2284
- function isHttpLocallyRecoverable(status) {
2285
- if (status === 413) {
2286
- return true;
2131
+ function toFloat(val) {
2132
+ if (typeof val === 'symbol') {
2133
+ return 'NaN';
2287
2134
  }
2288
- return isHttpRecoverable(status);
2135
+ return String(parseFloat(val));
2289
2136
  }
2290
-
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
+ };
2291
2152
  /**
2292
- * Returns a promise which errors after t seconds.
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.
2293
2156
  *
2294
- * @param t Timeout in seconds.
2295
- * @param taskName Name of task being timed for logging and error reporting.
2157
+ * @internal
2158
+ *
2159
+ * @param args
2160
+ * @returns Formatted string.
2296
2161
  */
2297
- function cancelableTimedPromise(t, taskName) {
2298
- let timeout;
2299
- let resolve;
2300
- const promise = new Promise((_res, reject) => {
2301
- resolve = _res;
2302
- timeout = setTimeout(() => {
2303
- const e = `${taskName} timed out after ${t} seconds.`;
2304
- reject(new LDTimeoutError(e));
2305
- }, t * 1000);
2306
- });
2307
- return {
2308
- promise,
2309
- cancel: () => {
2310
- resolve();
2311
- clearTimeout(timeout);
2312
- },
2313
- };
2314
- }
2315
-
2316
- function clone(obj) {
2317
- if (obj === undefined || obj === null) {
2318
- return obj;
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;
2319
2207
  }
2320
- return JSON.parse(JSON.stringify(obj));
2321
- }
2322
-
2323
- function secondsToMillis(sec) {
2324
- return Math.trunc(sec * 1000);
2208
+ return args.map(tryStringify).join(' ');
2325
2209
  }
2326
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'];
2327
2220
  /**
2328
- * Wait before calling the same function. Useful for expensive calls.
2329
- * Adapted from https://amitd.co/code/typescript/debounce.
2330
- *
2331
- * @return The debounced function.
2332
- *
2333
- * @example
2334
- *
2335
- * ```js
2336
- * const debouncedFunction = debounce(e => {
2337
- * console.log(e);
2338
- * }, 5000);
2221
+ * A basic logger which handles filtering by level.
2339
2222
  *
2340
- * // Console logs 'Hello world again ' after 5 seconds
2341
- * debouncedFunction('Hello world');
2342
- * debouncedFunction('Hello world again');
2343
- * ```
2344
- * @param fn The function to be debounced.
2345
- * @param delayMs Defaults to 5 seconds.
2346
- */
2347
- const debounce = (fn, delayMs = 5000) => {
2348
- let timer;
2349
- return (...args) => {
2350
- clearTimeout(timer);
2351
- timer = setTimeout(() => {
2352
- fn(...args);
2353
- }, delayMs);
2354
- };
2355
- };
2356
-
2357
- const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
2358
-
2359
- /**
2360
- * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.
2361
- * Sourced from below but modified to include checks for empty object and ignoring keys.
2362
- * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
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`.
2363
2227
  *
2364
- * @param obj
2365
- * @param ignoreKeys
2228
+ * If a formatter is available, then that should be overridden
2229
+ * as well for performance.
2366
2230
  */
2367
- const deepCompact = (obj, ignoreKeys) => {
2368
- if (!obj) {
2369
- return obj;
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({});
2370
2239
  }
2371
- return Object.entries(obj).reduce((acc, [key, value]) => {
2372
- if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {
2373
- acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;
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
+ };
2374
2251
  }
2375
- return acc;
2376
- }, {});
2377
- };
2378
-
2379
- /* eslint-disable */
2380
- // Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual
2381
- // {{? it.es6 }}
2382
- // var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
2383
- // {{?}}
2384
- function fastDeepEqual(a, b) {
2385
- if (a === b)
2386
- return true;
2387
- if (a && b && typeof a == 'object' && typeof b == 'object') {
2388
- if (a.constructor !== b.constructor)
2389
- return false;
2390
- var length, i, keys;
2391
- if (Array.isArray(a)) {
2392
- length = a.length;
2393
- if (length != b.length)
2394
- return false;
2395
- for (i = length; i-- !== 0;)
2396
- if (!fastDeepEqual(a[i], b[i]))
2397
- return false;
2398
- return true;
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
+ };
2399
2260
  }
2400
- // {{? it.es6 }}
2401
- if (a instanceof Map && b instanceof Map) {
2402
- if (a.size !== b.size)
2403
- return false;
2404
- for (i of a.entries())
2405
- if (!b.has(i[0]))
2406
- return false;
2407
- for (i of a.entries())
2408
- if (!fastDeepEqual(i[1], b.get(i[0])))
2409
- return false;
2410
- return true;
2261
+ }
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);
2411
2269
  }
2412
- if (a instanceof Set && b instanceof Set) {
2413
- if (a.size !== b.size)
2414
- return false;
2415
- for (i of a.entries())
2416
- if (!b.has(i[0]))
2417
- return false;
2418
- return true;
2270
+ catch {
2271
+ return format(...args);
2419
2272
  }
2420
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
2421
- // @ts-ignore
2422
- length = a.length;
2423
- // @ts-ignore
2424
- if (length != b.length)
2425
- return false;
2426
- for (i = length; i-- !== 0;) {
2427
- // @ts-ignore
2428
- if (a[i] !== b[i])
2429
- return false;
2273
+ }
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);
2430
2302
  }
2431
- return true;
2432
2303
  }
2433
- // {{?}}
2434
- if (a.constructor === RegExp)
2435
- return a.source === b.source && a.flags === b.flags;
2436
- if (a.valueOf !== Object.prototype.valueOf)
2437
- return a.valueOf() === b.valueOf();
2438
- if (a.toString !== Object.prototype.toString)
2439
- return a.toString() === b.toString();
2440
- keys = Object.keys(a);
2441
- length = keys.length;
2442
- if (length !== Object.keys(b).length)
2443
- return false;
2444
- for (i = length; i-- !== 0;)
2445
- if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
2446
- return false;
2447
- for (i = length; i-- !== 0;) {
2448
- var key = keys[i];
2449
- // {{? it.react }}
2450
- // if (key === '_owner' && a.$$typeof) {
2451
- // // React-specific: avoid traversing React elements' _owner.
2452
- // // _owner contains circular references
2453
- // // and is not needed when comparing the actual elements (and not their owners)
2454
- // continue;
2455
- // }
2456
- // {{?}}
2457
- if (!fastDeepEqual(a[key], b[key]))
2458
- return false;
2304
+ }
2305
+ error(...args) {
2306
+ this._log(LogPriority.error, args);
2307
+ }
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);
2316
+ }
2317
+ }
2318
+
2319
+ const loggerRequirements = {
2320
+ error: TypeValidators.Function,
2321
+ warn: TypeValidators.Function,
2322
+ info: TypeValidators.Function,
2323
+ debug: TypeValidators.Function,
2324
+ };
2325
+ /**
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.
2334
+ */
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);
2459
2362
  }
2460
- return true;
2461
2363
  }
2462
- // true if both NaN, false otherwise
2463
- return a !== a && b !== b;
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);
2375
+ }
2464
2376
  }
2465
2377
 
2466
- function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent', instanceId) {
2467
- const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();
2468
- const headers = {
2469
- [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
2470
- };
2471
- // edge sdks sets this to false because they use the clientSideID
2472
- // and they don't need the authorization header
2473
- if (includeAuthorizationHeader) {
2474
- headers.authorization = sdkKey;
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;
2386
+ };
2387
+
2388
+ /**
2389
+ * Messages for issues which can be encountered from processing the configuration options.
2390
+ */
2391
+ class OptionMessages {
2392
+ static deprecated(oldName, newName) {
2393
+ return `"${oldName}" is deprecated, please use "${newName}"`;
2475
2394
  }
2476
- if (wrapperName) {
2477
- headers['x-launchdarkly-wrapper'] = wrapperVersion
2478
- ? `${wrapperName}/${wrapperVersion}`
2479
- : wrapperName;
2395
+ static optionBelowMinimum(name, value, min) {
2396
+ return `Config option "${name}" had invalid value of ${value}, using minimum of ${min} instead`;
2480
2397
  }
2481
- if (tags?.value) {
2482
- headers['x-launchdarkly-tags'] = tags.value;
2398
+ static unknownOption(name) {
2399
+ return `Ignoring unknown config option "${name}"`;
2483
2400
  }
2484
- // Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
2485
- // per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
2486
- // for generating the GUID once per SDK instance and passing it here, so that it rides on
2487
- // every outbound request via this shared default-headers map. Client/edge SDKs do not pass
2488
- // this value, so the header is omitted for them.
2489
- if (instanceId) {
2490
- headers['x-launchdarkly-instance-id'] = instanceId;
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`;
2491
2415
  }
2492
- return headers;
2493
2416
  }
2494
- function httpErrorMessage(err, context, retryMessage) {
2495
- let desc;
2496
- if (err.status) {
2497
- desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;
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) };
2428
+ }
2429
+ return { valid: true };
2430
+ }
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(' ');
2464
+ }
2498
2465
  }
2499
- else {
2500
- desc = `I/O error (${err.message || 'unknown error'})`;
2466
+ }
2467
+
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
+ };
2501
2482
  }
2502
- const action = retryMessage ?? 'giving up permanently';
2503
- return `Received ${desc} for ${context} - ${action}`;
2504
2483
  }
2505
- function shouldRetry({ status }) {
2506
- return status ? isHttpRecoverable(status) : true;
2484
+
2485
+ function canonicalizeUri(uri) {
2486
+ return uri.replace(/\/+$/, '');
2487
+ }
2488
+ function canonicalizePath(path) {
2489
+ return path.replace(/^\/+/, '').replace(/\?$/, '');
2507
2490
  }
2508
2491
  /**
2509
- * In react-native use base64-js to polyfill btoa. This is safe
2510
- * because the react-native repo uses it too. Set the global.btoa to the encode
2511
- * function of base64-js.
2512
- * https://github.com/beatgammit/base64-js
2513
- * https://github.com/axios/axios/issues/2235#issuecomment-512204616
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;
2503
+ }
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;
2510
+ }
2511
+ const parts = parameters.map(({ key, value }) => `${key}=${value}`);
2512
+ return `${uri}?${parts.join('&')}`;
2513
+ }
2514
+ /**
2515
+ * Get the URI for the streaming endpoint.
2514
2516
  *
2515
- * Ripped from https://thewoods.blog/base64url/
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.
2516
2520
  */
2517
- const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
2518
-
2519
- var noop = () => { };
2520
-
2521
- const sleep = async (delayMillis = 1000) => new Promise((resolve) => {
2522
- setTimeout(resolve, delayMillis);
2523
- });
2524
-
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);
2528
+ }
2525
2529
  /**
2526
- * Returns a promise which errors after t seconds.
2530
+ * Get the URI for the polling endpoint.
2527
2531
  *
2528
- * @param t Timeout in seconds.
2529
- * @param taskName Name of task being timed for logging and error reporting.
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.
2530
2535
  */
2531
- const timedPromise = (t, taskName) => new Promise((_res, reject) => {
2532
- setTimeout(() => {
2533
- const e = `${taskName} timed out after ${t} seconds.`;
2534
- reject(new LDTimeoutError(e));
2535
- }, t * 1000);
2536
- });
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
+ }
2544
+ /**
2545
+ * Get the URI for the events endpoint.
2546
+ *
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.
2550
+ */
2551
+ function getEventsUri(endpoints, path, parameters = []) {
2552
+ const canonicalizedPath = canonicalizePath(path);
2553
+ return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
2554
+ }
2537
2555
 
2538
2556
  class DiagnosticsManager {
2539
2557
  constructor(sdkKey, _platform, _diagnosticInitConfig) {
@@ -3782,6 +3800,7 @@ exports.internal = index;
3782
3800
  exports.isHttpLocallyRecoverable = isHttpLocallyRecoverable;
3783
3801
  exports.isHttpRecoverable = isHttpRecoverable;
3784
3802
  exports.isNullish = isNullish;
3803
+ exports.monotonicNow = monotonicNow;
3785
3804
  exports.noop = noop;
3786
3805
  exports.secondsToMillis = secondsToMillis;
3787
3806
  exports.shouldRetry = shouldRetry;