@jini-ai/http-kit 0.7.3-next.2 → 0.7.4

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.
@@ -0,0 +1,279 @@
1
+ import { httpFallbackCopy } from '@jini-ai/core/contracts/server';
2
+ import { runOperation, UNAVAILABLE_ERROR_ID } from '@jini-ai/core/errors/reporter';
3
+ import { allowRouteOrigin, routeAuthorize, sendRouteException } from './adapter.js';
4
+ import { allowRouteBody, applyAdmittedResponseHeaders, applyResponseHeaders, assertRequestFactsPort, requestScopedDeps, routeRequestInput } from './adapter-request.js';
5
+ import { deferredBodyReader } from './deferred-body.js';
6
+ import { sendWebResponse } from './node-bridge.js';
7
+ import { sendApiError } from './response.js';
8
+ /**
9
+ * Combines required route fields and optional settings into a fresh raw spec, pinning its generic
10
+ * parameters at the definition site. Optional settings take precedence; neither argument is mutated.
11
+ * @complexity O(1).
12
+ */
13
+ export function defineRawRoute(requiredArgs, optionalArgs = {}) {
14
+ return { ...requiredArgs, ...optionalArgs };
15
+ }
16
+ /**
17
+ * Mounts one raw spec. Gates run in `mountJsonRoute`'s order — static response headers, body cap,
18
+ * workspace (then `admittedResponseHeaders`), same-origin, authenticate — then `handle`, whose `raw.readBody` reads the request body only
19
+ * when called (so a route that defers its body never reads an unauthorized one); a thrown error takes the same `onError` /
20
+ * SEC-005 path. The returned `Response` is written with its status, every header (each `Set-Cookie`
21
+ * on its own line) and its body: none ends the answer, a stream is piped and cancelled when the
22
+ * client leaves, and `handle`'s `signal` aborts on that same disconnect.
23
+ * `optional.bodyParsers` are registered between the path and the handler of this one route (`RouteMountOptions`).
24
+ * @throws At mount, when the spec opts into `requestFacts` without the host's resolver port.
25
+ * @complexity O(1) setup; per request, the gates, the host ports, `handle` and the body copy.
26
+ */
27
+ export function mountRawRoute(required, optional = {}) {
28
+ const { app, spec, adapter } = required;
29
+ const mountedDeps = required.deps;
30
+ const resolveDeps = required.depsForRequest ?? ((facts) => requestScopedDeps({ ...facts, deps: mountedDeps }, optional));
31
+ assertRequestFactsPort({ spec });
32
+ // The mode is chosen once, at mount: with `errors`, every request of this route uses the same
33
+ // mounted reporter for its execution, its exception and its write failures.
34
+ const errors = adapter?.errors;
35
+ app[spec.method](spec.path, ...(optional.bodyParsers ?? []), async (req, res) => {
36
+ // Observed on `res`, not `req`, for the reason `mountJsonRoute` documents: a parsed request
37
+ // body has already ended the request stream, so `req`'s `close` is not a disconnect. This abort
38
+ // is also how reporter mode tells a client that left (cancelled, nothing reported) from a failure.
39
+ const abortController = new AbortController();
40
+ const onResponseClose = () => abortController.abort();
41
+ res.on('close', onResponseClose);
42
+ const call = { req, res, spec, resolveDeps, mountOptions: optional, adapter, signal: abortController.signal };
43
+ try {
44
+ await (errors ? reporterRawRoute(call, { errors }) : legacyRawRoute(call));
45
+ }
46
+ finally {
47
+ res.off('close', onResponseClose);
48
+ }
49
+ });
50
+ }
51
+ /** Legacy mode (no `errors`): today's try/catch, with the SEC-005 sink of `sendRouteException`. */
52
+ async function legacyRawRoute(call) {
53
+ const { req, res, spec, adapter, signal } = call;
54
+ try {
55
+ const response = await executeRawRoute(call);
56
+ if (response)
57
+ await writeRawResponse({ req, res, spec, response, signal });
58
+ }
59
+ catch (e) {
60
+ // A body that fails after the head went out cannot be answered any more: cut the connection.
61
+ if (res.headersSent)
62
+ res.destroy();
63
+ else
64
+ sendRouteException({ res, spec, adapter, error: e });
65
+ }
66
+ }
67
+ /**
68
+ * Covers the gates, `handle`, and the write-back of its `Response`; returns early when a gate answered,
69
+ * with `undefined` (the gate helpers own that refusal's write, as in `mountJsonRoute`). The write-back
70
+ * itself is the caller's, after the operation ends (`writeTracedResponse`): this hands it back unwritten.
71
+ */
72
+ async function executeRawRoute({ req, res, spec, resolveDeps, adapter, signal }) {
73
+ applyResponseHeaders({ res, headers: spec.responseHeaders });
74
+ // Once per request, before every gate: the ports and `handle` see this request's bound deps.
75
+ const deps = resolveDeps({ req, res });
76
+ // `readBody` reads nothing until `handle` calls it, after every gate below (`deferred-body.ts`).
77
+ const raw = { ...routeRequestInput({ req, spec, deps }), readBody: deferredBodyReader({ req, res }) };
78
+ if (!allowRouteBody({ req, res, spec }))
79
+ return undefined;
80
+ if (spec.ports?.workspace)
81
+ await spec.ports.workspace({ raw, deps });
82
+ applyAdmittedResponseHeaders({ res, raw, spec });
83
+ if (!allowRouteOrigin({ req, res, spec, adapter }))
84
+ return undefined;
85
+ const context = spec.ports?.authenticate ? await spec.ports.authenticate({ raw, res, deps }) : undefined;
86
+ const authorize = routeAuthorize({ ports: spec.ports, deps, context });
87
+ return spec.handle({ raw, deps, context, authorize }, { signal });
88
+ }
89
+ /** Writes `handle`'s `Response` back; the transport owns this write and the body's drain. */
90
+ async function writeRawResponse({ req, res, spec, response, signal }) {
91
+ // The client left while `handle` ran: release the body's producer instead of writing to a closed socket.
92
+ if (signal.aborted) {
93
+ await response.body?.cancel();
94
+ return;
95
+ }
96
+ if (spec.bufferedReply === 'redirect')
97
+ await sendRedirectOrBufferedReply({ response, res });
98
+ else if (spec.bufferedReply)
99
+ await sendBufferedReply({ response, res });
100
+ else
101
+ await sendWebResponse({ response, res }, { headOnly: req.method === 'HEAD' });
102
+ }
103
+ /** What a client that hung up is logged as (nginx's convention); nobody receives it. */
104
+ const CLIENT_CLOSED_STATUS = 499;
105
+ const CANCELLED = { outcome: 'cancelled', failed: false, attributes: { 'http.status_code': CLIENT_CLOSED_STATUS } };
106
+ /**
107
+ * Reporter mode: one `http.route` operation spans the gates, `handle` and the creation of its
108
+ * `Response`, and ends before anything of that response is written. A stream's drain can outlive
109
+ * the request by minutes (SSE), so it is transport-owned and never held inside the operation.
110
+ */
111
+ async function reporterRawRoute(call, { errors }) {
112
+ const method = call.spec.method.toUpperCase();
113
+ // The registered pattern (`/files/:id`), never `req.url`: a URL carries ids, query strings and tokens.
114
+ const attributes = { 'http.method': method, 'http.route': call.spec.path };
115
+ const run = await runOperation({
116
+ deps: errors, operation: 'http.route', scope: 'http', step: `Handle ${method} ${call.spec.path}`, fallback: httpFallbackCopy({ method }), attributes,
117
+ work: () => tracedRawRoute(call, { errors }),
118
+ classify: (tagged) => tagged.verdict,
119
+ settle: (error) => disconnectVerdict({ signal: call.signal, error }),
120
+ }, { audience: 'anonymous' });
121
+ // The operation has ended. Every write below is the transport's, so a failure in it is recorded on
122
+ // its own and never reopens or re-ends the route operation.
123
+ if (run.ok) {
124
+ if (run.value.forwarded)
125
+ throw run.value.forwarded.error;
126
+ if (run.value.response)
127
+ await writeTracedResponse(call, { reporter: errors.reporter, attributes, response: run.value.response });
128
+ return;
129
+ }
130
+ // A cancelled run is a client that left: there is nobody to answer and nothing to report.
131
+ if (!('cancelled' in run))
132
+ writeFailure({ res: call.res, failure: run.failure });
133
+ }
134
+ /** The gates and `handle`, tagged; a throw goes to the host's `onError` first, as in legacy mode. */
135
+ async function tracedRawRoute(call, { errors }) {
136
+ try {
137
+ const response = await executeRawRoute(call);
138
+ // A gate wrote and finished its refusal, and that finished response's `close` aborts `signal` too:
139
+ // only a client gone before `handle`'s `Response` could be written is a cancellation.
140
+ if (!response)
141
+ return { response, verdict: answeredVerdict({ status: call.res.statusCode, aborted: false }) };
142
+ return { response, verdict: answeredVerdict({ status: response.status, aborted: call.signal.aborted }) };
143
+ }
144
+ catch (error) {
145
+ const onError = call.spec.ports?.onError;
146
+ // No host policy, or a head already on the wire: the throw reaches `runOperation`, whose reporter
147
+ // classifies it (a ClientFacingError or catalog refusal, else one incident).
148
+ if (!onError || call.res.headersSent)
149
+ throw error;
150
+ return hostPolicyAnswer({ res: call.res, error, onError }, { reporter: errors.reporter, mountOptions: call.mountOptions });
151
+ }
152
+ }
153
+ /**
154
+ * The host's `onError` answers BEFORE the reporter classifies anything, as in legacy mode. It writes
155
+ * to `res` itself, so this one write precedes the operation's end; the verdict is the status it chose.
156
+ * A policy that throws is its own incident, and the ORIGINAL error is rethrown so the reply carries its ID.
157
+ */
158
+ function hostPolicyAnswer({ res, error, onError }, { reporter, mountOptions }) {
159
+ try {
160
+ onError({ res, error });
161
+ }
162
+ catch (policyError) {
163
+ if (mountOptions.preserveHostErrorRouting)
164
+ return { response: undefined, verdict: { outcome: 'failed', failed: true }, forwarded: { error: policyError } };
165
+ recordOnce({ reporter, error: policyError, step: 'Answer with host error policy' });
166
+ throw error;
167
+ }
168
+ return { response: undefined, verdict: answeredVerdict({ status: res.statusCode, aborted: false }) };
169
+ }
170
+ /** A route's own answer: a 5xx it built is `failed` (its producer owns any report), a 4xx `refused`. */
171
+ function answeredVerdict({ status, aborted }) {
172
+ if (aborted)
173
+ return CANCELLED;
174
+ const outcome = status >= 500 ? 'failed' : status >= 400 ? 'refused' : 'completed';
175
+ return { outcome, failed: outcome === 'failed', attributes: { 'http.status_code': status } };
176
+ }
177
+ function isAbortLike({ signal, error }) {
178
+ return error === signal.reason || (typeof error === 'object' && error !== null && error.name === 'AbortError');
179
+ }
180
+ /**
181
+ * Cancellation only when the client is gone (the response's `close` aborted `signal`) AND the throw
182
+ * is that abort: the handler stopped because nobody is listening. Any other throw after a disconnect
183
+ * is a real failure and is recorded.
184
+ */
185
+ function disconnectVerdict({ signal, error }) {
186
+ return signal.aborted && isAbortLike({ signal, error }) ? CANCELLED : undefined;
187
+ }
188
+ /** The reporter's answer, written after the operation ended; a head already sent means the connection is cut instead. */
189
+ function writeFailure({ res, failure }) {
190
+ if (res.headersSent)
191
+ res.destroy();
192
+ else
193
+ sendApiError({ res, status: failure.status, error: failure.error });
194
+ }
195
+ /** Records a failure the reporter owns no operation for; a broken reporter still yields the stand-in ID. */
196
+ function recordOnce({ reporter, error, step, attributes }) {
197
+ try {
198
+ return reporter.record({ error, step, operation: 'http.route' }, attributes ? { attributes } : {}).errorId;
199
+ }
200
+ catch {
201
+ return UNAVAILABLE_ERROR_ID;
202
+ }
203
+ }
204
+ /**
205
+ * Writes `handle`'s `Response`. The transport owns this write: a stream that fails mid-way is recorded
206
+ * once here (the route operation already ended `completed` and is not touched), then the connection is
207
+ * closed, or answered with the ID when no head went out yet (a buffered body). A client that left is
208
+ * not a failure: the response's `close` aborted `signal`, so an abort-like rejection is just cut.
209
+ */
210
+ async function writeTracedResponse(call, { reporter, attributes, response }) {
211
+ const { res, signal } = call;
212
+ try {
213
+ await writeRawResponse({ ...call, response });
214
+ }
215
+ catch (error) {
216
+ if (disconnectVerdict({ signal, error })) {
217
+ res.destroy();
218
+ return;
219
+ }
220
+ if (!res.headersSent && call.mountOptions.preserveHostErrorRouting && call.spec.ports?.onError) {
221
+ call.spec.ports.onError({ res, error });
222
+ return;
223
+ }
224
+ const errorId = recordOnce({ reporter, error, step: 'Write response', attributes });
225
+ const fallback = httpFallbackCopy({ method: call.spec.method });
226
+ if (res.headersSent)
227
+ res.destroy();
228
+ else
229
+ sendApiError({ res, status: 500, error: { code: 'INTERNAL_ERROR', message: `${fallback.message} ${fallback.action} (error ${errorId})`, requestId: errorId } });
230
+ }
231
+ }
232
+ /**
233
+ * The `bufferedReply` write: the whole body is read, then handed to Express's own `res.send(Buffer)`, so
234
+ * the answer is exactly what a hand-written `res.status(s).set(h).send(buffer)` route gave — `Content-Length`,
235
+ * the host app's `etag` setting (Express's default: a weak ETag of the body; none when a header already names
236
+ * one), a bodiless 304 when the GET/HEAD is fresh (`If-None-Match` / `If-Modified-Since`, 2xx only), and no
237
+ * body for HEAD. Headers are copied as the streaming writer copies them (each `Set-Cookie` on its own line,
238
+ * `Vary` merged); a header the `Response` lacks is not invented, except the `application/octet-stream`
239
+ * `Content-Type` Express gives a buffer with none.
240
+ * @complexity O(n) in the body size: the body is held in memory, so this is for finished answers, never streams.
241
+ */
242
+ async function sendBufferedReply({ response, res }) {
243
+ const body = Buffer.from(await response.arrayBuffer());
244
+ res.statusCode = response.status;
245
+ copyResponseHeaders({ response, res });
246
+ res.send(body);
247
+ }
248
+ /** Every header of `response` onto `res` as `sendBufferedReply` copies them (each `Set-Cookie` on its own line, `Vary` merged), minus `skip`. O(h). */
249
+ function copyResponseHeaders({ response, res }, { skip = '' } = {}) {
250
+ const cookies = response.headers.getSetCookie();
251
+ response.headers.forEach((value, name) => {
252
+ if (name === 'vary')
253
+ res.vary(value);
254
+ else if (name !== 'set-cookie' && name !== skip)
255
+ res.setHeader(name, value);
256
+ });
257
+ for (const cookie of cookies)
258
+ res.append('set-cookie', cookie);
259
+ }
260
+ /**
261
+ * The `bufferedReply: 'redirect'` write: a 3xx `Response` with a `Location` is answered by Express's own
262
+ * `res.redirect(status, location)`, after its other headers and cookies are copied as `sendBufferedReply`
263
+ * copies them, so the answer is exactly what a hand-written `res.redirect` route gave — the Accept-negotiated
264
+ * HTML / plain-text / empty body, `Vary: Accept`, `Content-Length`, no body for HEAD. (`Location` itself is
265
+ * left to `res.redirect`, which writes it through `res.location`'s encoding, as the hand-written route did.)
266
+ * Any other answer takes `sendBufferedReply`.
267
+ * @complexity O(h) headers for a redirect (its body is discarded); otherwise `sendBufferedReply`'s.
268
+ */
269
+ async function sendRedirectOrBufferedReply({ response, res }) {
270
+ const location = response.headers.get('location');
271
+ if (response.status < 300 || response.status > 399 || location === null) {
272
+ await sendBufferedReply({ response, res });
273
+ return;
274
+ }
275
+ await response.body?.cancel();
276
+ copyResponseHeaders({ response, res }, { skip: 'location' });
277
+ res.redirect(response.status, location);
278
+ }
279
+ //# sourceMappingURL=raw-route.js.map
@@ -0,0 +1,19 @@
1
+ import type { ReportRouteInternalError } from '@jini-ai/core/contracts/server';
2
+ import type { ErrorReporter } from '@jini-ai/core/errors/reporter';
3
+ /**
4
+ * The reporter-mode `reportInternalError` an in-route caller uses for an incident it handles itself
5
+ * (it returns `err(...)` instead of throwing). The host's reporter owns the one record and tracker
6
+ * report under one error ID; the caller gets its plain words with that ID appended and as
7
+ * `requestId`. The boundary then classifies the returned `INTERNAL_ERROR` as `failed` without
8
+ * reporting it again.
9
+ *
10
+ * The legacy `onInternalError` sink in the compatibility second argument is ignored on purpose:
11
+ * a host in reporter mode must never get both a sink call and a record for one failure.
12
+ * @param required.reporter The host's one reporter; only `record` is used.
13
+ * @returns A `ReportRouteInternalError` with the same call shape as the legacy reporter.
14
+ * @complexity O(1) per call besides the reporter.
15
+ */
16
+ export declare function createReporterRouteInternalError({ reporter }: {
17
+ readonly reporter: Pick<ErrorReporter, 'record'>;
18
+ }, _optional?: Record<string, never>): ReportRouteInternalError;
19
+ //# sourceMappingURL=reporter-internal-error.d.ts.map
@@ -0,0 +1,34 @@
1
+ /** Route fields that are fixed, low-cardinality labels and may become record attributes. Anything
2
+ * else a route put on its report (a request body, a path, a user name) stays out of telemetry. */
3
+ const BOUNDED_REPORT_FIELDS = ['runId', 'batchId', 'source', 'provider', 'operation'];
4
+ /** Copies only the allow-listed fields whose value is a string; the reporter further drops any
5
+ * value that is not a short fixed-shape label. */
6
+ function boundedReportAttributes({ report }) {
7
+ const attributes = {};
8
+ for (const field of BOUNDED_REPORT_FIELDS) {
9
+ const value = report[field];
10
+ if (typeof value === 'string')
11
+ attributes[field] = value;
12
+ }
13
+ return attributes;
14
+ }
15
+ /**
16
+ * The reporter-mode `reportInternalError` an in-route caller uses for an incident it handles itself
17
+ * (it returns `err(...)` instead of throwing). The host's reporter owns the one record and tracker
18
+ * report under one error ID; the caller gets its plain words with that ID appended and as
19
+ * `requestId`. The boundary then classifies the returned `INTERNAL_ERROR` as `failed` without
20
+ * reporting it again.
21
+ *
22
+ * The legacy `onInternalError` sink in the compatibility second argument is ignored on purpose:
23
+ * a host in reporter mode must never get both a sink call and a record for one failure.
24
+ * @param required.reporter The host's one reporter; only `record` is used.
25
+ * @returns A `ReportRouteInternalError` with the same call shape as the legacy reporter.
26
+ * @complexity O(1) per call besides the reporter.
27
+ */
28
+ export function createReporterRouteInternalError({ reporter }, _optional = {}) {
29
+ return ({ report, logSource, message }) => {
30
+ const { errorId } = reporter.record({ error: report.error, step: logSource, operation: 'http.route' }, { attributes: boundedReportAttributes({ report }) });
31
+ return { code: 'INTERNAL_ERROR', message: `${message} (error ${errorId})`, requestId: errorId };
32
+ };
33
+ }
34
+ //# sourceMappingURL=reporter-internal-error.js.map
@@ -0,0 +1,9 @@
1
+ /** The header read from the request and echoed on the response (the de-facto proxy convention). */
2
+ export declare const REQUEST_ID_HEADER = "x-request-id";
3
+ /** Reuses a safe inbound `x-request-id`, else mints one (UUID v4 by default). */
4
+ export declare function resolveRequestId(required: {
5
+ header: string | string[] | undefined;
6
+ }, { mint }?: {
7
+ mint?: () => string;
8
+ }): string;
9
+ //# sourceMappingURL=request-id.d.ts.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @file Request-ID resolution for inbound HTTP (Reliability: structured logging + request IDs).
3
+ * Pure rules only; the host's request-tracking middleware applies them, because that middleware is
4
+ * registered first in the host app and so sees every request — including ones the serving gate
5
+ * rejects and 404s — that a log/trace join would need.
6
+ */
7
+ import { randomUUID } from "node:crypto";
8
+ /** The header read from the request and echoed on the response (the de-facto proxy convention). */
9
+ export const REQUEST_ID_HEADER = "x-request-id";
10
+ /**
11
+ * A proxy's or caller's id is reused only when it is short and log-safe: anything else could forge
12
+ * or split a log line keyed on it, or blow up the cardinality of whatever stores it. Bounded at 128,
13
+ * which fits UUIDs, ULIDs and the common edge-proxy formats.
14
+ */
15
+ const SAFE_INBOUND_REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/;
16
+ /** Reuses a safe inbound `x-request-id`, else mints one (UUID v4 by default). */
17
+ export function resolveRequestId(required, { mint = randomUUID } = {}) {
18
+ const { header } = required;
19
+ return typeof header === "string" && SAFE_INBOUND_REQUEST_ID.test(header) ? header : mint();
20
+ }
21
+ //# sourceMappingURL=request-id.js.map
package/dist/request.d.ts CHANGED
@@ -3,12 +3,17 @@
3
3
  * `RouteInputContext` the rest of the module operates on.
