@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.11

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 (214) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
package/dist/server.js CHANGED
@@ -1,9 +1,16 @@
1
1
  // @krate/runtime/server - Server-side rendering runtime
2
2
  // Provides the same API as the client runtime but renders to HTML strings.
3
3
  import { ATTR_ALIASES } from './htmlspec-attributes.js';
4
+ import { withBase } from './base-path.js';
4
5
  import { highlight as highlightCode, trimSpace } from './highlight.js';
6
+ import { accessDeniedStatus, isNotFoundSignal, redirectTarget } from './request-context.js';
7
+ import { sha256Hex } from './sha256.js';
8
+ import { markErrorCaught } from './cache-scope.js';
9
+ import { encodeProp } from './flight-props.js';
5
10
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
6
11
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
12
+ export { after } from './after.js';
13
+ export { getPlatform, getCloudflareContext } from './platform.js';
7
14
  export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
8
15
  export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
9
16
  export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
@@ -130,10 +137,168 @@ function asyncInSyncRender(where) {
130
137
  function isClassComponent(fn) {
131
138
  return typeof fn === "function" && fn.prototype && typeof fn.prototype.render === "function";
132
139
  }
140
+ // React element types that are objects or symbols rather than functions. A
141
+ // package compiled for React (Radix's Slot is a forwardRef) hands these to a
142
+ // dynamic tag (`const Comp = asChild ? Slot.Root : "button"`), so the server
143
+ // renderer must run them as components instead of printing them as a tag name.
144
+ const R_ELEMENT = new Set([Symbol.for("react.element"), Symbol.for("react.transitional.element")]);
145
+ const R_FORWARD_REF = Symbol.for("react.forward_ref");
146
+ const R_MEMO = Symbol.for("react.memo");
147
+ const R_LAZY = Symbol.for("react.lazy");
148
+ const R_PROVIDER = Symbol.for("react.provider");
149
+ const R_CONTEXT = Symbol.for("react.context");
150
+ const R_CONSUMER = Symbol.for("react.consumer");
151
+ const R_FRAGMENT = Symbol.for("react.fragment");
152
+ const R_SUSPENSE = Symbol.for("react.suspense");
153
+ const exoticCache = new WeakMap();
154
+ function describeType(type) {
155
+ if (typeof type === "symbol")
156
+ return type.toString();
157
+ if (type && typeof type === "object") {
158
+ const t = type;
159
+ const tag = typeof t.$$typeof === "symbol" ? t.$$typeof.toString() : undefined;
160
+ return tag ? `an object (${tag})` : "an object";
161
+ }
162
+ return String(type);
163
+ }
164
+ function notRenderable(type) {
165
+ return new Error(`Cannot render an element whose type is ${describeType(type)}. A server render can run strings, ` +
166
+ `function and class components, and React forwardRef, memo, lazy and context types; ` +
167
+ `pass a component or an HTML tag name instead.`);
168
+ }
169
+ // isSlotType reports Radix's Slot (createSlot names it `<owner>.Slot`). Its
170
+ // own render clones React elements and cannot work on Krate's, so the server
171
+ // uses ServerSlot for it.
172
+ function isSlotType(type) {
173
+ return typeof type.displayName === "string" && /(^|\.)Slot$/.test(type.displayName);
174
+ }
175
+ function childElements(children) {
176
+ return children.filter((c) => c != null && c !== false && !(typeof c === "string" && c.trim() === ""));
177
+ }
178
+ function mergeSlotProps(slot, child) {
179
+ const out = { ...slot, ...child };
180
+ for (const key of Object.keys(child)) {
181
+ const sv = slot[key];
182
+ const cv = child[key];
183
+ if (/^on[A-Z]/.test(key) && typeof sv === "function" && typeof cv === "function") {
184
+ out[key] = (...args) => {
185
+ cv(...args);
186
+ sv(...args);
187
+ };
188
+ }
189
+ else if (key === "style" && sv && cv && typeof sv === "object" && typeof cv === "object") {
190
+ out[key] = { ...sv, ...cv };
191
+ }
192
+ else if ((key === "className" || key === "class") && sv && cv) {
193
+ out[key] = `${sv} ${cv}`;
194
+ }
195
+ }
196
+ return out;
197
+ }
198
+ // ServerSlot is Radix's Slot for the server: it renders its single child
199
+ // element with the Slot's own props merged onto it (the child wins, class
200
+ // names join, handlers compose).
201
+ function ServerSlot(allProps) {
202
+ const { children, ref: _ref, ...slotProps } = allProps;
203
+ const kids = childElements(Array.isArray(children) ? children.flat(Infinity) : children == null ? [] : [children]);
204
+ const child = kids.length === 1 ? normalizeNode(kids[0]) : undefined;
205
+ if (!isElement(child))
206
+ return kids;
207
+ return { type: child.type, props: mergeSlotProps(slotProps, child.props), children: child.children };
208
+ }
209
+ // toReactElement converts a React element object (made by a package's own
210
+ // React) into Krate's element shape.
211
+ function isReactElement(v) {
212
+ return v != null && typeof v === "object" && R_ELEMENT.has(v.$$typeof);
213
+ }
214
+ function normalizeNode(node) {
215
+ if (!isReactElement(node))
216
+ return node;
217
+ const { children, ref: _ref, ...rest } = node.props ?? {};
218
+ const kids = Array.isArray(children) ? children.flat(Infinity) : children != null ? [children] : [];
219
+ return { type: node.type, props: rest, children: kids };
220
+ }
221
+ function foreignContext(type) {
222
+ if (type.$$typeof === R_PROVIDER)
223
+ return { ctx: type._context, provider: true };
224
+ if (type.$$typeof === R_CONSUMER)
225
+ return { ctx: type._context, provider: false };
226
+ if (type._context)
227
+ return { ctx: type._context, provider: false };
228
+ return { ctx: type, provider: type.Provider === type };
229
+ }
230
+ // withContextValue renders under a foreign Provider: consumers below read the
231
+ // value while its children are resolved.
232
+ function scopedContextFn(ctx, provider) {
233
+ if (provider) {
234
+ const Provider = (props) => props.children;
235
+ Provider.__krateForeignProvider = ctx;
236
+ return Provider;
237
+ }
238
+ const Consumer = (props) => consumerChild(props)(ctx._currentValue);
239
+ Consumer.__krateForeignConsumer = ctx;
240
+ return Consumer;
241
+ }
242
+ function consumerChild(props) {
243
+ const render = Array.isArray(props.children) && props.children.length === 1 ? props.children[0] : props.children;
244
+ if (typeof render !== "function")
245
+ throw new Error("A context Consumer needs a function as its child.");
246
+ return render;
247
+ }
248
+ // exoticType resolves a non-string, non-function element type to something
249
+ // the renderer can run. A pending React.lazy throws its promise.
250
+ function exoticType(type) {
251
+ if (typeof type === "string" || typeof type === "function")
252
+ return type;
253
+ if (type === R_FRAGMENT || type === R_SUSPENSE)
254
+ return Fragment;
255
+ if (type == null || typeof type !== "object")
256
+ throw notRenderable(type);
257
+ switch (type.$$typeof) {
258
+ case R_MEMO:
259
+ return exoticType(type.type);
260
+ case R_LAZY:
261
+ return exoticType(type._init(type._payload));
262
+ case R_FORWARD_REF: {
263
+ let fn = exoticCache.get(type);
264
+ if (!fn) {
265
+ fn = isSlotType(type) ? ServerSlot : (props) => type.render(props, props.ref ?? null);
266
+ exoticCache.set(type, fn);
267
+ }
268
+ return fn;
269
+ }
270
+ case R_PROVIDER:
271
+ case R_CONSUMER:
272
+ case R_CONTEXT: {
273
+ let fn = exoticCache.get(type);
274
+ if (!fn) {
275
+ const { ctx, provider } = foreignContext(type);
276
+ fn = scopedContextFn(ctx, provider);
277
+ exoticCache.set(type, fn);
278
+ }
279
+ return fn;
280
+ }
281
+ }
282
+ throw notRenderable(type);
283
+ }
284
+ // runForeignProvider evaluates `run` with a foreign Provider's value in place.
285
+ function withProviderValue(fn, props, run) {
286
+ const ctx = fn.__krateForeignProvider;
287
+ if (!ctx)
288
+ return run();
289
+ const prev = ctx._currentValue;
290
+ ctx._currentValue = props.value;
291
+ try {
292
+ return run();
293
+ }
294
+ finally {
295
+ ctx._currentValue = prev;
296
+ }
297
+ }
133
298
  function classFallback(type, instance, error) {
134
299
  if (typeof type.getDerivedStateFromError !== "function")
135
300
  throw error;
136
- instance.state = { ...(instance.state || {}), ...(type.getDerivedStateFromError(error) || {}) };
301
+ instance.state = { ...instance.state, ...type.getDerivedStateFromError(error) };
137
302
  try {
138
303
  if (typeof instance.componentDidCatch === "function")
139
304
  instance.componentDidCatch(error, { componentStack: "" });
@@ -143,6 +308,41 @@ function classFallback(type, instance, error) {
143
308
  }
144
309
  return instance.render();
145
310
  }
311
+ /**
312
+ * ServerErrorBoundary is the request-time form of a segment's error.tsx under
313
+ * an async layout: it renders `children`, and when rendering them throws it
314
+ * renders `<fallback error={{ name, message, digest }} />` in their place.
315
+ * notFound(), forbidden(), unauthorized() and redirect() signals pass through.
316
+ * The visitor sees a generic message and a digest; the real error is logged
317
+ * with the same digest. The render's scope records the catch, so the host
318
+ * answers 500 with no-store instead of a cacheable 200.
319
+ */
320
+ export class ServerErrorBoundary {
321
+ constructor(props) {
322
+ this.state = { error: undefined };
323
+ this.props = props;
324
+ }
325
+ static getDerivedStateFromError(error) {
326
+ if (isNotFoundSignal(error) || accessDeniedStatus(error) || redirectTarget(error))
327
+ throw error;
328
+ return { error: describeBoundaryError(error) };
329
+ }
330
+ render() {
331
+ const err = this.state.error;
332
+ if (!err)
333
+ return this.props.children;
334
+ return jsx(this.props.fallback, { error: err });
335
+ }
336
+ }
337
+ function describeBoundaryError(error) {
338
+ const e = error;
339
+ const message = (e && e.message) || String(error);
340
+ const stack = (e && typeof e.stack === "string" && e.stack) || "";
341
+ const digest = sha256Hex(message + "\n" + stack).slice(0, 10);
342
+ console.error(`[krate] Error caught by an error boundary (digest ${digest}):`, error);
343
+ markErrorCaught();
344
+ return { name: "Error", message: "Internal Server Error", digest };
345
+ }
146
346
  function renderNode(node) {
147
347
  if (node == null || node === false)
148
348
  return "";
@@ -158,6 +358,8 @@ function renderNode(node) {
158
358
  return node.map(renderNode).join("");
159
359
  if (typeof node === "object" && "__raw" in node)
160
360
  return node.__raw;
361
+ if (isReactElement(node))
362
+ return renderElement(normalizeNode(node));
161
363
  if (typeof node === "object" && "type" in node)
162
364
  return renderElement(node);
163
365
  return "";
@@ -255,42 +457,70 @@ function isJSXValue(v) {
255
457
  // render their children eagerly (marked __krateEagerChildren, e.g. Link) get
256
458
  // their children and JSX-valued props resolved first, so an async component
257
459
  // passed as a child still renders.
258
- async function resolveTree(node) {
460
+ async function resolveTree(node, vals) {
259
461
  if (isThenable(node))
260
- return resolveTree(await node);
462
+ return resolveTree(await node, vals);
261
463
  if (node == null || typeof node !== "object")
262
464
  return node;
263
465
  if (Array.isArray(node))
264
- return Promise.all(node.map(resolveTree));
466
+ return Promise.all(node.map((n) => resolveTree(n, vals)));
265
467
  if ("__raw" in node)
266
468
  return node;
469
+ if (isReactElement(node))
470
+ node = normalizeNode(node);
267
471
  if (!isElement(node))
268
472
  return node;
269
473
  const { type, props, children } = node;
270
- if (typeof type !== "function") {
271
- return { type, props, children: (await Promise.all(children.map(resolveTree))) };
474
+ if (typeof type === "string") {
475
+ return { type, props, children: (await Promise.all(children.map((n) => resolveTree(n, vals)))) };
476
+ }
477
+ const step = await expandComponent(node, vals);
478
+ return resolveTree(step.out, step.vals);
479
+ }
480
+ // expandComponent runs one component element (function, class, React exotic
481
+ // type, foreign Provider or Consumer) and returns what it rendered, with the
482
+ // context values in scope for that output.
483
+ async function expandComponent(node, vals) {
484
+ const { type, props, children } = node;
485
+ let fn = type;
486
+ while (typeof fn !== "function") {
487
+ try {
488
+ fn = exoticType(fn);
489
+ }
490
+ catch (e) {
491
+ if (!isThenable(e))
492
+ throw e;
493
+ await e;
494
+ }
272
495
  }
273
- const fn = type;
274
496
  if (fn.__krateSuspense)
275
- return resolveTree(children);
497
+ return { out: children, vals };
276
498
  let callProps = { ...props, children };
277
499
  if (fn.__krateEagerChildren) {
278
- const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v) : v]));
279
- callProps = { ...Object.fromEntries(entries), children: await resolveTree(children) };
500
+ const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v, vals) : v]));
501
+ callProps = { ...Object.fromEntries(entries), children: await resolveTree(children, vals) };
280
502
  }
