@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.
- package/CHANGELOG.md +14 -0
- package/dist/cjs/api/platform/Requests.d.ts +85 -0
- package/dist/cjs/api/platform/Requests.d.ts.map +1 -1
- package/dist/cjs/datasource/retry/ResetPolicy.d.ts.map +1 -1
- package/dist/cjs/index.cjs +1074 -924
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/internal/fetch/StreamingResponse.d.ts +83 -0
- package/dist/cjs/internal/fetch/StreamingResponse.d.ts.map +1 -0
- package/dist/cjs/internal/fetch/index.d.ts +3 -0
- package/dist/cjs/internal/fetch/index.d.ts.map +1 -0
- package/dist/cjs/internal/fetch/toRequestInit.d.ts +12 -0
- package/dist/cjs/internal/fetch/toRequestInit.d.ts.map +1 -0
- package/dist/cjs/internal/index.d.ts +1 -0
- package/dist/cjs/internal/index.d.ts.map +1 -1
- package/dist/cjs/utils/index.d.ts +2 -1
- package/dist/cjs/utils/index.d.ts.map +1 -1
- package/dist/cjs/utils/time.d.ts +16 -0
- package/dist/cjs/utils/time.d.ts.map +1 -0
- package/dist/esm/api/platform/Requests.d.ts +85 -0
- package/dist/esm/api/platform/Requests.d.ts.map +1 -1
- package/dist/esm/datasource/retry/ResetPolicy.d.ts.map +1 -1
- package/dist/esm/index.mjs +1074 -925
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/internal/fetch/StreamingResponse.d.ts +83 -0
- package/dist/esm/internal/fetch/StreamingResponse.d.ts.map +1 -0
- package/dist/esm/internal/fetch/index.d.ts +3 -0
- package/dist/esm/internal/fetch/index.d.ts.map +1 -0
- package/dist/esm/internal/fetch/toRequestInit.d.ts +12 -0
- package/dist/esm/internal/fetch/toRequestInit.d.ts.map +1 -0
- package/dist/esm/internal/index.d.ts +1 -0
- package/dist/esm/internal/index.d.ts.map +1 -1
- package/dist/esm/utils/index.d.ts +2 -1
- package/dist/esm/utils/index.d.ts.map +1 -1
- package/dist/esm/utils/time.d.ts +16 -0
- package/dist/esm/utils/time.d.ts.map +1 -0
- package/package.json +1 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1482,1059 +1482,1076 @@ exports.DataSourceErrorKind = void 0;
|
|
|
1482
1482
|
DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
|
|
1483
1483
|
})(exports.DataSourceErrorKind || (exports.DataSourceErrorKind = {}));
|
|
1484
1484
|
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1498
|
-
*
|
|
1499
|
-
*
|
|
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
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
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
|
-
*
|
|
1520
|
-
*
|
|
1522
|
+
* Classifies a transport-level failure (connection refused or dropped, DNS
|
|
1523
|
+
* failure, timeout, TLS negotiation failure).
|
|
1521
1524
|
*
|
|
1522
|
-
*
|
|
1523
|
-
*
|
|
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
|
|
1526
|
-
|
|
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
|
-
*
|
|
1561
|
-
* the
|
|
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
|
|
1564
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1644
|
-
*
|
|
1645
|
-
*
|
|
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
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1668
|
-
*
|
|
1563
|
+
* @param t Timeout in seconds.
|
|
1564
|
+
* @param taskName Name of task being timed for logging and error reporting.
|
|
1669
1565
|
*/
|
|
1670
|
-
function
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
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
|
-
*
|
|
1684
|
-
*
|
|
1685
|
-
*
|
|
1686
|
-
*
|
|
1687
|
-
*
|
|
1688
|
-
*
|
|
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
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
1717
|
-
*
|
|
1718
|
-
*
|
|
1719
|
-
*
|
|
1720
|
-
* @param
|
|
1721
|
-
* @
|
|
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
|
-
|
|
1724
|
-
if (
|
|
1725
|
-
return
|
|
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
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
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
|
-
|
|
1738
|
-
|
|
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
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
//
|
|
1762
|
-
|
|
1763
|
-
|
|
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 (
|
|
1767
|
-
|
|
1745
|
+
if (wrapperName) {
|
|
1746
|
+
headers['x-launchdarkly-wrapper'] = wrapperVersion
|
|
1747
|
+
? `${wrapperName}/${wrapperVersion}`
|
|
1748
|
+
: wrapperName;
|
|
1768
1749
|
}
|
|
1769
|
-
|
|
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
|
-
|
|
1782
|
-
|
|
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
|
|
1761
|
+
return headers;
|
|
1785
1762
|
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
1815
|
-
*
|
|
1816
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1821
|
-
*
|
|
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
|
-
|
|
1824
|
-
|
|
1825
|
-
if (
|
|
1826
|
-
|
|
1827
|
-
|
|
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
|
|
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
|
-
*
|
|
1819
|
+
* Returns a promise which errors after t seconds.
|
|
1883
1820
|
*
|
|
1884
|
-
*
|
|
1885
|
-
*
|
|
1886
|
-
|
|
1887
|
-
|
|
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
|
-
*
|
|
1890
|
-
*
|
|
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
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
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
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
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
|
-
*
|
|
1988
|
-
*
|
|
1989
|
-
*
|
|
1990
|
-
*
|
|
1991
|
-
*
|
|
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
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
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
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
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
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
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
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
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
|
-
|
|
2047
|
-
};
|
|
2048
|
-
|
|
1997
|
+
}
|
|
2049
1998
|
/**
|
|
2050
|
-
*
|
|
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
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
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
|
-
|
|
2120
|
-
|
|
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
|
-
*
|
|
2131
|
-
*
|
|
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
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
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
|
-
|
|
2147
|
-
return
|
|
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
|
-
*
|
|
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
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2173
|
-
return `${uri}?${parts.join('&')}`;
|
|
2123
|
+
return String(parseInt(val, 10));
|
|
2174
2124
|
}
|
|
2175
2125
|
/**
|
|
2176
|
-
*
|
|
2177
|
-
*
|
|
2178
|
-
* @param
|
|
2179
|
-
* @
|
|
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
|
|
2183
|
-
|
|
2184
|
-
|
|
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
|
|
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
|
-
*
|
|
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
|
-
* @
|
|
2194
|
-
*
|
|
2195
|
-
* @param
|
|
2157
|
+
* @internal
|
|
2158
|
+
*
|
|
2159
|
+
* @param args
|
|
2160
|
+
* @returns Formatted string.
|
|
2196
2161
|
*/
|
|
2197
|
-
function
|
|
2198
|
-
const
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
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
|
|
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
|
-
*
|
|
2221
|
+
* A basic logger which handles filtering by level.
|
|
2207
2222
|
*
|
|
2208
|
-
*
|
|
2209
|
-
*
|
|
2210
|
-
*
|
|
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
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
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
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
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
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
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
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
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
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
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
|
-
*
|
|
2294
|
-
*
|
|
2295
|
-
*
|
|
2296
|
-
*
|
|
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
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
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
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
2369
|
-
|
|
2370
|
-
return
|
|
2391
|
+
class OptionMessages {
|
|
2392
|
+
static deprecated(oldName, newName) {
|
|
2393
|
+
return `"${oldName}" is deprecated, please use "${newName}"`;
|
|
2371
2394
|
}
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
return
|
|
2377
|
-
}
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
if (
|
|
2403
|
-
if (
|
|
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
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
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
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
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
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
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
|
-
|
|
2501
|
-
|
|
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
|
|
2504
|
-
return
|
|
2511
|
+
const parts = parameters.map(({ key, value }) => `${key}=${value}`);
|
|
2512
|
+
return `${uri}?${parts.join('&')}`;
|
|
2505
2513
|
}
|
|
2506
|
-
|
|
2507
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
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
|
-
*
|
|
2545
|
+
* Get the URI for the events endpoint.
|
|
2528
2546
|
*
|
|
2529
|
-
* @param
|
|
2530
|
-
* @param
|
|
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
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
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;
|