4
4
  */
5
5
  import type { Request } from 'express';
6
- import type { RouteInputContext } from '@jini-ai/core/contracts/server';
6
+ import type { RouteInputContext, RouteRequestFacts } from '@jini-ai/core/contracts/server';
7
7
  /**
8
8
  * Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
9
- * route's `parse` function can be unit-tested without constructing a real `Request`.
9
+ * route's `parse` function can be unit-tested without constructing a real `Request`. `headers` names
10
+ * the request headers to hand over (`raw.headers`, lower-cased keys, absent ones left out) and `facts`
11
+ * the host-resolved request facts (`raw.facts`); without them neither key exists.
10
12
  */
11
13
  export declare function rawInput({ req }: {
12
14
  readonly req: Request;
13
- }, _optional?: Record<string, never>): RouteInputContext;
15
+ }, { headers, facts }?: {
16
+ readonly headers?: readonly string[];
17
+ readonly facts?: RouteRequestFacts;
18
+ }): RouteInputContext;
14
19
  //# sourceMappingURL=request.d.ts.map
package/dist/request.js CHANGED
@@ -1,12 +1,27 @@
1
1
  /**
2
2
  * Extracts `body`/`query`/`params` from an Express `Request` into a `RouteInputContext`, so a
3
- * route's `parse` function can be unit-tested without constructing a real `Request`.
3
+ * route's `parse` function can be unit-tested without constructing a real `Request`. `headers` names
4
+ * the request headers to hand over (`raw.headers`, lower-cased keys, absent ones left out) and `facts`
5
+ * the host-resolved request facts (`raw.facts`); without them neither key exists.
4
6
  */