281
503
  if (isClassComponent(fn)) {
282
504
  const instance = new fn(callProps);
283
505
  try {
284
- return await resolveTree(instance.render());
506
+ return { out: await resolveTree(instance.render(), vals), vals };
285
507
  }
286
508
  catch (error) {
287
- return resolveTree(classFallback(fn, instance, error));
509
+ return { out: classFallback(fn, instance, error), vals };
288
510
  }
289
511
  }
290
- let out = fn(callProps);
512
+ if (fn.__krateForeignConsumer) {
513
+ const ctx = fn.__krateForeignConsumer;
514
+ return { out: consumerChild(callProps)(vals?.has(ctx) ? vals.get(ctx) : ctx._currentValue), vals };
515
+ }
516
+ // A client boundary also gets the context values in scope (slotValues).
517
+ let out = fn.__krateClient ? fn(callProps, vals) : fn(callProps);
291
518
  if (isThenable(out))
292
519
  out = await out;
293
- return resolveTree(out);
520
+ if (fn.__krateForeignProvider) {
521
+ return { out, vals: new Map(vals).set(fn.__krateForeignProvider, props.value) };
522
+ }
523
+ return { out, vals };
294
524
  }
295
525
  // rawTextContent renders the children of <script>/<style>: their text is raw
296
526
  // text in HTML, so entity escaping would corrupt JSON-LD and inline code. The
