brass-runtime 1.15.0 → 1.16.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 (93) hide show
  1. package/README.md +409 -137
  2. package/dist/agent/cli/main.cjs +40 -35
  3. package/dist/agent/cli/main.js +9 -4
  4. package/dist/agent/cli/main.mjs +9 -4
  5. package/dist/agent/index.cjs +8 -4
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +7 -3
  8. package/dist/agent/index.mjs +7 -3
  9. package/dist/{chunk-PPUXIH5R.js → chunk-2WC63LJK.mjs} +11 -7
  10. package/dist/chunk-3RG5ZIWI.js +10 -0
  11. package/dist/chunk-45F7OKGT.cjs +104 -0
  12. package/dist/chunk-5YOQOXEQ.cjs +2491 -0
  13. package/dist/{chunk-STVLQ3XD.cjs → chunk-7HUOJA4W.cjs} +78 -74
  14. package/dist/{chunk-BMH5AV44.js → chunk-7LVI2GIN.js} +251 -370
  15. package/dist/chunk-7TL2LHQJ.js +2491 -0
  16. package/dist/chunk-7V4KY4RL.mjs +104 -0
  17. package/dist/chunk-7XOPAB5Q.js +2143 -0
  18. package/dist/chunk-CCKHV5BT.mjs +193 -0
  19. package/dist/{chunk-AR22SXML.js → chunk-CY33PGEX.mjs} +488 -421
  20. package/dist/chunk-DJQ7OMMB.cjs +144 -0
  21. package/dist/chunk-F5EUMJL7.mjs +2143 -0
  22. package/dist/chunk-FM4W4QPL.js +193 -0
  23. package/dist/{chunk-TO7IKXYT.js → chunk-G3XGCZDQ.js} +1 -1
  24. package/dist/{chunk-BDF4AMWX.mjs → chunk-G6IQOE4P.mjs} +251 -370
  25. package/dist/chunk-GOV47PPB.mjs +552 -0
  26. package/dist/chunk-H55LI6WY.js +93 -0
  27. package/dist/chunk-IJT6RRQ5.cjs +93 -0
  28. package/dist/{chunk-ELOOF35R.mjs → chunk-J3H54ZRV.mjs} +1 -1
  29. package/dist/chunk-JF4XXPZ5.cjs +552 -0
  30. package/dist/chunk-JNFRRJYH.cjs +2143 -0
  31. package/dist/chunk-JX3LZQJH.cjs +354 -0
  32. package/dist/chunk-K2T3DV26.mjs +93 -0
  33. package/dist/chunk-KCPT2D6G.js +552 -0
  34. package/dist/chunk-MWXMNYJS.cjs +1110 -0
  35. package/dist/{chunk-VEZNF5GZ.cjs → chunk-N6VHMOWB.cjs} +130 -126
  36. package/dist/{chunk-3QMOKAS5.js → chunk-NC5SDRYE.js} +9 -5
  37. package/dist/chunk-NOYZIMUJ.mjs +144 -0
  38. package/dist/{chunk-R3R2FVLG.cjs → chunk-NYL4D7SK.cjs} +5 -5
  39. package/dist/chunk-OBGZSXTJ.cjs +10 -0
  40. package/dist/{chunk-4NHES7VK.mjs → chunk-OOGJ73B6.js} +11 -7
  41. package/dist/chunk-PNVFW245.js +144 -0
  42. package/dist/chunk-PRWCB3QL.mjs +2491 -0
  43. package/dist/{chunk-JFPU5GQI.mjs → chunk-QY5FKYEQ.js} +488 -421
  44. package/dist/chunk-ROJC3NBJ.js +104 -0
  45. package/dist/chunk-SPUEME2B.cjs +343 -0
  46. package/dist/chunk-TDVMADDN.js +343 -0
  47. package/dist/chunk-TVN5I4U6.cjs +193 -0
  48. package/dist/chunk-U5KWK3PX.mjs +343 -0
  49. package/dist/chunk-VFIUZG7J.mjs +354 -0
  50. package/dist/{chunk-TGIFUAK4.cjs → chunk-WQ5QNU5R.cjs} +459 -578
  51. package/dist/chunk-XDZOO4L5.js +354 -0
  52. package/dist/chunk-Y6FXYEAI.mjs +10 -0
  53. package/dist/{chunk-K6M7MDZ4.mjs → chunk-ZGLD4TVZ.mjs} +9 -5
  54. package/dist/client-CtFmoDvM.d.ts +645 -0
  55. package/dist/core/index.cjs +72 -4
  56. package/dist/core/index.d.ts +92 -198
  57. package/dist/core/index.js +106 -38
  58. package/dist/core/index.mjs +106 -38
  59. package/dist/{effect-CMOQKX8y.d.ts → effect-CGNl5Rqp.d.ts} +107 -1
  60. package/dist/effectRunner-3ZHAD3LE.cjs +8 -0
  61. package/dist/effectRunner-A4CHJXJI.js +8 -0
  62. package/dist/effectRunner-OPUF6QRN.mjs +8 -0
  63. package/dist/http/index.cjs +2189 -1271
  64. package/dist/http/index.d.ts +830 -270
  65. package/dist/http/index.js +2008 -1090
  66. package/dist/http/index.mjs +2008 -1090
  67. package/dist/http/testing.cjs +159 -0
  68. package/dist/http/testing.d.ts +42 -0
  69. package/dist/http/testing.js +159 -0
  70. package/dist/http/testing.mjs +159 -0
  71. package/dist/index.cjs +246 -178
  72. package/dist/index.d.ts +9 -35
  73. package/dist/index.js +120 -52
  74. package/dist/index.mjs +120 -52
  75. package/dist/observability/index.cjs +677 -0
  76. package/dist/observability/index.d.ts +79 -0
  77. package/dist/observability/index.js +677 -0
  78. package/dist/observability/index.mjs +677 -0
  79. package/dist/schedule-Fque9Abz.d.ts +70 -0
  80. package/dist/schema/index.cjs +25 -0
  81. package/dist/schema/index.d.ts +177 -0
  82. package/dist/schema/index.js +25 -0
  83. package/dist/schema/index.mjs +25 -0
  84. package/dist/server-C8hDXA74.d.ts +674 -0
  85. package/dist/{stream-FQm9h4Mg.d.ts → stream-dvSs0QS5.d.ts} +1 -1
  86. package/dist/tracer-B5tRH9H7.d.ts +230 -0
  87. package/dist/tracing-Dt9S_6V8.d.ts +148 -0
  88. package/package.json +27 -1
  89. package/dist/chunk-BDYEENHT.js +0 -224
  90. package/dist/chunk-MS34J5LY.cjs +0 -224
  91. package/dist/chunk-UMAZLXAB.mjs +0 -224
  92. package/dist/chunk-XPZNXSVN.cjs +0 -1043
  93. package/dist/tracing-DNT9jEbr.d.ts +0 -106
@@ -1,242 +1,178 @@
1
- import { A as Async, t as AsyncWithPromise } from '../effect-CMOQKX8y.js';
2
- import { Z as ZStream } from '../stream-FQm9h4Mg.js';
3
- import { a as CircuitBreakerConfig, T as Tracer } from '../tracing-DNT9jEbr.js';
1
+ import { e as HttpClientFn, c as HttpError, b as HttpWireResponse, a as HttpRequest, d as HttpMiddleware, R as RetryPolicy, H as HttpClient, M as MakeHttpConfig, f as HttpWireResponseStream, g as HttpClientStream, h as HttpClientStats, i as AdaptiveLimiter, j as AdaptiveLimiterConfig, k as HttpMethod, l as AdaptiveLimiterPreset, m as HttpPoolConfig } from '../client-CtFmoDvM.js';
2
+ export { n as AdaptiveAcquireOptions, o as AdaptiveBaselineStrategy, p as AdaptiveHeadroomContext, q as AdaptiveHeadroomMode, r as AdaptiveHeadroomStrategy, s as AdaptiveLease, t as AdaptiveLimiterDiagnostics, u as AdaptiveLimiterKeySnapshot, A as AdaptiveLimiterStats, v as AdaptiveQueueLoadShedding, w as AdaptiveQueueStrategy, x as AdaptiveReleaseInfo, y as HttpBody, z as HttpClientStreamFn, B as HttpConcurrencyPool, C as HttpInit, D as HttpPoolKeyResolver, E as HttpPoolKeyStats, F as HttpPoolLease, G as HttpPoolStats, L as LimitChangeEvent, P as PerRequestRetryOverride, I as ResolvedConfig, J as RetryEvent, K as RetryScheduleInput, N as adaptiveLimiterPresets, O as backoffDelayMs, Q as decorate, S as defaultRetryOnError, T as defaultRetryOnStatus, U as defaultRetryableMethods, V as makeAdaptiveLimiterConfig, W as makeHttp, X as makeHttpStream, Y as normalizeHeadersInit, Z as normalizeRetryBudget, _ as resolveConfig, $ as resolveHttpPoolKey, a0 as retryAfterMs, a1 as validateConfig, a2 as withMiddleware, a3 as withRetry, a4 as withRetryStream } from '../client-CtFmoDvM.js';
3
+ import { A as Async, C as AsyncWithPromise, f as Runtime, h as RuntimeOptions } from '../effect-CGNl5Rqp.js';
4
+ import { SchemaIssue, JsonSchemaLike, AnyJsonSchemaLike, InferJsonSchema } from '../schema/index.js';
5
+ export { AnySchema, ConfigValidationError, InferObject, InferSchema, JsonValidator, JsonValidatorResult, NumberSchemaOptions, ObjectSchemaOptions, Schema, SchemaPathPart, SchemaResult, SchemaShape, SchemaValidationException, StringSchemaOptions, formatIssues, isSchema, makeSchemaIssue, parseConfig, s, schema, validateValue } from '../schema/index.js';
6
+ import { g as CircuitBreakerConfig, h as CircuitBreakerError } from '../tracer-B5tRH9H7.js';
7
+ import { T as Tracer, R as Resource } from '../tracing-Dt9S_6V8.js';
8
+ import { Server } from 'node:http';
9
+ import { AddressInfo } from 'node:net';
10
+ import { S as Schedule } from '../schedule-Fque9Abz.js';
11
+ import { O as Observability, p as HttpServerObservabilityOptions, Z as RuntimeHealthOptions } from '../server-C8hDXA74.js';
12
+ import '../stream-dvSs0QS5.js';
4
13
 
