@k8ordo/framework 1.4.4 → 2.0.0

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.
Files changed (55) hide show
  1. package/README.md +1 -1
  2. package/dist/generated.d.mts +23 -2
  3. package/dist/runtime/app-router.d.mts +10 -10
  4. package/dist/runtime/app-router.mjs +119 -83
  5. package/dist/runtime/browser-payloads.mjs +2 -1
  6. package/dist/runtime/client-files.d.mts +11 -0
  7. package/dist/runtime/client-files.mjs +42 -0
  8. package/dist/runtime/client-ready.d.mts +3 -2
  9. package/dist/runtime/document-root.mjs +1 -1
  10. package/dist/runtime/entry.browser.d.mts +1 -1
  11. package/dist/runtime/entry.browser.mjs +8 -12
  12. package/dist/runtime/entry.rsc.mjs +148 -102
  13. package/dist/runtime/entry.ssr.d.mts +21 -1
  14. package/dist/runtime/entry.ssr.mjs +10 -13
  15. package/dist/runtime/head-scripts.d.mts +18 -0
  16. package/dist/runtime/head-scripts.mjs +159 -0
  17. package/dist/runtime/hydrating-pathname.d.mts +16 -0
  18. package/dist/runtime/hydrating-pathname.mjs +26 -0
  19. package/dist/runtime/mount.d.mts +16 -11
  20. package/dist/runtime/mount.mjs +29 -18
  21. package/dist/runtime/payload.d.mts +22 -23
  22. package/dist/runtime/payload.mjs +11 -16
  23. package/dist/runtime/prefetch.d.mts +60 -25
  24. package/dist/runtime/prefetch.mjs +166 -38
  25. package/dist/runtime/recover.d.mts +2 -0
  26. package/dist/runtime/recover.mjs +11 -7
  27. package/dist/runtime/redirect.d.mts +20 -14
  28. package/dist/runtime/redirect.mjs +42 -15
  29. package/dist/runtime/request-scope.d.mts +1 -1
  30. package/dist/runtime/request-scope.mjs +11 -23
  31. package/dist/runtime/server.d.mts +6 -0
  32. package/dist/runtime/server.mjs +3 -0
  33. package/dist/runtime/stylesheets.d.mts +13 -0
  34. package/dist/runtime/stylesheets.mjs +15 -0
  35. package/dist/serve.d.mts +1 -0
  36. package/dist/serve.mjs +5 -11
  37. package/dist/static-file-BAjwBMMl.mjs +1274 -0
  38. package/dist/{static-host-C6D_11Gp.mjs → static-host-B-1fAfAw.mjs} +49 -74
  39. package/dist/vercel.d.mts +0 -1
  40. package/dist/vercel.mjs +20 -20
  41. package/dist/vite.mjs +228 -1518
  42. package/docs/GUIDE.md +3 -2
  43. package/docs/llms.txt +8 -4
  44. package/docs/references/csp.md +11 -9
  45. package/docs/references/deploy.md +17 -20
  46. package/docs/references/errors.md +0 -34
  47. package/docs/references/params.md +5 -5
  48. package/docs/references/routing.md +94 -31
  49. package/package.json +6 -6
  50. package/dist/runtime/redirect-file.d.mts +0 -20
  51. package/dist/runtime/redirect-file.mjs +0 -42
  52. package/dist/runtime/tree-pathname.d.mts +0 -2
  53. package/dist/runtime/tree-pathname.mjs +0 -11
  54. package/dist/server.d.mts +0 -110
  55. package/dist/server.mjs +0 -97
@@ -4,13 +4,12 @@ import { methodNotAllowed, routeAnswerFor, runRoute } from "./route.mjs";
4
4
  import { NOT_FOUND_SEGMENT } from "./pathname.mjs";
5
5
  import { ACTION_ID_HEADER, CLIENT_DEPS_HEADER, NONCE_HEADER, NOT_FOUND_DIGEST, NOT_FOUND_HEADER, SHELL_HEADER, clientDepsHeader } from "./payload.mjs";
6
6
  import { isPayloadPath, pagePathFor } from "./payload-path.mjs";
7
- import { isRedirect } from "./redirect.mjs";
8
7
  import { noticeCancel } from "./cancel.mjs";
9
8
  import { runGuards } from "./guard.mjs";
10
9
  import { PageShown } from "./page-shown.mjs";
11
10
  import { watchPage } from "./page-watch.mjs";
12
11
  import { parseCatchAllParams, parseParams } from "./params.mjs";
13
- import { resolveRedirects } from "./redirect-file.mjs";
12
+ import { Redirect, resolveRedirects } from "./redirect.mjs";
14
13
  import { renderMatch, renderNotFound } from "./render.mjs";
