brass-runtime 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +36 -3
  2. package/dist/agent/cli/main.cjs +31 -32
  3. package/dist/agent/cli/main.js +3 -4
  4. package/dist/agent/cli/main.mjs +3 -4
  5. package/dist/agent/index.cjs +4 -5
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +3 -4
  8. package/dist/agent/index.mjs +3 -4
  9. package/dist/{chunk-GYM3LLGS.mjs → chunk-2QNREG6K.mjs} +188 -5
  10. package/dist/{chunk-4ROBZFL6.cjs → chunk-2SLT3X6G.cjs} +6 -8
  11. package/dist/{chunk-KZJQ723N.cjs → chunk-3PFZGP23.cjs} +13 -15
  12. package/dist/{chunk-VWIPB6I5.js → chunk-3PHU7FWS.js} +528 -23
  13. package/dist/{chunk-BKK77SBA.js → chunk-4YQHPIWJ.js} +32 -11
  14. package/dist/chunk-5XADBMSU.cjs +33 -0
  15. package/dist/{chunk-DNFJLJMW.mjs → chunk-6MLAZPBL.mjs} +48 -24
  16. package/dist/chunk-7TKI527D.cjs +123 -0
  17. package/dist/{chunk-AGR5B2BC.cjs → chunk-7TXQJFZX.cjs} +564 -12
  18. package/dist/{chunk-RKGKFN2A.js → chunk-AADFFVYS.js} +1 -1
  19. package/dist/{chunk-52PPNNI4.cjs → chunk-AJMKZXRB.cjs} +2 -2
  20. package/dist/{chunk-3AYM6WPJ.js → chunk-BG5RNEA2.js} +20 -299
  21. package/dist/{chunk-2HQTDLHF.mjs → chunk-ELLF55ER.mjs} +555 -3
  22. package/dist/{chunk-EOC4UHBS.mjs → chunk-G5JTCFMI.mjs} +2 -2
  23. package/dist/chunk-H5GYX7RZ.js +6126 -0
  24. package/dist/{chunk-C3MDXTRZ.js → chunk-HCJ4S3YB.js} +48 -24
  25. package/dist/{chunk-6IXXWIUM.js → chunk-IBRHSH5H.js} +555 -3
  26. package/dist/{chunk-Q2I37RP3.cjs → chunk-IFRBVMWJ.cjs} +44 -323
  27. package/dist/{chunk-52OB2ROS.js → chunk-ITG6I7ZS.js} +2 -4
  28. package/dist/chunk-ITZQ526U.mjs +33 -0
  29. package/dist/{chunk-7JIJOVCT.js → chunk-JH4GI3DW.js} +2 -4
  30. package/dist/{chunk-F6XWZQY4.cjs → chunk-KHACHFBQ.cjs} +583 -78
  31. package/dist/{chunk-4P2HHGAX.mjs → chunk-KRYP6CAE.mjs} +32 -11
  32. package/dist/chunk-KTGDLBLD.mjs +123 -0
  33. package/dist/{chunk-WBGRHGBP.cjs → chunk-LXBU5E77.cjs} +114 -93
  34. package/dist/{chunk-PD4EJTQC.cjs → chunk-N6QNSTWD.cjs} +5 -5
  35. package/dist/{chunk-6RY2FFN4.mjs → chunk-OI4ESUMC.mjs} +9 -11
  36. package/dist/{chunk-EJ6BPYVR.mjs → chunk-OT2TESZU.mjs} +1 -1
  37. package/dist/{chunk-7X3K5RMS.js → chunk-PSEU65ND.js} +9 -11
  38. package/dist/{chunk-SK7UZRNI.mjs → chunk-QCOLAHU3.mjs} +528 -23
  39. package/dist/{chunk-KH4SYAOS.mjs → chunk-QZ6QFJNM.mjs} +20 -299
  40. package/dist/{chunk-MBEJI5HF.mjs → chunk-R6WDSZA6.mjs} +2 -4
  41. package/dist/{chunk-FHQGHPMO.mjs → chunk-RREBJX2S.mjs} +2 -4
  42. package/dist/{chunk-5QC7LRZ3.js → chunk-S4HHFUYP.js} +2 -2
  43. package/dist/{chunk-GLE2WY7Z.cjs → chunk-SSQJKDN3.cjs} +194 -11
  44. package/dist/{chunk-CZIVE6NT.cjs → chunk-UUMKZJRJ.cjs} +48 -24
  45. package/dist/chunk-VIFA4DPN.cjs +6126 -0
  46. package/dist/chunk-W6WR37HN.js +33 -0
  47. package/dist/{chunk-FH2X7BVP.js → chunk-XSAHV5HQ.js} +188 -5
  48. package/dist/chunk-YM3EDNYD.js +123 -0
  49. package/dist/{chunk-7ZPEZ57L.cjs → chunk-YTX2JYYP.cjs} +18 -20
  50. package/dist/chunk-Z3PSSXP3.mjs +6126 -0
  51. package/dist/core/index.cjs +31 -9
  52. package/dist/core/index.d.ts +19 -152
  53. package/dist/core/index.js +80 -58
  54. package/dist/core/index.mjs +80 -58
  55. package/dist/defaultClient-DhpCQW9m.d.ts +1623 -0
  56. package/dist/{effect-DIUHZ9IN.d.ts → effect-CtUDl5M5.d.ts} +1 -1
  57. package/dist/http/index.cjs +202 -59
  58. package/dist/http/index.d.ts +55 -819
  59. package/dist/http/index.js +216 -73
  60. package/dist/http/index.mjs +216 -73
  61. package/dist/http/testing.cjs +31 -10
  62. package/dist/http/testing.d.ts +16 -5
  63. package/dist/http/testing.js +29 -8
  64. package/dist/http/testing.mjs +29 -8
  65. package/dist/index.cjs +110 -88
  66. package/dist/index.d.ts +9 -8
  67. package/dist/index.js +81 -59
  68. package/dist/index.mjs +81 -59
  69. package/dist/{schedule-CK3Ml_7p.d.ts → layer-BalPI6cN.d.ts} +176 -2
  70. package/dist/observability/index.cjs +20 -7
  71. package/dist/observability/index.d.ts +32 -8
  72. package/dist/observability/index.js +19 -6
  73. package/dist/observability/index.mjs +19 -6
  74. package/dist/perf/cli.cjs +26 -28
  75. package/dist/perf/cli.js +11 -13
  76. package/dist/perf/cli.mjs +11 -13
  77. package/dist/perf/index.cjs +13 -15
  78. package/dist/perf/index.js +11 -13
  79. package/dist/perf/index.mjs +11 -13
  80. package/dist/schema/index.cjs +2 -2
  81. package/dist/schema/index.js +1 -1
  82. package/dist/schema/index.mjs +1 -1
  83. package/dist/{server-D6JZ15_e.d.ts → server-C1zVmqE6.d.ts} +5 -5
  84. package/dist/{stream-B4oK9JFP.d.ts → stream-Bb4FTejt.d.ts} +1 -1
  85. package/dist/{tracer-Hwt1cl7h.d.ts → tracer-DzfuE6um.d.ts} +2 -2
  86. package/dist/{tracing-DqbTKGcf.d.ts → tracing-BABA5arE.d.ts} +1 -1
  87. package/docs/README.md +2 -0
  88. package/docs/ai/PUBLIC_API.md +28 -7
  89. package/docs/articles/brass-runtime-http-observability.md +467 -0
  90. package/docs/frameworks/angular.md +51 -0
  91. package/docs/frameworks/express.md +58 -0
  92. package/docs/frameworks/fastify.md +49 -0
  93. package/docs/frameworks/nestjs.md +53 -0
  94. package/docs/frameworks/nextjs.md +55 -0
  95. package/docs/frameworks/react.md +44 -0
  96. package/docs/frameworks/vanilla.md +56 -0
  97. package/docs/guides/layers.md +130 -0
  98. package/docs/http-recipes.md +31 -1
  99. package/docs/http.md +50 -1
  100. package/docs/observability.md +132 -0
  101. package/docs/performance-profiler.md +6 -2
  102. package/docs/recipes/layers.md +46 -2
  103. package/docs/recipes/testing.md +25 -0
  104. package/package.json +4 -1
  105. package/dist/chunk-3LOYJFRR.cjs +0 -300
  106. package/dist/chunk-3Y2RIUMM.js +0 -300
  107. package/dist/chunk-5EC274J5.cjs +0 -2874
  108. package/dist/chunk-5VRJNBLZ.mjs +0 -2874
  109. package/dist/chunk-62AZW6UT.cjs +0 -313
  110. package/dist/chunk-74ZTY6CP.js +0 -2871
  111. package/dist/chunk-7CMJS3QE.mjs +0 -2871
  112. package/dist/chunk-A2OM6NEH.mjs +0 -194
  113. package/dist/chunk-B33ICAKP.js +0 -313
  114. package/dist/chunk-JF5WGYJJ.cjs +0 -194
  115. package/dist/chunk-KN32XNTH.mjs +0 -313
  116. package/dist/chunk-KQLYONSE.cjs +0 -2871
  117. package/dist/chunk-L2SYFEBS.js +0 -194
  118. package/dist/chunk-MIIYDLGM.js +0 -2874
  119. package/dist/chunk-PWC3RBQE.mjs +0 -300
  120. package/dist/client-CZHU674n.d.ts +0 -820
