@krate/runtime 0.5.0-rc.13 → 0.5.0-rc.15

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 (83) hide show
  1. package/dist/action-context.d.ts +2 -0
  2. package/dist/action-context.js +12 -1
  3. package/dist/action-seal.d.ts +5 -0
  4. package/dist/action-seal.js +105 -0
  5. package/dist/actions.js +7 -1
  6. package/dist/cache-scope.d.ts +2 -0
  7. package/dist/dev/api.d.ts +93 -0
  8. package/dist/dev/api.js +2 -0
  9. package/dist/dev/app.d.ts +165 -0
  10. package/dist/dev/app.js +1204 -0
  11. package/dist/dev/commands.d.ts +49 -0
  12. package/dist/dev/commands.js +114 -0
  13. package/dist/dev/highlight.d.ts +4 -0
  14. package/dist/dev/highlight.js +126 -0
  15. package/dist/dev/icons.d.ts +4 -0
  16. package/dist/dev/icons.js +57 -0
  17. package/dist/dev/inspect.d.ts +55 -0
  18. package/dist/dev/inspect.js +256 -0
  19. package/dist/dev/inspector.d.ts +39 -0
  20. package/dist/dev/inspector.js +348 -0
  21. package/dist/dev/issues.d.ts +83 -0
  22. package/dist/dev/issues.js +166 -0
  23. package/dist/dev/modal.d.ts +16 -0
  24. package/dist/dev/modal.js +836 -0
  25. package/dist/dev/native.d.ts +53 -0
  26. package/dist/dev/native.js +95 -0
  27. package/dist/dev/palette.d.ts +9 -0
  28. package/dist/dev/palette.js +250 -0
  29. package/dist/dev/panel.d.ts +31 -0
  30. package/dist/dev/panel.js +848 -0
  31. package/dist/dev/requests.d.ts +36 -0
  32. package/dist/dev/requests.js +150 -0
  33. package/dist/dev/settings.d.ts +32 -0
  34. package/dist/dev/settings.js +78 -0
  35. package/dist/dev/sourcemap.d.ts +22 -0
  36. package/dist/dev/sourcemap.js +148 -0
  37. package/dist/dev/stack.d.ts +38 -0
  38. package/dist/dev/stack.js +115 -0
  39. package/dist/dev/styles.d.ts +1 -0
  40. package/dist/dev/styles.js +424 -0
  41. package/dist/dev/util.d.ts +63 -0
  42. package/dist/dev/util.js +190 -0
  43. package/dist/dev-overlay.d.ts +9 -83
  44. package/dist/dev-overlay.js +17 -1038
  45. package/dist/flight-props.d.ts +2 -0
  46. package/dist/flight-props.js +12 -1
  47. package/dist/handler-routing.js +7 -1
  48. package/dist/island-swap.js +10 -1
  49. package/dist/krate-core.js +1 -1
  50. package/dist/krate-dev.js +441 -871
  51. package/dist/krate-f-actions.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router.js +1 -1
  55. package/dist/krate-hydrate-lite.js +5 -5
  56. package/dist/krate-hydrate.js +5 -5
  57. package/dist/krate-island-swap.js +1 -1
  58. package/dist/krate-runtime.js +5 -5
  59. package/dist/list.js +23 -1
  60. package/dist/metadata.js +23 -12
  61. package/dist/navigation-server.d.ts +1 -2
  62. package/dist/navigation-server.js +1 -2
  63. package/dist/navigation.d.ts +1 -1
  64. package/dist/navigation.js +7 -2
  65. package/dist/process-guard.d.ts +23 -0
  66. package/dist/process-guard.js +45 -0
  67. package/dist/react-types.d.ts +29 -0
  68. package/dist/react-types.js +1 -0
  69. package/dist/react.d.ts +2 -0
  70. package/dist/react.js +3 -0
  71. package/dist/request-context.d.ts +15 -0
  72. package/dist/request-context.js +41 -0
  73. package/dist/router.js +17 -0
  74. package/dist/server-handler.d.ts +4 -0
  75. package/dist/server-handler.js +43 -8
  76. package/dist/server-renderer.js +94 -2
  77. package/dist/server.d.ts +1 -1
  78. package/dist/server.js +57 -11
  79. package/dist/signal.d.ts +8 -0
  80. package/dist/signal.js +4 -0
  81. package/dist/ssr-core.d.ts +5 -0
  82. package/dist/ssr-core.js +49 -7
  83. package/package.json +5 -1