5
- export function rawInput({ req }, _optional = {}) {
7
+ export function rawInput({ req }, { headers, facts } = {}) {
6
8
  return {
7
9
  body: req.body,
8
10
  query: (req.query ?? {}),
9
11
  params: (req.params ?? {}),
12
+ ...(headers === undefined ? {} : { headers: pickHeaders({ req, names: headers }) }),
13
+ ...(facts === undefined ? {} : { facts }),
10
14
  };
11
15
  }
16
+ /** The named request headers, keyed lower-case; a repeated header is comma-joined as HTTP folds it. */
17
+ function pickHeaders({ req, names }) {
18
+ const picked = {};
19
+ for (const name of names) {
20
+ const key = name.toLowerCase();
21
+ const value = req.headers?.[key];
22
+ if (value !== undefined)
23
+ picked[key] = Array.isArray(value) ? value.join(', ') : value;
24
+ }
25
+ return picked;
26
+ }
12
27
  //# sourceMappingURL=request.js.map
package/dist/types.d.ts CHANGED
@@ -3,8 +3,8 @@
3
3
  * The framework-free vocabulary (`Result`, `Handler`, `InputParser`, …) lives in
4
4
  * `@jini-ai/core/contracts/server`.
5
5
  */
6
- import type { Handler, HttpMethod, InputParser, RouteInputContext } from '@jini-ai/core/contracts/server';
7
- import type { Response } from 'express';
6
+ import type { Handler, HttpMethod, InputParser, JsonRouteAuthorize, JsonRouteAuthorizeScope, RawRouteInputContext, RouteInputContext, RouteRequestFacts, ServerApiError } from '@jini-ai/core/contracts/server';
7
+ import type { Request, RequestHandler, Response } from 'express';
8
8
  /** Host-owned workspace, authentication/authorization and exception policy.
9
9
  * Guards throw on rejection; the error port owns their wire envelope. Without an error port the
10
10
  * adapter retains its caller-safe-error and SEC-005 redaction policy. Authentication can await
@@ -15,33 +15,156 @@ export interface JsonRoutePorts<Deps, Context = undefined> {
15
15
  readonly raw: RouteInputContext;
16
16
  readonly deps: Deps;
17
17
  }) => void | Promise<void>;
18
+ /** May answer `undefined` (no principal yet): the handler then sees no `context`, and the host's
19
+ * `authorize` port decides — after `parse`, so a body refusal still wins over a missing session. */
18
20
  readonly authenticate?: (requiredArgs: {
19
21
  readonly raw: RouteInputContext;
20
22
  readonly res: Response;
21
23
  readonly deps: Deps;
22
- }) => Context | Promise<Context>;
24
+ }) => Context | undefined | Promise<Context | undefined>;
25
+ /** `entityType` is present only when the handler gave one: a host pinning exact arguments sees no `entityType` key otherwise. */
23
26
  readonly authorize?: (requiredArgs: {
24
27
  readonly context: Context | undefined;
25
28
  readonly deps: Deps;
26
29
  readonly permission: string;
27
- readonly entityType: string;
28
- }) => void | Promise<void>;
30
+ readonly entityType?: string;
31
+ }, optionalArgs?: JsonRouteAuthorizeScope) => void | Promise<void>;
29
32
  readonly onError?: (requiredArgs: {
30
33
  readonly res: Response;
31
34
  readonly error: unknown;
32
35
  }) => void;
