@tschk/moonshine-dom 0.4.4 → 0.4.80

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 CHANGED
@@ -13,37 +13,67 @@ import {
13
13
  type Owner,
14
14
  } from "./reactive";
15
15
  import { styleEntries } from "./style";
16
- import { attributeValue } from "./attributes";
16
+ import { attributeValue, sourceAttributeValue } from "./attributes";
17
17
  import { createComponent } from "./component";
18
- import { createSSRRenderAttempt, type SSRRenderAttempt } from "./ssr-attempt";
19
- import { ssrOwner, withSSRRendering, type OwnedSSRChild } from "./ssr-owner";
18
+ import {
19
+ createSSRRenderAttempt,
20
+ resetSSRRenderAttempt,
21
+ withSSRRenderAttempt,
22
+ type SSRRenderAttempt,
23
+ } from "./ssr-attempt";
24
+ import {
25
+ ssrOwner,
26
+ withSSRRendering,
27
+ isSSRRendering,
28
+ type OwnedSSRChild,
29
+ } from "./ssr-owner";
20
30
  export { scopeSSRChild } from "./ssr-owner";
21
31
 
22
32
  /** 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
- )
33
+ export const selectBinding = /* @__PURE__ */ Symbol(
34
+ "moonshine server select binding",
35
+ );
36
+ export const optionBinding = /* @__PURE__ */ Symbol(
37
+ "moonshine server option binding",
38
+ );
39
+ type BindingValue = { value: unknown; preserveSelected?: boolean };
40
+ const ELEMENT_NAME = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
41
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
42
+ const EVENT_NAME = /^on/i;
43
+
44
+ function validateBindingBox(box: unknown): BindingValue {
45
+ if (box === null || typeof box !== "object")
46
+ throw new TypeError(
47
+ "Server binding metadata requires a plain { value } box",
48
+ );
49
+ const proto = Object.getPrototypeOf(box);
50
+ if (proto !== Object.prototype && proto !== null)
38
51
  throw new TypeError(
39
52
  "Server binding metadata requires a plain { value } box",
40
53
  );
41
54
  const descriptor = Object.getOwnPropertyDescriptor(box, "value");
42
55
  if (!descriptor || !("value" in descriptor))
43
56
  throw new TypeError("Server binding metadata requires an own data value");
44
- return { value: descriptor.value };
57
+ let preserveSelected: boolean | undefined;
58
+ if (Object.hasOwn(box, "preserveSelected")) {
59
+ const policy = Object.getOwnPropertyDescriptor(box, "preserveSelected");
60
+ if (policy && (!("value" in policy) || typeof policy.value !== "boolean"))
61
+ throw new TypeError(
62
+ "Server selected policy requires an own boolean data value",
63
+ );
64
+ preserveSelected = policy?.value;
65
+ }
66
+ return { value: descriptor.value, preserveSelected };
67
+ }
68
+
69
+ function bindingValue(
70
+ props: Record<string, unknown> | null,
71
+ key: symbol,
72
+ ): BindingValue | undefined {
73
+ if (!props || !Object.hasOwn(props, key)) return undefined;
74
+ return validateBindingBox(Reflect.get(props, key));
45
75
  }
