@tschk/moonshine-dom 0.0.0-stage → 0.4.4

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/ssr.ts ADDED
@@ -0,0 +1,617 @@
1
+ import { cleanupOrderKey } from "./cleanup-order";
2
+ /**
3
+ * Independent HTML factory. Raw markup requires explicit rawHTML; ordinary children escape.
4
+ * No script/style element factories or hydration ABI.
5
+ * Ordinary nonempty single selects require a match: HTML cannot preserve selection -1.
6
+ * Explicit live props win over defaults; HTML cannot encode separate live/reset values.
7
+ */
8
+ import {
9
+ createRoot,
10
+ getOwner,
11
+ runWithOwner,
12
+ errorHandlerKey,
13
+ type Owner,
14
+ } from "./reactive";
15
+ import { styleEntries } from "./style";
16
+ import { attributeValue } from "./attributes";
17
+ import { createComponent } from "./component";
18
+ import { createSSRRenderAttempt, type SSRRenderAttempt } from "./ssr-attempt";
19
+ import { ssrOwner, withSSRRendering, type OwnedSSRChild } from "./ssr-owner";
20
+ export { scopeSSRChild } from "./ssr-owner";
21
+
22
+ /** Compiler-only typed selection; payloads preserve literal function/object identity. */
23
+ export const selectBinding = Symbol("moonshine server select binding");
24
+ export const optionBinding = Symbol("moonshine server option binding");
25
+ type BindingValue = { value: unknown };
26
+ function bindingValue(
27
+ props: Record<string, unknown> | null,
28
+ key: symbol,
29
+ ): BindingValue | undefined {
30
+ if (!props || !Object.hasOwn(props, key)) return undefined;
31
+ const box = Reflect.get(props, key);
32
+ if (
33
+ box === null ||
34
+ typeof box !== "object" ||
35
+ (Object.getPrototypeOf(box) !== Object.prototype &&
36
+ Object.getPrototypeOf(box) !== null)
37
+ )
38
+ throw new TypeError(
39
+ "Server binding metadata requires a plain { value } box",
40
+ );
41
+ const descriptor = Object.getOwnPropertyDescriptor(box, "value");
42
+ if (!descriptor || !("value" in descriptor))
43
+ throw new TypeError("Server binding metadata requires an own data value");
44
+ return { value: descriptor.value };
45
+ }
46
+ const html = Symbol("moonshine server HTML");
47
+ type Selection = {
48
+ values?: Set<string>;
49
+ binding?: BindingValue;
50
+ multiple: boolean;
51
+ matched: boolean;
52
+ options: number;
53
+ };
54
+ export type HTML = {
55
+ readonly [html]: (selection?: Selection, svg?: boolean) => string;
56
+ };
57
+ export type SSRChild =
58
+ | HTML
59
+ | OwnedSSRChild
60
+ | string
61
+ | number
62
+ | bigint
63
+ | boolean
64
+ | null
65
+ | undefined
66
+ | readonly SSRChild[]
67
+ | (() => SSRChild);
68
+
69
+ const VOID = new Set([
70
+ "area",
71
+ "base",
72
+ "br",
73
+ "col",
74
+ "embed",
75
+ "hr",
76
+ "img",
77
+ "input",
78
+ "link",
79
+ "meta",
80
+ "param",
81
+ "source",
82
+ "track",
83
+ "wbr",
84
+ ]);
85
+
86
+ /** Explicit unsanitized server markup; ordinary children remain escaped. */
87
+ export function rawHTML(value: unknown): HTML {
88
+ const markup = String(value ?? "");
89
+ return { [html]: () => markup };
90
+ }
91
+
92
+ export function escapeHtml(value: unknown): string {
93
+ const text = String(value);
94
+ // Bun emits &#x27; for apostrophes; retain this API's exact &#39; output.
95
+ if (typeof Bun !== "undefined" && !text.includes("'"))
96
+ return Bun.escapeHTML(text);
97
+ return text.replace(/[&<>"']/g, (character) => {
98
+ switch (character) {
99
+ case "&":
100
+ return "&amp;";
101
+ case "<":
102
+ return "&lt;";
103
+ case ">":
104
+ return "&gt;";
105
+ case '"':
106
+ return "&quot;";
107
+ default:
108
+ return "&#39;";
109
+ }
110
+ });
111
+ }
112
+
113
+ function resolve(child: SSRChild): SSRChild {
114
+ if (typeof child === "function") return resolve(child());
115
+ if (Array.isArray(child)) return child.map(resolve);
116
+ if (
117
+ child != null &&
118
+ typeof child === "object" &&
119
+ !(html in child) &&
120
+ !(ssrOwner in child)
121
+ ) {
122
+ throw new TypeError("Server children must be text or factory HTML");
123
+ }
124
+ return child;
125
+ }
126
+
127
+ function text(child: SSRChild): string {
128
+ if (child && typeof child === "object" && ssrOwner in child)
129
+ return inSSRScope(child, () => text(child.child));
130
+ if (typeof child === "function") return text(child());
131
+ if (Array.isArray(child)) return child.map(text).join("");
132
+ if (child == null || typeof child === "boolean") return "";
133
+ if (typeof child === "object") {
134
+ throw new TypeError("Server textarea/title/option children must be text");
135
+ }
136
+ return String(child);
137
+ }
138
+
139
+ function content(child: SSRChild, selection?: Selection, svg = false): string {
140
+ if (child && typeof child === "object" && ssrOwner in child)
141
+ return inSSRScope(child, () => content(child.child, selection, svg));
142
+ if (typeof child === "function") return content(child(), selection, svg);
143
+ if (Array.isArray(child))
144
+ return child.map((value) => content(value, selection, svg)).join("");
145
+ if (child == null || typeof child === "boolean") return "";
146
+ if (typeof child === "object") {
147
+ if (html in child) return (child as HTML)[html](selection, svg);
148
+ throw new TypeError("Server children must be text or factory HTML");
149
+ }
150
+ return escapeHtml(child);
151
+ }
152
+
153
+ function inSSRScope<T>(child: OwnedSSRChild, render: () => T): T {
154
+ const owner = child[ssrOwner];
155
+ if (owner.disposed)
156
+ throw new Error("Cannot serialize a disposed SSR child scope");
157
+ return runWithOwner(owner, render);
158
+ }
159
+
160
+ /** Construct nested components during serialization in the containing owner's context. */
161
+ export function defer(fn: () => SSRChild): HTML {
162
+ return { [html]: (selection, svg) => content(fn(), selection, svg) };
163
+ }
164
+
165
+ /** Serialize the child successfully before publishing compiler binding values. */
166
+ export function afterRender(child: SSRChild, commit: () => void): HTML {
167
+ return {
168
+ [html]: (selection, svg) => {
169
+ const rendered = content(child, selection, svg);
170
+ commit();
171
+ return rendered;
172
+ },
173
+ };
174
+ }
175
+
176
+ /** Synchronous buffered recovery. Arbitrary state writes are not rolled back. */
177
+ export function boundary(
178
+ render: () => SSRChild,
179
+ fallback: (error: unknown) => SSRChild,
180
+ ): HTML {
181
+ return {
182
+ [html]: (selection, svg) => {
183
+ const owner = getOwner();
184
+ if (!owner || owner.disposed)
185
+ throw new Error(
186
+ "SSR boundary serialization requires a live native owner",
187
+ );
188
+ const branch = (renderBranch: () => SSRChild): string => {
189
+ let stop: (() => void) | undefined;
190
+ let attempt: SSRRenderAttempt | undefined;
191
+ let scope: Owner | undefined;
192
+ const localSelection = selection ? { ...selection } : undefined;
193
+ let rendered: string;
194
+ try {
195
+ rendered = runWithOwner(owner, () =>
196
+ createRoot((dispose) => {
197
+ stop = dispose;
198
+ scope = getOwner()!;
199
+ attempt = createSSRRenderAttempt();
200
+ // The attempt owns a fresh context map; setup errors belong to this buffer.
201
+ scope.context!.delete(errorHandlerKey);
202
+ try {
203
+ return content(renderBranch(), localSelection, svg);
204
+ } catch (error) {
205
+ // createRoot cleans failed setup before returning to the outer catch.
206
+ attempt.status = "discarded";
207
+ throw error;
208
+ }
209
+ }),
210
+ );
211
+ } catch (error) {
212
+ if (attempt) attempt.status = "discarded";
213
+ try {
214
+ stop?.();
215
+ } catch {
216
+ /* Preserve the render failure. */
217
+ }
218
+ throw error;
219
+ }
220
+ if (owner.disposed) {
221
+ attempt!.status = "discarded";
222
+ try {
223
+ stop!();
224
+ } catch {
225
+ /* Preserve the ownership failure. */
226
+ }
227
+ throw new Error("SSR boundary owner was disposed during rendering");
228
+ }
229
+ attempt!.status = "accepted";
230
+ scope!.parent = owner;
231
+ owner.children.add(scope!);
232
+ if (selection && localSelection) {
233
+ selection.matched = localSelection.matched;
234
+ selection.options = localSelection.options;
235
+ }
236
+ return rendered;
237
+ };
238
+ try {
239
+ return branch(render);
240
+ } catch (error) {
241
+ if (owner.disposed) throw error;
242
+ return branch(() => fallback(error));
243
+ }
244
+ },
245
+ };
246
+ }
247
+
248
+ /** Buffer repeatable template output until compiler binding writes stop invalidating it. */
249
+ export function settle(
250
+ renderTemplate: (invalidate: () => void) => SSRChild,
251
+ ): HTML {
252
+ const owner = getOwner();
253
+ if (!owner || owner.disposed)
254
+ throw new Error("SSR settlement requires a live native owner");
255
+ return {
256
+ [html]: (selection, svg) => {
257
+ if (owner.disposed)
258
+ throw new Error("Cannot serialize a disposed SSR settlement");
259
+ for (let iteration = 0; iteration < 1000; iteration++) {
260
+ let dirty = false;
261
+ let stop: (() => void) | undefined;
262
+ let attempt: SSRRenderAttempt | undefined;
263
+ let scope: Owner | undefined;
264
+ const localSelection = selection ? { ...selection } : undefined;
265
+ let rendered: string;
266
+ try {
267
+ rendered = runWithOwner(owner, () =>
268
+ createRoot((dispose) => {
269
+ stop = dispose;
270
+ scope = getOwner()!;
271
+ attempt = createSSRRenderAttempt();
272
+ return content(
273
+ renderTemplate(() => {
274
+ dirty = true;
275
+ }),
276
+ localSelection,
277
+ svg,
278
+ );
279
+ }),
280
+ );
281
+ } catch (error) {
282
+ if (attempt) attempt.status = "discarded";
283
+ try {
284
+ stop?.();
285
+ } catch {
286
+ /* Preserve the render failure. */
287
+ }
288
+ throw error;
289
+ }
290
+ if (dirty) {
291
+ attempt!.status = "discarded";
292
+ stop!();
293
+ continue;
294
+ }
295
+ if (owner.disposed) {
296
+ attempt!.status = "discarded";
297
+ try {
298
+ stop!();
299
+ } catch {
300
+ /* Preserve the ownership failure. */
301
+ }
302
+ throw new Error("SSR settlement owner was disposed during rendering");
303
+ }
304
+ attempt!.status = "accepted";
305
+ scope!.parent = owner;
306
+ owner.children.add(scope!);
307
+ if (selection && localSelection) {
308
+ selection.matched = localSelection.matched;
309
+ selection.options = localSelection.options;
310
+ }
311
+ return rendered;
312
+ }
313
+ throw new Error("SSR settlement update limit exceeded");
314
+ },
315
+ };
316
+ }
317
+
318
+ export function h<P extends object>(
319
+ component: (props: P & { children?: SSRChild }) => SSRChild,
320
+ props: P | null,
321
+ ...children: SSRChild[]
322
+ ): SSRChild;
323
+ export function h(
324
+ tag: string,
325
+ props?: Record<string, unknown> | null,
326
+ ...children: SSRChild[]
327
+ ): HTML;
328
+ export function h<P extends Record<string, unknown>>(
329
+ tag: string | ((props: P & { children?: SSRChild }) => SSRChild),
330
+ props: P | null = null,
331
+ ...children: SSRChild[]
332
+ ): SSRChild {
333
+ if (typeof tag === "function") {
334
+ const componentProps = children.length
335
+ ? Object.defineProperties(
336
+ {},
337
+ {
338
+ ...(props && Object.getOwnPropertyDescriptors(props)),
339
+ children: { value: children, enumerable: true, configurable: true },
340
+ },
341
+ )
342
+ : (props ?? {});
343
+ return createComponent(
344
+ tag,
345
+ componentProps as P & { children?: SSRChild },
346
+ "ssr",
347
+ );
348
+ }
349
+ if (!/^[a-zA-Z][a-zA-Z0-9:_-]*$/.test(tag)) {
350
+ throw new TypeError("Invalid server element name");
351
+ }
352
+ const owner = getOwner();
353
+ const lower = tag.toLowerCase();
354
+ const typedSelect =
355
+ lower === "select" ? bindingValue(props, selectBinding) : undefined;
356
+ const typedOption =
357
+ lower === "option" ? bindingValue(props, optionBinding) : undefined;
358
+ if (lower === "script" || lower === "style") {
359
+ throw new TypeError("Server script/style elements are unsupported");
360
+ }
361
+ const attributes: Array<[string, unknown]> = [];
362
+ let textareaValue: unknown;
363
+ let hasTextareaValue = false;
364
+ let selectValue: unknown;
365
+ let hasSelectValue = false;
366
+ let multiple = false;
367
+ let optionValue: string | undefined;
368
+ let selectedAttribute = "";
369
+ for (const name of Object.keys(props ?? {})) {
370
+ if (!/^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/.test(name)) {
371
+ throw new TypeError("Invalid server attribute name");
372
+ }
373
+ // Event and ref handlers are client-only and must never execute on the server.
374
+ if (/^on/i.test(name) || name === "ref" || name === "children") continue;
375
+ if (["innerHTML", "outerHTML", "dangerouslySetInnerHTML"].includes(name)) {
376
+ throw new TypeError("Raw server HTML is unsupported");
377
+ }
378
+ if (name === "defaultValue" && lower !== "input" && lower !== "textarea")
379
+ throw new TypeError(
380
+ "defaultValue is supported only on input and textarea",
381
+ );
382
+ if (name === "defaultChecked" && lower !== "input")
383
+ throw new TypeError("defaultChecked is supported only on input");
384
+ const property =
385
+ name === "defaultValue"
386
+ ? "value"
387
+ : name === "defaultChecked"
388
+ ? "checked"
389
+ : name;
390
+ if (property !== name && Object.hasOwn(props!, property)) continue;
391
+ // Typed options carry their serialized value as well as comparison identity.
392
+ // The ordinary value prop loses precedence without invoking its getter/accessor.
393
+ if (name === "value" && (typedOption || typedSelect)) continue;
394
+ const supplied = props![name];
395
+ let value = typeof supplied === "function" ? supplied() : supplied;
396
+ if (name === "style") {
397
+ if (value == null || value === false) value = undefined;
398
+ else if (typeof value === "object") {
399
+ value = styleEntries(value)
400
+ .map(([property, entry]) =>
401
+ entry == null || entry === "" ? "" : `${property}:${entry};`,
402
+ )
403
+ .join("");
404
+ } else if (typeof value !== "string") {
405
+ throw new TypeError(
406
+ "Style must be a CSS string, plain record, nullish or false",
407
+ );
408
+ }
409
+ }
410
+
411
+ if (lower === "select" && name === "multiple") {
412
+ multiple = attributeValue(name, value, true) !== undefined;
413
+ }
414
+ if (lower === "select" && name === "value") {
415
+ selectValue = value;
416
+ hasSelectValue = true;
417
+ continue;
418
+ }
419
+ if (lower === "option" && name === "selected") {
420
+ if (attributeValue(name, value, true) !== undefined)
421
+ selectedAttribute = ` selected=""`;
422
+ continue;
423
+ }
424
+ if (lower === "textarea" && property === "value") {
425
+ textareaValue = value;
426
+ hasTextareaValue = true;
427
+ continue;
428
+ }
429
+ const attr =
430
+ property === "className"
431
+ ? "class"
432
+ : property === "htmlFor"
433
+ ? "for"
434
+ : property;
435
+ if (property === "value") {
436
+ if (lower === "option") optionValue = String(value ?? "");
437
+ attributes.push(["value", value]);
438
+ continue;
439
+ }
440
+ attributes.push([attr, value]);
441
+ }
442
+ if (
443
+ typedOption &&
444
+ typedOption.value != null &&
445
+ typeof typedOption.value !== "function"
446
+ ) {
447
+ optionValue = String(typedOption.value);
448
+ attributes.push(["value", optionValue]);
449
+ }
450
+ if (
451
+ lower === "select" &&
452
+ !typedSelect &&
453
+ Array.isArray(selectValue) &&
454
+ !multiple
455
+ ) {
456
+ throw new TypeError("Server select array values require multiple");
457
+ }
458
+ const textOnly =
459
+ lower === "textarea" || lower === "title" || lower === "option";
460
+ const sourceChild =
461
+ lower === "textarea" && hasTextareaValue
462
+ ? undefined
463
+ : children.length === 1
464
+ ? children[0]
465
+ : children.length
466
+ ? children
467
+ : (props?.children as SSRChild);
468
+ const bodyChild = resolve(sourceChild);
469
+ const bodyText = textOnly
470
+ ? hasTextareaValue
471
+ ? String(textareaValue ?? "")
472
+ : text(bodyChild)
473
+ : undefined;
474
+ const explicitNamespace = attributes.find(([name]) => name === "xmlns")?.[1];
475
+ const isSvg = (inherited = false) =>
476
+ explicitNamespace != null
477
+ ? explicitNamespace === "http://www.w3.org/2000/svg"
478
+ : lower === "svg" || inherited;
479
+ const renderAttributes = (svg: boolean) =>
480
+ attributes
481
+ .map(([attr, value]) => {
482
+ if (!svg && attr === "checked" && !value) return "";
483
+ const text = attributeValue(
484
+ attr,
485
+ !svg &&
486
+ attr === "value" &&
487
+ lower !== "progress" &&
488
+ lower !== "meter" &&
489
+ lower !== "li"
490
+ ? (value ?? "")
491
+ : value,
492
+ !svg,
493
+ );
494
+ return text === undefined ? "" : ` ${attr}="${escapeHtml(text)}"`;
495
+ })
496
+ .join("");
497
+ if (VOID.has(lower)) {
498
+ if (content(bodyChild))
499
+ throw new TypeError("Void server elements cannot have children");
500
+ return {
501
+ [html]: (_selection, inheritedSvg) =>
502
+ `<${tag}${renderAttributes(isSvg(inheritedSvg))}>`,
503
+ };
504
+ }
505
+ return {
506
+ [html]: (inherited, inheritedSvg) => {
507
+ const svg = isSvg(inheritedSvg);
508
+ const selection =
509
+ lower === "select"
510
+ ? typedSelect
511
+ ? { binding: typedSelect, multiple, matched: false, options: 0 }
512
+ : hasSelectValue
513
+ ? {
514
+ values: new Set(
515
+ (multiple
516
+ ? Array.isArray(selectValue)
517
+ ? selectValue
518
+ : selectValue == null
519
+ ? []
520
+ : [selectValue]
521
+ : [selectValue ?? ""]
522
+ ).map(String),
523
+ ),
524
+ multiple,
525
+ matched: false,
526
+ options: 0,
527
+ }
528
+ : undefined
529
+ : inherited;
530
+ let selected = selectedAttribute;
531
+ if (lower === "option" && selection) {
532
+ selection.options++;
533
+ const value =
534
+ optionValue ??
535
+ bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, "");
536
+ const raw = typedOption ? typedOption.value : value;
537
+ const matches = selection.binding
538
+ ? selection.multiple && Array.isArray(selection.binding.value)
539
+ ? selection.binding.value.includes(raw)
540
+ : raw === selection.binding.value
541
+ : selection.values!.has(value) &&
542
+ (selection.multiple || !selection.matched);
543
+ selected = matches ? ` selected=""` : "";
544
+ if (matches) selection.matched = true;
545
+ }
546
+ let body =
547
+ bodyText === undefined
548
+ ? runWithOwner(owner && !owner.disposed ? owner : getOwner(), () =>
549
+ content(bodyChild, selection, svg && lower !== "foreignobject"),
550
+ )
551
+ : escapeHtml(bodyText);
552
+ if (
553
+ lower === "select" &&
554
+ selection &&
555
+ !selection.binding &&
556
+ !selection.multiple &&
557
+ selection.options > 0 &&
558
+ !selection.matched
559
+ ) {
560
+ throw new TypeError("Server select value has no matching option");
561
+ }
562
+ if (
563
+ lower === "textarea" &&
564
+ (body.startsWith("\n") || body.startsWith("\r"))
565
+ )
566
+ body = `\n${body}`;
567
+ return `<${tag}${renderAttributes(svg)}${selected}>${body}</${tag}>`;
568
+ },
569
+ };
570
+ }
571
+
572
+ export function renderToString(fn: () => SSRChild): string {
573
+ return withSSRRendering(() => {
574
+ let dispose = () => {};
575
+ let result: string;
576
+ try {
577
+ result = createRoot((stop) => {
578
+ dispose = stop;
579
+ const requestOwner = getOwner()!;
580
+ if (requestOwner.context?.has(cleanupOrderKey)) {
581
+ requestOwner.context = new Map(requestOwner.context);
582
+ requestOwner.context.delete(cleanupOrderKey);
583
+ }
584
+ return content(fn());
585
+ });
586
+ } catch (error) {
587
+ try {
588
+ dispose();
589
+ } catch {
590
+ /* Preserve the render error. */
591
+ }
592
+ throw error;
593
+ }
594
+ dispose();
595
+ return result;
596
+ });
597
+ }
598
+
599
+ /** Server lowering must import lifecycle hooks here; browser effects never run. */
600
+ export function createEffect<T>(_fn: (previous: T) => T, _initial: T): void;
601
+ export function createEffect(_fn: (previous: undefined) => unknown): void;
602
+ export function createEffect<T>(_fn: (previous: T) => T, _initial?: T): void {}
603
+ export function onMount(_fn: () => void): void {}
604
+
605
+ export {
606
+ createSignal,
607
+ createMemo,
608
+ createRoot,
609
+ createComputed,
610
+ batch,
611
+ untrack,
612
+ onCleanup,
613
+ on,
614
+ getOwner,
615
+ runWithOwner,
616
+ } from "./reactive";
617
+ export type { Accessor, Setter, Owner } from "./reactive";