15
14
  import { shellParams } from "./shell.mjs";
16
15
  import { isNotFound, normalizePathname, withBase, withoutBase } from "@k8ordo/router";
@@ -49,17 +48,11 @@ const NO_PARAMS = {
49
48
  * wrote to the async context, and nothing a refused pattern's did.
50
49
  *
51
50
  * A page's schema is an export of the page, and the table reads a page only
52
- * when a request reaches it; `routes.match` decides synchronously, so it is
53
- * asked for every pattern that fits, and the walk reads each file before
54
- * running the schemas along its stack, in the table's order.
51
+ * when a request reaches it, so the walk reads each file before running the
52
+ * schemas along its stack, in the table's order.
55
53
  */
56
54
  const find = async (pathname) => {
57
- const fits = [];
58
- routes.match(pathname, (fit) => {
59
- fits.push(fit);
60
- return false;
61
- });
62
- for (const fit of fits) {
55
+ for (const fit of routes.matchAll(pathname)) {
63
56
  if (fit.pattern.endsWith("/*")) return {
64
57
  match: fit,
65
58
  parsed: parseCatchAllParams(catchAllSchemas[fit.pattern] ?? [], fit.params)
@@ -144,7 +137,7 @@ const runAction = async (request, temporaryReferences) => {
144
137
  try {
145
138
  return await invokeAction(request, temporaryReferences);
146
139
  } catch (error) {
147
- if (isRedirect(error)) return { redirect: error.to };
140
+ if (error instanceof Redirect) return { redirect: error.to };
148
141
  throw error;
149
142
  }
150
143
  };
@@ -206,71 +199,50 @@ const renderFailed = (error) => new Response(error instanceof Error ? error.mess
206
199
  */
207
200
  function handler(request) {
208
201
  return withRequest(request, async () => answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
209
- console.error("k8ordo: answering %s failed", new URL(request.url).pathname, error);
202
+ reportFailed("answering", new URL(request.url).pathname, error);
210
203
  return renderFailed(error);
211
204
  })) : respond(request))));
212
205
  }
206
+ const reportFailed = (doing, pathname, error) => {
207
+ console.error(`k8ordo: ${doing} %s failed`, pathname, error);
208
+ };
209
+ const plainNotFound = (body) => new Response(body, {
210
+ status: 404,
211
+ headers: { "content-type": "text/plain;charset=utf-8" }
212
+ });
213
213
  const respond = async (request) => {
214
214
  const url = new URL(request.url);
215
215
  const own = withoutBase(url.pathname);
216
- if (own === null) return new Response("not found", {
217
- status: 404,
218
- headers: { "content-type": "text/plain;charset=utf-8" }
219
- });
216
+ if (own === null) return plainNotFound("not found");
220
217
  const wantsPayload = isPayloadPath(own);
221
218
  const pathname = wantsPayload ? pagePathFor(own) : own;
222
- const { match, parsed, leaf, shell } = await find(pathname);
219
+ const found = await find(pathname);
220
+ const { match, parsed, leaf, shell } = found;
223
221
  const declared = match === null ? null : redirectFor(match.pattern, pathname);
224
- if (declared !== null) {
225
- if (request.method !== "GET" && request.method !== "HEAD") return new Response("method not allowed", {
226
- status: 405,
227
- headers: { allow: "GET, HEAD" }
228
- });
229
- return redirectResponse(locationOf(declared.to), declared.permanent ? 308 : 307);
230
- }
231
- const module = match === null || routeModules[match.pattern] === void 0 ? void 0 : leaf;
232
- if (match !== null && module !== void 0) {
233
- if (wantsPayload) return new Response("not a page", {
234
- status: 404,
235
- headers: { "content-type": "text/plain;charset=utf-8" }
236
- });
237
- const found = routeAnswerFor(module, request.method);
238
- if (found === null) return methodNotAllowed(module);
239
- const guardedRoute = await parsed.enter(() => runGuards(guards[match.pattern] ?? [], {
240
- request,
241
- params: match.params
242
- }));
243
- if (guardedRoute !== null) return guardedRoute;
244
- return parsed.enter(() => runRoute(found, {
245
- request,
246
- params: parsed.params
247
- }));
248
- }
249
- if (!METHODS.includes(request.method)) return new Response("method not allowed", {
250
- status: 405,
251
- headers: { allow: METHODS.join(", ") }
252
- });
222
+ if (declared !== null) return answerRedirect(request, declared);
223
+ if (match !== null && leaf !== void 0 && routeModules[match.pattern] !== void 0) return answerRoute(request, match, parsed, leaf, wantsPayload);
224
+ const refused = await refusedBeforePage(request, url, found);
225
+ if (refused !== null) return refused;
253
226
  const isAction = request.method === "POST";
254
227
  const addressed = request.headers.get(ACTION_ID_HEADER) !== null;
255
- if (isAction && !sameOrigin(request, url)) return new Response("cross-origin action", { status: 403 });
256
- const guarded = await parsed.enter(() => runGuards(guards[match?.pattern ?? "/*"] ?? [], {
257
- request,
258
- params: match?.params ?? {}
259
- }));
260
- if (guarded !== null) return guarded;
261
228
  const temporaryReferences = createTemporaryReferenceSet();
262
229
  const action = isAction ? await parsed.enter(() => inPhase("action", () => runAction(request, temporaryReferences))) : {};
263
230
  if (action.redirect !== void 0 && !addressed) return redirectResponse(action.redirect, 303);
264
231
  const answersPayload = wantsPayload || addressed;
232
+ const contentType = answersPayload ? PAYLOAD_TYPE : HTML_TYPE;
265
233
  const missing = match === null || match.pattern.endsWith("/*");
266
234
  if (request.method === "HEAD" && missing) return new Response(null, {
267
235
  status: 404,
268
- headers: { "content-type": answersPayload ? PAYLOAD_TYPE : HTML_TYPE }
236
+ headers: { "content-type": contentType }
269
237
  });
270
238
  const routeRequest = import.meta.env.K8ORDO_MODE === "server" ? routeRequestOf(request) : fileRequest;
271
239
  const ssr = await import.meta.viteRsc.loadModule("ssr", "index");
272
240
  const readSearch = match === null || missing || leaf === void 0 ? void 0 : searchReaderOf(match.pattern, leaf);
273
241
  const search = readSearch?.(url.searchParams);
242
+ /**
243
+ * What the table answers for a URL nothing matched here — the nearest
244
+ * not-found.tsx — and the context its layouts' schemas leave.
245
+ */
274
246
  const nearestNotFound = async () => {
275
247
  const nearest = matchNotFound(pathname, shell !== void 0);
276
248
  return {
@@ -309,18 +281,9 @@ const respond = async (request) => {
309
281
  shell: shell !== void 0
310
282
  }) : null, enter, readSearch === void 0 ? void 0 : url.search, shell === void 0 ? void 0 : (await nearestNotFound()).tree);
311
283
  if (page !== null && (!answersPayload || request.method === "HEAD")) {
312
- const [forAnswer, forWatch] = rendered.stream.tee();
313
- rendered = {
314
- ...rendered,
315
- stream: forAnswer
316
- };
317
- const drained = drain(forWatch);
318
- const threw = await (import.meta.env.K8ORDO_MODE === "static" ? drained.then(() => Promise.race([page.settled, Promise.resolve()])) : Promise.race([
319
- page.settled,
320
- rendered.saidNotFound,
321
- drained
322
- ]));
323
- if (rendered.notFound() || isNotFound(threw)) {
284
+ const answered = await pageAnswer(rendered, page);
285
+ ({rendered} = answered);
286
+ if (answered.saidNotFound) {
324
287
  rendered.abort();
325
288
  const nearest = await nearestNotFound();
326
289
  status = 404;
@@ -329,14 +292,13 @@ const respond = async (request) => {
329
292
  rendered = render(nearest.tree, enter);
330
293
  }
331
294
  }
332
- const saidByPage = import.meta.env.K8ORDO_MODE === "static" && status === 404 && !missing ? { [NOT_FOUND_HEADER]: "page" } : {};
333
295
  const shellSaid = import.meta.env.K8ORDO_MODE === "static" && shell !== void 0 && status === 200 ? { [SHELL_HEADER]: shell.pattern } : {};
334
296
  if (request.method === "HEAD") {
335
297
  rendered.abort();
336
298
  return new Response(null, {
337
299
  status,
338
300
  headers: {
339
- "content-type": answersPayload ? PAYLOAD_TYPE : HTML_TYPE,
301
+ "content-type": contentType,
340
302
  ...shellSaid
341
303
  }
342
304
  });
@@ -344,38 +306,122 @@ const respond = async (request) => {
344
306
  if (answersPayload) return new Response(rendered.stream, {
345
307
  status,
346
308
  headers: {
347
- "content-type": PAYLOAD_TYPE,
309
+ "content-type": contentType,
348
310
  ...shellSaid
349
311
  }
350
312
  });
351
- if (import.meta.env.K8ORDO_MODE === "static") {
352
- const [forHtml, forNamed] = rendered.stream.tee();
353
- await drain(forNamed);
354
- const named = [...rendered.named.values()];
355
- let body;
356
- try {
357
- const html = await enter(() => ssr.renderHtml(forHtml, signingNonce(), showsPage, action.formState !== void 0, named));
358
- body = await new Response(html).arrayBuffer();
359
- } catch (error) {
360
- return renderFailed(rendered.failures[0] ?? error);
313
+ const saidByPage = import.meta.env.K8ORDO_MODE === "static" && status === 404 && !missing ? { [NOT_FOUND_HEADER]: "page" } : {};
314
+ return answerHtml(ssr, rendered, enter, {
315
+ status,
316
+ showsPage,
317
+ carriesFormState: action.formState !== void 0,
318
+ headers: {
319
+ ...saidByPage,
320
+ ...shellSaid
361
321
  }
362
- const failed = rendered.failures[0];
363
- if (failed !== void 0) return renderFailed(failed);
364
- return new Response(body, {
322
+ });
323
+ };
324
+ /** A `redirect.ts`'s answer: it answers a read and nothing else. */
325
+ const answerRedirect = (request, { to, permanent }) => {
326
+ if (request.method !== "GET" && request.method !== "HEAD") return new Response("method not allowed", {
327
+ status: 405,
328
+ headers: { allow: "GET, HEAD" }
329
+ });
330
+ return redirectResponse(locationOf(to), permanent ? 308 : 307);
331
+ };
332
+ /**
333
+ * A `route.ts`'s answer, by its own methods, from anywhere: no origin check,
334
+ * since what posts to it — a webhook — is not a form on this site, and it
335
+ * checks what it needs itself.
336
+ */
337
+ const answerRoute = async (request, match, parsed, module, wantsPayload) => {
338
+ if (wantsPayload) return plainNotFound("not a page");
339
+ const found = routeAnswerFor(module, request.method);
340
+ if (found === null) return methodNotAllowed(module);
341
+ const guarded = await parsed.enter(() => runGuards(guards[match.pattern] ?? [], {
342
+ request,
343
+ params: match.params
344
+ }));
345
+ if (guarded !== null) return guarded;
346
+ return parsed.enter(() => runRoute(found, {
347
+ request,
348
+ params: parsed.params
349
+ }));
350
+ };
351
+ /**
352
+ * What answers a page's request before anything renders, if anything does: a
353
+ * method a page does not take, a Server Action from another origin, a guard.
354
+ */
355
+ const refusedBeforePage = async (request, url, { match, parsed }) => {
356
+ if (!METHODS.includes(request.method)) return new Response("method not allowed", {
357
+ status: 405,
358
+ headers: { allow: METHODS.join(", ") }
359
+ });
360
+ if (request.method === "POST" && !sameOrigin(request, url)) return new Response("cross-origin action", { status: 403 });
361
+ return parsed.enter(() => runGuards(guards[match?.pattern ?? "/*"] ?? [], {
362
+ request,
363
+ params: match?.params ?? {}
364
+ }));
365
+ };
366
+ /**
367
+ * What a page said of itself, once a document can tell: the render, its
368
+ * stream still to be read, and whether the page said notFound().
369
+ */
370
+ const pageAnswer = async (rendered, page) => {
371
+ const [forAnswer, forWatch] = rendered.stream.tee();
372
+ const threw = await (import.meta.env.K8ORDO_MODE === "static" ? drain(forWatch) : Promise.race([
373
+ page.settled,
374
+ rendered.saidNotFound,
375
+ drain(forWatch)
376
+ ]));
377
+ return {
378
+ rendered: {
379
+ ...rendered,
380
+ stream: forAnswer
381
+ },
382
+ saidNotFound: rendered.notFound() || isNotFound(threw)
383
+ };
384
+ };
385
+ /** A document's HTML, rendered from its payload. */
386
+ const answerHtml = async (ssr, rendered, enter, { status, showsPage, carriesFormState, headers }) => {
387
+ if (import.meta.env.K8ORDO_MODE !== "static") {
388
+ const html = await enter(() => ssr.renderHtml(rendered.stream, {
389
+ nonce: signingNonce(),
390
+ showsPage,
391
+ carriesFormState
392
+ }));
393
+ return new Response(html, {
365
394
  status,
366
395
  headers: {
367
396
  "content-type": HTML_TYPE,
368
- [NONCE_HEADER]: signingNonce(),
369
- [CLIENT_DEPS_HEADER]: clientDepsHeader(rendered.named.values()),
370
- ...saidByPage,
371
- ...shellSaid
397
+ ...headers
372
398
  }
373
399
  });
374
400
  }
375
- const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0, []));
376
- return new Response(html, {
401
+ const [forHtml, forNamed] = rendered.stream.tee();
402
+ await drain(forNamed);
403
+ let body;
404
+ try {
405
+ const html = await enter(() => ssr.renderHtml(forHtml, {
406
+ nonce: signingNonce(),
407
+ showsPage,
408
+ carriesFormState,
409
+ named: [...rendered.named.values()]
410
+ }));
411
+ body = await new Response(html).arrayBuffer();
412
+ } catch (error) {
413
+ return renderFailed(rendered.failures[0] ?? error);
414
+ }
415
+ const failed = rendered.failures[0];
416
+ if (failed !== void 0) return renderFailed(failed);
417
+ return new Response(body, {
377
418
  status,
378
- headers: { "content-type": HTML_TYPE }
419
+ headers: {
420
+ "content-type": HTML_TYPE,
421
+ [NONCE_HEADER]: signingNonce(),
422
+ [CLIENT_DEPS_HEADER]: clientDepsHeader(rendered.named.values()),
423
+ ...headers
424
+ }
379
425
  });
380
426
  };
381
427
  /**
@@ -387,16 +433,18 @@ const respond = async (request) => {
387
433
  * value the shell answers.
388
434
  */
389
435
  const matchNotFound = (pathname, forShell) => {
390
- let parsed = NO_PARAMS;
391
436
  const page = normalizePathname(pathname);
437
+ for (const found of routes.matchAll(`${page === "/" ? "" : page}/${NOT_FOUND_SEGMENT}`)) {
438
+ if (!found.pattern.endsWith("/*")) continue;
439
+ if (forShell && Object.values(found.params).includes("!fallback")) continue;
440
+ return {
441
+ match: found,
442
+ parsed: parseCatchAllParams(catchAllSchemas[found.pattern] ?? [], found.params)
443
+ };
444
+ }
392
445
  return {
393
- match: routes.match(`${page === "/" ? "" : page}/${NOT_FOUND_SEGMENT}`, (found) => {
394
- if (!found.pattern.endsWith("/*")) return false;
395
- if (forShell && Object.values(found.params).includes("!fallback")) return false;
396
- parsed = parseCatchAllParams(catchAllSchemas[found.pattern] ?? [], found.params);
397
- return true;
398
- }),
399
- parsed
446
+ match: null,
447
+ parsed: NO_PARAMS
400
448
  };
401
449
  };
402
450
  const renderPayload = (payload, enter, temporaryReferences) => {
@@ -416,12 +464,10 @@ const renderPayload = (payload, enter, temporaryReferences) => {
416
464
  }
417
465
  if (controller.signal.aborted) return void 0;
418
466
  failures.push(error);
419
- console.error("k8ordo: rendering %s failed", payload.pathname, error);
467
+ reportFailed("rendering", payload.pathname, error);
420
468
  }
421
- }, import.meta.env.K8ORDO_MODE === "static" ? { onClientReference: ({ id, name, deps }) => {
422
- named.set(`${id}#${name}`, {
423
- id,
424
- name,
469
+ }, import.meta.env.K8ORDO_MODE === "static" ? { onClientReference: ({ id, deps }) => {
470
+ named.set(id, {
425
471
  js: deps.js,
426
472
  css: deps.css
427
473
  });
@@ -12,4 +12,24 @@ export declare const clientEntry: string;
12
12
  * one round trip. It is also what lets a prerendered `404.html` come alive —
13
13
  * there is no payload file at a URL the application does not have.
14
14
  */
15
- export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, nonce: string, showsPage: boolean, carriesFormState: boolean, named: readonly ClientDeps[]): Promise<ReadableStream>;
15
+ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonce, showsPage, carriesFormState, named }: {
16
+ /**
17
+ * The request's: every script written here carries it. What else does,
18
+ * the application signed, and the policy that names it is the
19
+ * application's.
20
+ */
21
+ readonly nonce: string;
22
+ /** Whether the payload holds the page, followed by `PageShown`. */
23
+ readonly showsPage: boolean;
24
+ /**
25
+ * Whether the payload carries a `formState`: a form was posted without
26
+ * JavaScript, and `useActionState` finds its result in the HTML it comes
27
+ * back to.
28
+ */
29
+ readonly carriesFormState: boolean;
30
+ /**
31
+ * Under mode: 'static', every client component the payload names, read
32
+ * to its end: the HTML links each, rendered or not.
33
+ */
34
+ readonly named?: readonly ClientDeps[];
35
+ }): Promise<ReadableStream>;
@@ -1,8 +1,10 @@
1
+ import { CLIENT_STYLESHEETS } from "./stylesheets.mjs";
1
2
  import { whenClientReady } from "./client-ready.mjs";
2
3
  import { AppRouter } from "./app-router.mjs";
3
4
  import { noticeCancel } from "./cancel.mjs";
4
5
  import { DocumentRoot } from "./document-root.mjs";
5
6
  import { PageShownContext } from "./page-shown.mjs";
7
+ import { scriptsBeforeStylesheetsStream } from "./head-scripts.mjs";
6
8
  import { use } from "react";
7
9
  import { jsx } from "react/jsx-runtime";
8
10
  import { createFromReadableStream, getClientEntryUrl } from "@vitejs/plugin-rsc/ssr";
@@ -38,7 +40,7 @@ const linkClientDeps = (named) => {
38
40
  for (const href of css) preinit(href, {
39
41
  as: "style",
40
42
  crossOrigin: "anonymous",
41
- precedence: "vite-rsc/client-reference"
43
+ precedence: CLIENT_STYLESHEETS
42
44
  });
43
45
  }
44
46
  };
@@ -49,7 +51,7 @@ const linkClientDeps = (named) => {
49
51
  * one round trip. It is also what lets a prerendered `404.html` come alive —
50
52
  * there is no payload file at a URL the application does not have.
51
53
  */
52
- async function renderHtml(rscStream, nonce, showsPage, carriesFormState, named) {
54
+ async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named = [] }) {
53
55
  const [forRender, forHydration] = rscStream.tee();
54
56
  let forHtml = forRender;
55
57
  let formState;
@@ -58,20 +60,15 @@ async function renderHtml(rscStream, nonce, showsPage, carriesFormState, named)
58
60
  forHtml = rest;
59
61
  ({formState} = await createFromReadableStream(forState, { nonce }));
60
62
  }
61
- let payload;
63
+ let reading;
62
64
  let ready;
63
65
  function Root() {
64
66
  linkClientDeps(named);
65
- payload ??= createFromReadableStream(forHtml, { nonce });
66
- const { notFound, pathname, search, tree } = use(payload);
67
- ready ??= whenClientReady([tree, notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
67
+ reading ??= createFromReadableStream(forHtml, { nonce });
68
+ const payload = use(reading);
69
+ ready ??= whenClientReady([payload.tree, payload.notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
68
70
  use(ready);
69
- return /* @__PURE__ */ jsx(AppRouter, {
70
- notFound,
71
- pathname,
72
- search,
73
- tree
74
- });
71
+ return /* @__PURE__ */ jsx(AppRouter, { arrived: payload });
75
72
  }
76
73
  const shown = Promise.withResolvers();
77
74
  let readerLeft = false;
@@ -96,7 +93,7 @@ async function renderHtml(rscStream, nonce, showsPage, carriesFormState, named)
96
93
  });
97
94
  if (import.meta.env.K8ORDO_MODE === "static") await htmlStream.allReady;
98
95
  else if (showsPage) await Promise.race([shown.promise, htmlStream.allReady.catch(() => void 0)]);
99
- return noticeCancel(htmlStream.pipeThrough(injectRSCPayload(forHydration, { nonce })), () => {
96
+ return noticeCancel(htmlStream.pipeThrough(scriptsBeforeStylesheetsStream()).pipeThrough(injectRSCPayload(forHydration, { nonce })), () => {
100
97
  readerLeft = true;
101
98
  });
102
99
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The document with every inline classic script of its `<head>` — no `src`,
3
+ * no `type` — moved ahead of the first stylesheet there, in the order they
4
+ * were written. React writes what it hoists into `<head>` (the stylesheets
5
+ * among it) before the head's own children, and a script after a stylesheet
6
+ * waits for that stylesheet to load, while the browser may paint the page
7
+ * without what the script would have set. What a `<noscript>` or a
8
+ * `<template>` holds stays where it is, and so does everything outside the
9
+ * `<head>`.
10
+ */
11
+ export declare const scriptsBeforeStylesheets: (html: string) => string;
12
+ /**
13
+ * `scriptsBeforeStylesheets` over a stream of HTML: it holds the bytes back
14
+ * only until the `<head>` has arrived whole, and passes the rest on as they
15
+ * come — a document that does not open with a `<head>`, from its first
16
+ * bytes.
17
+ */
18
+ export declare const scriptsBeforeStylesheetsStream: () => TransformStream<Uint8Array, Uint8Array>;
@@ -0,0 +1,159 @@
1
+ // src/runtime/head-scripts.ts
2
+ const OPAQUE = /* @__PURE__ */ new Set([
3
+ "noscript",
4
+ "script",
5
+ "style",
6
+ "template",
7
+ "textarea",
8
+ "title"
9
+ ]);
10
+ const TAG = /<(\/?)([A-Za-z][^\t\n\f\r />]*)/uy;
11
+ const ATTRIBUTE = /([^\t\n\f\r "'>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/gu;
12
+ const ENDS_TAG_NAME = /* @__PURE__ */ new Set([
13
+ " ",
14
+ "\n",
15
+ "\f",
16
+ "\r",
17
+ " ",
18
+ "/",
19
+ ">"
20
+ ]);
21
+ const attributesOf = (source) => new Map([...source.matchAll(ATTRIBUTE)].map(([, name = "", double, single, bare]) => [name.toLowerCase(), double ?? single ?? bare ?? ""]));
22
+ /** Where the next `</name` starts, in any case, or -1 when it has not arrived. */
23
+ const closingAt = (html, name, from) => {
24
+ for (let at = html.indexOf("</", from); at !== -1; at = html.indexOf("</", at + 2)) {
25
+ const after = at + 2 + name.length;
26
+ if (html.slice(at + 2, after).toLowerCase() === name && ENDS_TAG_NAME.has(html.charAt(after))) return at;
27
+ }
28
+ return -1;
29
+ };
30
+ const readHead = (html) => {
31
+ const elements = [];
32
+ let inHead = false;
33
+ let at = html.indexOf("<");
34
+ while (at !== -1) {
35
+ if (html.startsWith("<!--", at)) {
36
+ const close = html.indexOf("-->", at + 4);
37
+ if (close === -1) return "partial";
38
+ at = html.indexOf("<", close + 3);
39
+ continue;
40
+ }
41
+ TAG.lastIndex = at;
42
+ const tag = TAG.exec(html);
43
+ if (!(tag !== null || html.startsWith("<!", at))) {
44
+ if (at + 1 === html.length) return "partial";
45
+ at = html.indexOf("<", at + 1);
46
+ continue;
47
+ }
48
+ const close = html.indexOf(">", at);
49
+ if (close === -1) return "partial";
50
+ if (tag === null) {
51
+ at = html.indexOf("<", close + 1);
52
+ continue;
53
+ }
54
+ const [opening, slash, written = ""] = tag;
55
+ const closes = slash === "/";
56
+ const name = written.toLowerCase();
57
+ let end = close + 1;
58
+ if (!inHead) {
59
+ if (closes || name !== "html" && name !== "head") return "none";
60
+ inHead = name === "head";
61
+ } else if (closes) {
62
+ if (name === "head") return {
63
+ elements,
64
+ end
65
+ };
66
+ } else {
67
+ if (OPAQUE.has(name)) {
68
+ const closing = closingAt(html, name, end);
69
+ if (closing === -1) return "partial";
70
+ const closed = html.indexOf(">", closing);
71
+ if (closed === -1) return "partial";
72
+ end = closed + 1;
73
+ }
74
+ elements.push({
75
+ name,
76
+ start: at,
77
+ end,
78
+ attributes: attributesOf(html.slice(at + opening.length, close))
79
+ });
80
+ }
81
+ at = html.indexOf("<", end);
82
+ }
83
+ return "partial";
84
+ };
85
+ const isStylesheet = ({ name, attributes }) => name === "style" || name === "link" && (attributes.get("rel") ?? "").toLowerCase().split(/[\t\n\f\r ]+/u).includes("stylesheet");
86
+ /** A script the parser runs where it stands: inline, and classic. */
87
+ const runsInPlace = ({ name, attributes }) => name === "script" && !attributes.has("src") && !attributes.has("type");
88
+ const withScriptsFirst = (html, { elements }) => {
89
+ const first = elements.find(isStylesheet);
90
+ if (first === void 0) return html;
91
+ const scripts = elements.filter((element) => runsInPlace(element) && element.start > first.start);
92
+ if (scripts.length === 0) return html;
93
+ let written = html.slice(0, first.start) + scripts.map(({ start, end }) => html.slice(start, end)).join("");
94
+ let from = first.start;
95
+ for (const { start, end } of scripts) {
96
+ written += html.slice(from, start);
97
+ from = end;
98
+ }
99
+ return written + html.slice(from);
100
+ };
101
+ /**
102
+ * The document with every inline classic script of its `<head>` — no `src`,
103
+ * no `type` — moved ahead of the first stylesheet there, in the order they
104
+ * were written. React writes what it hoists into `<head>` (the stylesheets
105
+ * among it) before the head's own children, and a script after a stylesheet
106
+ * waits for that stylesheet to load, while the browser may paint the page
107
+ * without what the script would have set. What a `<noscript>` or a
108
+ * `<template>` holds stays where it is, and so does everything outside the
109
+ * `<head>`.
110
+ */
111
+ const scriptsBeforeStylesheets = (html) => {
112
+ const head = readHead(html);
113
+ return typeof head === "string" ? html : withScriptsFirst(html, head);
114
+ };
115
+ const joined = (held, chunk) => {
116
+ const bytes = new Uint8Array(held.length + chunk.length);
117
+ bytes.set(held);
118
+ bytes.set(chunk, held.length);
119
+ return bytes;
120
+ };
121
+ /**
122
+ * `scriptsBeforeStylesheets` over a stream of HTML: it holds the bytes back
123
+ * only until the `<head>` has arrived whole, and passes the rest on as they
124
+ * come — a document that does not open with a `<head>`, from its first
125
+ * bytes.
126
+ */
127
+ const scriptsBeforeStylesheetsStream = () => {
128
+ const decoder = new TextDecoder();
129
+ const encoder = new TextEncoder();
130
+ let held = /* @__PURE__ */ new Uint8Array(0);
131
+ return new TransformStream({
132
+ transform(chunk, controller) {
133
+ if (held === void 0) {
134
+ controller.enqueue(chunk);
135
+ return;
136
+ }
137
+ const bytes = joined(held, chunk);
138
+ const text = decoder.decode(bytes);
139
+ const head = readHead(text);
140
+ if (head === "partial") {
141
+ held = bytes;
142
+ return;
143
+ }
144
+ held = void 0;
145
+ if (head === "none") {
146
+ controller.enqueue(bytes);
147
+ return;
148
+ }
149
+ const through = text.slice(0, head.end);
150
+ controller.enqueue(encoder.encode(withScriptsFirst(through, head)));
151
+ const rest = bytes.subarray(encoder.encode(through).length);
152
+ if (rest.length > 0) controller.enqueue(rest);
153
+ },
154
+ flush(controller) {
155
+ if (held !== void 0 && held.length > 0) controller.enqueue(held);
156
+ }
157
+ });
158
+ };
159
+ export { scriptsBeforeStylesheets, scriptsBeforeStylesheetsStream };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Has `@k8ordo/i18n` read `pathname` as the URL while HTML rendered for it
3
+ * is hydrated somewhere else. `usePathname` reads it from `PathnameProvider`
4
+ * then; a message is no hook, and reads it from here.
5
+ */
6
+ export declare const hydrateAs: (pathname: string) => void;
7
+ /** Hands the URL back to `@k8ordo/i18n`: the HTML on screen is hydrated. */
8
+ export declare const doneHydrating: () => void;
9
+ /**
10
+ * Settles once the HTML `hydrateAs` named a pathname for is hydrated —
11
+ * `undefined` when there is none — and a tree is applied only then. Applied
12
+ * before, it renders at the pathname the HTML was rendered for; and were the
13
+ * URL handed back before, a boundary whose hydration the applying update
14
+ * interrupted would be hydrated again at the URL, against that HTML.
15
+ */
16
+ export declare const whenHydrated: () => Promise<undefined> | undefined;
@@ -0,0 +1,26 @@
1
+ // src/runtime/hydrating-pathname.ts
2
+ const KEY = Symbol.for("@k8ordo/i18n/hydrating-pathname");
3
+ let hydrated;
4
+ /**
5
+ * Has `@k8ordo/i18n` read `pathname` as the URL while HTML rendered for it
6
+ * is hydrated somewhere else. `usePathname` reads it from `PathnameProvider`
7
+ * then; a message is no hook, and reads it from here.
8
+ */
9
+ const hydrateAs = (pathname) => {
10
+ globalThis[KEY] = pathname;
11
+ hydrated = Promise.withResolvers();
12
+ };
13
+ /** Hands the URL back to `@k8ordo/i18n`: the HTML on screen is hydrated. */
14
+ const doneHydrating = () => {
15
+ globalThis[KEY] = void 0;
16
+ hydrated?.resolve(void 0);
17
+ };
18
+ /**
19
+ * Settles once the HTML `hydrateAs` named a pathname for is hydrated —
20
+ * `undefined` when there is none — and a tree is applied only then. Applied
21
+ * before, it renders at the pathname the HTML was rendered for; and were the
22
+ * URL handed back before, a boundary whose hydration the applying update
23
+ * interrupted would be hydrated again at the URL, against that HTML.
24
+ */
25
+ const whenHydrated = () => hydrated?.promise;
26
+ export { doneHydrating, hydrateAs, whenHydrated };