5
14
  /**
6
- * Observable event emitted on each retry attempt via the `onRetry` callback.
15
+ * A fixed-size circular buffer that stores latency samples and supports
16
+ * efficient min and percentile computation using the nearest-rank method.
17
+ *
18
+ * The ring preserves eviction order while `sorted` keeps an exact sorted view.
19
+ * Recording is O(windowSize) because it removes/inserts by binary search +
20
+ * splice, but percentile reads are O(1) and avoid sorting on every call.
7
21
  */
8
- type RetryEvent = {
9
- /** Zero-based attempt number (0 = first retry, not the initial request). */
10
- attempt: number;
11
- /** Computed delay in milliseconds before the next attempt. */
12
- delayMs: number;
13
- /** The error that triggered this retry, if the request failed with an HttpError. */
14
- error?: HttpError;
15
- /** The HTTP status code that triggered this retry, if the request returned a retryable status. */
16
- status?: number;
17
- /** The request URL. */
18
- url: string;
19
- /** The request HTTP method. */
20
- method: HttpMethod;
21
- /** Timestamp (ms since epoch) when the retry decision was made. */
22
- timestamp: number;
23
- };
24
- /**
25
- * Per-request retry override. Attached as `(req as any).retry`.
26
- * - `false` disables retry entirely for this request.
27
- * - A partial policy object merges with the middleware-level policy (per-request wins).
28
- */
29
- type PerRequestRetryOverride = false | {
30
- maxRetries?: number;
31
- baseDelayMs?: number;
32
- maxDelayMs?: number;
33
- retryOnStatus?: (status: number) => boolean;
34
- };
35
- type RetryPolicy = {
36
- maxRetries: number;
37
- baseDelayMs: number;
38
- maxDelayMs: number;
39
- /** Optional total retry budget, including request attempts and sleeps. */
40
- maxElapsedMs?: number;
41
- /** Defaults to true. When true, Retry-After is honored but capped by maxDelayMs/budget. */
42
- respectRetryAfter?: boolean;
43
- retryOnMethods?: HttpMethod[];
44
- retryOnStatus?: (status: number) => boolean;
45
- retryOnError?: (e: HttpError) => boolean;
46
- /** Strict engine selector for retry planning. Defaults to ts. */
47
- engine?: "ts" | "wasm";
48
- /** Back-compat knob: wasm=true maps to engine="wasm", wasm=false maps to engine="ts". */
49
- wasm?: boolean;
50
- /** Called synchronously before each retry delay begins. Zero overhead when omitted. */
51
- onRetry?: (event: RetryEvent) => void;
52
- };
53
- declare const defaultRetryableMethods: HttpMethod[];
54
- declare const defaultRetryOnStatus: (s: number) => s is 408 | 429 | 500 | 502 | 503 | 504;
55
- declare const defaultRetryOnError: (e: HttpError) => e is {
56
- _tag: "FetchError";
57
- message: string;
58
- } | {
59
- _tag: "Timeout";
60
- timeoutMs: number;
61
- message: string;
62
- phase?: "request" | "queue" | "retry";
63
- } | {
64
- _tag: "PoolTimeout";
65
- key: string;
66
- timeoutMs: number;
67
- message: string;
68
- };
69
- declare const backoffDelayMs: (attempt: number, base: number, cap: number) => number;
70
- declare const retryAfterMs: (headers: Record<string, string>) => number | undefined;
71
- declare const normalizeRetryBudget: (ms: number | undefined) => number | undefined;
72
- declare const withRetry: (p: RetryPolicy) => HttpMiddleware;
22
+ declare class LatencyWindow {
23
+ private readonly buffer;
24
+ private readonly sorted;
25
+ private readonly size;
26
+ private head;
27
+ private count;
28
+ constructor(size: number);
29
+ /**
30
+ * Record a latency sample. Discards non-positive, NaN, and Infinity values.
31
+ * Evicts the oldest sample when the buffer is full.
32
+ */
33
+ record(latencyMs: number): void;
34
+ /**
35
+ * Returns the minimum latency in the current window, or undefined if empty.
36
+ */
37
+ min(): number | undefined;
38
+ /**
39
+ * Computes the percentile using the nearest-rank method.
40
+ * Returns undefined if fewer than 2 samples are present.
41
+ * @param p - Percentile value in [0, 100]
42
+ */
43
+ percentile(p: number): number | undefined;
44
+ /**
45
+ * Computes a percentile where newer samples receive exponentially higher
46
+ * weight. A decay of 1 is identical to `percentile`; lower values adapt
47
+ * faster to recent latency shifts.
48
+ */
49
+ weightedPercentile(p: number, decay: number): number | undefined;
50
+ /** Number of samples currently in the window. */
51
+ get length(): number;
52
+ /** Maximum capacity of the window. */
53
+ get capacity(): number;
54
+ /** Returns a copy of the current samples (oldest to newest). */
55
+ samples(): number[];
56
+ private insertSorted;
57
+ private removeSorted;
58
+ private lowerBound;
59
+ }
73
60
 