36
+ /**
37
+ * Opt-in writer for a RETURNED parse or handler failure. Without it a returned `err` keeps the
38
+ * core `{ error: ServerApiError }` envelope at `statusForError` (the base pins), and it never
39
+ * reaches `onError` (a host's exception classifier must not re-map an already-classified
40
+ * failure). A host whose wire envelope is flat supplies this so a returned failure and a thrown
41
+ * refusal reach the caller in the same shape; `status` is the core default it may keep or override.
42
+ */
43
+ readonly onReturnedError?: (requiredArgs: {
44
+ readonly res: Response;
45
+ readonly error: ServerApiError;
46
+ readonly status: number;
47
+ readonly phase: 'parse' | 'handle';
48
+ }) => void;
49
+ /**
50
+ * The host's request-facts resolver (its proxy-trust answer for the client address, plus user agent
51
+ * and host). Consulted only for a spec with `requestFacts: true`; such a spec mounted without this
52
+ * port throws at mount time, so a missing resolver is never a silently absent client address.
53
+ */
54
+ readonly requestFacts?: (requiredArgs: {
55
+ readonly req: Request;
56
+ readonly deps: Deps;
57
+ }) => RouteRequestFacts;
58
+ /**
59
+ * Opt-in writer for the body-cap 413 that `allowRouteBody` answers when a spec's `maxBodyBytes` is
60
+ * exceeded (JSON and raw mounts alike). Absent, core's `payloadTooLargeError` envelope is written
61
+ * unchanged. A host whose admin client already reads its own 413 body supplies this so a route moved
62
+ * onto a spec keeps that body; the cap still runs before the workspace port and the handler.
63
+ */
64
+ readonly payloadTooLarge?: (requiredArgs: {
65
+ readonly res: Response;
66
+ readonly maxBytes: number;
67
+ }) => void;
68
+ }
69
+ export type RouteDepsSource<D> = {
70
+ readonly deps: D;
71
+ readonly depsForRequest?: never;
72
+ } | {
73
+ readonly deps?: never;
74
+ readonly depsForRequest: (required: {
75
+ readonly req: Request;
76
+ readonly res: Response;
77
+ }, _optional?: Record<string, never>) => D;
78
+ };
79
+ /** Optional mount settings shared by `mountJsonRoute` and `mountRawRoute`. */
80
+ export interface RouteMountOptions<Deps = never> {
81
+ /**
82
+ * Body parsers registered between the path and the handler of THIS route only
83
+ * (`app[method](path, ...bodyParsers, handler)`), as a hand-written route mounted its own
84
+ * `express.urlencoded`. Scoped to the one registration, never an `app.use`, so no other route sees it.
85
+ */
86
+ readonly bodyParsers?: readonly RequestHandler[];
87
+ readonly preserveHostErrorRouting?: true;
88
+ /**
89
+ * Per-request host deps: called once per request, after the spec's static `responseHeaders` and
90
+ * before every gate, with the request, the response and the mounted deps; what it returns is the
91
+ * `deps` the ports and `handle` receive for THAT request. It is how a host hands a spec facts only
92
+ * the request holds (a client address, a consent cookie, whether the socket is local) as closures
93
+ * already bound to that request, so the spec never sees `req` and stays server-framework neutral.
94
+ * Synchronous so the gates keep their tick order; a throw takes the route's error path. Absent,
95
+ * the mounted deps reach the route unchanged.
96
+ */
97
+ readonly requestDeps?: (required: {
98
+ readonly req: Request;
99
+ readonly res: Response;
100
+ readonly deps: Deps;
101
+ }) => Deps;
102
+ }
103
+ /** The request-context opt-ins and static response headers a JSON or raw spec may declare. */
104
+ export interface RouteRequestOptIns {
105
+ /** Header names handed to the route as `raw.headers` (lower-cased keys; an absent header has no key). */
106
+ readHeaders?: readonly string[];
107
+ /** Hands the host-resolved facts to the route as `raw.facts`; requires the `requestFacts` port. */
108
+ requestFacts?: true;
109
+ /** Static headers set on EVERY answer of the route, before any gate (a refusal carries them too). */
110
+ responseHeaders?: Readonly<Record<string, string>>;
111
+ /**
112
+ * Request-dependent headers, set once the workspace port admitted the request — before same-origin,
113
+ * authenticate, parse and handle — so the workspace refusal never carries them and every later answer
114
+ * (a refusal, a thrown authorization or handler failure, the success) does. `undefined` sets none.
115
+ * For a hand-written route that set a header from the query right after its workspace check
116
+ * (`?kind=document`'s `Cache-Control: private, no-store`). Absent, nothing extra is written.
117
+ */
118
+ admittedResponseHeaders?: (raw: RouteInputContext) => Readonly<Record<string, string>> | undefined;
33
119
  }
