@tschk/moonshine-server 0.4.1 → 0.4.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ const fetch = createRequestHandler({
10
10
  manifest,
11
11
  modules,
12
12
  renderer: reactRenderer,
13
- staticDir: "./.moonshine",
13
+ staticDir: "./.moonshine/public",
14
14
  });
15
15
 
16
16
  Bun.serve({ fetch });
@@ -25,5 +25,81 @@ Features:
25
25
  - `serializeData` escapes HTML-sensitive characters and rejects cycles.
26
26
  - `resolveStaticPath` / `tryServeStatic` for static file serving.
27
27
 
28
+ Ordinary headers use the last source value. `Set-Cookie` fields accumulate
29
+ separately across default, layout, route and response headers, including HEAD
30
+ responses; provide repeated cookies as a `Headers` instance or header tuples.
31
+
28
32
  See [docs/ROUTING.md](../../docs/ROUTING.md) and
29
33
  [DESIGN.md](../../DESIGN.md).
34
+
35
+ For an opt-in request-context build, pass the compiled server bundle's
36
+ `requestScope` to `createRequestHandler` alongside its `modules`. Deployment and
37
+ preview do this automatically when the manifest enables `requestContext`.
38
+ The server package itself does not import AsyncLocalStorage.
39
+
40
+ With an opt-in request scope, `getResponseHeaders()` from
41
+ `@tschk/moonshine-framework/request` returns the request's mutable response-header
42
+ sink. The pipeline merges it into completed responses, including redirects,
43
+ errors, not-found and HEAD responses. Explicit response headers win for ordinary
44
+ fields; `Set-Cookie` fields append separately. Without a supplied sink the helper
45
+ returns `undefined`. Custom scope wrappers must forward the optional third
46
+ `responseHeaders` argument to `runWithRequest`. The signal-only root is unchanged.
47
+
48
+ Loader/action results implementing the framework `RouteData` contract retain
49
+ payload identity while carrying rendered response status and headers. The
50
+ React Router adapter's `data()` produces this contract. Layout-to-page loader
51
+ metadata merges in route order, with explicit action metadata taking precedence;
52
+ `after` middleware sees the resulting response and can replace it. Statuses 204,
53
+ 205 and 304 discard rendered bodies. Direct or thrown `Response` values keep
54
+ precedence, and throwing a data wrapper is unsupported. Ordinary objects are
55
+ unchanged; `type: "DataWithResponseInit"` together with own `data` and an `init`
56
+ object is reserved for this contract.
57
+
58
+ ## Opt-in route-data responses
59
+
60
+ Add `dataRequests: true` to your existing Bun/Node `moonshine.config.ts`, or pass
61
+ it to `createRequestHandler` from `@tschk/moonshine-server/data-http` in a
62
+ hand-written server. The ordinary server entry rejects enabled data requests;
63
+ its bundle omits the HTTP protocol implementation. The generated manifest carries this option into
64
+ Bun/Node deployment and preview handlers. Other build targets currently reject
65
+ it. For a TLS proxy, configure the expected public origin explicitly:
66
+
67
+ ```ts
68
+ export default {
69
+ dataRequests: { origin: "https://app.example" },
70
+ };
71
+ ```
72
+
73
+ `true` checks against the request URL's origin. The object form checks against
74
+ its validated public origin; forwarding headers do not select the trusted origin.
75
+ Neither form rewrites the request URL. Requests with a mismatched/malformed
76
+ `Origin`, or cross-site/same-site fetch metadata without an origin, reject before
77
+ request scope, middleware or route callbacks run. Nonbrowser requests without
78
+ those headers remain supported. Existing document/API/webhook requests retain
79
+ their ordinary behavior.
80
+
81
+ This checks browser request origin, not user authorization or accepted server
82
+ hostnames. Deployments must validate their accepted Host values; use application
83
+ authentication before returning private loader data.
84
+
85
+ The opt-in request header is `x-moonshine-data: 1`:
86
+
87
+ | Method | Protocol response |
88
+ | --------------------------- | -------------------------------------------------------------------------------------------------------------- |
89
+ | GET / HEAD | Existing parallel loaders; `{ data: context.data }`; no page renderer. HEAD has no body. |
90
+ | POST / PUT / PATCH / DELETE | Leaf action only; `{ data: actionResult }`; no loaders. A client data router reloads separately after success. |
91
+
92
+ Core envelopes carry the version header and `application/json`. Values use plain
93
+ JSON semantics; an undefined action result becomes `null`. Loader/action metadata,
94
+ cookies, after middleware and request scope retain their response behavior.
95
+ Statuses 204/205 have no body and decode as `null` in the native client. Direct or
96
+ thrown `Response` values, redirects and error boundaries remain native HTTP.
97
+ Return JSON-compatible values to use the protocol. The entire loader-data map is
98
+ client-visible when requested, so keep private server values out of its results.
99
+
100
+ Enabled handlers add `Vary: x-moonshine-data` to both document and data responses,
101
+ preserving existing tokens and wildcard values. Protocol requests bypass static
102
+ HTML shortcuts; cache policy remains application-owned. Normal requests without
103
+ the exact protocol header keep their existing rendering and action/loader flow.
104
+ The optional [HTTP client](../router/README.md#optional-http-route-data) keeps
105
+ server modules out of browser bundles.
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-server",
3
- "version": "0.4.1",
3
+ "version": "0.4.49",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "types": "./src/index.ts",
8
8
  "exports": {
9
- ".": "./src/index.ts"
9
+ ".": "./src/index.ts",
10
+ "./data-http": "./src/data-http.ts"
10
11
  },
11
12
  "scripts": {
12
13
  "format": "bunx prettier --check .",
@@ -15,8 +16,8 @@
15
16
  "test": "bun test"
16
17
  },
17
18
  "dependencies": {
18
- "@tschk/moonshine-framework": "^0.4.1",
19
- "@tschk/moonshine-router": "^0.4.1"
19
+ "@tschk/moonshine-framework": "^0.4.48",
20
+ "@tschk/moonshine-router": "^0.4.48"
20
21
  },
21
22
  "devDependencies": {
22
23
  "@types/bun": "1.3.14",
@@ -0,0 +1,105 @@
1
+ import {
2
+ normalizeRouteDataRequests,
3
+ ROUTE_DATA_HEADER,
4
+ ROUTE_DATA_VERSION,
5
+ } from "@tschk/moonshine-framework/data-request";
6
+ import type { RequestHandlerOptions } from "./data.js";
7
+ import { json } from "./errors.js";
8
+ import { createPipelineHandler } from "./pipeline.js";
9
+
10
+ /** Opt-in HTTP route-data transport over the ordinary request pipeline. */
11
+ export function createRequestHandler(options: RequestHandlerOptions) {
12
+ const configured = options.dataRequests;
13
+ const config = normalizeRouteDataRequests(
14
+ configured !== undefined ? configured : options.manifest?.dataRequests,
15
+ );
16
+ if (!config) return createPipelineHandler(options);
17
+ const publicOrigin = typeof config === "object" ? config.origin : undefined;
18
+ const handler = createPipelineHandler(options, {
19
+ matches,
20
+ encode: (data) => json({ data }),
21
+ finalize(response) {
22
+ const headers = new Headers(response.headers);
23
+ headers.set("content-type", "application/json; charset=utf-8");
24
+ headers.set(ROUTE_DATA_HEADER, ROUTE_DATA_VERSION);
25
+ return new Response(response.body, {
26
+ status: response.status,
27
+ statusText: response.statusText,
28
+ headers,
29
+ });
30
+ },
31
+ });
32
+ return async (request: Request) => {
33
+ const rejection = matches(request)
34
+ ? rejectDataRequest(request, publicOrigin)
35
+ : undefined;
36
+ // Guard before request scope or application callbacks; preserve HEAD semantics.
37
+ return withDataVary(
38
+ rejection
39
+ ? new Response(
40
+ request.method === "HEAD" ? null : rejection.body,
41
+ rejection,
42
+ )
43
+ : await handler(request),
44
+ );
45
+ };
46
+ }
47
+
48
+ function matches(request: Request): boolean {
49
+ return request.headers.get(ROUTE_DATA_HEADER) === ROUTE_DATA_VERSION;
50
+ }
51
+
52
+ const DATA_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
53
+
54
+ function rejectDataRequest(
55
+ request: Request,
56
+ publicOrigin?: string,
57
+ ): Response | undefined {
58
+ const origin = request.headers.get("origin");
59
+ if (origin !== null) {
60
+ let valid = false;
61
+ try {
62
+ const parsed = new URL(origin);
63
+ valid =
64
+ origin === parsed.origin &&
65
+ parsed.origin === (publicOrigin ?? new URL(request.url).origin);
66
+ } catch {
67
+ valid = false;
68
+ }
69
+ if (!valid) return new Response("Forbidden", { status: 403 });
70
+ } else {
71
+ const site = request.headers.get("sec-fetch-site");
72
+ if (site === "cross-site" || site === "same-site") {
73
+ return new Response("Forbidden", { status: 403 });
74
+ }
75
+ }
76
+ if (!DATA_METHODS.has(request.method)) {
77
+ return new Response(null, {
78
+ status: 405,
79
+ headers: { allow: "GET, HEAD, POST, PUT, PATCH, DELETE" },
80
+ });
81
+ }
82
+ return undefined;
83
+ }
84
+
85
+ function withDataVary(response: Response): Response {
86
+ const current = response.headers.get("vary");
87
+ if (current !== null) {
88
+ const tokens = current
89
+ .split(",")
90
+ .map((token) => token.trim().toLowerCase());
91
+ if (tokens.includes("*") || tokens.includes(ROUTE_DATA_HEADER)) {
92
+ return response;
93
+ }
94
+ }
95
+ const headers = new Headers(response.headers);
96
+ headers.set(
97
+ "vary",
98
+ current ? `${current}, ${ROUTE_DATA_HEADER}` : ROUTE_DATA_HEADER,
99
+ );
100
+ return new Response(response.body, {
101
+ status: response.status,
102
+ statusText: response.statusText,
103
+ headers,
104
+ });
105
+ }
package/src/data.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import type { RouteDataRequests } from "@tschk/moonshine-framework/data-request";
1
2
  import type {
2
3
  MoonshineManifest,
3
4
  Renderer,
5
+ RequestScope,
4
6
  RouteDefinition,
5
7
  } from "@tschk/moonshine-framework";
6
- import type { RouteGraph } from "@tschk/moonshine-router";
8
+ import type { RouteGraph } from "@tschk/moonshine-router/graph";
7
9
 
8
10
  export type RouteContext = {
9
11
  request: Request;
@@ -29,6 +31,7 @@ export type ErrorBoundary = (
29
31
  ) => Response | Promise<Response>;
30
32
 
31
33
  export type RouteModule = {
34
+ methods?: readonly string[];
32
35
  before?: Middleware[];
33
36
  after?: Middleware[];
34
37
  loader?: Loader;
@@ -38,9 +41,11 @@ export type RouteModule = {
38
41
  };
39
42
 
40
43
  export type RequestHandlerOptions = {
44
+ requestScope?: RequestScope;
41
45
  graph?: RouteGraph<RouteDefinition>;
42
46
  routes?: RouteDefinition[];
43
47
  manifest?: MoonshineManifest;
48
+ dataRequests?: RouteDataRequests;
44
49
  modules?: Record<string, RouteModule>;
45
50
  renderer?: Renderer;
46
51
  staticDir?: string;
@@ -57,7 +62,7 @@ export function createRouteContext(
57
62
  request,
58
63
  params,
59
64
  signal: request.signal,
60
- data: {},
65
+ data: Object.create(null),
61
66
  };
62
67
  }
63
68
 
package/src/pipeline.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { createRouteGraph, matchRoutes } from "@tschk/moonshine-router";
1
+ import { createRouteGraph, matchRoutes } from "@tschk/moonshine-router/graph";
2
2
  import type {
3
+ RouteData,
3
4
  RouteArtifact,
4
5
  RouteDefinition,
5
6
  } from "@tschk/moonshine-framework";
@@ -25,6 +26,7 @@ function hasControlChars(value: string): boolean {
25
26
  function isSafeRedirect(location: string, request: Request): boolean {
26
27
  try {
27
28
  if (hasControlChars(location)) return false;
29
+ if (location.startsWith("//") || location.includes("\\")) return false;
28
30
  const base = new URL(request.url);
29
31
  const url = new URL(location, request.url);
30
32
  return url.origin === base.origin;
@@ -45,12 +47,12 @@ function buildModuleChain(
45
47
  const chain: ModuleChainItem[] = [];
46
48
 
47
49
  for (const key of route.layouts ?? []) {
48
- const module = modules[key];
50
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
49
51
  if (module) chain.push({ key, module });
50
52
  }
51
53
 
52
54
  for (const key of route.middleware ?? []) {
53
- const module = modules[key];
55
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
54
56
  if (module) chain.push({ key, module });
55
57
  }
56
58
 
@@ -61,7 +63,7 @@ function buildModuleChain(
61
63
  ];
62
64
 
63
65
  for (const key of leafKeys) {
64
- const module = modules[key];
66
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
65
67
  if (module) {
66
68
  chain.push({ key, module });
67
69
  break;
@@ -79,38 +81,63 @@ function mergeHeaders(
79
81
  for (const source of sources) {
80
82
  if (!source) continue;
81
83
 
82
- if (source instanceof Headers) {
83
- for (const [key, value] of source.entries()) {
84
- headers.set(key, value);
85
- }
86
- } else if (Array.isArray(source)) {
87
- for (const [key, value] of source) {
88
- headers.set(key, value);
89
- }
90
- } else {
91
- for (const [key, value] of Object.entries(
92
- source as Record<string, string>,
93
- )) {
94
- headers.set(key, value);
95
- }
84
+ const entries =
85
+ source instanceof Headers || Array.isArray(source)
86
+ ? source
87
+ : Object.entries(source);
88
+ for (const [key, value] of entries) {
89
+ // Cookies are separate response fields; joining or replacing loses sessions.
90
+ if (key.toLowerCase() === "set-cookie") headers.append(key, value);
91
+ else headers.set(key, value);
96
92
  }
97
93
  }
98
94
 
99
95
  return headers;
100
96
  }
101
97
 
98
+ function isRouteData(value: unknown): value is RouteData {
99
+ return (
100
+ typeof value === "object" &&
101
+ value !== null &&
102
+ "type" in value &&
103
+ value.type === "DataWithResponseInit" &&
104
+ Object.hasOwn(value, "data") &&
105
+ "init" in value &&
106
+ typeof value.init === "object" &&
107
+ value.init !== null
108
+ );
109
+ }
110
+
111
+ function discardResponse(response: Response, retained?: Response): void {
112
+ const body = response.body;
113
+ if (!body || body === retained?.body || body.locked || response.bodyUsed)
114
+ return;
115
+ try {
116
+ void body.cancel().catch(() => {});
117
+ } catch {
118
+ // Discarding an unused body must not replace the selected response/error.
119
+ }
120
+ }
121
+
122
+ function discardReplacedResponse(
123
+ response: Response,
124
+ retained?: Response,
125
+ ): void {
126
+ // shortcut: a returned stream may consume this body later; stronger cleanup needs explicit ownership.
127
+ if (retained?.body) return;
128
+ discardResponse(response, retained);
129
+ }
130
+
102
131
  function finalizeResponse(
103
132
  response: Response,
104
133
  baseHeaders?: HeadersInit,
105
134
  method?: string,
106
135
  ): Response {
107
- const headers = new Headers(baseHeaders);
108
- for (const [key, value] of response.headers.entries()) {
109
- headers.set(key, value);
110
- }
136
+ const headers = mergeHeaders(baseHeaders, response.headers);
111
137
  // HEAD must carry the GET headers and no body; shipping one is a protocol
112
138
  // violation and mismatches Content-Length on runtimes that do not strip it.
113
139
  const body = method === "HEAD" ? null : response.body;
140
+ if (method === "HEAD") discardResponse(response);
114
141
  return new Response(body, {
115
142
  status: response.status,
116
143
  statusText: response.statusText,
@@ -128,7 +155,9 @@ function findErrorBoundary(
128
155
  }
129
156
 
130
157
  if (route.errorBoundary) {
131
- const module = modules[route.errorBoundary];
158
+ const module = Object.hasOwn(modules, route.errorBoundary)
159
+ ? modules[route.errorBoundary]
160
+ : undefined;
132
161
  if (module?.errorBoundary) return module.errorBoundary;
133
162
  }
134
163
 
@@ -150,6 +179,7 @@ function resolveBaseHeaders(
150
179
  // Derived from the leaf, never hardcoded: an Allow header that lists methods
151
180
  // the route cannot serve sends clients down paths that will 405 again.
152
181
  function allowedMethods(leaf: ModuleChainItem | undefined): string {
182
+ if (leaf?.module.methods) return leaf.module.methods.join(", ");
153
183
  const methods = ["GET", "HEAD"];
154
184
  if (leaf?.module.action) methods.push("POST", "PUT", "PATCH", "DELETE");
155
185
  return methods.join(", ");
@@ -160,11 +190,40 @@ async function runCoreAndAfters(
160
190
  chain: ModuleChainItem[],
161
191
  options: RequestHandlerOptions,
162
192
  route: RouteDefinition,
193
+ dataRequest: DataRequestPolicy | undefined,
163
194
  ): Promise<Response> {
164
195
  const method = ctx.request.method;
165
196
  const leaf = chain[chain.length - 1];
166
197
 
167
- if (method !== "GET" && method !== "HEAD") {
198
+ if (leaf?.module.methods && !leaf.module.methods.includes(method)) {
199
+ return new Response(null, {
200
+ status: 405,
201
+ headers: { allow: allowedMethods(leaf) },
202
+ });
203
+ }
204
+
205
+ const dataHeaders = new Headers();
206
+ let dataStatus: number | undefined;
207
+ let dataStatusText: string | undefined;
208
+ let actionInit: ResponseInit | undefined;
209
+ const unpack = (value: unknown, applyInit = true) => {
210
+ if (!isRouteData(value)) return value;
211
+ const init = value.init;
212
+ // Validate metadata before rendering and use the platform's header rules.
213
+ const metadata = new Response(null, init);
214
+ if (!applyInit) return value.data;
215
+ for (const [key, header] of metadata.headers) {
216
+ if (key.toLowerCase() === "set-cookie") dataHeaders.append(key, header);
217
+ else dataHeaders.set(key, header);
218
+ }
219
+ if (init.status !== undefined) dataStatus = metadata.status;
220
+ if (init.statusText !== undefined) dataStatusText = metadata.statusText;
221
+ return value.data;
222
+ };
223
+ let actionResponse: Response | undefined;
224
+ let actionData: unknown = null;
225
+ const writeMethod = method !== "GET" && method !== "HEAD";
226
+ if (writeMethod) {
168
227
  // Without an action there is nothing to serve a write method. Falling
169
228
  // through would run the loaders — reachable by any verb, so a
170
229
  // CSRF-shaped POST reaches loader side effects — and answer DELETE with
@@ -176,40 +235,83 @@ async function runCoreAndAfters(
176
235
  });
177
236
  }
178
237
 
179
- const result = await callAction(leaf.module.action, ctx);
180
- if (result instanceof Response) return result;
181
- if (result !== undefined) {
238
+ ctx.signal.throwIfAborted();
239
+ const actionResult = await callAction(leaf.module.action, ctx);
240
+ if (isRouteData(actionResult)) actionInit = actionResult.init;
241
+ if (actionResult instanceof Response) actionResponse = actionResult;
242
+ else if (dataRequest) {
243
+ actionData = unpack(actionResult, false) ?? null;
244
+ } else if (actionResult !== undefined) {
245
+ const result = unpack(actionResult, false);
182
246
  if (leaf.module.loader) ctx.data.__action = result;
183
247
  else ctx.data[leaf.key] = result;
184
248
  }
185
249
  }
186
250
 
187
- const loaderEntries = chain.filter((c) => c.module.loader);
251
+ let loaderResponse: Response | undefined;
252
+ const loaderEntries =
253
+ actionResponse || (dataRequest && writeMethod)
254
+ ? []
255
+ : chain.filter((c) => c.module.loader);
188
256
  if (loaderEntries.length > 0) {
189
257
  ctx.signal.throwIfAborted();
190
- const results = await Promise.all(
191
- loaderEntries.map(async (c) => {
192
- const value = await callLoader(c.module.loader!, ctx);
193
- return { key: c.key, value };
194
- }),
195
- );
196
- for (const { key, value } of results) {
197
- if (value !== undefined) ctx.data[key] = value;
258
+ const resolvedResponses: Response[] = [];
259
+ let failed = false;
260
+ let failureResponse: Response | undefined;
261
+ let results: Array<{ key: string; value: unknown }>;
262
+ try {
263
+ results = await Promise.all(
264
+ loaderEntries.map(async (c) => {
265
+ const value = await callLoader(c.module.loader!, ctx);
266
+ if (value instanceof Response) {
267
+ if (failed) discardResponse(value, failureResponse);
268
+ else resolvedResponses.push(value);
269
+ }
270
+ return { key: c.key, value };
271
+ }),
272
+ );
273
+ ctx.signal.throwIfAborted();
274
+ } catch (error) {
275
+ failed = true;
276
+ failureResponse = error instanceof Response ? error : undefined;
277
+ for (const response of resolvedResponses)
278
+ discardResponse(response, failureResponse);
279
+ throw error;
198
280
  }
281
+ // Promise.all preserves chain order: outer loaders take response precedence.
282
+ try {
283
+ for (const { key, value } of results) {
284
+ if (value instanceof Response) loaderResponse ??= value;
285
+ else if (value !== undefined) ctx.data[key] = unpack(value);
286
+ }
287
+ } catch (error) {
288
+ for (const response of resolvedResponses) discardResponse(response);
289
+ throw error;
290
+ }
291
+ for (const response of resolvedResponses)
292
+ discardResponse(response, loaderResponse);
199
293
  }
200
294
 
201
- ctx.signal.throwIfAborted();
295
+ if (!actionResponse) ctx.signal.throwIfAborted();
202
296
 
203
297
  let response: Response;
204
- if (route.mode === "api") {
205
- const leafData = leaf ? ctx.data[leaf.key] : undefined;
206
- response = leafData instanceof Response ? leafData : json(ctx.data);
298
+ let envelope = false;
299
+ if (actionResponse) {
300
+ response = actionResponse;
301
+ } else if (loaderResponse) {
302
+ response = loaderResponse;
303
+ } else if (dataRequest) {
304
+ envelope = true;
305
+ response = dataRequest.encode(writeMethod ? actionData : ctx.data);
306
+ } else if (route.mode === "api") {
307
+ response = json(ctx.data);
207
308
  } else if (route.mode === "static" && options.staticDir) {
208
309
  const pathname = new URL(ctx.request.url).pathname;
209
310
  const staticRes = await tryServeStatic(
210
311
  options.staticDir,
211
312
  pathname,
212
313
  options.defaultMeta?.headers,
314
+ method,
213
315
  );
214
316
  if (staticRes) {
215
317
  response = staticRes;
@@ -236,46 +338,134 @@ async function runCoreAndAfters(
236
338
  response = json(ctx.data);
237
339
  }
238
340
 
341
+ if (
342
+ !actionResponse &&
343
+ !loaderResponse &&
344
+ (actionInit !== undefined ||
345
+ dataStatus !== undefined ||
346
+ dataStatusText !== undefined ||
347
+ !dataHeaders.keys().next().done)
348
+ ) {
349
+ const status = actionInit?.status ?? dataStatus ?? response.status;
350
+ const statusText =
351
+ actionInit?.statusText ?? dataStatusText ?? response.statusText;
352
+ const headers = mergeHeaders(
353
+ response.headers,
354
+ dataHeaders,
355
+ actionInit?.headers,
356
+ );
357
+ const bodyless = status === 204 || status === 205 || status === 304;
358
+ if (bodyless) discardResponse(response);
359
+ response = new Response(bodyless ? null : response.body, {
360
+ status,
361
+ statusText,
362
+ headers,
363
+ });
364
+ }
365
+
366
+ if (envelope && dataRequest) response = dataRequest.finalize(response);
367
+
239
368
  for (let i = chain.length - 1; i >= 0; i--) {
240
369
  for (const after of chain[i].module.after ?? []) {
241
- const next = async () => response;
242
- response = await after(ctx, next);
370
+ const previous = response;
371
+ const next = async () => previous;
372
+ try {
373
+ response = await after(ctx, next);
374
+ } catch (error) {
375
+ discardReplacedResponse(
376
+ previous,
377
+ error instanceof Response ? error : undefined,
378
+ );
379
+ throw error;
380
+ }
381
+ discardReplacedResponse(previous, response);
243
382
  }
244
383
  }
245
384
 
246
385
  return response;
247
386
  }
248
387
 
249
- function runBefores(
388
+ async function runBefores(
250
389
  ctx: RouteContext,
251
390
  index: number,
252
391
  befores: Middleware[],
253
392
  chain: ModuleChainItem[],
254
393
  options: RequestHandlerOptions,
255
394
  route: RouteDefinition,
395
+ dataRequest: DataRequestPolicy | undefined,
256
396
  ): Promise<Response> {
257
397
  if (index >= befores.length) {
258
- return runCoreAndAfters(ctx, chain, options, route);
398
+ return runCoreAndAfters(ctx, chain, options, route, dataRequest);
259
399
  }
260
400
 
261
401
  const mw = befores[index]!;
262
- const next = () => runBefores(ctx, index + 1, befores, chain, options, route);
263
- return mw(ctx, next);
402
+ const delivered: Response[] = [];
403
+ let settled = false;
404
+ let retained: Response | undefined;
405
+ const next = () => {
406
+ const pending = runBefores(
407
+ ctx,
408
+ index + 1,
409
+ befores,
410
+ chain,
411
+ options,
412
+ route,
413
+ dataRequest,
414
+ ).then(
415
+ (response) => {
416
+ if (settled) discardReplacedResponse(response, retained);
417
+ else delivered.push(response);
418
+ return response;
419
+ },
420
+ (error) => {
421
+ if (error instanceof Response) {
422
+ if (settled) discardReplacedResponse(error, retained);
423
+ else delivered.push(error);
424
+ }
425
+ throw error;
426
+ },
427
+ );
428
+ // A middleware may return before its next() settles; still observe rejection.
429
+ void pending.catch(() => {});
430
+ return pending;
431
+ };
432
+ try {
433
+ retained = await mw(ctx, next);
434
+ return retained;
435
+ } catch (error) {
436
+ retained = error instanceof Response ? error : undefined;
437
+ throw error;
438
+ } finally {
439
+ settled = true;
440
+ for (const response of delivered)
441
+ discardReplacedResponse(response, retained);
442
+ }
264
443
  }
265
444
 
266
- export function createRequestHandler(
445
+ export function createPipelineHandler(
267
446
  options: RequestHandlerOptions,
447
+ policy?: DataRequestPolicy,
268
448
  ): (request: Request) => Promise<Response> {
449
+ if (
450
+ options.manifest?.requestContext &&
451
+ typeof options.requestScope !== "function"
452
+ ) {
453
+ throw new Error(
454
+ "Request-context manifests require their bundled requestScope",
455
+ );
456
+ }
269
457
  // Compiling the route graph is linear in the route count, so build it once
270
458
  // per handler instead of once per request.
271
459
  let cachedGraph = options.graph;
272
460
 
273
- return async (request) => {
461
+ const handler = async (request: Request): Promise<Response> => {
274
462
  const url = new URL(request.url);
275
463
  const pathname = url.pathname.replace(/\/+$/, "") || "/";
276
464
  const method = request.method;
465
+ const dataRequest = policy?.matches(request) ? policy : undefined;
277
466
 
278
467
  if (
468
+ !dataRequest &&
279
469
  options.staticDir &&
280
470
  (method === "GET" || method === "HEAD") &&
281
471
  pathname !== "/"
@@ -284,6 +474,7 @@ export function createRequestHandler(
284
474
  options.staticDir,
285
475
  pathname,
286
476
  options.defaultMeta?.headers,
477
+ method,
287
478
  );
288
479
  if (staticRes) return staticRes;
289
480
  }
@@ -294,15 +485,23 @@ export function createRequestHandler(
294
485
  ? createRouteGraph(options.manifest.routes)
295
486
  : undefined);
296
487
  if (!graph) {
297
- return new Response("No route graph configured", { status: 500 });
488
+ return finalizeResponse(
489
+ new Response("No route graph configured", { status: 500 }),
490
+ options.defaultMeta?.headers,
491
+ method,
492
+ );
298
493
  }
299
494
 
300
495
  const match = matchRoutes(graph, pathname);
301
496
  if (!match) {
302
497
  const ctx = createRouteContext(request, {});
303
- return options.notFound
304
- ? await options.notFound(ctx)
305
- : new Response("Not Found", { status: 404 });
498
+ return finalizeResponse(
499
+ options.notFound
500
+ ? await options.notFound(ctx)
501
+ : new Response("Not Found", { status: 404 }),
502
+ options.defaultMeta?.headers,
503
+ method,
504
+ );
306
505
  }
307
506
 
308
507
  const route = match.route;
@@ -313,15 +512,27 @@ export function createRequestHandler(
313
512
  try {
314
513
  const befores: Middleware[] = [];
315
514
  for (const c of chain) befores.push(...(c.module.before ?? []));
316
- const response = await runBefores(ctx, 0, befores, chain, options, route);
515
+ const response = await runBefores(
516
+ ctx,
517
+ 0,
518
+ befores,
519
+ chain,
520
+ options,
521
+ route,
522
+ dataRequest,
523
+ );
317
524
  return finalizeResponse(response, baseHeaders, method);
318
525
  } catch (error) {
319
526
  if (error instanceof Redirect) {
320
527
  if (!isSafeRedirect(error.location, request)) {
321
- return new Response("Invalid redirect", {
322
- status: 400,
323
- headers: baseHeaders,
324
- });
528
+ return finalizeResponse(
529
+ new Response("Invalid redirect", {
530
+ status: 400,
531
+ headers: baseHeaders,
532
+ }),
533
+ undefined,
534
+ method,
535
+ );
325
536
  }
326
537
  const headers = new Headers(baseHeaders);
327
538
  headers.set("location", error.location);
@@ -330,7 +541,18 @@ export function createRequestHandler(
330
541
 
331
542
  const boundary = findErrorBoundary(chain, route, options.modules ?? {});
332
543
  if (boundary) {
333
- const res = await boundary(ctx, error);
544
+ let res: Response;
545
+ try {
546
+ res = await boundary(ctx, error);
547
+ } catch (boundaryError) {
548
+ if (error instanceof Response)
549
+ discardReplacedResponse(
550
+ error,
551
+ boundaryError instanceof Response ? boundaryError : undefined,
552
+ );
553
+ throw boundaryError;
554
+ }
555
+ if (error instanceof Response) discardReplacedResponse(error, res);
334
556
  return finalizeResponse(res, baseHeaders, method);
335
557
  }
336
558
 
@@ -345,4 +567,37 @@ export function createRequestHandler(
345
567
  );
346
568
  }
347
569
  };
570
+ const requestScope = options.requestScope;
571
+ const scoped = requestScope
572
+ ? (request: Request) => {
573
+ const responseHeaders = new Headers();
574
+ return requestScope(
575
+ request,
576
+ async () => {
577
+ const response = await handler(request);
578
+ return responseHeaders.keys().next().done
579
+ ? response
580
+ : finalizeResponse(response, responseHeaders, request.method);
581
+ },
582
+ responseHeaders,
583
+ );
584
+ }
585
+ : handler;
586
+ return scoped;
587
+ }
588
+
589
+ /** Private extension seam: wire protocols stay outside the ordinary server entry. */
590
+ export type DataRequestPolicy = {
591
+ matches(request: Request): boolean;
592
+ encode(data: unknown): Response;
593
+ finalize(response: Response): Response;
594
+ };
595
+
596
+ export function createRequestHandler(options: RequestHandlerOptions) {
597
+ if (options.dataRequests ?? options.manifest?.dataRequests) {
598
+ throw new Error(
599
+ "Route-data requests require @tschk/moonshine-server/data-http",
600
+ );
601
+ }
602
+ return createPipelineHandler(options);
348
603
  }
package/src/static.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { realpathSync } from "node:fs";
1
+ import { createReadStream, realpathSync } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+ import { Readable } from "node:stream";
2
4
  import { join, normalize, resolve, sep } from "node:path";
3
5
 
4
6
  function decodeSegment(part: string): string | null {
@@ -103,10 +105,33 @@ export async function tryServeStatic(
103
105
  staticDir: string,
104
106
  pathname: string,
105
107
  customHeaders?: HeadersInit,
108
+ method = "GET",
106
109
  ): Promise<Response | null> {
107
- if (typeof Bun === "undefined") return null;
110
+ if (method !== "GET" && method !== "HEAD") return null;
108
111
  const filePath = resolveStaticPath(staticDir, pathname);
109
112
  if (!filePath) return null;
113
+ if (typeof Bun === "undefined") {
114
+ let info;
115
+ try {
116
+ info = await stat(filePath);
117
+ if (!info.isFile() || !isContained(staticDir, filePath)) return null;
118
+ } catch {
119
+ return null;
120
+ }
121
+ const headers = staticFileHeaders(
122
+ MIME[extOf(filePath)] ?? "application/octet-stream",
123
+ customHeaders,
124
+ );
125
+ headers.set("content-length", String(info.size));
126
+ return new Response(
127
+ method === "HEAD"
128
+ ? null
129
+ : (Readable.toWeb(
130
+ createReadStream(filePath),
131
+ ) as unknown as ReadableStream),
132
+ { headers },
133
+ );
134
+ }
110
135
  const file = Bun.file(filePath);
111
136
  if (!(await file.exists())) return null;
112
137
  try {
@@ -117,7 +142,7 @@ export async function tryServeStatic(
117
142
  const type =
118
143
  MIME[extOf(filePath)] ?? (file.type || "application/octet-stream");
119
144
 
120
- return new Response(file, {
121
- headers: staticFileHeaders(type, customHeaders),
122
- });
145
+ const headers = staticFileHeaders(type, customHeaders);
146
+ headers.set("content-length", String(file.size));
147
+ return new Response(method === "HEAD" ? null : file, { headers });
123
148
  }