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

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/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 { sealBoundArgs } from './action-seal.js';
6
7
  import { accessDeniedStatus, 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';
@@ -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)
@@ -165,6 +165,8 @@ export interface SSRCore {
165
165
  applyInternalOp(op: CoreInternalOp, payload: any): Promise<Record<string, any>>;
166
166
  /** Drops every cached variant of a route and all region caches (dev reload). */
167
167
  devInvalidate(route: string): void;
168
+ /** Replaces the manifest findPage reads, so pages added while dev runs resolve. */
169
+ setManifest(next: ServerManifest | null): void;
168
170
  }
169
171
  /**
170
172
  * 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, 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;
@@ -385,7 +385,7 @@ export function createSSRCore(opts) {
385
385
  return { html: "", status: denied, denied };
386
386
  const to = redirectTarget(err);
387
387
  if (to)
388
- return { html: "", status: 307, redirect: to };
388
+ return { html: "", status: redirectStatus(err), redirect: to };
389
389
  return null;
390
390
  }
391
391
  function buildProps(req, tracker) {
@@ -944,5 +944,8 @@ export function createSSRCore(opts) {
944
944
  void isrStore.deleteRoute(route);
945
945
  clearRegionCache();
946
946
  },
947
+ setManifest(next) {
948
+ manifest = next;
949
+ },
947
950
  };
948
951
  }
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.14",
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"