@@ -0,0 +1,1623 @@
1
+ import { A as Async, C as AsyncWithPromise } from './effect-CtUDl5M5.js';
2
+ import { Z as ZStream } from './stream-Bb4FTejt.js';
3
+ import { l as Schedule, r as ScheduleObserver, d as CircuitBreakerError } from './layer-BalPI6cN.js';
4
+ import { SchemaIssue, JsonSchemaLike, AnyJsonSchemaLike, InferJsonSchema } from './schema/index.js';
5
+
6
+ type HttpRetryScheduleInput = {
7
+ readonly attempt: number;
8
+ readonly elapsedMs: number;
9
+ readonly request: HttpRequest;
10
+ readonly error?: HttpError;
11
+ readonly status?: number;
12
+ readonly retryAfterMs?: number;
13
+ };
14
+ type HttpRequestRetryOverride = false | {
15
+ readonly maxRetries?: number;
16
+ readonly baseDelayMs?: number;
17
+ readonly maxDelayMs?: number;
18
+ readonly schedule?: Schedule<HttpRetryScheduleInput, unknown>;
19
+ readonly retryOnStatus?: (status: number) => boolean;
20
+ };
21
+ type HttpRequestPolicy = {
22
+ readonly preset?: string;
23
+ readonly lane?: string;
24
+ readonly dedupKey?: string;
25
+ readonly priority?: number;
26
+ readonly retry?: HttpRequestRetryOverride;
27
+ readonly poolKey?: string;
28
+ };
29
+ type HttpRequestPolicyRef = HttpRequestPolicy | string;
30
+ type HttpPolicyPreset = HttpRequestPolicy | ((request: HttpRequest, presetName: string) => HttpRequestPolicy);
31
+ type HttpPolicyPresets = Record<string, HttpPolicyPreset>;
32
+ type ResolveHttpRequestPolicyOptions = {
33
+ readonly presets?: HttpPolicyPresets;
34
+ };
35
+ declare const defineHttpPolicyPresets: <Presets extends HttpPolicyPresets>(presets: Presets) => Presets;
36
+ declare const httpPolicy: Readonly<{
37
+ preset: (preset: string, overrides?: Omit<HttpRequestPolicy, "preset">) => HttpRequestPolicy;
38
+ lane: (lane: string, overrides?: Omit<HttpRequestPolicy, "preset" | "lane">) => HttpRequestPolicy;
39
+ define: <Presets extends HttpPolicyPresets>(presets: Presets) => Presets;
40
+ }>;
41
+ declare const getHttpRequestPolicy: (req: HttpRequest, options?: ResolveHttpRequestPolicyOptions) => HttpRequestPolicy;
42
+ declare const withHttpRequestPolicy: (req: HttpRequest, patch: Partial<HttpRequestPolicy>) => HttpRequest;
43
+ declare const resolveHttpRequestPolicyPresets: (req: HttpRequest, presets: HttpPolicyPresets) => HttpRequest;
44
+ declare const withHttpPolicyPresets: (presets: HttpPolicyPresets) => HttpMiddleware;
45
+
46
+ /**
47
+ * Observable event emitted on each retry attempt via the `onRetry` callback.
48
+ */
49
+ type RetryEvent = {
50
+ /** Zero-based attempt number (0 = first retry, not the initial request). */
51
+ attempt: number;
52
+ /** Computed delay in milliseconds before the next attempt. */
53
+ delayMs: number;
54
+ /** The error that triggered this retry, if the request failed with an HttpError. */
55
+ error?: HttpError;
56
+ /** The HTTP status code that triggered this retry, if the request returned a retryable status. */
57
+ status?: number;
58
+ /** The request URL. */
59
+ url: string;
60
+ /** The request HTTP method. */
61
+ method: HttpMethod;
62
+ /** Timestamp (ms since epoch) when the retry decision was made. */
63
+ timestamp: number;
64
+ };
65
+ type RetryScheduleInput = HttpRetryScheduleInput;
66
+ /**
67
+ * Per-request retry override. Prefer `req.policy.retry`; legacy top-level `req.retry`
68
+ * is still supported.
69
+ * - `false` disables retry entirely for this request.
70
+ * - A partial policy object merges with the middleware-level policy (per-request wins).
71
+ */
72
+ type PerRequestRetryOverride = HttpRequestRetryOverride;
73
+ type RetryPolicy = {
74
+ maxRetries: number;
75
+ baseDelayMs: number;
76
+ maxDelayMs: number;
77
+ /** Optional declarative schedule. When present, it provides retry delays. */
78
+ schedule?: Schedule<RetryScheduleInput, unknown>;
79
+ /** Optional observer for declarative schedule decisions. */
80
+ onScheduleDecision?: ScheduleObserver<RetryScheduleInput, unknown>;
81
+ /** Optional total retry budget, including request attempts and sleeps. */
82
+ maxElapsedMs?: number;
83
+ /** Defaults to true. When true, Retry-After is honored but capped by maxDelayMs/budget. */
84
+ respectRetryAfter?: boolean;
85
+ retryOnMethods?: HttpMethod[];
86
+ retryOnStatus?: (status: number) => boolean;
87
+ retryOnError?: (e: HttpError) => boolean;
88
+ /** Strict engine selector for retry planning. Defaults to ts. */
89
+ engine?: "ts" | "wasm";
90
+ /** Back-compat knob: wasm=true maps to engine="wasm", wasm=false maps to engine="ts". */
91
+ wasm?: boolean;
92
+ /** Called synchronously before each retry delay begins. Zero overhead when omitted. */
93
+ onRetry?: (event: RetryEvent) => void;
94
+ };
95
+ declare const defaultRetryableMethods: HttpMethod[];
96
+ declare const defaultRetryOnStatus: (s: number) => s is 408 | 429 | 500 | 502 | 503 | 504;
97
+ declare const defaultRetryOnError: (e: HttpError) => boolean;
98
+ declare const backoffDelayMs: (attempt: number, base: number, cap: number) => number;
99
+ declare const retryAfterMs: (headers: Record<string, string>) => number | undefined;
100
+ declare const normalizeRetryBudget: (ms: number | undefined) => number | undefined;
101
+ declare const withRetry: (p: RetryPolicy) => HttpMiddleware;
102
+
103
+ type HttpPoolKeyResolver = "global" | "origin" | "host" | ((req: HttpRequest, url: URL) => string);
104
+ type HttpPoolConfig = {
105
+ /** Max concurrent downstream calls per resolved key. */
106
+ readonly concurrency?: number;
107
+ /** Max queued waiters per key. `0` means fail fast when the pool is full. */
108
+ readonly maxQueue?: number;
109
+ /** Max time a request may wait for a pool slot before failing fast. */
110
+ readonly queueTimeoutMs?: number;
111
+ /** How to isolate pools. Default: `origin`; useful values: `global`, `host`, `origin`. */
112
+ readonly key?: HttpPoolKeyResolver;
113
+ /**
114
+ * Strict engine selector for permit governance. Defaults to ts.
115
+ * - ts: TypeScript permit pool.
116
+ * - wasm: require BrassWasmHttpPermitPool from wasm/pkg; never falls back.
117
+ */
118
+ readonly engine?: "ts" | "wasm";
119
+ /** Back-compat knob: wasm=true maps to engine="wasm", wasm=false maps to engine="ts". */
120
+ readonly wasm?: boolean;
121
+ };
122
+ type HttpPoolKeyStats = {
123
+ readonly key: string;
124
+ readonly running: number;
125
+ readonly queued: number;
126
+ readonly concurrency: number;
127
+ readonly maxQueue: number;
128
+ readonly acquired: number;
129
+ readonly released: number;
130
+ readonly rejected: number;
131
+ readonly queueTimeouts: number;
132
+ readonly abortedWhileQueued: number;
133
+ };
134
+ type HttpPoolStats = {
135
+ readonly running: number;
136
+ readonly queued: number;
137
+ readonly acquired: number;
138
+ readonly released: number;
139
+ readonly rejected: number;
140
+ readonly queueTimeouts: number;
141
+ readonly abortedWhileQueued: number;
142
+ readonly wasm?: unknown;
143
+ readonly keys: HttpPoolKeyStats[];
144
+ };
145
+ type HttpPoolLease = {
146
+ readonly key: string;
147
+ release: () => void;
148
+ };
149
+ declare function resolveHttpPoolKey(resolver: HttpPoolKeyResolver | undefined, req: HttpRequest, url: URL): string;
150
+ declare class HttpConcurrencyPool {
151
+ private readonly states;
152
+ private readonly concurrency;
153
+ private readonly maxQueue;
154
+ private readonly queueTimeoutMs;
155
+ readonly keyResolver: HttpPoolKeyResolver | undefined;
156
+ private readonly wasm;
157
+ private readonly wasmWaiters;
158
+ private wasmTimer;
159
+ private nextSubjectId;
160
+ constructor(config?: HttpPoolConfig);
161
+ acquire(key: string, signal: AbortSignal): Promise<HttpPoolLease>;
162
+ stats(): HttpPoolStats;
163
+ private acquireJs;
164
+ private acquireWasm;
165
+ private getState;
166
+ private makeLease;
167
+ private drain;
168
+ private handleWasmGrants;
169
+ private handleWasmTimeouts;
170
+ private scheduleWasmTimeoutPump;
171
+ private cleanupWaiter;
172
+ private removeWaiter;
173
+ private allocateSubjectId;
174
+ }
175
+
176
+ type AdaptiveHeadroomMode = "stable" | "probe" | "warmup" | "slow-start" | "circuit-open";
177
+ type AdaptiveHeadroomContext = {
178
+ readonly key: string;
179
+ readonly currentLimit: number;
180
+ readonly minLimit: number;
181
+ readonly maxLimit: number;
182
+ readonly gradient: number;
183
+ readonly mode: AdaptiveHeadroomMode;
184
+ };
185
+ type AdaptiveHeadroomStrategy = number | "fixed" | "proportional" | {
186
+ readonly type: "fixed";
187
+ readonly value?: number;
188
+ } | {
189
+ readonly type: "proportional";
190
+ readonly ratio?: number;
191
+ readonly min?: number;
192
+ readonly max?: number;
193
+ } | ((context: AdaptiveHeadroomContext) => number);
194
+ type AdaptiveBaselineStrategy = "min" | "p5" | "ema-low";
195
+ type AdaptiveQueueStrategy = "fifo" | "priority";
196
+ type AdaptiveQueueLoadShedding = "reject-new" | "priority-evict";
197
+ type AdaptiveLimiterPreset = "conservative" | "balanced" | "aggressive";
198
+ type AdaptiveAcquireOptions = {
199
+ /** Request priority from 0 (highest) to 9 (lowest). Default: 5. */
200
+ readonly priority?: number;
201
+ };
202
+ type AdaptiveReleaseInfo = {
203
+ /** HTTP response status, used by the error signal when >= 500 by default. */
204
+ readonly status?: number;
205
+ /** Marks a failed request without an HTTP response, e.g. fetch error or timeout. */
206
+ readonly error?: boolean;
207
+ };
208
+ /**
209
+ * Configuration for the adaptive concurrency limiter.
210
+ * All fields are optional with sensible defaults.
211
+ */
212
+ type AdaptiveLimiterConfig = {
213
+ /** Named production preset used before caller overrides are applied. */
214
+ readonly preset?: AdaptiveLimiterPreset;
215
+ /** Initial concurrency limit. Default: 10. */
216
+ readonly initialLimit?: number;
217
+ /** Minimum concurrency limit. Default: 1. */
218
+ readonly minLimit?: number;
219
+ /** Maximum concurrency limit. Default: 200. */
220
+ readonly maxLimit?: number;
221
+ /** EMA smoothing factor in (0, 1]. Default: 0.5. */
222
+ readonly smoothingFactor?: number;
223
+ /** Number of completions between probes. Default: 10. */
224
+ readonly probeInterval?: number;
225
+ /** Random probe interval spread. 0 disables jitter, 0.2 means ±20%. Default: 0.2. */
226
+ readonly probeJitterRatio?: number;
227
+ /** Sliding window size for latency samples. Default: 100. */
228
+ readonly windowSize?: number;
229
+ /** Minimum samples before the limiter may change its limit. Default: 10. */
230
+ readonly minSamples?: number;
231
+ /** Baseline used for gradient computation. Default: "min". */
232
+ readonly baselineStrategy?: AdaptiveBaselineStrategy;
233
+ /** Samples to wait after a decrease before allowing another decrease. Default: 0. */
234
+ readonly decreaseCooldownSamples?: number;
235
+ /** Number of limit-change events retained per key for diagnostics. Default: 32. */
236
+ readonly historySize?: number;
237
+ /** Exponential decay applied to percentile windows. 1 disables weighting. Default: 1. */
238
+ readonly windowDecayFactor?: number;
239
+ /** Error signal weight blended with latency gradient. 0 disables. Default: 0. */
240
+ readonly errorWeight?: number;
241
+ /** EMA smoothing factor for the error rate signal. Defaults to smoothingFactor. */
242
+ readonly errorSmoothingFactor?: number;
243
+ /** HTTP status at/above which responses count as downstream errors. Default: 500. */
244
+ readonly errorStatusThreshold?: number;
245
+ /** Internal queue ordering. Default: "fifo". */
246
+ readonly queueStrategy?: AdaptiveQueueStrategy;
247
+ /** Queue-full behavior. Default: "reject-new". */
248
+ readonly queueLoadShedding?: AdaptiveQueueLoadShedding;
249
+ /** Rejection streak before PoolRejected carries retryAfterMs. Default: 3. */
250
+ readonly rejectionBackoffThreshold?: number;
251
+ /** Backoff hint for sustained PoolRejected errors. Default: undefined. */
252
+ readonly rejectionBackoffMs?: number;
253
+ /** Remove inactive per-key state after this idle period. Use false to disable. Default: 300000. */
254
+ readonly stateTtlMs?: number | false;
255
+ /** Number of valid completions used for explicit linear warmup. 0 disables. Default: 0. */
256
+ readonly warmupRequests?: number;
257
+ /** Gradient below which the limiter decreases concurrency. Default: 0.75. */
258
+ readonly decreaseThreshold?: number;
259
+ /** Gradient at or above which the limiter may increase concurrency. Default: 1.0. */
260
+ readonly increaseThreshold?: number;
261
+ /** Maximum fraction of the current limit that can be removed in one adjustment. Default: 0.2. */
262
+ readonly maxDecreaseRatio?: number;
263
+ /** Fixed, proportional, or custom headroom added on stable growth/probes. Default: 1. */
264
+ readonly headroomStrategy?: AdaptiveHeadroomStrategy;
265
+ /** Enable fast recovery after sustained saturation. Default: true. */
266
+ readonly slowStartRecovery?: boolean;
267
+ /** Gradient at/below which samples count as strong saturation. Default: 0.5. */
268
+ readonly slowStartSaturationThreshold?: number;
269
+ /** Consecutive strong-saturation samples before slow-start recovery arms. Default: 3. */
270
+ readonly slowStartSaturationSamples?: number;
271
+ /** Key resolver for isolation scope. Default: "origin". */
272
+ readonly key?: HttpPoolKeyResolver;
273
+ /** Maximum queue depth per key. Default: 256. */
274
+ readonly maxQueue?: number;
275
+ /** Queue timeout in ms. Default: undefined (no timeout). */
276
+ readonly queueTimeoutMs?: number;
277
+ /** Callback invoked when the limit changes. */
278
+ readonly onLimitChange?: (event: LimitChangeEvent) => void;
279
+ /** Which percentile to use for gradient computation. Default: "p50". */
280
+ readonly percentile?: "p50" | "p99";
281
+ };
282
+ /**
283
+ * Event emitted when the concurrency limit changes.
284
+ */
285
+ type LimitChangeEvent = {
286
+ readonly key: string;
287
+ readonly previousLimit: number;
288
+ readonly newLimit: number;
289
+ readonly gradient: number;
290
+ readonly latencyGradient: number;
291
+ readonly errorRate: number;
292
+ readonly smoothedLatency: number;
293
+ readonly minLatency: number;
294
+ readonly baselineLatency: number;
295
+ readonly p5: number | undefined;
296
+ readonly timestamp: number;
297
+ readonly reason?: "gradient" | "probe" | "warmup" | "slow-start" | "circuit-open";
298
+ };
299
+ /**
300
+ * Snapshot of the adaptive limiter's current state for a given key.
301
+ */
302
+ type AdaptiveLimiterStats = {
303
+ readonly limit: number;
304
+ readonly inFlight: number;
305
+ readonly queueDepth: number;
306
+ readonly gradient: number | undefined;
307
+ readonly latencyGradient: number | undefined;
308
+ readonly errorRate: number | undefined;
309
+ readonly smoothedLatency: number | undefined;
310
+ readonly minLatency: number | undefined;
311
+ readonly baselineLatency: number | undefined;
312
+ readonly p5: number | undefined;
313
+ readonly p50: number | undefined;
314
+ readonly p99: number | undefined;
315
+ readonly probeCount: number;
316
+ readonly windowSize: number;
317
+ readonly warmupCompletions?: number;
318
+ readonly slowStart?: boolean;
319
+ readonly cooldownSamplesRemaining?: number;
320
+ readonly utilization?: number;
321
+ readonly requestsPerSecond?: number;
322
+ readonly completionsPerSecond?: number;
323
+ readonly rejectionRate?: number;
324
+ readonly suggestedBackoffMs?: number;
325
+ readonly stateCount?: number;
326
+ readonly keys?: readonly string[];
327
+ };
328
+ type AdaptiveLimiterKeySnapshot = AdaptiveLimiterStats & {
329
+ readonly key: string;
330
+ readonly createdAt: number;
331
+ readonly createdTimestamp: number;
332
+ readonly lastActivityAt: number;
333
+ readonly lastActivityTimestamp: number;
334
+ readonly nextProbeAt: number;
335
+ readonly warmupDone: boolean;
336
+ readonly saturationStreak: number;
337
+ readonly slowStartRecoveryStarted: boolean;
338
+ readonly history: readonly LimitChangeEvent[];
339
+ readonly acquired: number;
340
+ readonly released: number;
341
+ readonly rejected: number;
342
+ readonly queueTimeouts: number;
343
+ readonly abortedWhileQueued: number;
344
+ readonly evictedWhileQueued: number;
345
+ };
346
+ type AdaptiveLimiterDiagnostics = {
347
+ readonly stateCount: number;
348
+ readonly keys: readonly string[];
349
+ readonly aggregate: AdaptiveLimiterStats;
350
+ readonly states: readonly AdaptiveLimiterKeySnapshot[];
351
+ readonly history: readonly LimitChangeEvent[];
352
+ };
353
+ /**
354
+ * A lease representing an acquired concurrency slot.
355
+ * Call `release(latencyMs)` when the request completes to record latency and free the slot.
356
+ */
357
+ type AdaptiveLease = {
358
+ readonly key: string;
359
+ release(latencyMs: number, info?: AdaptiveReleaseInfo): void;
360
+ };
361
+ /** Resolved (non-optional) configuration with defaults applied. */
362
+ type ResolvedConfig = {
363
+ readonly preset: AdaptiveLimiterPreset | undefined;
364
+ readonly initialLimit: number;
365
+ readonly minLimit: number;
366
+ readonly maxLimit: number;
367
+ readonly smoothingFactor: number;
368
+ readonly probeInterval: number;
369
+ readonly probeJitterRatio: number;
370
+ readonly windowSize: number;
371
+ readonly minSamples: number;
372
+ readonly baselineStrategy: AdaptiveBaselineStrategy;
373
+ readonly decreaseCooldownSamples: number;
374
+ readonly historySize: number;
375
+ readonly windowDecayFactor: number;
376
+ readonly errorWeight: number;
377
+ readonly errorSmoothingFactor: number;
378
+ readonly errorStatusThreshold: number;
379
+ readonly queueStrategy: AdaptiveQueueStrategy;
380
+ readonly queueLoadShedding: AdaptiveQueueLoadShedding;
381
+ readonly rejectionBackoffThreshold: number;
382
+ readonly rejectionBackoffMs: number | undefined;
383
+ readonly stateTtlMs: number | undefined;
384
+ readonly warmupRequests: number;
385
+ readonly decreaseThreshold: number;
386
+ readonly increaseThreshold: number;
387
+ readonly maxDecreaseRatio: number;
388
+ readonly headroomStrategy: AdaptiveHeadroomStrategy;
389
+ readonly slowStartRecovery: boolean;
390
+ readonly slowStartSaturationThreshold: number;
391
+ readonly slowStartSaturationSamples: number;
392
+ readonly key: HttpPoolKeyResolver;
393
+ readonly maxQueue: number;
394
+ readonly queueTimeoutMs: number | undefined;
395
+ readonly onLimitChange: ((event: LimitChangeEvent) => void) | undefined;
396
+ readonly percentile: "p50" | "p99";
397
+ };
398
+ declare const adaptiveLimiterPresets: Readonly<{
399
+ conservative: Readonly<{
400
+ initialLimit: 8;
401
+ minLimit: 2;
402
+ maxLimit: 64;
403
+ maxQueue: 256;
404
+ queueTimeoutMs: 30000;
405
+ smoothingFactor: 0.3;
406
+ probeInterval: 40;
407
+ probeJitterRatio: 0.2;
408
+ windowSize: 100;
409
+ minSamples: 80;
410
+ baselineStrategy: "p5";
411
+ windowDecayFactor: 0.99;
412
+ errorWeight: 0.2;
413
+ decreaseThreshold: 0.65;
414
+ maxDecreaseRatio: 0.08;
415
+ headroomStrategy: "fixed";
416
+ queueStrategy: "priority";
417
+ queueLoadShedding: "priority-evict";
418
+ rejectionBackoffThreshold: 2;
419
+ rejectionBackoffMs: 150;
420
+ percentile: "p50";
421
+ }>;
422
+ balanced: Readonly<{
423
+ initialLimit: 16;
424
+ minLimit: 4;
425
+ maxLimit: 128;
426
+ maxQueue: 512;
427
+ queueTimeoutMs: 30000;
428
+ smoothingFactor: 0.35;
429
+ probeInterval: 25;
430
+ probeJitterRatio: 0.2;
431
+ windowSize: 100;
432
+ minSamples: 50;
433
+ baselineStrategy: "p5";
434
+ windowDecayFactor: 0.98;
435
+ errorWeight: 0.25;
436
+ decreaseThreshold: 0.5;
437
+ maxDecreaseRatio: 0.1;
438
+ headroomStrategy: {
439
+ type: "proportional";
440
+ ratio: number;
441
+ };
442
+ queueStrategy: "priority";
443
+ queueLoadShedding: "priority-evict";
444
+ rejectionBackoffThreshold: 3;
445
+ rejectionBackoffMs: 100;
446
+ percentile: "p50";
447
+ }>;
448
+ aggressive: Readonly<{
449
+ initialLimit: 32;
450
+ minLimit: 8;
451
+ maxLimit: 256;
452
+ maxQueue: 1024;
453
+ queueTimeoutMs: 30000;
454
+ smoothingFactor: 0.35;
455
+ probeInterval: 20;
456
+ probeJitterRatio: 0.2;
457
+ windowSize: 160;
458
+ minSamples: 100;
459
+ baselineStrategy: "p5";
460
+ windowDecayFactor: 0.98;
461
+ errorWeight: 0.25;
462
+ decreaseThreshold: 0.5;
463
+ maxDecreaseRatio: 0.1;
464
+ headroomStrategy: {
465
+ type: "proportional";
466
+ ratio: number;
467
+ };
468
+ queueStrategy: "priority";
469
+ queueLoadShedding: "priority-evict";
470
+ rejectionBackoffThreshold: 3;
471
+ rejectionBackoffMs: 100;
472
+ percentile: "p50";
473
+ }>;
474
+ }>;
475
+ declare function makeAdaptiveLimiterConfig(preset: AdaptiveLimiterPreset, overrides?: AdaptiveLimiterConfig): AdaptiveLimiterConfig;
476
+ /**
477
+ * Validates the adaptive limiter configuration.
478
+ * Throws a descriptive error for invalid combinations.
479
+ */
480
+ declare function validateConfig(config: AdaptiveLimiterConfig): void;
481
+ /**
482
+ * Resolves a partial configuration into a fully-resolved configuration with defaults applied.
483
+ * Handles minLimit > maxLimit by treating minLimit as the effective maxLimit.
484
+ */
485
+ declare function resolveConfig(config?: AdaptiveLimiterConfig): ResolvedConfig;
486
+
487
+ /**
488
+ * Adaptive concurrency limiter that dynamically adjusts the number of concurrent
489
+ * requests based on observed latency patterns using a gradient-based algorithm.
490
+ */
491
+ declare class AdaptiveLimiter {
492
+ private readonly config;
493
+ private readonly states;
494
+ private destroyed;
495
+ constructor(config?: AdaptiveLimiterConfig);
496
+ /** Key resolver for external use by the HTTP client. */
497
+ get keyResolver(): HttpPoolKeyResolver | undefined;
498
+ /**
499
+ * Acquire a concurrency slot for the given key.
500
+ * Resolves immediately if under the limit, otherwise queues the request.
501
+ * Rejects with PoolRejected if the queue is full, or PoolTimeout if the queue timeout expires.
502
+ */
503
+ acquire(key: string, signal: AbortSignal, options?: AdaptiveAcquireOptions): Promise<AdaptiveLease>;
504
+ /**
505
+ * Get stats for a specific key, or aggregate stats if no key is provided.
506
+ */
507
+ stats(key?: string): AdaptiveLimiterStats;
508
+ /** Return the currently retained per-key state identifiers. */
509
+ keys(): readonly string[];
510
+ /** Return a diagnostic snapshot for one retained key, if present. */
511
+ snapshot(key: string): AdaptiveLimiterKeySnapshot | undefined;
512
+ /** Return a full diagnostic dump across all retained keys. */
513
+ dump(): AdaptiveLimiterDiagnostics;
514
+ /** Return retained limit-change history for one key, or all keys if omitted. */
515
+ history(key?: string): readonly LimitChangeEvent[];
516
+ /**
517
+ * Circuit-breaker feedback hook. When a circuit is already open for `key`,
518
+ * collapse that key's limit to minLimit immediately instead of waiting for
519
+ * latency gradients to discover the saturation indirectly.
520
+ */
521
+ markCircuitOpen(key: string): void;
522
+ /** Destroy the limiter, reject queued waiters, clear timers, and drop state. */
523
+ destroy(): void;
524
+ /** Alias for destroy(), useful for graceful shutdown code paths. */
525
+ shutdown(): void;
526
+ private getOrCreateState;
527
+ private makeLease;
528
+ private recordAndAdjust;
529
+ private tryWarmup;
530
+ private baselineLatency;
531
+ private lowLatencySample;
532
+ private isErrorSignal;
533
+ private combineGradientWithErrors;
534
+ private windowPercentile;
535
+ private recordSaturation;
536
+ private applyLimit;
537
+ private recordLimitChange;
538
+ private resolveHeadroom;
539
+ private nextProbeInterval;
540
+ private enqueueWaiter;
541
+ private dequeueWaiter;
542
+ private tryEvictLowerPriorityWaiter;
543
+ private suggestedBackoffMs;
544
+ private drain;
545
+ private currentLatency;
546
+ private touch;
547
+ private scheduleIdleEviction;
548
+ private clearIdleTimer;
549
+ private evictIdleStates;
550
+ private evictIdleState;
551
+ private cleanupWaiter;
552
+ private removeWaiter;
553
+ private stateToStats;
554
+ private stateToKeySnapshot;
555
+ }
556
+
557
+ type ValidationError = {
558
+ readonly _tag: "ValidationError";
559
+ readonly message: string;
560
+ readonly body: string;
561
+ readonly issues: readonly SchemaIssue[];
562
+ readonly phase?: "request" | "response";
563
+ readonly schema?: string;
564
+ };
565
+ type JsonDecodeResult<A> = {
566
+ readonly success: true;
567
+ readonly data: A;
568
+ } | {
569
+ readonly success: false;
570
+ readonly error: ValidationError;
571
+ };
572
+ declare function makeJsonParseValidationError(bodyText: string, error: unknown, options?: {
573
+ readonly schemaName?: string;
574
+ }): ValidationError;
575
+ declare function decodeJsonBody<A = unknown>(bodyText: string, validator?: JsonSchemaLike<A>, options?: {
576
+ readonly schemaName?: string;
577
+ }): JsonDecodeResult<A>;
578
+ declare function encodeJsonBodyEffect(bodyObj: unknown, validator?: JsonSchemaLike<any>, options?: {
579
+ readonly schemaName?: string;
580
+ }): Async<unknown, ValidationError, string>;
581
+ declare function decodeJsonBodyEffect<A = unknown>(bodyText: string, validator?: JsonSchemaLike<A>, options?: {
582
+ readonly schemaName?: string;
583
+ }): Async<unknown, ValidationError, A>;
584
+ declare function validatedJson<A>(client: HttpClientFn, validator: JsonSchemaLike<A>): (req: Parameters<HttpClientFn>[0]) => Async<unknown, HttpError | ValidationError, A>;
585
+ declare function validatedJsonResponse<A>(client: HttpClientFn, validator: JsonSchemaLike<A>): (req: Parameters<HttpClientFn>[0]) => Async<unknown, HttpError | ValidationError, HttpWireResponse & {
586
+ readonly body: A;
587
+ }>;
588
+
589
+ type KnownHttpError = HttpError | ValidationError | CircuitBreakerError;
590
+ type KnownHttpErrorTag = KnownHttpError["_tag"];
591
+ type ToHttpErrorOptions = {
592
+ readonly signal?: AbortSignal;
593
+ readonly timeoutMs?: number;
594
+ readonly phase?: "request" | "queue" | "retry";
595
+ readonly message?: string | ((error: unknown) => string);
596
+ };
597
+ type RetryableHttpErrorOptions = {
598
+ readonly retryOnStatus?: (status: number) => boolean;
599
+ };
600
+ type HttpErrorHandlers<R> = {
601
+ readonly [K in KnownHttpErrorTag]?: (error: Extract<KnownHttpError, {
602
+ readonly _tag: K;
603
+ }>) => R;
604
+ } & {
605
+ readonly default?: (error: unknown) => R;
606
+ };
607
+ declare function isHttpError(error: unknown): error is HttpError;
608
+ declare function isValidationError(error: unknown): error is ValidationError;
609
+ declare function isCircuitBreakerOpen(error: unknown): error is CircuitBreakerError;
610
+ declare function isKnownHttpError(error: unknown): error is KnownHttpError;
611
+ declare function isAbortHttpError(error: unknown): error is Extract<HttpError, {
612
+ readonly _tag: "Abort";
613
+ }>;
614
+ declare function isTimeoutHttpError(error: unknown): error is Extract<HttpError, {
615
+ readonly _tag: "Timeout" | "PoolTimeout";
616
+ }>;
617
+ declare function isFetchHttpError(error: unknown): error is Extract<HttpError, {
618
+ readonly _tag: "FetchError";
619
+ }>;
620
+ declare function httpErrorStatus(error: unknown): number | undefined;
621
+ declare function isRetryableHttpStatus(status: number): boolean;
622
+ declare function isRetryableHttpError(error: unknown, options?: RetryableHttpErrorOptions): boolean;
623
+ declare function isExternalAbortError(error: unknown): boolean;
624
+ declare function isExternalTimeoutError(error: unknown): boolean;
625
+ declare function toHttpError(error: unknown, options?: ToHttpErrorOptions): HttpError;
626
+ declare function matchHttpError<R>(error: unknown, handlers: HttpErrorHandlers<R>): R | undefined;
627
+ declare function formatHttpError(error: unknown): string;
628
+
629
+ type HttpTransportContext = {
630
+ readonly request: HttpRequest;
631
+ readonly url: URL;
632
+ readonly signal: AbortSignal;
633
+ };
634
+ type HttpTransport = (context: HttpTransportContext) => Async<unknown, HttpError, HttpWireResponse>;
635
+ type HttpStreamTransport = (context: HttpTransportContext) => Async<unknown, HttpError, HttpWireResponseStream>;
636
+ type HttpTransportTiming = {
637
+ readonly startedAt: number;
638
+ readonly durationMs: number;
639
+ };
640
+ type PromiseHttpTransportResponse = Omit<HttpWireResponse, "ms"> & {
641
+ readonly ms?: number;
642
+ };
643
+ type PromiseHttpTransportConfig<Response> = {
644
+ readonly request: (context: HttpTransportContext) => Promise<Response>;
645
+ readonly response: (response: Response, context: HttpTransportContext, timing: HttpTransportTiming) => PromiseHttpTransportResponse | Promise<PromiseHttpTransportResponse>;
646
+ readonly error?: (error: unknown, context: HttpTransportContext) => HttpError;
647
+ };
648
+ type PromiseHttpTransportResponseInfo<Meta = unknown> = {
649
+ readonly status?: number;
650
+ readonly statusText?: string;
651
+ readonly headers?: unknown;
652
+ readonly ms?: number;
653
+ readonly transportMeta?: Meta;
654
+ };
655
+ type PromiseHttpTransportResponseInfoMapper<Response, Meta = unknown> = (response: Response, context: HttpTransportContext, timing: HttpTransportTiming) => PromiseHttpTransportResponseInfo<Meta> | Promise<PromiseHttpTransportResponseInfo<Meta>>;
656
+ type PromiseHttpTransportBodySelector<Response, Body = unknown> = (response: Response, context: HttpTransportContext, timing: HttpTransportTiming) => Body | Promise<Body>;
657
+ type PromiseHttpTransportRequestConfigContext = Omit<HttpTransportContext, "signal">;
658
+ type PromiseHttpTransportRequestConfigMapper<Config> = (context: PromiseHttpTransportRequestConfigContext) => Config | Promise<Config>;
659
+ type PromiseHttpTransportConfigWithSignal<Config> = Config extends object ? Config & {
660
+ readonly signal: AbortSignal;
661
+ } : Config;
662
+ type PromiseHttpTransportRequestConfigBuilder<Config> = {
663
+ readonly send: <Response>(send: (config: PromiseHttpTransportConfigWithSignal<Config>) => Promise<Response>) => PromiseHttpTransportBodyBuilder<Response>;
664
+ };
665
+ type PromiseHttpTransportFluentResponseBuilder<Response> = {
666
+ readonly response: (response?: PromiseHttpTransportResponseInfoMapper<Response>) => HttpTransport;
667
+ readonly error: (error: NonNullable<PromiseHttpTransportConfig<Response>["error"]>) => PromiseHttpTransportFluentResponseBuilder<Response>;
668
+ };
669
+ type PromiseHttpTransportBodyBuilder<Response> = {
670
+ readonly response: (response: PromiseHttpTransportConfig<Response>["response"]) => HttpTransport;
671
+ readonly json: <Body = unknown>(body?: PromiseHttpTransportBodySelector<Response, Body>, response?: PromiseHttpTransportResponseInfoMapper<Response>) => HttpTransport;
672
+ readonly text: (body?: PromiseHttpTransportBodySelector<Response, unknown>, response?: PromiseHttpTransportResponseInfoMapper<Response>) => HttpTransport;
673
+ readonly fromJson: <Body = unknown>(body?: PromiseHttpTransportBodySelector<Response, Body>) => PromiseHttpTransportFluentResponseBuilder<Response>;
674
+ readonly fromText: (body?: PromiseHttpTransportBodySelector<Response, unknown>) => PromiseHttpTransportFluentResponseBuilder<Response>;
675
+ readonly error: (error: NonNullable<PromiseHttpTransportConfig<Response>["error"]>) => PromiseHttpTransportBodyBuilder<Response>;
676
+ };
677
+ type PromiseHttpTransportStartBuilder = {
678
+ readonly request: <Response>(request: PromiseHttpTransportConfig<Response>["request"]) => PromiseHttpTransportBodyBuilder<Response>;
679
+ readonly requestConfig: <Config>(request: PromiseHttpTransportRequestConfigMapper<Config>) => PromiseHttpTransportRequestConfigBuilder<Config>;
680
+ };
681
+ declare const isTaggedHttpError: (error: unknown) => error is HttpError;
682
+ declare const isAbortError: (error: unknown) => boolean;
683
+ declare const normalizeHttpError: (error: unknown, options?: ToHttpErrorOptions) => HttpError;
684
+ declare const headersOf: (response: Response) => Record<string, string>;
685
+ declare function normalizeHttpHeaders(headers: unknown): Record<string, string>;
686
+ declare const abortErrorForSignal: (signal: AbortSignal) => HttpError;
687
+ declare const linkAbortSignals: (...signals: readonly (AbortSignal | undefined)[]) => {
688
+ signal: AbortSignal;
689
+ cleanup: () => void;
690
+ };
691
+ declare function makePromiseHttpTransport<Response>(config: PromiseHttpTransportConfig<Response>): HttpTransport;
692
+ declare function promiseHttpTransport(): PromiseHttpTransportStartBuilder;
693
+ declare function makeFetchTransport(): HttpTransport;
694
+ declare function makeFetchStreamTransport(): HttpStreamTransport;
695
+
696
+ type HttpError = {
697
+ _tag: "Abort";
698
+ } | {
699
+ _tag: "BadUrl";
700
+ message: string;
701
+ } | {
702
+ _tag: "FetchError";
703
+ message: string;
704
+ code?: string;
705
+ status?: number;
706
+ statusText?: string;
707
+ retryAfterMs?: number;
708
+ cause?: unknown;
709
+ } | {
710
+ _tag: "Timeout";
711
+ timeoutMs: number;
712
+ message: string;
713
+ phase?: "request" | "queue" | "retry";
714
+ } | {
715
+ _tag: "PoolRejected";
716
+ key: string;
717
+ limit: number;
718
+ message: string;
719
+ retryAfterMs?: number;
720
+ } | {
721
+ _tag: "PoolTimeout";
722
+ key: string;
723
+ timeoutMs: number;
724
+ message: string;
725
+ } | {
726
+ _tag: "PoolClosed";
727
+ key: string;
728
+ message: string;
729
+ } | {
730
+ _tag: "BatchSplitError";
731
+ expected: number;
732
+ actual: number;
733
+ message: string;
734
+ };
735
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
736
+ type HttpInit = Omit<RequestInit, "method" | "body" | "headers">;
737
+ type HttpBody = string | Uint8Array | ArrayBuffer;
738
+ type HttpRequest = {
739
+ method: HttpMethod;
740
+ url: string;
741
+ headers?: Record<string, string>;
742
+ body?: HttpBody;
743
+ init?: HttpInit;
744
+ /** Structured per-request execution policy. Legacy top-level fields are still read. */
745
+ policy?: HttpRequestPolicyRef;
746
+ /** Per-request override for `MakeHttpConfig.timeoutMs`. */
747
+ timeoutMs?: number;
748
+ /** Optional stable key for downstream isolation. When omitted, the pool uses origin/host/global config. */
749
+ poolKey?: string;
750
+ /** @deprecated Use `policy.lane`. Kept for middleware interop. */
751
+ lane?: string;
752
+ /** @deprecated Use `policy.dedupKey`. Kept for middleware interop. */
753
+ dedupKey?: string;
754
+ /** @deprecated Use `policy.priority`. Kept for middleware interop. */
755
+ priority?: number;
756
+ /** @deprecated Use `policy.retry`. Kept for middleware interop. */
757
+ retry?: HttpRequestRetryOverride;
758
+ };
759
+ type HttpWireResponse<Meta = unknown> = {
760
+ status: number;
761
+ statusText: string;
762
+ headers: Record<string, string>;
763
+ bodyText: string;
764
+ ms: number;
765
+ transportMeta?: Meta;
766
+ };
767
+ type HttpClientStats = {
768
+ readonly inFlight: number;
769
+ readonly started: number;
770
+ readonly succeeded: number;
771
+ readonly failed: number;
772
+ readonly aborted: number;
773
+ readonly timedOut: number;
774
+ readonly poolRejected: number;
775
+ readonly poolTimeouts: number;
776
+ readonly lastDurationMs?: number;
777
+ readonly pool?: HttpPoolStats;
778
+ readonly adaptiveLimiter?: AdaptiveLimiterStats;
779
+ };
780
+ type MakeHttpConfig = {
781
+ baseUrl?: string;
782
+ headers?: Record<string, string>;
783
+ /** Request budget covering pool wait + fetch + body read. Disabled when omitted. */
784
+ timeoutMs?: number;
785
+ /** Effect-based transport. Defaults to `fetch`; provide one for axios/undici/test transports. */
786
+ transport?: HttpTransport;
787
+ /** Effect-based streaming transport. Defaults to `fetch` streaming. */
788
+ streamTransport?: HttpStreamTransport;
789
+ /** Downstream pool/concurrency limiter. Disabled by default to preserve existing behavior. */
790
+ pool?: false | HttpPoolConfig;
791
+ /** Adaptive concurrency limiter. Replaces fixed pool when enabled. */
792
+ adaptiveLimiter?: false | AdaptiveLimiterConfig;
793
+ };
794
+ type HttpWireResponseStream<Meta = unknown> = {
795
+ status: number;
796
+ statusText: string;
797
+ headers: Record<string, string>;
798
+ body: ZStream<unknown, HttpError, Uint8Array>;
799
+ ms: number;
800
+ transportMeta?: Meta;
801
+ };
802
+ type HttpClientStreamFn = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponseStream>;
803
+ type HttpClientStream = HttpClientStreamFn & {
804
+ stats: () => HttpClientStats;
805
+ };
806
+ type HttpClientFn = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponse>;
807
+ type HttpMiddleware = (next: HttpClientFn) => HttpClientFn;
808
+ type HttpClient = HttpClientFn & {
809
+ with: (mw: HttpMiddleware) => HttpClient;
810
+ stats: () => HttpClientStats;
811
+ adaptiveLimiter?: AdaptiveLimiter;
812
+ destroy?: () => void;
813
+ shutdown?: () => void;
814
+ };
815
+ type HttpClientMetadata = Pick<HttpClient, "adaptiveLimiter" | "destroy" | "shutdown">;
816
+ declare const decorate: (run: HttpClientFn, stats?: () => HttpClientStats, metadata?: HttpClientMetadata) => HttpClient;
817
+ declare const withMiddleware: (mw: HttpMiddleware) => (c: HttpClient) => HttpClient;
818
+ declare const normalizeHeadersInit: (h: any) => Record<string, string> | undefined;
819
+ declare function makeHttpStream(cfg?: MakeHttpConfig): HttpClientStream;
820
+ declare function makeHttp(cfg?: MakeHttpConfig): HttpClient;
821
+ declare const withRetryStream: (p: RetryPolicy) => (next: HttpClientStream) => HttpClientStream;
822
+
823
+ /**
824
+ * Developer-provided function that defines how to combine multiple requests
825
+ * into one and split the response back.
826
+ *
827
+ * @typeParam K - The item type extracted from individual requests, ensuring
828
+ * type consistency between coalesce and split.
829
+ */
830
+ type BatchFunction<K> = {
831
+ /**
832
+ * Combines multiple HttpRequest objects into a single batched HttpRequest.
833
+ * The items array corresponds 1:1 with the requests array.
834
+ */
835
+ coalesce: (requests: readonly HttpRequest[]) => HttpRequest;
836
+ /**
837
+ * Splits the batched response back into individual responses.
838
+ * Must return an array of the same length as the original requests array.
839
+ */
840
+ split: (response: HttpWireResponse, requests: readonly HttpRequest[]) => HttpWireResponse[];
841
+ };
842
+ /**
843
+ * Configuration for the Batch_Middleware.
844
+ *
845
+ * @typeParam K - The item type linking coalesce and split operations.
846
+ */
847
+ type BatchConfig<K = unknown> = {
848
+ /** The batch function defining coalesce/split logic. Required. */
849
+ batch: BatchFunction<K>;
850
+ /**
851
+ * Time window in milliseconds to collect requests before dispatching.
852
+ * Valid range: [1, 5000]. Required.
853
+ */
854
+ windowMs: number;
855
+ /**
856
+ * Maximum number of requests in a single batch.
857
+ * When reached, the batch dispatches immediately.
858
+ * Valid range: [2, 10000]. Required.
859
+ */
860
+ maxBatchSize: number;
861
+ /**
862
+ * Computes the Batch_Key from a request.
863
+ * Requests with the same key are batched together.
864
+ * Return empty string to bypass batching for a request.
865
+ * Throwing bypasses batching for that request.
866
+ */
867
+ batchKey: (req: HttpRequest) => string;
868
+ };
869
+ /**
870
+ * Optional observer callback for batch lifecycle events.
871
+ */
872
+ type BatchEventCallback = (event: {
873
+ type: "batch-hit" | "batch-dispatch";
874
+ batchKey: string;
875
+ batchSize?: number;
876
+ }) => void;
877
+ /**
878
+ * Creates a Batch_Middleware that collects requests by Batch_Key during
879
+ * a time window and dispatches them as a single batched request.
880
+ *
881
+ * @typeParam K - Inferred from the provided BatchFunction.
882
+ * @param config - Batch configuration.
883
+ * @param onEvent - Optional lifecycle event observer.
884
+ * @returns An HttpMiddleware conforming to (next: HttpClientFn) => HttpClientFn.
885
+ */
886
+ declare function withBatch<K>(config: BatchConfig<K>, onEvent?: BatchEventCallback): HttpMiddleware;
887
+
888
+ /**
889
+ * Status of a pre-warm probe result.
890
+ */
891
+ type PrewarmResultStatus = "warmed" | "already-warm" | "failed" | "cancelled";
892
+ /**
893
+ * Result of a single pre-warm probe operation.
894
+ */
895
+ type PrewarmResult = {
896
+ /** The origin that was probed. */
897
+ origin: string;
898
+ /** Outcome of the probe operation. */
899
+ status: PrewarmResultStatus;
900
+ /** Duration of the probe in milliseconds (0 for "already-warm"). */
901
+ durationMs: number;
902
+ /** Error information if status is "failed". */
903
+ error?: string;
904
+ };
905
+ /**
906
+ * Event types emitted by the PrewarmManager during connection state changes.
907
+ */
908
+ type PrewarmEventType = "connection-warmed" | "connection-expired" | "connection-failed" | "connection-cancelled";
909
+ /**
910
+ * An event emitted by the PrewarmManager to notify observers of connection state changes.
911
+ */
912
+ type PrewarmEvent = {
913
+ /** The type of prewarm event. */
914
+ type: PrewarmEventType;
915
+ /** The origin associated with the event. */
916
+ origin: string;
917
+ /** Timestamp (ms) when the event occurred. */
918
+ timestamp: number;
919
+ /** Duration of the probe in milliseconds, if applicable. */
920
+ durationMs?: number;
921
+ /** Error information, if applicable. */
922
+ error?: string;
923
+ };
924
+ /**
925
+ * Per-origin connection state in the state machine.
926
+ */
927
+ type PrewarmOriginStatus = "idle" | "probing" | "warm" | "expired";
928
+ /**
929
+ * State information for a single managed origin.
930
+ */
931
+ type PrewarmOriginState = {
932
+ /** The origin string. */
933
+ origin: string;
934
+ /** Current state of the origin. */
935
+ status: PrewarmOriginStatus;
936
+ /** Timestamp of the last successful probe, if any. */
937
+ lastProbeAt?: number;
938
+ /** Timestamp until which the connection is considered warm. */
939
+ warmUntil?: number;
940
+ };
941
+ /**
942
+ * Snapshot of all managed origins and their current states.
943
+ */
944
+ type PrewarmStatusSnapshot = {
945
+ /** State of each managed origin. */
946
+ origins: PrewarmOriginState[];
947
+ };
948
+ /**
949
+ * Configuration for creating a PrewarmManager.
950
+ */
951
+ type PrewarmConfig = {
952
+ /** Origins to pre-warm. Each must be a valid URL origin (scheme + host + optional port). */
953
+ origins: string[];
954
+ /** Keep-alive duration in ms. Default: 55000. */
955
+ keepAliveDurationMs?: number;
956
+ /** Max concurrent in-flight probes. Default: 4. */
957
+ budget?: number;
958
+ /** Probe timeout in ms. Default: 5000. */
959
+ probeTimeoutMs?: number;
960
+ /** Auto-refresh expired connections. Default: false. */
961
+ autoRefresh?: boolean;
962
+ /** Route probes through the Wire_Client pool. Default: false. */
963
+ useClientPool?: boolean;
964
+ /** Optional Wire_Client to use when useClientPool is true. */
965
+ client?: HttpClientFn;
966
+ /** Event observer callback. */
967
+ onEvent?: (event: PrewarmEvent) => void;
968
+ };
969
+
970
+ /**
971
+ * Configuration for the prewarm layer within the lifecycle client.
972
+ *
973
+ * When provided to `makeLifecycleClient`, the lifecycle client creates and manages
974
+ * a PrewarmManager internally, triggering pre-warming based on the `afterResponse` hook.
975
+ */
976
+ type PrewarmLifecycleConfig = {
977
+ /** Origins to pre-warm at client creation. */
978
+ origins?: string[];
979
+ /** Hook called after each successful response to determine origins to pre-warm. */
980
+ afterResponse?: (response: HttpWireResponse, request: HttpRequest) => string[];
981
+ /** Keep-alive duration in ms. Default: 55000. */
982
+ keepAliveDurationMs?: number;
983
+ /** Max concurrent in-flight probes. Default: 4. */
984
+ budget?: number;
985
+ /** Probe timeout in ms. Default: 5000. */
986
+ probeTimeoutMs?: number;
987
+ /** Auto-refresh expired connections. Default: false. */
988
+ autoRefresh?: boolean;
989
+ /** Route probes through the Wire_Client pool. Default: false. */
990
+ useClientPool?: boolean;
991
+ /** Event observer for prewarm events. */
992
+ onEvent?: (event: PrewarmEvent) => void;
993
+ };
994
+ /**
995
+ * Configuration for the deduplication layer.
996
+ *
997
+ * When enabled, the dedup layer collapses concurrent identical requests into a single
998
+ * in-flight Async_Effect, sharing the response across all callers with the same Cache_Key.
999
+ *
1000
+ * @property {function} [dedupKey] - Custom key function that computes a dedup key from an HttpRequest.
1001
+ * When provided, overrides the default Cache_Key computation. Default: undefined (uses default key derivation).
1002
+ */
1003
+ type DedupConfig = {
1004
+ /** Custom key function. When provided, overrides default Cache_Key computation. */
1005
+ dedupKey?: (req: HttpRequest) => string;
1006
+ /** Internal lifecycle observer. Public callers should prefer LifecycleClientConfig.onEvent. */
1007
+ onEvent?: (event: {
1008
+ type: "dedup-hit" | "dedup-miss" | "dedup-active";
1009
+ cacheKey?: string;
1010
+ active?: number;
1011
+ }) => void;
1012
+ };
1013
+ /**
1014
+ * Configuration for the response cache layer.
1015
+ *
1016
+ * Controls how responses are stored and retrieved from the in-memory LRU cache.
1017
+ * Each cached entry is keyed by its deterministic Cache_Key.
1018
+ *
1019
+ * @property {number} [ttlSeconds] - Time-to-live in seconds for cached entries. Default: 60. Valid range: [1, 86400].
1020
+ * @property {number} [maxEntries] - Maximum number of cached entries before LRU eviction. Default: 1024. Valid range: >= 1.
1021
+ * @property {boolean} [staleWhileRevalidate] - When true, serves stale cache entries while revalidating in the background. Default: false.
1022
+ * @property {function} [cachePolicy] - Custom cache policy function that determines cacheability and optional TTL override for a given request/response pair. Default: undefined (uses built-in policy).
1023
+ * @property {string[]} [cacheRelevantHeaders] - Additional HTTP headers to include in Cache_Key computation beyond the defaults. Default: undefined (uses DEFAULT_CACHE_RELEVANT_HEADERS).
1024
+ */
1025
+ type CacheConfig = {
1026
+ /** Time-to-live in seconds. Default: 60. Range: [1, 86400]. */
1027
+ ttlSeconds?: number;
1028
+ /** Maximum number of cached entries. Default: 1024. Minimum: 1. */
1029
+ maxEntries?: number;
1030
+ /** Enable stale-while-revalidate. Default: false. */
1031
+ staleWhileRevalidate?: boolean;
1032
+ /** Custom cache policy function. */
1033
+ cachePolicy?: (req: HttpRequest, res: HttpWireResponse) => CachePolicyResult;
1034
+ /** Additional headers to include in Cache_Key computation. */
1035
+ cacheRelevantHeaders?: string[];
1036
+ /** Cache-specific observer for stale revalidation failures. */
1037
+ onEvent?: (event: {
1038
+ type: string;
1039
+ cacheKey?: string;
1040
+ error?: any;
1041
+ }) => void;
1042
+ /** Internal lifecycle observer. Public callers should prefer LifecycleClientConfig.onEvent. */
1043
+ onLifecycleEvent?: (event: {
1044
+ type: "cache-hit" | "cache-miss" | "cache-eviction";
1045
+ cacheKey?: string;
1046
+ count?: number;
1047
+ }) => void;
1048
+ };
1049
+ /**
1050
+ * Result of a custom cache policy evaluation.
1051
+ *
1052
+ * Returned by the `cachePolicy` function in {@link CacheConfig} to control
1053
+ * whether a response should be stored in the cache and for how long.
1054
+ *
1055
+ * @property {boolean} cacheable - Whether the response should be cached. Required.
1056
+ * @property {number} [ttlSeconds] - Optional TTL override in seconds. When provided, takes precedence over the global CacheConfig ttlSeconds. Valid range: [1, 86400].
1057
+ */
1058
+ type CachePolicyResult = {
1059
+ /** Whether the response should be cached. */
1060
+ cacheable: boolean;
1061
+ /** Optional TTL override in seconds. */
1062
+ ttlSeconds?: number;
1063
+ };
1064
+ /**
1065
+ * Configuration for the priority scheduler layer.
1066
+ *
1067
+ * The priority scheduler orders outgoing requests by priority level and limits
1068
+ * concurrency to prevent overwhelming the downstream Wire_Client.
1069
+ *
1070
+ * @property {number} [concurrency] - Maximum concurrent requests dispatched by the priority scheduler. Default: 32. Valid range: >= 1.
1071
+ * @property {number} [queueTimeoutMs] - Queue timeout in milliseconds for priority-queued requests. When a request waits longer than this value, it is rejected. Default: undefined (no timeout).
1072
+ */
1073
+ type PriorityConfig = {
1074
+ /** Maximum concurrent requests dispatched by the priority scheduler. Default: 32. Valid range: >= 1. */
1075
+ concurrency?: number;
1076
+ /** Queue timeout in ms for priority-queued requests. Default: no timeout. */
1077
+ queueTimeoutMs?: number;
1078
+ /** Internal lifecycle observer. Public callers should prefer LifecycleClientConfig.onEvent. */
1079
+ onEvent?: (event: {
1080
+ type: "queue-enqueue" | "queue-dispatch";
1081
+ priority: number;
1082
+ }) => void;
1083
+ };
1084
+ /**
1085
+ * Configuration for creating a lifecycle client.
1086
+ *
1087
+ * Extends MakeHttpConfig with optional lifecycle layer configurations.
1088
+ * Each layer (dedup, cache, priority) can be configured with an options object
1089
+ * or explicitly disabled by setting it to `false`. When omitted, the layer is disabled
1090
+ * (zero-cost when disabled).
1091
+ *
1092
+ * @property {DedupConfig | false} [dedup] - Dedup layer configuration. Set to an object to enable with options, or `false` to explicitly disable. Default: undefined (disabled).
1093
+ * @property {CacheConfig | false} [cache] - Cache layer configuration. Set to an object to enable with options, or `false` to explicitly disable. Default: undefined (disabled).
1094
+ * @property {PriorityConfig | false} [priority] - Priority scheduler configuration. Set to an object to enable with options, or `false` to explicitly disable. Default: undefined (disabled).
1095
+ * @property {function} [onEvent] - Optional event observer callback invoked for each {@link LifecycleEvent} during request processing. Default: undefined.
1096
+ */
1097
+ type LifecycleClientConfig = MakeHttpConfig & {
1098
+ /** Dedup layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1099
+ dedup?: DedupConfig | false;
1100
+ /** Batch layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1101
+ batch?: BatchConfig | false;
1102
+ /** Cache layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1103
+ cache?: CacheConfig | false;
1104
+ /** Priority scheduler config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1105
+ priority?: PriorityConfig | false;
1106
+ /** Retry policy. Set to `false` to explicitly disable. Default: undefined (disabled). */
1107
+ retry?: RetryPolicy | false;
1108
+ /** Prewarm layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1109
+ prewarm?: PrewarmLifecycleConfig | false;
1110
+ /** Adaptive concurrency limiter config. Set to `false` to explicitly disable. Default: undefined (disabled). */
1111
+ adaptiveLimiter?: AdaptiveLimiterConfig | false;
1112
+ /** Optional event observer for lifecycle events. */
1113
+ onEvent?: (event: LifecycleEvent) => void;
1114
+ };
1115
+ /**
1116
+ * The lifecycle client interface.
1117
+ *
1118
+ * A callable HTTP client function (Wire_Client wrapper) with additional lifecycle
1119
+ * management methods. Supports middleware composition via `.with()`, statistics
1120
+ * via `.stats()`, and bulk cancellation via `.cancelAll()`.
1121
+ *
1122
+ * @property {function} with - Apply middleware, returning a new LifecycleClient with the middleware applied.
1123
+ * @property {function} stats - Return a frozen snapshot of {@link LifecycleStats}.
1124
+ * @property {function} cancelAll - Cancel all in-flight and queued requests, returning an Async_Effect that resolves when cancellation is complete.
1125
+ * @property {object} cache - Cache management methods for manual invalidation.
1126
+ * @property {function} cache.invalidate - Invalidate a specific cache entry by its Cache_Key.
1127
+ * @property {function} cache.clear - Clear all cache entries.
1128
+ */
1129
+ type LifecycleClient = HttpClientFn & {
1130
+ /** Apply middleware, returning a new LifecycleClient with the middleware applied. */
1131
+ with: (mw: HttpMiddleware) => LifecycleClient;
1132
+ /** Return a frozen snapshot of lifecycle statistics. */
1133
+ stats: () => LifecycleStats;
1134
+ /** Cancel all in-flight and queued requests. Returns an Async_Effect that resolves when complete. */
1135
+ cancelAll: () => Async<unknown, never, void>;
1136
+ /** Cancel active work and release owned resources such as adaptive limiter timers. */
1137
+ shutdown: () => Async<unknown, never, void>;
1138
+ /** Adaptive limiter owned by the underlying wire client, when enabled. */
1139
+ adaptiveLimiter?: AdaptiveLimiter;
1140
+ /** Cache management methods. */
1141
+ cache: {
1142
+ /** Invalidate a specific cache entry by Cache_Key. */
1143
+ invalidate: (key: string) => void;
1144
+ /** Clear all cache entries. */
1145
+ clear: () => void;
1146
+ };
1147
+ };
1148
+ /**
1149
+ * Lifecycle event types emitted during request processing.
1150
+ *
1151
+ * Each value represents a distinct point in the lifecycle pipeline:
1152
+ * - `"request-start"` — Emitted when a request enters the lifecycle pipeline.
1153
+ * - `"request-end"` — Emitted when a request completes (success or failure).
1154
+ * - `"cache-hit"` — Emitted when a response is served from the cache.
1155
+ * - `"cache-miss"` — Emitted when a request misses the cache and proceeds to the Wire_Client.
1156
+ * - `"dedup-hit"` — Emitted when a request is collapsed into an existing in-flight Async_Effect.
1157
+ * - `"dedup-miss"` — Emitted when a request initiates a new in-flight Async_Effect (no existing match).
1158
+ * - `"queue-enqueue"` — Emitted when a request is enqueued in the priority scheduler.
1159
+ * - `"queue-dispatch"` — Emitted when a queued request is dispatched to the Wire_Client.
1160
+ * - `"retry"` — Emitted when the retry middleware schedules another attempt.
1161
+ */
1162
+ type LifecycleEventType = "request-start" | "request-end" | "cache-hit" | "cache-miss" | "dedup-hit" | "dedup-miss" | "queue-enqueue" | "queue-dispatch" | "retry" | "batch-hit" | "batch-dispatch" | "limit-change";
1163
+ /**
1164
+ * A lifecycle event emitted to the onEvent observer.
1165
+ *
1166
+ * Provides observability into the lifecycle pipeline by reporting events
1167
+ * as they occur during request processing.
1168
+ *
1169
+ * @property {LifecycleEventType} type - The type of lifecycle event. Required.
1170
+ * @property {number} timestamp - Timestamp in milliseconds (from `Date.now()`) when the event occurred. Required.
1171
+ * @property {string} [cacheKey] - The Cache_Key associated with the event, if applicable (present for cache and dedup events).
1172
+ * @property {number} [priority] - Priority level associated with the event, if applicable (present for queue events). Valid range: 0-9.
1173
+ * @property {number} [attempt] - Zero-based retry attempt, if applicable.
1174
+ * @property {number} [delayMs] - Retry delay in milliseconds, if applicable.
1175
+ * @property {number} [status] - HTTP status that triggered retry, if applicable.
1176
+ * @property {string} [errorTag] - HttpError tag that triggered retry, if applicable.
1177
+ */
1178
+ type LifecycleEvent = {
1179
+ /** The type of lifecycle event. */
1180
+ type: LifecycleEventType;
1181
+ /** Timestamp (ms) when the event occurred. */
1182
+ timestamp: number;
1183
+ /** Cache_Key associated with the event, if applicable. */
1184
+ cacheKey?: string;
1185
+ /** Priority level associated with the event, if applicable. Valid range: 0-9. */
1186
+ priority?: number;
1187
+ /** Batch_Key associated with the event, if applicable. Present for batch events. */
1188
+ batchKey?: string;
1189
+ /** Number of requests in the batch, if applicable. Present for batch-dispatch events. */
1190
+ batchSize?: number;
1191
+ /** Zero-based retry attempt, if applicable. */
1192
+ attempt?: number;
1193
+ /** Retry delay in milliseconds, if applicable. */
1194
+ delayMs?: number;
1195
+ /** HTTP status that triggered retry, if applicable. */
1196
+ status?: number;
1197
+ /** HttpError tag that triggered retry, if applicable. */
1198
+ errorTag?: string;
1199
+ /** Previous concurrency limit, present for limit-change events. */
1200
+ previousLimit?: number;
1201
+ /** New concurrency limit, present for limit-change events. */
1202
+ newLimit?: number;
1203
+ /** Gradient value, present for limit-change events. */
1204
+ gradient?: number;
1205
+ /** Smoothed latency value, present for limit-change events. */
1206
+ smoothedLatency?: number;
1207
+ };
1208
+ /**
1209
+ * Lifecycle statistics snapshot.
1210
+ *
1211
+ * All counters start at zero and increase monotonically. Returned as a frozen
1212
+ * object by {@link LifecycleClient.stats}.
1213
+ *
1214
+ * @property {number} cacheHits - Number of cache hits (responses served from cache). Default: 0.
1215
+ * @property {number} cacheMisses - Number of cache misses (requests forwarded to Wire_Client). Default: 0.
1216
+ * @property {number} cacheEvictions - Number of cache evictions triggered by LRU policy. Default: 0.
1217
+ * @property {number} dedupHits - Number of dedup hits (requests collapsed into an existing in-flight Async_Effect). Default: 0.
1218
+ * @property {number} dedupActive - Number of currently active dedup groups (in-flight unique Cache_Keys). Default: 0.
1219
+ * @property {number} queueDepth - Current depth of the priority queue (requests waiting to be dispatched). Default: 0.
1220
+ * @property {number} requestsStarted - Total number of requests that entered the lifecycle pipeline. Default: 0.
1221
+ * @property {number} requestsCompleted - Total number of requests that completed successfully. Default: 0.
1222
+ * @property {number} requestsFailed - Total number of requests that failed with an error. Default: 0.
1223
+ * @property {number} retries - Total number of retry attempts scheduled. Default: 0.
1224
+ * @property {HttpClientStats} wire - Underlying Wire_Client statistics snapshot.
1225
+ */
1226
+ type LifecycleStats = {
1227
+ /** Number of cache hits. */
1228
+ cacheHits: number;
1229
+ /** Number of cache misses. */
1230
+ cacheMisses: number;
1231
+ /** Number of cache evictions (LRU). */
1232
+ cacheEvictions: number;
1233
+ /** Number of dedup hits (requests collapsed into existing in-flight Async_Effect). */
1234
+ dedupHits: number;
1235
+ /** Number of currently active dedup groups. */
1236
+ dedupActive: number;
1237
+ /** Current depth of the priority queue. */
1238
+ queueDepth: number;
1239
+ /** Total number of requests started. */
1240
+ requestsStarted: number;
1241
+ /** Total number of requests completed successfully. */
1242
+ requestsCompleted: number;
1243
+ /** Total number of requests that failed. */
1244
+ requestsFailed: number;
1245
+ /** Total number of retry attempts scheduled. */
1246
+ retries: number;
1247
+ /** Total number of batch dispatches. */
1248
+ batchDispatches: number;
1249
+ /** Total number of individual requests that were coalesced into batches. */
1250
+ batchedRequests: number;
1251
+ /** Underlying Wire_Client stats. */
1252
+ wire: HttpClientStats;
1253
+ };
1254
+ /**
1255
+ * Per-request lifecycle options that can be passed alongside a request.
1256
+ *
1257
+ * Allows fine-grained control over lifecycle behavior on a per-request basis,
1258
+ * overriding the client-level configuration for individual requests.
1259
+ *
1260
+ * @property {number} [priority] - Priority level for this request. Valid range: 0-9 (0 = highest priority). Default: 5.
1261
+ * @property {string} [dedupKey] - Custom dedup key override for this request. When provided, overrides the computed Cache_Key for dedup purposes. Default: undefined.
1262
+ * @property {boolean} [noCache] - When true, bypasses the cache layer for this request (neither reads from nor writes to cache). Default: false.
1263
+ * @property {boolean} [noDedup] - When true, bypasses the dedup layer for this request (always creates a new in-flight Async_Effect). Default: false.
1264
+ */
1265
+ type LifecycleRequestOptions = {
1266
+ /** Priority level 0-9 (0 = highest). Default: 5. Valid range: 0-9. */
1267
+ priority?: number;
1268
+ /** Custom dedup key override for this request. */
1269
+ dedupKey?: string;
1270
+ /** Skip cache for this request. Default: false. */
1271
+ noCache?: boolean;
1272
+ /** Skip dedup for this request. Default: false. */
1273
+ noDedup?: boolean;
1274
+ };
1275
+
1276
+ /**
1277
+ * Supported content encoding algorithms.
1278
+ */
1279
+ type SupportedEncoding = "gzip" | "br" | "deflate";
1280
+ /**
1281
+ * All supported encodings in default preference order (Brotli first).
1282
+ */
1283
+ declare const SUPPORTED_ENCODINGS: readonly SupportedEncoding[];
1284
+ /**
1285
+ * Configuration for the compression middleware.
1286
+ */
1287
+ type CompressionConfig = {
1288
+ /**
1289
+ * Enabled encodings in preference order.
1290
+ * Default: ["br", "gzip", "deflate"]
1291
+ */
1292
+ encodings?: SupportedEncoding[];
1293
+ };
1294
+ type RequestCompressionConfig = {
1295
+ /**
1296
+ * Encoding to apply to outbound request bodies.
1297
+ * Default: "gzip".
1298
+ */
1299
+ encoding?: SupportedEncoding;
1300
+ /**
1301
+ * Minimum uncompressed body size in bytes before compression is attempted.
1302
+ * Default: 1024.
1303
+ */
1304
+ minBytes?: number;
1305
+ /**
1306
+ * HTTP methods eligible for request compression.
1307
+ * Default: ["POST", "PUT", "PATCH"].
1308
+ */
1309
+ methods?: readonly string[];
1310
+ };
1311
+ /**
1312
+ * Frozen snapshot of compression statistics.
1313
+ */
1314
+ type CompressionStats = {
1315
+ /** Responses decompressed per encoding type */
1316
+ readonly decompressed: Readonly<Record<SupportedEncoding, number>>;
1317
+ /** Total compressed bytes received */
1318
+ readonly compressedBytes: number;
1319
+ /** Total decompressed bytes produced */
1320
+ readonly decompressedBytes: number;
1321
+ /** Responses that bypassed decompression */
1322
+ readonly passthroughCount: number;
1323
+ /** Decompression errors encountered */
1324
+ readonly errorCount: number;
1325
+ /** Unsupported encoding warnings */
1326
+ readonly unsupportedEncodingCount: number;
1327
+ };
1328
+ type RequestCompressionStats = {
1329
+ readonly compressedCount: number;
1330
+ readonly skippedCount: number;
1331
+ readonly errorCount: number;
1332
+ readonly originalBytes: number;
1333
+ readonly compressedBytes: number;
1334
+ };
1335
+ /**
1336
+ * Result of a decompression attempt.
1337
+ */
1338
+ type DecompressResult = {
1339
+ ok: true;
1340
+ data: Buffer;
1341
+ } | {
1342
+ ok: false;
1343
+ error: string;
1344
+ };
1345
+ /**
1346
+ * Abstraction over zlib / noop decompression.
1347
+ */
1348
+ interface Decompressor {
1349
+ readonly isPassthrough: boolean;
1350
+ decompress(data: Buffer | Uint8Array, encoding: SupportedEncoding): DecompressResult;
1351
+ }
1352
+ /**
1353
+ * Result of makeCompressionMiddleware — the middleware plus a stats accessor.
1354
+ */
1355
+ type CompressionMiddlewareResult = {
1356
+ middleware: HttpMiddleware;
1357
+ stats: () => CompressionStats;
1358
+ };
1359
+ type RequestCompressionMiddlewareResult = {
1360
+ middleware: HttpMiddleware;
1361
+ stats: () => RequestCompressionStats;
1362
+ };
1363
+
1364
+ type HttpRequestPolicyInit = {
1365
+ readonly policy?: HttpRequestPolicyRef;
1366
+ readonly lane?: string;
1367
+ readonly dedupKey?: string;
1368
+ readonly priority?: number;
1369
+ readonly retry?: HttpRequestRetryOverride;
1370
+ };
1371
+
1372
+ type InitNoMethodBody$1 = Omit<RequestInit, "method" | "body"> & HttpRequestPolicyInit & {
1373
+ timeoutMs?: number;
1374
+ poolKey?: string;
1375
+ headers?: any;
1376
+ };
1377
+ type JsonInitNoSchema$1 = InitNoMethodBody$1 & {
1378
+ schema?: undefined;
1379
+ schemaName?: string;
1380
+ };
1381
+ type JsonInitWithSchema<Validator extends AnyJsonSchemaLike> = InitNoMethodBody$1 & {
1382
+ schema: Validator;
1383
+ schemaName?: string;
1384
+ };
1385
+ type PostJsonInitNoSchema$1 = AnyInitWithHeaders & {
1386
+ schema?: undefined;
1387
+ schemaName?: string;
1388
+ bodySchema?: undefined;
1389
+ bodySchemaName?: string;
1390
+ };
1391
+ type PostJsonInitWithBodySchema<BodyValidator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
1392
+ schema?: undefined;
1393
+ schemaName?: string;
1394
+ bodySchema: BodyValidator;
1395
+ bodySchemaName?: string;
1396
+ };
1397
+ type PostJsonInitWithSchema<Validator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
1398
+ schema: Validator;
1399
+ schemaName?: string;
1400
+ bodySchema?: undefined;
1401
+ bodySchemaName?: string;
1402
+ };
1403
+ type PostJsonInitWithSchemaAndBody<Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
1404
+ schema: Validator;
1405
+ schemaName?: string;
1406
+ bodySchema: BodyValidator;
1407
+ bodySchemaName?: string;
1408
+ };
1409
+ type AnyJsonInit = InitNoMethodBody$1 & {
1410
+ schema?: AnyJsonSchemaLike;
1411
+ schemaName?: string;
1412
+ };
1413
+ type HttpMeta = {
1414
+ request: HttpRequest;
1415
+ urlFinal: string;
1416
+ startedAt: number;
1417
+ durationMs: number;
1418
+ };
1419
+ type HttpResponse<A> = {
1420
+ status: number;
1421
+ statusText: string;
1422
+ headers: Record<string, string>;
1423
+ body: A;
1424
+ };
1425
+ type HttpWireWithMeta = {
1426
+ wire: HttpWireResponse;
1427
+ meta: HttpMeta;
1428
+ };
1429
+ type HttpResponseWithMeta<A> = {
1430
+ wire: HttpWireResponse;
1431
+ response: HttpResponse<A>;
1432
+ meta: HttpMeta;
1433
+ };
1434
+ type AnyInitWithHeaders = HttpRequestPolicyInit & {
1435
+ headers?: any;
1436
+ timeoutMs?: number;
1437
+ poolKey?: string;
1438
+ } & Record<string, any>;
1439
+ type Dx = {
1440
+ request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1441
+ get: (url: string, init?: AnyInitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1442
+ post: (url: string, body?: string, init?: AnyInitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1443
+ getText: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpResponse<string>>;
1444
+ getJson: {
1445
+ <Validator extends AnyJsonSchemaLike>(url: string, init: JsonInitWithSchema<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1446
+ <A = unknown>(url: string, init?: JsonInitNoSchema$1): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1447
+ };
1448
+ postJson: {
1449
+ <Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: PostJsonInitWithSchemaAndBody<Validator, BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1450
+ <BodyValidator extends AnyJsonSchemaLike, A = unknown>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: PostJsonInitWithBodySchema<BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1451
+ <Validator extends AnyJsonSchemaLike>(url: string, bodyObj: unknown, init: PostJsonInitWithSchema<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1452
+ <A = unknown>(url: string, bodyObj: unknown, init?: PostJsonInitNoSchema$1): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1453
+ };
1454
+ with: (mw: HttpMiddleware) => Dx;
1455
+ withRetry: (p: RetryPolicy) => Dx;
1456
+ wire: HttpClient;
1457
+ stats: () => ReturnType<HttpClient["stats"]>;
1458
+ };
1459
+ declare function httpClient(cfg?: MakeHttpConfig): Dx;
1460
+ declare function httpClientWithMeta(cfg?: MakeHttpConfig): {
1461
+ request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, {
1462
+ wire: HttpWireResponse<unknown>;
1463
+ meta: HttpMeta;
1464
+ }>;
1465
+ get: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
1466
+ wire: HttpWireResponse<unknown>;
1467
+ meta: HttpMeta;
1468
+ }>;
1469
+ getText: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
1470
+ wire: HttpWireResponse<unknown>;
1471
+ response: {
1472
+ status: number;
1473
+ statusText: string;
1474
+ headers: Record<string, string>;
1475
+ body: string;
1476
+ };
1477
+ meta: HttpMeta;
1478
+ }>;
1479
+ getJson: <A>(url: string, init?: AnyJsonInit) => AsyncWithPromise<unknown, HttpError | ValidationError, {
1480
+ wire: HttpWireResponse<unknown>;
1481
+ response: HttpResponse<A>;
1482
+ meta: HttpMeta;
1483
+ }>;
1484
+ post: (url: string, body?: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
1485
+ wire: HttpWireResponse<unknown>;
1486
+ meta: HttpMeta;
1487
+ }>;
1488
+ postJson: <A>(url: string, bodyObj: unknown, init?: AnyInitWithHeaders & {
1489
+ schema?: AnyJsonSchemaLike;
1490
+ schemaName?: string;
1491
+ bodySchema?: AnyJsonSchemaLike;
1492
+ bodySchemaName?: string;
1493
+ }) => AsyncWithPromise<unknown, HttpError | ValidationError, {
1494
+ wire: HttpWireResponse<unknown>;
1495
+ response: HttpResponse<A>;
1496
+ meta: HttpMeta;
1497
+ }>;
1498
+ };
1499
+ declare function httpClientStream(cfg?: MakeHttpConfig): {
1500
+ request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream<unknown>>;
1501
+ getStream: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream<unknown>>;
1502
+ get: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream<unknown>>;
1503
+ with: (mw: (n: HttpClientStream) => HttpClientStream) => /*elided*/ any;
1504
+ withRetry: (p: RetryPolicy) => /*elided*/ any;
1505
+ wire: HttpClientStream;
1506
+ stats: () => HttpClientStats;
1507
+ };
1508
+
1509
+ type InitNoMethodBody = Omit<RequestInit, "method" | "body"> & {
1510
+ timeoutMs?: number;
1511
+ poolKey?: string;
1512
+ headers?: unknown;
1513
+ } & HttpRequestPolicyInit;
1514
+ type InitWithHeaders = {
1515
+ headers?: unknown;
1516
+ timeoutMs?: number;
1517
+ poolKey?: string;
1518
+ } & HttpRequestPolicyInit & Record<string, unknown>;
1519
+ type HttpJsonInit<Validator extends AnyJsonSchemaLike> = InitNoMethodBody & {
1520
+ readonly schema: Validator;
1521
+ readonly schemaName?: string;
1522
+ };
1523
+ type HttpPostJsonInit<Validator extends AnyJsonSchemaLike> = InitWithHeaders & {
1524
+ readonly schema: Validator;
1525
+ readonly schemaName?: string;
1526
+ readonly bodySchema?: undefined;
1527
+ readonly bodySchemaName?: string;
1528
+ };
1529
+ type HttpPostJsonSchemaBodyInit<Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike> = InitWithHeaders & {
1530
+ readonly schema: Validator;
1531
+ readonly schemaName?: string;
1532
+ readonly bodySchema: BodyValidator;
1533
+ readonly bodySchemaName?: string;
1534
+ };
1535
+ type HttpPostJsonBodyInit<BodyValidator extends AnyJsonSchemaLike> = InitWithHeaders & {
1536
+ readonly schema?: undefined;
1537
+ readonly schemaName?: string;
1538
+ readonly bodySchema: BodyValidator;
1539
+ readonly bodySchemaName?: string;
1540
+ };
1541
+ type JsonInitNoSchema = InitNoMethodBody & {
1542
+ readonly schema?: undefined;
1543
+ readonly schemaName?: string;
1544
+ };
1545
+ type PostJsonInitNoSchema = InitWithHeaders & {
1546
+ readonly schema?: undefined;
1547
+ readonly schemaName?: string;
1548
+ readonly bodySchema?: undefined;
1549
+ readonly bodySchemaName?: string;
1550
+ };
1551
+ type DefaultGetJson = {
1552
+ <Validator extends AnyJsonSchemaLike>(url: string, init: HttpJsonInit<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1553
+ <A = unknown>(url: string, init?: JsonInitNoSchema): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1554
+ };
1555
+ type DefaultPostJson = {
1556
+ <Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: HttpPostJsonSchemaBodyInit<Validator, BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1557
+ <BodyValidator extends AnyJsonSchemaLike, A = unknown>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: HttpPostJsonBodyInit<BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1558
+ <Validator extends AnyJsonSchemaLike>(url: string, bodyObj: unknown, init: HttpPostJsonInit<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
1559
+ <A = unknown>(url: string, bodyObj: unknown, init?: PostJsonInitNoSchema): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
1560
+ };
1561
+ type DefaultHttpClientPreset = "minimal" | "proxy" | "highThroughputProxy" | "balanced" | "default" | "production";
1562
+ type DefaultHttpClientFeatures = {
1563
+ readonly dedup: boolean;
1564
+ readonly batch: boolean;
1565
+ readonly cache: boolean;
1566
+ readonly priority: boolean;
1567
+ readonly retry: boolean;
1568
+ readonly prewarm: boolean;
1569
+ readonly adaptiveLimiter: boolean;
1570
+ readonly compression: boolean;
1571
+ readonly middleware: number;
1572
+ };
1573
+ type DefaultHttpClientConfig = LifecycleClientConfig & {
1574
+ /**
1575
+ * Preset used as the baseline before caller overrides are applied.
1576
+ * - minimal: wire client + timeout only.
1577
+ * - proxy: low-latency proxy/BFF path; wire client only, no lifecycle queue or Brass timeout by default.
1578
+ * - highThroughputProxy: explicit alias for the hot proxy path; pair with makeNodeHttpProxyClient on Node.
1579
+ * - balanced: retry, priority, dedup, adaptive limiter, response compression.
1580
+ * - default: balanced + short safe-method response cache.
1581
+ * - production: stable alias for the full production-ready default preset.
1582
+ */
1583
+ readonly preset?: DefaultHttpClientPreset;
1584
+ /** Response decompression. Enabled by balanced/default presets; set false to disable. */
1585
+ readonly compression?: CompressionConfig | false;
1586
+ /** Extra middleware applied outermost after the preset stack, e.g. withHttpObservability(obs). */
1587
+ readonly middleware?: readonly HttpMiddleware[];
1588
+ /**
1589
+ * Named per-request policy presets. Requests can use `policy: "readModel"` or
1590
+ * `policy: { preset: "readModel", ...overrides }`.
1591
+ */
1592
+ readonly policyPresets?: HttpPolicyPresets;
1593
+ };
1594
+ type DefaultHttpClient = {
1595
+ readonly request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1596
+ readonly get: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1597
+ readonly post: (url: string, body?: string, init?: InitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
1598
+ readonly getText: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpResponse<string>>;
1599
+ readonly getJson: DefaultGetJson;
1600
+ readonly postJson: DefaultPostJson;
1601
+ readonly with: (mw: HttpMiddleware) => DefaultHttpClient;
1602
+ readonly wire: LifecycleClient;
1603
+ readonly stats: () => LifecycleStats;
1604
+ readonly cache: LifecycleClient["cache"];
1605
+ readonly cancelAll: LifecycleClient["cancelAll"];
1606
+ readonly shutdown: LifecycleClient["shutdown"];
1607
+ readonly preset: DefaultHttpClientPreset;
1608
+ readonly features: DefaultHttpClientFeatures;
1609
+ readonly compression?: {
1610
+ readonly stats: () => CompressionStats;
1611
+ };
1612
+ };
1613
+ declare const defaultHttpClientPreset: DefaultHttpClientPreset;
1614
+ /**
1615
+ * Creates the recommended default HTTP client.
1616
+ *
1617
+ * The returned client has the easy JSON/text helpers from `httpClient`, but its
1618
+ * wire path is the full lifecycle stack: priority, retry, cache, batch, dedup,
1619
+ * adaptive concurrency, optional prewarm, compression, stats, and cancelAll.
1620
+ */
1621
+ declare function makeDefaultHttpClient(config?: DefaultHttpClientConfig): DefaultHttpClient;
1622
+
1623
+ export { type DefaultHttpClientFeatures as $, type AdaptiveLimiterStats as A, type BatchConfig as B, type CompressionConfig as C, type DefaultHttpClient as D, type AdaptiveLimiterPreset as E, type HttpPoolConfig as F, type AdaptiveAcquireOptions as G, type HttpRequest as H, type AdaptiveBaselineStrategy as I, type AdaptiveHeadroomContext as J, type AdaptiveHeadroomMode as K, type LifecycleClientConfig as L, type AdaptiveHeadroomStrategy as M, type AdaptiveLease as N, type AdaptiveLimiterDiagnostics as O, type PrewarmResult as P, type AdaptiveLimiterKeySnapshot as Q, type RequestCompressionConfig as R, type AdaptiveQueueLoadShedding as S, type AdaptiveQueueStrategy as T, type AdaptiveReleaseInfo as U, type BatchFunction as V, type CachePolicyResult as W, type CompressionStats as X, type DecompressResult as Y, type Decompressor as Z, type DefaultGetJson as _, type HttpClient as a, abortErrorForSignal as a$, type DefaultPostJson as a0, type Dx as a1, type HttpBody as a2, type HttpClientStream as a3, type HttpClientStreamFn as a4, HttpConcurrencyPool as a5, type HttpErrorHandlers as a6, type HttpInit as a7, type HttpJsonInit as a8, type HttpMeta as a9, type PerRequestRetryOverride as aA, type PrewarmEvent as aB, type PrewarmEventType as aC, type PrewarmOriginStatus as aD, type PrewarmResultStatus as aE, type PromiseHttpTransportBodyBuilder as aF, type PromiseHttpTransportBodySelector as aG, type PromiseHttpTransportConfig as aH, type PromiseHttpTransportConfigWithSignal as aI, type PromiseHttpTransportFluentResponseBuilder as aJ, type PromiseHttpTransportRequestConfigBuilder as aK, type PromiseHttpTransportRequestConfigContext as aL, type PromiseHttpTransportRequestConfigMapper as aM, type PromiseHttpTransportResponse as aN, type PromiseHttpTransportResponseInfo as aO, type PromiseHttpTransportResponseInfoMapper as aP, type PromiseHttpTransportStartBuilder as aQ, type RequestCompressionStats as aR, type ResolveHttpRequestPolicyOptions as aS, type ResolvedConfig as aT, type RetryEvent as aU, type RetryScheduleInput as aV, type RetryableHttpErrorOptions as aW, SUPPORTED_ENCODINGS as aX, type SupportedEncoding as aY, type ToHttpErrorOptions as aZ, type ValidationError as a_, type HttpPolicyPreset as aa, type HttpPolicyPresets as ab, type HttpPoolKeyResolver as ac, type HttpPoolKeyStats as ad, type HttpPoolLease as ae, type HttpPoolStats as af, type HttpPostJsonBodyInit as ag, type HttpPostJsonInit as ah, type HttpPostJsonSchemaBodyInit as ai, type HttpRequestPolicy as aj, type HttpRequestPolicyRef as ak, type HttpRequestRetryOverride as al, type HttpResponse as am, type HttpResponseWithMeta as an, type HttpRetryScheduleInput as ao, type HttpStreamTransport as ap, type HttpTransportContext as aq, type HttpTransportTiming as ar, type HttpWireResponseStream as as, type HttpWireWithMeta as at, type JsonDecodeResult as au, type KnownHttpError as av, type KnownHttpErrorTag as aw, type LifecycleRequestOptions as ax, type LimitChangeEvent as ay, type MakeHttpConfig as az, type HttpWireResponse as b, adaptiveLimiterPresets as b0, backoffDelayMs as b1, decodeJsonBody as b2, decodeJsonBodyEffect as b3, decorate as b4, defaultHttpClientPreset as b5, defaultRetryOnError as b6, defaultRetryOnStatus as b7, defaultRetryableMethods as b8, defineHttpPolicyPresets as b9, makeFetchTransport as bA, makeHttp as bB, makeHttpStream as bC, makeJsonParseValidationError as bD, makePromiseHttpTransport as bE, matchHttpError as bF, normalizeHeadersInit as bG, normalizeHttpError as bH, normalizeHttpHeaders as bI, normalizeRetryBudget as bJ, promiseHttpTransport as bK, resolveConfig as bL, resolveHttpPoolKey as bM, resolveHttpRequestPolicyPresets as bN, retryAfterMs as bO, toHttpError as bP, validateConfig as bQ, validatedJson as bR, validatedJsonResponse as bS, withBatch as bT, withHttpPolicyPresets as bU, withHttpRequestPolicy as bV, withMiddleware as bW, withRetry as bX, withRetryStream as bY, encodeJsonBodyEffect as ba, formatHttpError as bb, getHttpRequestPolicy as bc, headersOf as bd, httpClient as be, httpClientStream as bf, httpClientWithMeta as bg, httpErrorStatus as bh, httpPolicy as bi, isAbortError as bj, isAbortHttpError as bk, isCircuitBreakerOpen as bl, isExternalAbortError as bm, isExternalTimeoutError as bn, isFetchHttpError as bo, isHttpError as bp, isKnownHttpError as bq, isRetryableHttpError as br, isRetryableHttpStatus as bs, isTaggedHttpError as bt, isTimeoutHttpError as bu, isValidationError as bv, linkAbortSignals as bw, makeAdaptiveLimiterConfig as bx, makeDefaultHttpClient as by, makeFetchStreamTransport as bz, type HttpError as c, type HttpMiddleware as d, type DefaultHttpClientConfig as e, type CompressionMiddlewareResult as f, type RequestCompressionMiddlewareResult as g, type HttpTransport as h, AdaptiveLimiter as i, type LifecycleClient as j, type LifecycleEvent as k, type HttpClientStats as l, type LifecycleEventType as m, type LifecycleStats as n, type PrewarmStatusSnapshot as o, type PrewarmConfig as p, type HttpClientFn as q, type PrewarmOriginState as r, type HttpMethod as s, type DefaultHttpClientPreset as t, type DedupConfig as u, type CacheConfig as v, type PriorityConfig as w, type RetryPolicy as x, type PrewarmLifecycleConfig as y, type AdaptiveLimiterConfig as z };