@@ -5,6 +5,7 @@ import cluster from "node:cluster";
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import vm from "node:vm";
8
+ import nodeModule from "node:module";
8
9
  import { pathToFileURL } from "node:url";
9
10
  import { AsyncLocalStorage } from "node:async_hooks";
10
11
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -14,11 +15,13 @@ import { installRenderStore, patchFetch } from "./cache-scope.js";
14
15
  import { cacheSpecFromEnv } from "./cache-adapter.js";
15
16
  import { isrStoreFor } from "./shared-isr.js";
16
17
  import { registerLanguage, setFenceResolver } from "./highlight.js";
18
+ import { installProcessGuards } from "./process-guard.js";
17
19
  // Render cache scopes (tags / revalidate windows read during a render) and the
18
20
  // Next-style fetch data cache. Installed once per process; page bundles share
19
21
  // the state through globalThis.
20
22
  installRenderStore(new AsyncLocalStorage());
21
23
  patchFetch();
24
+ installProcessGuards();
22
25
  // Shared secret for the mutating internal endpoints (/__krate/ssr/revalidate,
23
26
  // /refresh, /invalidate, /cache-invalidate). Krate passes it from the Go host;
24
27
  // a renderer started by hand without it keeps the endpoints open.
@@ -126,6 +129,24 @@ if (PARENT_PID > 0) {
126
129
  parentWatch.unref();
127
130
  }
128
131
  let manifest = null;
132
+ // manifestFile returns the server manifest on disk: KRATE_MANIFEST, else the
133
+ // one under the output directory.
134
+ function manifestFile() {
135
+ if (manifestPath && fs.existsSync(manifestPath))
136
+ return manifestPath;
137
+ const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
138
+ return fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
139
+ }
140
+ let manifestStamp = "";
141
+ function statStamp(file) {
142
+ try {
143
+ const st = fs.statSync(file);
144
+ return `${st.mtimeMs}:${st.size}`;
145
+ }
146
+ catch {
147
+ return "";
148
+ }
149
+ }
129
150
  if (manifestPath && fs.existsSync(manifestPath)) {
130
151
  const data = fs.readFileSync(manifestPath, "utf-8");
131
152
  manifest = JSON.parse(data);
@@ -197,6 +218,49 @@ async function loadPageModule(page) {
197
218
  throw err;
198
219
  }
199
220
  }
221
+ // A page bundle is re-imported with a new query on every dev rebuild, but the
222
+ // modules it imports (the client component render modules under
223
+ // server-bundles/client/ and their chunks) were cached by URL for good: an
224
+ // edited client component kept rendering its old code, and a module first
225
+ // loaded after a rebuild came from a newer build than the layout's, so two
226
+ // copies of a module that creates a context could meet in one render. Once
227
+ // the first dev rebuild arrives, imports inside server-bundles take over the
228
+ // query of the module that imports them, so each reload of a page bundle
229
+ // loads its whole graph afresh and the graph is consistent. Node only; other
230
+ // runtimes keep the cached behaviour.
231
+ let bundleGraphVersioned = false;
232
+ function versionBundleGraph() {
233
+ if (bundleGraphVersioned)
234
+ return;
235
+ bundleGraphVersioned = true;
236
+ const register = nodeModule.register;
237
+ if (typeof register !== "function")
238
+ return;
239
+ const hooks = "let prefixes = [];\n" +
240
+ "export function initialize(data) { prefixes = data.prefixes; }\n" +
241
+ "export async function resolve(specifier, context, nextResolve) {\n" +
242
+ " const out = await nextResolve(specifier, context);\n" +
243
+ " const parent = context.parentURL ? new URL(context.parentURL) : null;\n" +
244
+ " if (parent && parent.search && prefixes.some((p) => out.url.startsWith(p)) && !out.url.includes('?')) return { ...out, url: out.url + parent.search };\n" +
245
+ " return out;\n" +
246
+ "}\n";
247
+ try {
248
+ // Node resolves module URLs to real paths, so a symlinked project root
249
+ // (macOS /var is /private/var) needs the real path as well.
250
+ const dir = path.join(OUT_DIR, ".krate", "server-bundles");
251
+ const prefixes = [pathToFileURL(dir).href + "/"];
252
+ try {
253
+ const real = pathToFileURL(fs.realpathSync(dir)).href + "/";
254
+ if (real !== prefixes[0])
255
+ prefixes.push(real);
256
+ }
257
+ catch { }
258
+ register("data:text/javascript," + encodeURIComponent(hooks), { parentURL: import.meta.url, data: { prefixes } });
259
+ }
260
+ catch (err) {
261
+ console.error("[krate-ssr] Could not version the page module graph; client components may render stale code in dev:", err.message);
262
+ }
263
+ }
200
264
  const runtimeBundleCache = new Map();
