@xemahq/managed-fetch 0.1.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/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @xemahq/managed-fetch
2
+
3
+ This package belongs to **Layer 1** — a framework-agnostic HTTP SDK with **zero
4
+ runtime dependencies**. It is the managed outbound-fetch / polite-crawl client
5
+ that any ingestion, monitor, or scraper calls instead of bare `fetch`. It is
6
+ fully generic: it knows nothing about any Xema domain concept.
7
+
8
+ ## What it is
9
+
10
+ `ManagedFetch` wraps the platform `fetch` with the machinery a well-behaved
11
+ outbound caller needs:
12
+
13
+ - **Per-host rate limiting** — a reservation token bucket per hostname
14
+ (`requestsPerSecond` + `burst`), with a global default and per-host overrides.
15
+ - **Retry with backoff** — exponential backoff + full jitter on retryable
16
+ statuses (`429`/`502`/`503`/`504`) and network/timeout errors, honoring
17
+ `Retry-After` (capped), bounded by `maxRetries`. No infinite loops.
18
+ - **Per-host circuit breaker** — opens after N consecutive call failures, stays
19
+ open for a cooldown, then half-open probes before closing. States are the
20
+ closed enum `CircuitState = CLOSED | OPEN | HALF_OPEN`. Fails fast when OPEN.
21
+ - **Conditional requests** — pass prior `{ etag, lastModified }` and the client
22
+ sends `If-None-Match` / `If-Modified-Since`; a `304 Not Modified` is a
23
+ first-class success (`result.notModified === true`) for cheap change
24
+ detection.
25
+ - **User-Agent policy** — a configurable, honest, identifiable UA (client-wide
26
+ or per-request). No anti-bot evasion beyond setting the header.
27
+ - **Per-request timeouts** — via `AbortController`, with a sane default.
28
+ - **Health probe** — `probe(url)` → `{ healthy, status?, latencyMs }`.
29
+
30
+ ## Usage
31
+
32
+ ```ts
33
+ import { ManagedFetch } from '@xemahq/managed-fetch';
34
+
35
+ const client = new ManagedFetch({
36
+ userAgent: 'AcmeCrawler/2.0 (+https://acme.example)',
37
+ rateLimit: { requestsPerSecond: 1, burst: 3 },
38
+ perHostRateLimit: { 'api.example.com': { requestsPerSecond: 5, burst: 10 } },
39
+ retry: { maxRetries: 4, baseDelayMs: 250, maxDelayMs: 15_000 },
40
+ circuitBreaker: { failureThreshold: 5, cooldownMs: 30_000 },
41
+ });
42
+
43
+ const res = await client.fetch('https://example.com/feed.json', {
44
+ conditional: { etag: previousEtag },
45
+ });
46
+
47
+ if (res.notModified) {
48
+ // nothing changed — reuse the cached copy
49
+ } else {
50
+ const body = await res.json();
51
+ saveEtag(res.etag);
52
+ }
53
+ ```
54
+
55
+ Terminal conditions throw typed errors — never a silent degraded result:
56
+ `CircuitOpenError`, `RateLimitError`, `RequestTimeoutError`,
57
+ `RetriesExhaustedError` (all extend `ManagedFetchError`, each carrying a closed
58
+ `ManagedFetchErrorCode`).
59
+
60
+ ## Invariants
61
+
62
+ - **State is per-instance / in-memory.** The token bucket and circuit breaker
63
+ coordinate a single process only. Across horizontally-scaled pods each pod
64
+ keeps its own state — the effective global rate is `pods × requestsPerSecond`
65
+ and each pod trips its own breaker. This is intentional; a shared cross-pod
66
+ budget must be enforced at a shared upstream, not here.
67
+ - **Fail-fast, no silent fallbacks.** Every terminal failure throws a typed
68
+ error. A malformed URL, an unset transport, or an exceeded rate cap all fail
69
+ immediately.
70
+ - **Deterministic timing.** Backoff, rate-limit waits, and circuit timing run
71
+ off an injectable clock (`now` / `sleep` / `random`), so behavior is
72
+ reproducible and testable with no real sleeping. Timers are used only for the
73
+ network request timeout — never to drive control flow between retries.
@@ -0,0 +1,7 @@
1
+ export { ManagedFetch, createManagedFetch } from './lib/managed-fetch';
2
+ export { CircuitState } from './lib/circuit-breaker';
3
+ export { ManagedFetchError, ManagedFetchErrorCode, CircuitOpenError, RateLimitError, RequestTimeoutError, RetriesExhaustedError, } from './lib/errors';
4
+ export { computeBackoffMs, parseRetryAfterMs, resolveRetryDelayMs, } from './lib/backoff';
5
+ export { DEFAULT_USER_AGENT, DEFAULT_TIMEOUT_MS, DEFAULT_RATE_LIMIT, DEFAULT_RETRYABLE_STATUSES, DEFAULT_RETRY, DEFAULT_CIRCUIT_BREAKER, } from './lib/defaults';
6
+ export type { FetchImpl, ManagedFetchClock, ManagedFetchConfig, ManagedFetchRequest, ManagedFetchResult, ConditionalTokens, ProbeResult, RateLimitConfig, RetryConfig, CircuitBreakerConfig, } from './lib/types';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEvE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,0BAA0B,EAC1B,aAAa,EACb,uBAAuB,GACxB,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACV,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,WAAW,EACX,oBAAoB,GACrB,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CIRCUIT_BREAKER = exports.DEFAULT_RETRY = exports.DEFAULT_RETRYABLE_STATUSES = exports.DEFAULT_RATE_LIMIT = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_USER_AGENT = exports.resolveRetryDelayMs = exports.parseRetryAfterMs = exports.computeBackoffMs = exports.RetriesExhaustedError = exports.RequestTimeoutError = exports.RateLimitError = exports.CircuitOpenError = exports.ManagedFetchErrorCode = exports.ManagedFetchError = exports.CircuitState = exports.createManagedFetch = exports.ManagedFetch = void 0;
4
+ var managed_fetch_1 = require("./lib/managed-fetch");
5
+ Object.defineProperty(exports, "ManagedFetch", { enumerable: true, get: function () { return managed_fetch_1.ManagedFetch; } });
6
+ Object.defineProperty(exports, "createManagedFetch", { enumerable: true, get: function () { return managed_fetch_1.createManagedFetch; } });
7
+ var circuit_breaker_1 = require("./lib/circuit-breaker");
8
+ Object.defineProperty(exports, "CircuitState", { enumerable: true, get: function () { return circuit_breaker_1.CircuitState; } });
9
+ var errors_1 = require("./lib/errors");
10
+ Object.defineProperty(exports, "ManagedFetchError", { enumerable: true, get: function () { return errors_1.ManagedFetchError; } });
11
+ Object.defineProperty(exports, "ManagedFetchErrorCode", { enumerable: true, get: function () { return errors_1.ManagedFetchErrorCode; } });
12
+ Object.defineProperty(exports, "CircuitOpenError", { enumerable: true, get: function () { return errors_1.CircuitOpenError; } });
13
+ Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_1.RateLimitError; } });
14
+ Object.defineProperty(exports, "RequestTimeoutError", { enumerable: true, get: function () { return errors_1.RequestTimeoutError; } });
15
+ Object.defineProperty(exports, "RetriesExhaustedError", { enumerable: true, get: function () { return errors_1.RetriesExhaustedError; } });
16
+ var backoff_1 = require("./lib/backoff");
17
+ Object.defineProperty(exports, "computeBackoffMs", { enumerable: true, get: function () { return backoff_1.computeBackoffMs; } });
18
+ Object.defineProperty(exports, "parseRetryAfterMs", { enumerable: true, get: function () { return backoff_1.parseRetryAfterMs; } });
19
+ Object.defineProperty(exports, "resolveRetryDelayMs", { enumerable: true, get: function () { return backoff_1.resolveRetryDelayMs; } });
20
+ var defaults_1 = require("./lib/defaults");
21
+ Object.defineProperty(exports, "DEFAULT_USER_AGENT", { enumerable: true, get: function () { return defaults_1.DEFAULT_USER_AGENT; } });
22
+ Object.defineProperty(exports, "DEFAULT_TIMEOUT_MS", { enumerable: true, get: function () { return defaults_1.DEFAULT_TIMEOUT_MS; } });
23
+ Object.defineProperty(exports, "DEFAULT_RATE_LIMIT", { enumerable: true, get: function () { return defaults_1.DEFAULT_RATE_LIMIT; } });
24
+ Object.defineProperty(exports, "DEFAULT_RETRYABLE_STATUSES", { enumerable: true, get: function () { return defaults_1.DEFAULT_RETRYABLE_STATUSES; } });
25
+ Object.defineProperty(exports, "DEFAULT_RETRY", { enumerable: true, get: function () { return defaults_1.DEFAULT_RETRY; } });
26
+ Object.defineProperty(exports, "DEFAULT_CIRCUIT_BREAKER", { enumerable: true, get: function () { return defaults_1.DEFAULT_CIRCUIT_BREAKER; } });
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAUA,qDAAuE;AAA9D,6GAAA,YAAY,OAAA;AAAE,mHAAA,kBAAkB,OAAA;AAEzC,yDAAqD;AAA5C,+GAAA,YAAY,OAAA;AAErB,uCAOsB;AANpB,2GAAA,iBAAiB,OAAA;AACjB,+GAAA,qBAAqB,OAAA;AACrB,0GAAA,gBAAgB,OAAA;AAChB,wGAAA,cAAc,OAAA;AACd,6GAAA,mBAAmB,OAAA;AACnB,+GAAA,qBAAqB,OAAA;AAGvB,yCAIuB;AAHrB,2GAAA,gBAAgB,OAAA;AAChB,4GAAA,iBAAiB,OAAA;AACjB,8GAAA,mBAAmB,OAAA;AAGrB,2CAOwB;AANtB,8GAAA,kBAAkB,OAAA;AAClB,8GAAA,kBAAkB,OAAA;AAClB,8GAAA,kBAAkB,OAAA;AAClB,sHAAA,0BAA0B,OAAA;AAC1B,yGAAA,aAAa,OAAA;AACb,mHAAA,uBAAuB,OAAA"}
@@ -0,0 +1,12 @@
1
+ export declare function parseRetryAfterMs(headerValue: string | null | undefined, nowEpochMs: number): number | undefined;
2
+ export declare function computeBackoffMs(attempt: number, baseDelayMs: number, maxDelayMs: number, random: () => number): number;
3
+ export declare function resolveRetryDelayMs(params: {
4
+ attempt: number;
5
+ baseDelayMs: number;
6
+ maxDelayMs: number;
7
+ random: () => number;
8
+ respectRetryAfter: boolean;
9
+ retryAfterHeader: string | null | undefined;
10
+ nowEpochMs: number;
11
+ }): number;
12
+ //# sourceMappingURL=backoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.d.ts","sourceRoot":"","sources":["../../src/lib/backoff.ts"],"names":[],"mappings":"AAgBA,wBAAgB,iBAAiB,CAC/B,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACtC,UAAU,EAAE,MAAM,GACjB,MAAM,GAAG,SAAS,CAiBpB;AASD,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,MAAM,GACnB,MAAM,CAIR;AAOD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE;IAC1C,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,MAAM,CAAC;IACrB,iBAAiB,EAAE,OAAO,CAAC;IAC3B,gBAAgB,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAC5C,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,MAAM,CAQT"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseRetryAfterMs = parseRetryAfterMs;
4
+ exports.computeBackoffMs = computeBackoffMs;
5
+ exports.resolveRetryDelayMs = resolveRetryDelayMs;
6
+ function parseRetryAfterMs(headerValue, nowEpochMs) {
7
+ if (headerValue === null || headerValue === undefined) {
8
+ return undefined;
9
+ }
10
+ const trimmed = headerValue.trim();
11
+ if (trimmed === '') {
12
+ return undefined;
13
+ }
14
+ if (/^\d+$/.test(trimmed)) {
15
+ return Number(trimmed) * 1000;
16
+ }
17
+ const dateMs = Date.parse(trimmed);
18
+ if (!Number.isNaN(dateMs)) {
19
+ const delta = dateMs - nowEpochMs;
20
+ return delta > 0 ? delta : 0;
21
+ }
22
+ return undefined;
23
+ }
24
+ function computeBackoffMs(attempt, baseDelayMs, maxDelayMs, random) {
25
+ const exponential = baseDelayMs * 2 ** attempt;
26
+ const ceiling = Math.min(maxDelayMs, exponential);
27
+ return Math.floor(random() * ceiling);
28
+ }
29
+ function resolveRetryDelayMs(params) {
30
+ if (params.respectRetryAfter) {
31
+ const retryAfter = parseRetryAfterMs(params.retryAfterHeader, params.nowEpochMs);
32
+ if (retryAfter !== undefined) {
33
+ return Math.min(params.maxDelayMs, retryAfter);
34
+ }
35
+ }
36
+ return computeBackoffMs(params.attempt, params.baseDelayMs, params.maxDelayMs, params.random);
37
+ }
38
+ //# sourceMappingURL=backoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.js","sourceRoot":"","sources":["../../src/lib/backoff.ts"],"names":[],"mappings":";;AAgBA,8CAoBC;AASD,4CASC;AAOD,kDAgBC;AA7DD,SAAgB,iBAAiB,CAC/B,WAAsC,EACtC,UAAkB;IAElB,IAAI,WAAW,KAAK,IAAI,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QACtD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC;IACnC,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QACnB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1B,OAAO,MAAM,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAChC,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,MAAM,KAAK,GAAG,MAAM,GAAG,UAAU,CAAC;QAClC,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AASD,SAAgB,gBAAgB,CAC9B,OAAe,EACf,WAAmB,EACnB,UAAkB,EAClB,MAAoB;IAEpB,MAAM,WAAW,GAAG,WAAW,GAAG,CAAC,IAAI,OAAO,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC;AACxC,CAAC;AAOD,SAAgB,mBAAmB,CAAC,MAQnC;IACC,IAAI,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC7B,MAAM,UAAU,GAAG,iBAAiB,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;QACjF,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;IACD,OAAO,gBAAgB,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;AAChG,CAAC"}
@@ -0,0 +1,29 @@
1
+ export declare enum CircuitState {
2
+ CLOSED = "CLOSED",
3
+ OPEN = "OPEN",
4
+ HALF_OPEN = "HALF_OPEN"
5
+ }
6
+ export interface CircuitBreakerOptions {
7
+ failureThreshold: number;
8
+ cooldownMs: number;
9
+ halfOpenMaxProbes: number;
10
+ now: () => number;
11
+ }
12
+ export interface CircuitAcquire {
13
+ allowed: boolean;
14
+ cooldownRemainingMs: number;
15
+ }
16
+ export declare class CircuitBreaker {
17
+ private readonly opts;
18
+ private state;
19
+ private consecutiveFailures;
20
+ private openedAt;
21
+ private halfOpenProbes;
22
+ constructor(opts: CircuitBreakerOptions);
23
+ tryAcquire(): CircuitAcquire;
24
+ recordSuccess(): void;
25
+ recordFailure(): void;
26
+ get current(): CircuitState;
27
+ private open;
28
+ }
29
+ //# sourceMappingURL=circuit-breaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.d.ts","sourceRoot":"","sources":["../../src/lib/circuit-breaker.ts"],"names":[],"mappings":"AAgBA,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;IACb,SAAS,cAAc;CACxB;AAED,MAAM,WAAW,qBAAqB;IACpC,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,GAAG,EAAE,MAAM,MAAM,CAAC;CACnB;AAGD,MAAM,WAAW,cAAc;IAE7B,OAAO,EAAE,OAAO,CAAC;IAEjB,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAED,qBAAa,cAAc;IAMb,OAAO,CAAC,QAAQ,CAAC,IAAI;IALjC,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,mBAAmB,CAAK;IAChC,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,cAAc,CAAK;gBAEE,IAAI,EAAE,qBAAqB;IAcxD,UAAU,IAAI,cAAc;IAyB5B,aAAa,IAAI,IAAI;IAOrB,aAAa,IAAI,IAAI;IAiBrB,IAAI,OAAO,IAAI,YAAY,CAE1B;IAED,OAAO,CAAC,IAAI;CAKb"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CircuitBreaker = exports.CircuitState = void 0;
4
+ var CircuitState;
5
+ (function (CircuitState) {
6
+ CircuitState["CLOSED"] = "CLOSED";
7
+ CircuitState["OPEN"] = "OPEN";
8
+ CircuitState["HALF_OPEN"] = "HALF_OPEN";
9
+ })(CircuitState || (exports.CircuitState = CircuitState = {}));
10
+ class CircuitBreaker {
11
+ opts;
12
+ state = CircuitState.CLOSED;
13
+ consecutiveFailures = 0;
14
+ openedAt = 0;
15
+ halfOpenProbes = 0;
16
+ constructor(opts) {
17
+ this.opts = opts;
18
+ if (opts.failureThreshold <= 0) {
19
+ throw new RangeError('failureThreshold must be > 0');
20
+ }
21
+ if (opts.halfOpenMaxProbes <= 0) {
22
+ throw new RangeError('halfOpenMaxProbes must be > 0');
23
+ }
24
+ }
25
+ tryAcquire() {
26
+ const now = this.opts.now();
27
+ if (this.state === CircuitState.OPEN) {
28
+ const elapsed = now - this.openedAt;
29
+ if (elapsed >= this.opts.cooldownMs) {
30
+ this.state = CircuitState.HALF_OPEN;
31
+ this.halfOpenProbes = 0;
32
+ }
33
+ else {
34
+ return { allowed: false, cooldownRemainingMs: this.opts.cooldownMs - elapsed };
35
+ }
36
+ }
37
+ if (this.state === CircuitState.HALF_OPEN) {
38
+ if (this.halfOpenProbes >= this.opts.halfOpenMaxProbes) {
39
+ return { allowed: false, cooldownRemainingMs: 0 };
40
+ }
41
+ this.halfOpenProbes += 1;
42
+ return { allowed: true, cooldownRemainingMs: 0 };
43
+ }
44
+ return { allowed: true, cooldownRemainingMs: 0 };
45
+ }
46
+ recordSuccess() {
47
+ this.consecutiveFailures = 0;
48
+ this.halfOpenProbes = 0;
49
+ this.state = CircuitState.CLOSED;
50
+ }
51
+ recordFailure() {
52
+ this.consecutiveFailures += 1;
53
+ if (this.state === CircuitState.HALF_OPEN) {
54
+ this.open();
55
+ return;
56
+ }
57
+ if (this.consecutiveFailures >= this.opts.failureThreshold) {
58
+ this.open();
59
+ }
60
+ }
61
+ get current() {
62
+ return this.state;
63
+ }
64
+ open() {
65
+ this.state = CircuitState.OPEN;
66
+ this.openedAt = this.opts.now();
67
+ this.halfOpenProbes = 0;
68
+ }
69
+ }
70
+ exports.CircuitBreaker = CircuitBreaker;
71
+ //# sourceMappingURL=circuit-breaker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.js","sourceRoot":"","sources":["../../src/lib/circuit-breaker.ts"],"names":[],"mappings":";;;AAgBA,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,iCAAiB,CAAA;IACjB,6BAAa,CAAA;IACb,uCAAuB,CAAA;AACzB,CAAC,EAJW,YAAY,4BAAZ,YAAY,QAIvB;AAiBD,MAAa,cAAc;IAMI;IALrB,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC;IAC5B,mBAAmB,GAAG,CAAC,CAAC;IACxB,QAAQ,GAAG,CAAC,CAAC;IACb,cAAc,GAAG,CAAC,CAAC;IAE3B,YAA6B,IAA2B;QAA3B,SAAI,GAAJ,IAA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AAC;IAGD,aAAa;QACX,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC;IACnC,CAAC;IAGD,aAAa;QACX,IAAI,CAAC,mBAAmB,IAAI,CAAC,CAAC;QAC9B,IAAI,IAAI,CAAC,KAAK,KAAK,YAAY,CAAC,SAAS,EAAE,CAAC;YAC1C,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO;QACT,CAAC;QACD,IAAI,IAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC3D,IAAI,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACH,CAAC;IAQD,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAEO,IAAI;QACV,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAChC,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF;AA9ED,wCA8EC"}
@@ -0,0 +1,3 @@
1
+ import type { ManagedFetchClock } from './types';
2
+ export declare const defaultClock: ManagedFetchClock;
3
+ //# sourceMappingURL=clock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.d.ts","sourceRoot":"","sources":["../../src/lib/clock.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAyBjD,eAAO,MAAM,YAAY,EAAE,iBAI1B,CAAC"}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultClock = void 0;
4
+ function realSleep(ms, signal) {
5
+ return new Promise((resolve, reject) => {
6
+ if (signal?.aborted) {
7
+ reject(signal.reason);
8
+ return;
9
+ }
10
+ if (ms <= 0) {
11
+ resolve();
12
+ return;
13
+ }
14
+ const onAbort = () => {
15
+ clearTimeout(timer);
16
+ reject(signal?.reason);
17
+ };
18
+ const timer = setTimeout(() => {
19
+ signal?.removeEventListener('abort', onAbort);
20
+ resolve();
21
+ }, ms);
22
+ signal?.addEventListener('abort', onAbort, { once: true });
23
+ });
24
+ }
25
+ exports.defaultClock = {
26
+ now: () => Date.now(),
27
+ sleep: realSleep,
28
+ random: () => Math.random(),
29
+ };
30
+ //# sourceMappingURL=clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.js","sourceRoot":"","sources":["../../src/lib/clock.ts"],"names":[],"mappings":";;;AAQA,SAAS,SAAS,CAAC,EAAU,EAAE,MAAoB;IACjD,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC3C,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACtB,OAAO;QACT,CAAC;QACD,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;YACV,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,GAAS,EAAE;YACzB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACzB,CAAC,CAAC;QACF,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC;AAEY,QAAA,YAAY,GAAsB;IAC7C,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;IACrB,KAAK,EAAE,SAAS;IAChB,MAAM,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE;CAC5B,CAAC"}
@@ -0,0 +1,8 @@
1
+ import type { CircuitBreakerConfig, RateLimitConfig, RetryConfig } from './types';
2
+ export declare const DEFAULT_USER_AGENT = "XemaManagedFetch/1.0 (+https://xema.dev)";
3
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
4
+ export declare const DEFAULT_RATE_LIMIT: Required<RateLimitConfig>;
5
+ export declare const DEFAULT_RETRYABLE_STATUSES: readonly number[];
6
+ export declare const DEFAULT_RETRY: Required<RetryConfig>;
7
+ export declare const DEFAULT_CIRCUIT_BREAKER: Required<CircuitBreakerConfig>;
8
+ //# sourceMappingURL=defaults.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/lib/defaults.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAMlF,eAAO,MAAM,kBAAkB,6CAA6C,CAAC;AAE7E,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,eAAe,CAIxD,CAAC;AAGF,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAAyB,CAAC;AAElF,eAAO,MAAM,aAAa,EAAE,QAAQ,CAAC,WAAW,CAM/C,CAAC;AAEF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,oBAAoB,CAIlE,CAAC"}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CIRCUIT_BREAKER = exports.DEFAULT_RETRY = exports.DEFAULT_RETRYABLE_STATUSES = exports.DEFAULT_RATE_LIMIT = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_USER_AGENT = void 0;
4
+ exports.DEFAULT_USER_AGENT = 'XemaManagedFetch/1.0 (+https://xema.dev)';
5
+ exports.DEFAULT_TIMEOUT_MS = 30_000;
6
+ exports.DEFAULT_RATE_LIMIT = {
7
+ requestsPerSecond: 2,
8
+ burst: 4,
9
+ maxQueueMs: 30_000,
10
+ };
11
+ exports.DEFAULT_RETRYABLE_STATUSES = [429, 502, 503, 504];
12
+ exports.DEFAULT_RETRY = {
13
+ maxRetries: 3,
14
+ baseDelayMs: 200,
15
+ maxDelayMs: 10_000,
16
+ retryableStatuses: exports.DEFAULT_RETRYABLE_STATUSES,
17
+ respectRetryAfter: true,
18
+ };
19
+ exports.DEFAULT_CIRCUIT_BREAKER = {
20
+ failureThreshold: 5,
21
+ cooldownMs: 30_000,
22
+ halfOpenMaxProbes: 1,
23
+ };
24
+ //# sourceMappingURL=defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../src/lib/defaults.ts"],"names":[],"mappings":";;;AAUa,QAAA,kBAAkB,GAAG,0CAA0C,CAAC;AAEhE,QAAA,kBAAkB,GAAG,MAAM,CAAC;AAE5B,QAAA,kBAAkB,GAA8B;IAC3D,iBAAiB,EAAE,CAAC;IACpB,KAAK,EAAE,CAAC;IACR,UAAU,EAAE,MAAM;CACnB,CAAC;AAGW,QAAA,0BAA0B,GAAsB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAErE,QAAA,aAAa,GAA0B;IAClD,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,GAAG;IAChB,UAAU,EAAE,MAAM;IAClB,iBAAiB,EAAE,kCAA0B;IAC7C,iBAAiB,EAAE,IAAI;CACxB,CAAC;AAEW,QAAA,uBAAuB,GAAmC;IACrE,gBAAgB,EAAE,CAAC;IACnB,UAAU,EAAE,MAAM;IAClB,iBAAiB,EAAE,CAAC;CACrB,CAAC"}
@@ -0,0 +1,37 @@
1
+ export declare enum ManagedFetchErrorCode {
2
+ CIRCUIT_OPEN = "CIRCUIT_OPEN",
3
+ RATE_LIMITED = "RATE_LIMITED",
4
+ TIMEOUT = "TIMEOUT",
5
+ RETRIES_EXHAUSTED = "RETRIES_EXHAUSTED"
6
+ }
7
+ export declare abstract class ManagedFetchError extends Error {
8
+ abstract readonly code: ManagedFetchErrorCode;
9
+ readonly host: string;
10
+ constructor(message: string, host: string, options?: ErrorOptions);
11
+ }
12
+ export declare class CircuitOpenError extends ManagedFetchError {
13
+ readonly code = ManagedFetchErrorCode.CIRCUIT_OPEN;
14
+ readonly cooldownRemainingMs: number;
15
+ constructor(host: string, cooldownRemainingMs: number);
16
+ }
17
+ export declare class RateLimitError extends ManagedFetchError {
18
+ readonly code = ManagedFetchErrorCode.RATE_LIMITED;
19
+ readonly requiredWaitMs: number;
20
+ readonly maxQueueMs: number;
21
+ constructor(host: string, requiredWaitMs: number, maxQueueMs: number);
22
+ }
23
+ export declare class RequestTimeoutError extends ManagedFetchError {
24
+ readonly code = ManagedFetchErrorCode.TIMEOUT;
25
+ readonly timeoutMs: number;
26
+ constructor(host: string, timeoutMs: number);
27
+ }
28
+ export declare class RetriesExhaustedError extends ManagedFetchError {
29
+ readonly code = ManagedFetchErrorCode.RETRIES_EXHAUSTED;
30
+ readonly attempts: number;
31
+ readonly lastStatus: number | undefined;
32
+ constructor(host: string, attempts: number, options: {
33
+ cause?: unknown;
34
+ lastStatus?: number;
35
+ });
36
+ }
37
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/lib/errors.ts"],"names":[],"mappings":"AAUA,oBAAY,qBAAqB;IAE/B,YAAY,iBAAiB;IAE7B,YAAY,iBAAiB;IAE7B,OAAO,YAAY;IAEnB,iBAAiB,sBAAsB;CACxC;AAGD,8BAAsB,iBAAkB,SAAQ,KAAK;IACnD,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,qBAAqB,CAAC;IAG9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;gBAEV,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAMlE;AAGD,qBAAa,gBAAiB,SAAQ,iBAAiB;IACrD,QAAQ,CAAC,IAAI,sCAAsC;IAGnD,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;gBAEzB,IAAI,EAAE,MAAM,EAAE,mBAAmB,EAAE,MAAM;CAOtD;AAOD,qBAAa,cAAe,SAAQ,iBAAiB;IACnD,QAAQ,CAAC,IAAI,sCAAsC;IAGnD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAGhC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM;CAQrE;AAGD,qBAAa,mBAAoB,SAAQ,iBAAiB;IACxD,QAAQ,CAAC,IAAI,iCAAiC;IAG9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;gBAEf,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAI5C;AAGD,qBAAa,qBAAsB,SAAQ,iBAAiB;IAC1D,QAAQ,CAAC,IAAI,2CAA2C;IAGxD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAG1B,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;gBAGtC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE;CAWpD"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RetriesExhaustedError = exports.RequestTimeoutError = exports.RateLimitError = exports.CircuitOpenError = exports.ManagedFetchError = exports.ManagedFetchErrorCode = void 0;
4
+ var ManagedFetchErrorCode;
5
+ (function (ManagedFetchErrorCode) {
6
+ ManagedFetchErrorCode["CIRCUIT_OPEN"] = "CIRCUIT_OPEN";
7
+ ManagedFetchErrorCode["RATE_LIMITED"] = "RATE_LIMITED";
8
+ ManagedFetchErrorCode["TIMEOUT"] = "TIMEOUT";
9
+ ManagedFetchErrorCode["RETRIES_EXHAUSTED"] = "RETRIES_EXHAUSTED";
10
+ })(ManagedFetchErrorCode || (exports.ManagedFetchErrorCode = ManagedFetchErrorCode = {}));
11
+ class ManagedFetchError extends Error {
12
+ host;
13
+ constructor(message, host, options) {
14
+ super(message, options);
15
+ this.name = new.target.name;
16
+ this.host = host;
17
+ }
18
+ }
19
+ exports.ManagedFetchError = ManagedFetchError;
20
+ class CircuitOpenError extends ManagedFetchError {
21
+ code = ManagedFetchErrorCode.CIRCUIT_OPEN;
22
+ cooldownRemainingMs;
23
+ constructor(host, cooldownRemainingMs) {
24
+ super(`Circuit breaker is OPEN for host "${host}"; ${cooldownRemainingMs}ms until half-open probe`, host);
25
+ this.cooldownRemainingMs = cooldownRemainingMs;
26
+ }
27
+ }
28
+ exports.CircuitOpenError = CircuitOpenError;
29
+ class RateLimitError extends ManagedFetchError {
30
+ code = ManagedFetchErrorCode.RATE_LIMITED;
31
+ requiredWaitMs;
32
+ maxQueueMs;
33
+ constructor(host, requiredWaitMs, maxQueueMs) {
34
+ super(`Rate limit for host "${host}" would require waiting ${requiredWaitMs}ms (> maxQueueMs ${maxQueueMs}ms)`, host);
35
+ this.requiredWaitMs = requiredWaitMs;
36
+ this.maxQueueMs = maxQueueMs;
37
+ }
38
+ }
39
+ exports.RateLimitError = RateLimitError;
40
+ class RequestTimeoutError extends ManagedFetchError {
41
+ code = ManagedFetchErrorCode.TIMEOUT;
42
+ timeoutMs;
43
+ constructor(host, timeoutMs) {
44
+ super(`Request to host "${host}" timed out after ${timeoutMs}ms`, host);
45
+ this.timeoutMs = timeoutMs;
46
+ }
47
+ }
48
+ exports.RequestTimeoutError = RequestTimeoutError;
49
+ class RetriesExhaustedError extends ManagedFetchError {
50
+ code = ManagedFetchErrorCode.RETRIES_EXHAUSTED;
51
+ attempts;
52
+ lastStatus;
53
+ constructor(host, attempts, options) {
54
+ super(`Exhausted ${attempts} attempt(s) for host "${host}"` +
55
+ (options.lastStatus !== undefined ? ` (last status ${options.lastStatus})` : ''), host, options.cause !== undefined ? { cause: options.cause } : undefined);
56
+ this.attempts = attempts;
57
+ this.lastStatus = options.lastStatus;
58
+ }
59
+ }
60
+ exports.RetriesExhaustedError = RetriesExhaustedError;
61
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/lib/errors.ts"],"names":[],"mappings":";;;AAUA,IAAY,qBASX;AATD,WAAY,qBAAqB;IAE/B,sDAA6B,CAAA;IAE7B,sDAA6B,CAAA;IAE7B,4CAAmB,CAAA;IAEnB,gEAAuC,CAAA;AACzC,CAAC,EATW,qBAAqB,qCAArB,qBAAqB,QAShC;AAGD,MAAsB,iBAAkB,SAAQ,KAAK;IAI1C,IAAI,CAAS;IAEtB,YAAY,OAAe,EAAE,IAAY,EAAE,OAAsB;QAC/D,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAExB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAZD,8CAYC;AAGD,MAAa,gBAAiB,SAAQ,iBAAiB;IAC5C,IAAI,GAAG,qBAAqB,CAAC,YAAY,CAAC;IAG1C,mBAAmB,CAAS;IAErC,YAAY,IAAY,EAAE,mBAA2B;QACnD,KAAK,CACH,qCAAqC,IAAI,MAAM,mBAAmB,0BAA0B,EAC5F,IAAI,CACL,CAAC;QACF,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IACjD,CAAC;CACF;AAbD,4CAaC;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AAC;IACvC,CAAC;CACF;AAvBD,sDAuBC"}
@@ -0,0 +1,28 @@
1
+ import { CircuitState } from './circuit-breaker';
2
+ import type { ManagedFetchConfig, ManagedFetchRequest, ManagedFetchResult, ProbeResult } from './types';
3
+ export declare class ManagedFetch {
4
+ private readonly userAgent;
5
+ private readonly rateLimit;
6
+ private readonly perHostRateLimit;
7
+ private readonly retry;
8
+ private readonly circuitBreaker;
9
+ private readonly timeoutMs;
10
+ private readonly fetchImpl;
11
+ private readonly clock;
12
+ private readonly hosts;
13
+ constructor(config?: ManagedFetchConfig);
14
+ fetch(url: string, request?: ManagedFetchRequest): Promise<ManagedFetchResult>;
15
+ probe(url: string, request?: ManagedFetchRequest): Promise<ProbeResult>;
16
+ getCircuitState(host: string): CircuitState;
17
+ private applyRateLimit;
18
+ private executeWithRetries;
19
+ private backoff;
20
+ private executeOnce;
21
+ private buildHeaders;
22
+ private buildResult;
23
+ private isRetryableStatus;
24
+ private hostOf;
25
+ private hostState;
26
+ }
27
+ export declare function createManagedFetch(config?: ManagedFetchConfig): ManagedFetch;
28
+ //# sourceMappingURL=managed-fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"managed-fetch.d.ts","sourceRoot":"","sources":["../../src/lib/managed-fetch.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAkB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAgBjE,OAAO,KAAK,EAIV,kBAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,EAGZ,MAAM,SAAS,CAAC;AASjB,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAkB;IAC5C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA4C;IAC7E,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAwB;IAC9C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiC;IAChE,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAY;IACtC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoB;IAE1C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgC;gBAE1C,MAAM,GAAE,kBAAuB;IA6BrC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAwBlF,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,WAAW,CAAC;IAejF,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY;YAM7B,cAAc;YAiBd,kBAAkB;YAwDlB,OAAO;YAmBP,WAAW;IAiDzB,OAAO,CAAC,YAAY;IAmBpB,OAAO,CAAC,WAAW;IAqBnB,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,MAAM;IAKd,OAAO,CAAC,SAAS;CAkBlB;AAGD,wBAAgB,kBAAkB,CAAC,MAAM,GAAE,kBAAuB,GAAG,YAAY,CAEhF"}
@@ -0,0 +1,233 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ManagedFetch = void 0;
4
+ exports.createManagedFetch = createManagedFetch;
5
+ const backoff_1 = require("./backoff");
6
+ const circuit_breaker_1 = require("./circuit-breaker");
7
+ const clock_1 = require("./clock");
8
+ const defaults_1 = require("./defaults");
9
+ const errors_1 = require("./errors");
10
+ const token_bucket_1 = require("./token-bucket");
11
+ class ManagedFetch {
12
+ userAgent;
13
+ rateLimit;
14
+ perHostRateLimit;
15
+ retry;
16
+ circuitBreaker;
17
+ timeoutMs;
18
+ fetchImpl;
19
+ clock;
20
+ hosts = new Map();
21
+ constructor(config = {}) {
22
+ this.userAgent = config.userAgent ?? defaults_1.DEFAULT_USER_AGENT;
23
+ this.rateLimit = config.rateLimit ?? defaults_1.DEFAULT_RATE_LIMIT;
24
+ this.perHostRateLimit = config.perHostRateLimit ?? {};
25
+ this.retry = { ...defaults_1.DEFAULT_RETRY, ...config.retry };
26
+ this.circuitBreaker = { ...defaults_1.DEFAULT_CIRCUIT_BREAKER, ...config.circuitBreaker };
27
+ this.timeoutMs = config.timeoutMs ?? defaults_1.DEFAULT_TIMEOUT_MS;
28
+ const globalFetch = (config.fetchImpl ?? globalThis.fetch);
29
+ if (globalFetch === undefined) {
30
+ throw new TypeError('ManagedFetch: no global `fetch` available; pass `config.fetchImpl` explicitly');
31
+ }
32
+ this.fetchImpl = globalFetch;
33
+ this.clock = {
34
+ now: config.clock?.now ?? clock_1.defaultClock.now,
35
+ sleep: config.clock?.sleep ?? clock_1.defaultClock.sleep,
36
+ random: config.clock?.random ?? clock_1.defaultClock.random,
37
+ };
38
+ }
39
+ async fetch(url, request = {}) {
40
+ const host = this.hostOf(url);
41
+ const state = this.hostState(host);
42
+ const gate = state.circuit.tryAcquire();
43
+ if (!gate.allowed) {
44
+ throw new errors_1.CircuitOpenError(host, gate.cooldownRemainingMs);
45
+ }
46
+ await this.applyRateLimit(host, state, request.signal);
47
+ return this.executeWithRetries(url, host, state, request);
48
+ }
49
+ async probe(url, request = {}) {
50
+ const host = this.hostOf(url);
51
+ const start = this.clock.now();
52
+ try {
53
+ const res = await this.executeOnce(url, host, {
54
+ ...request,
55
+ method: request.method ?? 'HEAD',
56
+ });
57
+ return { healthy: res.ok, status: res.status, latencyMs: this.clock.now() - start };
58
+ }
59
+ catch {
60
+ return { healthy: false, latencyMs: this.clock.now() - start };
61
+ }
62
+ }
63
+ getCircuitState(host) {
64
+ return this.hosts.get(host)?.circuit.current ?? circuit_breaker_1.CircuitState.CLOSED;
65
+ }
66
+ async applyRateLimit(host, state, signal) {
67
+ const waitMs = state.bucket.reserve();
68
+ if (waitMs <= 0) {
69
+ return;
70
+ }
71
+ if (waitMs > state.maxQueueMs) {
72
+ state.bucket.refund();
73
+ throw new errors_1.RateLimitError(host, waitMs, state.maxQueueMs);
74
+ }
75
+ await this.clock.sleep(waitMs, signal);
76
+ }
77
+ async executeWithRetries(url, host, state, request) {
78
+ const totalAttempts = this.retry.maxRetries + 1;
79
+ let lastError;
80
+ for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
81
+ const isLastAttempt = attempt === totalAttempts - 1;
82
+ let response;
83
+ try {
84
+ response = await this.executeOnce(url, host, request);
85
+ }
86
+ catch (err) {
87
+ if (request.signal?.aborted) {
88
+ throw err;
89
+ }
90
+ lastError = err;
91
+ if (isLastAttempt) {
92
+ state.circuit.recordFailure();
93
+ if (err instanceof errors_1.RequestTimeoutError && this.retry.maxRetries === 0) {
94
+ throw err;
95
+ }
96
+ throw new errors_1.RetriesExhaustedError(host, totalAttempts, { cause: err });
97
+ }
98
+ await this.backoff(attempt, null, request.signal);
99
+ continue;
100
+ }
101
+ if (this.isRetryableStatus(response.status)) {
102
+ if (isLastAttempt) {
103
+ state.circuit.recordFailure();
104
+ throw new errors_1.RetriesExhaustedError(host, totalAttempts, { lastStatus: response.status });
105
+ }
106
+ await this.backoff(attempt, response.headers.get('retry-after'), request.signal);
107
+ continue;
108
+ }
109
+ state.circuit.recordSuccess();
110
+ return this.buildResult(url, response);
111
+ }
112
+ throw new errors_1.RetriesExhaustedError(host, totalAttempts, { cause: lastError });
113
+ }
114
+ async backoff(attempt, retryAfterHeader, signal) {
115
+ const delayMs = (0, backoff_1.resolveRetryDelayMs)({
116
+ attempt,
117
+ baseDelayMs: this.retry.baseDelayMs,
118
+ maxDelayMs: this.retry.maxDelayMs,
119
+ random: this.clock.random,
120
+ respectRetryAfter: this.retry.respectRetryAfter,
121
+ retryAfterHeader,
122
+ nowEpochMs: this.clock.now(),
123
+ });
124
+ if (delayMs > 0) {
125
+ await this.clock.sleep(delayMs, signal);
126
+ }
127
+ }
128
+ async executeOnce(url, host, request) {
129
+ const timeoutMs = request.timeoutMs ?? this.timeoutMs;
130
+ const controller = new AbortController();
131
+ let timedOut = false;
132
+ const timer = setTimeout(() => {
133
+ timedOut = true;
134
+ controller.abort();
135
+ }, timeoutMs);
136
+ const external = request.signal;
137
+ const onExternalAbort = () => controller.abort();
138
+ if (external) {
139
+ if (external.aborted) {
140
+ controller.abort();
141
+ }
142
+ else {
143
+ external.addEventListener('abort', onExternalAbort, { once: true });
144
+ }
145
+ }
146
+ const init = {
147
+ method: request.method ?? 'GET',
148
+ headers: this.buildHeaders(request),
149
+ signal: controller.signal,
150
+ };
151
+ if (request.body !== undefined) {
152
+ init.body = request.body;
153
+ }
154
+ try {
155
+ return await this.fetchImpl(url, init);
156
+ }
157
+ catch (err) {
158
+ if (timedOut) {
159
+ throw new errors_1.RequestTimeoutError(host, timeoutMs);
160
+ }
161
+ throw err;
162
+ }
163
+ finally {
164
+ clearTimeout(timer);
165
+ external?.removeEventListener('abort', onExternalAbort);
166
+ }
167
+ }
168
+ buildHeaders(request) {
169
+ const headers = {
170
+ 'user-agent': request.userAgent ?? this.userAgent,
171
+ };
172
+ if (request.conditional?.etag !== undefined) {
173
+ headers['if-none-match'] = request.conditional.etag;
174
+ }
175
+ if (request.conditional?.lastModified !== undefined) {
176
+ headers['if-modified-since'] = request.conditional.lastModified;
177
+ }
178
+ if (request.headers) {
179
+ for (const [key, value] of Object.entries(request.headers)) {
180
+ headers[key] = value;
181
+ }
182
+ }
183
+ return headers;
184
+ }
185
+ buildResult(url, response) {
186
+ const notModified = response.status === 304;
187
+ const etag = response.headers.get('etag') ?? undefined;
188
+ const lastModified = response.headers.get('last-modified') ?? undefined;
189
+ return {
190
+ url,
191
+ status: response.status,
192
+ ok: response.ok,
193
+ notModified,
194
+ fromCache: notModified,
195
+ headers: response.headers,
196
+ raw: response,
197
+ ...(etag !== undefined ? { etag } : {}),
198
+ ...(lastModified !== undefined ? { lastModified } : {}),
199
+ text: () => response.text(),
200
+ json: () => response.json(),
201
+ arrayBuffer: () => response.arrayBuffer(),
202
+ };
203
+ }
204
+ isRetryableStatus(status) {
205
+ return this.retry.retryableStatuses.includes(status);
206
+ }
207
+ hostOf(url) {
208
+ return new URL(url).hostname;
209
+ }
210
+ hostState(host) {
211
+ const existing = this.hosts.get(host);
212
+ if (existing !== undefined) {
213
+ return existing;
214
+ }
215
+ const rl = this.perHostRateLimit[host] ?? this.rateLimit;
216
+ const state = {
217
+ bucket: new token_bucket_1.TokenBucket({
218
+ requestsPerSecond: rl.requestsPerSecond,
219
+ burst: rl.burst,
220
+ now: this.clock.now,
221
+ }),
222
+ circuit: new circuit_breaker_1.CircuitBreaker({ ...this.circuitBreaker, now: this.clock.now }),
223
+ maxQueueMs: rl.maxQueueMs ?? defaults_1.DEFAULT_RATE_LIMIT.maxQueueMs,
224
+ };
225
+ this.hosts.set(host, state);
226
+ return state;
227
+ }
228
+ }
229
+ exports.ManagedFetch = ManagedFetch;
230
+ function createManagedFetch(config = {}) {
231
+ return new ManagedFetch(config);
232
+ }
233
+ //# sourceMappingURL=managed-fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"managed-fetch.js","sourceRoot":"","sources":["../../src/lib/managed-fetch.ts"],"names":[],"mappings":";;;AA+VA,gDAEC;AA/UD,uCAAgD;AAChD,uDAAiE;AACjE,mCAAuC;AACvC,yCAMoB;AACpB,qCAKkB;AAClB,iDAA6C;AAoB7C,MAAa,YAAY;IACN,SAAS,CAAS;IAClB,SAAS,CAAkB;IAC3B,gBAAgB,CAA4C;IAC5D,KAAK,CAAwB;IAC7B,cAAc,CAAiC;IAC/C,SAAS,CAAS;IAClB,SAAS,CAAY;IACrB,KAAK,CAAoB;IAEzB,KAAK,GAAG,IAAI,GAAG,EAAqB,CAAC;IAEtD,YAAY,SAA6B,EAAE;QACzC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,6BAAkB,CAAC;QACxD,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,6BAAkB,CAAC;QACxD,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,EAAE,CAAC;QACtD,IAAI,CAAC,KAAK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AK,EAAE,EAAE,CAAC,KAAK;gBACf,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG;aACpB,CAAC;YACF,OAAO,EAAE,IAAI,gCAAc,CAAC,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;YAC5E,UAAU,EAAE,EAAE,CAAC,UAAU,IAAI,6BAAkB,CAAC,UAAU;SAC3D,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAtSD,oCAsSC;AAGD,SAAgB,kBAAkB,CAAC,SAA6B,EAAE;IAChE,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;AAClC,CAAC"}
@@ -0,0 +1,16 @@
1
+ export interface TokenBucketOptions {
2
+ requestsPerSecond: number;
3
+ burst: number;
4
+ now: () => number;
5
+ }
6
+ export declare class TokenBucket {
7
+ private readonly opts;
8
+ private readonly refillPerMs;
9
+ private readonly capacity;
10
+ private tokens;
11
+ private lastRefill;
12
+ constructor(opts: TokenBucketOptions);
13
+ reserve(): number;
14
+ refund(): void;
15
+ }
16
+ //# sourceMappingURL=token-bucket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-bucket.d.ts","sourceRoot":"","sources":["../../src/lib/token-bucket.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,MAAM,CAAC;CACnB;AAED,qBAAa,WAAW;IAMV,OAAO,CAAC,QAAQ,CAAC,IAAI;IALjC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAS;gBAEE,IAAI,EAAE,kBAAkB;IAkBrD,OAAO,IAAI,MAAM;IAyBjB,MAAM,IAAI,IAAI;CAGf"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TokenBucket = void 0;
4
+ class TokenBucket {
5
+ opts;
6
+ refillPerMs;
7
+ capacity;
8
+ tokens;
9
+ lastRefill;
10
+ constructor(opts) {
11
+ this.opts = opts;
12
+ if (opts.requestsPerSecond <= 0) {
13
+ throw new RangeError('requestsPerSecond must be > 0');
14
+ }
15
+ if (opts.burst <= 0) {
16
+ throw new RangeError('burst must be > 0');
17
+ }
18
+ this.refillPerMs = opts.requestsPerSecond / 1000;
19
+ this.capacity = opts.burst;
20
+ this.tokens = opts.burst;
21
+ this.lastRefill = opts.now();
22
+ }
23
+ reserve() {
24
+ const now = this.opts.now();
25
+ const elapsed = now - this.lastRefill;
26
+ if (elapsed > 0) {
27
+ this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillPerMs);
28
+ this.lastRefill = now;
29
+ }
30
+ if (this.tokens >= 1) {
31
+ this.tokens -= 1;
32
+ return 0;
33
+ }
34
+ const deficit = 1 - this.tokens;
35
+ const waitMs = deficit / this.refillPerMs;
36
+ this.tokens -= 1;
37
+ return waitMs;
38
+ }
39
+ refund() {
40
+ this.tokens = Math.min(this.capacity, this.tokens + 1);
41
+ }
42
+ }
43
+ exports.TokenBucket = TokenBucket;
44
+ //# sourceMappingURL=token-bucket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-bucket.js","sourceRoot":"","sources":["../../src/lib/token-bucket.ts"],"names":[],"mappings":";;;AAwBA,MAAa,WAAW;IAMO;IALZ,WAAW,CAAS;IACpB,QAAQ,CAAS;IAC1B,MAAM,CAAS;IACf,UAAU,CAAS;IAE3B,YAA6B,IAAwB;QAAxB,SAAI,GAAJ,IAAI,CAAoB;QACnD,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,EAA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,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACzD,CAAC;CACF;AApDD,kCAoDC"}
@@ -0,0 +1,67 @@
1
+ export type ManagedFetchBody = RequestInit['body'];
2
+ export type FetchImpl = (input: string, init: RequestInit) => Promise<Response>;
3
+ export interface ManagedFetchClock {
4
+ now: () => number;
5
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
6
+ random: () => number;
7
+ }
8
+ export interface RateLimitConfig {
9
+ requestsPerSecond: number;
10
+ burst: number;
11
+ maxQueueMs?: number;
12
+ }
13
+ export interface RetryConfig {
14
+ maxRetries: number;
15
+ baseDelayMs: number;
16
+ maxDelayMs: number;
17
+ retryableStatuses?: readonly number[];
18
+ respectRetryAfter?: boolean;
19
+ }
20
+ export interface CircuitBreakerConfig {
21
+ failureThreshold: number;
22
+ cooldownMs: number;
23
+ halfOpenMaxProbes?: number;
24
+ }
25
+ export interface ManagedFetchConfig {
26
+ userAgent?: string;
27
+ rateLimit?: RateLimitConfig;
28
+ perHostRateLimit?: Readonly<Record<string, RateLimitConfig>>;
29
+ retry?: RetryConfig;
30
+ circuitBreaker?: CircuitBreakerConfig;
31
+ timeoutMs?: number;
32
+ fetchImpl?: FetchImpl;
33
+ clock?: Partial<ManagedFetchClock>;
34
+ }
35
+ export interface ConditionalTokens {
36
+ etag?: string;
37
+ lastModified?: string;
38
+ }
39
+ export interface ManagedFetchRequest {
40
+ method?: string;
41
+ headers?: Readonly<Record<string, string>>;
42
+ body?: ManagedFetchBody;
43
+ userAgent?: string;
44
+ timeoutMs?: number;
45
+ conditional?: ConditionalTokens;
46
+ signal?: AbortSignal;
47
+ }
48
+ export interface ManagedFetchResult {
49
+ url: string;
50
+ status: number;
51
+ ok: boolean;
52
+ notModified: boolean;
53
+ fromCache: boolean;
54
+ headers: Headers;
55
+ etag?: string;
56
+ lastModified?: string;
57
+ raw: Response;
58
+ text(): Promise<string>;
59
+ json<T = unknown>(): Promise<T>;
60
+ arrayBuffer(): Promise<ArrayBuffer>;
61
+ }
62
+ export interface ProbeResult {
63
+ healthy: boolean;
64
+ status?: number;
65
+ latencyMs: number;
66
+ }
67
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,gBAAgB,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;AAOnD,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAShF,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,MAAM,CAAC;IAClB,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,MAAM,EAAE,MAAM,MAAM,CAAC;CACtB;AAGD,MAAM,WAAW,eAAe;IAE9B,iBAAiB,EAAE,MAAM,CAAC;IAE1B,KAAK,EAAE,MAAM,CAAC;IAOd,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAGD,MAAM,WAAW,WAAW;IAE1B,UAAU,EAAE,MAAM,CAAC;IAEnB,WAAW,EAAE,MAAM,CAAC;IAEpB,UAAU,EAAE,MAAM,CAAC;IAEnB,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAEtC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAGD,MAAM,WAAW,oBAAoB;IAEnC,gBAAgB,EAAE,MAAM,CAAC;IAEzB,UAAU,EAAE,MAAM,CAAC;IAEnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAGD,MAAM,WAAW,kBAAkB;IAMjC,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,SAAS,CAAC,EAAE,eAAe,CAAC;IAE5B,gBAAgB,CAAC,EAAE,QAAQ,CAAC,MAA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1B,OAAO,EAAE,OAAO,CAAC;IAEjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,SAAS,EAAE,MAAM,CAAC;CACnB"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@xemahq/managed-fetch",
3
+ "version": "0.1.0",
4
+ "description": "Layer-1 managed outbound-fetch / polite-crawl HTTP client. A domain-agnostic wrapper any ingestion/monitor/scraper calls instead of bare `fetch`: per-host token-bucket rate limiting, exponential backoff+jitter with Retry-After, a per-host circuit breaker, first-class conditional (ETag / If-Modified-Since → 304) change-detection, configurable User-Agent, per-request timeouts, and a health probe. Fail-fast with typed errors; all rate-limit/circuit state is per-instance and in-memory. Zero runtime dependencies.",
5
+ "license": "Apache-2.0",
6
+ "author": "Neuralchowder Inc. <developer@xema.dev> (https://xema.dev)",
7
+ "homepage": "https://xema.dev",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/xema-dev/xema-kernel-sdk.git",
11
+ "directory": "packages/sdks/managed-fetch"
12
+ },
13
+ "bugs": "https://github.com/xema-dev/xema-kernel-sdk/issues",
14
+ "publishConfig": {
15
+ "registry": "https://registry.npmjs.org/",
16
+ "access": "public"
17
+ },
18
+ "main": "dist/index.js",
19
+ "types": "dist/index.d.ts",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "devDependencies": {
24
+ "@types/jest": "^30.0.0",
25
+ "@types/node": "25.2.3",
26
+ "jest": "^30.3.0",
27
+ "prettier": "3.6.2",
28
+ "ts-jest": "^29.4.9",
29
+ "typescript": "5.9.3"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "xema-source": "./src/index.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./dist/lib/*": {
38
+ "types": "./dist/lib/*.d.ts",
39
+ "default": "./dist/lib/*.js"
40
+ }
41
+ },
42
+ "scripts": {
43
+ "clean": "rm -rf dist",
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "format": "prettier --write \"src/**/*.ts\"",
46
+ "test": "jest --config jest.config.ts",
47
+ "typecheck": "tsc -p tsconfig.json --noEmit"
48
+ }
49
+ }