@tschk/moonshine-server 0.4.0 → 0.4.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.
package/README.md CHANGED
@@ -25,5 +25,14 @@ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-server",
3
- "version": "0.4.0",
3
+ "version": "0.4.4",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -15,8 +15,8 @@
15
15
  "test": "bun test"
16
16
  },
17
17
  "dependencies": {
18
- "@tschk/moonshine-framework": "^0.3.6",
19
- "@tschk/moonshine-router": "^0.3.6"
18
+ "@tschk/moonshine-framework": "^0.4.4",
19
+ "@tschk/moonshine-router": "^0.4.4"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@types/bun": "1.3.14",
package/src/data.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type {
2
2
  MoonshineManifest,
3
3
  Renderer,
4
+ RequestScope,
4
5
  RouteDefinition,
5
6
  } from "@tschk/moonshine-framework";
6
- import type { RouteGraph } from "@tschk/moonshine-router";
7
+ import type { RouteGraph } from "@tschk/moonshine-router/graph";
7
8
 
8
9
  export type RouteContext = {
9
10
  request: Request;
@@ -29,6 +30,7 @@ export type ErrorBoundary = (
29
30
  ) => Response | Promise<Response>;
30
31
 
31
32
  export type RouteModule = {
33
+ methods?: readonly string[];
32
34
  before?: Middleware[];
33
35
  after?: Middleware[];
34
36
  loader?: Loader;
@@ -38,6 +40,7 @@ export type RouteModule = {
38
40
  };
39
41
 
40
42
  export type RequestHandlerOptions = {
43
+ requestScope?: RequestScope;
41
44
  graph?: RouteGraph<RouteDefinition>;
42
45
  routes?: RouteDefinition[];
43
46
  manifest?: MoonshineManifest;
@@ -57,7 +60,7 @@ export function createRouteContext(
57
60
  request,
58
61
  params,
59
62
  signal: request.signal,
60
- data: {},
63
+ data: Object.create(null),
61
64
  };
62
65
  }
63
66
 
package/src/pipeline.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createRouteGraph, matchRoutes } from "@tschk/moonshine-router";
1
+ import { createRouteGraph, matchRoutes } from "@tschk/moonshine-router/graph";
2
2
  import type {
3
3
  RouteArtifact,
4
4
  RouteDefinition,
@@ -25,6 +25,7 @@ function hasControlChars(value: string): boolean {
25
25
  function isSafeRedirect(location: string, request: Request): boolean {
26
26
  try {
27
27
  if (hasControlChars(location)) return false;
28
+ if (location.startsWith("//") || location.includes("\\")) return false;
28
29
  const base = new URL(request.url);
29
30
  const url = new URL(location, request.url);
30
31
  return url.origin === base.origin;
@@ -45,12 +46,12 @@ function buildModuleChain(
45
46
  const chain: ModuleChainItem[] = [];
46
47
 
47
48
  for (const key of route.layouts ?? []) {
48
- const module = modules[key];
49
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
49
50
  if (module) chain.push({ key, module });
50
51
  }
51
52
 
52
53
  for (const key of route.middleware ?? []) {
53
- const module = modules[key];
54
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
54
55
  if (module) chain.push({ key, module });
55
56
  }
56
57
 
@@ -61,7 +62,7 @@ function buildModuleChain(
61
62
  ];
62
63
 
63
64
  for (const key of leafKeys) {
64
- const module = modules[key];
65
+ const module = Object.hasOwn(modules, key) ? modules[key] : undefined;
65
66
  if (module) {
66
67
  chain.push({ key, module });
67
68
  break;
@@ -79,38 +80,50 @@ function mergeHeaders(
79
80
  for (const source of sources) {
80
81
  if (!source) continue;
81
82
 
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
- }
83
+ const entries =
84
+ source instanceof Headers || Array.isArray(source)
85
+ ? source
86
+ : Object.entries(source);
87
+ for (const [key, value] of entries) {
88
+ // Cookies are separate response fields; joining or replacing loses sessions.
89
+ if (key.toLowerCase() === "set-cookie") headers.append(key, value);
90
+ else headers.set(key, value);
96
91
  }
97
92
  }
98
93
 
99
94
  return headers;
100
95
  }
101
96
 
97
+ function discardResponse(response: Response, retained?: Response): void {
98
+ const body = response.body;
99
+ if (!body || body === retained?.body || body.locked || response.bodyUsed)
100
+ return;
101
+ try {
102
+ void body.cancel().catch(() => {});
103
+ } catch {
104
+ // Discarding an unused body must not replace the selected response/error.
105
+ }
106
+ }
107
+
108
+ function discardReplacedResponse(
109
+ response: Response,
110
+ retained?: Response,
111
+ ): void {
112
+ // shortcut: a returned stream may consume this body later; stronger cleanup needs explicit ownership.
113
+ if (retained?.body) return;
114
+ discardResponse(response, retained);
115
+ }
116
+
102
117
  function finalizeResponse(
103
118
  response: Response,
104
119
  baseHeaders?: HeadersInit,
105
120
  method?: string,
106
121
  ): Response {
107
- const headers = new Headers(baseHeaders);
108
- for (const [key, value] of response.headers.entries()) {
109
- headers.set(key, value);
110
- }
122
+ const headers = mergeHeaders(baseHeaders, response.headers);
111
123
  // HEAD must carry the GET headers and no body; shipping one is a protocol
112
124
  // violation and mismatches Content-Length on runtimes that do not strip it.
113
125
  const body = method === "HEAD" ? null : response.body;
126
+ if (method === "HEAD") discardResponse(response);
114
127
  return new Response(body, {
115
128
  status: response.status,
116
129
  statusText: response.statusText,
@@ -128,7 +141,9 @@ function findErrorBoundary(
128
141
  }
129
142
 
130
143
  if (route.errorBoundary) {
131
- const module = modules[route.errorBoundary];
144
+ const module = Object.hasOwn(modules, route.errorBoundary)
145
+ ? modules[route.errorBoundary]
146
+ : undefined;
132
147
  if (module?.errorBoundary) return module.errorBoundary;
133
148
  }
134
149
 
@@ -150,6 +165,7 @@ function resolveBaseHeaders(
150
165
  // Derived from the leaf, never hardcoded: an Allow header that lists methods
151
166
  // the route cannot serve sends clients down paths that will 405 again.
152
167
  function allowedMethods(leaf: ModuleChainItem | undefined): string {
168
+ if (leaf?.module.methods) return leaf.module.methods.join(", ");
153
169
  const methods = ["GET", "HEAD"];
154
170
  if (leaf?.module.action) methods.push("POST", "PUT", "PATCH", "DELETE");
155
171
  return methods.join(", ");
@@ -164,6 +180,14 @@ async function runCoreAndAfters(
164
180
  const method = ctx.request.method;
165
181
  const leaf = chain[chain.length - 1];
166
182
 
183
+ if (leaf?.module.methods && !leaf.module.methods.includes(method)) {
184
+ return new Response(null, {
185
+ status: 405,
186
+ headers: { allow: allowedMethods(leaf) },
187
+ });
188
+ }
189
+
190
+ let actionResponse: Response | undefined;
167
191
  if (method !== "GET" && method !== "HEAD") {
168
192
  // Without an action there is nothing to serve a write method. Falling
169
193
  // through would run the loaders — reachable by any verb, so a
@@ -177,39 +201,67 @@ async function runCoreAndAfters(
177
201
  }
178
202
 
179
203
  const result = await callAction(leaf.module.action, ctx);
180
- if (result instanceof Response) return result;
181
- if (result !== undefined) {
204
+ if (result instanceof Response) actionResponse = result;
205
+ else if (result !== undefined) {
182
206
  if (leaf.module.loader) ctx.data.__action = result;
183
207
  else ctx.data[leaf.key] = result;
184
208
  }
185
209
  }
186
210
 
187
- const loaderEntries = chain.filter((c) => c.module.loader);
211
+ let loaderResponse: Response | undefined;
212
+ const loaderEntries = actionResponse
213
+ ? []
214
+ : chain.filter((c) => c.module.loader);
188
215
  if (loaderEntries.length > 0) {
189
216
  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
- );
217
+ const resolvedResponses: Response[] = [];
218
+ let failed = false;
219
+ let failureResponse: Response | undefined;
220
+ let results: Array<{ key: string; value: unknown }>;
221
+ try {
222
+ results = await Promise.all(
223
+ loaderEntries.map(async (c) => {
224
+ const value = await callLoader(c.module.loader!, ctx);
225
+ if (value instanceof Response) {
226
+ if (failed) discardResponse(value, failureResponse);
227
+ else resolvedResponses.push(value);
228
+ }
229
+ return { key: c.key, value };
230
+ }),
231
+ );
232
+ ctx.signal.throwIfAborted();
233
+ } catch (error) {
234
+ failed = true;
235
+ failureResponse = error instanceof Response ? error : undefined;
236
+ for (const response of resolvedResponses)
237
+ discardResponse(response, failureResponse);
238
+ throw error;
239
+ }
240
+ // Promise.all preserves chain order: outer loaders take response precedence.
196
241
  for (const { key, value } of results) {
197
- if (value !== undefined) ctx.data[key] = value;
242
+ if (value instanceof Response) loaderResponse ??= value;
243
+ else if (value !== undefined) ctx.data[key] = value;
198
244
  }
245
+ for (const response of resolvedResponses)
246
+ discardResponse(response, loaderResponse);
199
247
  }
200
248
 
201
- ctx.signal.throwIfAborted();
249
+ if (!actionResponse) ctx.signal.throwIfAborted();
202
250
 
203
251
  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);
252
+ if (actionResponse) {
253
+ response = actionResponse;
254
+ } else if (loaderResponse) {
255
+ response = loaderResponse;
256
+ } else if (route.mode === "api") {
257
+ response = json(ctx.data);
207
258
  } else if (route.mode === "static" && options.staticDir) {
208
259
  const pathname = new URL(ctx.request.url).pathname;
209
260
  const staticRes = await tryServeStatic(
210
261
  options.staticDir,
211
262
  pathname,
212
263
  options.defaultMeta?.headers,
264
+ method,
213
265
  );
214
266
  if (staticRes) {
215
267
  response = staticRes;
@@ -238,15 +290,25 @@ async function runCoreAndAfters(
238
290
 
239
291
  for (let i = chain.length - 1; i >= 0; i--) {
240
292
  for (const after of chain[i].module.after ?? []) {
241
- const next = async () => response;
242
- response = await after(ctx, next);
293
+ const previous = response;
294
+ const next = async () => previous;
295
+ try {
296
+ response = await after(ctx, next);
297
+ } catch (error) {
298
+ discardReplacedResponse(
299
+ previous,
300
+ error instanceof Response ? error : undefined,
301
+ );
302
+ throw error;
303
+ }
304
+ discardReplacedResponse(previous, response);
243
305
  }
244
306
  }
245
307
 
246
308
  return response;
247
309
  }
248
310
 
249
- function runBefores(
311
+ async function runBefores(
250
312
  ctx: RouteContext,
251
313
  index: number,
252
314
  befores: Middleware[],
@@ -259,18 +321,64 @@ function runBefores(
259
321
  }
260
322
 
261
323
  const mw = befores[index]!;
262
- const next = () => runBefores(ctx, index + 1, befores, chain, options, route);
263
- return mw(ctx, next);
324
+ const delivered: Response[] = [];
325
+ let settled = false;
326
+ let retained: Response | undefined;
327
+ const next = () => {
328
+ const pending = runBefores(
329
+ ctx,
330
+ index + 1,
331
+ befores,
332
+ chain,
333
+ options,
334
+ route,
335
+ ).then(
336
+ (response) => {
337
+ if (settled) discardReplacedResponse(response, retained);
338
+ else delivered.push(response);
339
+ return response;
340
+ },
341
+ (error) => {
342
+ if (error instanceof Response) {
343
+ if (settled) discardReplacedResponse(error, retained);
344
+ else delivered.push(error);
345
+ }
346
+ throw error;
347
+ },
348
+ );
349
+ // A middleware may return before its next() settles; still observe rejection.
350
+ void pending.catch(() => {});
351
+ return pending;
352
+ };
353
+ try {
354
+ retained = await mw(ctx, next);
355
+ return retained;
356
+ } catch (error) {
357
+ retained = error instanceof Response ? error : undefined;
358
+ throw error;
359
+ } finally {
360
+ settled = true;
361
+ for (const response of delivered)
362
+ discardReplacedResponse(response, retained);
363
+ }
264
364
  }
265
365
 
266
366
  export function createRequestHandler(
267
367
  options: RequestHandlerOptions,
268
368
  ): (request: Request) => Promise<Response> {
369
+ if (
370
+ options.manifest?.requestContext &&
371
+ typeof options.requestScope !== "function"
372
+ ) {
373
+ throw new Error(
374
+ "Request-context manifests require their bundled requestScope",
375
+ );
376
+ }
269
377
  // Compiling the route graph is linear in the route count, so build it once
270
378
  // per handler instead of once per request.
271
379
  let cachedGraph = options.graph;
272
380
 
273
- return async (request) => {
381
+ const handler = async (request: Request): Promise<Response> => {
274
382
  const url = new URL(request.url);
275
383
  const pathname = url.pathname.replace(/\/+$/, "") || "/";
276
384
  const method = request.method;
@@ -284,6 +392,7 @@ export function createRequestHandler(
284
392
  options.staticDir,
285
393
  pathname,
286
394
  options.defaultMeta?.headers,
395
+ method,
287
396
  );
288
397
  if (staticRes) return staticRes;
289
398
  }
@@ -294,15 +403,23 @@ export function createRequestHandler(
294
403
  ? createRouteGraph(options.manifest.routes)
295
404
  : undefined);
296
405
  if (!graph) {
297
- return new Response("No route graph configured", { status: 500 });
406
+ return finalizeResponse(
407
+ new Response("No route graph configured", { status: 500 }),
408
+ options.defaultMeta?.headers,
409
+ method,
410
+ );
298
411
  }
299
412
 
300
413
  const match = matchRoutes(graph, pathname);
301
414
  if (!match) {
302
415
  const ctx = createRouteContext(request, {});
303
- return options.notFound
304
- ? await options.notFound(ctx)
305
- : new Response("Not Found", { status: 404 });
416
+ return finalizeResponse(
417
+ options.notFound
418
+ ? await options.notFound(ctx)
419
+ : new Response("Not Found", { status: 404 }),
420
+ options.defaultMeta?.headers,
421
+ method,
422
+ );
306
423
  }
307
424
 
308
425
  const route = match.route;
@@ -318,10 +435,14 @@ export function createRequestHandler(
318
435
  } catch (error) {
319
436
  if (error instanceof Redirect) {
320
437
  if (!isSafeRedirect(error.location, request)) {
321
- return new Response("Invalid redirect", {
322
- status: 400,
323
- headers: baseHeaders,
324
- });
438
+ return finalizeResponse(
439
+ new Response("Invalid redirect", {
440
+ status: 400,
441
+ headers: baseHeaders,
442
+ }),
443
+ undefined,
444
+ method,
445
+ );
325
446
  }
326
447
  const headers = new Headers(baseHeaders);
327
448
  headers.set("location", error.location);
@@ -330,7 +451,18 @@ export function createRequestHandler(
330
451
 
331
452
  const boundary = findErrorBoundary(chain, route, options.modules ?? {});
332
453
  if (boundary) {
333
- const res = await boundary(ctx, error);
454
+ let res: Response;
455
+ try {
456
+ res = await boundary(ctx, error);
457
+ } catch (boundaryError) {
458
+ if (error instanceof Response)
459
+ discardReplacedResponse(
460
+ error,
461
+ boundaryError instanceof Response ? boundaryError : undefined,
462
+ );
463
+ throw boundaryError;
464
+ }
465
+ if (error instanceof Response) discardReplacedResponse(error, res);
334
466
  return finalizeResponse(res, baseHeaders, method);
335
467
  }
336
468
 
@@ -345,4 +477,8 @@ export function createRequestHandler(
345
477
  );
346
478
  }
347
479
  };
480
+ const requestScope = options.requestScope;
481
+ return requestScope
482
+ ? (request) => requestScope(request, () => handler(request))
483
+ : handler;
348
484
  }
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
  }