201
265
  // loadRuntimeRenderer loads a compiled runtime component bundle and returns its
202
266
  // __krate_render(props) function (props as an object or JSON). Bundles are cached by bundle path.
@@ -243,16 +307,37 @@ const core = createSSRCore({
243
307
  });
244
308
  const isrCache = isrMemory.cache;
245
309
  const { findPage, renderPage, renderRegion, renderPageRegion } = core;
310
+ manifestStamp = statStamp(manifestFile());
311
+ // reloadManifest re-reads the server manifest when a dev rebuild changed it,
312
+ // so pages added while `krate dev` runs resolve without a restart. A manifest
313
+ // that cannot be read keeps the last good one.
314
+ function reloadManifest() {
315
+ const file = manifestFile();
316
+ const stamp = statStamp(file);
317
+ if (!stamp || stamp === manifestStamp)
318
+ return;
319
+ try {
320
+ const next = JSON.parse(fs.readFileSync(file, "utf-8"));
321
+ manifest = next;
322
+ core.setManifest(next);
323
+ manifestStamp = stamp;
324
+ console.log(`[krate-ssr] Reloaded manifest: ${next.pages.length} SSR/ISR/streaming pages`);
325
+ }
326
+ catch (err) {
327
+ console.error("[krate-ssr] Manifest not reloaded, keeping the last good one:", err.message);
328
+ }
329
+ }
246
330
  // ISR cache persistence - survives renderer restarts so a bounce doesn't
247
331
  // cold-render every ISR variant. Written debounced (coalesced) to the build
248
332
  // output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
333
+ const PRERENDER_MODE = process.env.KRATE_PRERENDER === "1";
249
334
  const isrCacheFile = process.env.KRATE_ISR_CACHE || "";
250
335
  let persistTimer = null;
251
336
  function isrCachePath() {
252
337
  return isrCacheFile || path.join(OUT_DIR, ".krate", "isr-cache.json");
253
338
  }
