@tschk/moonshine-server 0.4.4 → 0.4.80

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 });
@@ -36,3 +36,70 @@ For an opt-in request-context build, pass the compiled server bundle's
36
36
  `requestScope` to `createRequestHandler` alongside its `modules`. Deployment and
37
37
  preview do this automatically when the manifest enables `requestContext`.
38
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.4",
3
+ "version": "0.4.80",
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.4",
19
- "@tschk/moonshine-router": "^0.4.4"
19
+ "@tschk/moonshine-framework": "^0.4.80",
20
+ "@tschk/moonshine-router": "^0.4.80"
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,3 +1,4 @@
1
+ import type { RouteDataRequests } from "@tschk/moonshine-framework/data-request";
1
2
  import type {
2
3
  MoonshineManifest,
3
4
  Renderer,
@@ -44,6 +45,7 @@ export type RequestHandlerOptions = {
44
45
  graph?: RouteGraph<RouteDefinition>;
45
46
  routes?: RouteDefinition[];
46
47
  manifest?: MoonshineManifest;
48
+ dataRequests?: RouteDataRequests;
47
49
  modules?: Record<string, RouteModule>;
48
50
  renderer?: Renderer;
49
51
  staticDir?: string;
package/src/pipeline.ts CHANGED
@@ -1,5 +1,6 @@
1
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";
@@ -94,6 +95,19 @@ function mergeHeaders(
94
95
  return headers;
95
96
  }
96
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
+
97
111
  function discardResponse(response: Response, retained?: Response): void {
98
112
  const body = response.body;
99
113
  if (!body || body === retained?.body || body.locked || response.bodyUsed)
@@ -176,6 +190,7 @@ async function runCoreAndAfters(
176
190
  chain: ModuleChainItem[],
177
191
  options: RequestHandlerOptions,
178
192
  route: RouteDefinition,
193
+ dataRequest: DataRequestPolicy | undefined,
179
194
  ): Promise<Response> {
180
195
  const method = ctx.request.method;
181
196
  const leaf = chain[chain.length - 1];
@@ -187,8 +202,28 @@ async function runCoreAndAfters(
187
202
  });
188
203
  }
189
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
+ };
190
223
  let actionResponse: Response | undefined;
191
- if (method !== "GET" && method !== "HEAD") {
224
+ let actionData: unknown = null;
225
+ const writeMethod = method !== "GET" && method !== "HEAD";
226
+ if (writeMethod) {
192
227
  // Without an action there is nothing to serve a write method. Falling
193
228
  // through would run the loaders — reachable by any verb, so a
194
229
  // CSRF-shaped POST reaches loader side effects — and answer DELETE with
@@ -200,18 +235,24 @@ async function runCoreAndAfters(
200
235
  });
201
236
  }
202
237
 
203
- const result = await callAction(leaf.module.action, ctx);
204
- if (result instanceof Response) actionResponse = result;
205
- else 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);
206
246
  if (leaf.module.loader) ctx.data.__action = result;
207
247
  else ctx.data[leaf.key] = result;
208
248
  }
209
249
  }
210
250
 
211
251
  let loaderResponse: Response | undefined;
