@sigil-dev/grimoire 0.9.10 → 0.9.12

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.
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { SafeHtml } from "@sigil-dev/runtime";
3
3
  import { startCollecting, stopCollecting } from "../client/deps";
4
+ import { filterPublic } from "../env/index";
4
5
  import { findClosestError, type MatchedRoute } from "../routing/router";
5
6
  import type { RouteFile } from "../routing/scanner";
6
7
  import { isErrorResult } from "../sentinels/error.ts";
@@ -66,6 +67,23 @@ function extractDeferred(
66
67
  }
67
68
  }
68
69
 
70
+ /**
71
+ * The data a component renders with on the server: a value still in flight
72
+ * reads as `undefined`, so `{data.reviews ?? "Loading…"}` shows its
73
+ * fallback. The state script keeps the markers, and the settled values
74
+ * reach the browser before it hydrates.
75
+ */
76
+ function renderable(data: unknown): unknown {
77
+ if (!data || typeof data !== "object" || Array.isArray(data)) return data;
78
+ const values = Object.values(data as Record<string, unknown>);
79
+ if (!values.some((v) => v instanceof DeferredMarker)) return data;
80
+ const out: Record<string, unknown> = {};
81
+ for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
82
+ out[k] = v instanceof DeferredMarker ? undefined : v;
83
+ }
84
+ return out;
85
+ }
86
+
69
87
  /** Template + patch script for one settled deferred value. */
