@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.3

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 (152) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +272 -16
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/ssr-core-behavior.test.js +3 -515
  63. package/dist/testing.d.ts +59 -0
  64. package/dist/testing.js +88 -0
  65. package/dist/testing.test.js +73 -0
  66. package/package.json +9 -1
  67. package/dist/action-context.test.js +0 -72
  68. package/dist/base-path.test.js +0 -88
  69. package/dist/class-component.test.js +0 -462
  70. package/dist/class-helpers.test.js +0 -169
  71. package/dist/context.test.js +0 -57
  72. package/dist/derived.test.js +0 -140
  73. package/dist/dev-overlay.test.js +0 -165
  74. package/dist/discrete.test.js +0 -100
  75. package/dist/dom.test.d.ts +0 -1
  76. package/dist/dom.test.js +0 -39
  77. package/dist/effect-errors.test.d.ts +0 -1
  78. package/dist/effect-errors.test.js +0 -199
  79. package/dist/effects.test.d.ts +0 -1
  80. package/dist/effects.test.js +0 -485
  81. package/dist/handler-routing.test.d.ts +0 -1
  82. package/dist/handler-routing.test.js +0 -99
  83. package/dist/highlight-bind.test.d.ts +0 -1
  84. package/dist/highlight-bind.test.js +0 -124
  85. package/dist/highlight.test.d.ts +0 -1
  86. package/dist/highlight.test.js +0 -56
  87. package/dist/lanes.test.d.ts +0 -1
  88. package/dist/lanes.test.js +0 -59
  89. package/dist/list.test.d.ts +0 -1
  90. package/dist/list.test.js +0 -435
  91. package/dist/metadata.test.d.ts +0 -1
  92. package/dist/metadata.test.js +0 -167
  93. package/dist/navigation.test.d.ts +0 -1
  94. package/dist/navigation.test.js +0 -130
  95. package/dist/optimistic-lanes.test.d.ts +0 -1
  96. package/dist/optimistic-lanes.test.js +0 -45
  97. package/dist/patterns.test.d.ts +0 -1
  98. package/dist/patterns.test.js +0 -125
  99. package/dist/portal.test.d.ts +0 -1
  100. package/dist/portal.test.js +0 -99
  101. package/dist/react-effects.test.d.ts +0 -1
  102. package/dist/react-effects.test.js +0 -133
  103. package/dist/react-suspense.test.d.ts +0 -1
  104. package/dist/react-suspense.test.js +0 -194
  105. package/dist/react.test.d.ts +0 -1
  106. package/dist/react.test.js +0 -60
  107. package/dist/react19.test.d.ts +0 -1
  108. package/dist/react19.test.js +0 -176
  109. package/dist/reactivity-core.test.d.ts +0 -1
  110. package/dist/reactivity-core.test.js +0 -152
  111. package/dist/reconcile.test.d.ts +0 -1
  112. package/dist/reconcile.test.js +0 -110
  113. package/dist/refs.test.d.ts +0 -1
  114. package/dist/refs.test.js +0 -257
  115. package/dist/router-layout.test.d.ts +0 -1
  116. package/dist/router-layout.test.js +0 -249
  117. package/dist/router-slots.test.d.ts +0 -1
  118. package/dist/router-slots.test.js +0 -144
  119. package/dist/router-speculation.test.d.ts +0 -1
  120. package/dist/router-speculation.test.js +0 -25
  121. package/dist/router-styles.test.d.ts +0 -1
  122. package/dist/router-styles.test.js +0 -98
  123. package/dist/router.test.d.ts +0 -1
  124. package/dist/router.test.js +0 -36
  125. package/dist/server-async.test.d.ts +0 -1
  126. package/dist/server-async.test.js +0 -216
  127. package/dist/server-highlight.test.d.ts +0 -1
  128. package/dist/server-highlight.test.js +0 -32
  129. package/dist/signal-lanes.test.d.ts +0 -1
  130. package/dist/signal-lanes.test.js +0 -32
  131. package/dist/slots.test.d.ts +0 -1
  132. package/dist/slots.test.js +0 -187
  133. package/dist/snapshots.test.d.ts +0 -1
  134. package/dist/snapshots.test.js +0 -208
  135. package/dist/ssr-core.test.d.ts +0 -1
  136. package/dist/ssr-core.test.js +0 -324
  137. package/dist/static-memory.test.d.ts +0 -1
  138. package/dist/static-memory.test.js +0 -26
  139. package/dist/storage.test.d.ts +0 -1
  140. package/dist/storage.test.js +0 -46
  141. package/dist/suspense-actions.test.d.ts +0 -1
  142. package/dist/suspense-actions.test.js +0 -72
  143. package/dist/suspense.test.d.ts +0 -1
  144. package/dist/suspense.test.js +0 -556
  145. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  146. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → testing.test.d.ts} +0 -0
