@tschk/moonshine-dom 0.0.0-stage → 0.4.49

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/src/error.ts ADDED
@@ -0,0 +1,59 @@
1
+ /** Optional native DOM/accessor error boundaries; SSR is unsupported. */
2
+ import {
3
+ createErrorOwner,
4
+ errorHandlerKey,
5
+ queueErrorHandler,
6
+ runWithOwner,
7
+ createSignal,
8
+ createRenderMemo,
9
+ untrack,
10
+ type Accessor,
11
+ } from "./reactive";
12
+ function normalizeError(error: unknown): Error {
13
+ return error instanceof Error
14
+ ? error
15
+ : new Error(typeof error === "string" ? error : "Unknown error", {
16
+ cause: error,
17
+ });
18
+ }
19
+ export function catchError<T>(
20
+ fn: () => T,
21
+ handler: (error: Error) => void,
22
+ ): T | undefined {
23
+ const scope = createErrorOwner();
24
+ const parent = scope.context?.get(errorHandlerKey) as
25
+ ((error: unknown) => boolean) | undefined;
26
+ const route = (error: unknown): boolean => {
27
+ if (scope.disposed) return parent?.(error) ?? false;
28
+ const normalized = normalizeError(error);
29
+ queueErrorHandler(() => {
30
+ if (scope.disposed) return;
31
+ try {
32
+ runWithOwner(scope, () => untrack(() => handler(normalized)));
33
+ } catch (failure) {
34
+ if (!parent?.(failure)) throw normalizeError(failure);
35
+ }
36
+ });
37
+ return true;
38
+ };
39
+ scope.context = new Map(scope.context);
40
+ scope.context.set(errorHandlerKey, route);
41
+ try {
42
+ return runWithOwner(scope, fn);
43
+ } catch (error) {
44
+ route(error);
45
+ }
46
+ }
47
+ /** DOM/accessor boundary only; no SSR serialization boundary is provided. */
48
+ export function ErrorBoundary<T>(props: {
49
+ children: () => T;
50
+ fallback: (error: Error, reset: () => void) => T;
51
+ }): Accessor<T | undefined> {
52
+ const [error, setError] = createSignal<Error | undefined>(undefined);
53
+ return createRenderMemo(() => {
54
+ const failure = error();
55
+ if (!failure) return catchError(props.children, setError);
56
+ const fallback = props.fallback;
57
+ return untrack(() => fallback(failure, () => setError(undefined)));
58
+ });
59
+ }
@@ -0,0 +1,20 @@
1
+ import type { Renderer } from "@tschk/moonshine-framework";
2
+
3
+ async function load(): Promise<Renderer> {
4
+ // Source compatibility only: bundled deployments use framework-native.
5
+ const { sourceRenderer } = await import(
6
+ new URL("./framework-source.ts", import.meta.url).href
7
+ );
8
+ return sourceRenderer;
9
+ }
10
+
11
+ /** Compatibility name; pages use native server factories, not legacy React View IR. */
12
+ export const crepusRenderer: Renderer = {
13
+ name: "crepus",
14
+ async prerender(context) {
15
+ return (await load()).prerender(context);
16
+ },
17
+ async render(context) {
18
+ return (await load()).render(context);
19
+ },
20
+ };
@@ -0,0 +1,141 @@
1
+ import {
2
+ serializeData,
3
+ type Renderer,
4
+ type Metadata,
5
+ type DocumentMetadata,
6
+ type RenderContext,
7
+ } from "@tschk/moonshine-framework";
8
+ import { h, defer, escapeHtml, type SSRChild } from "./ssr";
9
+ import { head, title, renderWithHead } from "./head-ssr";
10
+
11
+ type PageProps = {
12
+ params: Record<string, string>;
13
+ data: unknown;
14
+ children?: SSRChild;
15
+ };
16
+ type Module = {
17
+ default?: (props: PageProps) => SSRChild;
18
+ metadata?: Metadata;
19
+ };
20
+
21
+ /** Bundled modules are the only source of components, including after relocation. */
22
+ export function createNativeRenderer(
23
+ modules: Record<string, Module>,
24
+ layoutsByRoute: Record<string, string[]> = {},
25
+ ): Renderer {
26
+ function component(key: string): (props: PageProps) => SSRChild {
27
+ const value = Object.hasOwn(modules, key)
28
+ ? modules[key]?.default
29
+ : undefined;
30
+ if (typeof value !== "function")
31
+ throw new Error(`Missing native component: ${key}`);
32
+ return value;
33
+ }
34
+
35
+ function document(context: RenderContext): string {
36
+ const { route, params, data } = context;
37
+ if (route.mode === "island")
38
+ throw new Error("Native island hydration is not implemented");
39
+ const layoutKeys = Object.hasOwn(layoutsByRoute, route.id)
40
+ ? layoutsByRoute[route.id]!
41
+ : (route.layouts ?? []);
42
+ const pageKey = Object.hasOwn(modules, route.id) ? route.id : route.file;
43
+ const metadata: DocumentMetadata = { lang: "en" };
44
+ for (const key of [...layoutKeys, pageKey]) {
45
+ const mod = Object.hasOwn(modules, key) ? modules[key] : undefined;
46
+ const source =
47
+ mod && Object.hasOwn(mod, "metadata") ? mod.metadata : undefined;
48
+ if (source === undefined) continue;
49
+ const value = typeof source === "function" ? source(context) : source;
50
+ if (value && typeof value === "object" && "then" in value) {
51
+ try {
52
+ if (typeof (value as { then?: unknown }).then === "function")
53
+ void Promise.resolve(value).catch(() => {});
54
+ } catch {
55
+ // A throwing then getter is invalid metadata too.
56
+ }
57
+ throw new TypeError(
58
+ `Native metadata must be a synchronous object: ${key}`,
59
+ );
60
+ }
61
+ if (!value || typeof value !== "object" || Array.isArray(value))
62
+ throw new TypeError(
63
+ `Native metadata must be a synchronous object: ${key}`,
64
+ );
65
+ for (const field of ["title", "description", "lang"] as const) {
66
+ if (!Object.hasOwn(value, field)) continue;
67
+ const entry = value[field];
68
+ if (entry === undefined) continue;
69
+ if (entry !== null && typeof entry !== "string")
70
+ throw new TypeError(`Invalid native metadata ${field}: ${key}`);
71
+ metadata[field] = entry;
72
+ }
73
+ }
74
+ let body: string;
75
+ let headHTML = "";
76
+ const renderBody = (read: () => SSRChild): string => {
77
+ const result = renderWithHead(() => {
78
+ if (metadata.description != null)
79
+ head(() =>
80
+ h("meta", { name: "description", content: metadata.description }),
81
+ );
82
+ if (metadata.title != null) title(() => metadata.title);
83
+ return read();
84
+ });
85
+ headHTML = result.head;
86
+ return result.body;
87
+ };
88
+ let scripts = "";
89
+ if (route.mode === "spa") {
90
+ if (!route.clientEntries.length)
91
+ throw new Error("Native SPA route requires a client entry");
92
+ body = renderBody(() =>
93
+ h("div", { id: "moonshine-app", "data-moonshine-app": route.id }),
94
+ );
95
+ scripts = `<script type="application/json" data-moonshine-props>${serializeData({ params, data })}</script>`;
96
+ for (const entry of route.clientEntries) {
97
+ scripts += `<script type="module" src="${escapeHtml(entry)}"></script>`;
98
+ }
99
+ } else {
100
+ const Page = component(pageKey);
101
+ const layouts = layoutKeys.map(component);
102
+ body = renderBody(() => {
103
+ let child: () => SSRChild = () => h(Page, { params, data });
104
+ for (let index = layouts.length - 1; index >= 0; index--) {
105
+ const Layout = layouts[index]!;
106
+ const children = child;
107
+ child = () => h(Layout, { params, data, children: defer(children) });
108
+ }
109
+ return child();
110
+ });
111
+ }
112
+ const styles = (route.clientStyles ?? [])
113
+ .map((href) => `<link rel="stylesheet" href="${escapeHtml(href)}">`)
114
+ .join("");
115
+ const lang =
116
+ metadata.lang == null ? "" : ` lang="${escapeHtml(metadata.lang)}"`;
117
+ return `<!doctype html><html${lang}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${headHTML}${styles}</head><body>${body}${scripts}</body></html>`;
118
+ }
119
+
120
+ return {
121
+ name: "native",
122
+ async prerender(context) {
123
+ return context.route.mode === "api"
124
+ ? JSON.stringify(context.data)
125
+ : document(context);
126
+ },
127
+ async render(context) {
128
+ const api = context.route.mode === "api";
129
+ return new Response(
130
+ api ? JSON.stringify(context.data) : document(context),
131
+ {
132
+ headers: {
133
+ "content-type": api
134
+ ? "application/json; charset=utf-8"
135
+ : "text/html; charset=utf-8",
136
+ },
137
+ },
138
+ );
139
+ },
140
+ };
141
+ }
@@ -0,0 +1,28 @@
1
+ /** Source-file compatibility renderer for Bun/Node; deployed bundles use framework-native. */
2
+ import type { RenderContext, Renderer } from "@tschk/moonshine-framework";
3
+ import { createNativeRenderer } from "./framework-native";
4
+
5
+ async function load(context: RenderContext): Promise<Renderer> {
6
+ if (context.route.mode === "island")
7
+ throw new Error("Native island hydration is not implemented");
8
+ const modules: Parameters<typeof createNativeRenderer>[0] =
9
+ Object.create(null);
10
+ if (context.route.mode !== "api" && context.route.mode !== "spa") {
11
+ for (const file of new Set([
12
+ context.route.file,
13
+ ...(context.route.layouts ?? []),
14
+ ]))
15
+ modules[file] = await import(file);
16
+ }
17
+ return createNativeRenderer(modules);
18
+ }
19
+
20
+ export const sourceRenderer: Renderer = {
21
+ name: "native",
22
+ async prerender(context) {
23
+ return (await load(context)).prerender(context);
24
+ },
25
+ async render(context) {
26
+ return (await load(context)).render(context);
27
+ },
28
+ };
@@ -0,0 +1,108 @@
1
+ /** Optional synchronous SSR head collector; no browser, host or async-SSR support. */
2
+ import {
3
+ h,
4
+ getOwner,
5
+ renderToString,
6
+ serializeSSRChild,
7
+ type SSRChild,
8
+ } from "./ssr";
9
+ import { isSSRRendering, getSSRRenderScope } from "./ssr-owner";
10
+ import {
11
+ captureActiveSSRRenderAttempt,
12
+ isSSRRenderAccepted,
13
+ type SSRRenderAttempt,
14
+ } from "./ssr-attempt";
15
+
16
+ type Entry = {
17
+ html: string;
18
+ title: boolean;
19
+ scope?: Entry;
20
+ attempt: SSRRenderAttempt | undefined;
21
+ };
22
+ type Collector = { entries: Entry[]; scope?: Entry; request?: object };
23
+
24
+ const collectorKey = /* @__PURE__ */ Symbol("moonshine.ssr.head");
25
+
26
+ function activeCollector(name: string): Collector {
27
+ const owner = getOwner();
28
+ const collector = owner?.context?.get(collectorKey) as Collector | undefined;
29
+ if (
30
+ !isSSRRendering() ||
31
+ !owner ||
32
+ owner.disposed ||
33
+ !collector ||
34
+ collector.request !== getSSRRenderScope()
35
+ )
36
+ throw new Error(
37
+ `${name}() requires an active renderWithHead() server scope`,
38
+ );
39
+ return collector;
40
+ }
41
+
42
+ function reserve(collector: Collector, isTitle: boolean): Entry {
43
+ const entry: Entry = {
44
+ html: "",
45
+ title: isTitle,
46
+ attempt: captureActiveSSRRenderAttempt(),
47
+ };
48
+ collector.entries.push(entry);
49
+ return entry;
50
+ }
51
+
52
+ function release(collector: Collector, entry: Entry): void {
53
+ const index = collector.entries.indexOf(entry);
54
+ if (index >= 0) collector.entries.splice(index);
55
+ }
56
+
57
+ export function renderWithHead(fn: () => SSRChild): {
58
+ body: string;
59
+ head: string;
60
+ } {
61
+ const collector: Collector = { entries: [] };
62
+ const body = renderToString(() => {
63
+ collector.request = getSSRRenderScope();
64
+ const owner = getOwner()!;
65
+ owner.context = new Map(owner.context);
66
+ owner.context.set(collectorKey, collector);
67
+ return fn();
68
+ });
69
+ let headHTML = "";
70
+ let titleHTML = "";
71
+ const titled = new Set<Entry>();
72
+ for (const entry of collector.entries) {
73
+ if (!isSSRRenderAccepted(entry.attempt)) continue;
74
+ if (entry.title) {
75
+ if (entry.scope && titled.has(entry.scope)) continue;
76
+ if (entry.scope) titled.add(entry.scope);
77
+ titleHTML = entry.html;
78
+ } else headHTML += entry.html;
79
+ }
80
+ return { body, head: headHTML + titleHTML };
81
+ }
82
+
83
+ export function head(render: () => SSRChild): undefined {
84
+ const collector = activeCollector("head");
85
+ const entry = reserve(collector, false);
86
+ const previous = collector.scope;
87
+ collector.scope = entry;
88
+ try {
89
+ entry.html = serializeSSRChild(render());
90
+ } catch (error) {
91
+ release(collector, entry);
92
+ throw error;
93
+ } finally {
94
+ collector.scope = previous;
95
+ }
96
+ }
97
+
98
+ export function title(read: () => SSRChild): undefined {
99
+ const collector = activeCollector("title");
100
+ const entry = reserve(collector, true);
101
+ entry.scope = collector.scope;
102
+ try {
103
+ entry.html = serializeSSRChild(h("title", null, read()));
104
+ } catch (error) {
105
+ release(collector, entry);
106
+ throw error;
107
+ }
108
+ }
package/src/head.ts ADDED
@@ -0,0 +1,34 @@
1
+ /** Opt-in document head declarations; title writes persist after owner disposal. */
2
+ import { render, type DOMChild } from "./dom";
3
+ import { createRenderEffect, getOwner, onCleanup } from "./reactive";
4
+ import { isSSRRendering } from "./ssr-owner";
5
+ import { peekComponentContext, withComponentConsumer } from "./component";
6
+
7
+ function requireOwner(): void {
8
+ const owner = getOwner();
9
+ if (!owner || owner.disposed || isSSRRendering())
10
+ throw new Error("DOM head declarations require a live browser owner");
11
+ }
12
+
13
+ /** Mount only this owner's head nodes, preserving unrelated document content. */
14
+ export function head(children: () => DOMChild): undefined {
15
+ requireOwner();
16
+ let stop: (() => void) | undefined;
17
+ let disposed = false;
18
+ onCleanup(() => {
19
+ disposed = true;
20
+ stop?.();
21
+ });
22
+ stop = render(children, document.head);
23
+ // Child setup may dispose the containing component before render returns.
24
+ if (disposed) stop();
25
+ }
26
+
27
+ /** Update the document title; removing a declaration does not restore an older title. */
28
+ export function title(read: () => string): undefined {
29
+ requireOwner();
30
+ const consumer = peekComponentContext();
31
+ createRenderEffect(() => {
32
+ document.title = consumer ? withComponentConsumer(consumer, read) : read();
33
+ });
34
+ }
package/src/html.ts ADDED
@@ -0,0 +1,54 @@
1
+ /** Explicit unsanitized markup. Default native children continue to escape text. */
2
+ import { createRenderEffect, getOwner, onCleanup } from "./reactive";
3
+
4
+ export function rawHTML(
5
+ read: () => unknown,
6
+ namespace: "html" | "svg" | "mathml" = "html",
7
+ ): () => Node[] {
8
+ if (typeof read !== "function")
9
+ throw new TypeError("rawHTML requires a getter");
10
+ if (namespace !== "html" && namespace !== "svg" && namespace !== "mathml")
11
+ throw new TypeError("Unsupported raw HTML namespace");
12
+ let previous: unknown = "";
13
+ let nodes: Node[] = [];
14
+ return () => {
15
+ const value = read() ?? "";
16
+ if (previous === value) return nodes;
17
+ const wrapper =
18
+ namespace === "html"
19
+ ? document.createElement("template")
20
+ : document.createElementNS(
21
+ namespace === "svg"
22
+ ? "http://www.w3.org/2000/svg"
23
+ : "http://www.w3.org/1998/Math/MathML",
24
+ namespace === "svg" ? "svg" : "math",
25
+ );
26
+ // Assign directly: coercing here would discard TrustedHTML identity.
27
+ wrapper.innerHTML = value as string;
28
+ nodes = Array.from(
29
+ (namespace === "html"
30
+ ? (wrapper as HTMLTemplateElement).content
31
+ : wrapper
32
+ ).childNodes,
33
+ );
34
+ previous = value;
35
+ return nodes;
36
+ };
37
+ }
38
+
39
+ /** Own the complete contents of a fresh sole-child element, including final cleanup. */
40
+ export function htmlContent(element: Element, read: () => unknown): void {
41
+ const owner = getOwner();
42
+ if (!owner || owner.disposed)
43
+ throw new Error("htmlContent requires a live native owner");
44
+ if (!(element instanceof Element) || typeof read !== "function")
45
+ throw new TypeError("htmlContent requires an element and getter");
46
+ let previous: unknown = "";
47
+ onCleanup(() => element.replaceChildren());
48
+ createRenderEffect(() => {
49
+ const value = read() ?? "";
50
+ if (previous === value) return;
51
+ element.innerHTML = value as string;
52
+ previous = value;
53
+ });
54
+ }
@@ -0,0 +1,19 @@
1
+ import type { DOMChild } from "./dom";
2
+
3
+ /** Opt-in source checking only; Crepus lowers JSX, not a JSX runtime. */
4
+ declare global {
5
+ namespace JSX {
6
+ type Element = DOMChild;
7
+ // Component props are checked at JSX use sites; this admits any prop shape.
8
+ type ElementType = keyof IntrinsicElements | ((props: any) => DOMChild);
9
+ interface ElementChildrenAttribute {
10
+ children: {};
11
+ }
12
+ type IntrinsicElements = {
13
+ [K in keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap]: Record<
14
+ string,
15
+ unknown
16
+ > & { children?: DOMChild };
17
+ };
18
+ }
19
+ }
@@ -0,0 +1,4 @@
1
+ import GlobalTypes = globalThis;
2
+ export type { GlobalTypes };
3
+
4
+ export declare function sourceRealm(): typeof globalThis;
@@ -0,0 +1,4 @@
1
+ // Compiler imports keep authored globalThis bindings out of generated operations.
2
+ export function sourceRealm() {
3
+ return globalThis;
4
+ }