254
339
  function persistIsrNow() {
255
- if (SSR_WORKERS > 1)
340
+ if (PRERENDER_MODE || SSR_WORKERS > 1)
256
341
  return;
257
342
  if (persistTimer) {
258
343
  clearTimeout(persistTimer);
@@ -271,13 +356,15 @@ function persistIsrNow() {
271
356
  function scheduleIsrPersist() {
272
357
  // Clustered: multiple workers would race on the same cache file; keep the ISR
273
358
  // cache in memory only.
274
- if (SSR_WORKERS > 1)
359
+ if (PRERENDER_MODE || SSR_WORKERS > 1)
275
360
  return;
276
361
  if (persistTimer)
277
362
  clearTimeout(persistTimer);
278
363
  persistTimer = setTimeout(persistIsrNow, 1000);
279
364
  }
280
365
  function loadIsrCache() {
366
+ if (PRERENDER_MODE)
367
+ return;
281
368
  try {
282
369
  const file = isrCachePath();
283
370
  if (fs.existsSync(file)) {
@@ -304,6 +391,10 @@ async function applyInternalOp(op, payload) {
304
391
  if (op !== "dev-invalidate")
305
392
  return core.applyInternalOp(op, payload);
306
393
  const { route: targetRoute, source, bundlePath } = payload;
394
+ reloadManifest();
395
+ versionBundleGraph();
396
+ if (!targetRoute)
397
+ return { ok: true };
307
398
  // Invalidate the page and region caches for this route, then the module
308
399
  // cache for the source file or bundle.
309
400
  const key = bundlePath || source;
@@ -456,6 +547,7 @@ const server = http.createServer(async (req, res) => {
456
547
  params: parsed.params,
457
548
  query: parsed.query,
458
549
  regions: parsed.regions,
550
+ prerender: !!parsed.prerender,
459
551
  };
460
552
  const page = findPage(renderReq.route);
461
553
  if (!page) {
package/dist/server.d.ts CHANGED
@@ -97,7 +97,7 @@ export declare function lazy<P = Record<string, any>>(loader: () => Promise<{
97
97
  } | ((props: P) => unknown)>): (props: P & {
98
98
  children?: JSXNode;
99
99
  }) => Promise<JSXNode>;
100
- type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null, fwd?: SlotValues, capture?: Record<string, SlotValues>) => string;
100
+ type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null, fwd?: SlotValues, capture?: Record<string, SlotValues>, ids?: string) => string;
101
101
  type SlotValues = {
102
102
  k: string;
103
103
  v: unknown;
package/dist/server.js CHANGED
@@ -3,9 +3,10 @@
3
3
  import { ATTR_ALIASES } from './htmlspec-attributes.js';
4
4
  import { withBase } from './base-path.js';
5
5
  import { highlight as highlightCode, trimSpace } from './highlight.js';
6
- import { accessDeniedStatus, isNotFoundSignal, redirectTarget } from './request-context.js';
6
+ import { sealBoundArgs } from './action-seal.js';
7
+ import { accessDeniedStatus, isDynamicUsageError, isNotFoundSignal, redirectTarget } from './request-context.js';
7
8
  import { sha256Hex } from './sha256.js';
8
- import { markErrorCaught } from './cache-scope.js';
9
+ import { currentRenderScope, markErrorCaught } from './cache-scope.js';
9
10
  import { encodeProp } from './flight-props.js';
10
11
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
11
12
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
@@ -323,7 +324,7 @@ export class ServerErrorBoundary {
323
324
  this.props = props;
324
325
  }
325
326
  static getDerivedStateFromError(error) {
326
- if (isNotFoundSignal(error) || accessDeniedStatus(error) || redirectTarget(error))
327
+ if (isNotFoundSignal(error) || accessDeniedStatus(error) || redirectTarget(error) || isDynamicUsageError(error))
327
328
  throw error;
328
329
  return { error: describeBoundaryError(error) };
329
330
  }
@@ -514,7 +515,7 @@ async function expandComponent(node, vals) {
514
515
  return { out: consumerChild(callProps)(vals?.has(ctx) ? vals.get(ctx) : ctx._currentValue), vals };
515
516
  }
516
517
  // A client boundary also gets the context values in scope (slotValues).
517
- let out = fn.__krateClient ? fn(callProps, vals) : fn(callProps);
518
+ let out = fn.__krateClient ? fn(callProps, vals, RENDER_CALL) : fn(callProps);
518
519
  if (isThenable(out))
519
520
  out = await out;
520
521
  if (fn.__krateForeignProvider) {
@@ -562,7 +563,7 @@ function renderElement(el) {
562
563
  return renderNode(classFallback(type, instance, error));
563
564
  }
564
565
  }
565
- const result = type({ ...props, children });
566
+ const result = type.__krateClient ? type({ ...props, children }, undefined, RENDER_CALL) : type({ ...props, children });
566
567
  if (isThenable(result))
567
568
  throw asyncInSyncRender(`<${componentName(type)}>`);
568
569
  return withProviderValue(type, props, () => renderNode(result));
@@ -670,6 +671,7 @@ function serializeClientProp(v, path, component) {
670
671
  return undefined;
671
672
  return encodeProp(v, path, {
672
673
  isAction: flightIsAction,
674
+ sealBound: sealBoundArgs,
673
675
  isJSX: flightIsJSX,
674
676
  fail: (p, what, hint) => clientPropError(p, component, what, hint),
675
677
  });
@@ -834,14 +836,45 @@ export const ISLAND_CLOSE = "<!--/krate-island-->";
834
836
  // islandOpen is the opening comment of a Preact island: its module, export,
835
837
  // chunk and props as JSON. "<", ">" and "--" are escaped (they occur only in
836
838
  // strings), so no value can end the comment or open another one.
837
- function islandOpen(moduleId, exportName, src, props) {
838
- const json = JSON.stringify({ m: moduleId, e: exportName, s: src, p: props })
839
+ function islandOpen(moduleId, exportName, src, props, ids) {
840
+ const json = JSON.stringify({ m: moduleId, e: exportName, s: src, i: ids, p: props })
839
841
  .replace(/</g, "\\u003c")
840
842
  .replace(/>/g, "\\u003e")
841
843
  .replace(/--/g, "-\\u002d");
842
844
  return `<!--${ISLAND_OPEN}${json}-->`;
843
845
  }
846
+ // islandIdPrefix names the next island of a component in the render that is
847
+ // running: a hash of its module and export, and how many islands of that
848
+ // component came before it in this document. useId() numbers from 0 inside
849
+ // each island, so the prefix is what keeps ids unique across the page. The
850
+ // router pairs the n-th island of a component in the live page with the n-th
851
+ // one in the new markup, so a page that a navigation swaps in never reuses the
852
+ // prefix of an island the swap keeps.
853
+ const looseIslands = new Map();
854
+ function islandIdPrefix(moduleId, exportName) {
855
+ const key = moduleId + "#" + exportName;
856
+ const scope = currentRenderScope();
857
+ const seen = scope ? (scope.islands ?? (scope.islands = new Map())) : looseIslands;
858
+ const n = seen.get(key) ?? 0;
859
+ seen.set(key, n + 1);
860
+ let h = 0x811C9DC5;
861
+ for (let i = 0; i < key.length; i++)
862
+ h = Math.imul(h ^ key.charCodeAt(i), 0x01000193) >>> 0;
863
+ return h.toString(36).padStart(7, "0") + "_" + n;
864
+ }
844
865
  const warnedUncloneable = new Set();
866
+ // RENDER_CALL is the third argument the renderer passes when it renders a
867
+ // client boundary as a component (a registered symbol: the renderer bundles its own
868
+ // copy of this module). A call without it is user code calling an
869
+ // export of a "use client" module as a function.
870
+ const RENDER_CALL = Symbol.for("krate.render");
871
+ function clientCallError(exportName, name) {
872
+ const what = exportName === "default" ? name : exportName;
873
+ return new Error(`Attempted to call ${what}() from the server but ${what} is on the client. ` +
874
+ `It is exported by a "use client" module, so a server component can render it as <${what} /> ` +
875
+ `or pass it to a client component, but cannot call it. ` +
876
+ `Move the function into a module without "use client" and import it from both sides.`);
877
+ }
845
878
  // warnUncloneable reports an asChild component whose child reached the
846
879
  // client as server-rendered HTML (raw HTML, a deferred slot), which its Slot
847
880
  // cannot clone or merge props into.
@@ -897,7 +930,17 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
897
930
  if (typeof impl !== "function")
898
931
  return impl;
899
932
  const name = impl.displayName || impl.name || exportName;
900
- const Boundary = async (props, vals) => {
933
+ // Called by user code, the boundary fails here and now. An async function
934
+ // would hand back a rejected promise the caller never awaits, and that
935
+ // unhandled rejection would take the renderer process down.
936
+ const Boundary = (props, vals, from) => {
937
+ if (from !== RENDER_CALL)
938
+ throw clientCallError(exportName, name);
939
+ return renderBoundary(props, vals);
940
+ };
941
+ const renderBoundary = async (props, vals) => {
942
+ // Taken before the first await, so islands number in render order.
943
+ const ids = islandIdPrefix(moduleId, exportName);
901
944
  const { children, ...rest } = props || {};
902
945
  const slots = [];
903
946
  const slotCtx = { hydrate: false, component: name, slots, vals };
@@ -919,7 +962,7 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
919
962
  }
920
963
  const fwd = vals?.get(slotValues);
921
964
  const capture = {};
922
- let html = render(impl, data, null, fwd, capture);
965
+ let html = render(impl, data, null, fwd, capture, ids);
923
966
  const rendered = await Promise.all(slots.map(async (s) => {
924
967
  const scope = mergeSlotValues(fwd, capture[s.token]);
925
968
  const base = s.vals ?? vals;
@@ -941,7 +984,7 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
941
984
  // element of its own; a Preact island hydrates the nodes between its two
942
985
  // comments in place.
943
986
  if (!flight)
944
- return raw(islandOpen(moduleId, exportName, src, data) + html + ISLAND_CLOSE);
987
+ return raw(islandOpen(moduleId, exportName, src, data, ids) + html + ISLAND_CLOSE);
945
988
  return raw(propsScript(data) +
946
989
  `<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
947
990
  `data-src="${escapeHTML(src)}">${html}</krate-island>`);
@@ -949,7 +992,10 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
949
992
  Object.defineProperty(Boundary, "name", { value: name });
950
993
  const ref = { moduleId, exportName, src, impl, hydrate };
951
994
  Boundary.__krateClient = ref;
952
- clientRegistry().set(`${moduleId}#${exportName}`, ref);
995
+ // A render module reads its siblings from its own generation: see
996
+ // __krateComp in the compiler's clientSSRSource.
997
+ const gen = typeof render === "function" && typeof render.__krateGen === "string" ? render.__krateGen : "";
998
+ clientRegistry().set(`${gen}|${moduleId}#${exportName}`, ref);
953
999
  return Boundary;
954
1000
  }
955
1001
  // Built-in Components (server stubs)
package/dist/signal.d.ts CHANGED
@@ -216,6 +216,8 @@ export type CSSFlagsScope<K extends string> = [
216
216
  trigger: (flag: K) => Record<string, unknown>;
217
217
  panel: (flag: K) => Record<string, unknown>;
218
218
  close: () => Record<string, unknown>;
219
+ /** Condition atom for `showIf`: true while `flag` is on. */
220
+ is: (flag: K) => boolean;
219
221
  };
220
222
  export declare function createCSSFlags<K extends string>(flags: readonly K[], _options?: CSSARIAOptions & {
221
223
  vars?: Record<string, Partial<Record<K, string>>>;
@@ -261,6 +263,12 @@ export type CSSScope<T> = [() => T, (next: T) => void] & {
261
263
  close: () => Record<string, unknown>;
262
264
  /** The current selected value (live, via `--krate-current`). */
263
265
  current: () => T;
266
+ /** Condition atom for `showIf`: true while `value` is selected. */
267
+ is: (value: T) => boolean;
268
+ /** Condition atom for a toggle: true while it is on. */
269
+ on: () => boolean;
270
+ /** Negated condition atom for a toggle: true while it is off. */
271
+ off: () => boolean;
264
272
  };
265
273
  /** Actions destructured from a `createCSSStack` result. */
266
274
  export interface CSSStackActions<K extends string> {
package/dist/signal.js CHANGED
@@ -571,6 +571,7 @@ export function createCSSFlags(flags, _options) {
571
571
  scope.trigger = (flag) => ({ 'data-krate-scope': 'trigger', value: flag });
572
572
  scope.panel = (flag) => ({ 'data-krate-scope': 'panel', value: flag });
573
573
  scope.close = () => ({ 'data-krate-scope': 'close' });
574
+ scope.is = (flag) => getters[flag]?.() ?? false;
574
575
  return scope;
575
576
  }
576
577
  /**
@@ -595,6 +596,9 @@ function withScopeHelpers(result) {
595
596
  scope.panel = (value) => ({ 'data-krate-scope': 'panel', value });
596
597
  scope.close = () => ({ 'data-krate-scope': 'close' });
597
598
  scope.current = () => result[0]();
599
+ scope.is = (value) => result[0]() === value;
600
+ scope.on = () => Boolean(result[0]());
601
+ scope.off = () => !result[0]();
598
602
  return scope;
599
603
  }
600
604
  /**
@@ -47,6 +47,7 @@ export interface RenderRequest {
47
47
  id: string;
48
48
  kind?: "component" | "page";
49
49
  }[];
50
+ prerender?: boolean;
50
51
  }
51
52
  export type CacheStatus = "hit" | "stale" | "miss";
52
53
  export interface RenderResponse {
@@ -56,6 +57,8 @@ export interface RenderResponse {
56
57
  notFound?: boolean;
57
58
  /** 401 or 403 when the render called unauthorized() or forbidden(). */
58
59
  denied?: 401 | 403;
60
+ /** Request-only API that bailed out a build-time prerender. */
61
+ dynamicUsage?: string;
59
62
  cached?: boolean;
60
63
  cacheStatus?: CacheStatus;
61
64
  error?: string;
@@ -165,6 +168,8 @@ export interface SSRCore {
165
168
  applyInternalOp(op: CoreInternalOp, payload: any): Promise<Record<string, any>>;
166
169
  /** Drops every cached variant of a route and all region caches (dev reload). */
167
170
  devInvalidate(route: string): void;
171
+ /** Replaces the manifest findPage reads, so pages added while dev runs resolve. */
172
+ setManifest(next: ServerManifest | null): void;
168
173
  }
169
174
  /**
170
175
  * Splits the document <title> out of rendered page html (see takeHead for the
package/dist/ssr-core.js CHANGED
@@ -6,7 +6,7 @@
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import { jsx, renderToStringAsync } from "./server.js";
8
8
  import { sha256Hex as portableSha256Hex } from "./sha256.js";
9
- import { isNotFoundSignal, accessDeniedStatus, parseCookieHeader, redirectTarget, thenable, thenableRecord, } from "./request-context.js";
9
+ import { isNotFoundSignal, isDynamicUsageError, dynamicUsageError, dynamicUsageReason, accessDeniedStatus, parseCookieHeader, redirectTarget, redirectStatus, thenable, thenableRecord, } from "./request-context.js";
10
10
  import { HEAD_CLOSE, HEAD_OPEN, takeHead } from "./head-tags.js";
11
11
  import { metadataHeadTags } from "./metadata.js";
12
12
  import { SegmentedLRU } from "./segmented-lru.js";
@@ -328,7 +328,7 @@ export function createSSRCore(opts) {
328
328
  });
329
329
  }
330
330
  // Renderer
331
- const manifest = opts.manifest;
331
+ let manifest = opts.manifest;
332
332
  function findPage(route) {
333
333
  if (!manifest)
334
334
  return undefined;
@@ -370,14 +370,17 @@ export function createSSRCore(opts) {
370
370
  headers: h,
371
371
  cookies: parseCookieHeader(h.get("cookie")),
372
372
  params: { ...req.params },
373
- searchParams: tracker ? trackedQuery(req.query, tracker) : { ...req.query },
373
+ searchParams: req.prerender ? {} : tracker ? trackedQuery(req.query, tracker) : { ...req.query },
374
+ prerender: !!req.prerender,
374
375
  };
375
376
  }
376
377
  function withRequest(req, fn, tracker) {
377
378
  return requestStore.run(requestContextFor(req, tracker), fn);
378
379
  }
379
- // renderSignal maps notFound()/redirect() thrown during a render to a response.
380
+ // renderSignal maps notFound()/redirect()/dynamic-usage thrown during a render to a response.
380
381
  function renderSignal(err) {
382
+ if (isDynamicUsageError(err))
383
+ return { html: "", status: 200, dynamicUsage: dynamicUsageReason(err) };
381
384
  if (isNotFoundSignal(err))
382
385
  return { html: "", status: 404, notFound: true };
383
386
  const denied = accessDeniedStatus(err);
@@ -385,9 +388,39 @@ export function createSSRCore(opts) {
385
388
  return { html: "", status: denied, denied };
386
389
  const to = redirectTarget(err);
387
390
  if (to)
388
- return { html: "", status: 307, redirect: to };
391
+ return { html: "", status: redirectStatus(err), redirect: to };
389
392
  return null;
390
393
  }
394
+ // prerenderSearchParams returns a thenable Proxy that throws a dynamic-usage
395
+ // error if page or generateMetadata code reads any key or enumerates it,
396
+ // while letting pages that merely receive props without reading searchParams
397
+ // prerender cleanly.
398
+ function prerenderSearchParams() {
399
+ const makeProxy = () => new Proxy({}, {
400
+ get(obj, prop, recv) {
401
+ if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor") {
402
+ throw dynamicUsageError("searchParams");
403
+ }
404
+ return Reflect.get(obj, prop, recv);
405
+ },
406
+ has(_obj, prop) {
407
+ if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor") {
408
+ throw dynamicUsageError("searchParams");
409
+ }
410
+ return false;
411
+ },
412
+ ownKeys() {
413
+ throw dynamicUsageError("searchParams");
414
+ },
415
+ getOwnPropertyDescriptor(obj, prop) {
416
+ if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor") {
417
+ throw dynamicUsageError("searchParams");
418
+ }
419
+ return Reflect.getOwnPropertyDescriptor(obj, prop);
420
+ },
421
+ });
422
+ return thenable(makeProxy(), makeProxy);
423
+ }
391
424
  function buildProps(req, tracker) {
392
425
  // Page-level data fetching (getStaticProps/getServerSideProps) has been
393
426
  // removed; per-request data is provided by server components (@server),
@@ -401,6 +434,10 @@ export function createSSRCore(opts) {
401
434
  const props = {};
402
435
  if (req.params)
403
436
  props.params = thenableRecord(req.params);
437
+ if (req.prerender) {
438
+ props.searchParams = prerenderSearchParams();
439
+ return props;
440
+ }
404
441
  if (tracker) {
405
442
  // Reads through the view are recorded; awaiting it resolves to another
406
443
  // tracked view so `const { page } = await searchParams` records "page".
@@ -457,7 +494,7 @@ export function createSSRCore(opts) {
457
494
  }
458
495
  // An uncacheable read (no-store) keeps the render out of the ISR cache, and
459
496
  // a revalidation that landed mid-render means the HTML may be stale.
460
- if (page.mode === "isr" && !scope.noStore && !invalidated) {
497
+ if (!req.prerender && page.mode === "isr" && !scope.noStore && !invalidated) {
461
498
  recordQueryReads(req, tracker);
462
499
  await isrStore.set(pageKey(req), {
463
500
  html,
@@ -552,7 +589,7 @@ export function createSSRCore(opts) {
552
589
  return { html: "", status: 404, notFound: true };
553
590
  }
554
591
  // ISR: serve from cache with stale-while-revalidate.
555
- if (page.mode === "isr") {
592
+ if (!req.prerender && page.mode === "isr") {
556
593
  const interval = page.revalidate || 60;
557
594
  pageIntervals.set(page.route, interval);
558
595
  const key = pageKey(req);
@@ -861,6 +898,8 @@ export function createSSRCore(opts) {
861
898
  frame.notFound = true;
862
899
  if (result.denied)
863
900
  frame.denied = result.denied;
901
+ if (result.dynamicUsage)
902
+ frame.dynamicUsage = result.dynamicUsage;
864
903
  if (result.redirect)
865
904
  frame.redirect = result.redirect;
866
905
  if (result.error)
@@ -944,5 +983,8 @@ export function createSSRCore(opts) {
944
983
  void isrStore.deleteRoute(route);
945
984
  clearRegionCache();
946
985
  },
986
+ setManifest(next) {
987
+ manifest = next;
988
+ },
947
989
  };
948
990
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.13",
3
+ "version": "0.5.0-rc.15",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -70,6 +70,10 @@
70
70
  "types": "./dist/jsx-types.d.ts",
71
71
  "default": "./dist/jsx-types.js"
72
72
  },
73
+ "./react-types": {
74
+ "types": "./dist/react-types.d.ts",
75
+ "default": "./dist/react-types.js"
76
+ },
73
77
  "./react": {
74
78
  "types": "./dist/react.d.ts",
75
79
  "default": "./dist/react.js"