34
120
  /**
35
121
  * Declarative description of one JSON route: how to parse input, how to handle it, and whether
36
122
  * it requires a same-origin request. Consumed by `mountJsonRoute` in `adapter.ts`.
37
123
  */
38
- export interface JsonRouteSpec<Input, Output, Deps, Context = undefined> {
124
+ export interface JsonRouteSpec<Input, Output, Deps, Context = undefined> extends RouteRequestOptIns {
39
125
  method: HttpMethod;
40
126
  path: string;
41
127
  requireSameOrigin?: boolean;
128
+ /**
129
+ * Body ceiling for every method but GET/HEAD, same field as core's `JsonRouteSpec`. It can only
130
+ * tighten the host's JSON parser limit, never widen it: that parser reads the wire first.
131
+ */
132
+ maxBodyBytes?: number;
42
133
  parse: InputParser<Input>;
43
134
  handle: Handler<Input, Output, Deps, Context>;
44
135
  successStatus?: number;
45
136
  ports?: JsonRoutePorts<Deps, Context>;
46
137
  }
138
+ /**
139
+ * Declarative description of one non-JSON route (HTML, a stream, an upload, a download, a redirect
140
+ * with cookies): the same gates and host ports as a JSON spec, but `handle` receives the raw input and
141
+ * answers with a web `Response`, which `mountRawRoute` writes back. `raw.body` is whatever the host's
142
+ * per-route parser left on the request (a `Buffer` behind `express.raw`); a route that must not read an
143
+ * unauthorized body registers no parser and calls `raw.readBody(...)` after its gates instead.
144
+ */
145
+ export interface RawRouteSpec<Deps, Context = undefined> extends RouteRequestOptIns {
146
+ method: HttpMethod;
147
+ path: string;
148
+ requireSameOrigin?: boolean;
149
+ /** Body ceiling for every method but GET/HEAD, measured as in `JsonRouteSpec`. */
150
+ maxBodyBytes?: number;
151
+ ports?: JsonRoutePorts<Deps, Context>;
152
+ /**
153
+ * Opt-in: read the whole `Response` body and answer through Express's `res.send(Buffer)` instead of
154
+ * streaming it — `Content-Length`, the host's ETag and a bodiless 304 for a fresh GET/HEAD, as a
155
+ * hand-written `res.send` route answered. Absent: the body streams chunked, with no ETag and no 304.
156
+ * `'redirect'`: the same, except that a 3xx answer carrying `Location` is replayed through the host
157
+ * framework's own redirect writer, so a top-level browser redirect keeps its Accept-negotiated body and
158
+ * `Vary: Accept` (the spec still only states its intent: status, `Location`, headers, cookies).
159
+ */
160
+ bufferedReply?: true | 'redirect';
161
+ handle(requiredArgs: {
162
+ readonly raw: RawRouteInputContext;
163
+ readonly deps: Deps;
164
+ readonly context: Context | undefined;
165
+ readonly authorize: JsonRouteAuthorize;
166
+ }, optionalArgs: {
167
+ readonly signal: AbortSignal;
168
+ }): Promise<globalThis.Response>;
169
+ }
47
170
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/http-kit",
3
- "version": "0.7.3-next.2",
3
+ "version": "0.7.4",
4
4
  "description": "Generic Express transport primitives, request parsing, response serialization, origin guards and route-pack mounting.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -17,9 +17,11 @@
17
17
  "./middleware": "node",
18
18
  "./settings": "node",
19
19
  "./observability": "node",
20
+ "./request-id": "node",
20
21
  "./html-response": "node",
21
22
  "./range": "universal",
22
- "./node-bridge": "node"
23
+ "./node-bridge": "node",
24
+ "./dev-proxy": "node"
23
25
  },
