castrum 0.7.0 → 0.9.1

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 (207) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +154 -368
  3. package/castrum.linux-x64-gnu.node +0 -0
  4. package/dist/index.d.ts +2763 -0
  5. package/dist/index.js +8707 -0
  6. package/docs/API.md +337 -0
  7. package/docs/ARCHITECTURE.md +507 -0
  8. package/docs/BENCHMARKS.md +343 -0
  9. package/docs/CASE_STUDY.md +240 -0
  10. package/docs/ENVIRONMENT.md +81 -0
  11. package/docs/FFI_BUN_GUIDE.md +327 -0
  12. package/docs/GETTING_STARTED.md +192 -0
  13. package/docs/INGRESS-ROUTER.md +81 -0
  14. package/docs/INGRESS.md +746 -0
  15. package/docs/NATIVE-ROUTE.md +53 -0
  16. package/docs/REPO_MAP.md +279 -0
  17. package/docs/adr/0001-two-wire-formats.md +39 -0
  18. package/docs/adr/0002-zero-dom-fast-schema.md +38 -0
  19. package/docs/adr/0003-bun-builtins-delegation.md +43 -0
  20. package/docs/bun-builtins-decision-matrix.md +115 -0
  21. package/index.ts +44 -8
  22. package/package.json +98 -33
  23. package/src/ingress/body.ts +289 -0
  24. package/src/ingress/constants.ts +220 -48
  25. package/src/ingress/context.ts +136 -0
  26. package/src/ingress/decode/baked-result.ts +121 -0
  27. package/src/ingress/decode/fast-result.ts +160 -0
  28. package/src/ingress/decode/packed-sections.ts +56 -0
  29. package/src/ingress/decode/result-base.ts +172 -0
  30. package/src/ingress/errors.ts +72 -0
  31. package/src/ingress/fast.ts +152 -1021
  32. package/src/ingress/handlers.ts +639 -1001
  33. package/src/ingress/headers/baked-templates.ts +102 -0
  34. package/src/ingress/headers/cors.ts +44 -0
  35. package/src/ingress/headers/fast-templates.ts +238 -0
  36. package/src/ingress/headers/hsts.ts +83 -0
  37. package/src/ingress/health.ts +68 -0
  38. package/src/ingress/index.ts +142 -405
  39. package/src/ingress/metrics.ts +132 -0
  40. package/src/ingress/options.ts +197 -0
  41. package/src/ingress/packing/gather-raw-headers.ts +139 -0
  42. package/src/ingress/packing/header-packing.ts +75 -0
  43. package/src/ingress/packing/input-packer.ts +164 -0
  44. package/src/ingress/packing/scratch.ts +50 -0
  45. package/src/ingress/packing/select-headers.ts +102 -0
  46. package/src/ingress/response/error-bodies.ts +75 -0
  47. package/src/ingress/response/terminal.ts +59 -0
  48. package/src/ingress/router.ts +237 -0
  49. package/src/ingress/routes/common.ts +79 -0
  50. package/src/ingress/routes/delete.ts +14 -0
  51. package/src/ingress/routes/echo.ts +107 -0
  52. package/src/ingress/routes/fallback.ts +23 -0
  53. package/src/ingress/routes/head.ts +27 -0
  54. package/src/ingress/routes/index.ts +11 -0
  55. package/src/ingress/routes/json-write.ts +129 -0
  56. package/src/ingress/routes/options.ts +26 -0
  57. package/src/ingress/routes/read.ts +35 -0
  58. package/src/ingress/routes/responder.ts +159 -0
  59. package/src/ingress/server-node.ts +376 -0
  60. package/src/ingress/server.ts +475 -0
  61. package/src/ingress/shared.ts +132 -0
  62. package/src/ingress/status.ts +97 -0
  63. package/src/ingress/types.ts +191 -0
  64. package/src/integration/batch.ts +58 -0
  65. package/src/integration/index.ts +29 -0
  66. package/src/integration/pipeline.ts +220 -0
  67. package/src/integration/streaming.ts +78 -0
  68. package/src/integration/websocket.ts +93 -0
  69. package/src/loader/batch.ts +137 -0
  70. package/src/loader/cost.ts +105 -0
  71. package/src/loader/index.ts +745 -0
  72. package/src/loader/ops.ts +657 -0
  73. package/src/loader/state.ts +84 -0
  74. package/src/loader/types.ts +145 -0
  75. package/src/native/ffi/constants.ts +58 -0
  76. package/src/native/ffi/selftest.ts +729 -0
  77. package/src/native/ffi/types.ts +474 -0
  78. package/src/native/ffi.ts +1775 -0
  79. package/src/native/index.ts +8 -207
  80. package/src/native/loader.ts +240 -0
  81. package/src/native/types/instances.ts +274 -0
  82. package/src/native/types.ts +401 -0
  83. package/src/runtime/builtins.ts +131 -0
  84. package/src/runtime/codec.ts +147 -0
  85. package/src/runtime/detect.ts +36 -0
  86. package/src/runtime/index.ts +28 -0
  87. package/src/runtime/native.ts +35 -0
  88. package/src/runtime/server.ts +31 -0
  89. package/src/runtime/transport.ts +64 -0
  90. package/src/runtime/types.ts +173 -0
  91. package/src/runtime/uuid.ts +45 -0
  92. package/src/runtime/websocket.ts +30 -0
  93. package/src/rust-ffi/addon.ts +10 -0
  94. package/src/rust-ffi/batch/build.ts +155 -0
  95. package/src/rust-ffi/batch/index.ts +8 -0
  96. package/src/rust-ffi/batch/types.ts +92 -0
  97. package/src/rust-ffi/client.ts +87 -0
  98. package/src/rust-ffi/context.ts +193 -0
  99. package/src/rust-ffi/index.ts +51 -541
  100. package/src/rust-ffi/into.ts +21 -0
  101. package/src/rust-ffi/options.ts +113 -0
  102. package/src/rust-ffi/packed.ts +253 -0
  103. package/src/rust-ffi/proven.ts +28 -0
  104. package/src/rust-ffi/scalar/crypto.ts +346 -0
  105. package/src/rust-ffi/scalar/factories.ts +459 -0
  106. package/src/rust-ffi/scalar/hashing.ts +74 -0
  107. package/src/rust-ffi/scalar/http.ts +337 -0
  108. package/src/rust-ffi/scalar/index.ts +31 -0
  109. package/src/rust-ffi/scalar/interface.ts +325 -0
  110. package/src/rust-ffi/scalar/json-packed.ts +175 -0
  111. package/src/rust-ffi/scalar/json.ts +61 -0
  112. package/src/rust-ffi/scalar/payload.ts +241 -0
  113. package/src/rust-ffi/text.ts +121 -0
  114. package/src/selection.json +194 -0
  115. package/src/selection.ts +73 -0
  116. package/src/shared/adaptive.ts +67 -0
  117. package/src/shared/buffer-pool.ts +264 -0
  118. package/src/shared/bytes.ts +108 -9
  119. package/src/shared/codec.ts +78 -0
  120. package/src/shared/env.ts +20 -0
  121. package/src/shared/log.ts +75 -0
  122. package/src/shared/metrics.ts +247 -0
  123. package/src/shared/packed/index.ts +10 -0
  124. package/src/shared/packed/parsers.ts +31 -0
  125. package/src/shared/packed/schema.ts +23 -0
  126. package/src/shared/packed/wire.ts +504 -0
  127. package/src/shared/proven.ts +289 -0
  128. package/src/shared/request-id.ts +67 -0
  129. package/src/shared/response.ts +104 -0
  130. package/src/shared/runtime.ts +29 -0
  131. package/src/shared/trace.ts +81 -0
  132. package/src/shared/uuid.ts +15 -0
  133. package/Cargo.toml +0 -73
  134. package/bench.ts +0 -3
  135. package/rust/batch.rs +0 -195
  136. package/rust/cookie_parser.rs +0 -70
  137. package/rust/cors.rs +0 -263
  138. package/rust/hashing.rs +0 -164
  139. package/rust/headers.rs +0 -234
  140. package/rust/hmac_sha256.rs +0 -113
  141. package/rust/http_parser.rs +0 -132
  142. package/rust/ingress.rs +0 -616
  143. package/rust/ingress_constants.rs +0 -89
  144. package/rust/ip_trust.rs +0 -185
  145. package/rust/json_ops.rs +0 -66
  146. package/rust/json_patch_ops.rs +0 -25
  147. package/rust/json_schema.rs +0 -151
  148. package/rust/json_ser.rs +0 -429
  149. package/rust/lib.rs +0 -48
  150. package/rust/method.rs +0 -141
  151. package/rust/mime_lookup.rs +0 -76
  152. package/rust/output.rs +0 -238
  153. package/rust/proxy.rs +0 -90
  154. package/rust/query_parser.rs +0 -141
  155. package/rust/random_token.rs +0 -52
  156. package/rust/rate_limit.rs +0 -203
  157. package/rust/terminal.rs +0 -95
  158. package/rust/unit_tests.rs +0 -843
  159. package/rust/url_codec.rs +0 -133
  160. package/rust/util.rs +0 -537
  161. package/rust/validation.rs +0 -107
  162. package/rust/websocket.rs +0 -23
  163. package/src/baseline/index.ts +0 -12
  164. package/src/baseline/tasks/cookie.ts +0 -22
  165. package/src/baseline/tasks/hashing.ts +0 -18
  166. package/src/baseline/tasks/hmac.ts +0 -38
  167. package/src/baseline/tasks/http.ts +0 -62
  168. package/src/baseline/tasks/json-patch.ts +0 -12
  169. package/src/baseline/tasks/json.ts +0 -50
  170. package/src/baseline/tasks/mime.ts +0 -5
  171. package/src/baseline/tasks/query.ts +0 -14
  172. package/src/baseline/tasks/token.ts +0 -15
  173. package/src/baseline/tasks/url.ts +0 -11
  174. package/src/baseline/tasks/validation.ts +0 -19
  175. package/src/baseline/tasks/websocket.ts +0 -14
  176. package/src/bench/assert.ts +0 -70
  177. package/src/bench/checks.ts +0 -227
  178. package/src/bench/checksum.ts +0 -27
  179. package/src/bench/comparisons.ts +0 -70
  180. package/src/bench/concurrent-worker.ts +0 -135
  181. package/src/bench/fixtures.ts +0 -233
  182. package/src/bench/index.ts +0 -2
  183. package/src/bench/measure.ts +0 -177
  184. package/src/bench/now.ts +0 -3
  185. package/src/bench/report.ts +0 -79
  186. package/src/bench/run.ts +0 -57
  187. package/src/bench/tasks/complex.ts +0 -232
  188. package/src/bench/tasks/concurrent.ts +0 -213
  189. package/src/bench/tasks/cookie.ts +0 -44
  190. package/src/bench/tasks/hashing.ts +0 -33
  191. package/src/bench/tasks/hmac.ts +0 -36
  192. package/src/bench/tasks/http.ts +0 -50
  193. package/src/bench/tasks/index.ts +0 -52
  194. package/src/bench/tasks/json-patch.ts +0 -21
  195. package/src/bench/tasks/json.ts +0 -33
  196. package/src/bench/tasks/mime.ts +0 -21
  197. package/src/bench/tasks/query.ts +0 -44
  198. package/src/bench/tasks/stress.ts +0 -142
  199. package/src/bench/tasks/token.ts +0 -20
  200. package/src/bench/tasks/url.ts +0 -34
  201. package/src/bench/tasks/validation.ts +0 -57
  202. package/src/bench/tasks/websocket.ts +0 -21
  203. package/src/bench/types.ts +0 -60
  204. package/src/data/json-rows.ts +0 -33
  205. package/src/ingress/packed-input.ts +0 -59
  206. package/src/shared/json.ts +0 -18
  207. package/src/shared/packed.ts +0 -316