package/dist/server.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
2
2
  export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
3
3
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
4
+ export { after } from './after.js';
5
+ export { getPlatform, getCloudflareContext } from './platform.js';
6
+ export type { PlatformContext, PlatformTarget, PlatformExecutionContext, CloudflareContext, KrateCloudflareEnv } from './platform.js';
7
+ export type { AfterTask, KrateRequest, KrateRequestCookies, KrateNextURL } from './after.js';
4
8
  export type { RevalidatePathType, UnstableCacheOptions } from './cache.js';
5
9
  export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
6
10
  export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
@@ -55,13 +59,19 @@ interface SuspenseProps {
55
59
  export declare function Suspense(props: SuspenseProps): JSXNode;
56
60
  type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null) => string;
57
61
  /**
58
- * clientBoundary wraps an export of a `"use client"` module for the server
59
- * bundle of a page that renders server components. The server renders the
60
- * component's initial HTML (render) into a <krate-island> marker carrying its
62
+ * clientBoundary wraps an export of a `"use client"` module, or a component
63
+ * of a React package, for the server bundle of a page that renders server
64
+ * components. The server renders the component's initial HTML (render) and,
65
+ * when it hydrates, puts it in a <krate-island> marker carrying its
61
66
  * serialized props; the per-module client chunk at src hydrates it in the
62
- * browser. Children are rendered on the server and passed as HTML.
67
+ * browser. A component without state or effects (hydrate false, an icon)
68
+ * is plain HTML. Children are rendered on the server and passed as HTML, or,
69
+ * when they hold client components of their own, as a tree that keeps those
70
+ * components in the same Preact tree. A namespace export (Radix's Dialog) is
71
+ * wrapped member by member. With `flight` the children always travel as a
72
+ * tree (a real-React island rebuilds them as elements, not HTML).
63
73
  */
64
- export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender): unknown;
74
+ export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean): unknown;
65
75
  export declare const HEAD_OPEN = "<!--krate-head-->";
66
76
  export declare const HEAD_CLOSE = "<!--/krate-head-->";