212
- const loaderEntries = actionResponse
213
- ? []
214
- : chain.filter((c) => c.module.loader);
252
+ const loaderEntries =
253
+ actionResponse || (dataRequest && writeMethod)
254
+ ? []
255
+ : chain.filter((c) => c.module.loader);
215
256
  if (loaderEntries.length > 0) {
216
257
  ctx.signal.throwIfAborted();
217
258
  const resolvedResponses: Response[] = [];
@@ -238,9 +279,14 @@ async function runCoreAndAfters(
238
279
  throw error;
239
280
  }
240
281
  // Promise.all preserves chain order: outer loaders take response precedence.
241
- for (const { key, value } of results) {
242
- if (value instanceof Response) loaderResponse ??= value;
243
- else if (value !== undefined) ctx.data[key] = value;
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;
244
290
  }
245
291
  for (const response of resolvedResponses)
246
292
  discardResponse(response, loaderResponse);
@@ -249,10 +295,14 @@ async function runCoreAndAfters(
249
295
  if (!actionResponse) ctx.signal.throwIfAborted();
250
296
 
251
297
  let response: Response;
298
+ let envelope = false;
252
299
  if (actionResponse) {
253
300
  response = actionResponse;
254
301
  } else if (loaderResponse) {
255
302
  response = loaderResponse;
303
+ } else if (dataRequest) {
304
+ envelope = true;
305
+ response = dataRequest.encode(writeMethod ? actionData : ctx.data);
256
306
  } else if (route.mode === "api") {
257
307
  response = json(ctx.data);
258
308
  } else if (route.mode === "static" && options.staticDir) {
@@ -288,6 +338,33 @@ async function runCoreAndAfters(
288
338
  response = json(ctx.data);
289
339
  }
290
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
+
291
368
  for (let i = chain.length - 1; i >= 0; i--) {
292
369
  for (const after of chain[i].module.after ?? []) {
293
370
  const previous = response;
@@ -315,9 +392,10 @@ async function runBefores(
315
392
  chain: ModuleChainItem[],
316
393
  options: RequestHandlerOptions,
317
394
  route: RouteDefinition,
395
+ dataRequest: DataRequestPolicy | undefined,
318
396
  ): Promise<Response> {
319
397
  if (index >= befores.length) {
320
- return runCoreAndAfters(ctx, chain, options, route);
398
+ return runCoreAndAfters(ctx, chain, options, route, dataRequest);
321
399
  }
322
400
 
323
401
  const mw = befores[index]!;
@@ -332,6 +410,7 @@ async function runBefores(
332
410
  chain,
333
411
  options,
334
412
  route,
413
+ dataRequest,
335
414
  ).then(
336
415
  (response) => {
337
416
  if (settled) discardReplacedResponse(response, retained);
@@ -363,8 +442,25 @@ async function runBefores(
363
442
  }
364
443
  }
365
444
 
366
- export function createRequestHandler(
445
+ const NOT_FOUND_PATH = "/404";
446
+
447
+ /** A page's loader answered 404 without a body of its own. */
448
+ function isBareNotFound(
449
+ response: Response,
450
+ route: RouteDefinition,
451
+ dataRequest: unknown,
452
+ ): boolean {
453
+ return (
454
+ response.status === 404 &&
455
+ response.body === null &&
456
+ !dataRequest &&
457
+ (route as Partial<RouteArtifact>).mode !== "api"
458
+ );
459
+ }
460
+
461
+ export function createPipelineHandler(
367
462
  options: RequestHandlerOptions,
463
+ policy?: DataRequestPolicy,
368
464
  ): (request: Request) => Promise<Response> {
369
465
  if (
370
466
  options.manifest?.requestContext &&
@@ -378,12 +474,55 @@ export function createRequestHandler(
378
474
  // per handler instead of once per request.
379
475
  let cachedGraph = options.graph;
380
476
 
477
+ /**
478
+ * Like Waku's `404.tsx` and Next.js's `pages/404`, a page route at /404
479
+ * renders unmatched GET and HEAD requests, and page requests whose loader
480
+ * answers a bodiless 404 (Next.js's `notFound()`), with status 404 and the
481
+ * page's own headers. An explicit `notFound` option takes precedence.
482
+ */
483
+ const notFoundPage = async (
484
+ request: Request,
485
+ ): Promise<Response | undefined> => {
486
+ const { method } = request;
487
+ const url = new URL(request.url);
488
+ if (
489
+ options.notFound ||
490
+ (method !== "GET" && method !== "HEAD") ||
491
+ (url.pathname.replace(/\/+$/, "") || "/") === NOT_FOUND_PATH
492
+ )
493
+ return undefined;
494
+ const graph = cachedGraph;
495
+ const page = graph ? matchRoutes(graph, NOT_FOUND_PATH) : undefined;
496
+ if (
497
+ !page ||
498
+ page.route.path !== NOT_FOUND_PATH ||
499
+ (page.route as Partial<RouteArtifact>).mode === "api"
500
+ )
501
+ return undefined;
502
+ const response = await handler(
503
+ new Request(new URL(NOT_FOUND_PATH, url), {
504
+ method,
505
+ headers: request.headers,
506
+ signal: request.signal,
507
+ }),
508
+ );
509
+ if (response.status === 200)
510
+ return new Response(response.body, {
511
+ status: 404,
512
+ headers: response.headers,
513
+ });
514
+ await response.body?.cancel();
515
+ return undefined;
516
+ };
517
+
381
518
  const handler = async (request: Request): Promise<Response> => {
382
519
  const url = new URL(request.url);
383
520
  const pathname = url.pathname.replace(/\/+$/, "") || "/";
384
521
  const method = request.method;
522
+ const dataRequest = policy?.matches(request) ? policy : undefined;
385
523
 
386
524
  if (
525
+ !dataRequest &&
387
526
  options.staticDir &&
388
527
  (method === "GET" || method === "HEAD") &&
389
528
  pathname !== "/"
@@ -412,6 +551,8 @@ export function createRequestHandler(
412
551
 
413
552
  const match = matchRoutes(graph, pathname);
414
553
  if (!match) {
554
+ const page = dataRequest ? undefined : await notFoundPage(request);
555
+ if (page) return page;
415
556
  const ctx = createRouteContext(request, {});
416
557
  return finalizeResponse(
417
558
  options.notFound
@@ -430,7 +571,19 @@ export function createRequestHandler(
430
571
  try {
431
572
  const befores: Middleware[] = [];
432
573
  for (const c of chain) befores.push(...(c.module.before ?? []));
433
- const response = await runBefores(ctx, 0, befores, chain, options, route);
574
+ const response = await runBefores(
575
+ ctx,
576
+ 0,
577
+ befores,
578
+ chain,
579
+ options,
580
+ route,
581
+ dataRequest,
582
+ );
583
+ const page = isBareNotFound(response, route, dataRequest)
584
+ ? await notFoundPage(request)
585
+ : undefined;
586
+ if (page) return page;
434
587
  return finalizeResponse(response, baseHeaders, method);
435
588
  } catch (error) {
436
589
  if (error instanceof Redirect) {
@@ -467,6 +620,10 @@ export function createRequestHandler(
467
620
  }
468
621
 
469
622
  if (error instanceof Response) {
623
+ const page = isBareNotFound(error, route, dataRequest)
624
+ ? await notFoundPage(request)
625
+ : undefined;
626
+ if (page) return page;
470
627
  return finalizeResponse(error, baseHeaders, method);
471
628
  }
472
629
 
@@ -478,7 +635,36 @@ export function createRequestHandler(
478
635
  }
479
636
  };
480
637
  const requestScope = options.requestScope;
481
- return requestScope
482
- ? (request) => requestScope(request, () => handler(request))
638
+ const scoped = requestScope
639
+ ? (request: Request) => {
640
+ const responseHeaders = new Headers();
641
+ return requestScope(
642
+ request,
643
+ async () => {
644
+ const response = await handler(request);
645
+ return responseHeaders.keys().next().done
646
+ ? response
647
+ : finalizeResponse(response, responseHeaders, request.method);
648
+ },
649
+ responseHeaders,
650
+ );
651
+ }
483
652
  : handler;
653
+ return scoped;
654
+ }
655
+
656
+ /** Private extension seam: wire protocols stay outside the ordinary server entry. */
657
+ export type DataRequestPolicy = {
658
+ matches(request: Request): boolean;
659
+ encode(data: unknown): Response;
660
+ finalize(response: Response): Response;
661
+ };
662
+
663
+ export function createRequestHandler(options: RequestHandlerOptions) {
664
+ if (options.dataRequests ?? options.manifest?.dataRequests) {
665
+ throw new Error(
666
+ "Route-data requests require @tschk/moonshine-server/data-http",
667
+ );
668
+ }
669
+ return createPipelineHandler(options);
484
670
  }