74
- type HttpPoolKeyResolver = "global" | "origin" | "host" | ((req: HttpRequest, url: URL) => string);
75
- type HttpPoolConfig = {
76
- /** Max concurrent downstream calls per resolved key. */
77
- readonly concurrency?: number;
78
- /** Max queued waiters per key. `0` means fail fast when the pool is full. */
79
- readonly maxQueue?: number;
80
- /** Max time a request may wait for a pool slot before failing fast. */
81
- readonly queueTimeoutMs?: number;
82
- /** How to isolate pools. Default: `origin`; useful values: `global`, `host`, `origin`. */
83
- readonly key?: HttpPoolKeyResolver;
61
+ /**
62
+ * Exponential Moving Average computer.
63
+ * Smooths latency samples using the formula: ema = α * sample + (1 - α) * previous_ema
64
+ */
65
+ declare class EmaComputer {
66
+ private readonly alpha;
67
+ private current;
68
+ /**
69
+ * @param alpha - Smoothing factor in (0, 1]. Higher values weight recent samples more.
70
+ */
71
+ constructor(alpha: number);
84
72
  /**
85
- * Strict engine selector for permit governance. Defaults to ts.
86
- * - ts: TypeScript permit pool.
87
- * - wasm: require BrassWasmHttpPermitPool from wasm/pkg; never falls back.
73
+ * Update the EMA with a new sample and return the new EMA value.
74
+ * On the first sample, the EMA is initialized to that sample.
88
75
  */
89
- readonly engine?: "ts" | "wasm";
90
- /** Back-compat knob: wasm=true maps to engine="wasm", wasm=false maps to engine="ts". */
91
- readonly wasm?: boolean;
92
- };
93
- type HttpPoolKeyStats = {
94
- readonly key: string;
95
- readonly running: number;
96
- readonly queued: number;
97
- readonly concurrency: number;
98
- readonly maxQueue: number;
99
- readonly acquired: number;
100
- readonly released: number;
101
- readonly rejected: number;
102
- readonly queueTimeouts: number;
103
- readonly abortedWhileQueued: number;
104
- };
105
- type HttpPoolStats = {
106
- readonly running: number;
107
- readonly queued: number;
108
- readonly acquired: number;
109
- readonly released: number;
110
- readonly rejected: number;
111
- readonly queueTimeouts: number;
112
- readonly abortedWhileQueued: number;
113
- readonly wasm?: unknown;
114
- readonly keys: HttpPoolKeyStats[];
115
- };
116
- type HttpPoolLease = {
117
- readonly key: string;
118
- release: () => void;
119
- };
120
- declare function resolveHttpPoolKey(resolver: HttpPoolKeyResolver | undefined, req: HttpRequest, url: URL): string;
121
- declare class HttpConcurrencyPool {
122
- private readonly states;
123
- private readonly concurrency;
124
- private readonly maxQueue;
125
- private readonly queueTimeoutMs;
126
- readonly keyResolver: HttpPoolKeyResolver | undefined;
127
- private readonly wasm;
128
- private readonly wasmWaiters;
129
- private wasmTimer;
130
- private nextSubjectId;
131
- constructor(config?: HttpPoolConfig);
132
- acquire(key: string, signal: AbortSignal): Promise<HttpPoolLease>;
133
- stats(): HttpPoolStats;
134
- private acquireJs;
135
- private acquireWasm;
136
- private getState;
137
- private makeLease;
138
- private drain;
139
- private handleWasmGrants;
140
- private handleWasmTimeouts;
141
- private scheduleWasmTimeoutPump;
142
- private cleanupWaiter;
143
- private removeWaiter;
144
- private allocateSubjectId;
76
+ update(sample: number): number;
77
+ /** Returns the current EMA value, or undefined if no samples have been recorded. */
78
+ get value(): number | undefined;
79
+ /** Resets the EMA state. */
80
+ reset(): void;
145
81
  }
146
82
 
147
- type HttpError = {
148
- _tag: "Abort";
149
- } | {
150
- _tag: "BadUrl";
151
- message: string;
152
- } | {
153
- _tag: "FetchError";
154
- message: string;
155
- } | {
156
- _tag: "Timeout";
157
- timeoutMs: number;
158
- message: string;
159
- phase?: "request" | "queue" | "retry";
160
- } | {
161
- _tag: "PoolRejected";
162
- key: string;
163
- limit: number;
164
- message: string;
83
+ /**
84
+ * Computes the gradient as the ratio of minimum latency to current (smoothed) latency.
85
+ * A gradient < 1.0 indicates latency is increasing (saturation).
86
+ * A gradient >= 1.0 indicates latency is stable or decreasing.
87
+ */
88
+ declare function computeGradient(minLatency: number, currentLatency: number): number;
89
+ /**
90
+ * Computes the new concurrency limit based on the gradient.
91
+ *
92
+ * - If gradient < decreaseThreshold: decrease toward `currentLimit * gradient`
93
+ * - If gradient >= increaseThreshold: newLimit = currentLimit + headroom
94
+ * - Otherwise: hold the current limit
95
+ *
96
+ * Decreases are capped by `maxDecreaseRatio` so a single noisy latency sample
97
+ * cannot collapse concurrency.
98
+ *
99
+ * The result is clamped to [minBound, maxBound].
100
+ */
101
+ declare function computeNewLimit(currentLimit: number, gradient: number, headroom: number, minBound: number, maxBound: number, options?: {
102
+ readonly decreaseThreshold?: number;
103
+ readonly increaseThreshold?: number;
104
+ readonly maxDecreaseRatio?: number;
105
+ }): number;
106
+
107
+ type ValidationError = {
108
+ readonly _tag: "ValidationError";
109
+ readonly message: string;
110
+ readonly body: string;
111
+ readonly issues: readonly SchemaIssue[];
112
+ readonly phase?: "request" | "response";
113
+ readonly schema?: string;
114
+ };
115
+ type JsonDecodeResult<A> = {
116
+ readonly success: true;
117
+ readonly data: A;
165
118
  } | {
166
- _tag: "PoolTimeout";
167
- key: string;
168
- timeoutMs: number;
169
- message: string;
119
+ readonly success: false;
120
+ readonly error: ValidationError;
170
121
  };
171
- type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
172
- type HttpInit = Omit<RequestInit, "method" | "body" | "headers">;
173
- type HttpBody = string | Uint8Array | ArrayBuffer;
174
- type HttpRequest = {
175
- method: HttpMethod;
176
- url: string;
177
- headers?: Record<string, string>;
178
- body?: HttpBody;
179
- init?: HttpInit;
180
- /** Per-request override for `MakeHttpConfig.timeoutMs`. */
122
+ declare function decodeJsonBody<A = unknown>(bodyText: string, validator?: JsonSchemaLike<A>, options?: {
123
+ readonly schemaName?: string;
124
+ }): JsonDecodeResult<A>;
125
+ declare function encodeJsonBodyEffect(bodyObj: unknown, validator?: JsonSchemaLike<any>, options?: {
126
+ readonly schemaName?: string;
127
+ }): Async<unknown, ValidationError, string>;
128
+ declare function decodeJsonBodyEffect<A = unknown>(bodyText: string, validator?: JsonSchemaLike<A>, options?: {
129
+ readonly schemaName?: string;
130
+ }): Async<unknown, ValidationError, A>;
131
+ declare function validatedJson<A>(client: HttpClientFn, validator: JsonSchemaLike<A>): (req: Parameters<HttpClientFn>[0]) => Async<unknown, HttpError | ValidationError, A>;
132
+ declare function validatedJsonResponse<A>(client: HttpClientFn, validator: JsonSchemaLike<A>): (req: Parameters<HttpClientFn>[0]) => Async<unknown, HttpError | ValidationError, HttpWireResponse & {
133
+ readonly body: A;
134
+ }>;
135
+
136
+ type InitNoMethodBody$1 = Omit<RequestInit, "method" | "body"> & {
181
137
  timeoutMs?: number;
182
- /** Optional stable key for downstream isolation. When omitted, the pool uses origin/host/global config. */
183
138
  poolKey?: string;
139
+ headers?: any;
184
140
  };
185
- type HttpWireResponse = {
186
- status: number;
187
- statusText: string;
188
- headers: Record<string, string>;
189
- bodyText: string;
190
- ms: number;
141
+ type JsonInitNoSchema$1 = InitNoMethodBody$1 & {
142
+ schema?: undefined;
143
+ schemaName?: string;
191
144
  };
192
- type HttpClientStats = {
193
- readonly inFlight: number;
194
- readonly started: number;
195
- readonly succeeded: number;
196
- readonly failed: number;
197
- readonly aborted: number;
198
- readonly timedOut: number;
199
- readonly poolRejected: number;
200
- readonly poolTimeouts: number;
201
- readonly lastDurationMs?: number;
202
- readonly pool?: HttpPoolStats;
203
- };
204
- type MakeHttpConfig = {
205
- baseUrl?: string;
206
- headers?: Record<string, string>;
207
- /** Request budget covering pool wait + fetch + body read. Disabled when omitted. */
208
- timeoutMs?: number;
209
- /** Downstream pool/concurrency limiter. Disabled by default to preserve existing behavior. */
210
- pool?: false | HttpPoolConfig;
145
+ type JsonInitWithSchema<Validator extends AnyJsonSchemaLike> = InitNoMethodBody$1 & {
146
+ schema: Validator;
147
+ schemaName?: string;
211
148
  };
212
- type HttpWireResponseStream = {
213
- status: number;
214
- statusText: string;
215
- headers: Record<string, string>;
216
- body: ZStream<unknown, HttpError, Uint8Array>;
217
- ms: number;
149
+ type PostJsonInitNoSchema$1 = AnyInitWithHeaders & {
150
+ schema?: undefined;
151
+ schemaName?: string;
152
+ bodySchema?: undefined;
153
+ bodySchemaName?: string;
218
154
  };
219
- type HttpClientStreamFn = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponseStream>;
220
- type HttpClientStream = HttpClientStreamFn & {
221
- stats: () => HttpClientStats;
155
+ type PostJsonInitWithBodySchema<BodyValidator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
156
+ schema?: undefined;
157
+ schemaName?: string;
158
+ bodySchema: BodyValidator;
159
+ bodySchemaName?: string;
222
160
  };
223
- type HttpClientFn = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponse>;
224
- type HttpMiddleware = (next: HttpClientFn) => HttpClientFn;
225
- type HttpClient = HttpClientFn & {
226
- with: (mw: HttpMiddleware) => HttpClient;
227
- stats: () => HttpClientStats;
161
+ type PostJsonInitWithSchema<Validator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
162
+ schema: Validator;
163
+ schemaName?: string;
164
+ bodySchema?: undefined;
165
+ bodySchemaName?: string;
228
166
  };
229
- declare const decorate: (run: HttpClientFn, stats?: () => HttpClientStats) => HttpClient;
230
- declare const withMiddleware: (mw: HttpMiddleware) => (c: HttpClient) => HttpClient;
231
- declare const normalizeHeadersInit: (h: any) => Record<string, string> | undefined;
232
- declare function makeHttpStream(cfg?: MakeHttpConfig): HttpClientStream;
233
- declare function makeHttp(cfg?: MakeHttpConfig): HttpClient;
234
- declare const withRetryStream: (p: RetryPolicy) => (next: HttpClientStream) => HttpClientStream;
235
-
236
- type InitNoMethodBody = Omit<RequestInit, "method" | "body"> & {
237
- timeoutMs?: number;
238
- poolKey?: string;
239
- headers?: any;
167
+ type PostJsonInitWithSchemaAndBody<Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike> = AnyInitWithHeaders & {
168
+ schema: Validator;
169
+ schemaName?: string;
170
+ bodySchema: BodyValidator;
171
+ bodySchemaName?: string;
172
+ };
173
+ type AnyJsonInit = InitNoMethodBody$1 & {
174
+ schema?: AnyJsonSchemaLike;
175
+ schemaName?: string;
240
176
  };
241
177
  type HttpMeta = {
242
178
  request: HttpRequest;
@@ -268,9 +204,17 @@ type Dx = {
268
204
  request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
269
205
  get: (url: string, init?: AnyInitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
270
206
  post: (url: string, body?: string, init?: AnyInitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
271
- getText: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpResponse<string>>;
272
- getJson: <A>(url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpResponse<A>>;
273
- postJson: <A>(url: string, bodyObj: unknown, init?: AnyInitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpResponse<A>>;
207
+ getText: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpResponse<string>>;
208
+ getJson: {
209
+ <Validator extends AnyJsonSchemaLike>(url: string, init: JsonInitWithSchema<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
210
+ <A = unknown>(url: string, init?: JsonInitNoSchema$1): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
211
+ };
212
+ postJson: {
213
+ <Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: PostJsonInitWithSchemaAndBody<Validator, BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
214
+ <BodyValidator extends AnyJsonSchemaLike, A = unknown>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: PostJsonInitWithBodySchema<BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
215
+ <Validator extends AnyJsonSchemaLike>(url: string, bodyObj: unknown, init: PostJsonInitWithSchema<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
216
+ <A = unknown>(url: string, bodyObj: unknown, init?: PostJsonInitNoSchema$1): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
217
+ };
274
218
  with: (mw: HttpMiddleware) => Dx;
275
219
  withRetry: (p: RetryPolicy) => Dx;
276
220
  wire: HttpClient;
@@ -282,11 +226,11 @@ declare function httpClientWithMeta(cfg?: MakeHttpConfig): {
282
226
  wire: HttpWireResponse;
283
227
  meta: HttpMeta;
284
228
  }>;
285
- get: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, {
229
+ get: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
286
230
  wire: HttpWireResponse;
287
231
  meta: HttpMeta;
288
232
  }>;
289
- getText: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, {
233
+ getText: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
290
234
  wire: HttpWireResponse;
291
235
  response: {
292
236
  status: number;
@@ -296,37 +240,30 @@ declare function httpClientWithMeta(cfg?: MakeHttpConfig): {
296
240
  };
297
241
  meta: HttpMeta;
298
242
  }>;
299
- getJson: <A>(url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, {
243
+ getJson: <A>(url: string, init?: AnyJsonInit) => AsyncWithPromise<unknown, HttpError | ValidationError, {
300
244
  wire: HttpWireResponse;
301
- response: {
302
- status: number;
303
- statusText: string;
304
- headers: Record<string, string>;
305
- body: A;
306
- };
245
+ response: HttpResponse<A>;
307
246
  meta: HttpMeta;
308
247
  }>;
309
- post: (url: string, body?: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, {
248
+ post: (url: string, body?: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, {
310
249
  wire: HttpWireResponse;
311
250
  meta: HttpMeta;
312
251
  }>;
313
- postJson: <A>(url: string, bodyObj: unknown, init?: HttpInit & {
314
- headers?: Record<string, string>;
315
- }) => AsyncWithPromise<unknown, HttpError, {
252
+ postJson: <A>(url: string, bodyObj: unknown, init?: AnyInitWithHeaders & {
253
+ schema?: AnyJsonSchemaLike;
254
+ schemaName?: string;
255
+ bodySchema?: AnyJsonSchemaLike;
256
+ bodySchemaName?: string;
257
+ }) => AsyncWithPromise<unknown, HttpError | ValidationError, {
316
258
  wire: HttpWireResponse;
317
- response: {
318
- status: number;
319
- statusText: string;
320
- headers: Record<string, string>;
321
- body: A;
322
- };
259
+ response: HttpResponse<A>;
323
260
  meta: HttpMeta;
324
261
  }>;
325
262
  };
326
263
  declare function httpClientStream(cfg?: MakeHttpConfig): {
327
264
  request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream>;
328
- getStream: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream>;
329
- get: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream>;
265
+ getStream: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream>;
266
+ get: (url: string, init?: InitNoMethodBody$1) => AsyncWithPromise<unknown, HttpError, HttpWireResponseStream>;
330
267
  with: (mw: (n: HttpClientStream) => HttpClientStream) => /*elided*/ any;
331
268
  withRetry: (p: RetryPolicy) => /*elided*/ any;
332
269
  wire: HttpClientStream;
@@ -336,6 +273,10 @@ declare function httpClientStream(cfg?: MakeHttpConfig): {
336
273
  type HttpCircuitBreakerConfig = CircuitBreakerConfig & {
337
274
  /** Key resolver for per-origin circuit breakers. Default: per-origin. */
338
275
  perOrigin?: boolean;
276
+ /** Optional limiter to notify when this breaker is already/opened. Defaults to `next.adaptiveLimiter` when available. */
277
+ adaptiveLimiter?: Pick<AdaptiveLimiter, "keyResolver" | "markCircuitOpen">;
278
+ /** Optional resolver when the limiter key differs from the request URL origin/global fallback. */
279
+ adaptiveLimiterKey?: (req: HttpRequest) => string;
339
280
  };
340
281
  /**
341
282
  * HTTP middleware that wraps requests in a circuit breaker.
@@ -348,36 +289,193 @@ declare function withCircuitBreaker(config?: HttpCircuitBreakerConfig): HttpMidd
348
289
  */
349
290
  declare function withTracing(tracer: Tracer): HttpMiddleware;
350
291
 
351
- type ValidationError = {
352
- _tag: "ValidationError";
353
- message: string;
354
- body: string;
355
- schema?: string;
292
+ type KnownHttpError = HttpError | ValidationError | CircuitBreakerError;
293
+ type KnownHttpErrorTag = KnownHttpError["_tag"];
294
+ type HttpErrorHandlers<R> = {
295
+ readonly [K in KnownHttpErrorTag]?: (error: Extract<KnownHttpError, {
296
+ readonly _tag: K;
297
+ }>) => R;
298
+ } & {
299
+ readonly default?: (error: unknown) => R;
356
300
  };
357
- type JsonValidator<A> = (data: unknown) => {
358
- success: true;
359
- data: A;
360
- } | {
361
- success: false;
362
- error: string;
301
+ declare function isHttpError(error: unknown): error is HttpError;
302
+ declare function isValidationError(error: unknown): error is ValidationError;
303
+ declare function isCircuitBreakerOpen(error: unknown): error is CircuitBreakerError;
304
+ declare function isKnownHttpError(error: unknown): error is KnownHttpError;
305
+ declare function matchHttpError<R>(error: unknown, handlers: HttpErrorHandlers<R>): R | undefined;
306
+ declare function formatHttpError(error: unknown): string;
307
+
308
+ /**
309
+ * Developer-provided function that defines how to combine multiple requests
310
+ * into one and split the response back.
311
+ *
312
+ * @typeParam K - The item type extracted from individual requests, ensuring
313
+ * type consistency between coalesce and split.
314
+ */
315
+ type BatchFunction<K> = {
316
+ /**
317
+ * Combines multiple HttpRequest objects into a single batched HttpRequest.
318
+ * The items array corresponds 1:1 with the requests array.
319
+ */
320
+ coalesce: (requests: readonly HttpRequest[]) => HttpRequest;
321
+ /**
322
+ * Splits the batched response back into individual responses.
323
+ * Must return an array of the same length as the original requests array.
324
+ */
325
+ split: (response: HttpWireResponse, requests: readonly HttpRequest[]) => HttpWireResponse[];
363
326
  };
364
327
  /**
365
- * Creates a validated JSON getter that checks the response body against a schema.
328
+ * Configuration for the Batch_Middleware.
366
329
  *
367
- * Usage:
368
- * ```ts
369
- * const getUser = validatedJson<User>(client, (data) => {
370
- * if (typeof data === "object" && data !== null && "id" in data) {
371
- * return { success: true, data: data as User };
372
- * }
373
- * return { success: false, error: "Invalid user shape" };
374
- * });
330
+ * @typeParam K - The item type linking coalesce and split operations.
331
+ */
332
+ type BatchConfig<K = unknown> = {
333
+ /** The batch function defining coalesce/split logic. Required. */
334
+ batch: BatchFunction<K>;
335
+ /**
336
+ * Time window in milliseconds to collect requests before dispatching.
337
+ * Valid range: [1, 5000]. Required.
338
+ */
339
+ windowMs: number;
340
+ /**
341
+ * Maximum number of requests in a single batch.
342
+ * When reached, the batch dispatches immediately.
343
+ * Valid range: [2, 10000]. Required.
344
+ */
345
+ maxBatchSize: number;
346
+ /**
347
+ * Computes the Batch_Key from a request.
348
+ * Requests with the same key are batched together.
349
+ * Return empty string to bypass batching for a request.
350
+ * Throwing bypasses batching for that request.
351
+ */
352
+ batchKey: (req: HttpRequest) => string;
353
+ };
354
+ /**
355
+ * Optional observer callback for batch lifecycle events.
356
+ */
357
+ type BatchEventCallback = (event: {
358
+ type: "batch-hit" | "batch-dispatch";
359
+ batchKey: string;
360
+ batchSize?: number;
361
+ }) => void;
362
+ /**
363
+ * Creates a Batch_Middleware that collects requests by Batch_Key during
364
+ * a time window and dispatches them as a single batched request.
375
365
  *
376
- * const user = await run(getUser({ method: "GET", url: "/users/1" }));
377
- * ```
366
+ * @typeParam K - Inferred from the provided BatchFunction.
367
+ * @param config - Batch configuration.
368
+ * @param onEvent - Optional lifecycle event observer.
369
+ * @returns An HttpMiddleware conforming to (next: HttpClientFn) => HttpClientFn.
378
370
  */
379
- declare function validatedJson<A>(client: HttpClientFn, validator: JsonValidator<A>): (req: Parameters<HttpClientFn>[0]) => Async<unknown, HttpError | ValidationError, A>;
371
+ declare function withBatch<K>(config: BatchConfig<K>, onEvent?: BatchEventCallback): HttpMiddleware;
380
372
 
373
+ /**
374
+ * Status of a pre-warm probe result.
375
+ */
376
+ type PrewarmResultStatus = "warmed" | "already-warm" | "failed" | "cancelled";
377
+ /**
378
+ * Result of a single pre-warm probe operation.
379
+ */
380
+ type PrewarmResult = {
381
+ /** The origin that was probed. */
382
+ origin: string;
383
+ /** Outcome of the probe operation. */
384
+ status: PrewarmResultStatus;
385
+ /** Duration of the probe in milliseconds (0 for "already-warm"). */
386
+ durationMs: number;
387
+ /** Error information if status is "failed". */
388
+ error?: string;
389
+ };
390
+ /**
391
+ * Event types emitted by the PrewarmManager during connection state changes.
392
+ */
393
+ type PrewarmEventType = "connection-warmed" | "connection-expired" | "connection-failed" | "connection-cancelled";
394
+ /**
395
+ * An event emitted by the PrewarmManager to notify observers of connection state changes.
396
+ */
397
+ type PrewarmEvent = {
398
+ /** The type of prewarm event. */
399
+ type: PrewarmEventType;
400
+ /** The origin associated with the event. */
401
+ origin: string;
402
+ /** Timestamp (ms) when the event occurred. */
403
+ timestamp: number;
404
+ /** Duration of the probe in milliseconds, if applicable. */
405
+ durationMs?: number;
406
+ /** Error information, if applicable. */
407
+ error?: string;
408
+ };
409
+ /**
410
+ * Per-origin connection state in the state machine.
411
+ */
412
+ type PrewarmOriginStatus = "idle" | "probing" | "warm" | "expired";
413
+ /**
414
+ * State information for a single managed origin.
415
+ */
416
+ type PrewarmOriginState = {
417
+ /** The origin string. */
418
+ origin: string;
419
+ /** Current state of the origin. */
420
+ status: PrewarmOriginStatus;
421
+ /** Timestamp of the last successful probe, if any. */
422
+ lastProbeAt?: number;
423
+ /** Timestamp until which the connection is considered warm. */
424
+ warmUntil?: number;
425
+ };
426
+ /**
427
+ * Snapshot of all managed origins and their current states.
428
+ */
429
+ type PrewarmStatusSnapshot = {
430
+ /** State of each managed origin. */
431
+ origins: PrewarmOriginState[];
432
+ };
433
+ /**
434
+ * Configuration for creating a PrewarmManager.
435
+ */
436
+ type PrewarmConfig = {
437
+ /** Origins to pre-warm. Each must be a valid URL origin (scheme + host + optional port). */
438
+ origins: string[];
439
+ /** Keep-alive duration in ms. Default: 55000. */
440
+ keepAliveDurationMs?: number;
441
+ /** Max concurrent in-flight probes. Default: 4. */
442
+ budget?: number;
443
+ /** Probe timeout in ms. Default: 5000. */
444
+ probeTimeoutMs?: number;
445
+ /** Auto-refresh expired connections. Default: false. */
446
+ autoRefresh?: boolean;
447
+ /** Route probes through the Wire_Client pool. Default: false. */
448
+ useClientPool?: boolean;
449
+ /** Optional Wire_Client to use when useClientPool is true. */
450
+ client?: HttpClientFn;
451
+ /** Event observer callback. */
452
+ onEvent?: (event: PrewarmEvent) => void;
453
+ };
454
+
455
+ /**
456
+ * Configuration for the prewarm layer within the lifecycle client.
457
+ *
458
+ * When provided to `makeLifecycleClient`, the lifecycle client creates and manages
459
+ * a PrewarmManager internally, triggering pre-warming based on the `afterResponse` hook.
460
+ */
461
+ type PrewarmLifecycleConfig = {
462
+ /** Origins to pre-warm at client creation. */
463
+ origins?: string[];
464
+ /** Hook called after each successful response to determine origins to pre-warm. */
465
+ afterResponse?: (response: HttpWireResponse, request: HttpRequest) => string[];
466
+ /** Keep-alive duration in ms. Default: 55000. */
467
+ keepAliveDurationMs?: number;
468
+ /** Max concurrent in-flight probes. Default: 4. */
469
+ budget?: number;
470
+ /** Probe timeout in ms. Default: 5000. */
471
+ probeTimeoutMs?: number;
472
+ /** Auto-refresh expired connections. Default: false. */
473
+ autoRefresh?: boolean;
474
+ /** Route probes through the Wire_Client pool. Default: false. */
475
+ useClientPool?: boolean;
476
+ /** Event observer for prewarm events. */
477
+ onEvent?: (event: PrewarmEvent) => void;
478
+ };
381
479
  /**
382
480
  * Configuration for the deduplication layer.
383
481
  *
@@ -484,12 +582,18 @@ type PriorityConfig$1 = {
484
582
  type LifecycleClientConfig = MakeHttpConfig & {
485
583
  /** Dedup layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
486
584
  dedup?: DedupConfig$1 | false;
585
+ /** Batch layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
586
+ batch?: BatchConfig | false;
487
587
  /** Cache layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
488
588
  cache?: CacheConfig$1 | false;
489
589
  /** Priority scheduler config. Set to `false` to explicitly disable. Default: undefined (disabled). */
490
590
  priority?: PriorityConfig$1 | false;
491
591
  /** Retry policy. Set to `false` to explicitly disable. Default: undefined (disabled). */
492
592
  retry?: RetryPolicy | false;
593
+ /** Prewarm layer config. Set to `false` to explicitly disable. Default: undefined (disabled). */
594
+ prewarm?: PrewarmLifecycleConfig | false;
595
+ /** Adaptive concurrency limiter config. Set to `false` to explicitly disable. Default: undefined (disabled). */
596
+ adaptiveLimiter?: AdaptiveLimiterConfig | false;
493
597
  /** Optional event observer for lifecycle events. */
494
598
  onEvent?: (event: LifecycleEvent) => void;
495
599
  };
@@ -514,6 +618,10 @@ type LifecycleClient = HttpClientFn & {
514
618
  stats: () => LifecycleStats;
515
619
  /** Cancel all in-flight and queued requests. Returns an Async_Effect that resolves when complete. */
516
620
  cancelAll: () => Async<unknown, never, void>;
621
+ /** Cancel active work and release owned resources such as adaptive limiter timers. */
622
+ shutdown: () => Async<unknown, never, void>;
623
+ /** Adaptive limiter owned by the underlying wire client, when enabled. */
624
+ adaptiveLimiter?: AdaptiveLimiter;
517
625
  /** Cache management methods. */
518
626
  cache: {
519
627
  /** Invalidate a specific cache entry by Cache_Key. */
@@ -536,7 +644,7 @@ type LifecycleClient = HttpClientFn & {
536
644
  * - `"queue-dispatch"` — Emitted when a queued request is dispatched to the Wire_Client.
537
645
  * - `"retry"` — Emitted when the retry middleware schedules another attempt.
538
646
  */
539
- type LifecycleEventType = "request-start" | "request-end" | "cache-hit" | "cache-miss" | "dedup-hit" | "dedup-miss" | "queue-enqueue" | "queue-dispatch" | "retry";
647
+ 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";
540
648
  /**
541
649
  * A lifecycle event emitted to the onEvent observer.
542
650
  *
@@ -561,6 +669,10 @@ type LifecycleEvent = {
561
669
  cacheKey?: string;
562
670
  /** Priority level associated with the event, if applicable. Valid range: 0-9. */
563
671
  priority?: number;
672
+ /** Batch_Key associated with the event, if applicable. Present for batch events. */
673
+ batchKey?: string;
674
+ /** Number of requests in the batch, if applicable. Present for batch-dispatch events. */
675
+ batchSize?: number;
564
676
  /** Zero-based retry attempt, if applicable. */
565
677
  attempt?: number;
566
678
  /** Retry delay in milliseconds, if applicable. */
@@ -569,6 +681,14 @@ type LifecycleEvent = {
569
681
  status?: number;
570
682
  /** HttpError tag that triggered retry, if applicable. */
571
683
  errorTag?: string;
684
+ /** Previous concurrency limit, present for limit-change events. */
685
+ previousLimit?: number;
686
+ /** New concurrency limit, present for limit-change events. */
687
+ newLimit?: number;
688
+ /** Gradient value, present for limit-change events. */
689
+ gradient?: number;
690
+ /** Smoothed latency value, present for limit-change events. */
691
+ smoothedLatency?: number;
572
692
  };
573
693
  /**
574
694
  * Lifecycle statistics snapshot.
@@ -609,6 +729,10 @@ type LifecycleStats = {
609
729
  requestsFailed: number;
610
730
  /** Total number of retry attempts scheduled. */
611
731
  retries: number;
732
+ /** Total number of batch dispatches. */
733
+ batchDispatches: number;
734
+ /** Total number of individual requests that were coalesced into batches. */
735
+ batchedRequests: number;
612
736
  /** Underlying Wire_Client stats. */
613
737
  wire: HttpClientStats;
614
738
  };
@@ -1252,6 +1376,8 @@ declare class LifecycleStatsTracker {
1252
1376
  private _requestsCompleted;
1253
1377
  private _requestsFailed;
1254
1378
  private _retries;
1379
+ private _batchDispatches;
1380
+ private _batchedRequests;
1255
1381
  private readonly _onEvent;
1256
1382
  private readonly _wireStats;
1257
1383
  /**
@@ -1391,6 +1517,15 @@ declare class LifecycleStatsTracker {
1391
1517
  */
1392
1518
  requestFailed(): void;
1393
1519
  retry(): void;
1520
+ /**
1521
+ * Records a batch dispatch. Increments the batch dispatches counter by 1.
1522
+ */
1523
+ batchDispatch(): void;
1524
+ /**
1525
+ * Records requests that were coalesced into a batch.
1526
+ * @param count - The number of individual requests in the batch.
1527
+ */
1528
+ batchedRequests(count: number): void;
1394
1529
  /**
1395
1530
  * Emits a lifecycle event to the registered `onEvent` callback.
1396
1531
  *
@@ -1415,6 +1550,8 @@ declare class LifecycleStatsTracker {
1415
1550
  emit(type: LifecycleEventType, extra?: {
1416
1551
  cacheKey?: string;
1417
1552
  priority?: number;
1553
+ batchKey?: string;
1554
+ batchSize?: number;
1418
1555
  attempt?: number;
1419
1556
  delayMs?: number;
1420
1557
  status?: number;
@@ -1781,6 +1918,149 @@ type RequestBatchingConfig = {
1781
1918
  };
1782
1919
  declare function withRequestBatching(config: RequestBatchingConfig): HttpMiddleware;
1783
1920
 
1921
+ /**
1922
+ * The PrewarmManager interface for managing connection pre-warming.
1923
+ */
1924
+ type PrewarmManager = {
1925
+ /** Warm a single origin. Skips if already warm. */
1926
+ warm: (origin: string) => Promise<PrewarmResult>;
1927
+ /** Warm all configured origins. Skips already-warm origins. */
1928
+ warmAll: () => Promise<PrewarmResult[]>;
1929
+ /** Check if an origin has an active warm connection. */
1930
+ isWarm: (origin: string) => boolean;
1931
+ /** Cancel in-flight probe for a specific origin. */
1932
+ cancel: (origin: string) => void;
1933
+ /** Cancel all in-flight and queued probes. */
1934
+ cancelAll: () => void;
1935
+ /** Get a snapshot of all managed origins and their states. */
1936
+ status: () => PrewarmStatusSnapshot;
1937
+ /** Dispose the manager: cancel all, stop timers, release resources. */
1938
+ dispose: () => void;
1939
+ };
1940
+ /**
1941
+ * Creates a PrewarmManager that proactively establishes TCP+TLS connections
1942
+ * to known origins using lightweight HEAD probe requests.
1943
+ *
1944
+ * @param config - Configuration for the prewarm manager.
1945
+ * @returns A PrewarmManager instance.
1946
+ * @throws Error if fetch/AbortController is unavailable or origins are invalid.
1947
+ */
1948
+ declare function makePrewarmManager(config: PrewarmConfig): PrewarmManager;
1949
+
1950
+ /**
1951
+ * Validates and normalizes an origin string.
1952
+ *
1953
+ * A valid origin is: scheme + host + optional port (e.g., "https://api.example.com" or "http://localhost:3000").
1954
+ * Trailing slashes are stripped. Paths, query strings, and fragments are rejected.
1955
+ *
1956
+ * @param origin - The origin string to validate.
1957
+ * @returns The normalized origin string.
1958
+ * @throws Error if the origin is invalid.
1959
+ */
1960
+ declare function validateOrigin(origin: string): string;
1961
+
1962
+ /**
1963
+ * Detects the current runtime platform.
1964
+ *
1965
+ * @returns "browser" if running in a browser environment, "node" otherwise.
1966
+ */
1967
+ declare function detectPlatform(): "browser" | "node";
1968
+ /**
1969
+ * Validates that the global `fetch` API is available.
1970
+ *
1971
+ * @throws Error if `fetch` or `AbortController` is not available.
1972
+ */
1973
+ declare function validateFetchAvailable(): void;
1974
+
1975
+ /**
1976
+ * Outcome of a probe request.
1977
+ */
1978
+ type ProbeOutcome = {
1979
+ /** Whether the probe succeeded (connection established). */
1980
+ ok: boolean;
1981
+ /** Duration of the probe in milliseconds. */
1982
+ durationMs: number;
1983
+ /** Error message if the probe failed. */
1984
+ error?: string;
1985
+ };
1986
+ /**
1987
+ * Options for executing a probe request.
1988
+ */
1989
+ type ProbeOptions = {
1990
+ /** Probe timeout in milliseconds. */
1991
+ timeoutMs: number;
1992
+ /** AbortSignal for external cancellation. */
1993
+ signal: AbortSignal;
1994
+ /** Runtime platform. */
1995
+ platform: "browser" | "node";
1996
+ /** Optional Wire_Client to route through (when useClientPool is true). */
1997
+ client?: HttpClientFn;
1998
+ };
1999
+ /**
2000
+ * Executes a HEAD probe request to the root path of the given origin.
2001
+ *
2002
+ * The probe is a lightweight HEAD request to `${origin}/` designed to trigger
2003
+ * TCP+TLS connection establishment in the platform's connection pool.
2004
+ *
2005
+ * @param origin - The validated origin to probe (e.g., "https://api.example.com").
2006
+ * @param options - Probe configuration options.
2007
+ * @returns A ProbeOutcome indicating success or failure.
2008
+ */
2009
+ declare function executeProbe(origin: string, options: ProbeOptions): Promise<ProbeOutcome>;
2010
+
2011
+ /**
2012
+ * Interface for the connection state map.
2013
+ */
2014
+ type ConnectionStateMap = {
2015
+ /** Mark an origin as warm with the current timestamp. */
2016
+ markWarm: (origin: string, now?: number) => void;
2017
+ /** Mark an origin as expired. */
2018
+ markExpired: (origin: string) => void;
2019
+ /** Mark an origin as idle (reset state). */
2020
+ markIdle: (origin: string) => void;
2021
+ /** Mark an origin as probing. */
2022
+ markProbing: (origin: string) => void;
2023
+ /** Check if an origin is currently warm (not expired). */
2024
+ isWarm: (origin: string, now?: number) => boolean;
2025
+ /** Get the current state of an origin. */
2026
+ getState: (origin: string) => PrewarmOriginState | undefined;
2027
+ /** Get a snapshot of all managed origins. */
2028
+ snapshot: () => PrewarmStatusSnapshot;
2029
+ };
2030
+ /**
2031
+ * Creates a connection state map for tracking per-origin warm/expired/idle states.
2032
+ *
2033
+ * @param origins - Array of origin strings to manage.
2034
+ * @param keepAliveDurationMs - Duration in ms after which a warm connection expires.
2035
+ * @returns A ConnectionStateMap instance.
2036
+ */
2037
+ declare function makeConnectionStateMap(origins: string[], keepAliveDurationMs: number): ConnectionStateMap;
2038
+
2039
+ /**
2040
+ * A lightweight counting semaphore that limits concurrent in-flight operations.
2041
+ */
2042
+ type BudgetSemaphore = {
2043
+ /** Acquire a slot. Resolves with a release handle when a slot is available. */
2044
+ acquire: () => Promise<{
2045
+ release: () => void;
2046
+ }>;
2047
+ /** Try to acquire a slot synchronously. Returns undefined if no slot is available. */
2048
+ tryAcquire: () => {
2049
+ release: () => void;
2050
+ } | undefined;
2051
+ /** Number of currently available slots. */
2052
+ available: () => number;
2053
+ /** Number of waiters currently queued. */
2054
+ queued: () => number;
2055
+ };
2056
+ /**
2057
+ * Creates a budget semaphore with the given capacity.
2058
+ *
2059
+ * @param capacity - Maximum number of concurrent slots. Must be >= 1.
2060
+ * @returns A BudgetSemaphore instance.
2061
+ */
2062
+ declare function makeBudgetSemaphore(capacity: number): BudgetSemaphore;
2063
+
1784
2064
  type ConnectionPrewarmAttempt = {
1785
2065
  url: string;
1786
2066
  origin: string;
@@ -1834,4 +2114,284 @@ declare function prewarmConnections(config?: ConnectionPrewarmConfig): Async<unk
1834
2114
  declare const prewarmHttpConnections: typeof prewarmConnections;
1835
2115
  declare function withConnectionPrewarming(config?: ConnectionPrewarmingMiddlewareConfig): HttpMiddleware;
1836
2116
 
1837
- export { type CacheConfig$1 as CacheConfig, type CacheKeyComponents, type CachePolicyResult$1 as CachePolicyResult, type CompressionConfig, type CompressionMiddlewareResult, type CompressionStats, type ConnectionPrewarmAttempt, type ConnectionPrewarmConfig, type ConnectionPrewarmEvent, type ConnectionPrewarmResult, type ConnectionPrewarmingMiddlewareConfig, DEFAULT_CACHE_RELEVANT_HEADERS, type DecompressResult, type Decompressor, type DedupConfig$1 as DedupConfig, type Dx, type HttpBody, type HttpCircuitBreakerConfig, type HttpClient, type HttpClientFn, type HttpClientStats, type HttpClientStream, type HttpClientStreamFn, HttpConcurrencyPool, type HttpError, type HttpInit, type HttpMeta, type HttpMethod, type HttpMiddleware, type HttpPoolConfig, type HttpPoolKeyResolver, type HttpPoolKeyStats, type HttpPoolLease, type HttpPoolStats, type HttpRequest, type HttpResponse, type HttpResponseWithMeta, type HttpWireResponse, type HttpWireResponseStream, type HttpWireWithMeta, type JsonValidator, LRUCache, type LRUCacheConfig, type LifecycleClient, type LifecycleClientConfig, type LifecycleEvent, type LifecycleEventType, type LifecycleRequestOptions, type LifecycleStats, LifecycleStatsTracker, type LogEvent, type MakeHttpConfig, type PerRequestRetryOverride, type PriorityConfig$1 as PriorityConfig, PriorityQueue, type PriorityQueueEntry, type RequestBatchingConfig, type RequestBatchingEvent, type RequestCompressionConfig, type RequestCompressionMiddlewareResult, type RequestCompressionStats, type RetryEvent, type RetryPolicy, SEPARATOR, SUPPORTED_ENCODINGS, type SupportedEncoding, type ValidationError, backoffDelayMs, clampPriority, computeCacheKey, decorate, defaultRetryOnError, defaultRetryOnStatus, defaultRetryableMethods, httpClient, httpClientStream, httpClientWithMeta, makeCompressionMiddleware, makeHttp, makeHttpClient, makeHttpStream, makeLifecycleClient, makeRequestCompressionMiddleware, makeResponseCompressionMiddleware, normalizeHeadersInit, normalizeRetryBudget, parseCacheKey, prewarmConnections, prewarmHttpConnections, resolveHttpPoolKey, retryAfterMs, validatedJson, withAuth, withCache, withCircuitBreaker, withConnectionPrewarming, withDedup, withLogging, withMiddleware, withPriority, withRequestBatching, withResponseTransform, withRetry, withRetryStream, withTracing };
2117
+ type InitNoMethodBody = Omit<RequestInit, "method" | "body"> & {
2118
+ timeoutMs?: number;
2119
+ poolKey?: string;
2120
+ headers?: unknown;
2121
+ };
2122
+ type InitWithHeaders = {
2123
+ headers?: unknown;
2124
+ timeoutMs?: number;
2125
+ poolKey?: string;
2126
+ } & Record<string, unknown>;
2127
+ type HttpJsonInit<Validator extends AnyJsonSchemaLike> = InitNoMethodBody & {
2128
+ readonly schema: Validator;
2129
+ readonly schemaName?: string;
2130
+ };
2131
+ type HttpPostJsonInit<Validator extends AnyJsonSchemaLike> = InitWithHeaders & {
2132
+ readonly schema: Validator;
2133
+ readonly schemaName?: string;
2134
+ readonly bodySchema?: undefined;
2135
+ readonly bodySchemaName?: string;
2136
+ };
2137
+ type HttpPostJsonSchemaBodyInit<Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike> = InitWithHeaders & {
2138
+ readonly schema: Validator;
2139
+ readonly schemaName?: string;
2140
+ readonly bodySchema: BodyValidator;
2141
+ readonly bodySchemaName?: string;
2142
+ };
2143
+ type HttpPostJsonBodyInit<BodyValidator extends AnyJsonSchemaLike> = InitWithHeaders & {
2144
+ readonly schema?: undefined;
2145
+ readonly schemaName?: string;
2146
+ readonly bodySchema: BodyValidator;
2147
+ readonly bodySchemaName?: string;
2148
+ };
2149
+ type JsonInitNoSchema = InitNoMethodBody & {
2150
+ readonly schema?: undefined;
2151
+ readonly schemaName?: string;
2152
+ };
2153
+ type PostJsonInitNoSchema = InitWithHeaders & {
2154
+ readonly schema?: undefined;
2155
+ readonly schemaName?: string;
2156
+ readonly bodySchema?: undefined;
2157
+ readonly bodySchemaName?: string;
2158
+ };
2159
+ type DefaultGetJson = {
2160
+ <Validator extends AnyJsonSchemaLike>(url: string, init: HttpJsonInit<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
2161
+ <A = unknown>(url: string, init?: JsonInitNoSchema): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
2162
+ };
2163
+ type DefaultPostJson = {
2164
+ <Validator extends AnyJsonSchemaLike, BodyValidator extends AnyJsonSchemaLike>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: HttpPostJsonSchemaBodyInit<Validator, BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
2165
+ <BodyValidator extends AnyJsonSchemaLike, A = unknown>(url: string, bodyObj: InferJsonSchema<BodyValidator>, init: HttpPostJsonBodyInit<BodyValidator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
2166
+ <Validator extends AnyJsonSchemaLike>(url: string, bodyObj: unknown, init: HttpPostJsonInit<Validator>): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<InferJsonSchema<Validator>>>;
2167
+ <A = unknown>(url: string, bodyObj: unknown, init?: PostJsonInitNoSchema): AsyncWithPromise<unknown, HttpError | ValidationError, HttpResponse<A>>;
2168
+ };
2169
+ type DefaultHttpClientPreset = "minimal" | "balanced" | "default";
2170
+ type DefaultHttpClientFeatures = {
2171
+ readonly dedup: boolean;
2172
+ readonly batch: boolean;
2173
+ readonly cache: boolean;
2174
+ readonly priority: boolean;
2175
+ readonly retry: boolean;
2176
+ readonly prewarm: boolean;
2177
+ readonly adaptiveLimiter: boolean;
2178
+ readonly compression: boolean;
2179
+ readonly middleware: number;
2180
+ };
2181
+ type DefaultHttpClientConfig = LifecycleClientConfig & {
2182
+ /**
2183
+ * Preset used as the baseline before caller overrides are applied.
2184
+ * - minimal: wire client + timeout only.
2185
+ * - balanced: retry, priority, dedup, adaptive limiter, response compression.
2186
+ * - default: balanced + short safe-method response cache.
2187
+ */
2188
+ readonly preset?: DefaultHttpClientPreset;
2189
+ /** Response decompression. Enabled by balanced/default presets; set false to disable. */
2190
+ readonly compression?: CompressionConfig | false;
2191
+ /** Extra middleware applied outermost after the preset stack, e.g. withHttpObservability(obs). */
2192
+ readonly middleware?: readonly HttpMiddleware[];
2193
+ };
2194
+ type DefaultHttpClient = {
2195
+ readonly request: (req: HttpRequest) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
2196
+ readonly get: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
2197
+ readonly post: (url: string, body?: string, init?: InitWithHeaders) => AsyncWithPromise<unknown, HttpError, HttpWireResponse>;
2198
+ readonly getText: (url: string, init?: InitNoMethodBody) => AsyncWithPromise<unknown, HttpError, HttpResponse<string>>;
2199
+ readonly getJson: DefaultGetJson;
2200
+ readonly postJson: DefaultPostJson;
2201
+ readonly with: (mw: HttpMiddleware) => DefaultHttpClient;
2202
+ readonly wire: LifecycleClient;
2203
+ readonly stats: () => LifecycleStats;
2204
+ readonly cache: LifecycleClient["cache"];
2205
+ readonly cancelAll: LifecycleClient["cancelAll"];
2206
+ readonly shutdown: LifecycleClient["shutdown"];
2207
+ readonly preset: DefaultHttpClientPreset;
2208
+ readonly features: DefaultHttpClientFeatures;
2209
+ readonly compression?: {
2210
+ readonly stats: () => CompressionStats;
2211
+ };
2212
+ };
2213
+ declare const defaultHttpClientPreset: DefaultHttpClientPreset;
2214
+ /**
2215
+ * Creates the recommended default HTTP client.
2216
+ *
2217
+ * The returned client has the easy JSON/text helpers from `httpClient`, but its
2218
+ * wire path is the full lifecycle stack: priority, retry, cache, batch, dedup,
2219
+ * adaptive concurrency, optional prewarm, compression, stats, and cancelAll.
2220
+ */
2221
+ declare function makeDefaultHttpClient(config?: DefaultHttpClientConfig): DefaultHttpClient;
2222
+
2223
+ type HttpClientBuilder = {
2224
+ readonly config: () => DefaultHttpClientConfig;
2225
+ readonly baseUrl: (baseUrl: string) => HttpClientBuilder;
2226
+ readonly header: (name: string, value: string) => HttpClientBuilder;
2227
+ readonly headers: (headers: Record<string, string>) => HttpClientBuilder;
2228
+ readonly timeoutMs: (timeoutMs: number) => HttpClientBuilder;
2229
+ readonly timeout: (timeoutMs: number) => HttpClientBuilder;
2230
+ readonly preset: (preset: DefaultHttpClientPreset) => HttpClientBuilder;
2231
+ readonly minimal: () => HttpClientBuilder;
2232
+ readonly balanced: () => HttpClientBuilder;
2233
+ readonly defaultPreset: () => HttpClientBuilder;
2234
+ readonly dedup: (config?: DedupConfig$1 | false) => HttpClientBuilder;
2235
+ readonly noDedup: () => HttpClientBuilder;
2236
+ readonly batch: (config: BatchConfig | false) => HttpClientBuilder;
2237
+ readonly noBatch: () => HttpClientBuilder;
2238
+ readonly cache: (config?: CacheConfig$1 | false) => HttpClientBuilder;
2239
+ readonly noCache: () => HttpClientBuilder;
2240
+ readonly priority: (config?: PriorityConfig$1 | false) => HttpClientBuilder;
2241
+ readonly noPriority: () => HttpClientBuilder;
2242
+ readonly retry: (config?: RetryPolicy | false) => HttpClientBuilder;
2243
+ readonly noRetry: () => HttpClientBuilder;
2244
+ readonly prewarm: (config?: PrewarmLifecycleConfig | false) => HttpClientBuilder;
2245
+ readonly noPrewarm: () => HttpClientBuilder;
2246
+ readonly adaptiveLimiter: (config?: AdaptiveLimiterConfig | false) => HttpClientBuilder;
2247
+ readonly adaptiveLimiterPreset: (preset: AdaptiveLimiterPreset, overrides?: AdaptiveLimiterConfig) => HttpClientBuilder;
2248
+ readonly conservativeLimiter: (overrides?: AdaptiveLimiterConfig) => HttpClientBuilder;
2249
+ readonly balancedLimiter: (overrides?: AdaptiveLimiterConfig) => HttpClientBuilder;
2250
+ readonly aggressiveLimiter: (overrides?: AdaptiveLimiterConfig) => HttpClientBuilder;
2251
+ readonly noAdaptiveLimiter: () => HttpClientBuilder;
2252
+ readonly pool: (config?: HttpPoolConfig | false) => HttpClientBuilder;
2253
+ readonly noPool: () => HttpClientBuilder;
2254
+ readonly compression: (config?: CompressionConfig | false) => HttpClientBuilder;
2255
+ readonly noCompression: () => HttpClientBuilder;
2256
+ readonly middleware: (mw: HttpMiddleware) => HttpClientBuilder;
2257
+ readonly use: (mw: HttpMiddleware) => HttpClientBuilder;
2258
+ readonly configure: (config: DefaultHttpClientConfig) => HttpClientBuilder;
2259
+ readonly build: () => DefaultHttpClient;
2260
+ readonly buildWire: () => LifecycleClient;
2261
+ };
2262
+ declare function httpClientBuilder(config?: DefaultHttpClientConfig): HttpClientBuilder;
2263
+ declare const makeHttpClientBuilder: typeof httpClientBuilder;
2264
+ declare const httpBuilder: typeof httpClientBuilder;
2265
+
2266
+ type HttpServerMethod = HttpMethod | "ALL";
2267
+ type HttpServerHeaders = Record<string, string>;
2268
+ type HttpServerQuery = Record<string, string | readonly string[]>;
2269
+ type HttpServerParams = Record<string, string>;
2270
+ type HttpServerBody = string | Uint8Array | ArrayBuffer | unknown;
2271
+ type HttpServerRequest = {
2272
+ readonly method: string;
2273
+ readonly url: string;
2274
+ readonly path: string;
2275
+ readonly target: string;
2276
+ readonly headers: HttpServerHeaders;
2277
+ readonly query: HttpServerQuery;
2278
+ readonly params: HttpServerParams;
2279
+ readonly bodyText: string;
2280
+ readonly raw?: unknown;
2281
+ };
2282
+ type HttpServerContext<Params = HttpServerParams, Query = HttpServerQuery, Body = unknown> = Omit<HttpServerRequest, "params" | "query"> & {
2283
+ readonly route: string;
2284
+ readonly params: Params;
2285
+ readonly query: Query;
2286
+ readonly body: Body;
2287
+ };
2288
+ type HttpServerResponse<Body = unknown> = {
2289
+ readonly status?: number;
2290
+ readonly headers?: HttpServerHeaders;
2291
+ readonly body?: Body;
2292
+ };
2293
+ type HttpServerHandler<R = unknown, E = unknown, Params = HttpServerParams, Query = HttpServerQuery, Body = unknown, ResponseBody = unknown> = (ctx: HttpServerContext<Params, Query, Body>) => Async<R, E, HttpServerResponse<ResponseBody>>;
2294
+ type HttpServerMiddleware = (next: HttpServerHandler<any, any, any, any, any, any>) => HttpServerHandler<any, any, any, any, any, any>;
2295
+ type HttpRouteSchemas<ParamsSchema extends AnyJsonSchemaLike | undefined = undefined, QuerySchema extends AnyJsonSchemaLike | undefined = undefined, BodySchema extends AnyJsonSchemaLike | undefined = undefined, ResponseSchema extends AnyJsonSchemaLike | undefined = undefined> = {
2296
+ readonly params?: ParamsSchema;
2297
+ readonly paramsSchemaName?: string;
2298
+ readonly query?: QuerySchema;
2299
+ readonly querySchemaName?: string;
2300
+ readonly body?: BodySchema;
2301
+ readonly bodySchemaName?: string;
2302
+ readonly response?: ResponseSchema;
2303
+ readonly responseSchemaName?: string;
2304
+ };
2305
+ type HttpRouteOptions<ParamsSchema extends AnyJsonSchemaLike | undefined = undefined, QuerySchema extends AnyJsonSchemaLike | undefined = undefined, BodySchema extends AnyJsonSchemaLike | undefined = undefined, ResponseSchema extends AnyJsonSchemaLike | undefined = undefined> = HttpRouteSchemas<ParamsSchema, QuerySchema, BodySchema, ResponseSchema> & {
2306
+ readonly middleware?: readonly HttpServerMiddleware[];
2307
+ };
2308
+ type HttpRuntimeHealthRouteOptions = RuntimeHealthOptions & {
2309
+ readonly path?: string;
2310
+ };
2311
+ type InferServerPart<Schema, Fallback> = Schema extends AnyJsonSchemaLike ? InferJsonSchema<Schema> : Fallback;
2312
+ type RoutePathParamNames<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}` ? StripRouteParamModifier<Param> | RoutePathParamNames<`/${Rest}`> : Path extends `${string}:${infer Param}` ? StripRouteParamModifier<Param> : never;
2313
+ type RoutePathParams<Path extends string> = [
2314
+ RoutePathParamNames<Path>
2315
+ ] extends [never] ? {} : {
2316
+ readonly [Key in RoutePathParamNames<Path>]: string;
2317
+ };
2318
+ type StripRouteParamModifier<Param extends string> = Param extends `${infer Name}?` ? Name : Param extends `${infer Name}+` ? Name : Param extends `${infer Name}*` ? Name : Param;
2319
+ type HttpServerRoute<R = unknown, E = unknown, Path extends string = string, ParamsSchema extends AnyJsonSchemaLike | undefined = AnyJsonSchemaLike | undefined, QuerySchema extends AnyJsonSchemaLike | undefined = AnyJsonSchemaLike | undefined, BodySchema extends AnyJsonSchemaLike | undefined = AnyJsonSchemaLike | undefined, ResponseSchema extends AnyJsonSchemaLike | undefined = AnyJsonSchemaLike | undefined> = {
2320
+ readonly method: HttpServerMethod;
2321
+ readonly path: Path;
2322
+ readonly options: HttpRouteOptions<ParamsSchema, QuerySchema, BodySchema, ResponseSchema>;
2323
+ readonly handler: HttpServerHandler<R, E, InferServerPart<ParamsSchema, RoutePathParams<Path>>, InferServerPart<QuerySchema, HttpServerQuery>, InferServerPart<BodySchema, unknown>, InferServerPart<ResponseSchema, unknown>>;
2324
+ readonly match: (path: string) => HttpServerParams | undefined;
2325
+ };
2326
+ type HttpRouterOptions = {
2327
+ readonly middleware?: readonly HttpServerMiddleware[];
2328
+ readonly includeErrorDetails?: boolean;
2329
+ };
2330
+ type HttpRouteMatch = {
2331
+ readonly _tag: "Match";
2332
+ readonly route: HttpServerRoute<any, any, any, any, any, any, any>;
2333
+ readonly params: HttpServerParams;
2334
+ } | {
2335
+ readonly _tag: "MethodNotAllowed";
2336
+ readonly route: HttpServerRoute<any, any, any, any, any, any, any>;
2337
+ readonly allowed: readonly HttpServerMethod[];
2338
+ } | {
2339
+ readonly _tag: "NotFound";
2340
+ };
2341
+ type HttpRouter = {
2342
+ readonly routes: readonly HttpServerRoute<any, any, any, any, any, any, any>[];
2343
+ readonly match: (method: string, path: string) => HttpRouteMatch;
2344
+ readonly handle: (request: HttpServerRequest, match?: HttpRouteMatch) => Async<unknown, never, HttpServerResponse>;
2345
+ readonly listen: <R extends object = {}>(options?: Omit<NodeHttpServerOptions<R>, "router">) => Resource<unknown, NodeHttpServerError, NodeHttpServerHandle>;
2346
+ };
2347
+ type NodeHttpServerError = {
2348
+ readonly _tag: "ListenError";
2349
+ readonly error: unknown;
2350
+ readonly message: string;
2351
+ } | {
2352
+ readonly _tag: "ServerClosed";
2353
+ readonly message: string;
2354
+ };
2355
+ type NodeHttpServerHandle = {
2356
+ readonly server: Server;
2357
+ readonly router: HttpRouter;
2358
+ readonly address: () => AddressInfo | string | null;
2359
+ readonly url: () => string | undefined;
2360
+ readonly close: () => Promise<void>;
2361
+ };
2362
+ type NodeHttpServerOptions<R extends object = {}> = {
2363
+ readonly router: HttpRouter | readonly HttpServerRoute<any, any, any, any, any, any, any>[];
2364
+ readonly host?: string;
2365
+ readonly port?: number;
2366
+ readonly env?: R;
2367
+ readonly runtime?: Runtime<R>;
2368
+ readonly runtimeOptions?: Omit<RuntimeOptions<R>, "env" | "hooks">;
2369
+ readonly observability?: Observability;
2370
+ readonly observabilityOptions?: HttpServerObservabilityOptions<HttpServerResponse>;
2371
+ readonly maxBodyBytes?: number;
2372
+ readonly gracefulShutdownMs?: number;
2373
+ readonly shutdownPollSchedule?: Schedule<NodeHttpServerShutdownState, unknown>;
2374
+ readonly onError?: (error: unknown) => void;
2375
+ };
2376
+ type NodeHttpServerShutdownState = {
2377
+ readonly listening: boolean;
2378
+ readonly elapsedMs: number;
2379
+ };
2380
+ declare function route<Path extends string, ParamsSchema extends AnyJsonSchemaLike | undefined = undefined, QuerySchema extends AnyJsonSchemaLike | undefined = undefined, BodySchema extends AnyJsonSchemaLike | undefined = undefined, ResponseSchema extends AnyJsonSchemaLike | undefined = undefined, R = unknown, E = unknown>(method: HttpServerMethod, path: Path, options: HttpRouteOptions<ParamsSchema, QuerySchema, BodySchema, ResponseSchema>, handler: HttpServerHandler<R, E, InferServerPart<ParamsSchema, RoutePathParams<Path>>, InferServerPart<QuerySchema, HttpServerQuery>, InferServerPart<BodySchema, unknown>, InferServerPart<ResponseSchema, unknown>>): HttpServerRoute<R, E, Path, ParamsSchema, QuerySchema, BodySchema, ResponseSchema>;
2381
+ declare function route<Path extends string, R = unknown, E = unknown>(method: HttpServerMethod, path: Path, handler: HttpServerHandler<R, E, RoutePathParams<Path>>): HttpServerRoute<R, E, Path, undefined, undefined, undefined, undefined>;
2382
+ declare const httpRoute: typeof route;
2383
+ declare function makeHttpRouter(routes: readonly HttpServerRoute<any, any, any, any, any, any, any>[], options?: HttpRouterOptions): HttpRouter;
2384
+ declare function json<Body>(body: Body, init?: Omit<HttpServerResponse<Body>, "body">): HttpServerResponse<Body>;
2385
+ declare function text(body: string, init?: Omit<HttpServerResponse<string>, "body">): HttpServerResponse<string>;
2386
+ declare function empty(status?: number, headers?: HttpServerHeaders): HttpServerResponse<void>;
2387
+ declare function makeRuntimeHealthRoute(options?: HttpRuntimeHealthRouteOptions): HttpServerRoute<unknown, never, string, undefined, undefined, undefined, undefined>;
2388
+ declare function makeRuntimeReadinessRoute(options?: HttpRuntimeHealthRouteOptions): HttpServerRoute<unknown, never, string, undefined, undefined, undefined, undefined>;
2389
+ declare const runtimeHealthRoute: typeof makeRuntimeHealthRoute;
2390
+ declare const runtimeReadinessRoute: typeof makeRuntimeReadinessRoute;
2391
+ declare function withResponseHeader(name: string, value: string): HttpServerMiddleware;
2392
+ declare function makeNodeHttpServer<R extends object = {}>(options: NodeHttpServerOptions<R>): Async<unknown, NodeHttpServerError, NodeHttpServerHandle>;
2393
+ declare function nodeHttpServerResource<R extends object = {}>(options: NodeHttpServerOptions<R>): Resource<unknown, NodeHttpServerError, NodeHttpServerHandle>;
2394
+ declare const makeNodeHttpServerResource: typeof nodeHttpServerResource;
2395
+ declare const makeHttpServerResource: typeof nodeHttpServerResource;
2396
+
2397
+ export { AdaptiveLimiter, AdaptiveLimiterConfig, AdaptiveLimiterPreset, AnyJsonSchemaLike, type BatchConfig, type BatchFunction, type BudgetSemaphore, type CacheConfig$1 as CacheConfig, type CacheKeyComponents, type CachePolicyResult$1 as CachePolicyResult, type CompressionConfig, type CompressionMiddlewareResult, type CompressionStats, type ConnectionPrewarmAttempt, type ConnectionPrewarmConfig, type ConnectionPrewarmEvent, type ConnectionPrewarmResult, type ConnectionPrewarmingMiddlewareConfig, type ConnectionStateMap, DEFAULT_CACHE_RELEVANT_HEADERS, type DecompressResult, type Decompressor, type DedupConfig$1 as DedupConfig, type DefaultGetJson, type DefaultHttpClient, type DefaultHttpClientConfig, type DefaultHttpClientFeatures, type DefaultHttpClientPreset, type DefaultPostJson, type Dx, EmaComputer, type HttpCircuitBreakerConfig, HttpClient, type HttpClientBuilder, HttpClientFn, HttpClientStats, HttpClientStream, HttpError, type HttpErrorHandlers, type HttpJsonInit, type HttpMeta, HttpMethod, HttpMiddleware, HttpPoolConfig, type HttpPostJsonBodyInit, type HttpPostJsonInit, type HttpPostJsonSchemaBodyInit, HttpRequest, type HttpResponse, type HttpResponseWithMeta, type HttpRouteMatch, type HttpRouteOptions, type HttpRouteSchemas, type HttpRouter, type HttpRouterOptions, type HttpRuntimeHealthRouteOptions, type HttpServerBody, type HttpServerContext, type HttpServerHandler, type HttpServerHeaders, type HttpServerMethod, type HttpServerMiddleware, type HttpServerParams, type HttpServerQuery, type HttpServerRequest, type HttpServerResponse, type HttpServerRoute, HttpWireResponse, HttpWireResponseStream, type HttpWireWithMeta, InferJsonSchema, type InferServerPart, type JsonDecodeResult, JsonSchemaLike, type KnownHttpError, type KnownHttpErrorTag, LRUCache, type LRUCacheConfig, LatencyWindow, type LifecycleClient, type LifecycleClientConfig, type LifecycleEvent, type LifecycleEventType, type LifecycleRequestOptions, type LifecycleStats, LifecycleStatsTracker, type LogEvent, MakeHttpConfig, type NodeHttpServerError, type NodeHttpServerHandle, type NodeHttpServerOptions, type NodeHttpServerShutdownState, type PrewarmConfig, type PrewarmEvent, type PrewarmEventType, type PrewarmLifecycleConfig, type PrewarmManager, type PrewarmOriginState, type PrewarmOriginStatus, type PrewarmResult, type PrewarmResultStatus, type PrewarmStatusSnapshot, type PriorityConfig$1 as PriorityConfig, PriorityQueue, type PriorityQueueEntry, type ProbeOutcome, type RequestBatchingConfig, type RequestBatchingEvent, type RequestCompressionConfig, type RequestCompressionMiddlewareResult, type RequestCompressionStats, RetryPolicy, type RoutePathParamNames, type RoutePathParams, SEPARATOR, SUPPORTED_ENCODINGS, SchemaIssue, type SupportedEncoding, type ValidationError, clampPriority, computeCacheKey, computeGradient, computeNewLimit, decodeJsonBody, decodeJsonBodyEffect, defaultHttpClientPreset, detectPlatform, empty, encodeJsonBodyEffect, executeProbe, formatHttpError, httpBuilder, httpClient, httpClientBuilder, httpClientStream, httpClientWithMeta, httpRoute, isCircuitBreakerOpen, isHttpError, isKnownHttpError, isValidationError, json, makeBudgetSemaphore, makeCompressionMiddleware, makeConnectionStateMap, makeDefaultHttpClient, makeHttpClient, makeHttpClientBuilder, makeHttpRouter, makeHttpServerResource, makeLifecycleClient, makeNodeHttpServer, makeNodeHttpServerResource, makePrewarmManager, makeRequestCompressionMiddleware, makeResponseCompressionMiddleware, makeRuntimeHealthRoute, makeRuntimeReadinessRoute, matchHttpError, nodeHttpServerResource, parseCacheKey, prewarmConnections, prewarmHttpConnections, route, runtimeHealthRoute, runtimeReadinessRoute, text, validateFetchAvailable, validateOrigin, validatedJson, validatedJsonResponse, withAuth, withBatch, withCache, withCircuitBreaker, withConnectionPrewarming, withDedup, withLogging, withPriority, withRequestBatching, withResponseHeader, withResponseTransform, withTracing };