67
77
  export declare function Head(props: {
package/dist/server.js CHANGED
@@ -5,6 +5,8 @@ import { withBase } from './base-path.js';
5
5
  import { highlight as highlightCode, trimSpace } from './highlight.js';
6
6
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
7
7
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
8
+ export { after } from './after.js';
9
+ export { getPlatform, getCloudflareContext } from './platform.js';
8
10
  export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
9
11
  export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
10
12
  export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
@@ -430,14 +432,114 @@ function clientPropError(path, component, what, hint) {
430
432
  (hint || "Pass JSON-serializable data (strings, numbers, booleans, null, plain objects, arrays) or a server action; " +
431
433
  "move event handlers and class instances into the client component."));
432
434
  }
435
+ function clientRegistry() {
436
+ const g = globalThis;
437
+ return (g.__krateClientImpls ?? (g.__krateClientImpls = new Map()));
438
+ }
439
+ function clientRefOf(type) {
440
+ return typeof type === "function" ? type.__krateClient : undefined;
441
+ }
442
+ // hasClientElement reports whether a children value holds a client boundary
443
+ // element reachable through host elements and arrays. Server components stop
444
+ // the walk: they render to HTML on their own.
445
+ function hasClientElement(node) {
446
+ if (node == null || typeof node !== "object")
447
+ return false;
448
+ if (Array.isArray(node))
449
+ return node.some(hasClientElement);
450
+ if (!isElement(node))
451
+ return false;
452
+ if (clientRefOf(node.type))
453
+ return true;
454
+ return typeof node.type === "string" && node.children.some(hasClientElement);
455
+ }
456
+ function flightProps(props, ctx) {
457
+ const out = {};
458
+ for (const [k, v] of Object.entries(props)) {
459
+ if (k === "key" || k === "children")
460
+ continue;
461
+ const sv = serializeClientProp(v, k, ctx.component);
462
+ if (sv !== undefined)
463
+ out[k] = sv;
464
+ }
465
+ return out;
466
+ }
467
+ // toFlight turns the children of a client boundary into a serializable tree
468
+ // that keeps nested client components as components, so they render inside the
469
+ // parent's Preact tree and share its context (Radix Dialog.Root with its
470
+ // Trigger and Content). Everything else is host markup or server-rendered HTML.
471
+ async function toFlight(node, ctx) {
472
+ if (isThenable(node))
473
+ return toFlight(await node, ctx);
474
+ if (node == null || typeof node === "boolean")
475
+ return [];
476
+ if (typeof node === "string" || typeof node === "number")
477
+ return [node];
478
+ if (Array.isArray(node)) {
479
+ const out = [];
480
+ for (const n of node)
481
+ out.push(...(await toFlight(n, ctx)));
482
+ return out;
483
+ }
484
+ if (typeof node !== "object")
485
+ return [];
486
+ if ("__raw" in node)
487
+ return [{ $: "h", h: node.__raw }];
488
+ if (!isElement(node))
489
+ return [];
490
+ const { type, props, children } = node;
491
+ if (typeof type === "string") {
492
+ return [{ $: "e", t: type, p: flightProps(props, ctx), c: await toFlight(children, ctx) }];
493
+ }
494
+ if (type === Link) {
495
+ return [{ $: "e", t: "a", p: linkAttributes({ ...props, children }), c: await toFlight(children, ctx) }];
496
+ }
497
+ const ref = clientRefOf(type);
498
+ if (ref) {
499
+ if (ref.hydrate)
500
+ ctx.hydrate = true;
501
+ const nested = { ...ctx, component: ref.exportName };
502
+ const c = await toFlight(children, nested);
503
+ if (nested.hydrate)
504
+ ctx.hydrate = true;
505
+ return [{ $: "c", m: ref.moduleId, e: ref.exportName, s: ref.src, p: flightProps(props, nested), c }];
506
+ }
507
+ return [{ $: "h", h: await renderToStringAsync(node) }];
508
+ }
509
+ function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
510
+ const out = {};
511
+ for (const key of Object.keys(ns)) {
512
+ const v = ns[key];
513
+ const isComponentName = /^[A-Z]/.test(key);
514
+ if (isComponentName && typeof v === "function") {
515
+ out[key] = clientBoundary(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
516
+ }
517
+ else if (isComponentName && v && typeof v === "object" && !Array.isArray(v)) {
518
+ out[key] = wrapClientNamespace(moduleId, `${exportName}.${key}`, src, v, render, hydrate);
519
+ }
520
+ else {
521
+ out[key] = v;
522
+ }
523
+ }
524
+ return out;
525
+ }
433
526
  /**
434
- * clientBoundary wraps an export of a `"use client"` module for the server
435
- * bundle of a page that renders server components. The server renders the
436
- * component's initial HTML (render) into a <krate-island> marker carrying its
527
+ * clientBoundary wraps an export of a `"use client"` module, or a component
528
+ * of a React package, for the server bundle of a page that renders server
529
+ * components. The server renders the component's initial HTML (render) and,
530
+ * when it hydrates, puts it in a <krate-island> marker carrying its
437
531
  * serialized props; the per-module client chunk at src hydrates it in the
438
- * browser. Children are rendered on the server and passed as HTML.
532
+ * browser. A component without state or effects (hydrate false, an icon)
533
+ * is plain HTML. Children are rendered on the server and passed as HTML, or,
534
+ * when they hold client components of their own, as a tree that keeps those
535
+ * components in the same Preact tree. A namespace export (Radix's Dialog) is
536
+ * wrapped member by member. With `flight` the children always travel as a
537
+ * tree (a real-React island rebuilds them as elements, not HTML).
439
538
  */
440
- export function clientBoundary(moduleId, exportName, src, impl, render) {
539
+ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate = true, flight = false) {
540
+ if (impl && typeof impl === "object" && !Array.isArray(impl)) {
541
+ return wrapClientNamespace(moduleId, exportName, src, impl, render, hydrate);
542
+ }
441
543
  if (typeof impl !== "function")
442
544
  return impl;
443
545
  const name = impl.displayName || impl.name || exportName;
@@ -452,14 +554,28 @@ export function clientBoundary(moduleId, exportName, src, impl, render) {
452
554
  data[k] = sv;
453
555
  }
454
556
  const hasChildren = children != null && !(Array.isArray(children) && children.length === 0);
455
- const childrenHTML = hasChildren ? await renderToStringAsync(children) : null;
456
- if (childrenHTML !== null)
557
+ let hydrates = hydrate;
558
+ let childrenHTML = null;
559
+ if (hasChildren && (flight || hasClientElement(children))) {
560
+ const ctx = { hydrate: false, component: exportName };
561
+ data.__krateTree = await toFlight(children, ctx);
562
+ if (ctx.hydrate)
563
+ hydrates = true;
564
+ }
565
+ else if (hasChildren) {
566
+ childrenHTML = await renderToStringAsync(children);
457
567
  data.__krateChildren = childrenHTML;
568
+ }
458
569
  const html = render(impl, data, childrenHTML);
570
+ if (!hydrates)
571
+ return raw(html);
459
572
  return raw(`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
460
573
  `data-src="${escapeHTML(src)}" data-props="${escapeHTML(JSON.stringify(data))}">${html}</krate-island>`);
461
574
  };
462
575
  Object.defineProperty(Boundary, "name", { value: name });
576
+ const ref = { moduleId, exportName, src, impl, hydrate };
577
+ Boundary.__krateClient = ref;
578
+ clientRegistry().set(`${moduleId}#${exportName}`, ref);
463
579
  return Boundary;
464
580
  }
465
581
  // Built-in Components (server stubs)
@@ -484,38 +600,49 @@ export function Script(props) {
484
600
  export function Style(props) {
485
601
  return `<style>${props.children ?? ""}</style>`;
486
602
  }
487
- // Link - renders an <a> tag wired for SPA navigation (server renderer).
488
- export function Link(props) {
489
- const { href = "", prefetch, replace, scroll, children, ...rest } = props;
490
- const attrs = [];
603
+ // linkAttributes computes the attributes of a <Link> anchor. An empty string
604
+ // stands for a boolean attribute.
605
+ function linkAttributes(props) {
606
+ const { href = "", prefetch, replace, scroll, basePath: noBase, children: _children, ...rest } = props;
607
+ const attrs = {};
608
+ // basePath={false}: the URL belongs to another app on the host.
609
+ const outside = noBase === false;
491
610
  if (href)
492
- attrs.push(`href="${escapeHTML(withBase(href))}"`);
493
- const external = /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
611
+ attrs.href = outside ? href : withBase(href);
612
+ const external = outside ||
613
+ /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
494
614
  href.startsWith("//") ||
495
615
  rest.target === "_blank" ||
496
616
  rest.download !== undefined;
497
617
  if (external) {
498
- attrs.push("data-krate-external");
618
+ attrs["data-krate-external"] = "";
619
+ if (outside)
620
+ attrs["data-krate-no-base"] = "";
499
621
  }
500
622
  else {
501
- attrs.push("data-krate-link");
623
+ attrs["data-krate-link"] = "";
502
624
  if (prefetch !== false)
503
- attrs.push("data-prefetch");
625
+ attrs["data-prefetch"] = "";
504
626
  if (replace)
505
- attrs.push("data-krate-replace");
627
+ attrs["data-krate-replace"] = "";
506
628
  if (scroll === false)
507
- attrs.push('data-krate-scroll="false"');
629
+ attrs["data-krate-scroll"] = "false";
508
630
  }
509
631
  for (const key of ["target", "rel", "title", "id", "aria-label"]) {
510
632
  const v = rest[key];
511
633
  if (v !== undefined && v !== null)
512
- attrs.push(`${key}="${escapeHTML(String(v))}"`);
634
+ attrs[key] = String(v);
513
635
  }
514
636
  if (rest.target === "_blank" && rest.rel === undefined)
515
- attrs.push('rel="noopener noreferrer"');
637
+ attrs.rel = "noopener noreferrer";
516
638
  if (rest.className)
517
- attrs.push(`class="${escapeHTML(String(rest.className))}"`);
518
- const inner = children != null ? renderNode(children) : "";
639
+ attrs.class = String(rest.className);
640
+ return attrs;
641
+ }
642
+ // Link - renders an <a> tag wired for SPA navigation (server renderer).
643
+ export function Link(props) {
644
+ const attrs = Object.entries(linkAttributes(props)).map(([k, v]) => v === "" ? k : `${k}="${escapeHTML(v)}"`);
645
+ const inner = props.children != null ? renderNode(props.children) : "";
519
646
  return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
520
647
  }
521
648
  Link.__krateEagerChildren = true;
@@ -1,42 +1,14 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { jsx, renderToString, goComponent } from './server';
2
+ import { clientBoundary, jsx, renderToString, renderToStringAsync } from './server';
3
3
  describe('renderToString', () => {
4
4
  it('renders nested elements and escapes text', () => {
5
5
  const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
6
6
  expect(renderToString(node)).toBe('<div class="x"><span>a &amp; b</span></div>');
7
7
  });
8
- it('renders void elements without a close tag', () => {
9
- expect(renderToString(jsx('img', { src: '/x.png', alt: 'y' }))).toBe('<img src="/x.png" alt="y">');
10
- });
11
- it('invokes function components', () => {
12
- const Comp = () => jsx('p', { children: 'hi' });
13
- expect(renderToString(jsx(Comp, {}))).toBe('<p>hi</p>');
14
- });
15
8
  it('drops event and internal props', () => {
16
9
  const node = jsx('button', { onClick: () => undefined, children: 'x' });
17
10
  expect(renderToString(node)).toBe('<button>x</button>');
18
11
  });
19
- it('omits null/false-valued attributes', () => {
20
- expect(renderToString(jsx('input', { disabled: false, value: null }))).toBe('<input>');
21
- expect(renderToString(jsx('input', { disabled: true }))).toBe('<input disabled>');
22
- });
23
- it('passes raw HTML through without escaping', () => {
24
- expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
25
- });
26
- it('maps React attribute aliases like the compiler renderer', () => {
27
- const html = renderToString(jsx('label', { className: 'x', htmlFor: 'name', children: 'Name' }));
28
- expect(html).toBe('<label class="x" for="name">Name</label>');
29
- });
30
- it('serializes style objects with unitless exceptions', () => {
31
- const html = renderToString(jsx('div', {
32
- style: { backgroundColor: 'red', marginTop: 4, opacity: 0.5, zIndex: 2, '--raw': 1 },
33
- }));
34
- expect(html).toBe('<div style="background-color:red;margin-top:4px;opacity:0.5;z-index:2;--raw:1"></div>');
35
- });
36
- it('renders dangerouslySetInnerHTML instead of an attribute', () => {
37
- const html = renderToString(jsx('div', { dangerouslySetInnerHTML: { __html: '<b>hi</b>' } }));
38
- expect(html).toBe('<div><b>hi</b></div>');
39
- });
40
12
  it('blocks javascript: URLs and drops reserved props', () => {
41
13
  const html = renderToString(jsx('a', { href: 'javascript:alert(1)', ref: {}, key: 'k', children: 'x' }));
42
14
  expect(html).toContain('href="javascript:throw new Error(');
@@ -44,38 +16,7 @@ describe('renderToString', () => {
44
16
  expect(html).not.toContain(' key=');
45
17
  });
46
18
  });
47
- describe('goComponent', () => {
48
- it('inlines baked HTML for an annotated server-tier call site', () => {
49
- const baked = { 'gc3_5_Badge': '<span class="badge">Hi</span>' };
50
- const node = goComponent('Badge', 'server', baked, { __krateGoId: 'gc3_5_Badge', label: 'Hi' });
51
- expect(renderToString(node)).toBe('<span class="badge">Hi</span>');
52
- });
53
- it('emits a marker for runtime-tier calls, encoding props + children', () => {
54
- const node = goComponent('Clock', 'runtime', null, { zone: 'UTC', children: ['a ', jsx('b', { children: 'c' })] }, 45);
55
- const html = renderToString(node);
56
- const m = html.match(/^<!--krate-go:Clock:(\d+):([A-Za-z0-9_-]+)-->$/);
57
- expect(m).not.toBeNull();
58
- expect(m[1]).toBe('45');
59
- const b64 = m[2].replace(/-/g, '+').replace(/_/g, '/');
60
- const payload = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
61
- expect(payload.zone).toBe('UTC');
62
- expect(payload.children).toBe('a <b>c</b>');
63
- });
64
- it('falls back to a marker when a server call site is not in the baked map', () => {
65
- const node = goComponent('Badge', 'server', {}, { __krateGoId: 'missing', label: 'Hi' });
66
- expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
67
- });
68
- });
69
19
  describe('server actions', () => {
70
- it('renders an action function as a POST form endpoint', () => {
71
- const action = Object.assign(() => undefined, {
72
- actionUrl: '/base/__krate/action/a123',
73
- });
74
- const html = renderToString(jsx('form', { action, children: [] }));
75
- expect(html).toContain('action="/base/__krate/action/a123"');
76
- expect(html).toContain('method="post"');
77
- expect(html).toContain('data-krate-action');
78
- });
79
20
  it('renders a formAction function as a POST submit endpoint', () => {
80
21
  const action = Object.assign(() => undefined, {
81
22
  actionUrl: '/__krate/action/a456',
@@ -86,3 +27,54 @@ describe('server actions', () => {
86
27
  expect(html).toContain('data-krate-action');
87
28
  });
88
29
  });
30
+ describe('clientBoundary', () => {
31
+ // The render callback stands in for the Preact render module: it echoes the
32
+ // serialized props so the test sees exactly what travels to the client.
33
+ const render = (_c, props) => `<i>${JSON.stringify(props)}</i>`;
34
+ it('renders a stateless component as plain HTML without an island', async () => {
35
+ const Icon = clientBoundary('m1', 'Icon', '/c.js', function Icon() { return null; }, render, false);
36
+ const html = await renderToStringAsync(jsx(Icon, { size: 4 }));
37
+ expect(html).toBe('<i>{"size":4}</i>');
38
+ });
39
+ it('wraps a stateful component in a krate-island with its props', async () => {
40
+ const Box = clientBoundary('m2', 'Box', '/c.js', function Box() { return null; }, render);
41
+ const html = await renderToStringAsync(jsx(Box, { id: 'x' }));
42
+ expect(html).toContain('<krate-island');
43
+ expect(html).toContain('data-module="m2"');
44
+ expect(html).toContain('data-export="Box"');
45
+ });
46
+ it('sends children as a tree, not HTML, when asked to (real-React islands)', async () => {
47
+ const Box = clientBoundary('m7', 'Box', '/c.js', function Box() { return null; }, render, true, true);
48
+ const html = await renderToStringAsync(jsx(Box, { children: jsx('mesh', { position: [1, 2, 3] }) }));
49
+ expect(html).toContain('__krateTree');
50
+ expect(html).not.toContain('__krateChildren');
51
+ });
52
+ it('wraps the members of a namespace export under dotted names', async () => {
53
+ const ns = clientBoundary('m3', 'Dialog', '/c.js', { Root() { return null; }, helper() { return 1; } }, render);
54
+ expect(typeof ns.Root).toBe('function');
55
+ expect(ns.helper()).toBe(1);
56
+ const html = await renderToStringAsync(jsx(ns.Root, {}));
57
+ expect(html).toContain('data-export="Dialog.Root"');
58
+ });
59
+ it('keeps nested client components in the parent tree so they can share context', async () => {
60
+ const ns = clientBoundary('m4', 'Dialog', '/c.js', { Root() { return null; }, Trigger() { return null; } }, render);
61
+ const html = await renderToStringAsync(jsx(ns.Root, { children: [jsx('div', { children: jsx(ns.Trigger, { id: 't', children: 'Open' }) })] }));
62
+ const attr = html.match(/data-props="([^"]*)"/)[1].replace(/&quot;/g, '"');
63
+ const data = JSON.parse(attr);
64
+ expect(data.__krateChildren).toBeUndefined();
65
+ expect(data.__krateTree).toEqual([
66
+ { $: 'e', t: 'div', p: {}, c: [{ $: 'c', m: 'm4', e: 'Dialog.Trigger', s: '/c.js', p: { id: 't' }, c: ['Open'] }] },
67
+ ]);
68
+ });
69
+ it('hydrates a stateless parent when a nested component has state', async () => {
70
+ const Wrap = clientBoundary('m5', 'Wrap', '/c.js', function Wrap() { return null; }, render, false);
71
+ const Inner = clientBoundary('m5', 'Inner', '/c.js', function Inner() { return null; }, render, true);
72
+ const html = await renderToStringAsync(jsx(Wrap, { children: [jsx(Inner, {})] }));
73
+ expect(html).toContain('<krate-island');
74
+ });
75
+ it('sends server-only children as HTML', async () => {
76
+ const Box = clientBoundary('m6', 'Box', '/c.js', function Box() { return null; }, render);
77
+ const html = await renderToStringAsync(jsx(Box, { children: jsx('b', { children: 'note' }) }));
78
+ expect(html).toContain('__krateChildren');
79
+ });
80
+ });
@@ -0,0 +1,13 @@
1
+ /** Site config injected by the compiler. */
2
+ export interface KrateRuntimeConfig {
3
+ basePath?: string;
4
+ viewTransitions?: boolean | 'auto';
5
+ /** Milliseconds a prefetched document stays fresh (default 30000). */
6
+ prefetchTTL?: number;
7
+ /** Set by `krate dev`: enables router dev warnings. */
8
+ dev?: boolean;
9
+ }
10
+ /** Id of the JSON data block the compiler writes. */
11
+ export declare const CFG_BLOCK_ID = "__krate_cfg__";
12
+ /** The site config, read once from the head's JSON block when the global is not set. */
13
+ export declare function siteConfig(): KrateRuntimeConfig;
@@ -0,0 +1,28 @@
1
+ // The site runtime config (`__KRATE_CFG__`). The compiler writes it into the
2
+ // page head as a JSON data block rather than an inline script, so a strict
3
+ // `script-src 'self'` policy needs no allowance for it. Server bundles set the
4
+ // global directly. The block is only present when something differs from the
5
+ // defaults (a base path, View Transitions off, dev mode).
6
+ /** Id of the JSON data block the compiler writes. */
7
+ export const CFG_BLOCK_ID = '__krate_cfg__';
8
+ /** The site config, read once from the head's JSON block when the global is not set. */
9
+ export function siteConfig() {
10
+ const g = globalThis;
11
+ if (g.__KRATE_CFG__)
12
+ return g.__KRATE_CFG__;
13
+ const doc = g.document;
14
+ const el = doc && typeof doc.getElementById === 'function' ? doc.getElementById(CFG_BLOCK_ID) : null;
15
+ if (el) {
16
+ try {
17
+ const parsed = JSON.parse(el.textContent || '{}');
18
+ if (parsed && typeof parsed === 'object') {
19
+ g.__KRATE_CFG__ = parsed;
20
+ return parsed;
21
+ }
22
+ }
23
+ catch {
24
+ // a malformed block falls back to the defaults
25
+ }
26
+ }
27
+ return {};
28
+ }
@@ -0,0 +1,30 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { basePath } from './base-path.js';
3
+ import { siteConfig } from './site-config.js';
4
+ const g = globalThis;
5
+ function withBlock(text) {
6
+ g.document = { getElementById: (id) => (id === '__krate_cfg__' && text !== null ? { textContent: text } : null) };
7
+ }
8
+ afterEach(() => {
9
+ delete g.document;
10
+ delete g.__KRATE_CFG__;
11
+ });
12
+ describe('site config JSON block', () => {
13
+ it('reads the base path and flags from the head data block', () => {
14
+ withBlock('{"basePath":"/docs","viewTransitions":false}');
15
+ expect(siteConfig().viewTransitions).toBe(false);
16
+ expect(basePath()).toBe('/docs');
17
+ });
18
+ it('falls back to the defaults without a block or with a malformed one', () => {
19
+ withBlock(null);
20
+ expect(siteConfig()).toEqual({});
21
+ expect(basePath()).toBe('');
22
+ withBlock('{nope');
23
+ expect(siteConfig()).toEqual({});
24
+ });
25
+ it('prefers a config the server already set on globalThis', () => {
26
+ g.__KRATE_CFG__ = { basePath: '/app' };
27
+ withBlock('{"basePath":"/other"}');
28
+ expect(basePath()).toBe('/app');
29
+ });
30
+ });