@krate/runtime 0.5.0-rc.16 → 0.5.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
1
  # @krate/runtime
2
2
 
3
- The client-side runtime for krate, providing signal-based reactivity.
3
+ The client runtime for [Krate](https://krate.js.org): signals, DOM binding and
4
+ hydration, the SPA router, resources and context. It also carries the
5
+ server-side pieces that run in Krate's SSR and API sidecars (request helpers,
6
+ cache invalidation, the request handler).
7
+
8
+ Most apps use it indirectly: the compiler turns TSX into static HTML plus a
9
+ small hydration bundle that calls into this package, and production builds ship
10
+ only the runtime features a site references. You import it directly when you
11
+ write reactive state, use router hooks, or call server-side helpers.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @krate/runtime
17
+ ```
18
+
19
+ New projects get it from `npx create-krate-app@latest`. Node 20 or newer.
20
+
21
+ ## Usage
22
+
23
+ ```tsx
24
+ import { createSignal, createEffect, createMemo } from "@krate/runtime";
25
+
26
+ export default function Counter() {
27
+ const [count, setCount] = createSignal(0);
28
+ const doubled = createMemo(() => count() * 2);
29
+ createEffect(() => console.log("count is", count()));
30
+
31
+ return (
32
+ <button onClick={() => setCount((n) => n + 1)}>
33
+ {count()} x 2 = {doubled()}
34
+ </button>
35
+ );
36
+ }
37
+ ```
38
+
39
+ Server-side helpers live in subpath exports:
40
+
41
+ ```tsx
42
+ import { cookies, notFound } from "@krate/runtime/server";
43
+
44
+ export default async function Post({ params }) {
45
+ const { slug } = await params;
46
+ const theme = (await cookies()).get("theme")?.value;
47
+ if (!slug) notFound();
48
+ return <article class={theme}>{slug}</article>;
49
+ }
50
+ ```
51
+
52
+ ## What it exports
53
+
54
+ The root export (`@krate/runtime`) covers:
55
+
56
+ - Reactivity: `createSignal` (with an optional `persist` option),
57
+ `createEffect`, `createMemo`, `createReducer`, `createRoot`, `onMount`,
58
+ `onCleanup`, `untrack`, and the zero-JS CSS state primitives
59
+ (`createCSSChoice`, `createCSSToggle`, `createCSSFlags`, `createCSSGroup`,
60
+ `createCSSRange`, `createCSSStack`).
61
+ - DOM: `h`, `mount`, `hydrate`, `insert`, plus the JSX runtime.
62
+ - Router and navigation: `navigate`, `usePathname`, `useSearchParams`,
63
+ `useParams`, `useRouter`, `redirect`, `notFound`.
64
+ - Data and state: `createResource`, `createContext`, and the form/action
65
+ helpers `getFormStatus`, `requestFormReset`.
66
+ - Class helpers: `clsx`, `cn`, `cva`, `Slot`.
67
+
68
+ Subpath exports (see `exports` in `package.json`):
69
+
70
+ | Subpath | Purpose |
71
+ |---|---|
72
+ | `@krate/runtime/server` | `cookies`, `headers`, `redirect`, `notFound`, `after`, `revalidatePath`, `revalidateTag`, `unstable_cache` for server components, API routes and actions |
73
+ | `@krate/runtime/cache` | On-demand revalidation and the data cache (also re-exported from `/server`) |
74
+ | `@krate/runtime/testing` | `callRoute` and `runAction` for testing API routes and server actions in-process (Node only) |
75
+ | `@krate/runtime/jsx-runtime`, `/jsx-dev-runtime`, `/jsx-types` | JSX runtime and types |
76
+ | `@krate/runtime/react-compat`, `/react`, `/react-types`, `/react-server`, `/navigation-react` | React compatibility layers |
77
+ | `@krate/runtime/highlight`, `/hints`, `/og`, `/slot` | Syntax highlighting, resource hints, Open Graph images, slots |
78
+ | `@krate/runtime/server-handler`, `/node-server`, `/cloudflare-workers`, `/assets-static`, `/cache-adapter`, `/cache-redis` | Request handler and deploy-target adapters used by `krate start` and deploy builds |
79
+
80
+ The server-handler and adapter subpaths are compiler-facing; app code rarely
81
+ imports them.
82
+
83
+ ## Docs
84
+
85
+ - [Runtime API](https://krate.js.org/docs/reference/runtime-api/) - every root export
86
+ - [Reactivity](https://krate.js.org/docs/core-concepts/reactivity/)
87
+ - [Async server components](https://krate.js.org/docs/features/server-components/)
88
+ - [Caching and revalidation](https://krate.js.org/docs/guides/caching-and-revalidation/)
89
+ - [Testing](https://krate.js.org/docs/guides/testing/)
90
+ - [React compatibility](https://krate.js.org/docs/guides/react-compatibility/)
91
+
92
+ ## License
93
+
94
+ Apache-2.0
package/dist/actions.js CHANGED
@@ -40,8 +40,13 @@ export function isServerAction(value) {
40
40
  return typeof value === 'function' && typeof value.$$krateAction === 'string';
41
41
  }
42
42
  // Counts redirects the client followed, so useActionState can tell that an
43
- // action navigated away instead of producing a next state.
44
- let redirectsFollowed = 0;
43
+ // action navigated away instead of producing a next state. It lives on
44
+ // globalThis: island bundles carry their own copy of this module, and the
45
+ // compat useActionState (react-compat.ts) reads it too.
46
+ const REDIRECTS = '__krateActionRedirects';
47
+ function redirectsFollowed() {
48
+ return globalThis[REDIRECTS] || 0;
49
+ }
45
50
  function navigateTo(url) {
46
51
  const safe = safeRedirect(url);
47
52
  if (!safe)
@@ -132,7 +137,7 @@ export async function callServerAction(url, args) {
132
137
  if (payload.revalidated)
133
138
  dispatchRevalidate(payload.revalidation);
134
139
  if (typeof payload.redirect === 'string' && payload.redirect) {
135
- redirectsFollowed++;
140
+ globalThis[REDIRECTS] = redirectsFollowed() + 1;
136
141
  if (payload.external)
137
142
  navigateExternal(payload.redirect);
138
143
  else
@@ -579,10 +584,10 @@ export function __krateActionState(action, getState, setState, setPending) {
579
584
  const item = queue.shift();
580
585
  let ok = false;
581
586
  try {
582
- const before = redirectsFollowed;
587
+ const before = redirectsFollowed();
583
588
  const next = await runActionTransition(() => action(getState(), item.payload));
584
589
  // A redirecting action has no next state: the page is being replaced.
585
- if (redirectsFollowed === before)
590
+ if (redirectsFollowed() === before)
586
591
  krateTransitionWrites(() => setState(next));
587
592
  ok = true;
588
593
  }
package/dist/context.js CHANGED
@@ -138,6 +138,9 @@ export function krateContextRows(entries, render) {
138
138
  export function krateWithContexts(entries, fn) {
139
139
  const pushed = [];
140
140
  for (const [ctx, get] of entries) {
141
+ // A compiled entry can name a context its script does not declare.
142
+ if (!ctx)
143
+ continue;
141
144
  const stack = contextStack.get(ctx.id);
142
145
  if (!stack)
143
146
  continue;
package/dist/dev/app.js CHANGED
@@ -122,7 +122,9 @@ export class KrateDev {
122
122
  this.shadow.addEventListener('input', (e) => this.onInput(e));
123
123
  this.shadow.addEventListener('change', (e) => this.onInput(e));
124
124
  this.listen(document, 'keydown', (e) => this.onKey(e), true);
125
- if (this.cfg.frames)
125
+ if (this.cfg.standalone)
126
+ this.setConn('open');
127
+ else if (this.cfg.frames)
126
128
  this.connectFrames();
127
129
  else
128
130
  this.connectSSE();
@@ -274,7 +276,7 @@ export class KrateDev {
274
276
  }
275
277
  // editor and actions
276
278
  async openInEditor(file, line, col) {
277
- if (!file)
279
+ if (!file || !this.cfg.open)
278
280
  return;
279
281
  let url = this.cfg.open + '?file=' + encodeURIComponent(file) + '&line=' + encodeURIComponent(String(line || ''));
280
282
  if (col)
@@ -1141,6 +1143,8 @@ export class KrateDev {
1141
1143
  });
1142
1144
  }
1143
1145
  send(payload) {
1146
+ if (this.cfg.standalone || !this.cfg.errors)
1147
+ return;
1144
1148
  const body = JSON.stringify(payload);
1145
1149
  // sendBeacon throws on the custom scheme of a native webview (WebKitGTK),
1146
1150
  // so a failed or absent beacon falls back to fetch.
package/dist/dev/modal.js CHANGED
@@ -17,8 +17,8 @@ function fixKey(i) {
17
17
  function isProjectFile(f) {
18
18
  return !!f && !/^[a-z][a-z0-9+.-]*:\/\//i.test(f) && !/^(chunks|__krate)\//.test(f);
19
19
  }
20
- function canOpen(i) {
21
- return isProjectFile(i.file) && !i.served;
20
+ function canOpen(app, i) {
21
+ return !!app.cfg.open && isProjectFile(i.file) && !i.served;
22
22
  }
23
23
  const SOURCE_NAME = {
24
24
  'SSR renderer': 'SSR sidecar',
@@ -278,7 +278,7 @@ function fileLine(app, i, shown) {
278
278
  return ('<div class="fileline">' +
279
279
  pathHTML(i, shown) +
280
280
  '<span class="grow"></span>' +
281
- (canOpen(i)
281
+ (canOpen(app, i)
282
282
  ? '<button class="b" type="button" data-act="open-issue">' + icon('square-arrow-up-right-exit') + 'Open in editor <span class="kbd">O</span></button>'
283
283
  : '') +
284
284
  '<button class="b" type="button" data-act="copy-ai">' +
@@ -286,7 +286,7 @@ function fileLine(app, i, shown) {
286
286
  'Copy for AI</button></div>');
287
287
  }
288
288
  function runtimeDetail(app, i) {
289
- const frame = canOpen(i) || i.served ? app.frames.get(frameKey(i)) || null : null;
289
+ const frame = canOpen(app, i) || i.served ? app.frames.get(frameKey(i)) || null : null;
290
290
  const frames = parseStack(i.stack);
291
291
  const items = splitStack(frames);
292
292
  const appCount = frames.filter((f) => f.app).length;
@@ -357,7 +357,7 @@ function runtimeDetail(app, i) {
357
357
  if (it.type === 'app') {
358
358
  const f = it.frame;
359
359
  html +=
360
- (f.served
360
+ (f.served || !app.cfg.open
361
361
  ? '<div class="fr app">'
362
362
  : '<button class="fr app" type="button" data-act="open" data-file="' + esc(f.file) + '" data-line="' + f.line + '" data-col="' + f.col + '">') +
363
363
  '<span class="fn">' +
@@ -369,7 +369,7 @@ function runtimeDetail(app, i) {
369
369
  ':' +
370
370
  f.col +
371
371
  '</span>' +
372
- (f.served ? '</div>' : '</button>');
372
+ (f.served || !app.cfg.open ? '</div>' : '</button>');
373
373
  return;
374
374
  }
375
375
  const key = i.id + '#' + k;
@@ -462,7 +462,7 @@ function serverDetail(app, i) {
462
462
  const logFile = app.logFile();
463
463
  html +=
464
464
  '<div class="lbl" style="margin-top:18px">Last console lines<span class="grow"></span>' +
465
- (logFile ? '<button class="link" type="button" style="font-size:12px" data-act="open" data-file="' + esc(logFile) + '">Open ' + esc(logFile) + '</button>' : '') +
465
+ (logFile && app.cfg.open ? '<button class="link" type="button" style="font-size:12px" data-act="open" data-file="' + esc(logFile) + '">Open ' + esc(logFile) + '</button>' : '') +
466
466
  '</div>';
467
467
  if (log.length) {
468
468
  html +=
@@ -630,7 +630,7 @@ export function prepareIssue(app, i) {
630
630
  rerender();
631
631
  });
632
632
  }
633
- if (canOpen(i) && !app.frames.has(fk) && !app.busy.has('src:' + fk)) {
633
+ if (canOpen(app, i) && !app.frames.has(fk) && !app.busy.has('src:' + fk)) {
634
634
  app.busy.add('src:' + fk);
635
635
  void app.getJSON('/source', { file: i.file, line: i.line || 1, context: 3 }).then((f) => {
636
636
  app.busy.delete('src:' + fk);
@@ -814,7 +814,7 @@ export function modalKey(app, e, typing) {
814
814
  break;
815
815
  case 'o':
816
816
  case 'O':
817
- if (i && canOpen(i))
817
+ if (i && canOpen(app, i))
818
818
  void app.openInEditor(i.file, i.line, i.col);
819
819
  break;
820
820
  case 'f':
package/dist/dev/panel.js CHANGED
@@ -45,7 +45,9 @@ export function renderPanel(app, headOnly = false) {
45
45
  ? '<span class="conn off">Reconnecting</span>'
46
46
  : app.building
47
47
  ? '<span class="conn busy">Rebuilding</span>'
48
- : '<span class="conn">Connected</span>';
48
+ : app.cfg.standalone
49
+ ? '<span class="conn">Local</span>'
50
+ : '<span class="conn">Connected</span>';
49
51
  const ver = app.info?.version || app.cfg.version;
50
52
  const tabHTML = tabs
51
53
  .map((t) => {
@@ -8,6 +8,11 @@ interface MapSegment {
8
8
  export declare function decodeVLQ(str: string): number[];
9
9
  /** Decodes a v3 `mappings` string into per-generated-line segments. */
10
10
  export declare function decodeMappings(mappings: string): MapSegment[][];
11
+ /**
12
+ * The source map URL a script advertises: its SourceMap (or X-SourceMap)
13
+ * header, else the last sourceMappingURL comment. Null when it has none.
14
+ */
15
+ export declare function advertisedMapURL(scriptURL: string, source: string, headers?: Headers): string | null;
11
16
  interface StackFrame {
12
17
  prefix: string;
13
18
  url: string;
@@ -1,6 +1,8 @@
1
1
  // Source-map symbolication. When the build enables source maps the overlay
2
2
  // decodes them so runtime stack traces point at real source locations instead
3
- // of bundle offsets. Fetches fail silently when maps are absent.
3
+ // of bundle offsets. Only a map the script advertises (a sourceMappingURL
4
+ // comment or a SourceMap header) is fetched: guessing <script>.map for chunks
5
+ // that ship none logs a 404 in the console for every frame.
4
6
  import { rawFetch } from './requests.js';
5
7
  const B64_VLQ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6
8
  /** Decodes a Base64 VLQ mapping segment into a delta array. */
@@ -58,6 +60,28 @@ export function decodeMappings(mappings) {
58
60
  return lines;
59
61
  }
60
62
  const mapCache = new Map();
63
+ /**
64
+ * The source map URL a script advertises: its SourceMap (or X-SourceMap)
65
+ * header, else the last sourceMappingURL comment. Null when it has none.
66
+ */
67
+ export function advertisedMapURL(scriptURL, source, headers) {
68
+ const header = headers?.get('SourceMap') || headers?.get('X-SourceMap');
69
+ let ref = header ? header.trim() : '';
70
+ if (!ref) {
71
+ const re = /\/[/*][#@]\s*sourceMappingURL=([^\s'"*]+)/g;
72
+ let m;
73
+ while ((m = re.exec(source)))
74
+ ref = m[1];
75
+ }
76
+ if (!ref)
77
+ return null;
78
+ try {
79
+ return new URL(ref, scriptURL).href;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
61
85
  async function loadSourceMap(url) {
62
86
  const cached = mapCache.get(url);
63
87
  if (cached)
@@ -67,7 +91,17 @@ async function loadSourceMap(url) {
67
91
  const u = new URL(url, location.href);
68
92
  if (u.protocol !== location.protocol || u.host !== location.host)
69
93
  return null;
70
- const res = await rawFetch(url + '.map');
94
+ // The script already ran, so this is normally a cache hit.
95
+ const script = await rawFetch(u.href);
96
+ if (!script.ok)
97
+ return null;
98
+ const mapURL = advertisedMapURL(u.href, await script.text(), script.headers);
99
+ if (!mapURL)
100
+ return null;
101
+ const mu = new URL(mapURL);
102
+ if (mu.protocol !== 'data:' && (mu.protocol !== location.protocol || mu.host !== location.host))
103
+ return null;
104
+ const res = await rawFetch(mapURL);
71
105
  if (!res.ok)
72
106
  return null;
73
107
  const json = await res.json();
@@ -4,6 +4,12 @@ export interface DevPage {
4
4
  mode?: string;
5
5
  }
6
6
  export interface DevConfig {
7
+ /**
8
+ * No dev server exists behind this page (the in-browser playground): skip the
9
+ * event stream and error reports, and show no connection state. The
10
+ * client-side overlay (error capture, inspector, panels) still works.
11
+ */
12
+ standalone?: boolean;
7
13
  sse?: string;
8
14
  /** Path of a frame stream carrying `{hmr: message}` frames (Krate Native). Replaces SSE. */
9
15
  frames?: string;
package/dist/dev/util.js CHANGED
@@ -13,6 +13,7 @@ export function devConfig() {
13
13
  const runtime = siteConfig();
14
14
  const native = isNativeOrigin();
15
15
  return {
16
+ standalone: !!raw?.standalone,
16
17
  sse: raw?.sse ?? '/__krate/hotreload',
17
18
  frames: raw?.frames ?? (native ? '/__krate/hmr' : ''),
18
19
  events: raw?.events ?? (native ? '/__krate/dev/events' : ''),
package/dist/dom.d.ts CHANGED
@@ -23,6 +23,32 @@ export declare function krateTrackNode(node: Node, dispose: () => void): void;
23
23
  export declare function krateBindRef(el: Element, get: (() => KrateRef) | null, assign?: (v: unknown) => void): () => void;
24
24
  /** Dispose all effects registered for a node and its subtree. */
25
25
  export declare function disposeNode(node: Node): void;
26
+ /** Decides whether a leaving element stays for an exit animation. */
27
+ export interface KrateExitHook {
28
+ /** Returns true to keep `el` in the document; it calls `done` when the exit has finished. */
29
+ exit(el: Element, done: () => void): boolean;
30
+ /** `el`, kept for its exit, is shown again by a conditional before `done` ran. */
31
+ cancel?(el: Element): void;
32
+ }
33
+ /** Installs (or with null, removes) the exit hook. */
34
+ export declare function krateSetExitHook(hook: KrateExitHook | null): void;
35
+ /**
36
+ * Disposes `node` and removes it from `parent`, unless the exit hook keeps it:
37
+ * then that happens when its exit animation has finished.
38
+ */
39
+ export declare function krateRemoveNode(parent: Node, node: Node): void;
40
+ /**
41
+ * For a conditional branch swapped out of the document: when the exit hook
42
+ * keeps `el`, a placeholder takes its place in `into` (the detached branch)
43
+ * and `el` stays in the document until its exit finishes, then moves to the
44
+ * placeholder's place. Returns false when `el` should move now.
45
+ */
46
+ export declare function krateKeepForExit(el: Element, into: Node): boolean;
47
+ /**
48
+ * Puts elements still running their exit back in place of their placeholders
49
+ * in `frag` (a branch shown again) and tells the exit hook.
50
+ */
51
+ export declare function krateRestoreKept(frag: Node): void;
26
52
  /**
27
53
  * Clear all nodes between two markers (exclusive of the markers themselves).
28
54
  * @param start - start comment marker
package/dist/dom.js CHANGED
@@ -2,7 +2,7 @@ import { createEffect, onCleanup, krateGetOwner, krateSetOwner } from './signal.
2
2
  import { krateWithOwner, krateUnmount } from './effects.js';
3
3
  import { krateSanitizeAttr } from './slots.js';
4
4
  import { krateOn, krateControl, krateSetControl } from './events.js';
5
- import { krateAttachRef } from './refs.js';
5
+ import { krateAttachRef, krateRefsLeave } from './refs.js';
6
6
  import { withBase } from './base-path.js';
7
7
  export { krateOn, krateControl, krateSetControl, krateSynthetic, krateEventRoot, krateEventName, krateMountFields, } from './events.js';
8
8
  export { krateAttachRef, krateSetRef, krateRefsEnter, krateRefsLeave, krateRefsFlush, krateRefsHold } from './refs.js';
@@ -79,6 +79,81 @@ export function disposeNode(node) {
79
79
  disposeNode(node.childNodes[i]);
80
80
  }
81
81
  }
82
+ let exitHook = null;
83
+ /** Installs (or with null, removes) the exit hook. */
84
+ export function krateSetExitHook(hook) {
85
+ exitHook = hook;
86
+ }
87
+ /**
88
+ * Disposes `node` and removes it from `parent`, unless the exit hook keeps it:
89
+ * then that happens when its exit animation has finished.
90
+ */
91
+ export function krateRemoveNode(parent, node) {
92
+ if (exitHook && node.nodeType === 1) {
93
+ let finished = false;
94
+ const kept = exitHook.exit(node, () => {
95
+ if (finished)
96
+ return;
97
+ finished = true;
98
+ disposeNode(node);
99
+ if (node.parentNode)
100
+ node.parentNode.removeChild(node);
101
+ });
102
+ if (kept)
103
+ return;
104
+ }
105
+ disposeNode(node);
106
+ parent.removeChild(node);
107
+ }
108
+ const keptByPlaceholder = new WeakMap();
109
+ /**
110
+ * For a conditional branch swapped out of the document: when the exit hook
111
+ * keeps `el`, a placeholder takes its place in `into` (the detached branch)
112
+ * and `el` stays in the document until its exit finishes, then moves to the
113
+ * placeholder's place. Returns false when `el` should move now.
114
+ */
115
+ export function krateKeepForExit(el, into) {
116
+ if (!exitHook)
117
+ return false;
118
+ const ph = document.createComment('');
119
+ const rec = { el, done: false };
120
+ const kept = exitHook.exit(el, () => {
121
+ if (rec.done)
122
+ return;
123
+ rec.done = true;
124
+ const p = ph.parentNode;
125
+ if (p) {
126
+ p.replaceChild(el, ph);
127
+ if (!el.isConnected)
128
+ krateRefsLeave(el);
129
+ }
130
+ else if (el.parentNode) {
131
+ el.parentNode.removeChild(el);
132
+ }
133
+ });
134
+ if (!kept)
135
+ return false;
136
+ keptByPlaceholder.set(ph, rec);
137
+ into.appendChild(ph);
138
+ return true;
139
+ }
140
+ /**
141
+ * Puts elements still running their exit back in place of their placeholders
142
+ * in `frag` (a branch shown again) and tells the exit hook.
143
+ */
144
+ export function krateRestoreKept(frag) {
145
+ for (let n = frag.firstChild; n;) {
146
+ const next = n.nextSibling;
147
+ const rec = n.nodeType === 8 ? keptByPlaceholder.get(n) : undefined;
148
+ if (rec && !rec.done) {
149
+ rec.done = true;
150
+ frag.replaceChild(rec.el, n);
151
+ if (exitHook && exitHook.cancel)
152
+ exitHook.cancel(rec.el);
153
+ }
154
+ n = next;
155
+ }
156
+ }
82
157
  // comment-marker DOM traversal
83
158
  /**
84
159
  * Find the matching end comment marker for a start marker.
@@ -107,8 +182,7 @@ export function clearNodes(start, end) {
107
182
  let node = start.nextSibling;
108
183
  while (node && node !== end) {
109
184
  const next = node.nextSibling;
110
- disposeNode(node);
111
- parent.removeChild(node);
185
+ krateRemoveNode(parent, node);
112
186
  node = next;
113
187
  }
114
188
  }
@@ -493,8 +567,7 @@ export function clearBetween(start, end) {
493
567
  let node = start.nextSibling;
494
568
  while (node && node !== end) {
495
569
  const next = node.nextSibling;
496
- disposeNode(node);
497
- parent.removeChild(node);
570
+ krateRemoveNode(parent, node);
498
571
  node = next;
499
572
  }
500
573
  }
@@ -6,4 +6,12 @@ export type FlightHooks = {
6
6
  sealBound?(id: string, bound: unknown[], path: string): string;
7
7
  };
8
8
  export declare function describeValue(v: unknown): string;
9
+ /**
10
+ * Awaits the Promises nested in v (through plain objects and arrays), as
11
+ * React Server Components do for a Promise prop, and records each result on
12
+ * the promise the way React tracks a thenable (status, value or reason). A
13
+ * render that reads one with use() then gets the value without suspending,
14
+ * and encodeProp can send it to the client.
15
+ */
16
+ export declare function settleThenables(v: unknown, seen?: Set<object>): Promise<void>;
9
17
  export declare function encodeProp(v: unknown, path: string, hooks: FlightHooks): unknown;
@@ -33,6 +33,39 @@ export function describeValue(v) {
33
33
  }
34
34
  return typeof v;
35
35
  }
36
+ /**
37
+ * Awaits the Promises nested in v (through plain objects and arrays), as
38
+ * React Server Components do for a Promise prop, and records each result on
39
+ * the promise the way React tracks a thenable (status, value or reason). A
40
+ * render that reads one with use() then gets the value without suspending,
41
+ * and encodeProp can send it to the client.
42
+ */
43
+ export async function settleThenables(v, seen = new Set()) {
44
+ if (!v || typeof v !== "object" || seen.has(v))
45
+ return;
46
+ seen.add(v);
47
+ if (v instanceof Promise) {
48
+ const p = v;
49
+ if (p.status !== "fulfilled" && p.status !== "rejected") {
50
+ try {
51
+ p.value = await p;
52
+ p.status = "fulfilled";
53
+ }
54
+ catch (err) {
55
+ p.reason = err;
56
+ p.status = "rejected";
57
+ }
58
+ }
59
+ if (p.status === "fulfilled")
60
+ await settleThenables(p.value, seen);
61
+ return;
62
+ }
63
+ const proto = Object.getPrototypeOf(v);
64
+ if (Array.isArray(v))
65
+ await Promise.all(v.map((x) => settleThenables(x, seen)));
66
+ else if (proto === Object.prototype || proto === null)
67
+ await Promise.all(Object.values(v).map((x) => settleThenables(x, seen)));
68
+ }
36
69
  // encodeProp converts one prop value. A top-level undefined is dropped by the
37
70
  // caller (an absent prop); nested ones are kept as an "U" tag.
38
71
  export function encodeProp(v, path, hooks) {
@@ -80,6 +113,17 @@ export function encodeProp(v, path, hooks) {
80
113
  throw hooks.fail(path, "JSX", "pass JSX as a prop value, an array of JSX, or as children; JSX nested inside an object cannot be sent to a client component");
81
114
  }
82
115
  const proto = Object.getPrototypeOf(v);
116
+ if (v instanceof Promise) {
117
+ // Settled by settleThenables; the client gets an already settled promise.
118
+ const p = v;
119
+ if (p.status === "fulfilled")
120
+ return tag("P", encodeProp(p.value, `${path}.then()`, hooks));
121
+ if (p.status === "rejected") {
122
+ const r = p.reason;
123
+ return tag("PX", r && typeof r.message === "string" ? r.message : String(p.reason));
124
+ }
125
+ throw hooks.fail(path, "a Promise that has not settled", "await the value before passing it, or pass the Promise straight from the server component");
126
+ }
83
127
  if (proto === Date.prototype) {
84
128
  const t = v.getTime();
85
129
  return tag("D", Number.isNaN(t) ? null : t);
package/dist/hints.d.ts CHANGED
@@ -30,6 +30,12 @@ export declare const prefetchDNS: typeof krateHintPrefetchDNS;
30
30
  export declare const preloadModule: typeof krateHintPreloadModule;
31
31
  export declare const preinitModule: typeof krateHintPreinitModule;
32
32
  export declare function flushSync<T>(fn: () => T): T;
33
+ export declare function createPortal(_children: unknown, _container: unknown): null;
34
+ export declare function unstable_batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
35
+ export declare function findDOMNode(..._args: unknown[]): never;
36
+ export declare function render(..._args: unknown[]): never;
37
+ export declare function hydrate(..._args: unknown[]): never;
38
+ export declare function unmountComponentAtNode(..._args: unknown[]): never;
33
39
  declare const _default: {
34
40
  preload: typeof krateHintPreload;
35
41
  preinit: typeof krateHintPreinit;
@@ -38,5 +44,11 @@ declare const _default: {
38
44
  preloadModule: typeof krateHintPreloadModule;
39
45
  preinitModule: typeof krateHintPreinitModule;
40
46
  flushSync: typeof flushSync;
47
+ createPortal: typeof createPortal;
48
+ unstable_batchedUpdates: typeof unstable_batchedUpdates;
49
+ findDOMNode: typeof findDOMNode;
50
+ render: typeof render;
51
+ hydrate: typeof hydrate;
52
+ unmountComponentAtNode: typeof unmountComponentAtNode;
41
53
  };
42
54
  export default _default;
package/dist/hints.js CHANGED
@@ -157,7 +157,8 @@ export function krateHintPreinitModule(href, opts) {
157
157
  return;
158
158
  emit('script', [['type', 'module'], ['src', href], ['async', ''], ...optAttrs(opts, ['crossOrigin', 'integrity', 'nonce'])]);
159
159
  }
160
- // The react-dom exports a server module can use. flushSync(fn) is fn() here.
160
+ // The react-dom exports a server module can use (this module is react-dom in
161
+ // server bundles). flushSync(fn) is fn() here.
161
162
  export const preload = krateHintPreload;
162
163
  export const preinit = krateHintPreinit;
163
164
  export const preconnect = krateHintPreconnect;
@@ -167,4 +168,33 @@ export const preinitModule = krateHintPreinitModule;
167
168
  export function flushSync(fn) {
168
169
  return fn();
169
170
  }
170
- export default { preload, preinit, preconnect, prefetchDNS, preloadModule, preinitModule, flushSync };
171
+ // A portal is not part of the server-rendered HTML (as in React): it mounts
172
+ // in the browser after hydration.
173
+ export function createPortal(_children, _container) {
174
+ return null;
175
+ }
176
+ export function unstable_batchedUpdates(fn, a) {
177
+ return fn(a);
178
+ }
179
+ // The react-dom exports React 19 removed. A package may still import them;
180
+ // only a call fails, with the KR8001 explanation. Declarations, so a bundle
181
+ // that does not call them drops them.
182
+ function removedAPI(name, hint) {
183
+ throw new Error('[KR8001] react-dom ' + name + ' was removed in React 19 and has no Krate equivalent: ' + hint);
184
+ }
185
+ export function findDOMNode(..._args) {
186
+ return removedAPI('findDOMNode', 'attach a ref to the element instead (ref={nodeRef}, then read nodeRef.current)');
187
+ }
188
+ export function render(..._args) {
189
+ return removedAPI('render', 'Krate mounts pages itself; render the component from a page instead of calling ReactDOM.render');
190
+ }
191
+ export function hydrate(..._args) {
192
+ return removedAPI('hydrate', 'Krate hydrates pages itself; remove the ReactDOM.hydrate call');
193
+ }
194
+ export function unmountComponentAtNode(..._args) {
195
+ return removedAPI('unmountComponentAtNode', 'Krate unmounts pages on navigation; render the content conditionally instead');
196
+ }
197
+ export default {
198
+ preload, preinit, preconnect, prefetchDNS, preloadModule, preinitModule, flushSync,
199
+ createPortal, unstable_batchedUpdates, findDOMNode, render, hydrate, unmountComponentAtNode,
200
+ };
package/dist/index.d.ts CHANGED
@@ -31,4 +31,8 @@ export type { Component, PropsWithChildren, ComponentProps, RefCallback } from '
31
31
  export type { RefObject, Ref, UseRefResult } from './signal.js';
32
32
  import './jsx-types.js';
33
33
  export { Link, Head, Icon, Image, Script, Style, Suspense, SyntaxHighlight } from './builtin-tags.js';
34
+ /** Props of the built-in <Image> (the next/image ImageProps counterpart). */
35
+ export type ImageProps = JSX.ImageProps;
36
+ /** Props of the built-in <Link> (the next/link LinkProps counterpart). */
37
+ export type LinkProps = JSX.LinkProps;
34
38
  import './css-modules.js';