@@ -0,0 +1,2763 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ /** A single JSON Schema validation error (fast path + DOM fallback). */
4
+ export interface SchemaError {
5
+ /** RFC 6901 JSON pointer to the failing instance value ("" = root). */
6
+ instancePath: string;
7
+ /** JSON pointer into the schema at the failing keyword. */
8
+ schemaPath: string;
9
+ /** The failing keyword (e.g. "type", "pattern", "required"). */
10
+ keyword: string;
11
+ /** Human-readable failure message. */
12
+ message: string;
13
+ }
14
+ /** The native `SchemaValidator` class instance. */
15
+ export interface SchemaValidatorInstance {
16
+ /** Validate a single JSON document. */
17
+ validate(input: Uint8Array): boolean;
18
+ /** Opaque handle (bun:ffi fast path) — `castrum_schema_validator_validate`. */
19
+ innerPtr?(): bigint;
20
+ /** Validate a single JSON document, returning detailed errors (empty = valid). */
21
+ validateDetailed(input: Uint8Array): SchemaError[];
22
+ /** Validate a single JSON document, returning only the first error (null = valid). */
23
+ validateFirstError(input: Uint8Array): SchemaError | null;
24
+ validateBatchPackedCount(packed: Uint8Array): number;
25
+ validateBatchPackedBitset(packed: Uint8Array): Uint8Array;
26
+ /**
27
+ * One-pass validate + extract: validate `input` against the schema and
28
+ * capture scalar values / array lengths at `paths` during the same native
29
+ * walk (no `JSON.parse`, no DOM). For "derive" routes (response built from a
30
+ * handful of body fields) this replaces `JSON.parse` + Ajv on the happy path
31
+ * and rejects invalid bodies with zero DOM/GC.
32
+ *
33
+ * `paths` are RFC 6901 JSON pointers of OBJECT KEYS; a trailing `/-`
34
+ * captures the ARRAY LENGTH at that path (e.g. `"/totalCents"`,
35
+ * `"/lineItems/-"`). Array-index steps are not supported.
36
+ */
37
+ derive(input: Uint8Array, paths: string[]): JsonDeriveResult;
38
+ }
39
+ /** A single derived value captured during one-pass validation. */
40
+ export interface JsonDeriveValue {
41
+ /** `"int" | "number" | "string" | "bool" | "null"`. */
42
+ kind: string;
43
+ int: number | null;
44
+ number: number | null;
45
+ text: string | null;
46
+ boolean: boolean | null;
47
+ }
48
+ /** Result of a one-pass `validate + derive`. */
49
+ export interface JsonDeriveResult {
50
+ /** `true` when the document is schema-valid; `false` → caller rejects. */
51
+ ok: boolean;
52
+ /** One entry per requested path (`null` = path absent from the document). */
53
+ values: Array<JsonDeriveValue | null>;
54
+ }
55
+ /** The native `HmacSigner` class instance. */
56
+ export interface HmacSignerInstance {
57
+ sign(data: Uint8Array): Uint8Array;
58
+ verify(data: Uint8Array, sig: Uint8Array): boolean;
59
+ }
60
+ /** The native `FormParser` class instance (reusable output buffer). */
61
+ export interface FormParserInstance {
62
+ /** Parse an x-www-form-urlencoded body into packed pairs (reuses the buffer). */
63
+ parse(input: Uint8Array): Uint8Array;
64
+ /** Zero-alloc parse into a caller-provided output buffer. */
65
+ parseInto(input: Uint8Array, output: Uint8Array): number;
66
+ }
67
+ /** A parsed Content-Type / media type. */
68
+ export interface MediaTypeResult {
69
+ /** Lowercased `type/subtype`. */
70
+ mediaType: string;
71
+ charset: string | null;
72
+ boundary: string | null;
73
+ params: Record<string, string>;
74
+ }
75
+ /** The native `MediaTypeParser` class instance. */
76
+ export interface MediaTypeParserInstance {
77
+ parse(input: Uint8Array): MediaTypeResult;
78
+ }
79
+ /** The native `ConditionalRequest` class instance (per-resource 304 checks). */
80
+ export interface ConditionalRequestInstance {
81
+ isNotModified(ifNoneMatch: Uint8Array | null, ifModifiedSince: Uint8Array | null): boolean;
82
+ /** Opaque handle to the precompiled state (present when the bun:ffi fast path
83
+ * is active) — `castrum_conditional_is_not_modified` in rust/ffi.rs. */
84
+ innerPtr?(): bigint;
85
+ }
86
+ /** One parsed Accept-Encoding preference. */
87
+ export interface EncodingPrefResult {
88
+ encoding: string;
89
+ q: number;
90
+ order: number;
91
+ }
92
+ /**
93
+ * The native `AcceptNegotiator` class instance (supported encodings compiled
94
+ * once). Best supported encoding for a header, or `null` for identity.
95
+ */
96
+ export interface AcceptNegotiatorInstance {
97
+ /** Best supported encoding for `header`, or null for identity. */
98
+ negotiate(header: Uint8Array): string | null;
99
+ /** Opaque handle (bun:ffi fast path) — `castrum_accept_negotiator_negotiate`. */
100
+ innerPtr?(): bigint;
101
+ }
102
+ /** The native `Base64Codec` class instance (config compiled once). */
103
+ export interface Base64CodecInstance {
104
+ encode(input: Uint8Array): Uint8Array;
105
+ decode(input: Uint8Array): Uint8Array;
106
+ }
107
+ /** Result of a native rate-limit check for one key at a point in time. */
108
+ export interface RateCheckResult {
109
+ allowed: boolean;
110
+ remaining: number;
111
+ resetMs: number;
112
+ }
113
+ /** The native `RateLimiter` class instance (sharded fixed-window state). */
114
+ export interface RateLimiterInstance {
115
+ check(key: string, nowMs: number): RateCheckResult;
116
+ checkKey(key: number, nowMs: number): RateCheckResult;
117
+ /** Opaque handle (bun:ffi fast path) — `castrum_rate_limiter_check*`. */
118
+ innerPtr?(): bigint;
119
+ }
120
+ /** The native `CookieSigner` class instance (HMAC key compiled once). */
121
+ export interface CookieSignerInstance {
122
+ sign(value: Uint8Array): Uint8Array;
123
+ /** Returns the signed value without its signature, or null on invalid. */
124
+ verify(signed: Uint8Array): Uint8Array | null;
125
+ }
126
+ /** The native `CsrfProtector` class instance (HMAC key compiled once). */
127
+ export interface CsrfProtectorInstance {
128
+ create(): Uint8Array;
129
+ verify(token: Uint8Array): boolean;
130
+ }
131
+ /** The native `UrlBuilder` class instance (base parsed once). */
132
+ export interface UrlBuilderInstance {
133
+ resolve(reference: Uint8Array): Uint8Array;
134
+ /** Opaque handle to the precompiled base (present when the bun:ffi fast path
135
+ * is active) — `castrum_url_builder_resolve` in rust/ffi.rs. */
136
+ innerPtr?(): bigint;
137
+ }
138
+ /** Options for `passwordHash` (argon2id). */
139
+ export interface PasswordHashOptions {
140
+ mCost?: number;
141
+ tCost?: number;
142
+ pCost?: number;
143
+ outLen?: number;
144
+ }
145
+ /** A parsed multipart/form-data part. */
146
+ export interface MultipartPart {
147
+ name: string;
148
+ filename: string | null;
149
+ contentType: string | null;
150
+ data: Uint8Array;
151
+ }
152
+ /** A decoded RFC 6455 websocket frame. */
153
+ export interface WsFrame {
154
+ fin: boolean;
155
+ opcode: number;
156
+ payload: Uint8Array;
157
+ }
158
+ /** The native `TemplateRenderer` class instance. */
159
+ export interface TemplateRendererInstance {
160
+ render(context: unknown): Uint8Array;
161
+ /** Render from pre-serialized JSON context bytes (no napi Value marshal). */
162
+ renderBytes(contextJson: Uint8Array): Uint8Array;
163
+ /** Parallel batch render: packed contexts in → packed rendered out. */
164
+ renderBatchPacked(data: Uint8Array): Uint8Array;
165
+ /** Opaque handle (bun:ffi fast path) — `castrum_template_render`. */
166
+ innerPtr?(): bigint;
167
+ }
168
+ /** The native `MediaTypeMatcher` class instance (expected precompiled once). */
169
+ export interface MediaTypeMatcherInstance {
170
+ /** Wildcard match against the precompiled expected type. */
171
+ matches(actual: Uint8Array): boolean;
172
+ /** Opaque handle (bun:ffi fast path) — `castrum_media_type_matcher_matches`. */
173
+ innerPtr?(): bigint;
174
+ }
175
+ /** The native `JwtSigner` class instance (HS256 key + ttl compiled once). */
176
+ export interface JwtSignerInstance {
177
+ sign(claims: unknown, nowSeconds: number): Uint8Array;
178
+ /** Sign from pre-serialized claim JSON bytes (no napi Value marshal). */
179
+ signBytes(claimsJson: Uint8Array, nowSeconds: number): Uint8Array;
180
+ verify(token: Uint8Array, nowSeconds: number): unknown;
181
+ /** Opaque handle (bun:ffi fast path) — `castrum_jwt_signer_*`. */
182
+ innerPtr?(): bigint;
183
+ }
184
+ /** The native `AeadCipher` class instance (algorithm + key compiled once). */
185
+ export interface AeadCipherInstance {
186
+ encrypt(nonce: Uint8Array, plaintext: Uint8Array): Uint8Array;
187
+ decrypt(nonce: Uint8Array, ciphertext: Uint8Array): Uint8Array | null;
188
+ }
189
+ /** The native `Argon2Hasher` class instance (params compiled once). */
190
+ export interface Argon2HasherInstance {
191
+ hash(password: Uint8Array, salt: Uint8Array): Uint8Array;
192
+ verify(password: Uint8Array, phc: Uint8Array): boolean;
193
+ }
194
+ /** Parse a query string (`a=1&b=2`) into an object via the native parser. */
195
+ export declare function parseQueryString(query: string): Record<string, string | string[]>;
196
+ /** Parse a cookie header (`a=1; b=2`) into an object via the native parser. */
197
+ export declare function parseCookieHeader(header: string): Record<string, string | string[]>;
198
+ /** Parse an application/x-www-form-urlencoded body into a key/value object. */
199
+ export declare function parseFormBody(body: Uint8Array): Record<string, string | string[]>;
200
+ /** Native JSON-Schema validator handle (see `createSchemaValidator`). */
201
+ export type SchemaValidator = SchemaValidatorInstance;
202
+ /**
203
+ * Unpack a packed u32 array: `[u32 count]{[u32 value]}` → `Uint32Array`.
204
+ * @throws {RangeError} when the buffer is shorter than `count` × 4 bytes.
205
+ */
206
+ export declare function unpackU32Array(bytes: Uint8Array): Uint32Array;
207
+ /**
208
+ * Unpack a packed bitset: `[u32 count]{bit per item}` → one 0/1 byte per item.
209
+ * @throws {RangeError} when the buffer is shorter than `count` bits.
210
+ */
211
+ export declare function unpackBitset(bytes: Uint8Array): Uint8Array;
212
+ /**
213
+ * Unpack a packed i64 array as SIGNED `BigInt64Array`.
214
+ * @throws {RangeError} when the buffer is shorter than `count` × 8 bytes.
215
+ */
216
+ export declare function unpackI64ArrayAsBigInt(bytes: Uint8Array): BigInt64Array;
217
+ /**
218
+ * Unpack a packed byte-results buffer: `[u32 count]{[u32 len][bytes]}` → one
219
+ * `Uint8Array` slice per item. The slices reference `bytes`'s backing store
220
+ * (zero-copy) — copy them if held beyond the buffer's lifetime.
221
+ */
222
+ export declare function unpackByteResults(bytes: Uint8Array): Uint8Array[];
223
+ /** A decoded `[name, value]` pair from a packed buffer. */
224
+ export type Pair = [
225
+ string,
226
+ string
227
+ ];
228
+ /**
229
+ * Decode a packed `[u32 count][u32 keyLen][key][u32 valLen][val]...` buffer
230
+ * into `[name, value]` string pairs (see `packPairs` for the layout).
231
+ */
232
+ export declare function readPairsPacked(bytes: Uint8Array): Pair[];
233
+ /**
234
+ * Fold `[name, value]` pairs into an object; repeated names collect into a
235
+ * string array (query-string/cookie semantics).
236
+ */
237
+ export declare function pairsToObject(pairs: Pair[]): Record<string, string | string[]>;
238
+ /** A decoded HTTP request from the native packed parser. */
239
+ export interface ParsedHttpRequestPacked {
240
+ method: string;
241
+ path: string;
242
+ version: string;
243
+ headers: Record<string, string>;
244
+ }
245
+ /**
246
+ * Decode a native `httpParseRequestPacked` buffer into a plain request object
247
+ * (zero-alloc on the Rust side; this builds the JS strings once).
248
+ */
249
+ export declare function readHttpPacked(bytes: Uint8Array): ParsedHttpRequestPacked;
250
+ /**
251
+ * Build a packed batch buffer. Returns an OWNED buffer (safe to hold across
252
+ * later calls) — this is the public entry point. Hot internal paths that can
253
+ * guarantee synchronous consumption should use `withPackScratch` instead.
254
+ */
255
+ export declare function packBatch(items: Uint8Array[]): Uint8Array;
256
+ /**
257
+ * Pack `[name, value]` string pairs into the native `[u32 count]...` layout
258
+ * that `readPairsPacked` / the batch validators consume.
259
+ */
260
+ export declare function packPairs(pairs: Array<[
261
+ string,
262
+ string
263
+ ]>): Uint8Array;
264
+ /** Bounds-checked section offsets for one ingress output buffer. */
265
+ export interface PackedSectionLayout {
266
+ /** Cookie-JSON length clamped to the buffer (0 if none / out of range). */
267
+ safeCookiesLen: number;
268
+ /** Byte offset where the query-JSON section begins. */
269
+ queryStart: number;
270
+ /** Query-JSON length clamped to the buffer (0 if none / out of range). */
271
+ safeQueryLen: number;
272
+ /** Byte offset where the body-JSON section begins. */
273
+ bodyJsonStart: number;
274
+ /** Body-JSON length clamped to the buffer (0 if none / out of range). */
275
+ safeBodyJsonLen: number;
276
+ /** Whether any declared section length overran the buffer. */
277
+ truncated: boolean;
278
+ }
279
+ declare abstract class IngressResultBase {
280
+ /** Raw native verdict byte (0 = accepted). */
281
+ verdict: number;
282
+ /** Raw native error-code byte. */
283
+ errorCode: number;
284
+ /** Normalized HTTP status. */
285
+ status: number;
286
+ /** Header template variant byte emitted by the native core. */
287
+ headerVariant: number;
288
+ /** Remaining rate-limit budget (count). */
289
+ rateRemaining: number;
290
+ /** Rate-limit window reset (ms epoch). */
291
+ rateResetMs: number;
292
+ /** Retry-After value (ms). */
293
+ retryAfterMs: number;
294
+ /** True when the pipeline returned a terminal (error) verdict. */
295
+ terminal: boolean;
296
+ /** True when the pipeline accepted the request (verdict 0 + 2xx/3xx). */
297
+ ok: boolean;
298
+ /** True when the request was a CORS preflight. */
299
+ isPreflight: boolean;
300
+ /** True when the CORS engine allowed the request origin. */
301
+ corsAllowed: boolean;
302
+ /** True when the request was rate-limited. */
303
+ rateLimited: boolean;
304
+ /** True when the request came from a trusted proxy. */
305
+ trustedProxy: boolean;
306
+ /** True when the request body parsed as valid JSON. */
307
+ bodyValidJson: boolean;
308
+ /** True when the request body validated against the ingress schema. */
309
+ schemaValid: boolean;
310
+ /** True when a declared output section overran the buffer. */
311
+ bodyTruncated: boolean;
312
+ /** Request body bytes (may be an empty view). */
313
+ body: Uint8Array;
314
+ protected _buf: Uint8Array;
315
+ protected _bodyJsonStart: number;
316
+ protected _bodyJsonLen: number;
317
+ private _cookiesBuf;
318
+ private _queryBuf;
319
+ private _cookiesDecoded;
320
+ private _queryDecoded;
321
+ /** Reset the shared fields to their empty state (call from subclass `invalidate`). */
322
+ protected resetShared(): void;
323
+ /** Recompute `terminal`/`ok` from the (subclass-set) verdict + status. */
324
+ protected updateOkTerminal(): void;
325
+ /**
326
+ * Store the rate-limit window fields. Both decoders read the same OUT_*
327
+ * slots and gate them on the same conditions (a positive budget OR the
328
+ * rate-limited flag), so the read cannot drift between paths.
329
+ */
330
+ protected setRateWindow(rateLimit: number, rateLimited: boolean, view: DataView): void;
331
+ /**
332
+ * Store the bounds-checked cookie/query/body JSON sections from `layout`.
333
+ *
334
+ * `bodyJsonLen` is the body-JSON length to trust for `bodyJson()`: the fast
335
+ * path passes the RAW declared length (it re-checks bounds on read), the
336
+ * baked path passes the already-clamped `layout.safeBodyJsonLen`. Sections
337
+ * are stored as slices and decoded lazily by `cookiesJson()`/`queryJson()`.
338
+ */
339
+ protected setSections(buf: Uint8Array, layout: PackedSectionLayout, bodyJsonLen: number): void;
340
+ /** Decoded cookies-JSON section, or `"{}"` when absent. */
341
+ cookiesJson(): string;
342
+ /** Decoded query-JSON section, or `"{}"` when absent. */
343
+ queryJson(): string;
344
+ /** Bounds-checked body-JSON slice (empty when absent / out of range). */
345
+ protected bodyJsonSlice(): Uint8Array;
346
+ }
347
+ /** Zero-alloc, reusable result decoder for the pre-baked handler path. */
348
+ export declare class BakedIngressResult extends IngressResultBase {
349
+ refresh(buf: Uint8Array, body: Uint8Array, view: DataView): void;
350
+ invalidate(): void;
351
+ setInternalError(): void;
352
+ bodyJson(copy: boolean): Uint8Array;
353
+ }
354
+ /** User-facing CORS configuration. */
355
+ export interface CorsOptions {
356
+ allowOrigin?: string[];
357
+ allowMethods?: string[];
358
+ allowHeaders?: string[];
359
+ exposeHeaders?: string[];
360
+ allowCredentials?: boolean;
361
+ maxAge?: number;
362
+ }
363
+ /** Precomputed, immutable CORS policy strings. */
364
+ export interface CorsStaticStrings {
365
+ readonly allowMethodsJoined: string;
366
+ readonly allowHeadersJoined: string;
367
+ readonly exposeHeadersJoined: string;
368
+ readonly maxAgeString: string | null;
369
+ readonly isWildcard: boolean;
370
+ readonly credentials: boolean;
371
+ }
372
+ /** User-facing security-headers configuration. */
373
+ export interface SecurityHeadersOptions {
374
+ contentSecurityPolicy?: string;
375
+ hsts?: boolean;
376
+ hstsMaxAge?: number;
377
+ hstsIncludeSubdomains?: boolean;
378
+ hstsPreload?: boolean;
379
+ frameOptions?: string;
380
+ nosniff?: boolean;
381
+ referrerPolicy?: string;
382
+ coep?: string;
383
+ coop?: string;
384
+ corp?: string;
385
+ xssProtection?: string;
386
+ }
387
+ /** Zero-alloc, lazy-decoding view over a native Ingress output buffer. */
388
+ export declare class FastIngressResult extends IngressResultBase {
389
+ status: number;
390
+ verdict: number;
391
+ errorCode: number;
392
+ flags: number;
393
+ https: boolean;
394
+ hasCookies: boolean;
395
+ hasQuery: boolean;
396
+ rateLimit: number;
397
+ requestId: string;
398
+ refresh(buf: Uint8Array, body: Uint8Array, requestId: string): void;
399
+ invalidate(): void;
400
+ setInternalError(requestId: string): void;
401
+ /** Bounds-checked body-JSON section, or an empty view when absent. */
402
+ bodyJson(): Uint8Array;
403
+ }
404
+ /** Options accepted by `createIngressFast` / `createIngress`. */
405
+ export interface IngressFastOptions {
406
+ trustProxy?: boolean;
407
+ trustedProxies?: {
408
+ enabled?: boolean;
409
+ networks?: string[];
410
+ };
411
+ parseCookies?: boolean;
412
+ parseQuery?: boolean;
413
+ requireJsonBody?: boolean;
414
+ schema?: Uint8Array;
415
+ cors?: CorsOptions;
416
+ rateLimit?: {
417
+ limit?: number;
418
+ windowMs?: number;
419
+ maxEntries?: number;
420
+ };
421
+ /**
422
+ * Structured security-header options (CSP/HSTS) — honored by the fast/async
423
+ * paths (`createIngressFast` throws on it; `createIngress` applies it via
424
+ * `buildResponseContext`). The PRE-BAKED path (`createIngressHandler`)
425
+ * instead takes raw `securityHeaders: [name, value][]` pairs. The two paths
426
+ * intentionally use different option shapes (see docs/INGRESS.md).
427
+ */
428
+ security?: SecurityHeadersOptions;
429
+ https?: boolean;
430
+ maxBodyBytes?: number;
431
+ enableSecurityHeaders?: boolean;
432
+ enableRequestIds?: boolean;
433
+ enableBodySizeGuard?: boolean;
434
+ emitMetadataJson?: boolean;
435
+ readBody?: boolean;
436
+ outputBufferSize?: number;
437
+ /**
438
+ * Overall deadline (ms) for reading a request body in the async
439
+ * `createIngress` path. 0 disables. Default: `DEFAULT_BODY_TIMEOUT_MS` (30s).
440
+ * Ignored by the sync `createIngressFast` (it does not read bodies).
441
+ */
442
+ bodyTimeoutMs?: number;
443
+ /**
444
+ * Invoked when the native pipeline throws (the request becomes a 500).
445
+ * Native failures are otherwise silent in the fast path. Never throws.
446
+ */
447
+ onError?: (error: Error) => void;
448
+ /**
449
+ * When true, run one probe GET at construction so the `run()` closure,
450
+ * packed pipeline and FFI ingress call are JIT-warmed before the first real
451
+ * request (cuts cold-invocation tail latency in serverless-style
452
+ * deployments). Opt-in; default false. Not forwarded to the native addon.
453
+ */
454
+ warmOnCreate?: boolean;
455
+ limits?: {
456
+ maxUrlBytes?: number;
457
+ maxQueryBytes?: number;
458
+ maxCookieBytes?: number;
459
+ maxHeadersBytes?: number;
460
+ maxHeaders?: number;
461
+ maxPairs?: number;
462
+ };
463
+ }
464
+ /** The zero-alloc sync handler returned by `createIngressFast`. */
465
+ export interface IngressFastHandler {
466
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: FastIngressResult) => T): T;
467
+ }
468
+ /**
469
+ * Options accepted by `createIngressHandler` (path 2).
470
+ *
471
+ * Same native option surface as the fast path, minus `onError` — path 2
472
+ * reports native failures through `BakedIngressRuntime.onError` instead of the
473
+ * options bag.
474
+ */
475
+ export type IngressHandlerOptions = Omit<IngressFastOptions, "onError">;
476
+ /** Public ingress options (extends the fast-path options). */
477
+ export interface IngressOptions extends IngressFastOptions {
478
+ enableRequestIds?: boolean;
479
+ /**
480
+ * Invoked before a request is processed (for tracing/context hooks).
481
+ * Only used by the async `createIngress` path.
482
+ */
483
+ onRequest?: (req: Request, requestId: string, ip: string | undefined) => void;
484
+ /**
485
+ * Invoked after a terminal context (and its `Response`) is produced, for
486
+ * metrics/logging hooks. Only used by the async `createIngress` path.
487
+ */
488
+ onResponse?: (req: Request, result: IngressContext, status: number, requestId: string) => void;
489
+ }
490
+ /**
491
+ * Readonly structural view of a decoded ingress result.
492
+ *
493
+ * Note: the exported `FastIngressResult` class is the zero-alloc implementation;
494
+ * this interface is the readonly view used by the public sync/async handlers.
495
+ */
496
+ export interface IngressResult {
497
+ readonly status: number;
498
+ readonly verdict: number;
499
+ readonly flags: number;
500
+ readonly errorCode: number;
501
+ readonly terminal: boolean;
502
+ readonly ok: boolean;
503
+ readonly https: boolean;
504
+ readonly trustedProxy: boolean;
505
+ readonly hasCookies: boolean;
506
+ readonly hasQuery: boolean;
507
+ readonly bodyValidJson: boolean;
508
+ readonly schemaValid: boolean;
509
+ readonly corsAllowed: boolean;
510
+ readonly isPreflight: boolean;
511
+ readonly rateLimited: boolean;
512
+ readonly rateLimit: number;
513
+ readonly rateRemaining: number;
514
+ readonly rateResetMs: number;
515
+ readonly retryAfterMs: number;
516
+ readonly body: Uint8Array;
517
+ readonly headerVariant: number;
518
+ readonly requestId: string;
519
+ readonly bodyTruncated: boolean;
520
+ cookiesJson(): string;
521
+ queryJson(): string;
522
+ bodyJson(): Uint8Array;
523
+ }
524
+ /** A result plus the terminal Response computed for it. */
525
+ export interface IngressContext extends IngressResult {
526
+ response: Response | null;
527
+ }
528
+ /**
529
+ * Synchronous ingress handler.
530
+ *
531
+ * The callback runs on the zero-alloc result object and MUST be synchronous:
532
+ * returning a Promise (or any thenable) throws. The result is invalidated after
533
+ * `run()` returns, so capture the fields you need inside the callback (or use
534
+ * the async {@link IngressHandler} which snapshots for you).
535
+ */
536
+ export interface SyncIngressHandler {
537
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, requestId: string, fn: (result: IngressResult) => T): T;
538
+ }
539
+ /** Async ingress handler (wraps {@link SyncIngressHandler} with body reading). */
540
+ export type IngressHandler = (req: Request, ip?: string) => Promise<IngressContext>;
541
+ /** Mutable per-request context threaded through the pre-baked handler run. */
542
+ export interface BakedContext {
543
+ /** The request-id string (null when `emitRequestIdHeader` is off). */
544
+ requestIdHeader: string | null;
545
+ /** The `Origin` request header when CORS extraction is enabled. */
546
+ origin: string | null;
547
+ }
548
+ /**
549
+ * An optimized ingress handler. `run()` is the zero-alloc pipeline entry
550
+ * point; the response-builder methods are pre-baked and bound to this
551
+ * handler's configuration, so consumers can build custom routes without
552
+ * touching header templates or error bodies.
553
+ */
554
+ export interface OptimizedIngressHandler {
555
+ run<T>(req: Request, ip: string | undefined, body: Uint8Array | null, fn: (result: BakedIngressResult, ctx: BakedContext) => T): T;
556
+ responseHeaders(variant: number, requestIdHeader: string | null, origin: string | null, rateRemaining?: number, rateResetSecs?: number, retryAfterSecs?: number): [
557
+ string,
558
+ string
559
+ ][];
560
+ terminalHeaders(variant: number, ctx: BakedContext, result: BakedIngressResult | null): [
561
+ string,
562
+ string
563
+ ][];
564
+ /** `req` is accepted for back-compat but unused by the baked terminal path. */
565
+ terminalResponse(req: Request | undefined, result: BakedIngressResult, ctx: BakedContext): Response | null;
566
+ /** `req` is accepted for back-compat but unused by the baked error path. */
567
+ errorResponse(req: Request | undefined, result: BakedIngressResult | null, status: number, code: string, message: string, ctx: BakedContext): Response;
568
+ internalErrorResponse(ctx: BakedContext, result?: BakedIngressResult): Response;
569
+ withContentType(headers: ReadonlyArray<[
570
+ string,
571
+ string
572
+ ]>, contentType: string): [
573
+ string,
574
+ string
575
+ ][];
576
+ /**
577
+ * Build a zero-copy `Response` whose body is the request's pooled output
578
+ * slice. The pooled buffer is returned to its pool once the body has been
579
+ * consumed (stream closed) or the request aborted. Use when `copyBody` is
580
+ * `false`; otherwise a copied body is released eagerly at the end of `run()`.
581
+ */
582
+ zeroCopyResponse(result: BakedIngressResult, ctx: BakedContext, init: ResponseInit): Response;
583
+ }
584
+ /** Terminal (rejection) response envelope style for responder routes.
585
+ * `"castrum"` (default) emits the pre-baked `ok:false`/`ratelimit-*` wire;
586
+ * `"ignex"` emits the ignex framework envelope (`{error,status,code}` +
587
+ * `x-frame-options`/`nosniff`/`referrer-policy` security headers). Additive —
588
+ * castrum's own wire formats are untouched. */
589
+ export type TerminalStyle = "castrum" | "ignex";
590
+ /**
591
+ * Decoded request context handed to a {@link NativeResponder} after the native
592
+ * pipeline succeeded (non-terminal). The native pipeline owns parse/validate/
593
+ * CORS/rate-limit + terminal rejections; the responder builds the 2xx body
594
+ * (async OK). Fields are captured INSIDE the sync `run()` callback, so the
595
+ * pooled output buffer is never aliased after it is released.
596
+ */
597
+ export interface NativeRequestContext {
598
+ readonly requestId: string;
599
+ readonly status: number;
600
+ readonly rateLimited: boolean;
601
+ readonly retryAfterMs: number;
602
+ /** Parsed query object (last-wins per key) — `{}` when `parseQuery` is off. */
603
+ readonly query: Record<string, string | string[]>;
604
+ /** Parsed cookie object (last-wins per key) — `{}` when `parseCookies` is off. */
605
+ readonly cookies: Record<string, string>;
606
+ /** Request body bytes when read for native validation, else empty. */
607
+ readonly body: Uint8Array;
608
+ readonly ip: string | undefined;
609
+ readonly req: Request;
610
+ }
611
+ /** A JS 2xx builder invoked after the native pipeline succeeds (async OK). */
612
+ export type NativeResponder = (snap: NativeRequestContext) => Response | Promise<Response>;
613
+ /** Options accepted by the pre-baked route factories. */
614
+ export interface BakedHandlerOptions {
615
+ /** Resolve the client IP from the server object (e.g. `srv.requestIP`). */
616
+ getIp?: (req: Request, srv: unknown) => string | undefined;
617
+ /** Copy body slices instead of sharing the native buffer. Default: true (safe). */
618
+ copyBody?: boolean;
619
+ /** Maximum request body bytes for write/echo handlers. Default: 1 MiB. */
620
+ maxBodyBytes?: number;
621
+ /**
622
+ * Overall deadline (ms) for reading the request body. Default: 30s
623
+ * (`DEFAULT_BODY_TIMEOUT_MS`). Set `0` to disable. Protects against
624
+ * slowloris / trickling bodies.
625
+ */
626
+ bodyTimeoutMs?: number;
627
+ /** Fallback handler used for write error paths. Defaults to the write ingress. */
628
+ fallback?: OptimizedIngressHandler;
629
+ /**
630
+ * When true, route the JSON-validity fallback check through the higher-order
631
+ * loader (`loader("jsonValid")`) instead of the direct native call —
632
+ * exercising the loader's dispatch + counters on the real request path.
633
+ * Default: false (the direct call is marginally faster for a single request;
634
+ * the loader pays off for same-tick bursts / bulk work, see src/integration/batch.ts).
635
+ */
636
+ enableLoader?: boolean;
637
+ }
638
+ /** A raw web-standard route handler (`Request` → `Response`), e.g. the
639
+ * health/metrics probes (`livenessHandler`, `readinessHandler`,
640
+ * `healthHandler`, `metricsHandler`). Accepted as `BakedRoute.read` and
641
+ * served for GET directly, outside the ingress pipeline. The optional third
642
+ * arg carries the matched dynamic path params (`:param`/`*`) on the Node
643
+ * adapter (Bun's native router handles matching; the ingress pipeline does
644
+ * not echo params in its response). */
645
+ type RouteHandler = (req: Request, srv?: unknown, params?: Record<string, string>) => Response | Promise<Response>;
646
+ /** Route spec for the Bun.serve builder. */
647
+ export interface BakedRoute {
648
+ /**
649
+ * Wires GET + HEAD read handlers. Accepts an optimized ingress handler OR a
650
+ * raw `RouteHandler` function (health/metrics probes are raw — see
651
+ * src/ingress/health.ts). A raw handler is served for GET only.
652
+ */
653
+ read?: OptimizedIngressHandler | RouteHandler;
654
+ /** Wires POST/PUT/PATCH JSON-write handlers (and OPTIONS fallback). */
655
+ write?: OptimizedIngressHandler;
656
+ /** Wires a POST echo handler. */
657
+ echo?: OptimizedIngressHandler;
658
+ /** Wires a GET read handler (cookies-style route). */
659
+ cookies?: OptimizedIngressHandler;
660
+ /** Wires a DELETE read-style handler. */
661
+ delete?: OptimizedIngressHandler;
662
+ /**
663
+ * A JS responder route: the native pipeline owns parse/validate/CORS/
664
+ * rate-limit + terminal rejections; the responder builds the 2xx body
665
+ * (async OK). Wired for `methods` (default GET). Built by
666
+ * `nativeResponderRoute` (src/ingress/routes/responder.ts).
667
+ */
668
+ responder?: {
669
+ /** The route's compiled native `IngressInner`. */
670
+ ingress: OptimizedIngressHandler;
671
+ /** The JS 2xx builder. */
672
+ handler: NativeResponder;
673
+ /** HTTP methods to wire (default `['GET']`). */
674
+ methods?: ReadonlyArray<string>;
675
+ /** Terminal envelope style (`'castrum'` default / `'ignex'`). */
676
+ terminalStyle?: TerminalStyle;
677
+ /** Read the body for native validation (default false — framework owns it). */
678
+ readBody?: boolean;
679
+ };
680
+ /** Overrides `maxBodyBytes` for this route's write/echo handlers. */
681
+ maxBodyBytes?: number;
682
+ /**
683
+ * Overall deadline (ms) for reading the request body on this route's
684
+ * write/echo handlers. Default: 30_000 (`DEFAULT_BODY_TIMEOUT_MS`).
685
+ * Set 0 to disable.
686
+ */
687
+ bodyTimeoutMs?: number;
688
+ }
689
+ /** RFC 6455 handshake values returned by `CreateIngressServerOptions.upgrade`. */
690
+ export interface NodeUpgradeHandshake {
691
+ /** `Sec-WebSocket-Accept` value (compute via `rust.text.wsAcceptKey`). */
692
+ accept: string;
693
+ /** Optional negotiated subprotocol (`Sec-WebSocket-Protocol`). */
694
+ protocol?: string;
695
+ }
696
+ /** Options for {@link createIngressServer}. */
697
+ export interface CreateIngressServerOptions {
698
+ port: number;
699
+ hostname?: string;
700
+ idleTimeout?: number;
701
+ maxRequestBodySize?: number;
702
+ reusePort?: boolean;
703
+ copyBody?: boolean;
704
+ getIp?: (req: Request, srv: unknown) => string | undefined;
705
+ routes: Record<string, BakedRoute>;
706
+ fallback?: OptimizedIngressHandler;
707
+ /**
708
+ * Invoked when an unhandled error escapes a request handler (currently wired
709
+ * on the Node adapter; the Bun path uses runtime.onResponse). Never throws —
710
+ * hook failures are swallowed.
711
+ */
712
+ onError?: (info: {
713
+ error: Error;
714
+ request?: Request;
715
+ }) => void;
716
+ /** Node adapter only: ms to receive the complete request (headers + body).
717
+ * Guards slowloris/trickling requests. Default: 30_000. */
718
+ requestTimeoutMs?: number;
719
+ /** Node adapter only: ms to receive the request headers. Default: 30_000. */
720
+ headersTimeoutMs?: number;
721
+ /** Node adapter only: max requests per keep-alive socket before Node forces
722
+ * a fresh connection (bounds long-lived socket reuse). Default: 1000. */
723
+ maxRequestsPerSocket?: number;
724
+ /** Node adapter only: optional WebSocket upgrade handler. Return the RFC 6455
725
+ * handshake values (see {@link NodeUpgradeHandshake}) to complete the
726
+ * handshake on the hijacked socket; return null/undefined to decline the
727
+ * upgrade. Ignored by the Bun server. (`createWebSocketUpgrade` is Bun-only
728
+ * — Node's Response cannot carry a 101.) */
729
+ upgrade?: (req: Request) => NodeUpgradeHandshake | null | undefined;
730
+ /** Node adapter only: called after a WebSocket upgrade handshake completes
731
+ * (the 101 response was accepted), with the hijacked socket so the caller
732
+ * can attach a frame codec/message loop (e.g. the `ws` library). Ignored by
733
+ * the Bun server. */
734
+ onUpgrade?: (socket: import("node:stream").Duplex, req: unknown, head: Buffer) => void;
735
+ }
736
+ /**
737
+ * Minimal surface of the running server that castrum relies on.
738
+ *
739
+ * This is intentionally NOT `ReturnType<typeof Bun.serve>` so that the public
740
+ * types stay runtime-agnostic — Node.js TypeScript consumers don't need
741
+ * `@types/bun` just to import castrum's types. Bun's server exposes far more
742
+ * fields; treat the handle as opaque.
743
+ */
744
+ export interface ServerHandle {
745
+ /** The port the server is bound to, when known (Bun exposes it; Node's
746
+ * http.Server does not — use `BakedServer.port` instead). */
747
+ port?: number;
748
+ /** Force-stop the server. Bun semantics: `true` drops active connections. */
749
+ stop(force?: boolean): void;
750
+ }
751
+ /** A running server instance plus a stop helper. */
752
+ export interface BakedServer {
753
+ server: ServerHandle;
754
+ stop(): void;
755
+ port: number;
756
+ }
757
+ /** Options for `gracefulShutdown` (drain grace period + signals). */
758
+ export interface GracefulShutdownOptions {
759
+ /** Grace period (ms) to drain in-flight requests before force-closing. */
760
+ timeoutMs?: number;
761
+ /** Signals to listen for. Default: SIGTERM + SIGINT. */
762
+ signals?: NodeJS.Signals[];
763
+ }
764
+ /**
765
+ * Wire SIGTERM/SIGINT to a graceful shutdown: soft-stop (drain in-flight
766
+ * requests) then force-close after `timeoutMs`. Works with both the Bun and
767
+ * Node server handles (both expose `stop(force?)`).
768
+ *
769
+ * Returns a cleanup function that removes the signal listeners. Call it (or
770
+ * `process.exit`) to tear down without hanging.
771
+ */
772
+ export declare function gracefulShutdown(handles: ReadonlyArray<ServerHandle>, options?: GracefulShutdownOptions): () => void;
773
+ /** A matched dynamic route: the handler map + the extracted path params. */
774
+ export interface PathMatch {
775
+ methods: Record<string, unknown>;
776
+ params: Record<string, string>;
777
+ }
778
+ /** Options for `createWebSocketUpgrade` (supported subprotocols). */ export interface WebSocketUpgradeOptions {
779
+ /** Subprotocols this server supports; the first client-requested match wins. */
780
+ protocols?: ReadonlyArray<string>;
781
+ }
782
+ /** The WebSocket upgrade handshake result (101 response + negotiation info). */
783
+ export interface WebSocketUpgradeResult {
784
+ /** The 101 Switching Protocols response — return it from your fetch handler. */
785
+ readonly response: Response;
786
+ /** The client's `Sec-WebSocket-Key` (handy for connection logging). */
787
+ readonly key: string;
788
+ /** The negotiated subprotocol, if any. */
789
+ readonly protocol: string | null;
790
+ }
791
+ /**
792
+ * Build a WebSocket 101 upgrade handshake response for a request.
793
+ *
794
+ * Validates `Sec-WebSocket-Key` presence and computes the RFC 6455 accept key
795
+ * via the native `rust.wsAcceptKey`, optionally negotiates a subprotocol, and
796
+ * returns a ready-to-serve `Response`. Returns `null` when the request is not a
797
+ * valid upgrade (missing/empty key).
798
+ *
799
+ * This only produces the handshake — pair it with your framework's own
800
+ * WebSocket server (Bun.serve's `websocket` handler, or a WS library), which
801
+ * owns the subsequent frames:
802
+ *
803
+ * @example
804
+ * ```ts
805
+ * const srv = Bun.serve({
806
+ * port: 3000,
807
+ * fetch(req, server) {
808
+ * const up = createWebSocketUpgrade(req, { protocols: ["chat"] });
809
+ * if (up && server.upgrade(req, { data: { protocol: up.protocol } })) {
810
+ * return up.response;
811
+ * }
812
+ * return new Response("Not a websocket", { status: 400 });
813
+ * },
814
+ * websocket: {
815
+ * message(ws, msg) { ws.send(msg); },
816
+ * },
817
+ * });
818
+ * ```
819
+ */
820
+ export declare function createWebSocketUpgrade(req: Request, opts?: WebSocketUpgradeOptions): WebSocketUpgradeResult | null;
821
+ /** Options accepted by `createRust` / `rust.configure`. */
822
+ export interface RustOptions {
823
+ /**
824
+ * Rayon thread pool size.
825
+ *
826
+ * The rayon pool is process-wide and initialized **once** (native
827
+ * `OnceLock`) — the first initialization wins. Importing this module
828
+ * initializes the pool with defaults, so this option only takes effect when
829
+ * the pool has not yet been created. For reliable control set
830
+ * `CASTRUM_RAYON_THREADS` / `RUST_RAYON_THREADS` before import.
831
+ * Default: max(1, hardwareConcurrency - 1).
832
+ */
833
+ rayonThreads?: number;
834
+ /** Cache MIME lookups keyed by normalized extension. Default: true. */
835
+ mimeCache?: boolean;
836
+ /** Reuse HMAC signers keyed by key-buffer identity. Default: true. */
837
+ hmacCache?: boolean;
838
+ }
839
+ /**
840
+ * The `rust.batch.*` array-of-bytes batch surface: N items in → one packed
841
+ * native call → bitsets / typed arrays / byte arrays out. Separated from the
842
+ * implementation (`./build.ts`) so type-only consumers don't pull the native
843
+ * resolver.
844
+ */
845
+ export interface RustBatch {
846
+ jsonValid(items: Uint8Array[]): Uint8Array;
847
+ crc32(items: Uint8Array[]): Uint32Array;
848
+ validateEmail(items: Uint8Array[]): Uint8Array;
849
+ validateUuid(items: Uint8Array[]): Uint8Array;
850
+ validateIpv4(items: Uint8Array[]): Uint8Array;
851
+ validateIpv6(items: Uint8Array[]): Uint8Array;
852
+ jsonSumIds(items: Uint8Array[]): BigInt64Array;
853
+ queryParse(items: Uint8Array[]): Uint8Array[];
854
+ cookieParse(items: Uint8Array[]): Uint8Array[];
855
+ httpParseRequest(items: Uint8Array[]): Uint8Array[];
856
+ jsonPatch(docs: Uint8Array[], patches: Uint8Array[]): Uint8Array[];
857
+ hexEncode(items: Uint8Array[]): Uint8Array[];
858
+ hexDecode(items: Uint8Array[]): Uint8Array[];
859
+ base64Encode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
860
+ base64Decode(items: Uint8Array[], urlSafe?: boolean, padding?: boolean): Uint8Array[];
861
+ formParse(items: Uint8Array[]): Uint8Array[];
862
+ signCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array[];
863
+ verifyCookie(items: Uint8Array[], secret: Uint8Array): Uint8Array;
864
+ csrfVerify(items: Uint8Array[], secret: Uint8Array): Uint8Array;
865
+ schemaValidate(validator: SchemaValidator, items: Uint8Array[]): Uint8Array;
866
+ schemaValidateCount(validator: SchemaValidator, items: Uint8Array[]): number;
867
+ fnv1a64(items: Uint8Array[]): BigUint64Array;
868
+ etag(items: Uint8Array[], weak?: boolean | null): Uint8Array[];
869
+ urlEncode(items: Uint8Array[]): Uint8Array[];
870
+ urlDecode(items: Uint8Array[]): Uint8Array[];
871
+ urlDecodeBytes(items: Uint8Array[]): Uint8Array[];
872
+ mimeFromExtension(items: Uint8Array[]): Uint8Array[];
873
+ wsAcceptKey(items: Uint8Array[]): Uint8Array[];
874
+ base64UrlEncode(items: Uint8Array[]): Uint8Array[];
875
+ base64UrlDecode(items: Uint8Array[]): Uint8Array[];
876
+ passwordHash(passwords: Uint8Array[], salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array[];
877
+ aeadEncrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
878
+ aeadDecrypt(key: Uint8Array, nonce: Uint8Array, items: Uint8Array[], algorithm?: string | null): Uint8Array[];
879
+ gzipCompress(items: Uint8Array[], level?: number | null): Uint8Array[];
880
+ gzipDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
881
+ brotliCompress(items: Uint8Array[], quality?: number | null): Uint8Array[];
882
+ brotliDecompress(items: Uint8Array[], maxDecompressed?: number | null): Uint8Array[];
883
+ jwtVerify(tokens: Uint8Array[], secret: Uint8Array, nowSeconds: number): Uint8Array;
884
+ hmacSha256(items: Uint8Array[], key: Uint8Array): Uint8Array[];
885
+ hmacSha256Verify(items: Uint8Array[], sigs: Uint8Array[], key: Uint8Array): Uint8Array;
886
+ passwordVerify(items: Uint8Array[], phcs: Uint8Array[]): Uint8Array;
887
+ urlResolve(bases: Uint8Array[], references: Uint8Array[]): Uint8Array[];
888
+ jwtSign(items: Uint8Array[], secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array[];
889
+ sseEncode(items: Uint8Array[], event?: string | null, id?: string | null, retry?: number | null): Uint8Array[];
890
+ wsFrameEncode(items: Uint8Array[], opcode: number, mask: boolean, fin: boolean): Uint8Array[];
891
+ wsFrameDecode(items: Uint8Array[]): Uint8Array[];
892
+ multipartParse(items: Uint8Array[], boundary: Uint8Array): MultipartPart[][];
893
+ templateRender(source: string, contexts: Uint8Array[]): Uint8Array[];
894
+ }
895
+ /** Raw packed-wire FFI namespace. */
896
+ export interface RustPacked {
897
+ crc32BatchPacked(input: Uint8Array): Uint8Array;
898
+ jsonValidBatchPacked(input: Uint8Array): Uint8Array;
899
+ validateEmailBatchPacked(input: Uint8Array): Uint8Array;
900
+ validateUuidBatchPacked(input: Uint8Array): Uint8Array;
901
+ validateIpv4BatchPacked(input: Uint8Array): Uint8Array;
902
+ validateIpv6BatchPacked(input: Uint8Array): Uint8Array;
903
+ jsonSumBatchPacked(input: Uint8Array): Uint8Array;
904
+ queryParseBatchPacked(input: Uint8Array): Uint8Array;
905
+ cookieParseBatchPacked(input: Uint8Array): Uint8Array;
906
+ httpParseRequestBatchPacked(input: Uint8Array): Uint8Array;
907
+ /** Batch RFC 6902 JSON Patch (two packed lists, zipped) → packed results. */
908
+ jsonPatchBatchPacked(docs: Uint8Array, patches: Uint8Array): Uint8Array;
909
+ /** Packed FNV-1a 64 batch (i64 per item). */
910
+ fnv1A64BatchPacked(input: Uint8Array): Uint8Array;
911
+ /** Packed ETag batch (10 strong / 12 weak bytes per item). */
912
+ etagBatchPacked(input: Uint8Array, weak?: boolean | null): Uint8Array;
913
+ urlEncodeBatchPacked(input: Uint8Array): Uint8Array;
914
+ urlDecodeBatchPacked(input: Uint8Array): Uint8Array;
915
+ urlDecodeBytesBatchPacked(input: Uint8Array): Uint8Array;
916
+ mimeFromExtensionBatchPacked(input: Uint8Array): Uint8Array;
917
+ wsAcceptKeyBatchPacked(input: Uint8Array): Uint8Array;
918
+ jsonValidBatchCountPacked(input: Uint8Array): number;
919
+ validateEmailBatchCountPacked(input: Uint8Array): number;
920
+ validateUuidBatchCountPacked(input: Uint8Array): number;
921
+ validateIpv4BatchCountPacked(input: Uint8Array): number;
922
+ validateIpv6BatchCountPacked(input: Uint8Array): number;
923
+ jsonSumBatchTotalPacked(input: Uint8Array): number;
924
+ queryParseBatchTotalLenPacked(input: Uint8Array): number;
925
+ cookieParseBatchTotalLenPacked(input: Uint8Array): number;
926
+ httpParseRequestBatchTotalLenPacked(input: Uint8Array): number;
927
+ passwordHashBatchPacked(input: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array;
928
+ /** Packed password-verify batch (two packed lists, zipped) → bitset. */
929
+ passwordVerifyBatchPacked(passwords: Uint8Array, phcs: Uint8Array): Uint8Array;
930
+ /** Packed URL-resolve batch (two packed lists, zipped) → packed results. */
931
+ urlResolveBatchPacked(bases: Uint8Array, references: Uint8Array): Uint8Array;
932
+ aeadEncryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
933
+ aeadDecryptBatchPacked(input: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null): Uint8Array;
934
+ gzipCompressBatchPacked(input: Uint8Array, level?: number | null): Uint8Array;
935
+ gzipDecompressBatchPacked(input: Uint8Array): Uint8Array;
936
+ brotliCompressBatchPacked(input: Uint8Array, quality?: number | null): Uint8Array;
937
+ brotliDecompressBatchPacked(input: Uint8Array): Uint8Array;
938
+ jwtSignBatchPacked(input: Uint8Array, secret: Uint8Array, ttlSeconds: number | null, nowSeconds: number): Uint8Array;
939
+ jwtVerifyBatchPacked(input: Uint8Array, secret: Uint8Array, nowSeconds: number): Uint8Array;
940
+ /** Batch HMAC-SHA256 sign (packed in → hex-signature byte results). */
941
+ hmacSha256BatchPacked(input: Uint8Array, key: Uint8Array): Uint8Array;
942
+ /** Batch HMAC-SHA256 verify (two packed lists: data + hex sigs, zipped) → bitset. */
943
+ hmacSha256VerifyBatchPacked(input: Uint8Array, sigs: Uint8Array, key: Uint8Array): Uint8Array;
944
+ multipartParseBatchPacked(input: Uint8Array, boundary: Uint8Array): Uint8Array;
945
+ templateRenderBatchPacked(input: Uint8Array, source: string): Uint8Array;
946
+ sseEncodeBatchPacked(input: Uint8Array, event: string | null, id: string | null, retry: number | null): Uint8Array;
947
+ wsFrameEncodeBatchPacked(input: Uint8Array, opcode: number, mask: boolean, fin: boolean): Uint8Array;
948
+ wsFrameDecodeBatchPacked(input: Uint8Array): Uint8Array;
949
+ }
950
+ /**
951
+ * The flat `rust.*` scalar method surface: bytes in → normalized out. Built by
952
+ * the scalar builders from the native addon + Bun built-in delegations.
953
+ */
954
+ export interface RustScalar {
955
+ crc32(input: Uint8Array): number;
956
+ fnv1a64(input: Uint8Array): bigint;
957
+ /**
958
+ * XXH3-64 over raw bytes (high-throughput non-cryptographic hash).
959
+ * Compare against `Bun.hash.xxHash3` — see docs/bun-builtins-decision-matrix.md.
960
+ */
961
+ xxh3(input: Uint8Array): bigint;
962
+ hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array | string;
963
+ hmacSha256Verify(key: Uint8Array, data: Uint8Array, sig: Uint8Array | string): boolean;
964
+ jsonValid(input: Uint8Array): boolean;
965
+ /**
966
+ * Parse JSON to a JS value (FFI packed structural parse on Bun — sonic-rs
967
+ * parses ONCE, JS assembles from a token stream with no re-parse; napi
968
+ * sonic-rs DOM fallback). Throws on invalid JSON.
969
+ */
970
+ jsonParse(input: Uint8Array): unknown;
971
+ jsonSumIds(input: Uint8Array): bigint;
972
+ jsonPatch(doc: Uint8Array, patch: Uint8Array): Uint8Array | string;
973
+ mimeFromExtension(ext: Uint8Array): Uint8Array | string;
974
+ randomToken(byteLen: number): Uint8Array | string;
975
+ randomTokenInto(byteLen: number, output: Uint8Array): number;
976
+ urlEncode(input: Uint8Array): Uint8Array | string;
977
+ urlDecode(input: Uint8Array): Uint8Array;
978
+ /**
979
+ * Strict percent-decode without UTF-8 validation.
980
+ */
981
+ urlDecodeBytes(input: Uint8Array): Uint8Array;
982
+ urlEncodeInto(input: Uint8Array, output: Uint8Array): number;
983
+ urlDecodeInto(input: Uint8Array, output: Uint8Array): number;
984
+ validateEmail(input: Uint8Array): boolean;
985
+ validateUuid(input: Uint8Array): boolean;
986
+ validateIpv4(input: Uint8Array): boolean;
987
+ validateIpv6(input: Uint8Array): boolean;
988
+ wsAcceptKey(key: Uint8Array): Uint8Array | string;
989
+ wsAcceptKeyInto(key: Uint8Array, output: Uint8Array): number;
990
+ httpParseRequestPacked(input: Uint8Array): Uint8Array;
991
+ queryParsePacked(input: Uint8Array): Uint8Array;
992
+ cookieParsePacked(input: Uint8Array): Uint8Array;
993
+ httpParseRequestPackedInto(input: Uint8Array, output: Uint8Array): number;
994
+ queryParsePackedInto(input: Uint8Array, output: Uint8Array): number;
995
+ cookieParsePackedInto(input: Uint8Array, output: Uint8Array): number;
996
+ /**
997
+ * Parse an application/x-www-form-urlencoded body into packed pairs.
998
+ */
999
+ formParsePacked(input: Uint8Array): Uint8Array;
1000
+ formParsePackedInto(input: Uint8Array, output: Uint8Array): number;
1001
+ /**
1002
+ * Parse a Content-Type header into a structured media type.
1003
+ */
1004
+ parseMediaType(input: Uint8Array): MediaTypeResult;
1005
+ /**
1006
+ * Generate a strong/weak ETag (crc32-based).
1007
+ */
1008
+ etag(data: Uint8Array, weak?: boolean): Uint8Array | string;
1009
+ etagInto(data: Uint8Array, output: Uint8Array, weak?: boolean): number;
1010
+ /**
1011
+ * Format a unix timestamp as an IMF-fixdate HTTP-date.
1012
+ */
1013
+ httpDate(secs?: number): Uint8Array | string;
1014
+ httpDateInto(secs: number | undefined, output: Uint8Array): number;
1015
+ parseHttpDate(input: Uint8Array): bigint | null;
1016
+ parseAcceptEncoding(input: Uint8Array): EncodingPrefResult[];
1017
+ /**
1018
+ * Base64 encode (standard by default; url-safe/padding configurable).
1019
+ */
1020
+ base64Encode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array | string;
1021
+ /**
1022
+ * Base64 decode (standard); throws on invalid input.
1023
+ */
1024
+ base64Decode(input: Uint8Array, urlSafe?: boolean, padding?: boolean): Uint8Array;
1025
+ base64EncodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
1026
+ base64DecodeInto(input: Uint8Array, output: Uint8Array, urlSafe?: boolean, padding?: boolean): number;
1027
+ base64UrlEncode(input: Uint8Array): Uint8Array | string;
1028
+ base64UrlDecode(input: Uint8Array): Uint8Array;
1029
+ /**
1030
+ * Lowercase hex encode.
1031
+ */
1032
+ hexEncode(input: Uint8Array): Uint8Array | string;
1033
+ /**
1034
+ * Hex decode; throws on odd length or invalid digits.
1035
+ */
1036
+ hexDecode(input: Uint8Array): Uint8Array;
1037
+ hexEncodeInto(input: Uint8Array, output: Uint8Array): number;
1038
+ hexDecodeInto(input: Uint8Array, output: Uint8Array): number;
1039
+ hmacSha256Into(key: Uint8Array, data: Uint8Array, output: Uint8Array): number;
1040
+ signCookieInto(value: Uint8Array, secret: Uint8Array, output: Uint8Array): number;
1041
+ verifyCookieInto(signed: Uint8Array, secret: Uint8Array, output: Uint8Array): number | null;
1042
+ csrfTokenInto(secret: Uint8Array, output: Uint8Array): number;
1043
+ aeadEncryptInto(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, output: Uint8Array, algorithm?: string | null): number;
1044
+ wsFrameEncodeInto(opcode: number, payload: Uint8Array, mask: boolean, fin: boolean, output: Uint8Array): number;
1045
+ gzipCompressInto(data: Uint8Array, output: Uint8Array, level?: number | null): number;
1046
+ brotliCompressInto(data: Uint8Array, output: Uint8Array, quality?: number | null): number;
1047
+ /**
1048
+ * Sign a cookie value as `value.signature` (HMAC-SHA256 hex).
1049
+ */
1050
+ signCookie(value: Uint8Array, secret: Uint8Array): Uint8Array | string;
1051
+ /**
1052
+ * Verify a signed cookie; returns the value or null.
1053
+ */
1054
+ verifyCookie(signed: Uint8Array, secret: Uint8Array): Uint8Array | string | null;
1055
+ /**
1056
+ * Create a CSRF token (32-byte random hex + HMAC signature).
1057
+ */
1058
+ csrfToken(secret: Uint8Array): Uint8Array | string;
1059
+ /**
1060
+ * Constant-time verify a CSRF token.
1061
+ */
1062
+ csrfVerify(token: Uint8Array, secret: Uint8Array): boolean;
1063
+ /**
1064
+ * Resolve a URL reference against a base (RFC 3986).
1065
+ */
1066
+ urlResolve(base: Uint8Array, reference: Uint8Array): Uint8Array | string;
1067
+ /**
1068
+ * Build a percent-encoded query string from params (sorted keys).
1069
+ */
1070
+ urlEncodeQuery(params: Record<string, string>): Uint8Array | string;
1071
+ createSchemaValidator(schema: Uint8Array): SchemaValidatorInstance;
1072
+ createHmacSigner(key: Uint8Array): HmacSignerInstance;
1073
+ createTemplateRenderer(source: string): TemplateRendererInstance;
1074
+ createFormParser(capacity?: number): FormParserInstance;
1075
+ createMediaTypeParser(): MediaTypeParserInstance;
1076
+ /**
1077
+ * Higher-order conditional-request check: per-resource 304 decision (setup once).
1078
+ */
1079
+ createConditionalRequest(etagValue: Uint8Array, lastModifiedSecs?: number): ConditionalRequestInstance;
1080
+ /**
1081
+ * Higher-order negotiator: precompiles supported encodings once.
1082
+ */
1083
+ createAcceptNegotiator(supported: string[]): AcceptNegotiatorInstance;
1084
+ createBase64Codec(urlSafe?: boolean, padding?: boolean): Base64CodecInstance;
1085
+ createCookieSigner(secret: Uint8Array): CookieSignerInstance;
1086
+ createCsrfProtector(secret: Uint8Array): CsrfProtectorInstance;
1087
+ createUrlBuilder(base: Uint8Array): UrlBuilderInstance;
1088
+ createJwtSigner(secret: Uint8Array, ttlSeconds?: number): JwtSignerInstance;
1089
+ createAeadCipher(key: Uint8Array, algorithm?: string): AeadCipherInstance;
1090
+ createArgon2Hasher(options?: PasswordHashOptions | null): Argon2HasherInstance;
1091
+ createMediaTypeMatcher(expected: Uint8Array): MediaTypeMatcherInstance;
1092
+ /**
1093
+ * Sharded fixed-window per-key rate limiter. `maxEntries` clamps internally
1094
+ * (default 1,048,576). Each instance owns an independent budget.
1095
+ * @remarks Scalar per-check cost: ~3-14x SLOWER than the JS Map baseline —
1096
+ * prefer the ingress pipeline (one FFI for all stages) for native rate
1097
+ * limiting in a request path. [measured 2026-08]
1098
+ */
1099
+ createRateLimiter(limit: number, windowMs: number, maxEntries?: number | null): RateLimiterInstance;
1100
+ initThreadPool(rayonThreads?: number): void;
1101
+ rayonNumThreads(): number;
1102
+ jwtSign(claims: Record<string, unknown>, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array;
1103
+ /**
1104
+ * Sign a JWT from pre-serialized claim JSON bytes — skips the napi
1105
+ * `serde_json::Value` marshal of `jwtSign` for callers that already hold the
1106
+ * bytes (same injection semantics).
1107
+ */
1108
+ jwtSignBytes(claimsJson: Uint8Array, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): Uint8Array | string;
1109
+ jwtSignBytesInto(claimsJson: Uint8Array, secret: Uint8Array, output: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number): number;
1110
+ jwtVerify(token: Uint8Array, secret: Uint8Array, nowSeconds?: number): unknown;
1111
+ passwordHash(password: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null): Uint8Array | string;
1112
+ passwordVerify(password: Uint8Array, phc: Uint8Array): boolean;
1113
+ /**
1114
+ * bcrypt password hash → `$2b$` PHC string (cost clamped 4..=31).
1115
+ */
1116
+ passwordHashBcrypt(password: Uint8Array, cost: number): string;
1117
+ /**
1118
+ * Verify a password against a bcrypt `$2b$` PHC string.
1119
+ */
1120
+ passwordVerifyBcrypt(password: Uint8Array, hash: string): boolean;
1121
+ /**
1122
+ * PBKDF2-HMAC-SHA256 key derivation (dkLen clamped to 1 MiB).
1123
+ */
1124
+ pbkdf2Sha256(password: Uint8Array, salt: Uint8Array, rounds: number, dkLen: number): Uint8Array;
1125
+ aeadEncrypt(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array, algorithm?: string | null): Uint8Array;
1126
+ aeadDecrypt(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array, algorithm?: string | null): Uint8Array | null;
1127
+ gzipCompress(data: Uint8Array, level?: number | null): Uint8Array;
1128
+ /**
1129
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1130
+ * decompression-bomb guard; a larger value errors.
1131
+ */
1132
+ gzipDecompress(data: Uint8Array, maxDecompressed?: number | null): Uint8Array;
1133
+ /**
1134
+ * gzip-decompress into `output` (pooled — caller-owned buffer); returns bytes
1135
+ * written. Throws when `output` is too small (the exact required size is
1136
+ * reported) or the input is invalid / exceeds `maxDecompressed`.
1137
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1138
+ * decompression-bomb guard; a larger value errors.
1139
+ */
1140
+ gzipDecompressInto(data: Uint8Array, output: Uint8Array, maxDecompressed?: number | null): number;
1141
+ brotliCompress(data: Uint8Array, quality?: number | null): Uint8Array;
1142
+ /**
1143
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1144
+ * decompression-bomb guard; a larger value errors.
1145
+ */
1146
+ brotliDecompress(data: Uint8Array, maxDecompressed?: number | null): Uint8Array;
1147
+ /**
1148
+ * brotli-decompress into `output` (pooled — caller-owned buffer); returns
1149
+ * bytes written. Throws when `output` is too small (the exact required size
1150
+ * is reported) or the input is invalid / exceeds `maxDecompressed`.
1151
+ * @param maxDecompressed Caps decompressed output (default 64 MiB) as a
1152
+ * decompression-bomb guard; a larger value errors.
1153
+ */
1154
+ brotliDecompressInto(data: Uint8Array, output: Uint8Array, maxDecompressed?: number | null): number;
1155
+ multipartParse(body: Uint8Array, boundary: Uint8Array): MultipartPart[];
1156
+ multipartParsePacked(body: Uint8Array, boundary: Uint8Array): Uint8Array;
1157
+ multipartParsePackedInto(body: Uint8Array, boundary: Uint8Array, output: Uint8Array): number;
1158
+ wsFrameEncode(opcode: number, payload: Uint8Array, mask: boolean, fin: boolean): Uint8Array;
1159
+ wsFrameDecode(data: Uint8Array): WsFrame | null;
1160
+ wsFrameDecodePackedInto(data: Uint8Array, output: Uint8Array): number | null;
1161
+ sseEncodeEvent(event: string | null, data: Uint8Array, id: string | null, retry: number | null): Uint8Array;
1162
+ sseEncodeEventInto(event: string | null, data: Uint8Array, id: string | null, retry: number | null, output: Uint8Array): number;
1163
+ }
1164
+ /** String-oriented FFI namespace. */
1165
+ export interface RustText {
1166
+ /**
1167
+ * Resolve a lowercase file extension to a MIME type string (e.g. `"html"` →
1168
+ * `"text/html"`). Unknown extensions return `"application/octet-stream"`.
1169
+ * @param ext the file extension WITHOUT a leading dot, case-insensitive.
1170
+ * @returns the MIME type for `ext`.
1171
+ */
1172
+ mimeFromExtension(ext: string): string;
1173
+ /**
1174
+ * RFC 3986 percent-encode a string (the `encodeURIComponent` unreserved
1175
+ * set). Under Bun this delegates to the native `encodeURIComponent` for
1176
+ * ~4x speed with byte-for-byte parity.
1177
+ * @param input the string to encode.
1178
+ * @returns the percent-encoded string.
1179
+ */
1180
+ urlEncode(input: string): string;
1181
+ /**
1182
+ * Percent-decode a string. Throws on malformed `%XX` or invalid UTF-8
1183
+ * output (parity with `decodeURIComponent`, which is used under Bun).
1184
+ * @param input the percent-encoded string to decode.
1185
+ * @returns the decoded string.
1186
+ */
1187
+ urlDecode(input: string): string;
1188
+ /**
1189
+ * Compute the RFC 6455 `Sec-WebSocket-Accept` value for a client key.
1190
+ * @param key the base64 `Sec-WebSocket-Key` header value.
1191
+ * @returns the 28-byte base64 accept value.
1192
+ */
1193
+ wsAcceptKey(key: string): string;
1194
+ /** @param input an email address. @returns whether it is RFC-valid. */
1195
+ validateEmail(input: string): boolean;
1196
+ /** @param input a UUID string. @returns whether it is a valid (v1-v8) UUID. */
1197
+ validateUuid(input: string): boolean;
1198
+ /** @param input an IPv4 address. @returns whether it is valid. */
1199
+ validateIpv4(input: string): boolean;
1200
+ /** @param input an IPv6 address. @returns whether it is valid. */
1201
+ validateIpv6(input: string): boolean;
1202
+ }
1203
+ /** The full Rust FFI client (scalar methods + namespaces + configuration). */
1204
+ export interface RustClient extends RustScalar {
1205
+ text: RustText;
1206
+ batch: RustBatch;
1207
+ packed: RustPacked;
1208
+ /**
1209
+ * Resolve the native transport in use on this runtime: `"ffi"` (bun:ffi —
1210
+ * the PRIMARY transport under Bun) or `"napi"` (Node, forced
1211
+ * `CASTRUM_FFI_MODE=napi`, or a failed ffi bind-time self-test).
1212
+ */
1213
+ transport(): "ffi" | "napi";
1214
+ /** Whether the bun:ffi transport is live (equivalent to `transport() === "ffi"`). */
1215
+ ffiActive(): boolean;
1216
+ /**
1217
+ * Update defaults on this instance. `mimeCache` / `hmacCache` apply
1218
+ * immediately (per-instance). `rayonThreads` is applied only if the
1219
+ * process-wide pool is not yet initialized (see {@link RustOptions}).
1220
+ */
1221
+ configure(options: RustOptions): void;
1222
+ }
1223
+ /**
1224
+ * Create an isolated Rust client with the given defaults.
1225
+ *
1226
+ * `mimeCache` / `hmacCache` are per-instance. `rayonThreads` only applies
1227
+ * before the process-wide rayon pool is initialized (once per process — see
1228
+ * {@link RustOptions.rayonThreads}); the pool defaults to the env var or
1229
+ * `max(1, hardwareConcurrency - 1)` otherwise.
1230
+ */
1231
+ export declare function createRust(options?: RustOptions): RustClient;
1232
+ /**
1233
+ * The default, ready-to-use `RustClient` created with no options (resolves
1234
+ * rayon threads from the host automatically). Most consumers just do
1235
+ * `import { rust } from "castrum"` and call `rust.<fn>(...)` directly.
1236
+ */
1237
+ export declare const rust: RustClient;
1238
+ /** The benchmark-proven default implementation for an op. */
1239
+ export type ProvenImpl = "native" | "js" | "bun";
1240
+ /** How decisive the baked winner is. */
1241
+ export type ProvenStatus = "proven" | "parity" | "unmeasured";
1242
+ /** One entry in the baked proven-selection registry. */
1243
+ export interface ProvenEntry {
1244
+ /** Selection op name (matches `opImpl(op)` / `src/selection.json` keys). */
1245
+ name: string;
1246
+ /** The baked default implementation: the benchmark-proven winner. */
1247
+ impl: ProvenImpl;
1248
+ /** `proven` = decisive win, `parity` = borderline, `unmeasured` = pinned by policy. */
1249
+ status: ProvenStatus;
1250
+ /** Measured ratio behind the decision (see module doc for the axis). */
1251
+ typicalRatio?: number;
1252
+ /** Why this classification. */
1253
+ note?: string;
1254
+ }
1255
+ /**
1256
+ * Baked proven-winner registry. Covering the FULL selection surface
1257
+ * (`src/selection.json` ops + every Bun built-in delegation) so nothing can be
1258
+ * silently dropped. Classifications are based on release/perf-build results;
1259
+ * `test/unit/shared/proven.test.ts` re-checks them against the LIVE wiring.
1260
+ */
1261
+ export declare const PROVEN_SELECTION: readonly ProvenEntry[];
1262
+ /**
1263
+ * The baked {@link ProvenEntry} for `op`, or `undefined` for unknown ops.
1264
+ * Pure data — never dlopens the addon.
1265
+ */
1266
+ export declare function provenEntry(op: string): ProvenEntry | undefined;
1267
+ /** The baked default implementation for `op` (`native` / `js` / `bun`), or `null`. */
1268
+ export declare function provenImpl(op: string): ProvenImpl | null;
1269
+ /** The baked status for `op`, or `null` for unknown ops. */
1270
+ export declare function provenStatus(op: string): ProvenStatus | null;
1271
+ /** Whether the op's baked winner is a decisive (`proven`) win. */
1272
+ export declare function isProven(op: string): boolean;
1273
+ /** The full baked registry (same array as {@link PROVEN_SELECTION}). */
1274
+ export declare function provenSurface(): readonly ProvenEntry[];
1275
+ /** A one-line summary of the baked selection (counts per implementation). */
1276
+ export declare function provenSummary(): string;
1277
+ /** The full `rust.*` surface — identical to `rust`; the proven wiring is baked (see {@link ../shared/proven}). */
1278
+ export type ProvenClient = RustClient;
1279
+ /** The full `rust.*` surface, exposed for audit. Same object as `rust`. */
1280
+ export declare const proven: ProvenClient;
1281
+ /** Recommended implementation for an operation. */
1282
+ export type OpImpl = "native" | "js";
1283
+ /** A selection decision: recommended implementation + rationale note. */
1284
+ export interface OpDecision {
1285
+ /** The recommended implementation when the addon is available. */
1286
+ readonly impl: OpImpl;
1287
+ /** Why this decision (measured ratio / rationale). */
1288
+ readonly note?: string;
1289
+ }
1290
+ /**
1291
+ * The benchmark-driven native-vs-JS decision for `op` — runtime-aware.
1292
+ *
1293
+ * Returns `"native"` when the Rust addon is the recommended implementation,
1294
+ * `"js"` when a pure-JS (or Bun built-in) implementation wins, or `null` for
1295
+ * unknown ops (or when the addon is unavailable — with no addon there is no
1296
+ * "native" choice). Under Bun, ops in the adapter's builtins registry resolve
1297
+ * to `"js"` so the consumer's JS path delegates to the faster Bun built-in.
1298
+ *
1299
+ * The default is the BAKED proven selection (`src/shared/proven.ts`):
1300
+ * `native` / `js` directly, `bun` resolves to `"js"` via the builtins check
1301
+ * above. Unknown ops (and `bun` entries on a non-Bun runtime, where no
1302
+ * built-in exists) fall back to the addon's embedded decision
1303
+ * (`rust/selection.rs` ← `src/selection.json`).
1304
+ */
1305
+ export declare const opImpl: (op: string) => OpImpl | null;
1306
+ /** `true` when the Rust addon is the recommended impl for `op`. */
1307
+ export declare const isNativeOp: (op: string) => boolean;
1308
+ /** The decision record for `op`, or `null` when unknown. */
1309
+ export declare const opDecision: (op: string) => OpDecision | null;
1310
+ /**
1311
+ * Shared UTF-8 encoder (encode / encodeInto), backed by the runtime-native
1312
+ * codec (`src/shared/codec.ts`): on Bun the work is done by Bun's native
1313
+ * transfer machinery (`Bun.ArrayBufferSink` / a zero-copy `Buffer` view
1314
+ * write); under Node it falls back to `TextEncoder`. Reusing a single object
1315
+ * avoids allocation overhead in hot paths.
1316
+ *
1317
+ * `encode` accepts the string-or-bytes union the text-returning `rust.*` ops
1318
+ * surface (Bun returns strings, Node returns bytes) and normalizes to bytes —
1319
+ * a string is UTF-8 encoded, bytes pass through unchanged.
1320
+ */
1321
+ export declare const encoder: {
1322
+ encode(s: Uint8Array | string): Uint8Array;
1323
+ encodeInto(s: string, dest: Uint8Array): {
1324
+ read: number;
1325
+ written: number;
1326
+ };
1327
+ };
1328
+ /**
1329
+ * Shared UTF-8 decoder, backed by the runtime-native codec
1330
+ * (`src/shared/codec.ts`): on Bun it uses `new CString(ptr, 0, len)` from
1331
+ * `bun:ffi` (JSC-native, exact-length clone); under Node it falls back to
1332
+ * `TextDecoder`. Reusing a single object avoids allocation overhead in hot
1333
+ * paths.
1334
+ *
1335
+ * `decode` accepts the string-or-bytes union the text-returning `rust.*` ops
1336
+ * surface and normalizes to a string — bytes are UTF-8 decoded, strings pass
1337
+ * through unchanged.
1338
+ */
1339
+ export declare const decoder: {
1340
+ decode(bytes: Uint8Array | string): string;
1341
+ };
1342
+ /** Options for an `AdaptiveEstimate`: EWMA smoothing, bounds, starting value. */ export interface AdaptiveEstimateOptions {
1343
+ /**
1344
+ * EWMA smoothing factor in (0, 1]. Higher reacts faster to new samples;
1345
+ * lower smooths more. Default: 0.25.
1346
+ */
1347
+ alpha?: number;
1348
+ /** Starting estimate. Default 0 (the first sample wins). */
1349
+ initial?: number;
1350
+ /** Clamp the estimate to at least this. Default 0. */
1351
+ min?: number;
1352
+ /** Clamp the estimate to at most this (bounds memory / resources). Default Infinity. */
1353
+ max?: number;
1354
+ }
1355
+ /**
1356
+ * A bounded exponential-moving-average estimate of an observed quantity.
1357
+ *
1358
+ * `sample(x)` folds a new observation into the running estimate; `estimate`
1359
+ * reads the current value. The estimate is clamped to `[min, max]`, so it is
1360
+ * safe to drive resource sizing (buffer pools, batch thresholds) with it —
1361
+ * a single outlier cannot blow up the estimate, and it decays toward recent
1362
+ * observations.
1363
+ */
1364
+ export declare class AdaptiveEstimate {
1365
+ private readonly alpha;
1366
+ private readonly min;
1367
+ private readonly max;
1368
+ private readonly initial;
1369
+ private value;
1370
+ constructor(options?: AdaptiveEstimateOptions);
1371
+ /** Fold a new observation into the running estimate. */
1372
+ sample(x: number): void;
1373
+ /** Current estimate (clamped to `[min, max]`). */
1374
+ get estimate(): number;
1375
+ /** Reset the estimate (back to `initial`). */
1376
+ reset(): void;
1377
+ }
1378
+ /**
1379
+ * Generate a UUIDv7 (time-ordered) string, preferring Bun's native built-in.
1380
+ * Under Node this falls back to `crypto.randomUUID` (v4).
1381
+ *
1382
+ * @returns A UUID string.
1383
+ */
1384
+ export declare const uuidv7: () => string;
1385
+ /** Default histogram buckets (Prometheus-style, seconds). */
1386
+ export declare const DEFAULT_BUCKETS: readonly number[];
1387
+ export type Labels = Readonly<Record<string, string>>;
1388
+ /** A single labelled counter value. */
1389
+ export interface Counter {
1390
+ /** Increment by 1 (or `by`). `labels` must match the label names exactly. */
1391
+ inc(labels?: Labels, by?: number): void;
1392
+ }
1393
+ /** A single labelled gauge value (can go up and down). */
1394
+ export interface Gauge {
1395
+ inc(labels?: Labels, by?: number): void;
1396
+ dec(labels?: Labels, by?: number): void;
1397
+ set(labels: Labels | undefined, value: number): void;
1398
+ }
1399
+ /** A single labelled histogram. */
1400
+ export interface Histogram {
1401
+ /** Record one observation. `labels` must match the label names exactly. */
1402
+ observe(value: number, labels?: Labels): void;
1403
+ }
1404
+ /** The metrics registry factory. */
1405
+ export interface MetricsRegistry {
1406
+ /** Create (or fetch) a counter. `help` is only used on first creation. */
1407
+ counter(name: string, help: string, labelNames?: readonly string[]): Counter;
1408
+ /** Create (or fetch) a gauge. */
1409
+ gauge(name: string, help: string, labelNames?: readonly string[]): Gauge;
1410
+ /**
1411
+ * Create (or fetch) a histogram. `buckets`/`help` only apply on first
1412
+ * creation; later calls with the same name return the existing histogram.
1413
+ */
1414
+ histogram(name: string, help: string, buckets?: readonly number[], labelNames?: readonly string[]): Histogram;
1415
+ /** Render the Prometheus text exposition format. */
1416
+ render(): string;
1417
+ /** Reset all metrics (for tests / interval rotation). */
1418
+ reset(): void;
1419
+ }
1420
+ /** Create a fresh metrics registry. */
1421
+ export declare function createMetrics(): MetricsRegistry;
1422
+ /**
1423
+ * Create the runtime-appropriate ingress server: `Bun.serve` on Bun, the
1424
+ * `node:http` adapter on Node. Selected ONCE at module load — the branch
1425
+ * never runs in the hot path.
1426
+ */
1427
+ export declare function createIngressServer(options: CreateIngressServerOptions): BakedServer;
1428
+ /**
1429
+ * Generate the next request ID as 16 lowercase hex bytes (zero-alloc).
1430
+ *
1431
+ * @returns A shared buffer aliased across calls — decode/copy before the next
1432
+ * `generateRequestId()` invocation.
1433
+ */
1434
+ export declare function generateRequestId(): Uint8Array;
1435
+ /** A parsed W3C trace context (valid per the spec's length/hex rules). */
1436
+ export interface TraceContext {
1437
+ /** Version, always `"00"` for accepted headers. */
1438
+ version: string;
1439
+ /** 32 hex chars — the trace id (shared across the whole trace). */
1440
+ traceId: string;
1441
+ /** 16 hex chars — the current span id. */
1442
+ spanId: string;
1443
+ /** The flags byte (bit 0 = sampled). */
1444
+ flags: number;
1445
+ /** True when the `sampled` (bit 0) flag is set. */
1446
+ sampled: boolean;
1447
+ }
1448
+ /**
1449
+ * Parse a `traceparent` header value into a {@link TraceContext}, or `null`
1450
+ * when malformed (wrong version / length / non-hex). Invalid contexts are
1451
+ * ignored per the spec — callers should generate a fresh trace then.
1452
+ */
1453
+ export declare function parseTraceParent(header: string | null | undefined): TraceContext | null;
1454
+ /** Random 32-hex trace id (crypto-backed where available). */
1455
+ export declare function createTraceId(): string;
1456
+ /** Random 16-hex span id. */
1457
+ export declare function createSpanId(): string;
1458
+ /** Serialize a trace context back to a `traceparent` header value. */
1459
+ export declare function serializeTraceParent(ctx: TraceContext): string;
1460
+ /** Offset of the verdict byte (0 = accepted, nonzero = terminal error). */
1461
+ export declare const OUT_VERDICT: number;
1462
+ /** Offset of the error-code byte (see ERR_CODE_* below). */
1463
+ export declare const OUT_ERROR_CODE: number;
1464
+ /** Offset of the raw u16 status. */
1465
+ export declare const OUT_STATUS: number;
1466
+ /** Offset of the u32 flags word (see FLAG_* below). */
1467
+ export declare const OUT_FLAGS: number;
1468
+ /** Offset of the u32 rate-limit budget (U32_MAX = disabled). */
1469
+ export declare const OUT_RATE_LIMIT: number;
1470
+ /** Offset of the u32 rate-limit remaining count. */
1471
+ export declare const OUT_RATE_REMAINING: number;
1472
+ /** Offset of the u64 rate-limit window reset (ms epoch). */
1473
+ export declare const OUT_RATE_RESET: number;
1474
+ /** Offset of the u64 Retry-After value (ms). */
1475
+ export declare const OUT_RETRY_AFTER: number;
1476
+ /** Offset of the u32 cookies-JSON section length. */
1477
+ export declare const OUT_COOKIES_JSON_LEN: number;
1478
+ /** Offset of the u32 query-JSON section length. */
1479
+ export declare const OUT_QUERY_JSON_LEN: number;
1480
+ /** Offset of the header-template variant byte (see HV_* below). */
1481
+ export declare const OUT_HEADER_VARIANT: number;
1482
+ /** Offset of the u32 body-JSON section length. */
1483
+ export declare const OUT_BODY_JSON_LEN: number;
1484
+ /** Byte offset where the variable-length JSON sections begin. */
1485
+ export declare const OUT_DATA_START: number;
1486
+ /** Request carried a cookie header (cookie-JSON section present). */
1487
+ export declare const FLAG_HAS_COOKIES: number;
1488
+ /** Request carried a query string (query-JSON section present). */
1489
+ export declare const FLAG_HAS_QUERY: number;
1490
+ /** The request body parsed as valid JSON. */
1491
+ export declare const FLAG_BODY_VALID_JSON: number;
1492
+ /** The request body validated against the ingress schema. */
1493
+ export declare const FLAG_SCHEMA_VALID: number;
1494
+ /** The CORS engine allowed the request origin. */
1495
+ export declare const FLAG_CORS_ALLOWED: number;
1496
+ /** The request was a CORS preflight (OPTIONS + request-method). */
1497
+ export declare const FLAG_IS_PREFLIGHT: number;
1498
+ /** The request was rate-limited. */
1499
+ export declare const FLAG_RATE_LIMITED: number;
1500
+ /** The request arrived over HTTPS (trusted-proxy scheme). */
1501
+ export declare const FLAG_HTTPS: number;
1502
+ /** The request came from a trusted proxy (per the proxy config). */
1503
+ export declare const FLAG_TRUSTED_PROXY: number;
1504
+ /** A declared output section overran the buffer (truncated). */
1505
+ export declare const FLAG_BODY_TRUNCATED: number;
1506
+ /** Response body is JSON (`content-type: application/json`). */
1507
+ export declare const HV_JSON: number;
1508
+ /** CORS simple-request variant (Origin echoed + vary headers). */
1509
+ export declare const HV_CORS_SIMPLE: number;
1510
+ /** CORS preflight variant (allow-methods/headers/max-age). */
1511
+ export declare const HV_CORS_PREFLIGHT: number;
1512
+ /** Rate-limit active variant (`ratelimit-limit` header). */
1513
+ export declare const HV_RATE_ACTIVE: number;
1514
+ /** Rate-limited variant (Retry-After emitted). */
1515
+ export declare const HV_RATE_LIMITED: number;
1516
+ /** Total number of header-variant combinations (32). */
1517
+ export declare const HV_COUNT: number;
1518
+ /** No error (accepted). */
1519
+ export declare const ERR_CODE_NONE: number;
1520
+ /** CORS preflight rejected. */
1521
+ export declare const ERR_CODE_CORS_PREFLIGHT: number;
1522
+ /** Rate limit exceeded. */
1523
+ export declare const ERR_CODE_RATE_LIMITED: number;
1524
+ /** Request body exceeded the size guard. */
1525
+ export declare const ERR_CODE_BODY_TOO_LARGE: number;
1526
+ /** Request body is not valid JSON. */
1527
+ export declare const ERR_CODE_INVALID_JSON: number;
1528
+ /** Request body failed schema validation. */
1529
+ export declare const ERR_CODE_SCHEMA_VALIDATION: number;
1530
+ /** Malformed request (bad request line / headers). */
1531
+ export declare const ERR_CODE_BAD_REQUEST: number;
1532
+ /** Request headers/URL exceeded the configured limits. */
1533
+ export declare const ERR_CODE_REQUEST_TOO_LARGE: number;
1534
+ /** Internal pipeline failure (maps to 500). */
1535
+ export declare const ERR_CODE_INTERNAL: number;
1536
+ /**
1537
+ * JS-only error-code sentinel for a request-body read timeout in the async
1538
+ * `createIngress` path.
1539
+ *
1540
+ * The native pipeline never emits this value — it is a JS body-reader error
1541
+ * (`REQUEST_TIMEOUT` from `readBodyWithLimit`) mapped onto the numeric
1542
+ * error-code contract so the shared status/name/message helpers stay
1543
+ * consistent. Deliberately not sourced from Rust (see the header comment:
1544
+ * numeric layout values come from the addon; this one is a JS-level error).
1545
+ */
1546
+ export declare const ERR_CODE_REQUEST_TIMEOUT: number;
1547
+ /** Map a native error code to its stable string name. */
1548
+ export declare function errorCodeName(code: number): string;
1549
+ /** Map a native error code (plus status context) to a human message. */
1550
+ export declare function errorMessage(status: number, code: number): string;
1551
+ /** A single precomputed header-variant template. */
1552
+ export interface HeaderTemplate {
1553
+ readonly entries: ReadonlyArray<readonly [
1554
+ string,
1555
+ string
1556
+ ]>;
1557
+ readonly needsOriginEcho: boolean;
1558
+ readonly needsRateDynamic: boolean;
1559
+ readonly needsRetryAfter: boolean;
1560
+ readonly needsDynamicHsts: boolean;
1561
+ }
1562
+ /** Precomputed per-handler response context. */
1563
+ export interface ResponseBuildContext {
1564
+ readonly templates: HeaderTemplate[];
1565
+ readonly corsStatic: CorsStaticStrings | null;
1566
+ readonly hstsValue: string | null;
1567
+ }
1568
+ /**
1569
+ * Build the full response context (header templates + static CORS strings +
1570
+ * HSTS value) for a handler configuration.
1571
+ */
1572
+ export declare function buildResponseContext(options: {
1573
+ cors?: CorsOptions;
1574
+ security?: SecurityHeadersOptions;
1575
+ https?: boolean;
1576
+ enableSecurityHeaders?: boolean;
1577
+ rateLimit?: {
1578
+ limit?: number;
1579
+ };
1580
+ }): ResponseBuildContext;
1581
+ /**
1582
+ * Build the response headers for a decoded result, applying the dynamic parts
1583
+ * (request-id, origin echo, rate-limit counters, retry-after, dynamic HSTS).
1584
+ */
1585
+ export declare function headersForResult(ctx: ResponseBuildContext, r: {
1586
+ readonly headerVariant: number;
1587
+ readonly corsAllowed: boolean;
1588
+ readonly rateRemaining: number;
1589
+ readonly rateResetMs: number;
1590
+ readonly retryAfterMs: number;
1591
+ readonly https: boolean;
1592
+ }, req: Request, requestId: string): Headers;
1593
+ /**
1594
+ * Build a terminal response for a result, or `null` when the result is not
1595
+ * terminal (the caller should serve the body instead).
1596
+ */
1597
+ export declare function buildTerminalResponse(ctx: ResponseBuildContext, r: {
1598
+ readonly terminal: boolean;
1599
+ readonly isPreflight: boolean;
1600
+ readonly corsAllowed: boolean;
1601
+ readonly errorCode: number;
1602
+ readonly status: number;
1603
+ readonly headerVariant: number;
1604
+ readonly https: boolean;
1605
+ readonly rateLimit: number;
1606
+ readonly rateRemaining: number;
1607
+ readonly rateResetMs: number;
1608
+ readonly retryAfterMs: number;
1609
+ }, req: Request, requestId: string): Response | null;
1610
+ /** Default maximum request body size in bytes. */
1611
+ export declare const DEFAULT_MAX_BODY_BYTES = 1048576;
1612
+ /**
1613
+ * Default overall deadline (ms) for reading a request body. Non-zero so the
1614
+ * async `createIngress` / route handlers are protected against slowloris and
1615
+ * trickling bodies by default. Set `bodyTimeoutMs: 0` to disable.
1616
+ */
1617
+ export declare const DEFAULT_BODY_TIMEOUT_MS = 30000;
1618
+ /** Maps HTTP methods to the native Ingress method-kind enum. */
1619
+ export declare const METHOD_KIND: Record<string, number>;
1620
+ /** Which request headers to extract into the packed input. */
1621
+ export interface HeaderPlan {
1622
+ cookie: boolean;
1623
+ cors: boolean;
1624
+ proxy: boolean;
1625
+ proto: boolean;
1626
+ }
1627
+ /**
1628
+ * Whether a raw status is a legal HTTP response status for the ingress
1629
+ * pipeline (101 switch-protocol or any 2xx–5xx).
1630
+ */
1631
+ export declare function isValidResponseStatus(status: number): boolean;
1632
+ /**
1633
+ * Map a native ingress error code to the HTTP status that should be returned.
1634
+ * A permitted CORS preflight always yields 204.
1635
+ */
1636
+ export declare function statusForErrorCode(errorCode: number, isPreflightAllowed: boolean): number;
1637
+ /**
1638
+ * Normalize a raw status to a legal response status, falling back to the
1639
+ * error-code mapping when the raw status is not legal.
1640
+ */
1641
+ export declare function normalizeResponseStatus(status: number, errorCode: number, isPreflightAllowed: boolean): number;
1642
+ /**
1643
+ * Compute a safe terminal status for a result: a permitted CORS preflight
1644
+ * yields 204, otherwise the normalized status (or the error-code mapping).
1645
+ */
1646
+ export declare function safeTerminalStatus(r: {
1647
+ readonly status: number;
1648
+ readonly errorCode: number;
1649
+ readonly isPreflight: boolean;
1650
+ readonly corsAllowed: boolean;
1651
+ }): number;
1652
+ /**
1653
+ * Create a fast packed-input ingress handler (path 1).
1654
+ *
1655
+ * JS packs the request headers into a binary buffer (`IngressInputPacker`) and
1656
+ * the native `Ingress.handleRequestPacked` decodes them. Responses use the
1657
+ * `{"error":{...}}` wire format with `x-ratelimit-*` headers.
1658
+ *
1659
+ * Prefer this when you want the lowest-overhead pipeline and will call `run()`
1660
+ * yourself with a **synchronous** callback. For ready-made route handlers and a
1661
+ * server builder, use `createIngressHandler` (path 2).
1662
+ */
1663
+ export declare function createIngressFast(options?: IngressFastOptions): IngressFastHandler;
1664
+ declare function createStructuredLogger(stream?: Pick<NodeJS.WritableStream, "write">, env?: NodeJS.ProcessEnv): {
1665
+ /** Record one completed request. */
1666
+ request(info: {
1667
+ requestId: string;
1668
+ method: string;
1669
+ path: string;
1670
+ status: number;
1671
+ durationMs: number;
1672
+ ip?: string;
1673
+ }): void;
1674
+ error(info: {
1675
+ requestId?: string;
1676
+ method?: string;
1677
+ path?: string;
1678
+ code?: string;
1679
+ message: string;
1680
+ }): void;
1681
+ };
1682
+ /** Pre-encoded static error bodies, keyed by error-code string name. */
1683
+ export declare const ERROR_BODIES: Record<string, Uint8Array>;
1684
+ /**
1685
+ * Pre-baked GET read handler: returns the ingress body JSON on success.
1686
+ */
1687
+ export declare function readHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1688
+ /**
1689
+ * Pre-baked DELETE handler: DELETE is a read-style method (no request body is
1690
+ * read), so it shares the exact pipeline flow of {@link readHandler} — it
1691
+ * returns the ingress body JSON on success and the terminal/error responses
1692
+ * otherwise. Reusing the read factory keeps the two handlers byte-identical
1693
+ * and avoids a copy-pasted variant.
1694
+ *
1695
+ * Wire it via the `delete` key of a `BakedRoute` (see `createIngressServer`).
1696
+ */
1697
+ export declare const deleteHandler: typeof readHandler;
1698
+ /**
1699
+ * Pre-baked echo handler: streams the request body back with the client's
1700
+ * Content-Type, bounded by `maxBodyBytes`.
1701
+ */
1702
+ export declare function echoHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
1703
+ /**
1704
+ * Pre-baked fallback handler: 404 for unmatched routes / OPTIONS.
1705
+ */
1706
+ export declare function fallbackHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1707
+ /**
1708
+ * Pre-baked HEAD read handler: headers only, no body.
1709
+ */
1710
+ export declare function headHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1711
+ /**
1712
+ * Pre-baked JSON-write handler (POST/PUT/PATCH): enforces Content-Type,
1713
+ * content-length/body-size limits, JSON validity and (optionally) schema
1714
+ * validation, then returns the ingress body JSON on success.
1715
+ */
1716
+ export declare function jsonWriteHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Promise<Response>;
1717
+ /**
1718
+ * Pre-baked OPTIONS handler: serves the native pipeline's CORS preflight
1719
+ * decision — 204 when the preflight is allowed, 403 (terminal) when denied —
1720
+ * and a plain 204 for non-preflight OPTIONS.
1721
+ *
1722
+ * `createIngressServer` wires this for EVERY route that has a handler, so
1723
+ * read-only routes also answer preflights (previously OPTIONS only reached the
1724
+ * pipeline on write routes that also configured a fallback).
1725
+ */
1726
+ export declare function optionsHandler(ingress: OptimizedIngressHandler, opts?: BakedHandlerOptions): (req: Request, srv?: unknown) => Response;
1727
+ /** Options for {@link nativeResponderRoute}. */
1728
+ export interface ResponderRouteOptions extends BakedHandlerOptions {
1729
+ /** Terminal envelope style. Default: `'castrum'` (the pre-baked wire). */
1730
+ terminalStyle?: TerminalStyle;
1731
+ /**
1732
+ * Read the request body and pass it to the native pipeline for validation
1733
+ * (`requireJsonBody`/schema). Default `false` — the framework owns the body
1734
+ * (the responder reads it via `ctx.body`); native only needs the bytes when
1735
+ * a body stage is enabled in the route's `IngressHandlerOptions`.
1736
+ */
1737
+ readBody?: boolean;
1738
+ }
1739
+ /**
1740
+ * Build a responder route: native pipeline decides + rejects (terminal
1741
+ * response in the chosen style); on success the JS `responder` builds the 2xx.
1742
+ * Returns an async `RouteHandler` (`(req, srv?, params?) => Promise<Response>`).
1743
+ */
1744
+ export declare function nativeResponderRoute(ingress: OptimizedIngressHandler, responder: NativeResponder, opts?: ResponderRouteOptions): RouteHandler;
1745
+ /** A Node.js ingress server: {@link BakedServer} plus an async ready signal. */
1746
+ export interface NodeIngressServer extends BakedServer {
1747
+ /**
1748
+ * Resolves to the actually-bound port once the server is listening
1749
+ * (`node:http` binds asynchronously; useful when `port: 0`).
1750
+ */
1751
+ ready: Promise<number>;
1752
+ }
1753
+ /**
1754
+ * Start a Node.js `node:http` server serving the same pre-baked ingress route
1755
+ * handlers as {@link createIngressServer}. Returns a {@link NodeIngressServer};
1756
+ * `stop()` drains in-flight connections (graceful) before closing, and
1757
+ * `ready` resolves to the bound port once listening.
1758
+ *
1759
+ * Requires Node.js >= 20.3 (N-API floor). Bun users should prefer
1760
+ * {@link createIngressServer} (Bun.serve).
1761
+ */
1762
+ export declare function createIngressServerNode(options: CreateIngressServerOptions): NodeIngressServer;
1763
+ /** Sentinel value used by Rust to mean "rate limiting disabled". */
1764
+ export declare const RATE_LIMIT_U32_MAX = 4294967295;
1765
+ /** Runtime configuration for the pre-baked handler path (`createIngressHandler`). */
1766
+ export interface BakedIngressRuntime {
1767
+ /** Emit an `x-request-id` header on responses. Default: false. */
1768
+ emitRequestIdHeader?: boolean;
1769
+ /** Enable security headers on responses. Default: true. */
1770
+ enableSecurityHeaders?: boolean;
1771
+ /**
1772
+ * Ordered `[name, value]` security headers (names are lowercased).
1773
+ * NOTE: this PRE-BAKED path takes RAW `[name, value]` pairs here; the
1774
+ * fast/async paths (`createIngressFast`/`createIngress`) instead take a
1775
+ * structured `security: SecurityHeadersOptions` object (CSP/HSTS builders).
1776
+ * The two paths intentionally use different option shapes (see
1777
+ * docs/INGRESS.md).
1778
+ */
1779
+ securityHeaders?: ReadonlyArray<[
1780
+ string,
1781
+ string
1782
+ ]>;
1783
+ /** Native output buffer size in bytes. Default: 131072. */
1784
+ outputBufferSize?: number;
1785
+ /** Invoked before a request is processed (for tracing/context hooks). */
1786
+ onRequest?: (req: Request, requestId: string, ip: string | undefined) => void;
1787
+ /** Invoked after a Response is produced (for metrics/logging hooks). */
1788
+ onResponse?: (req: Request, result: BakedIngressResult, status: number, requestId: string) => void;
1789
+ /**
1790
+ * Invoked when the native pipeline fails (the request becomes a 500).
1791
+ * Native failures are otherwise silent — wire this to your error tracker.
1792
+ */
1793
+ onError?: (req: Request, requestId: string, error: Error) => void;
1794
+ /**
1795
+ * Emit one structured JSON line per request/error via the built-in logger
1796
+ * (gated by `CASTRUM_LOG_LEVEL`). Default: false.
1797
+ */
1798
+ structuredLog?: boolean;
1799
+ /**
1800
+ * Custom structured logger (e.g. with a custom stream or extra fields).
1801
+ * When provided, request/error lines go here instead of the built-in stderr
1802
+ * logger and `structuredLog` is implicitly enabled.
1803
+ */
1804
+ logger?: ReturnType<typeof createStructuredLogger>;
1805
+ /**
1806
+ * Hard cap on concurrently borrowed output buffers (zero-copy responses not
1807
+ * yet consumed). Bounds memory when zero-copy responses are consumed
1808
+ * slowly; when exceeded, requests fail with a 500 (pool exhaustion) instead
1809
+ * of allocating unbounded temporaries. 0 (default) is unlimited — see
1810
+ * `BufferPool.maxInFlight`.
1811
+ */
1812
+ maxInFlight?: number;
1813
+ /**
1814
+ * Abandonment guard (ms) for zero-copy responses: if a response body is
1815
+ * neither pulled nor cancelled within this window, its pooled buffer is
1816
+ * released and the stream closed. Bounds memory under abandoned (unread)
1817
+ * zero-copy responses. 0 (default) disables it — see `pooledBodyResponse`.
1818
+ */
1819
+ zeroCopyTimeoutMs?: number;
1820
+ }
1821
+ /**
1822
+ * Create a pre-baked ingress handler (path 2).
1823
+ *
1824
+ * The request frame (url/ip/rid/headers) is packed in JS via `IngressInputPacker`
1825
+ * + `gatherRawHeadersPacked` and driven through the same native core as the
1826
+ * fast path (`Ingress.handleRequestPacked`), writing into a pooled output
1827
+ * buffer (no per-request allocation). Responses use the benchmark wire format
1828
+ * (`{"ok":false,"error":{...}}` + `ratelimit-*` headers) — see AGENTS.md for
1829
+ * why this differs from `createIngressFast`.
1830
+ *
1831
+ * Returns an `OptimizedIngressHandler` whose response-builder methods are
1832
+ * bound to this handler's configuration. Pair it with the route factories
1833
+ * (`readHandler`, `jsonWriteHandler`, ...) or `createIngressServer`.
1834
+ */
1835
+ export declare function createIngressHandler(options?: IngressHandlerOptions, runtime?: BakedIngressRuntime): OptimizedIngressHandler;
1836
+ /**
1837
+ * Liveness probe: `200 {"status":"ok"}` as long as the process is alive.
1838
+ * Never touches dependencies.
1839
+ */
1840
+ export declare function livenessHandler(): (_req: Request) => Response;
1841
+ /**
1842
+ * Readiness probe: runs the optional async `check` (dependency readiness).
1843
+ * Returns `200 {"status":"ready"}` when the check passes (or no check is
1844
+ * given), `503 {"status":"not_ready"}` when it throws or returns false.
1845
+ */
1846
+ export declare function readinessHandler(check?: () => boolean | Promise<boolean>): (_req: Request) => Promise<Response>;
1847
+ /**
1848
+ * Combined health probe: liveness by default, plus an optional readiness
1849
+ * `check`. When a `check` is provided the response is 503 on failure
1850
+ * (readiness semantics), otherwise always 200.
1851
+ */
1852
+ export declare function healthHandler(check?: () => boolean | Promise<boolean>): ((_req: Request) => Response) | ((_req: Request) => Promise<Response>);
1853
+ /** The runtime hooks + registry for ingress metrics. */
1854
+ export interface IngressMetrics {
1855
+ registry: MetricsRegistry;
1856
+ /** Pass as the runtime to `createIngressHandler`. */
1857
+ runtime: Pick<BakedIngressRuntime, "onRequest" | "onResponse" | "onError">;
1858
+ /** Render the Prometheus exposition. */
1859
+ render(): string;
1860
+ }
1861
+ /**
1862
+ * Build ingress request/error/latency metrics wired to the pre-baked handler
1863
+ * runtime hooks. Metric names follow the Prometheus `castrum_http_*` scheme.
1864
+ */
1865
+ export declare function createIngressMetrics(): IngressMetrics;
1866
+ /**
1867
+ * Route handler exposing the registry in Prometheus text format
1868
+ * (`content-type: text/plain; version=0.0.4`). Serve it as a `read` route:
1869
+ *
1870
+ * createIngressServer({ routes: { "/metrics": { read: metricsHandler(m) } } })
1871
+ */
1872
+ export declare function metricsHandler(metrics: IngressMetrics): (_req: Request) => Response;
1873
+ /** Per-route spec for {@link createIngressRouter}. */
1874
+ export interface RouterRouteSpec {
1875
+ /**
1876
+ * Per-route ingress options — compiled into a DEDICATED native `IngressInner`
1877
+ * for this route (parseCookies, parseQuery, schema, cors, rateLimit, limits,
1878
+ * requireJsonBody, ...). This is what makes the pipeline prune per route.
1879
+ */
1880
+ options?: IngressHandlerOptions;
1881
+ /** Wire GET + HEAD read handlers over this route's compiled handler. */
1882
+ read?: boolean;
1883
+ /** Wire POST/PUT/PATCH JSON-write handlers over this route's compiled handler. */
1884
+ write?: boolean;
1885
+ /** Wire a POST echo handler over this route's compiled handler. */
1886
+ echo?: boolean;
1887
+ /** Wire a GET read handler (cookies-style) over this route's compiled handler. */
1888
+ cookies?: boolean;
1889
+ /** Wire a DELETE read-style handler over this route's compiled handler. */
1890
+ delete?: boolean;
1891
+ /**
1892
+ * A JS responder route: the native pipeline decides + rejects (terminal
1893
+ * response in {@link terminalStyle}); on success the responder builds the
1894
+ * 2xx body (async OK) from a decoded snapshot. Wired for `methods`
1895
+ * (default `['GET']`). When set, the standard `read`/`write`/etc. flags for
1896
+ * this route are ignored.
1897
+ */
1898
+ responder?: {
1899
+ handler: NativeResponder;
1900
+ /** HTTP methods to wire (default `['GET']`). */
1901
+ methods?: ReadonlyArray<string>;
1902
+ /** Read the body for native validation (default false — framework owns it). */
1903
+ readBody?: boolean;
1904
+ };
1905
+ /** Terminal envelope style for this route's responder (default: router-level
1906
+ * `terminalStyle` or `'castrum'`). */
1907
+ terminalStyle?: TerminalStyle;
1908
+ /**
1909
+ * A raw request→Response handler served directly for GET, OUTSIDE the
1910
+ * ingress pipeline (health/metrics probes, /metrics). When set, `read`/
1911
+ * `write`/etc. for this route are ignored.
1912
+ */
1913
+ raw?: RouteHandler;
1914
+ /** Overrides `maxBodyBytes` for this route's write/echo handlers. */
1915
+ maxBodyBytes?: number;
1916
+ /** Overrides `bodyTimeoutMs` for this route's write/echo handlers. */
1917
+ bodyTimeoutMs?: number;
1918
+ }
1919
+ /** Options for {@link createIngressRouter}. */
1920
+ export interface CreateIngressRouterOptions {
1921
+ /** Route table: path → per-route spec. */
1922
+ routes: Record<string, RouterRouteSpec>;
1923
+ /** Shared runtime hooks (onRequest/onResponse/onError, security headers,
1924
+ * output buffer size) applied to EVERY compiled route handler. */
1925
+ runtime?: BakedIngressRuntime;
1926
+ /** Shared `getIp` resolver for route handlers. */
1927
+ getIp?: (req: Request, srv: unknown) => string | undefined;
1928
+ /** Shared `copyBody` default for route handlers. */
1929
+ copyBody?: boolean;
1930
+ /** Default terminal envelope style for responder routes (`'castrum'`). */
1931
+ terminalStyle?: TerminalStyle;
1932
+ /** Pre-warm every compiled route at construction (JIT the packed pipeline +
1933
+ * the FFI ingress call before the first real request). Default: false. */
1934
+ warmOnCreate?: boolean;
1935
+ }
1936
+ /** A compiled per-route router. */
1937
+ export interface IngressRouter {
1938
+ /** The per-route compiled handlers keyed by path (for custom route wiring). */
1939
+ routeHandlers: Record<string, OptimizedIngressHandler>;
1940
+ /** The route → method → handler map (compatible with Bun.serve `routes` and
1941
+ * `createIngressServerNode`). */
1942
+ routes: Record<string, Record<string, unknown>>;
1943
+ /** The path matcher (`:param`/`*` dynamic routes). */
1944
+ match: (pathname: string) => PathMatch | undefined;
1945
+ /** A fetch-style dispatcher: match path + method → the route's handler. */
1946
+ fetch: (req: Request, srv?: unknown) => Response | Promise<Response>;
1947
+ /** Pre-warm every compiled route (JIT the packed pipeline + FFI call). */
1948
+ prewarm: () => void;
1949
+ }
1950
+ /**
1951
+ * Compile a route table into per-route native ingress instances.
1952
+ *
1953
+ * Each route with a pipeline-backed spec (`read`/`write`/`echo`/`cookies`/
1954
+ * `delete`) compiles its OWN `createIngressHandler(options)` — a dedicated
1955
+ * `IngressInner` pruned to that route's stages + a per-route header plan.
1956
+ * Routes that need nothing (a bare `read` with no cookies/query/cors) therefore
1957
+ * gather zero headers and run a near-empty native pipeline. All routes share
1958
+ * the same wire format and the shared process-wide rate-limiter budgets.
1959
+ *
1960
+ * @example
1961
+ * ```ts
1962
+ * const router = createIngressRouter({
1963
+ * warmOnCreate: true,
1964
+ * runtime: ingressMetrics?.runtime,
1965
+ * routes: {
1966
+ * '/health': { read: true, options: { parseCookies: false, parseQuery: false } },
1967
+ * '/api/users': {
1968
+ * read: true,
1969
+ * write: true,
1970
+ * options: { parseCookies: true, parseQuery: true, schema: USER_SCHEMA_BYTES },
1971
+ * },
1972
+ * '/metrics': { raw: metricsHandler(ingressMetrics) },
1973
+ * },
1974
+ * })
1975
+ * const server = Bun.serve({ routes: router.routes }) // or router.fetch
1976
+ * ```
1977
+ */
1978
+ export declare function createIngressRouter(options: CreateIngressRouterOptions): IngressRouter;
1979
+ /**
1980
+ * Synchronous convenience wrapper over `createIngressFast` (path 1).
1981
+ *
1982
+ * The callback runs on the fast-path result and MUST be synchronous. Use
1983
+ * {@link createIngress} when you want automatic body reading + error contexts.
1984
+ */
1985
+ export declare function createIngressSync(options?: IngressOptions): SyncIngressHandler;
1986
+ /**
1987
+ * Async ingress factory: reads the request body (size guard + deadline) and
1988
+ * returns a snapshot `IngressContext` with a terminal `Response`.
1989
+ *
1990
+ * Recommended default for serverless/edge-style `fetch` handlers. For maximum
1991
+ * throughput use `createIngressFast` / `createIngressSync` directly.
1992
+ */
1993
+ export declare function createIngress(options?: IngressOptions): IngressHandler;
1994
+ /** Readonly snapshot of the ingress decision, safe after `run()` returns. */
1995
+ export interface PipelineResult {
1996
+ readonly ok: boolean;
1997
+ readonly status: number;
1998
+ readonly errorCode: number;
1999
+ readonly terminal: boolean;
2000
+ readonly rateLimited: boolean;
2001
+ readonly bodyValidJson: boolean;
2002
+ readonly schemaValid: boolean;
2003
+ readonly bodyTruncated: boolean;
2004
+ readonly requestId: string;
2005
+ /** The raw request body the pipeline saw (read-only; aliases the request body). */
2006
+ readonly body: Uint8Array;
2007
+ /** The ingress metadata JSON body (when `emitMetadataJson` is on), else empty. */
2008
+ readonly metadataJson: Uint8Array;
2009
+ }
2010
+ /** Per-request context threaded into the app's handler. */
2011
+ export interface PipelineContext {
2012
+ readonly requestId: string;
2013
+ readonly ip: string | undefined;
2014
+ /** Mutable per-request storage for middleware/user state. */
2015
+ readonly locals: Map<string, unknown>;
2016
+ }
2017
+ /** Result of running `preprocess`: terminal short-circuit or pass-through. */
2018
+ export interface PreprocessOutcome {
2019
+ /** True when the pipeline short-circuited (error/denied) — serve `response`. */
2020
+ readonly terminal: boolean;
2021
+ readonly response: Response | null;
2022
+ readonly result: PipelineResult | null;
2023
+ readonly ctx: PipelineContext;
2024
+ }
2025
+ /** Options for `createPipeline`. */
2026
+ export interface CreatePipelineOptions {
2027
+ /** Ingress options (same surface as `createIngressHandler`). */
2028
+ options?: IngressHandlerOptions;
2029
+ /** Runtime hooks: onRequest/onResponse/onError, logging, pool sizing. */
2030
+ runtime?: BakedIngressRuntime;
2031
+ /** Body limit for `readBody`/`preprocess`. Default: 1 MiB. */
2032
+ maxBodyBytes?: number;
2033
+ /** Body-read deadline (ms) for `readBody`/`preprocess`. Default: 30s. */
2034
+ bodyTimeoutMs?: number;
2035
+ /**
2036
+ * When true (default), `preprocess` reads a request body (guarded) so the
2037
+ * result carries it. Set false when the app handler owns the body.
2038
+ */
2039
+ readBody?: boolean;
2040
+ /**
2041
+ * Optional renderer for the OK (non-terminal) case of `handleRequest`.
2042
+ * Defaults to a minimal `{"ok":true,"requestId":...}` JSON body.
2043
+ */
2044
+ render?: (result: PipelineResult, ctx: PipelineContext) => Response | Promise<Response>;
2045
+ }
2046
+ /** The composed ingress pipeline: preprocess / handleRequest / readBody. */
2047
+ export interface IngressPipeline {
2048
+ /** The underlying pre-baked handler (custom route factories / responses). */
2049
+ readonly ingress: OptimizedIngressHandler;
2050
+ /** Run the pipeline for a middleware/framework. */
2051
+ preprocess(req: Request, ip?: string): Promise<PreprocessOutcome>;
2052
+ /** Fetch-compatible handler: terminal response or the renderer's response. */
2053
+ handleRequest(req: Request, ip?: string): Promise<Response>;
2054
+ /** Stream-read a request body with the configured limits. */
2055
+ readBody(req: Request, maxBytes?: number, timeoutMs?: number): Promise<Uint8Array>;
2056
+ }
2057
+ /**
2058
+ * Create a framework-agnostic ingress pipeline.
2059
+ *
2060
+ * @example
2061
+ * ```ts
2062
+ * // Plain Bun.serve fetch handler
2063
+ * const pipeline = createPipeline({ options: { parseCookies: true } });
2064
+ * Bun.serve({ port: 3000, fetch: (req) => pipeline.handleRequest(req) });
2065
+ *
2066
+ * // Hono-style middleware: short-circuit on terminal, else handle the app route
2067
+ * app.use("*", async (c, next) => {
2068
+ * const { terminal, response, ctx } = await pipeline.preprocess(c.req.raw);
2069
+ * if (terminal && response) return response;
2070
+ * c.set("ingress", ctx); // pass requestId / locals into the app handler
2071
+ * await next();
2072
+ * });
2073
+ * ```
2074
+ */
2075
+ export declare function createPipeline(opts?: CreatePipelineOptions): IngressPipeline;
2076
+ /** One SSE event to frame via `sseResponse` (event/id/retry/data). */ export interface SseEvent {
2077
+ /** Optional `event:` field. */
2078
+ event?: string | null;
2079
+ /** Optional `id:` field. */
2080
+ id?: string | null;
2081
+ /** Optional `retry:` field (ms). */
2082
+ retry?: number | null;
2083
+ /** Event data. */
2084
+ data: string | Uint8Array;
2085
+ }
2086
+ /**
2087
+ * Build a `text/event-stream` Response from an (async) iterable of events.
2088
+ *
2089
+ * Each event is framed with the native `rust.sseEncodeEvent` (zero-DOM, byte
2090
+ * parity with the FFI primitive), so SSE stays on the fast path:
2091
+ *
2092
+ * @example
2093
+ * ```ts
2094
+ * async function* tick() {
2095
+ * for (let i = 0; i < 5; i++) {
2096
+ * await Bun.sleep(250);
2097
+ * yield { event: "tick", data: String(i) };
2098
+ * }
2099
+ * }
2100
+ * return sseResponse(tick(), { headers: { "x-request-id": rid } });
2101
+ * ```
2102
+ */
2103
+ export declare function sseResponse(events: AsyncIterable<SseEvent> | Iterable<SseEvent>, init?: ResponseInit): Response;
2104
+ /** Result kinds supported by the loader (mirrors the packed batch wire shapes). */
2105
+ export type LoaderResultKind = "boolean" | "number" | "bigint" | "bytes";
2106
+ /** Single-item (scalar) result type for a kind. */
2107
+ export type ScalarResult<K extends LoaderResultKind> = K extends "boolean" ? boolean : K extends "number" ? number : K extends "bigint" ? bigint : Uint8Array;
2108
+ /** Bulk (array-input) result type for a kind — same shape as `rust.batch.*`. */
2109
+ export type BulkResult<K extends LoaderResultKind> = K extends "boolean" ? Uint8Array : K extends "number" ? Uint32Array : K extends "bigint" ? BigInt64Array : Uint8Array[];
2110
+ /**
2111
+ * Bulk-result type overrides per op. Bigint ops whose hashes can set the high
2112
+ * bit (e.g. `fnv1a64`) return an UNSIGNED `BigUint64Array` to match the scalar
2113
+ * `rust.<op>`; the default signed `BigInt64Array` stays for sum-style ops.
2114
+ */
2115
+ export interface LoaderOpBulkOverride {
2116
+ fnv1a64: BigUint64Array;
2117
+ }
2118
+ /** Bulk result type of a specific op (per-op override wins). */
2119
+ export type LoaderBulk<K extends LoaderOpName> = K extends keyof LoaderOpBulkOverride ? LoaderOpBulkOverride[K] : BulkResult<LoaderOpKind<K>>;
2120
+ /** Every op the loader can dispatch. */
2121
+ export type LoaderOpName = "crc32" | "fnv1a64" | "jsonValid" | "jsonSumIds" | "validateEmail" | "validateUuid" | "validateIpv4" | "validateIpv6" | "queryParse" | "cookieParse" | "formParse" | "httpParseRequest" | "hexEncode" | "hexDecode" | "base64Encode" | "base64Decode" | "base64UrlEncode" | "base64UrlDecode" | "gzipCompress" | "gzipDecompress" | "brotliCompress" | "brotliDecompress" | "etag" | "urlEncode" | "urlDecode" | "urlDecodeBytes" | "wsAcceptKey" | "mimeFromExtension" | "signCookie" | "verifyCookie" | "csrfVerify" | "passwordHash" | "passwordVerify" | "hmacSha256" | "hmacSha256Verify" | "aeadEncrypt" | "aeadDecrypt" | "jwtSign" | "jwtVerify" | "jsonPatch" | "urlResolve" | "wsFrameEncode" | "sseEncode" | "schemaValidate";
2122
+ /** Extra arguments (after the item/items) for each op — the SINGLE call shape. */
2123
+ export interface LoaderOpArgs {
2124
+ crc32: [
2125
+ ];
2126
+ fnv1a64: [
2127
+ ];
2128
+ jsonValid: [
2129
+ ];
2130
+ jsonSumIds: [
2131
+ ];
2132
+ validateEmail: [
2133
+ ];
2134
+ validateUuid: [
2135
+ ];
2136
+ validateIpv4: [
2137
+ ];
2138
+ validateIpv6: [
2139
+ ];
2140
+ queryParse: [
2141
+ ];
2142
+ cookieParse: [
2143
+ ];
2144
+ formParse: [
2145
+ ];
2146
+ httpParseRequest: [
2147
+ ];
2148
+ hexEncode: [
2149
+ ];
2150
+ hexDecode: [
2151
+ ];
2152
+ base64Encode: [
2153
+ urlSafe?: boolean,
2154
+ padding?: boolean
2155
+ ];
2156
+ base64Decode: [
2157
+ urlSafe?: boolean,
2158
+ padding?: boolean
2159
+ ];
2160
+ base64UrlEncode: [
2161
+ ];
2162
+ base64UrlDecode: [
2163
+ ];
2164
+ gzipCompress: [
2165
+ level?: number | null
2166
+ ];
2167
+ gzipDecompress: [
2168
+ ];
2169
+ brotliCompress: [
2170
+ quality?: number | null
2171
+ ];
2172
+ brotliDecompress: [
2173
+ ];
2174
+ etag: [
2175
+ weak?: boolean | null
2176
+ ];
2177
+ urlEncode: [
2178
+ ];
2179
+ urlDecode: [
2180
+ ];
2181
+ urlDecodeBytes: [
2182
+ ];
2183
+ wsAcceptKey: [
2184
+ ];
2185
+ mimeFromExtension: [
2186
+ ];
2187
+ signCookie: [
2188
+ secret: Uint8Array
2189
+ ];
2190
+ /** Boolean-validity op: returns valid/invalid (use `rust.verifyCookie` for the value). */
2191
+ verifyCookie: [
2192
+ secret: Uint8Array
2193
+ ];
2194
+ csrfVerify: [
2195
+ secret: Uint8Array
2196
+ ];
2197
+ passwordHash: [
2198
+ salt: Uint8Array,
2199
+ options?: PasswordHashOptions | null
2200
+ ];
2201
+ passwordVerify: [
2202
+ phc: Uint8Array
2203
+ ];
2204
+ hmacSha256: [
2205
+ key: Uint8Array
2206
+ ];
2207
+ hmacSha256Verify: [
2208
+ key: Uint8Array,
2209
+ sig: Uint8Array
2210
+ ];
2211
+ aeadEncrypt: [
2212
+ key: Uint8Array,
2213
+ nonce: Uint8Array,
2214
+ algorithm?: string | null
2215
+ ];
2216
+ aeadDecrypt: [
2217
+ key: Uint8Array,
2218
+ nonce: Uint8Array,
2219
+ algorithm?: string | null
2220
+ ];
2221
+ jwtSign: [
2222
+ secret: Uint8Array,
2223
+ ttlSeconds?: number | null,
2224
+ nowSeconds?: number
2225
+ ];
2226
+ /** Boolean-validity op: returns valid/invalid (use `rust.jwtVerify` for the payload). */
2227
+ jwtVerify: [
2228
+ secret: Uint8Array,
2229
+ nowSeconds?: number
2230
+ ];
2231
+ jsonPatch: [
2232
+ patch: Uint8Array
2233
+ ];
2234
+ urlResolve: [
2235
+ base: Uint8Array
2236
+ ];
2237
+ wsFrameEncode: [
2238
+ opcode: number,
2239
+ mask: boolean,
2240
+ fin: boolean
2241
+ ];
2242
+ sseEncode: [
2243
+ event?: string | null,
2244
+ id?: string | null,
2245
+ retry?: number | null
2246
+ ];
2247
+ schemaValidate: [
2248
+ validator: SchemaValidator
2249
+ ];
2250
+ }
2251
+ /**
2252
+ * Extra arguments for the BULK call shape. Paired ops take a per-item
2253
+ * companion ARRAY here; every other op inherits the scalar `LoaderOpArgs`
2254
+ * shape (companions are shared across the batch).
2255
+ */
2256
+ export interface LoaderOpBulkArgs {
2257
+ jsonPatch: [
2258
+ patches: Uint8Array[]
2259
+ ];
2260
+ hmacSha256Verify: [
2261
+ key: Uint8Array,
2262
+ sigs: Uint8Array[]
2263
+ ];
2264
+ passwordVerify: [
2265
+ phcs: Uint8Array[]
2266
+ ];
2267
+ urlResolve: [
2268
+ bases: Uint8Array[]
2269
+ ];
2270
+ }
2271
+ /** Bulk call shape for any op (defaults to the scalar shape). */
2272
+ export type LoaderBulkArgs<K extends LoaderOpName> = K extends keyof LoaderOpBulkArgs ? LoaderOpBulkArgs[K] : LoaderOpArgs[K];
2273
+ declare function boolElem(bulk: unknown, index: number): boolean;
2274
+ declare function numElem(bulk: unknown, index: number): number;
2275
+ declare function bigElem(bulk: unknown, index: number): bigint;
2276
+ declare function byteElem(bulk: unknown, index: number): Uint8Array;
2277
+ declare function boolFast(_view: DataView, output: Uint8Array, index: number): boolean;
2278
+ declare function bitsetOutSize(count: number): number;
2279
+ declare function u32Fast(view: DataView, _output: Uint8Array, index: number): number;
2280
+ declare function u32OutSize(count: number): number;
2281
+ declare function i64Fast(view: DataView, _output: Uint8Array, index: number): bigint;
2282
+ declare function u64Fast(view: DataView, _output: Uint8Array, index: number): bigint;
2283
+ declare function i64OutSize(count: number): number;
2284
+ /**
2285
+ * Registry — single source of truth for loader-op wiring. Every op must have
2286
+ * a scalar variant and a packed batch variant; ops whose scalar returns
2287
+ * something other than the bulk element (e.g. `jwtVerify` returning the
2288
+ * decoded payload, `verifyCookie` returning the value) are deliberately
2289
+ * EXCLUDED so single and bulk semantics stay identical.
2290
+ */
2291
+ export declare const LOADER_OPS: {
2292
+ readonly crc32: {
2293
+ readonly kind: "number";
2294
+ readonly scalar: (i: Uint8Array) => number;
2295
+ readonly batch: (items: Uint8Array[]) => Uint32Array<ArrayBufferLike>;
2296
+ readonly element: typeof numElem;
2297
+ readonly fast: {
2298
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2299
+ readonly element: typeof u32Fast;
2300
+ readonly outSize: typeof u32OutSize;
2301
+ };
2302
+ };
2303
+ readonly fnv1a64: {
2304
+ readonly kind: "bigint";
2305
+ readonly unsigned: true;
2306
+ readonly scalar: (i: Uint8Array) => bigint;
2307
+ readonly batch: (items: Uint8Array[]) => BigUint64Array<ArrayBufferLike>;
2308
+ readonly element: typeof bigElem;
2309
+ readonly fast: {
2310
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2311
+ readonly element: typeof u64Fast;
2312
+ readonly outSize: typeof i64OutSize;
2313
+ };
2314
+ };
2315
+ readonly jsonValid: {
2316
+ readonly kind: "boolean";
2317
+ readonly scalar: (i: Uint8Array) => boolean;
2318
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2319
+ readonly element: typeof boolElem;
2320
+ readonly fast: {
2321
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2322
+ readonly element: typeof boolFast;
2323
+ readonly outSize: typeof bitsetOutSize;
2324
+ };
2325
+ };
2326
+ readonly jsonSumIds: {
2327
+ readonly kind: "bigint";
2328
+ readonly scalar: (i: Uint8Array) => bigint;
2329
+ readonly batch: (items: Uint8Array[]) => BigInt64Array<ArrayBufferLike>;
2330
+ readonly element: typeof bigElem;
2331
+ readonly fast: {
2332
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2333
+ readonly element: typeof i64Fast;
2334
+ readonly outSize: typeof i64OutSize;
2335
+ };
2336
+ };
2337
+ readonly validateEmail: {
2338
+ readonly kind: "boolean";
2339
+ readonly scalar: (i: Uint8Array) => boolean;
2340
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2341
+ readonly element: typeof boolElem;
2342
+ readonly fast: {
2343
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2344
+ readonly element: typeof boolFast;
2345
+ readonly outSize: typeof bitsetOutSize;
2346
+ };
2347
+ };
2348
+ readonly validateUuid: {
2349
+ readonly kind: "boolean";
2350
+ readonly scalar: (i: Uint8Array) => boolean;
2351
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2352
+ readonly element: typeof boolElem;
2353
+ readonly fast: {
2354
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2355
+ readonly element: typeof boolFast;
2356
+ readonly outSize: typeof bitsetOutSize;
2357
+ };
2358
+ };
2359
+ readonly validateIpv4: {
2360
+ readonly kind: "boolean";
2361
+ readonly scalar: (i: Uint8Array) => boolean;
2362
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2363
+ readonly element: typeof boolElem;
2364
+ readonly fast: {
2365
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2366
+ readonly element: typeof boolFast;
2367
+ readonly outSize: typeof bitsetOutSize;
2368
+ };
2369
+ };
2370
+ readonly validateIpv6: {
2371
+ readonly kind: "boolean";
2372
+ readonly scalar: (i: Uint8Array) => boolean;
2373
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2374
+ readonly element: typeof boolElem;
2375
+ readonly fast: {
2376
+ readonly batch: (packed: Uint8Array<ArrayBufferLike>, output: Uint8Array<ArrayBufferLike>) => number;
2377
+ readonly element: typeof boolFast;
2378
+ readonly outSize: typeof bitsetOutSize;
2379
+ };
2380
+ };
2381
+ readonly queryParse: {
2382
+ readonly kind: "bytes";
2383
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2384
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2385
+ readonly element: typeof byteElem;
2386
+ };
2387
+ readonly cookieParse: {
2388
+ readonly kind: "bytes";
2389
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2390
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2391
+ readonly element: typeof byteElem;
2392
+ };
2393
+ readonly formParse: {
2394
+ readonly kind: "bytes";
2395
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2396
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2397
+ readonly element: typeof byteElem;
2398
+ };
2399
+ readonly httpParseRequest: {
2400
+ readonly kind: "bytes";
2401
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2402
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2403
+ readonly element: typeof byteElem;
2404
+ };
2405
+ readonly hexEncode: {
2406
+ readonly kind: "bytes";
2407
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2408
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2409
+ readonly element: typeof byteElem;
2410
+ };
2411
+ readonly hexDecode: {
2412
+ readonly kind: "bytes";
2413
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2414
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2415
+ readonly element: typeof byteElem;
2416
+ };
2417
+ readonly base64Encode: {
2418
+ readonly kind: "bytes";
2419
+ readonly scalar: (i: Uint8Array, urlSafe?: boolean, padding?: boolean) => string | Uint8Array<ArrayBufferLike>;
2420
+ readonly batch: (items: Uint8Array[], urlSafe?: boolean, padding?: boolean) => Uint8Array<ArrayBufferLike>[];
2421
+ readonly element: typeof byteElem;
2422
+ };
2423
+ readonly base64Decode: {
2424
+ readonly kind: "bytes";
2425
+ readonly scalar: (i: Uint8Array, urlSafe?: boolean, padding?: boolean) => Uint8Array<ArrayBufferLike>;
2426
+ readonly batch: (items: Uint8Array[], urlSafe?: boolean, padding?: boolean) => Uint8Array<ArrayBufferLike>[];
2427
+ readonly element: typeof byteElem;
2428
+ };
2429
+ readonly base64UrlEncode: {
2430
+ readonly kind: "bytes";
2431
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2432
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2433
+ readonly element: typeof byteElem;
2434
+ };
2435
+ readonly base64UrlDecode: {
2436
+ readonly kind: "bytes";
2437
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2438
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2439
+ readonly element: typeof byteElem;
2440
+ };
2441
+ readonly gzipCompress: {
2442
+ readonly kind: "bytes";
2443
+ readonly scalar: (i: Uint8Array, level?: number | null) => Uint8Array<ArrayBufferLike>;
2444
+ readonly batch: (items: Uint8Array[], level?: number | null) => Uint8Array<ArrayBufferLike>[];
2445
+ readonly element: typeof byteElem;
2446
+ };
2447
+ readonly gzipDecompress: {
2448
+ readonly kind: "bytes";
2449
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2450
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2451
+ readonly element: typeof byteElem;
2452
+ };
2453
+ readonly brotliCompress: {
2454
+ readonly kind: "bytes";
2455
+ readonly scalar: (i: Uint8Array, quality?: number | null) => Uint8Array<ArrayBufferLike>;
2456
+ readonly batch: (items: Uint8Array[], quality?: number | null) => Uint8Array<ArrayBufferLike>[];
2457
+ readonly element: typeof byteElem;
2458
+ };
2459
+ readonly brotliDecompress: {
2460
+ readonly kind: "bytes";
2461
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2462
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2463
+ readonly element: typeof byteElem;
2464
+ };
2465
+ readonly etag: {
2466
+ readonly kind: "bytes";
2467
+ readonly scalar: (i: Uint8Array, weak?: boolean | null) => string | Uint8Array<ArrayBufferLike>;
2468
+ readonly batch: (items: Uint8Array[], weak?: boolean | null) => Uint8Array<ArrayBufferLike>[];
2469
+ readonly element: typeof byteElem;
2470
+ };
2471
+ readonly urlEncode: {
2472
+ readonly kind: "bytes";
2473
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2474
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2475
+ readonly element: typeof byteElem;
2476
+ };
2477
+ readonly urlDecode: {
2478
+ readonly kind: "bytes";
2479
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2480
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2481
+ readonly element: typeof byteElem;
2482
+ };
2483
+ readonly urlDecodeBytes: {
2484
+ readonly kind: "bytes";
2485
+ readonly scalar: (i: Uint8Array) => Uint8Array<ArrayBufferLike>;
2486
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2487
+ readonly element: typeof byteElem;
2488
+ };
2489
+ readonly wsAcceptKey: {
2490
+ readonly kind: "bytes";
2491
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2492
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2493
+ readonly element: typeof byteElem;
2494
+ };
2495
+ readonly mimeFromExtension: {
2496
+ readonly kind: "bytes";
2497
+ readonly scalar: (i: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2498
+ readonly batch: (items: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2499
+ readonly element: typeof byteElem;
2500
+ };
2501
+ readonly signCookie: {
2502
+ readonly kind: "bytes";
2503
+ readonly scalar: (i: Uint8Array, secret: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2504
+ readonly batch: (items: Uint8Array[], secret: Uint8Array) => Uint8Array<ArrayBufferLike>[];
2505
+ readonly element: typeof byteElem;
2506
+ };
2507
+ readonly verifyCookie: {
2508
+ readonly kind: "boolean";
2509
+ readonly scalar: (i: Uint8Array, secret: Uint8Array) => boolean;
2510
+ readonly batch: (items: Uint8Array[], secret: Uint8Array) => Uint8Array<ArrayBufferLike>;
2511
+ readonly element: typeof boolElem;
2512
+ };
2513
+ readonly csrfVerify: {
2514
+ readonly kind: "boolean";
2515
+ readonly scalar: (i: Uint8Array, secret: Uint8Array) => boolean;
2516
+ readonly batch: (items: Uint8Array[], secret: Uint8Array) => Uint8Array<ArrayBufferLike>;
2517
+ readonly element: typeof boolElem;
2518
+ };
2519
+ readonly passwordHash: {
2520
+ readonly kind: "bytes";
2521
+ readonly scalar: (i: Uint8Array, salt: Uint8Array, options?: PasswordHashOptions | null) => string | Uint8Array<ArrayBufferLike>;
2522
+ readonly batch: (items: Uint8Array[], salt: Uint8Array, options?: PasswordHashOptions | null) => Uint8Array<ArrayBufferLike>[];
2523
+ readonly element: typeof byteElem;
2524
+ };
2525
+ readonly passwordVerify: {
2526
+ readonly kind: "boolean";
2527
+ readonly pairedRest: [
2528
+ 0
2529
+ ];
2530
+ readonly scalar: (i: Uint8Array, phc: Uint8Array) => boolean;
2531
+ readonly batch: (items: Uint8Array[], phcs: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2532
+ readonly element: typeof boolElem;
2533
+ };
2534
+ readonly aeadEncrypt: {
2535
+ readonly kind: "bytes";
2536
+ readonly scalar: (i: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null) => Uint8Array<ArrayBufferLike>;
2537
+ readonly batch: (items: Uint8Array[], key: Uint8Array, nonce: Uint8Array, algorithm?: string | null) => Uint8Array<ArrayBufferLike>[];
2538
+ readonly element: typeof byteElem;
2539
+ };
2540
+ readonly aeadDecrypt: {
2541
+ readonly kind: "bytes";
2542
+ readonly scalar: (i: Uint8Array, key: Uint8Array, nonce: Uint8Array, algorithm?: string | null) => Uint8Array<ArrayBufferLike>;
2543
+ readonly batch: (items: Uint8Array[], key: Uint8Array, nonce: Uint8Array, algorithm?: string | null) => Uint8Array<ArrayBufferLike>[];
2544
+ readonly element: typeof byteElem;
2545
+ };
2546
+ readonly jwtSign: {
2547
+ readonly kind: "bytes";
2548
+ readonly scalar: (i: Uint8Array, secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number) => Uint8Array<ArrayBufferLike>;
2549
+ readonly batch: (items: Uint8Array[], secret: Uint8Array, ttlSeconds?: number | null, nowSeconds?: number) => Uint8Array<ArrayBufferLike>[];
2550
+ readonly element: typeof byteElem;
2551
+ };
2552
+ readonly jwtVerify: {
2553
+ readonly kind: "boolean";
2554
+ readonly scalar: (i: Uint8Array, secret: Uint8Array, nowSeconds?: number) => boolean;
2555
+ readonly batch: (items: Uint8Array[], secret: Uint8Array, nowSeconds?: number) => Uint8Array<ArrayBufferLike>;
2556
+ readonly element: typeof boolElem;
2557
+ };
2558
+ readonly jsonPatch: {
2559
+ readonly kind: "bytes";
2560
+ readonly pairedRest: [
2561
+ 0
2562
+ ];
2563
+ readonly scalar: (i: Uint8Array, patch: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2564
+ readonly batch: (items: Uint8Array[], patches: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2565
+ readonly element: typeof byteElem;
2566
+ };
2567
+ readonly urlResolve: {
2568
+ readonly kind: "bytes";
2569
+ readonly pairedRest: [
2570
+ 0
2571
+ ];
2572
+ readonly scalar: (i: Uint8Array, base: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2573
+ readonly batch: (items: Uint8Array[], bases: Uint8Array[]) => Uint8Array<ArrayBufferLike>[];
2574
+ readonly element: typeof byteElem;
2575
+ };
2576
+ readonly wsFrameEncode: {
2577
+ readonly kind: "bytes";
2578
+ readonly scalar: (i: Uint8Array, opcode: number, mask: boolean, fin: boolean) => Uint8Array<ArrayBufferLike>;
2579
+ readonly batch: (items: Uint8Array[], opcode: number, mask: boolean, fin: boolean) => Uint8Array<ArrayBufferLike>[];
2580
+ readonly element: typeof byteElem;
2581
+ };
2582
+ readonly sseEncode: {
2583
+ readonly kind: "bytes";
2584
+ readonly scalar: (i: Uint8Array, event?: string | null, id?: string | null, retry?: number | null) => Uint8Array<ArrayBufferLike>;
2585
+ readonly batch: (items: Uint8Array[], event?: string | null, id?: string | null, retry?: number | null) => Uint8Array<ArrayBufferLike>[];
2586
+ readonly element: typeof byteElem;
2587
+ };
2588
+ readonly schemaValidate: {
2589
+ readonly kind: "boolean";
2590
+ readonly scalar: (i: Uint8Array, validator: SchemaValidator) => boolean;
2591
+ readonly batch: (items: Uint8Array[], validator: SchemaValidator) => Uint8Array<ArrayBufferLike>;
2592
+ readonly element: typeof boolElem;
2593
+ };
2594
+ readonly hmacSha256: {
2595
+ readonly kind: "bytes";
2596
+ readonly scalar: (i: Uint8Array, key: Uint8Array) => string | Uint8Array<ArrayBufferLike>;
2597
+ readonly batch: (items: Uint8Array[], key: Uint8Array) => Uint8Array<ArrayBufferLike>[];
2598
+ readonly element: typeof byteElem;
2599
+ };
2600
+ readonly hmacSha256Verify: {
2601
+ readonly kind: "boolean";
2602
+ readonly pairedRest: [
2603
+ 1
2604
+ ];
2605
+ readonly scalar: (i: Uint8Array, key: Uint8Array, sig: Uint8Array) => boolean;
2606
+ readonly batch: (items: Uint8Array[], key: Uint8Array, sigs: Uint8Array[]) => Uint8Array<ArrayBufferLike>;
2607
+ readonly element: typeof boolElem;
2608
+ };
2609
+ };
2610
+ /** Kind of a specific op. */
2611
+ export type LoaderOpKind<K extends LoaderOpName> = (typeof LOADER_OPS)[K]["kind"];
2612
+ /** Single-item result type of a specific op. */
2613
+ export type LoaderScalar<K extends LoaderOpName> = ScalarResult<LoaderOpKind<K>>;
2614
+ /** All op names, as a readonly array (for iteration). */
2615
+ export declare const LOADER_OP_NAMES: LoaderOpName[];
2616
+ /** Options for `createLoader()` / `loader.configure()`. */
2617
+ export interface LoaderOptions {
2618
+ /** Let each op adapt `batchMin` from measured dispatch cost. Default true. */
2619
+ adaptive?: boolean;
2620
+ /** Initial batch threshold in [2, 8]. Default 2 (batch wins for n >= 2). */
2621
+ batchMin?: number;
2622
+ /** Max cached keys (bounded LRU). 0 disables caching. Default 256. */
2623
+ maxCacheKeys?: number;
2624
+ /** Default `cache` behavior for `load()`. Default true. */
2625
+ caching?: boolean;
2626
+ /** Sample timing every N dispatches (hot-path cost control). Default 32. */
2627
+ sampleEvery?: number;
2628
+ /**
2629
+ * `load()` dispatch strategy. `"auto"` (default) switches each op between
2630
+ * `"single"` (low load → direct scalar call, no coalescer) and
2631
+ * `"coalesce"` (rising load → one packed batch call) from observed load.
2632
+ */
2633
+ loadStrategy?: LoadStrategy;
2634
+ }
2635
+ /** Options for `load()` / `opFn.load()`. */
2636
+ export interface LoadOptions {
2637
+ /**
2638
+ * Explicit cache key. When omitted (and caching is on) the default key is
2639
+ * `fnv1a64(input)` — which costs one extra native call per load.
2640
+ */
2641
+ key?: string;
2642
+ /** Override the loader-wide caching toggle for this call. Default true. */
2643
+ cache?: boolean;
2644
+ }
2645
+ /** Per-op counters exposed on `opFn.stats`. */
2646
+ export interface LoaderOpStats {
2647
+ scalarCalls: number;
2648
+ batchCalls: number;
2649
+ itemsDispatched: number;
2650
+ cachedHits: number;
2651
+ /** Current learned batch threshold for this op. */
2652
+ batchMin: number;
2653
+ /** Current `load()` strategy: "single" (low load) or "coalesce" (bulk). */
2654
+ mode: "single" | "coalesce";
2655
+ }
2656
+ /** Aggregate loader statistics. */
2657
+ export interface LoaderStats {
2658
+ scalarCalls: number;
2659
+ batchCalls: number;
2660
+ itemsDispatched: number;
2661
+ flushes: number;
2662
+ cachedHits: number;
2663
+ cacheSize: number;
2664
+ cacheEvictions: number;
2665
+ }
2666
+ /** A specialized, pre-bound op function returned by `loader(op)`. */
2667
+ export interface LoaderOpFn<K extends LoaderOpName> {
2668
+ /** Single item → scalar result. */
2669
+ (input: Uint8Array, ...rest: LoaderOpArgs[K]): LoaderScalar<K>;
2670
+ /** Bulk items → ONE packed batch call; same shape as `rust.batch.<op>`. */
2671
+ (inputs: Uint8Array[], ...rest: LoaderBulkArgs<K>): LoaderBulk<K>;
2672
+ readonly name: K;
2673
+ readonly stats: LoaderOpStats;
2674
+ clear(): void;
2675
+ /** Sync cache peek (default key `fnv1a64(input)` unless `key` given). */
2676
+ cache(input: Uint8Array, key?: string): LoaderScalar<K> | undefined;
2677
+ /**
2678
+ * Coalesced, cache-aware load. Unavailable (`undefined`) on ops that require
2679
+ * extra arguments (e.g. `hmacSha256`, `signCookie`) — use `run` for those.
2680
+ */
2681
+ load: K extends LoadableName ? LoaderLoadFn<K> : undefined;
2682
+ }
2683
+ export type LoaderLoadFn<K extends LoaderOpName> = (input: Uint8Array, opts?: LoadOptions) => Promise<LoaderScalar<K>>;
2684
+ /** Ops whose extra args are all optional/empty → they support `load()`. */
2685
+ export type LoadableName = {
2686
+ [K in LoaderOpName]: LoaderOpArgs[K] extends [
2687
+ ] | [
2688
+ unknown?
2689
+ ] | [
2690
+ unknown?,
2691
+ unknown?
2692
+ ] | [
2693
+ unknown?,
2694
+ unknown?,
2695
+ unknown?
2696
+ ] ? K : never;
2697
+ }[LoaderOpName];
2698
+ /** A validator-bound helper returned by `loader.schema(validator)`. */
2699
+ export interface LoaderSchemaFn {
2700
+ /** Single JSON document → valid? */
2701
+ (input: Uint8Array): boolean;
2702
+ /** Bulk JSON documents → bitset (1 per doc). */
2703
+ (inputs: Uint8Array[]): Uint8Array;
2704
+ /** Count how many bulk documents are valid. */
2705
+ count(inputs: Uint8Array[]): number;
2706
+ }
2707
+ /** The global callable loader. */
2708
+ interface Loader$1 {
2709
+ /** Higher-order function: `loader(op)` → specialized hot op function. */
2710
+ <K extends LoaderOpName>(op: K): LoaderOpFn<K>;
2711
+ /** Single-item dispatch. */
2712
+ run<K extends LoaderOpName>(op: K, input: Uint8Array, ...rest: LoaderOpArgs[K]): LoaderScalar<K>;
2713
+ /** Bulk dispatch (one packed batch call, or adaptive scalar loop). */
2714
+ run<K extends LoaderOpName>(op: K, inputs: Uint8Array[], ...rest: LoaderBulkArgs<K>): LoaderBulk<K>;
2715
+ /** Coalesced, cache-aware load (ops with required extra args throw). */
2716
+ load<K extends LoadableName>(op: K, input: Uint8Array, opts?: LoadOptions): Promise<LoaderScalar<K>>;
2717
+ /** Sync cache peek. */
2718
+ cache<K extends LoaderOpName>(op: K, input: Uint8Array, key?: string): LoaderScalar<K> | undefined;
2719
+ /**
2720
+ * Bind a `SchemaValidator` for repeated single/bulk JSON-schema validation
2721
+ * plus a whole-batch `count`. The returned callable uses the loader's normal
2722
+ * dispatch machinery (cost model + counters).
2723
+ */
2724
+ schema(validator: SchemaValidator): LoaderSchemaFn;
2725
+ /** Clear the shared cache (pending coalesced loads still flush). */
2726
+ clear(): void;
2727
+ /** Update options at runtime. */
2728
+ configure(options: LoaderOptions): void;
2729
+ readonly stats: LoaderStats;
2730
+ readonly opNames: LoaderOpName[];
2731
+ }
2732
+ /** Load-dispatch strategy selector for `load()`. */
2733
+ export type LoadStrategy = "auto" | "single" | "coalesce";
2734
+ /** Create an isolated loader with the given defaults. */
2735
+ export declare function createLoader(options?: LoaderOptions): Loader$1;
2736
+ /**
2737
+ * The global, ready-to-use loader. Most consumers just do
2738
+ * `import { loader } from "castrum"` and either `loader("validateEmail")(…)`
2739
+ * (higher-order function) or `loader.run("validateEmail", …)`.
2740
+ */
2741
+ export declare const loader: Loader$1;
2742
+ /**
2743
+ * Batch-validate JSON documents against a schema through the loader's bulk
2744
+ * `schemaValidate` path. Returns a bitset — byte `i` is 1 when document `i`
2745
+ * is valid (same shape as `rust.batch.schemaValidate`).
2746
+ */
2747
+ export declare function validateMany(validator: SchemaValidator, docs: Uint8Array[]): Uint8Array;
2748
+ /** Count how many of `docs` validate against `validator` (one packed call). */
2749
+ export declare function validateCount(validator: SchemaValidator, docs: Uint8Array[]): number;
2750
+ /**
2751
+ * Generic loader bulk dispatch: `loader.run(op, items, ...rest)` → one packed
2752
+ * batch native call (or the adaptive scalar loop for tiny batches).
2753
+ */
2754
+ export declare function runMany<K extends LoaderOpName>(op: K, items: Uint8Array[], ...rest: LoaderBulkArgs<K>): LoaderBulk<K>;
2755
+ /** Single-item loader dispatch — pairs with `runMany` for mixed workloads. */
2756
+ export declare function runOne<K extends LoaderOpName>(op: K, item: Uint8Array, ...rest: LoaderOpArgs[K]): LoaderScalar<K>;
2757
+
2758
+ export {
2759
+ Loader$1 as Loader,
2760
+ RouteHandler as IngressNodeRouteHandler,
2761
+ };
2762
+
2763
+ export {};