46
- const html = Symbol("moonshine server HTML");
76
+ const html = /* @__PURE__ */ Symbol("moonshine server HTML");
47
77
  type Selection = {
48
78
  values?: Set<string>;
49
79
  binding?: BindingValue;
@@ -66,7 +96,7 @@ export type SSRChild =
66
96
  | readonly SSRChild[]
67
97
  | (() => SSRChild);
68
98
 
69
- const VOID = new Set([
99
+ const VOID = /* @__PURE__ */ new Set([
70
100
  "area",
71
101
  "base",
72
102
  "br",
@@ -90,7 +120,8 @@ export function rawHTML(value: unknown): HTML {
90
120
  }
91
121
 
92
122
  export function escapeHtml(value: unknown): string {
93
- const text = String(value);
123
+ const text = typeof value === "string" ? value : String(value);
124
+ if (text.length === 0) return "";
94
125
  // Bun emits &#x27; for apostrophes; retain this API's exact &#39; output.
95
126
  if (typeof Bun !== "undefined" && !text.includes("'"))
96
127
  return Bun.escapeHTML(text);
@@ -111,45 +142,66 @@ export function escapeHtml(value: unknown): string {
111
142
  }
112
143
 
113
144
  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
- ) {
145
+ while (typeof child === "function") child = child();
146
+ if (child == null || typeof child !== "object") return child;
147
+ if (Array.isArray(child)) {
148
+ const length = child.length;
149
+ if (length === 0) return "";
150
+ if (length === 1) return resolve(child[0]);
151
+ const resolved: SSRChild[] = [];
152
+ for (let index = 0; index < length; index++)
153
+ resolved.push(resolve(child[index]));
154
+ return resolved;
155
+ }
156
+ if (!(html in child) && !(ssrOwner in child)) {
122
157
  throw new TypeError("Server children must be text or factory HTML");
123
158
  }
124
159
  return child;
125
160
  }
126
161
 
127
162
  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("");
163
+ while (typeof child === "function") child = child();
132
164
  if (child == null || typeof child === "boolean") return "";
133
- if (typeof child === "object") {
134
- throw new TypeError("Server textarea/title/option children must be text");
165
+ if (typeof child === "string") return child;
166
+ if (typeof child !== "object") return String(child);
167
+ if (ssrOwner in child) return inSSRScope(child, () => text(child.child));
168
+ if (Array.isArray(child)) {
169
+ let out = "";
170
+ for (let index = 0; index < child.length; index++)
171
+ out += text(child[index]);
172
+ return out;
135
173
  }
136
- return String(child);
174
+ throw new TypeError("Server textarea/title/option children must be text");
137
175
  }
138
176
 
139
177
  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("");
178
+ while (typeof child === "function") child = child();
145
179
  if (child == null || typeof child === "boolean") return "";
146
180
  if (typeof child === "object") {
147
181
  if (html in child) return (child as HTML)[html](selection, svg);
182
+ if (ssrOwner in child)
183
+ return inSSRScope(child, () => content(child.child, selection, svg));
184
+ if (Array.isArray(child)) {
185
+ let out = "";
186
+ for (let index = 0; index < child.length; index++)
187
+ out += content(child[index], selection, svg);
188
+ return out;
189
+ }
148
190
  throw new TypeError("Server children must be text or factory HTML");
149
191
  }
150
192
  return escapeHtml(child);
151
193
  }
152
194
 
195
+ /** Serialize within the active request and owner without starting or disposing a root. */
196
+ export function serializeSSRChild(child: SSRChild): string {
197
+ const owner = getOwner();
198
+ if (!isSSRRendering() || !owner || owner.disposed)
199
+ throw new Error(
200
+ "SSR child serialization requires a live server render owner",
201
+ );
202
+ return content(child);
203
+ }
204
+
153
205
  function inSSRScope<T>(child: OwnedSSRChild, render: () => T): T {
154
206
  const owner = child[ssrOwner];
155
207
  if (owner.disposed)
@@ -200,7 +252,9 @@ export function boundary(
200
252
  // The attempt owns a fresh context map; setup errors belong to this buffer.
201
253
  scope.context!.delete(errorHandlerKey);
202
254
  try {
203
- return content(renderBranch(), localSelection, svg);
255
+ return withSSRRenderAttempt(attempt, () =>
256
+ content(renderBranch(), localSelection, svg),
257
+ );
204
258
  } catch (error) {
205
259
  // createRoot cleans failed setup before returning to the outer catch.
206
260
  attempt.status = "discarded";
@@ -269,12 +323,14 @@ export function settle(
269
323
  stop = dispose;
270
324
  scope = getOwner()!;
271
325
  attempt = createSSRRenderAttempt();
272
- return content(
273
- renderTemplate(() => {
274
- dirty = true;
275
- }),
276
- localSelection,
277
- svg,
326
+ return withSSRRenderAttempt(attempt, () =>
327
+ content(
328
+ renderTemplate(() => {
329
+ dirty = true;
330
+ }),
331
+ localSelection,
332
+ svg,
333
+ ),
278
334
  );
279
335
  }),
280
336
  );
@@ -346,61 +402,186 @@ export function h<P extends Record<string, unknown>>(
346
402
  "ssr",
347
403
  );
348
404
  }
349
- if (!/^[a-zA-Z][a-zA-Z0-9:_-]*$/.test(tag)) {
405
+ return intrinsic(tag, props, children);
406
+ }
407
+
408
+ /** Compiler-only source attribute codec; children use the existing lazy contract. */
409
+ export function hSource(
410
+ tag: string,
411
+ props: Record<string, unknown> | null = null,
412
+ ...children: SSRChild[]
413
+ ): HTML {
414
+ return intrinsic(tag, props, children, sourceAttributeValue);
415
+ }
416
+
417
+ /** Compiler-only ordered source attributes, including repeated authored names. */
418
+ export function hSourceEntries(
419
+ tag: string,
420
+ entries: ReadonlyArray<readonly [string, unknown]>,
421
+ ...children: SSRChild[]
422
+ ): HTML {
423
+ return intrinsic(tag, null, children, sourceAttributeValue, entries);
424
+ }
425
+
426
+ /** Explicit HTML attributes without DOM property aliases or form-binding inference. */
427
+ export function hAttributes(
428
+ tag: string,
429
+ attributes: Record<string, unknown> | null = null,
430
+ ...children: SSRChild[]
431
+ ): HTML {
432
+ return intrinsic(tag, attributes, children, undefined, undefined, true);
433
+ }
434
+
435
+ /** Compiler-facing ordered explicit attributes; repeated names retain source order. */
436
+ export function hAttributeEntries(
437
+ tag: string,
438
+ entries: ReadonlyArray<readonly [string, unknown]>,
439
+ ...children: SSRChild[]
440
+ ): HTML {
441
+ return intrinsic(tag, null, children, undefined, entries, true);
442
+ }
443
+
444
+ /** Compiler-only explicit attributes with independent typed select/option identity. */
445
+ export function hSelectionEntries(
446
+ tag: "select" | "option",
447
+ entries: ReadonlyArray<readonly [string, unknown]>,
448
+ selection: { value: unknown; preserveSelected?: boolean },
449
+ ...children: SSRChild[]
450
+ ): HTML {
451
+ if (tag !== "select" && tag !== "option")
452
+ throw new TypeError("Selection entries require select or option");
453
+ return intrinsic(
454
+ tag,
455
+ null,
456
+ children,
457
+ undefined,
458
+ entries,
459
+ true,
460
+ validateBindingBox(selection),
461
+ );
462
+ }
463
+
464
+ function intrinsic(
465
+ tag: string,
466
+ props: Record<string, unknown> | null,
467
+ children: SSRChild[],
468
+ sourceCodec?: typeof sourceAttributeValue,
469
+ sourceEntries?: ReadonlyArray<readonly [string, unknown]>,
470
+ explicitAttributes = false,
471
+ selectionBox?: BindingValue,
472
+ ): HTML {
473
+ if (!ELEMENT_NAME.test(tag)) {
350
474
  throw new TypeError("Invalid server element name");
351
475
  }
352
476
  const owner = getOwner();
353
477
  const lower = tag.toLowerCase();
354
478
  const typedSelect =
355
- lower === "select" ? bindingValue(props, selectBinding) : undefined;
479
+ lower === "select"
480
+ ? (selectionBox ??
481
+ (!explicitAttributes ? bindingValue(props, selectBinding) : undefined))
482
+ : undefined;
356
483
  const typedOption =
357
- lower === "option" ? bindingValue(props, optionBinding) : undefined;
484
+ lower === "option"
485
+ ? (selectionBox ??
486
+ (!explicitAttributes ? bindingValue(props, optionBinding) : undefined))
487
+ : undefined;
358
488
  if (lower === "script" || lower === "style") {
359
489
  throw new TypeError("Server script/style elements are unsupported");
360
490
  }
361
- const attributes: Array<[string, unknown]> = [];
491
+ const staticMode = explicitAttributes || Boolean(sourceCodec);
492
+ let staticAttributes = "";
493
+ const attributes: Array<[string, unknown]> | undefined = staticMode
494
+ ? undefined
495
+ : [];
362
496
  let textareaValue: unknown;
363
497
  let hasTextareaValue = false;
364
498
  let selectValue: unknown;
365
499
  let hasSelectValue = false;
366
500
  let multiple = false;
367
501
  let optionValue: string | undefined;
502
+ let typedOptionValueSlot = false;
368
503
  let selectedAttribute = "";
369
- for (const name of Object.keys(props ?? {})) {
370
- if (!/^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/.test(name)) {
504
+ let sourceNamespace: unknown;
505
+ const names = sourceEntries
506
+ ? undefined
507
+ : props
508
+ ? Object.keys(props)
509
+ : undefined;
510
+ const attributeCount = sourceEntries
511
+ ? sourceEntries.length
512
+ : (names?.length ?? 0);
513
+ for (let index = 0; index < attributeCount; index++) {
514
+ const name = sourceEntries ? sourceEntries[index]![0] : names![index]!;
515
+ if (!ATTRIBUTE_NAME.test(name)) {
371
516
  throw new TypeError("Invalid server attribute name");
372
517
  }
373
518
  // 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)) {
519
+ if (
520
+ EVENT_NAME.test(name) ||
521
+ (!explicitAttributes && (name === "ref" || name === "children"))
522
+ )
523
+ continue;
524
+ if (
525
+ !explicitAttributes &&
526
+ (name === "innerHTML" ||
527
+ name === "outerHTML" ||
528
+ name === "dangerouslySetInnerHTML")
529
+ ) {
376
530
  throw new TypeError("Raw server HTML is unsupported");
377
531
  }
378
- if (name === "defaultValue" && lower !== "input" && lower !== "textarea")
532
+ if (
533
+ !explicitAttributes &&
534
+ name === "defaultValue" &&
535
+ lower !== "input" &&
536
+ lower !== "textarea"
537
+ )
379
538
  throw new TypeError(
380
539
  "defaultValue is supported only on input and textarea",
381
540
  );
382
- if (name === "defaultChecked" && lower !== "input")
541
+ if (!explicitAttributes && name === "defaultChecked" && lower !== "input")
383
542
  throw new TypeError("defaultChecked is supported only on input");
384
543
  const property =
385
- name === "defaultValue"
544
+ !explicitAttributes && name === "defaultValue"
386
545
  ? "value"
387
- : name === "defaultChecked"
546
+ : !explicitAttributes && name === "defaultChecked"
388
547
  ? "checked"
389
548
  : name;
390
- if (property !== name && Object.hasOwn(props!, property)) continue;
549
+ if (
550
+ property !== name &&
551
+ (sourceEntries
552
+ ? sourceEntries.some(([candidate]) => candidate === property)
553
+ : Object.hasOwn(props!, property))
554
+ )
555
+ continue;
391
556
  // Typed options carry their serialized value as well as comparison identity.
392
557
  // The ordinary value prop loses precedence without invoking its getter/accessor.
393
- if (name === "value" && (typedOption || typedSelect)) continue;
394
- const supplied = props![name];
558
+ if (name === "value" && (typedOption || typedSelect)) {
559
+ if (typedOption && staticMode) {
560
+ typedOptionValueSlot = true;
561
+ if (
562
+ typedOption.value != null &&
563
+ typeof typedOption.value !== "function"
564
+ ) {
565
+ optionValue = String(typedOption.value);
566
+ staticAttributes += ` value="${escapeHtml(optionValue)}"`;
567
+ }
568
+ }
569
+ continue;
570
+ }
571
+ const supplied = sourceEntries ? sourceEntries[index]![1] : props![name];
395
572
  let value = typeof supplied === "function" ? supplied() : supplied;
396
- if (name === "style") {
573
+ if (name === "xmlns") sourceNamespace = value;
574
+ if (!explicitAttributes && name === "style") {
397
575
  if (value == null || value === false) value = undefined;
398
576
  else if (typeof value === "object") {
399
- value = styleEntries(value)
400
- .map(([property, entry]) =>
401
- entry == null || entry === "" ? "" : `${property}:${entry};`,
402
- )
403
- .join("");
577
+ const entries = styleEntries(value);
578
+ let styleText = "";
579
+ for (let styleIndex = 0; styleIndex < entries.length; styleIndex++) {
580
+ const [styleProp, entry] = entries[styleIndex]!;
581
+ if (entry != null && entry !== "")
582
+ styleText += `${styleProp}:${entry};`;
583
+ }
584
+ value = styleText;
404
585
  } else if (typeof value !== "string") {
405
586
  throw new TypeError(
406
587
  "Style must be a CSS string, plain record, nullish or false",
@@ -408,44 +589,83 @@ export function h<P extends Record<string, unknown>>(
408
589
  }
409
590
  }
410
591
 
411
- if (lower === "select" && name === "multiple") {
412
- multiple = attributeValue(name, value, true) !== undefined;
592
+ if (
593
+ (!explicitAttributes || typedSelect) &&
594
+ lower === "select" &&
595
+ name === "multiple"
596
+ ) {
597
+ multiple =
598
+ (sourceCodec
599
+ ? sourceCodec(name, value, true)
600
+ : attributeValue(name, value, true)) !== undefined;
413
601
  }
414
- if (lower === "select" && name === "value") {
602
+ if (!explicitAttributes && lower === "select" && name === "value") {
415
603
  selectValue = value;
416
604
  hasSelectValue = true;
417
605
  continue;
418
606
  }
419
- if (lower === "option" && name === "selected") {
420
- if (attributeValue(name, value, true) !== undefined)
607
+ if (!explicitAttributes && lower === "option" && name === "selected") {
608
+ if (
609
+ (sourceCodec
610
+ ? sourceCodec(name, value, true)
611
+ : attributeValue(name, value, true)) !== undefined
612
+ )
421
613
  selectedAttribute = ` selected=""`;
422
614
  continue;
423
615
  }
424
- if (lower === "textarea" && property === "value") {
616
+ if (!explicitAttributes && lower === "textarea" && property === "value") {
425
617
  textareaValue = value;
426
618
  hasTextareaValue = true;
427
619
  continue;
428
620
  }
429
621
  const attr =
430
- property === "className"
622
+ !explicitAttributes && property === "className"
431
623
  ? "class"
432
- : property === "htmlFor"
624
+ : !explicitAttributes && property === "htmlFor"
433
625
  ? "for"
434
626
  : property;
435
- if (property === "value") {
436
- if (lower === "option") optionValue = String(value ?? "");
437
- attributes.push(["value", value]);
627
+ if (!explicitAttributes && property === "value") {
628
+ if (sourceCodec) {
629
+ const serialized = sourceCodec(
630
+ "value",
631
+ value,
632
+ typeof supplied === "function",
633
+ );
634
+ if (lower === "option") optionValue = String(serialized ?? "");
635
+ if (serialized !== undefined)
636
+ staticAttributes += ` value="${escapeHtml(serialized)}"`;
637
+ } else {
638
+ if (lower === "option") optionValue = String(value ?? "");
639
+ attributes!.push(["value", value]);
640
+ }
438
641
  continue;
439
642
  }
440
- attributes.push([attr, value]);
643
+ if (explicitAttributes) {
644
+ if (value != null) staticAttributes += ` ${attr}="${escapeHtml(value)}"`;
645
+ } else if (sourceCodec) {
646
+ const serialized = sourceCodec(
647
+ attr,
648
+ value,
649
+ typeof supplied === "function",
650
+ );
651
+ if (serialized !== undefined)
652
+ staticAttributes += ` ${attr}="${escapeHtml(serialized)}"`;
653
+ } else {
654
+ attributes!.push([attr, value]);
655
+ }
441
656
  }
442
657
  if (
443
658
  typedOption &&
659
+ !typedOptionValueSlot &&
444
660
  typedOption.value != null &&
445
661
  typeof typedOption.value !== "function"
446
662
  ) {
447
663
  optionValue = String(typedOption.value);
448
- attributes.push(["value", optionValue]);
664
+ if (staticMode) {
665
+ staticAttributes += ` value="${escapeHtml(optionValue)}"`;
666
+ } else {
667
+ attributes!.push(["value", optionValue]);
668
+ }
449
669
  }
450
670
  if (
451
671
  lower === "select" &&
@@ -464,44 +684,67 @@ export function h<P extends Record<string, unknown>>(
464
684
  ? children[0]
465
685
  : children.length
466
686
  ? children
467
- : (props?.children as SSRChild);
687
+ : explicitAttributes
688
+ ? undefined
689
+ : (props?.children as SSRChild);
468
690
  const bodyChild = resolve(sourceChild);
469
691
  const bodyText = textOnly
470
692
  ? hasTextareaValue
471
693
  ? String(textareaValue ?? "")
472
694
  : text(bodyChild)
473
695
  : undefined;
474
- const explicitNamespace = attributes.find(([name]) => name === "xmlns")?.[1];
696
+ let escapedBodyText =
697
+ bodyText === undefined ? undefined : escapeHtml(bodyText);
698
+ if (
699
+ escapedBodyText !== undefined &&
700
+ !explicitAttributes &&
701
+ lower === "textarea" &&
702
+ (escapedBodyText.startsWith("\n") || escapedBodyText.startsWith("\r"))
703
+ ) {
704
+ escapedBodyText = `\n${escapedBodyText}`;
705
+ }
475
706
  const isSvg = (inherited = false) =>
476
- explicitNamespace != null
477
- ? explicitNamespace === "http://www.w3.org/2000/svg"
707
+ sourceNamespace != null
708
+ ? sourceNamespace === "http://www.w3.org/2000/svg"
478
709
  : 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("");
710
+ const renderAttributes = (svg: boolean) => {
711
+ if (staticMode) return staticAttributes;
712
+ let out = "";
713
+ for (let index = 0; index < attributes!.length; index++) {
714
+ const [attr, value] = attributes![index]!;
715
+ if (!svg && attr === "checked" && !value) continue;
716
+ const serialized = attributeValue(
717
+ attr,
718
+ !svg &&
719
+ attr === "value" &&
720
+ lower !== "progress" &&
721
+ lower !== "meter" &&
722
+ lower !== "li"
723
+ ? (value ?? "")
724
+ : value,
725
+ !svg,
726
+ );
727
+ if (serialized !== undefined)
728
+ out += ` ${attr}="${escapeHtml(serialized)}"`;
729
+ }
730
+ return out;
731
+ };
497
732
  if (VOID.has(lower)) {
498
- if (content(bodyChild))
733
+ if (bodyChild != null && bodyChild !== false && content(bodyChild))
499
734
  throw new TypeError("Void server elements cannot have children");
735
+ if (staticMode) {
736
+ const markup = `<${tag}${staticAttributes}>`;
737
+ return { [html]: () => markup };
738
+ }
500
739
  return {
501
740
  [html]: (_selection, inheritedSvg) =>
502
741
  `<${tag}${renderAttributes(isSvg(inheritedSvg))}>`,
503
742
  };
504
743
  }
744
+ if (staticMode && escapedBodyText !== undefined && lower !== "option") {
745
+ const markup = `<${tag}${staticAttributes}>${escapedBodyText}</${tag}>`;
746
+ return { [html]: () => markup };
747
+ }
505
748
  return {
506
749
  [html]: (inherited, inheritedSvg) => {
507
750
  const svg = isSvg(inheritedSvg);
@@ -530,25 +773,45 @@ export function h<P extends Record<string, unknown>>(
530
773
  let selected = selectedAttribute;
531
774
  if (lower === "option" && selection) {
532
775
  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) &&
776
+ let matches: boolean;
777
+ if (selection.binding) {
778
+ const raw =
779
+ typedOption !== undefined
780
+ ? typedOption.value
781
+ : (optionValue ??
782
+ bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, ""));
783
+ matches =
784
+ selection.multiple && Array.isArray(selection.binding.value)
785
+ ? selection.binding.value.includes(raw)
786
+ : raw === selection.binding.value;
787
+ } else {
788
+ const value =
789
+ optionValue ??
790
+ bodyText!.replace(/[\t\n\f\r ]+/g, " ").replace(/^ | $/g, "");
791
+ matches =
792
+ selection.values!.has(value) &&
542
793
  (selection.multiple || !selection.matched);
543
- selected = matches ? ` selected=""` : "";
794
+ }
795
+ selected =
796
+ matches || (selection.binding?.preserveSelected && selectedAttribute)
797
+ ? ` selected=""`
798
+ : "";
544
799
  if (matches) selection.matched = true;
545
800
  }
546
- let body =
547
- bodyText === undefined
548
- ? runWithOwner(owner && !owner.disposed ? owner : getOwner(), () =>
549
- content(bodyChild, selection, svg && lower !== "foreignobject"),
550
- )
551
- : escapeHtml(bodyText);
801
+ let body: string;
802
+ if (escapedBodyText !== undefined) {
803
+ body = escapedBodyText;
804
+ } else {
805
+ const activeOwner = getOwner();
806
+ const targetOwner = owner && !owner.disposed ? owner : activeOwner;
807
+ const nextSvg = svg && lower !== "foreignobject";
808
+ body =
809
+ targetOwner === activeOwner
810
+ ? content(bodyChild, selection, nextSvg)
811
+ : runWithOwner(targetOwner, () =>
812
+ content(bodyChild, selection, nextSvg),
813
+ );
814
+ }
552
815
  if (
553
816
  lower === "select" &&
554
817
  selection &&
@@ -559,41 +822,39 @@ export function h<P extends Record<string, unknown>>(
559
822
  ) {
560
823
  throw new TypeError("Server select value has no matching option");
561
824
  }
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}>`;
825
+ return `<${tag}${staticMode ? staticAttributes : renderAttributes(svg)}${selected}>${body}</${tag}>`;
568
826
  },
569
827
  };
570
828
  }
571
829
 
572
830
  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) {
831
+ return withSSRRendering(() =>
832
+ withSSRRenderAttempt(undefined, () => {
833
+ let dispose = () => {};
834
+ let result: string;
587
835
  try {
588
- dispose();
589
- } catch {
590
- /* Preserve the render error. */
836
+ result = createRoot((stop) => {
837
+ dispose = stop;
838
+ resetSSRRenderAttempt();
839
+ const requestOwner = getOwner()!;
840
+ if (requestOwner.context?.has(cleanupOrderKey)) {
841
+ requestOwner.context = new Map(requestOwner.context);
842
+ requestOwner.context.delete(cleanupOrderKey);
843
+ }
844
+ return content(fn());
845
+ });
846
+ } catch (error) {
847
+ try {
848
+ dispose();
849
+ } catch {
850
+ /* Preserve the render error. */
851
+ }
852
+ throw error;
591
853
  }
592
- throw error;
593
- }
594
- dispose();
595
- return result;
596
- });
854
+ dispose();
855
+ return result;
856
+ }),
857
+ );
597
858
  }
598
859
 
599
860
  /** Server lowering must import lifecycle hooks here; browser effects never run. */