70
88
  function deferredChunk(key: string, value: unknown, error: boolean): string {
71
89
  const keyJson = JSON.stringify(key);
@@ -75,12 +93,22 @@ function deferredChunk(key: string, value: unknown, error: boolean): string {
75
93
  return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
76
94
  }
77
95
 
96
+ /**
97
+ * PUBLIC_ environment variables for `$env/dynamic/public` in the browser,
98
+ * as the server sees them now.
99
+ */
100
+ function publicEnvScript(nonceAttr: string): string {
101
+ const env = filterPublic(process.env);
102
+ if (Object.keys(env).length === 0) return "";
103
+ return `\n <script${nonceAttr}>window.__grimoire_env__=${safeStateJson(env)}</script>`;
104
+ }
105
+
78
106
  function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
79
107
  return `<!DOCTYPE html>
80
108
  <html>
81
109
  <head>
82
110
  <meta charset="UTF-8" />
83
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
111
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
84
112
  <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
85
113
  ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
86
114
  }
@@ -104,6 +132,59 @@ function hoistStylesheets(bodyHtml: string): string {
104
132
  return [...links].join("\n ");
105
133
  }
106
134
 
135
+ /**
136
+ * <style> tags for the scoped CSS of every component file whose scope class
137
+ * appears in `html`. Server builds register each file's CSS by hash (see
138
+ * serverStyleSnippet in the compiler), so a server-rendered page is styled
139
+ * before any script runs; the browser build's own injection sees the id and
140
+ * skips it.
141
+ */
142
+ function scopedStyles(html: string, nonceAttr: string): string {
143
+ const registry = (globalThis as { __sigil_css__?: Map<string, string> })
144
+ .__sigil_css__;
145
+ if (!registry) return "";
146
+ let out = "";
147
+ for (const [hash, css] of registry) {
148
+ if (!html.includes(hash)) continue;
149
+ out += `<style id="sigil-${hash}"${nonceAttr}>${css.replace(/<\/style/gi, "<\\/style")}</style>`;
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /**
155
+ * The CSRF token for this response: the visitor's existing `_csrf` cookie
156
+ * when it holds a well-formed token, so pages open in other tabs keep
157
+ * working, otherwise a fresh one.
158
+ */
159
+ function csrfTokenFor(req: Request): string {
160
+ const m = /(?:^|;\s*)_csrf=([0-9a-f]{64})(?:;|$)/.exec(
161
+ req.headers.get("cookie") ?? "",
162
+ );
163
+ return m?.[1] ?? randomBytes(32).toString("hex");
164
+ }
165
+
166
+ /**
167
+ * Put the token into every POST form, with or without an action attribute
168
+ * (one without posts back to the page). GET forms never get it: the token
169
+ * would end up in the URL, and a GET is never CSRF-checked anyway.
170
+ */
171
+ function injectCsrf(html: string, token: string): string {
172
+ const input = `<input type="hidden" name="_csrf" value="${token}" data-grimoire-csrf>`;
173
+ return html.replace(
174
+ /<form\b([^>]*\bmethod=["']?post["']?[^>]*)>/gi,
175
+ `<form$1>${input}`,
176
+ );
177
+ }
178
+
179
+ const csrfCookie = (token: string) => `_csrf=${token}; SameSite=Strict; Path=/`;
180
+
181
+ /**
182
+ * The collected <Head> tags between marker comments, so the client router
183
+ * can find and replace them on navigation.
184
+ */
185
+ const headBlock = (headHtml: string) =>
186
+ `<!--grimoire-head-->${headHtml}<!--/grimoire-head-->`;
187
+
107
188
  /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
108
189
  function applyLayoutTree(
109
190
  innerHtml: string,
@@ -116,7 +197,7 @@ function applyLayoutTree(
116
197
  for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
117
198
  bodyHtml = String(
118
199
  layoutMod.default({
119
- data,
200
+ data: renderable(data),
120
201
  children: new SafeHtml(bodyHtml),
121
202
  params,
122
203
  path: pattern,
@@ -166,8 +247,9 @@ export async function renderErrorPage(
166
247
  const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
167
248
  const headHtml = collectHead();
168
249
  const hoistedCss = hoistStylesheets(bodyHtml);
250
+ const styles = scopedStyles(bodyHtml, nonceAttr);
169
251
 
170
- const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
252
+ const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${styles ? `\n ${styles}` : ""}\n${headBlock(headHtml)}
171
253
  </head>
172
254
  <body>
173
255
  <div id="app">${bodyHtml}</div>
@@ -191,6 +273,9 @@ export async function renderRoute(
191
273
  cspNonce?: string,
192
274
  dev?: boolean,
193
275
  patchedFetch?: typeof fetch,
276
+ /** A form action's fail() on a plain (non-enhanced) POST: the page renders
277
+ * again with the failure as its `form` prop, and with its status. */
278
+ actionFailure?: { status: number; data: unknown },
194
279
  ): Promise<Response> {
195
280
  return runWithContext(async () => {
196
281
  const context: LoadContext = {
@@ -232,11 +317,21 @@ export async function renderRoute(
232
317
  };
233
318
  await runHook(plugins, "onRouteLoad", route, context);
234
319
 
235
- for (const layout of matched.layouts) {
320
+ // One level per folder with a +layout.tsx, a +layout.server.ts, or
321
+ // both. A server load without a layout component still runs: it's
322
+ // where a folder's guard lives, and skipping it left the folder open.
323
+ const levels = [
324
+ ...new Set(
325
+ [...matched.layouts, ...matched.layoutServers].map((l) => l.path),
326
+ ),
327
+ ].sort((a, b) => a.length - b.length);
328
+
329
+ for (const levelPath of levels) {
330
+ const layout = matched.layouts.find((l) => l.path === levelPath);
236
331
  // loads in this layout see everything accumulated so far
237
332
  context.parent = async () => ({ ...parentData });
238
333
 
239
- const layoutMod = await loadModule(layout.filePath);
334
+ const layoutMod = layout ? await loadModule(layout.filePath) : {};
240
335
 
241
336
  if (layoutMod.canMatch) {
242
337
  try {
@@ -271,7 +366,7 @@ export async function renderRoute(
271
366
  }
272
367
 
273
368
  const layoutServer = matched.layoutServers.find(
274
- (ls) => ls.path === layout.path,
369
+ (ls) => ls.path === levelPath,
275
370
  );
276
371
  let data: unknown;
277
372
  if (layoutServer) {
@@ -310,7 +405,9 @@ export async function renderRoute(
310
405
  { ...universalLayoutData, ...data }
311
406
  : data;
312
407
 
313
- layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
408
+ // only components wrap the page; the client indexes layoutData by them
409
+ if (layout)
410
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
314
411
  extractDeferred(mergedLayoutData, deferred, deferredCounter);
315
412
  if (mergedLayoutData && typeof mergedLayoutData === "object") {
316
413
  Object.assign(parentData, mergedLayoutData);
@@ -398,18 +495,21 @@ export async function renderRoute(
398
495
  // ── two-pass streaming (loading export present) ─────────────────────────
399
496
  if (hasLoading && !isNavigate) {
400
497
  const uid = Math.random().toString(36).slice(2);
498
+ const csrfToken = csrfTokenFor(req);
401
499
  const loadingHtml = String(pageMod.loading());
402
- const loadingBody = applyLayouts(
403
- `<div id="ab-${uid}">${loadingHtml}</div>`,
500
+ const loadingBody = injectCsrf(
501
+ applyLayouts(`<div id="ab-${uid}">${loadingHtml}</div>`),
502
+ csrfToken,
404
503
  );
405
504
  // layout stylesheets are in the loading shell — hoist before first flush
406
505
  const hoistedCss = hoistStylesheets(loadingBody);
506
+ const shellStyles = scopedStyles(loadingBody, nonceAttr);
407
507
 
408
508
  const stream = new ReadableStream({
409
509
  async start(controller) {
410
510
  // 1. skeleton + loading shell — browser paints immediately
411
511
  controller.enqueue(
412
- `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
512
+ `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
413
513
  </head>
414
514
  <body>
415
515
  <div id="app">${loadingBody}`,
@@ -434,8 +534,17 @@ export async function renderRoute(
434
534
  extractDeferred(mergedData, deferred, deferredCounter);
435
535
 
436
536
  // 3. render real page + collect head
437
- const pageHtml = await Promise.resolve(
438
- pageMod.default({ data: mergedData, params: matched.params }),
537
+ const pageHtml = injectCsrf(
538
+ String(
539
+ await Promise.resolve(
540
+ pageMod.default({
541
+ data: renderable(mergedData),
542
+ params: matched.params,
543
+ form: actionFailure?.data,
544
+ }),
545
+ ),
546
+ ),
547
+ csrfToken,
439
548
  );
440
549
  const headHtml = collectHead();
441
550
  const stateJson = safeStateJson({
@@ -444,18 +553,19 @@ export async function renderRoute(
444
553
  layoutData: layoutPairs.map((l) => l.data),
445
554
  pattern: matched.route.path,
446
555
  deps: [...collectedDeps],
556
+ form: actionFailure?.data,
447
557
  });
448
558
 
449
559
  // 4. inject late head tags
450
560
  if (headHtml) {
451
561
  controller.enqueue(
452
- `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
562
+ `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString(${JSON.stringify(`<head>${headHtml}</head>`).replace(/</g, "\\u003c")},"text/html");for(var e of Array.from(p.head.children)){var c=e.cloneNode(true);c.setAttribute("data-grimoire-head","1");document.head.appendChild(c)}})();</script>`,
453
563
  );
454
564
  }
455
565
 
456
566
  // 5. swap shell with real content
457
567
  controller.enqueue(
458
- `<template id="ab-${uid}-r">${String(pageHtml)}</template>
568
+ `<template id="ab-${uid}-r">${scopedStyles(String(pageHtml), nonceAttr)}${String(pageHtml)}</template>
459
569
  <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
460
570
  <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
461
571
  </div>
@@ -478,7 +588,12 @@ export async function renderRoute(
478
588
  });
479
589
 
480
590
  return new Response(stream, {
481
- headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
591
+ status: actionFailure?.status ?? 200,
592
+ headers: {
593
+ "Content-Type": "text/html",
594
+ "Set-Cookie": csrfCookie(csrfToken),
595
+ Vary: NAVIGATE_HEADER,
596
+ },
482
597
  });
483
598
  }
484
599
 
@@ -499,7 +614,11 @@ export async function renderRoute(
499
614
  extractDeferred(mergedData, deferred, deferredCounter);
500
615
 
501
616
  const pageHtml = await Promise.resolve(
502
- pageMod.default({ data: mergedData, params: matched.params }),
617
+ pageMod.default({
618
+ data: renderable(mergedData),
619
+ params: matched.params,
620
+ form: actionFailure?.data,
621
+ }),
503
622
  );
504
623
 
505
624
  // layouts must render before collectHead(): a <Head> call inside a
@@ -539,22 +658,20 @@ export async function renderRoute(
539
658
  }
540
659
 
541
660
  // ── single-pass SSR stream ──────────────────────────────────────────────
542
- const csrfToken = randomBytes(32).toString("hex");
661
+ const csrfToken = csrfTokenFor(req);
543
662
  const stateJson = safeStateJson({
544
663
  params: matched.params,
545
664
  data: mergedData,
546
665
  layoutData: layoutPairs.map((l) => l.data),
547
666
  pattern: matched.route.path,
548
667
  deps: [...collectedDeps],
668
+ form: actionFailure?.data,
549
669
  });
550
670
 
551
- const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}" data-grimoire-csrf>`;
552
- bodyHtml = bodyHtml.replace(
553
- /<form([^>]*action=[^>]*)>/gi,
554
- `<form$1>${csrfInput}`,
555
- );
671
+ bodyHtml = injectCsrf(bodyHtml, csrfToken);
556
672
 
557
673
  const hoistedCss = hoistStylesheets(bodyHtml);
674
+ const styles = scopedStyles(bodyHtml, nonceAttr);
558
675
 
559
676
  const stream = new ReadableStream({
560
677
  async start(controller) {
@@ -563,9 +680,10 @@ export async function renderRoute(
563
680
  if (hoistedCss) {
564
681
  controller.enqueue(`\n ${hoistedCss}`);
565
682
  }
566
- if (headHtml) {
567
- controller.enqueue(`\n${headHtml}`);
683
+ if (styles) {
684
+ controller.enqueue(`\n ${styles}`);
568
685
  }
686
+ controller.enqueue(`\n${headBlock(headHtml)}`);
569
687
 
570
688
  controller.enqueue(`\n</head>
571
689
  <body>
@@ -589,9 +707,10 @@ export async function renderRoute(
589
707
  });
590
708
 
591
709
  return new Response(stream, {
710
+ status: actionFailure?.status ?? 200,
592
711
  headers: {
593
712
  "Content-Type": "text/html",
594
- "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
713
+ "Set-Cookie": csrfCookie(csrfToken),
595
714
  Vary: NAVIGATE_HEADER,
596
715
  },
597
716
  });
@@ -1,13 +1,26 @@
1
- import { createHash } from "node:crypto";
2
1
  import { transformSync } from "@babel/core";
3
2
  import sigilPlugin from "@sigil-dev/compiler/babel";
3
+ import {
4
+ computeHash,
5
+ extractStyles,
6
+ serverStyleSnippet,
7
+ } from "@sigil-dev/compiler/css";
4
8
  import { log } from "../logger/instance";
9
+ import { rewriteAliases } from "../server/resolver";
5
10
  import type { GrimoirePlugin } from "../types";
6
11
 
7
12
  const logger = log.scope("scope");
8
13
  let registered = false;
9
14
 
10
- export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
15
+ /**
16
+ * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
17
+ * to file paths in every compiled module: Bun's runtime plugins can't
18
+ * resolve them for static imports.
19
+ */
20
+ export function registerSSRPlugin(
21
+ plugins: GrimoirePlugin[] = [],
22
+ aliases: Record<string, string> = {},
23
+ ) {
11
24
  if (registered) return;
12
25
  registered = true;
13
26
 
@@ -44,16 +57,12 @@ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
44
57
  if (process.env.SIGIL_VERBOSE) {
45
58
  logger.debug("[sigil-ssr] XFORM:", path);
46
59
  }
47
- const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
48
- // scoped <style> blocks never render server-side (SSR mode never
49
- // injects the CSS — see bun-plugin.ts's mode !== "ssr" guard), but
50
- // their raw CSS text still needs stripping or the JSX parser treats
51
- // a bare `{` in a declaration like `position: sticky;` as the start
52
- // of an embedded expression and throws
53
- const sourceNoStyle = source.replace(
54
- /<style[^>]*>[\s\S]*?<\/style>/gi,
55
- "",
56
- );
60
+ // must match the client build, or scoped classes differ per side;
61
+ // files without a <style> block get no scope class at all. The
62
+ // CSS is registered for the renderer, which puts it in <head>.
63
+ const styles = extractStyles(source, computeHash(path), path);
64
+ const hash = styles.css ? computeHash(path) : undefined;
65
+ const sourceNoStyle = styles.code;
57
66
  const result = transformSync(sourceNoStyle, {
58
67
  configFile: false,
59
68
  babelrc: false,
@@ -64,7 +73,13 @@ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
64
73
  filename: path,
65
74
  });
66
75
 
67
- let contents = transpiler.transformSync(result?.code ?? "");
76
+ let contents = rewriteAliases(
77
+ transpiler.transformSync(result?.code ?? ""),
78
+ aliases,
79
+ );
80
+ if (styles.css && hash) {
81
+ contents = serverStyleSnippet(hash, styles.css) + contents;
82
+ }
68
83
 
69
84
  for (const plugin of plugins) {
70
85
  if (plugin.transform)
@@ -1,22 +1,14 @@
1
1
  import { basename, dirname, join, relative, resolve } from "node:path";
2
2
  import { transformSync } from "@babel/core";
3
3
  import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import {
5
+ clientStyleSnippet,
6
+ computeHash,
7
+ extractStyles,
8
+ } from "@sigil-dev/compiler/css";
4
9
  import type { GrimoirePlugin } from "../types";
5
10
  import type { RouteFile } from "./scanner";
6
11
 
7
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
8
-
9
- // Inline the same hash helper used in bun-plugin.ts to avoid importing
10
- // unexported internals from @sigil-dev/compiler.
11
- function computeHash(filePath: string): string {
12
- let h = 0x811c9dc5;
13
- for (let i = 0; i < filePath.length; i++) {
14
- h ^= filePath.charCodeAt(i);
15
- h = (h * 0x01000193) >>> 0;
16
- }
17
- return h.toString(36);
18
- }
19
-
20
12
  function rewriteRelativeImports(filePath: string) {
21
13
  const basedir = dirname(filePath);
22
14
  const rewrite = (source?: { value: string }) => {
@@ -65,9 +57,16 @@ export async function transformRoutes(
65
57
 
66
58
  await Promise.all(
67
59
  routes.map(async (route, index) => {
68
- let code = await Bun.file(route.filePath).text();
69
- const hash = computeHash(route.filePath);
70
- code = code.replace(STYLE_RE, "");
60
+ // scope classes only where there is scoped CSS to match. The CSS
61
+ // used to be dropped here: a route's own <style> never reached
62
+ // the browser build
63
+ const styles = extractStyles(
64
+ await Bun.file(route.filePath).text(),
65
+ computeHash(route.filePath),
66
+ route.filePath,
67
+ );
68
+ const code = styles.code;
69
+ const hash = styles.css ? computeHash(route.filePath) : undefined;
71
70
 
72
71
  const res = transformSync(code, {
73
72
  configFile: false,
@@ -83,6 +82,7 @@ export async function transformRoutes(
83
82
  filename: route.filePath,
84
83
  });
85
84
  let out = transpiler.transformSync(res?.code ?? "");
85
+ if (styles.css && hash) out = clientStyleSnippet(hash, styles.css) + out;
86
86
  for (const plugin of plugins) {
87
87
  if (plugin.transform)
88
88
  out = (await plugin.transform(out, route.filePath)) ?? out;
@@ -0,0 +1,194 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { log } from "../logger/instance.ts";
3
+
4
+ const logger = log.scope("server");
5
+
6
+ /**
7
+ * Tasks collected for the in-flight request.
8
+ *
9
+ * AsyncLocalStorage is what makes afterResponse() work without threading a
10
+ * context argument through every function that might want to defer work.
11
+ * A plain module-level array would interleave badly under concurrency: two
12
+ * requests running at once could collect each other's tasks, and a task
13
+ * would run at the end of the wrong response.
14
+ */
15
+ interface RequestScope {
16
+ tasks: Array<() => unknown>;
17
+ /** Resolves when fire() has run every task, so drain can wait for this. */
18
+ flushed: Promise<void>;
19
+ markFlushed: () => void;
20
+ }
21
+ const scope = new AsyncLocalStorage<RequestScope>();
22
+
23
+ let inflight = new Set<Promise<unknown>>();
24
+ /**
25
+ * Flush promises for requests whose body has not finished streaming.
26
+ *
27
+ * Tracked separately from `inflight` because a task is not running yet while
28
+ * its response is still streaming — a shutdown that only waits on running
29
+ * work would return while queued work was still pending.
30
+ */
31
+ let unflushed = new Set<Promise<void>>();
32
+ let shuttingDown = false;
33
+
34
+ /**
35
+ * Run work after the response for the current request has been flushed.
36
+ *
37
+ * Does not block the response, and does not survive a restart — a task that
38
+ * has not finished is lost if the process exits. That makes this for work
39
+ * that is cheap and re-derivable: analytics, cache warming, a last-seen
40
+ * timestamp. Anything a user was promised belongs in a durable queue, and
41
+ * this is the call site to change when a job starts to matter.
42
+ *
43
+ * Errors are logged, never thrown. The response is already sent by the time
44
+ * a task runs, so a failure cannot be reported to anyone.
45
+ *
46
+ * Outside a request (at startup, in `init`) the task runs on the next
47
+ * microtask instead. That keeps the call valid anywhere without pretending
48
+ * there was a response to wait for.
49
+ */
50
+ export function afterResponse(fn: () => unknown): Promise<unknown> {
51
+ if (shuttingDown) {
52
+ return Promise.reject(
53
+ new Error("afterResponse() called during shutdown"),
54
+ );
55
+ }
56
+
57
+ // Wrap so a synchronous throw inside fn becomes a rejection instead of
58
+ // propagating out of the caller's await.
59
+ const run = async () => {
60
+ try {
61
+ await fn();
62
+ } catch (e) {
63
+ logger.error("afterResponse task failed:", e);
64
+ }
65
+ };
66
+
67
+ const current = scope.getStore();
68
+ if (!current) {
69
+ return track(run());
70
+ }
71
+
72
+ current.tasks.push(() => track(run()));
73
+ return Promise.resolve();
74
+ }
75
+
76
+ function deferred(): { flushed: Promise<void>; markFlushed: () => void } {
77
+ let mark!: () => void;
78
+ const flushed = new Promise<void>((resolve) => {
79
+ mark = resolve;
80
+ });
81
+ return { flushed, markFlushed: mark };
82
+ }
83
+
84
+ function track(p: Promise<unknown>): Promise<unknown> {
85
+ inflight.add(p);
86
+ p.finally(() => inflight.delete(p));
87
+ return p;
88
+ }
89
+
90
+ /**
91
+ * Run a handler inside a request scope, then fire the collected tasks once
92
+ * the response body has finished streaming.
93
+ *
94
+ * Wrapping the body is what makes "after the response" true for streaming
95
+ * responses: scheduling on the handler's return would run the task while
96
+ * the client is still receiving. Firing on the stream's end means a slow
97
+ * download does not start the work early.
98
+ */
99
+ export async function withAfterResponse(
100
+ req: Request,
101
+ handler: (req: Request) => Response | Promise<Response>,
102
+ ): Promise<Response> {
103
+ const requestScope: RequestScope = { tasks: [], ...deferred() };
104
+ unflushed.add(requestScope.flushed);
105
+ requestScope.flushed.finally(() => unflushed.delete(requestScope.flushed));
106
+ const response = await scope.run(requestScope, () => handler(req));
107
+
108
+ const fire = () => {
109
+ requestScope.markFlushed();
110
+ if (requestScope.tasks.length === 0) return;
111
+ // Copy first: a task may register another task.
112
+ const tasks = requestScope.tasks.splice(0);
113
+ for (const t of tasks) t();
114
+ };
115
+
116
+ if (!(response instanceof Response) || response.body === null) {
117
+ fire();
118
+ return response as Response;
119
+ }
120
+
121
+ const { readable, writable } = new TransformStream();
122
+ // Errors on the original body propagate, and the tasks still run: a
123
+ // client disconnecting mid-stream must not silently skip the work.
124
+ Promise.resolve(response.body)
125
+ .then((body) => body?.pipeTo(writable))
126
+ .catch(() => writable.abort())
127
+ .finally(fire);
128
+
129
+ return new Response(readable, {
130
+ status: response.status,
131
+ statusText: response.statusText,
132
+ headers: response.headers,
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Wait for in-flight afterResponse tasks so a graceful shutdown does not
138
+ * abandon work already started. Subsequent registrations are rejected.
139
+ */
140
+ export async function drainAfterResponse(timeoutMs = 5000): Promise<void> {
141
+ shuttingDown = true;
142
+
143
+ const deadline = Date.now() + timeoutMs;
144
+ const timedOut = Symbol("timeout");
145
+
146
+ const waitFor = async <T>(work: Promise<T>): Promise<T | typeof timedOut> => {
147
+ const left = deadline - Date.now();
148
+ if (left <= 0) return timedOut;
149
+ let timer: ReturnType<typeof setTimeout> | undefined;
150
+ const result = await Promise.race([
151
+ work,
152
+ new Promise<typeof timedOut>((resolve) => {
153
+ timer = setTimeout(() => resolve(timedOut), left);
154
+ }),
155
+ ]);
156
+ if (timer) clearTimeout(timer);
157
+ return result;
158
+ };
159
+
160
+ // Two waits, not one. A task registered during a request is not in
161
+ // `inflight` until the response body has flushed and it actually
162
+ // starts, so draining only that set would return while a response was
163
+ // still streaming and its work was still queued.
164
+ const flushed = await waitFor(Promise.allSettled([...unflushed]));
165
+ if (flushed === timedOut) {
166
+ logger.warn(
167
+ `responses were still streaming after ${timeoutMs}ms; ` +
168
+ `afterResponse tasks for them will be lost`,
169
+ );
170
+ return;
171
+ }
172
+
173
+ if (inflight.size === 0) {
174
+ unflushed.clear();
175
+ return;
176
+ }
177
+
178
+ logger.info(`waiting for ${inflight.size} afterResponse task(s)...`);
179
+ const result = await waitFor(Promise.allSettled([...inflight]));
180
+ if (result === timedOut) {
181
+ logger.warn(
182
+ `afterResponse tasks did not finish within ${timeoutMs}ms, abandoning them`,
183
+ );
184
+ }
185
+ inflight.clear();
186
+ unflushed.clear();
187
+ }
188
+
189
+ /** Test-only: reset module state between cases. */
190
+ export function _resetAfterResponseForTest(): void {
191
+ inflight = new Set();
192
+ unflushed = new Set();
193
+ shuttingDown = false;
194
+ }