24
26
  "runtime": "node"
25
27
  },
@@ -53,6 +55,11 @@
53
55
  "import": "./dist/observability.js",
54
56
  "default": "./dist/observability.js"
55
57
  },
58
+ "./request-id": {
59
+ "types": "./dist/request-id.d.ts",
60
+ "import": "./dist/request-id.js",
61
+ "default": "./dist/request-id.js"
62
+ },
56
63
  "./html-response": {
57
64
  "types": "./dist/html-response.d.ts",
58
65
  "import": "./dist/html-response.js",
@@ -67,6 +74,11 @@
67
74
  "types": "./dist/node-bridge.d.ts",
68
75
  "import": "./dist/node-bridge.js",
69
76
  "default": "./dist/node-bridge.js"
77
+ },
78
+ "./dev-proxy": {
79
+ "types": "./dist/dev-proxy.d.ts",
80
+ "import": "./dist/dev-proxy.js",
81
+ "default": "./dist/dev-proxy.js"
70
82
  }
71
83
  },
72
84
  "files": [
@@ -89,12 +101,12 @@
89
101
  "@types/express": "^4.17.21",
90
102
  "@vitest/coverage-v8": "^3.2.6",
91
103
  "express": "^4.21.0",
92
- "@jini-ai/protocol": "0.7.3-next.2",
93
- "@jini-ai/core": "0.7.3-next.2"
104
+ "@jini-ai/protocol": "0.7.4",
105
+ "@jini-ai/core": "0.7.4"
94
106
  },
95
107
  "dependencies": {
96
- "@jini-ai/core": "^0.7.3-next.2",
97
- "@jini-ai/protocol": "^0.7.3-next.2"
108
+ "@jini-ai/protocol": "^0.7.4",
109
+ "@jini-ai/core": "^0.7.4"
98
110
  },
99
111
  "scripts": {
100
112
  "build": "tsc -p tsconfig.json",