@@ -310,6 +540,18 @@ function rawTextContent(tag, children) {
310
540
  function renderElement(el) {
311
541
  const { type, props, children } = el;
312
542
  // Component
543
+ if (typeof type !== "string" && typeof type !== "function") {
544
+ let fn;
545
+ try {
546
+ fn = exoticType(type);
547
+ }
548
+ catch (e) {
549
+ if (isThenable(e))
550
+ throw asyncInSyncRender("A lazy component");
551
+ throw e;
552
+ }
553
+ return renderElement({ type: fn, props, children });
554
+ }
313
555
  if (typeof type === "function") {
314
556
  if (isClassComponent(type)) {
315
557
  const instance = new type({ ...props, children });
@@ -323,7 +565,7 @@ function renderElement(el) {
323
565
  const result = type({ ...props, children });
324
566
  if (isThenable(result))
325
567
  throw asyncInSyncRender(`<${componentName(type)}>`);
326
- return renderNode(result);
568
+ return withProviderValue(type, props, () => renderNode(result));
327
569
  }
328
570
  // HTML element
329
571
  const tag = type;
@@ -375,90 +617,339 @@ export function Suspense(props) {
375
617
  `<template data-suspense="${id}">${inner}</template>`);
376
618
  }
377
619
  Suspense.__krateSuspense = true;
378
- function describeValue(v) {
379
- if (typeof v === "function")
380
- return "a function";
381
- if (typeof v === "symbol")
382
- return "a symbol";
383
- if (typeof v === "bigint")
384
- return "a bigint";
385
- if (v && typeof v === "object") {
386
- const ctor = Object.getPrototypeOf(v)?.constructor?.name;
387
- return ctor ? `an instance of ${ctor}` : "a non-plain object";
388
- }
389
- return typeof v;
620
+ /**
621
+ * lazy() in a server tree: the loader's module is imported while the page
622
+ * renders and its component renders in place. Nothing is code-split to the
623
+ * browser, so a server-only module can be loaded this way.
624
+ */
625
+ export function lazy(loader) {
626
+ let loaded;
627
+ return async function Lazy(props) {
628
+ loaded ?? (loaded = Promise.resolve(loader()));
629
+ const mod = await loaded;
630
+ const C = typeof mod === "function" ? mod : mod?.default;
631
+ if (typeof C !== "function") {
632
+ throw new Error("lazy(): the loader did not resolve to a component; export it as the module's default or return it from .then()");
633
+ }
634
+ return jsx(C, props);
635
+ };
636
+ }
637
+ // slotValues is the ContextValues entry holding the client context forwarded
638
+ // into a server-rendered slot of a client component: nested client
639
+ // components render inside it, as they would in one React tree.
640
+ const slotValues = {};
641
+ let slotSeq = 0;
642
+ function deferSlot(ctx, node, done) {
643
+ slotSeq = (slotSeq + 1) % 1e9;
644
+ const id = slotSeq.toString(36) + Math.random().toString(36).slice(2, 8);
645
+ const token = `<!--krate-slot:${id}-->`;
646
+ ctx.slots.push({ token, id, node, done: (html) => done(html, id), vals: ctx.vals });
647
+ return token;
390
648
  }
649
+ // slotClose is the marker that ends the HTML of the slot with this id.
650
+ const slotClose = (id) => `<!--/krate-slot:${id}-->`;
651
+ // mergeSlotValues layers the values a component provides at a slot over the
652
+ // ones forwarded into the component.
653
+ function mergeSlotValues(outer, own) {
654
+ if (!own)
655
+ return outer;
656
+ if (!outer || outer.length === 0)
657
+ return own;
658
+ const keys = new Set(own.map((e) => e.k));
659
+ return outer.filter((e) => !keys.has(e.k)).concat(own);
660
+ }
661
+ const flightIsAction = (v) => (isServerAction(v) ? v.actionUrl : undefined);
662
+ const flightIsJSX = (v) => isElement(v) || "__raw" in v;
391
663
  // serializeClientProp converts a prop crossing from the server to a client
392
- // component into JSON-safe data. Server actions become references the client
393
- // chunk turns back into callable proxies; anything else that JSON cannot carry
394
- // faithfully throws with the offending prop path.
664
+ // component into JSON-safe data (see flight-props.ts for the encoding). Server
665
+ // actions become references the client chunk turns back into callable
666
+ // proxies; anything JSON and the tag encoding cannot carry faithfully throws
667
+ // with the offending prop path.
395
668
  function serializeClientProp(v, path, component) {
396
- if (v === null || typeof v === "string" || typeof v === "boolean")
397
- return v;
398
- if (typeof v === "number") {
399
- if (!Number.isFinite(v))
400
- throw clientPropError(path, component, `the number ${v}`);
401
- return v;
402
- }
403
669
  if (v === undefined)
404
670
  return undefined;
405
- if (isServerAction(v))
406
- return { __krateAction: v.actionUrl };
671
+ return encodeProp(v, path, {
672
+ isAction: flightIsAction,
673
+ isJSX: flightIsJSX,
674
+ fail: (p, what, hint) => clientPropError(p, component, what, hint),
675
+ });
676
+ }
677
+ function clientPropError(path, component, what, hint) {
678
+ return new Error(`Prop \`${path}\` passed to client component <${component}> is ${what}, which cannot be sent from a server ` +
679
+ `component to the client. ` +
680
+ (hint || "Pass serializable data (strings, numbers, booleans, null, undefined, bigint, Date, Map, Set, typed arrays, " +
681
+ "plain objects, arrays) or a server action; move event handlers and class instances into the client component."));
682
+ }
683
+ function clientRegistry() {
684
+ const g = globalThis;
685
+ return (g.__krateClientImpls ?? (g.__krateClientImpls = new Map()));
686
+ }
687
+ function clientRefOf(type) {
688
+ return typeof type === "function" ? type.__krateClient : undefined;
689
+ }
690
+ // hasClientElement reports whether a children value holds a client boundary
691
+ // element reachable through host elements and arrays. Server components stop
692
+ // the walk: they render to HTML on their own.
693
+ function hasClientElement(node) {
694
+ if (node == null || typeof node !== "object")
695
+ return false;
696
+ if (Array.isArray(node))
697
+ return node.some(hasClientElement);
698
+ if (!isElement(node))
699
+ return false;
700
+ if (clientRefOf(node.type))
701
+ return true;
702
+ return typeof node.type === "string" && node.children.some(hasClientElement);
703
+ }
704
+ // isSlotValue reports whether a prop holds server-rendered JSX (an element, raw
705
+ // HTML, or an array containing either). Such a prop is a slot: it is rendered
706
+ // on the server and revived on the client like `children`.
707
+ function isSlotValue(v) {
407
708
  if (Array.isArray(v))
408
- return v.map((x, i) => serializeClientProp(x, `${path}[${i}]`, component));
409
- if (typeof v === "object") {
410
- if (isElement(v) || "__raw" in v) {
411
- throw clientPropError(path, component, "JSX", "only `children` can carry server-rendered JSX into a client component");
412
- }
413
- const proto = Object.getPrototypeOf(v);
414
- if (proto !== Object.prototype && proto !== null)
415
- throw clientPropError(path, component, describeValue(v));
416
- const out = {};
417
- for (const [k, x] of Object.entries(v)) {
418
- const sv = serializeClientProp(x, `${path}.${k}`, component);
419
- if (sv !== undefined)
420
- out[k] = sv;
709
+ return v.some(isSlotValue);
710
+ return v != null && typeof v === "object" && (isElement(v) || "__raw" in v);
711
+ }
712
+ // slotProp renders a JSX-valued prop. A slot without client components of its
713
+ // own travels as HTML; one with them (or any slot when tree is set) travels as
714
+ // a tree that keeps those components in the island's Preact tree.
715
+ async function slotProp(v, ctx, tree) {
716
+ if (tree || hasClientElement(v)) {
717
+ const nested = { hydrate: false, component: ctx.component, slots: ctx.slots, vals: ctx.vals };
718
+ const out = await toFlight(v, nested);
719
+ if (nested.hydrate)
720
+ ctx.hydrate = true;
721
+ return { __krateSlotTree: out };
722
+ }
723
+ const slot = { __krateSlotHTML: "" };
724
+ slot.__krateSlotHTML = deferSlot(ctx, v, (html, id) => {
725
+ if (html !== null)
726
+ slot.__krateSlotHTML = html;
727
+ else {
728
+ delete slot.__krateSlotHTML;
729
+ slot.__krateSlotRef = id;
421
730
  }
731
+ });
732
+ return slot;
733
+ }
734
+ // clientProps serializes the props of a client component, rendering the
735
+ // JSX-valued ones (any name, not only `children`) as slots.
736
+ async function clientProps(props, ctx, tree) {
737
+ const out = {};
738
+ for (const [k, v] of Object.entries(props)) {
739
+ if (k === "key" || k === "children")
740
+ continue;
741
+ const sv = isSlotValue(v) ? await slotProp(v, ctx, tree) : serializeClientProp(v, k, ctx.component);
742
+ if (sv !== undefined)
743
+ out[k] = sv;
744
+ }
745
+ return out;
746
+ }
747
+ // toFlight turns the children of a client boundary into a serializable tree
748
+ // that keeps nested client components as components, so they render inside the
749
+ // parent's Preact tree and share its context (Radix Dialog.Root with its
750
+ // Trigger and Content). Everything else is host markup or server-rendered HTML.
751
+ //
752
+ // With inline set (the children of an asChild component) a server component
753
+ // at the top of a child is run here instead of becoming HTML, until a host
754
+ // element or client component comes out: Radix's Slot clones that element and
755
+ // merges its handlers, ref and ARIA props into it, as it does with the React
756
+ // element RSC hands it. Client components in its output stay in the tree.
757
+ async function toFlight(node, ctx, inline = false) {
758
+ if (isThenable(node))
759
+ return toFlight(await node, ctx, inline);
760
+ if (node == null || typeof node === "boolean")
761
+ return [];
762
+ if (typeof node === "string" || typeof node === "number")
763
+ return [node];
764
+ if (Array.isArray(node)) {
765
+ const out = [];
766
+ for (const n of node)
767
+ out.push(...(await toFlight(n, ctx, inline)));
768
+ return out;
769
+ }
770
+ if (typeof node !== "object")
771
+ return [];
772
+ if ("__raw" in node)
773
+ return [htmlSlot(ctx, node)];
774
+ if (inline && isReactElement(node))
775
+ node = normalizeNode(node);
776
+ if (!isElement(node))
777
+ return [];
778
+ const { type, props, children } = node;
779
+ if (typeof type === "string") {
780
+ return [{ $: "e", t: type, p: await clientProps(props, ctx, true), c: await toFlight(children, ctx) }];
781
+ }
782
+ if (type === Link) {
783
+ return [{ $: "e", t: "a", p: linkAttributes({ ...props, children }), c: await toFlight(children, ctx) }];
784
+ }
785
+ const ref = clientRefOf(type);
786
+ if (ref) {
787
+ if (ref.hydrate)
788
+ ctx.hydrate = true;
789
+ const nested = { ...ctx, component: ref.exportName };
790
+ const c = await toFlight(children, nested, !!props.asChild);
791
+ if (nested.hydrate)
792
+ ctx.hydrate = true;
793
+ if (props.asChild)
794
+ warnUncloneable(ref.exportName, c);
795
+ return [{ $: "c", m: ref.moduleId, e: ref.exportName, s: ref.src, p: await clientProps(props, nested, true), c }];
796
+ }
797
+ if (inline) {
798
+ const step = await expandComponent(node, ctx.vals);
799
+ const nested = { ...ctx, vals: step.vals };
800
+ const out = await toFlight(step.out, nested, true);
801
+ if (nested.hydrate)
802
+ ctx.hydrate = true;
422
803
  return out;
423
804
  }
424
- throw clientPropError(path, component, describeValue(v));
805
+ return [htmlSlot(ctx, node)];
425
806
  }
426
- function clientPropError(path, component, what, hint) {
427
- return new Error(`Prop \`${path}\` passed to client component <${component}> is ${what}, which cannot be sent from a server ` +
428
- `component to the client. ` +
429
- (hint || "Pass JSON-serializable data (strings, numbers, booleans, null, plain objects, arrays) or a server action; " +
430
- "move event handlers and class instances into the client component."));
807
+ // htmlSlot is a server-rendered part of a children tree: { $: "h", h: html },
808
+ // or { $: "h", r: id } once the component has rendered it into the document.
809
+ function htmlSlot(ctx, node) {
810
+ const slot = { $: "h", h: "" };
811
+ slot.h = deferSlot(ctx, node, (html, id) => {
812
+ if (html !== null)
813
+ slot.h = html;
814
+ else {
815
+ delete slot.h;
816
+ slot.r = id;
817
+ }
818
+ });
819
+ return slot;
820
+ }
821
+ // propsScript is the JSON script that carries a real-React island's props,
822
+ // placed just before its <krate-island>. Every "<" is escaped, so no
823
+ // "</script" or "<!--" in a value can end the script or open a comment.
824
+ function propsScript(data) {
825
+ return `<script type="application/json" data-krate-props>${JSON.stringify(data).replace(/</g, "\\u003c")}</script>`;
826
+ }
827
+ // ISLAND_OPEN starts the comment that opens a Preact island; ISLAND_CLOSE is
828
+ // the comment that ends it. The island's HTML sits between them with no
829
+ // element of its own, so child combinators and sibling selectors of the
830
+ // parent (space-y-*, divide-*, > :first-child) see the component's root
831
+ // nodes, as in React.
832
+ export const ISLAND_OPEN = "krate-island:";
833
+ export const ISLAND_CLOSE = "<!--/krate-island-->";
834
+ // islandOpen is the opening comment of a Preact island: its module, export,
835
+ // chunk and props as JSON. "<", ">" and "--" are escaped (they occur only in
836
+ // 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
+ .replace(/</g, "\\u003c")
840
+ .replace(/>/g, "\\u003e")
841
+ .replace(/--/g, "-\\u002d");
842
+ return `<!--${ISLAND_OPEN}${json}-->`;
843
+ }
844
+ const warnedUncloneable = new Set();
845
+ // warnUncloneable reports an asChild component whose child reached the
846
+ // client as server-rendered HTML (raw HTML, a deferred slot), which its Slot
847
+ // cannot clone or merge props into.
848
+ function warnUncloneable(component, tree) {
849
+ if (!tree.some((n) => n != null && typeof n === "object" && n.$ === "h"))
850
+ return;
851
+ if (warnedUncloneable.has(component))
852
+ return;
853
+ warnedUncloneable.add(component);
854
+ console.warn(`[krate] <${component} asChild> received a child rendered to HTML, so it cannot merge its props and handlers ` +
855
+ `into it. Pass a single element or a component that renders one (not raw HTML) as the child.`);
856
+ }
857
+ function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
858
+ const out = {};
859
+ for (const key of Object.keys(ns)) {
860
+ const v = ns[key];
861
+ const isComponentName = /^[A-Z]/.test(key);
862
+ if (isComponentName && typeof v === "function") {
863
+ out[key] = clientBoundary(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
864
+ }
865
+ else if (isComponentName && v && typeof v === "object" && !Array.isArray(v)) {
866
+ out[key] = wrapClientNamespace(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
867
+ }
868
+ else {
869
+ out[key] = v;
870
+ }
871
+ }
872
+ return out;
431
873
  }
432
874
  /**
433
- * clientBoundary wraps an export of a `"use client"` module for the server
434
- * bundle of a page that renders server components. The server renders the
435
- * component's initial HTML (render) into a <krate-island> marker carrying its
436
- * serialized props; the per-module client chunk at src hydrates it in the
437
- * browser. Children are rendered on the server and passed as HTML.
875
+ * clientBoundary wraps an export of a `"use client"` module, or a component
876
+ * of a React package, for the server bundle of a page that renders server
877
+ * components. The server renders the component's initial HTML (render) and,
878
+ * when it hydrates, puts it between <!--krate-island:{...}--> (module,
879
+ * export, chunk and serialized props) and <!--/krate-island--> with no
880
+ * element around it; the per-module client chunk at src hydrates those nodes
881
+ * in the browser. A real-React island (flight) gets a <krate-island> element
882
+ * instead, preceded by a JSON script with its props, because createRoot needs
883
+ * a container. A component without state or effects (hydrate
884
+ * false, an icon) is plain HTML. Children are rendered on the server into the
885
+ * component's HTML and adopted there by the browser (see DeferredSlot), or,
886
+ * when they hold client components of their own, sent as a tree that keeps
887
+ * those components in the same Preact tree. The children of an asChild component
888
+ * always travel as a tree, with a server component at the top of a child run
889
+ * to the element it renders, so the component's Slot can clone it. A
890
+ * namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
891
+ * tree (a real-React island rebuilds them as elements, not HTML).
438
892
  */
439
- export function clientBoundary(moduleId, exportName, src, impl, render) {
893
+ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate = true, flight = false) {
894
+ if (impl && typeof impl === "object" && !Array.isArray(impl)) {
895
+ return wrapClientNamespace(moduleId, exportName, src, impl, render, hydrate);
896
+ }
440
897
  if (typeof impl !== "function")
441
898
  return impl;
442
899
  const name = impl.displayName || impl.name || exportName;
443
- const Boundary = async (props) => {
900
+ const Boundary = async (props, vals) => {
444
901
  const { children, ...rest } = props || {};
445
- const data = {};
446
- for (const [k, v] of Object.entries(rest)) {
447
- if (k === "key")
448
- continue;
449
- const sv = serializeClientProp(v, k, name);
450
- if (sv !== undefined)
451
- data[k] = sv;
452
- }
902
+ const slots = [];
903
+ const slotCtx = { hydrate: false, component: name, slots, vals };
904
+ const data = await clientProps(rest, slotCtx, flight);
453
905
  const hasChildren = children != null && !(Array.isArray(children) && children.length === 0);
454
- const childrenHTML = hasChildren ? await renderToStringAsync(children) : null;
455
- if (childrenHTML !== null)
456
- data.__krateChildren = childrenHTML;
457
- const html = render(impl, data, childrenHTML);
458
- return raw(`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
459
- `data-src="${escapeHTML(src)}" data-props="${escapeHTML(JSON.stringify(data))}">${html}</krate-island>`);
906
+ let hydrates = hydrate || slotCtx.hydrate;
907
+ // An asChild component clones its child, so the child travels as a tree.
908
+ const asChild = !!rest.asChild;
909
+ if (hasChildren && (flight || asChild || hasClientElement(children))) {
910
+ const ctx = { hydrate: false, component: exportName, slots, vals };
911
+ data.__krateTree = await toFlight(children, ctx, asChild);
912
+ if (ctx.hydrate)
913
+ hydrates = true;
914
+ if (asChild)
915
+ warnUncloneable(exportName, data.__krateTree);
916
+ }
917
+ else if (hasChildren) {
918
+ data.__krateChildren = deferSlot(slotCtx, children, (html, id) => (data.__krateChildren = html ?? { __krateSlotRef: id }));
919
+ }
920
+ const fwd = vals?.get(slotValues);
921
+ const capture = {};
922
+ let html = render(impl, data, null, fwd, capture);
923
+ const rendered = await Promise.all(slots.map(async (s) => {
924
+ const scope = mergeSlotValues(fwd, capture[s.token]);
925
+ const base = s.vals ?? vals;
926
+ const inner = scope ? new Map(base).set(slotValues, scope) : base;
927
+ return renderNode(await resolveTree(s.node, inner));
928
+ }));
929
+ // A slot whose token is in the render is in the document: the browser
930
+ // adopts those nodes, so they are not sent again inside the props. An
931
+ // island keeps the token as the slot's open marker and closes it after
932
+ // the HTML; a component without an island needs no markers.
933
+ const placed = slots.map((s) => html.includes(s.token));
934
+ slots.forEach((s, i) => {
935
+ s.done(placed[i] ? null : rendered[i]);
936
+ html = html.split(s.token).join(hydrates ? s.token + rendered[i] + slotClose(s.id) : rendered[i]);
937
+ });
938
+ if (!hydrates)
939
+ return raw(html);
940
+ // A real-React island (flight) mounts with createRoot, which needs an
941
+ // element of its own; a Preact island hydrates the nodes between its two
942
+ // comments in place.
943
+ if (!flight)
944
+ return raw(islandOpen(moduleId, exportName, src, data) + html + ISLAND_CLOSE);
945
+ return raw(propsScript(data) +
946
+ `<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
947
+ `data-src="${escapeHTML(src)}">${html}</krate-island>`);
460
948
  };
461
949
  Object.defineProperty(Boundary, "name", { value: name });
950
+ const ref = { moduleId, exportName, src, impl, hydrate };
951
+ Boundary.__krateClient = ref;
952
+ clientRegistry().set(`${moduleId}#${exportName}`, ref);
462
953
  return Boundary;
463
954
  }
464
955
  // Built-in Components (server stubs)
@@ -472,55 +963,81 @@ export const HEAD_CLOSE = "<!--/krate-head-->";
472
963
  export function Head(props) {
473
964
  return [raw(HEAD_OPEN), props.children ?? "", raw(HEAD_CLOSE)];
474
965
  }
475
- // Script - renders a <script> tag.
966
+ // Script and Style render the element in place with every attribute (src,
967
+ // defer, async, data-*, nonce, ...), as the static compiler does. Their
968
+ // children are raw text. `strategy` is next/script's and has no HTML meaning.
476
969
  export function Script(props) {
477
- if (props.src) {
478
- return `<script src="${escapeHTML(props.src)}"></script>`;
479
- }
480
- return `<script>${props.children ?? ""}</script>`;
970
+ const { strategy: _strategy, ...rest } = props;
971
+ return jsx("script", rest);
481
972
  }
482
- // Style - renders a <style> tag.
483
973
  export function Style(props) {
484
- return `<style>${props.children ?? ""}</style>`;
974
+ return jsx("style", props);
485
975
  }
486
- // Link - renders an <a> tag wired for SPA navigation (server renderer).
487
- export function Link(props) {
488
- const { href = "", prefetch, replace, scroll, children, ...rest } = props;
489
- const attrs = [];
976
+ // linkAttributes computes the attributes of a <Link> anchor. An empty string
977
+ // stands for a boolean attribute.
978
+ function linkAttributes(props) {
979
+ const { href = "", prefetch, replace, scroll, basePath: noBase, children: _children, ...rest } = props;
980
+ const attrs = {};
981
+ // basePath={false}: the URL belongs to another app on the host.
982
+ const outside = noBase === false;
490
983
  if (href)
491
- attrs.push(`href="${escapeHTML(href)}"`);
492
- const external = /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
984
+ attrs.href = outside ? href : withBase(href);
985
+ const external = outside ||
986
+ /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
493
987
  href.startsWith("//") ||
494
988
  rest.target === "_blank" ||
495
989
  rest.download !== undefined;
496
990
  if (external) {
497
- attrs.push("data-krate-external");
991
+ attrs["data-krate-external"] = "";
992
+ if (outside)
993
+ attrs["data-krate-no-base"] = "";
498
994
  }
499
995
  else {
500
- attrs.push("data-krate-link");
996
+ attrs["data-krate-link"] = "";
501
997
  if (prefetch !== false)
502
- attrs.push("data-prefetch");
998
+ attrs["data-prefetch"] = "";
503
999
  if (replace)
504
- attrs.push("data-krate-replace");
1000
+ attrs["data-krate-replace"] = "";
505
1001
  if (scroll === false)
506
- attrs.push('data-krate-scroll="false"');
1002
+ attrs["data-krate-scroll"] = "false";
507
1003
  }
508
1004
  for (const key of ["target", "rel", "title", "id", "aria-label"]) {
509
1005
  const v = rest[key];
510
1006
  if (v !== undefined && v !== null)
511
- attrs.push(`${key}="${escapeHTML(String(v))}"`);
1007
+ attrs[key] = String(v);
512
1008
  }
513
1009
  if (rest.target === "_blank" && rest.rel === undefined)
514
- attrs.push('rel="noopener noreferrer"');
1010
+ attrs.rel = "noopener noreferrer";
515
1011
  if (rest.className)
516
- attrs.push(`class="${escapeHTML(String(rest.className))}"`);
517
- const inner = children != null ? renderNode(children) : "";
1012
+ attrs.class = String(rest.className);
1013
+ // Every other attribute reaches the anchor, so data-*, aria-*, class and
1014
+ // style that a Slot (asChild) merges onto a Link are not lost.
1015
+ for (const [key, v] of Object.entries(rest)) {
1016
+ const name = ATTR_ALIASES[key] || key;
1017
+ if (name in attrs || v == null || v === false || typeof v === "function")
1018
+ continue;
1019
+ if (key === "key" || key === "ref" || key === "className" || key === "dangerouslySetInnerHTML" || key.startsWith("on") || key.startsWith("__"))
1020
+ continue;
1021
+ if (key === "style" && typeof v === "object") {
1022
+ const css = styleString(v);
1023
+ if (css)
1024
+ attrs.style = css;
1025
+ continue;
1026
+ }
1027
+ attrs[name] = v === true ? "" : String(v);
1028
+ }
1029
+ return attrs;
1030
+ }
1031
+ // Link - renders an <a> tag wired for SPA navigation (server renderer).
1032
+ export function Link(props) {
1033
+ const attrs = Object.entries(linkAttributes(props)).map(([k, v]) => v === "" ? k : `${k}="${escapeHTML(v)}"`);
1034
+ const inner = props.children != null ? renderNode(props.children) : "";
518
1035
  return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
519
1036
  }
520
1037
  Link.__krateEagerChildren = true;
521
1038
  // Image - renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
522
1039
  export function Image(props) {
523
- const { src = "", alt = "", width, height, ...rest } = props;
1040
+ const { src = "", alt = "", width, height } = props;
524
1041
  const attrs = [];
525
1042
  if (src)
526
1043
  attrs.push(`src="${escapeHTML(src)}"`);