@tschk/moonshine-server 0.4.4 → 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 });
@@ -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.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.4",
19
- "@tschk/moonshine-router": "^0.4.4"
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,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,9 @@ async function runBefores(
363
442
  }
364
443
  }
365
444
 
366
- export function createRequestHandler(
445
+ export function createPipelineHandler(
367
446
  options: RequestHandlerOptions,
447
+ policy?: DataRequestPolicy,
368
448
  ): (request: Request) => Promise<Response> {
369
449
  if (
370
450
  options.manifest?.requestContext &&
@@ -382,8 +462,10 @@ export function createRequestHandler(
382
462
  const url = new URL(request.url);
383
463
  const pathname = url.pathname.replace(/\/+$/, "") || "/";
384
464
  const method = request.method;
465
+ const dataRequest = policy?.matches(request) ? policy : undefined;
385
466
 
386
467
  if (
468
+ !dataRequest &&
387
469
  options.staticDir &&
388
470
  (method === "GET" || method === "HEAD") &&
389
471
  pathname !== "/"
@@ -430,7 +512,15 @@ export function createRequestHandler(
430
512
  try {
431
513
  const befores: Middleware[] = [];
432
514
  for (const c of chain) befores.push(...(c.module.before ?? []));
433
- 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
+ );
434
524
  return finalizeResponse(response, baseHeaders, method);
435
525
  } catch (error) {
436
526
  if (error instanceof Redirect) {
@@ -478,7 +568,36 @@ export function createRequestHandler(
478
568
  }
479
569
  };
480
570
  const requestScope = options.requestScope;
481
- return requestScope
482
- ? (request) => requestScope(request, () => handler(request))
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
+ }
483
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);
484
603
  }