@verajs/ssr 0.2.1 → 0.3.0

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 (63) hide show
  1. package/README.md +507 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +98 -0
  4. package/dist/vera/escaping.d.ts +142 -0
  5. package/dist/vera/escaping.js +267 -0
  6. package/dist/vera/events.d.ts +41 -0
  7. package/dist/vera/events.js +162 -0
  8. package/dist/vera/frames.d.ts +38 -0
  9. package/dist/vera/frames.js +195 -0
  10. package/dist/vera/index.d.ts +48 -0
  11. package/dist/vera/index.js +480 -0
  12. package/{types → dist/vera}/nodes.d.ts +389 -302
  13. package/dist/vera/nodes.js +2322 -0
  14. package/dist/vera/parse.d.ts +37 -0
  15. package/dist/vera/parse.js +390 -0
  16. package/dist/vera/reflections.d.ts +566 -0
  17. package/dist/vera/reflections.js +820 -0
  18. package/dist/vera/registry.d.ts +14 -0
  19. package/{src → dist}/vera/registry.js +5 -1
  20. package/dist/vera/report.d.ts +27 -0
  21. package/dist/vera/report.js +56 -0
  22. package/dist/vera/scan.d.ts +37 -0
  23. package/dist/vera/scan.js +143 -0
  24. package/dist/vera/select.d.ts +40 -0
  25. package/dist/vera/select.js +261 -0
  26. package/dist/vera/serializer.d.ts +39 -0
  27. package/dist/vera/serializer.js +1372 -0
  28. package/dist/vera/shim.d.ts +42 -0
  29. package/dist/vera/shim.js +853 -0
  30. package/dist/vera/slots.d.ts +5 -0
  31. package/dist/vera/slots.js +104 -0
  32. package/dist/vera/stylesheets.d.ts +62 -0
  33. package/dist/vera/stylesheets.js +180 -0
  34. package/dist/vera/tokenizer.d.ts +32 -0
  35. package/dist/vera/tokenizer.js +528 -0
  36. package/dist/vera/types.d.ts +117 -0
  37. package/dist/vera/views.d.ts +63 -0
  38. package/dist/vera/views.js +245 -0
  39. package/package.json +12 -13
  40. package/src/vera/escaping.js +0 -135
  41. package/src/vera/events.js +0 -164
  42. package/src/vera/frames.js +0 -102
  43. package/src/vera/index.js +0 -1187
  44. package/src/vera/nodes.js +0 -2294
  45. package/src/vera/parse.js +0 -381
  46. package/src/vera/reflections.js +0 -811
  47. package/src/vera/select.js +0 -234
  48. package/src/vera/serializer.js +0 -1080
  49. package/src/vera/shim.js +0 -761
  50. package/src/vera/stylesheets.js +0 -155
  51. package/src/vera/views.js +0 -240
  52. package/types/escaping.d.ts +0 -27
  53. package/types/events.d.ts +0 -4
  54. package/types/frames.d.ts +0 -12
  55. package/types/index.d.ts +0 -13
  56. package/types/parse.d.ts +0 -19
  57. package/types/reflections.d.ts +0 -657
  58. package/types/registry.d.ts +0 -8
  59. package/types/select.d.ts +0 -5
  60. package/types/serializer.d.ts +0 -26
  61. package/types/shim.d.ts +0 -23
  62. package/types/stylesheets.d.ts +0 -53
  63. package/types/views.d.ts +0 -26
@@ -0,0 +1,20 @@
1
+ /**
2
+ * **@verajs/ssr's diagnostics, keyed by code — every build** (2026-10-09). ssr is Node-only and
3
+ * compiled per file with no `__DEV__`, so its words stay and each line gains its code (`report.ts` formats them),
4
+ * as the jsx compiler's do: a server's log is read by its developer. `PROSE` is ssr's own, published as
5
+ * `packages/ssr/diagnostics.json`. `TWINS` are facts @verajs/shared-utils already states — the renderer says them
6
+ * in the browser — which ssr cannot import (it ships `src` with no dependencies): the SAME text under the same code,
7
+ * held equal by `tests/ssr-shared-twins.test.mjs` on generated text, and never published here (their docs page is
8
+ * shared-utils').
9
+ */
10
+ type Prose = (...args: string[]) => readonly [string, string?];
11
+ export declare const PROSE: Record<string, Prose>;
12
+ /** The shared-utils facts, word for word — see the header. The export names are shared-utils' (the name IS the code). */
13
+ export declare const TWINS: {
14
+ getterOnlyProp: (key: string) => readonly [`received a bound property \`.${string}\` (or \`!${string}\`), but its class declares \`${string}\` as a getter with no setter \u2014 the value cannot be delivered and the binding is ignored.`, "Add a setter, or stop binding it."];
15
+ tagHole: () => readonly ["an expression in tag position (`<${…}>`) cannot be a tag name — a tag name must be a tag value.", "Use `tag`h1`` from @verajs/renderer/tag, with that entry's `html`."];
16
+ scriptUrl: (name: string) => readonly [`\`${string}\` was given a javascript: URL \u2014 refused, and the attribute removed.`, "A bound URL is data, and data must never become code."];
17
+ nameExpression: (written: string, given: string) => readonly [`an attribute name cannot be an expression \u2014 \`${string}\` is read by the parser before any value exists.`, `A name known only at runtime is a spread: \`\${spread({ [\`${string}\`]: ${string} })}\` (from @verajs/renderer/spread).`];
18
+ forgedTemplate: () => readonly ["is shaped like a template but was not made by html`` — rendered as text.", "A template from data (JSON, or html([markup])) is never markup; for trusted markup, bind it: <div .innerHTML=${markup}>."];
19
+ };
20
+ export {};
@@ -0,0 +1,98 @@
1
+ export const PROSE = {
2
+ 'ssr-selector-unsupported': (selector, why) => [
3
+ `this DOM cannot answer the selector ${selector} — ${why}.`,
4
+ 'It matches on structure and attributes only; rather than return a wrong answer it says so.',
5
+ ],
6
+ 'ssr-markup-declined': () => [
7
+ "some of this element's markup could not be parsed, so children/querySelector do not see it — they answer emptily, or with only the part that did parse.",
8
+ 'This DOM parses markup it can reproduce exactly and declines the rest, rather than building a tree the browser would not — a mismatched or stray closing tag is the usual cause. Make the markup well-formed, or build the children with createElement/appendChild if a component needs to read them back.',
9
+ ],
10
+ 'ssr-listener-threw': (type) => [
11
+ `a "${type}" listener threw — the dispatch went on, as in a browser; its error follows.`,
12
+ 'The error names what went wrong. This is said once per component and event type for the life of the process.',
13
+ ],
14
+ 'ssr-setter-threw': (tag, name, thrown) => [
15
+ `<${tag}> refused the bound property \`.${name}\` — its setter threw ${thrown}.`,
16
+ "The binding's value is the argument it was given; the setter's own error is this one's cause.",
17
+ ],
18
+ 'ssr-unfinished-tag': () => [
19
+ 'a template cannot end inside a tag — the client drops an unfinished tag.',
20
+ 'Close the tag inside the template.',
21
+ ],
22
+ 'ssr-template-in-text': () => [
23
+ 'a template cannot render inside a text-only element (`<textarea>`, `<title>`…) — its content is text.',
24
+ 'Render a string there.',
25
+ ],
26
+ 'ssr-nesting-depth': (max) => [
27
+ `component nesting exceeded ${max} levels. A component that renders itself recurses without bound, and on a server that is a hung request — so this refuses rather than waiting for the stack to go.`,
28
+ 'If the tree is genuinely this deep it renders fine in a browser, which has no such limit; that difference is in the @verajs/ssr README.',
29
+ ],
30
+ 'ssr-sheet-text': () => [
31
+ 'CSSStyleSheet.deleteRule needs a parsed rule list; this sheet is text.',
32
+ 'Remove the rule from the text instead, or replace the sheet.',
33
+ ],
34
+ 'ssr-styles-vary': () => [
35
+ 'hoisted different CSS than it did on an earlier render, and the new stylesheet was dropped.',
36
+ "A tag's styles are established once per class for the life of the process, so CSS that varies per request cannot be hoisted — put the varying part in an inline style or a custom property instead.",
37
+ ],
38
+ 'ssr-prop-refused': (tag, thrown) => [
39
+ `<${tag}> refused a value from \`props\` — setting it threw ${thrown}.`,
40
+ 'A read-only property cannot be set; pass it as an attribute, or give the class a setter. The setter\'s own error is this one\'s cause.',
41
+ ],
42
+ 'ssr-async-connected': (tag) => [
43
+ `<${tag}> has an async connectedCallback or an async setup, which cannot be awaited during a synchronous render — its markup would be empty.`,
44
+ 'Use renderToStringAsync, or load data first and pass it as attributes.',
45
+ ],
46
+ 'ssr-attribute-name': (name) => [
47
+ `\`attributes\` cannot use ${name} as a name — an attribute name may not contain whitespace, a quote, "/", "=" or ">"; setAttribute refuses it in the browser too.`,
48
+ 'Give it a valid attribute name.',
49
+ ],
50
+ 'ssr-option': (name, expected) => [`\`${name}\` must be ${expected}.`, 'Check the options passed to renderToString.'],
51
+ 'ssr-url-refused': (href, root) => [
52
+ `refused ${href} — it resolves outside ${root}.`,
53
+ 'Nothing was imported. A module URL is bounded to `base`; point it at a module inside that directory.',
54
+ ],
55
+ 'ssr-no-definition': (url) => [
56
+ `no custom element definition found for ${url}.`,
57
+ "Export the component's class from that module, or pass { tag }.",
58
+ ],
59
+ 'ssr-renderer-replaced': () => [
60
+ 'the server renderer has been replaced — a renderer was wired that does not know @verajs/ssr is rendering, and every component would render empty.',
61
+ "Import @verajs/ssr BEFORE wiring the renderer: vera's renderer then declines on the server and keeps only its shadow default. A renderer that is not vera's: guard its wiring (`if (!globalThis.__veraSsrShimmed)`).",
62
+ ],
63
+ 'ssr-timeout': (timeout, pendingIn, waitingOn) => [
64
+ `was served after its ${timeout} ms \`timeout\` with a promise still pending${pendingIn ? ` in ${pendingIn}` : ''} (an async setup or connectedCallback, or a promise a frame callback returned), so the page is what had rendered by then.${waitingOn ? ` Still waiting on customElements.whenDefined for ${waitingOn}, which the server never defined.` : ''}`,
65
+ `${waitingOn ? 'If only the browser defines it, return before that wait on the server — `if (globalThis.__veraSsrShimmed) return;` — so the server serves what the component shows before the wait, as the browser does first. ' : ''}Raise \`timeout\` if the wait is real, or find the promise that never settles. Said once per component for the life of the process.`,
66
+ ],
67
+ 'ssr-static-write': (prop) => [
68
+ `this render declared itself static, so its stores are not reactive and writing ${prop} would change nothing.`,
69
+ 'Remove `static: true` from renderToString, or stop writing to the store during the render.',
70
+ ],
71
+ 'ssr-render-threw': (tag, others, thrown) => [
72
+ `<${tag}> threw while rendering${others} — its markup would be empty: ${thrown}.`,
73
+ "The component's own error is this one's cause.",
74
+ ],
75
+ };
76
+ /** The shared-utils facts, word for word — see the header. The export names are shared-utils' (the name IS the code). */
77
+ export const TWINS = {
78
+ getterOnlyProp: (key) => [
79
+ `received a bound property \`.${key}\` (or \`!${key}\`), but its class declares \`${key}\` as a getter with no setter — the value cannot be delivered and the binding is ignored.`,
80
+ 'Add a setter, or stop binding it.',
81
+ ],
82
+ tagHole: () => [
83
+ 'an expression in tag position (`<${…}>`) cannot be a tag name — a tag name must be a tag value.',
84
+ "Use `tag`h1`` from @verajs/renderer/tag, with that entry's `html`.",
85
+ ],
86
+ scriptUrl: (name) => [
87
+ `\`${name}\` was given a javascript: URL — refused, and the attribute removed.`,
88
+ 'A bound URL is data, and data must never become code.',
89
+ ],
90
+ nameExpression: (written, given) => [
91
+ `an attribute name cannot be an expression — \`${written}\` is read by the parser before any value exists.`,
92
+ `A name known only at runtime is a spread: \`\${spread({ [\`${written}\`]: ${given} })}\` (from @verajs/renderer/spread).`,
93
+ ],
94
+ forgedTemplate: () => [
95
+ 'is shaped like a template but was not made by html`` — rendered as text.',
96
+ 'A template from data (JSON, or html([markup])) is never markup; for trusted markup, bind it: <div .innerHTML=${markup}>.',
97
+ ],
98
+ };
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Escaping at the render boundary, and the elements that must not be escaped at all.
3
+ *
4
+ * One place decides what becomes a character reference, because escaping in two places
5
+ * double-escapes and escaping in none is an injection. `<style>` and `<script>` hold **raw text**: a
6
+ * browser does not decode a character reference inside them, so escaping there does not protect
7
+ * anything and does corrupt the content — a `static styles` with `.a > .b` shipped a broken
8
+ * stylesheet until that was understood. `<textarea>` and `<title>` hold text too, but RCDATA: a
9
+ * reference IS decoded there, so escaping is exactly right — and writing them raw let a value close
10
+ * the element (see `TextShim.markup`).
11
+ */
12
+ export declare const escapeHtml: (value: unknown) => string;
13
+ /**
14
+ * Neutralize a `</style>` sequence inside CSS text.
15
+ *
16
+ * `<style>` is a raw-text element: its content is not HTML, so `escapeHtml` cannot be used here —
17
+ * it would turn every `>` in a selector into `&#62;` and break the stylesheet. The only sequence
18
+ * that matters is the end tag, because it is the one thing the HTML tokenizer looks for while
19
+ * inside the element. A value interpolated into `css` and carrying `</style>` therefore closes the
20
+ * element and everything after it parses as markup.
21
+ *
22
+ * `<\/style` is valid CSS — a backslash escape is legal in identifiers and strings, and renders
23
+ * identically — while the tokenizer no longer matches an end tag. Applied here, at the render
24
+ * boundary, rather than in `css` itself: escaping at the source would corrupt the constructed
25
+ * stylesheet path, which is the double-escaping principle #8 warns about. It also catches a
26
+ * sequence assembled across several interpolations, which source-side escaping cannot see.
27
+ *
28
+ * **Deliberately duplicated** in `@verajs/styles` (`escapeStyleText` there is the same three
29
+ * lines). It cannot be shared: the obvious home is `@verajs/shared-utils`, which is private and
30
+ * inlined at build time, and `@verajs/ssr` publishes its `src` with **no dependencies at all** — an
31
+ * import of a package that is never published would break the published tarball. Two copies of a
32
+ * security rule is a real risk, so `tests/ssr-escaping.test.mjs` asserts the two agree on the
33
+ * payloads that matter rather than trusting they will be edited together.
34
+ */
35
+ export declare const escapeStyleText: (value: unknown) => string;
36
+ export declare const escapeRawText: (value: unknown, tag: string) => string;
37
+ /**
38
+ * Elements whose content is text rather than markup. Setting `textContent` on one of these stores
39
+ * the text as written: inside `<style>` or `<script>` a character reference is **not** decoded, so
40
+ * escaping there does not protect anything and does corrupt the content.
41
+ */
42
+ /**
43
+ * Elements a parser reads the children of as text.
44
+ *
45
+ * `iframe` and `noscript` were absent, so this DOM built a tree no browser builds:
46
+ * `<noscript><img src="x"></noscript>` parsed to an element here and `querySelectorAll('noscript img')`
47
+ * answered **1** where every engine answers 0, because the content is a text node.
48
+ *
49
+ * Measured across Chromium, Firefox and WebKit rather than read off a spec — and jsdom is not the
50
+ * oracle for this one. It parses with scripting *disabled*, so it agrees with the old list about
51
+ * `noscript` and all three real engines disagree with both.
52
+ */
53
+ export declare const RAW_TEXT_ELEMENTS: Set<string>;
54
+ /** The raw-text elements whose text IS decoded — RCDATA. The rest mean their bytes. */
55
+ export declare const RCDATA_ELEMENTS: Set<string>;
56
+ /**
57
+ * **A parsed value starts by normalizing line breaks.** The input stream turns every CRLF and lone CR into LF before a
58
+ * token exists, so `a\r\nb` is `"a\nb"` as text, as an attribute value, as comment data and as raw text alike — while a
59
+ * REFERENCE to CR (`&#13;`) is decoded after that and stays a CR. So this runs on bytes, before any decoding.
60
+ */
61
+ export declare const normalizeNewlines: (raw: string) => string;
62
+ /**
63
+ * **The line feed a parser takes.** Right after a `<pre>`, `<listing>` or `<textarea>` start tag the HTML parser drops
64
+ * ONE line feed: a raw LF, a CR or CRLF (the input stream normalizes both to LF first), or a reference to one
65
+ * (`&#10;`, `&#xA;`, `&NewLine;`). So content that BEGINS with a line feed loses it on the way in. The platform's own
66
+ * serialization does not guard against that — Chromium, Firefox, WebKit and jsdom all serialize a `<pre>` whose text is
67
+ * `"\nabc"` as `<pre>\nabc</pre>`, which parses back as `"abc"` (measured 2026-10-06) — so a server that writes what
68
+ * the platform writes ships content the client never had. Whatever this package writes for such an element puts one
69
+ * extra line feed in front of content that starts with one, for the parser to take.
70
+ */
71
+ export declare const NEWLINE_TAKERS: Set<string>;
72
+ /** How many characters at `at` form the line feed a parser takes there — `0` when it would take none. */
73
+ export declare const leadingNewline: (text: string, at: number) => number;
74
+ /**
75
+ * Elements that have no end tag. Writing one is not merely redundant — a parser reads `</br>` as
76
+ * *another* `<br>`, so `appendChild(createElement('br'))` served `<br></br>` and rendered two line
77
+ * breaks where the client has one. The same content assigned as a markup string was already correct,
78
+ * so the two paths disagreed with each other as well as with the browser.
79
+ */
80
+ export declare const VOID_ELEMENTS: Set<string>;
81
+ /**
82
+ * **A URL a browser reads as `javascript:`** — the twin of `SCRIPT_URL` in `@verajs/shared-utils`,
83
+ * which this package cannot import (it publishes its `src` with no dependencies). Matched the way the
84
+ * URL Standard's parser reads a scheme: leading C0 controls and spaces stripped, ASCII tab, LF and CR
85
+ * removed anywhere, case-insensitive. A bound value that parses this way is code arriving as data, so
86
+ * the client refuses it — and a server that emitted it would serve the very link the client refuses,
87
+ * and a working exploit to anyone who never hydrates. `tests/url-sinks.test.mjs` drives both homes
88
+ * against one stated spec.
89
+ */
90
+ export declare const SCRIPT_URL: RegExp;
91
+ /**
92
+ * The names whose bound value is checked for `javascript:` — captured: checked from the start (where a browser
93
+ * navigates); not captured: an SVG animation's values, checked item by item. The twin of `URL_SINK` there.
94
+ */
95
+ export declare const URL_SINK: RegExp;
96
+ /** `SCRIPT_URL` at the start of any `;`-separated item — an animation's `values` list — the twin of `SCRIPT_URL_ITEM` there. */
97
+ export declare const SCRIPT_URL_ITEM: RegExp;
98
+ /** A bound inline event-handler attribute runs its value as code — the twin of `INLINE_HANDLER` there. */
99
+ export declare const INLINE_HANDLER: RegExp;
100
+ /**
101
+ * **A numeric reference's character, exactly as a parser decodes it** — the one decoder every reader here uses: NUL, a
102
+ * surrogate or an out-of-range value is U+FFFD, and 0x80–0x9F map through `C1`. `String.fromCodePoint` THROWS past
103
+ * U+10FFFF, so the copies that called it directly took a whole render down on `&#1114112;` in markup.
104
+ */
105
+ export declare const decodeCodePoint: (code: number) => string;
106
+ export declare const decodeSchemeReferences: (text: string) => string;
107
+ /**
108
+ * Where a comment opened at `open` (the index of its `<!--`) ends, as the HTML tokenizer reads it: at `-->`, at
109
+ * `--!>`, or ABRUPTLY at `<!-->` and `<!--->`. Answers the index just past it, or `-1` when it runs to the end of the
110
+ * input — one number, never an allocation, since the component scan asks it for every comment of every render.
111
+ *
112
+ * Knowing only `-->` read `<p><!-->${value}</p>` as a comment swallowing the value, which the browser renders. Every
113
+ * scanner here that meets a comment asks this one rule, and the client's scanner holds its twin.
114
+ *
115
+ * @param markup
116
+ * @param open
117
+ * @returns The index past the comment, or `-1`. The declared `number` is what makes a caller still reading the old
118
+ * `[dataEnd, end]` shape a compile error; `server-content.test.mjs` also pins every comment shape before a script.
119
+ */
120
+ export declare const commentEnd: (markup: string, open: number) => number;
121
+ /**
122
+ * Where a comment's TEXT stops, given the end `commentEnd` answered: before `-->`/`--!>`, or at once when abrupt.
123
+ *
124
+ * @param markup
125
+ * @param open
126
+ * @param end
127
+ */
128
+ export declare const commentDataEnd: (markup: string, open: number, end: number) => number;
129
+ /**
130
+ * **What a thrown value says, whatever was thrown — and it never throws itself.** JavaScript can throw anything, and
131
+ * the value comes from component code: `null`, `undefined`, an object with no prototype (`String()` finds no
132
+ * `toString`), one whose `toString` or `message` getter throws, a Proxy whose every trap throws. A message built from
133
+ * `(error as Error).message` crashed on the first two, and a careless formatter crashes on the rest — either way the
134
+ * real failure was replaced by an unrelated TypeError from inside the framework. So anything that cannot be read
135
+ * becomes a fixed phrase; `Object.prototype.toString` is no fallback, since it reads `Symbol.toStringTag` through a
136
+ * Proxy's trap too.
137
+ *
138
+ * **A deliberate duplicate of `thrownMessage` in `packages/shared-utils/src/utils.ts` — fix both copies.** This package
139
+ * is compiled per file with no bundling, so it cannot import that private, unpublished package at run time;
140
+ * `tests/thrown-message-copies.test.mjs` runs one table of thrown values against both, so they cannot drift.
141
+ */
142
+ export declare const thrownMessage: (error: unknown) => string;
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Escaping at the render boundary, and the elements that must not be escaped at all.
3
+ *
4
+ * One place decides what becomes a character reference, because escaping in two places
5
+ * double-escapes and escaping in none is an injection. `<style>` and `<script>` hold **raw text**: a
6
+ * browser does not decode a character reference inside them, so escaping there does not protect
7
+ * anything and does corrupt the content — a `static styles` with `.a > .b` shipped a broken
8
+ * stylesheet until that was understood. `<textarea>` and `<title>` hold text too, but RCDATA: a
9
+ * reference IS decoded there, so escaping is exactly right — and writing them raw let a value close
10
+ * the element (see `TextShim.markup`).
11
+ */
12
+ const NEEDS_ESCAPE = /[&<>"'\r]/;
13
+ const ESCAPE = /[&<>"'\r]/g;
14
+ /**
15
+ * Escaping is the hottest thing in a large render, and most values have nothing to escape.
16
+ *
17
+ * Asking first is worth it: 200 escapes of ordinary text measured 9.60 µs going straight to
18
+ * `replace` against 3.03 µs testing first — and text that *does* need escaping came out slightly
19
+ * ahead too (21.73 vs 20.03), because a global `replace` sets up more than a single `test` does. On
20
+ * a 100-row table of clean data that is a quarter of the whole render.
21
+ */
22
+ /**
23
+ * **Carriage return is here for correctness, not for safety.**
24
+ *
25
+ * The HTML input-stream preprocessor rewrites CR and CRLF to a single LF *before* tokenization, so a
26
+ * raw `\r` written into markup does not survive being parsed — the server renders `a\r\nb` and the
27
+ * client reads back `a\nb`. Nothing is injected and nothing looks wrong; the two sides simply hold
28
+ * different strings, which is a hydration mismatch on every render of anything carrying a Windows
29
+ * newline: a `<textarea>` value, a CSV cell, a string from an HTTP payload.
30
+ *
31
+ * Character references are resolved *after* preprocessing, so `&#13;` does survive. **Verified in
32
+ * Chromium, Firefox and WebKit**, all three identical: raw CRLF parses to `[97, 10, 98]` and
33
+ * `a&#13;\nb` parses to `[97, 13, 10, 98]`, in text and in attribute values alike.
34
+ *
35
+ * **NUL is the other character the preprocessor rewrites, and it is not fixable here.** A raw NUL is
36
+ * dropped in text and becomes U+FFFD in an attribute, and `&#0;` is a parse error that also becomes
37
+ * U+FFFD — there is no spelling that round-trips, so a string containing NUL cannot be server
38
+ * rendered faithfully by anyone. It is listed as a limitation in the README rather than silently
39
+ * transformed here, because turning it into U+FFFD would make the markup lie about what the
40
+ * component rendered without making the two sides agree.
41
+ *
42
+ * Precomputed, because building `'&#' + c.charCodeAt(0) + ';'` per character is the slow half.
43
+ */
44
+ const ESCAPED = { '&': '&#38;', '<': '&#60;', '>': '&#62;', '"': '&#34;', "'": '&#39;', '\r': '&#13;' };
45
+ export const escapeHtml = (value) => {
46
+ /**
47
+ * `` `${value}` `` rather than `String(value)`: identical for everything except a **symbol**,
48
+ * which `String` special-cases into its description while every DOM conversion on the client
49
+ * throws. Serving `Symbol(s)` into markup the client cannot reproduce is the leniency this
50
+ * package's README warns about — it does not make anything work, it moves the failure across the
51
+ * boundary and strips the context.
52
+ */
53
+ const text = typeof value === 'string' ? value : `${value}`;
54
+ return NEEDS_ESCAPE.test(text) ? text.replace(ESCAPE, (character) => ESCAPED[character]) : text;
55
+ };
56
+ /**
57
+ * Neutralize a `</style>` sequence inside CSS text.
58
+ *
59
+ * `<style>` is a raw-text element: its content is not HTML, so `escapeHtml` cannot be used here —
60
+ * it would turn every `>` in a selector into `&#62;` and break the stylesheet. The only sequence
61
+ * that matters is the end tag, because it is the one thing the HTML tokenizer looks for while
62
+ * inside the element. A value interpolated into `css` and carrying `</style>` therefore closes the
63
+ * element and everything after it parses as markup.
64
+ *
65
+ * `<\/style` is valid CSS — a backslash escape is legal in identifiers and strings, and renders
66
+ * identically — while the tokenizer no longer matches an end tag. Applied here, at the render
67
+ * boundary, rather than in `css` itself: escaping at the source would corrupt the constructed
68
+ * stylesheet path, which is the double-escaping principle #8 warns about. It also catches a
69
+ * sequence assembled across several interpolations, which source-side escaping cannot see.
70
+ *
71
+ * **Deliberately duplicated** in `@verajs/styles` (`escapeStyleText` there is the same three
72
+ * lines). It cannot be shared: the obvious home is `@verajs/shared-utils`, which is private and
73
+ * inlined at build time, and `@verajs/ssr` publishes its `src` with **no dependencies at all** — an
74
+ * import of a package that is never published would break the published tarball. Two copies of a
75
+ * security rule is a real risk, so `tests/ssr-escaping.test.mjs` asserts the two agree on the
76
+ * payloads that matter rather than trusting they will be edited together.
77
+ */
78
+ export const escapeStyleText = (value) => `${value}`.replace(/<\/(style)/gi, '<\\/$1');
79
+ /**
80
+ * The same neutralization, for whichever RAWTEXT element the value landed in.
81
+ *
82
+ * `<style>` and `<script>` are the only two: a browser does not decode a character reference inside
83
+ * either, so escaping their content protects nothing and corrupts it. Interpolating `.a > .b` into a
84
+ * stylesheet produced `.a &#62; .b` — a selector matching nothing — while the client, which sets
85
+ * text through the DOM and never re-parses, rendered it correctly. Every interpolated stylesheet was
86
+ * broken on the server and right in the browser.
87
+ *
88
+ * Writing raw means the element's own end tag has to come out of the value instead, or it closes the
89
+ * element and everything after it parses as markup. `<\/style` is valid CSS and `<\/script` is the
90
+ * canonical form in JavaScript; both render identically and neither is seen by the tokenizer. Only
91
+ * the end tag matters, because it is the only sequence the tokenizer looks for while inside.
92
+ *
93
+ * `<title>` and `<textarea>` are **RCDATA** — references *are* decoded there — so they keep ordinary
94
+ * escaping, which is also what the client produces for them.
95
+ */
96
+ const RAW_TEXT_CLOSERS = { style: /<\/(style)/gi, script: /<\/(script)/gi };
97
+ export const escapeRawText = (value, tag) => {
98
+ const closer = RAW_TEXT_CLOSERS[tag];
99
+ return closer ? `${value}`.replace(closer, '<\\/$1') : escapeHtml(value);
100
+ };
101
+ /**
102
+ * Elements whose content is text rather than markup. Setting `textContent` on one of these stores
103
+ * the text as written: inside `<style>` or `<script>` a character reference is **not** decoded, so
104
+ * escaping there does not protect anything and does corrupt the content.
105
+ */
106
+ /**
107
+ * Elements a parser reads the children of as text.
108
+ *
109
+ * `iframe` and `noscript` were absent, so this DOM built a tree no browser builds:
110
+ * `<noscript><img src="x"></noscript>` parsed to an element here and `querySelectorAll('noscript img')`
111
+ * answered **1** where every engine answers 0, because the content is a text node.
112
+ *
113
+ * Measured across Chromium, Firefox and WebKit rather than read off a spec — and jsdom is not the
114
+ * oracle for this one. It parses with scripting *disabled*, so it agrees with the old list about
115
+ * `noscript` and all three real engines disagree with both.
116
+ */
117
+ export const RAW_TEXT_ELEMENTS = new Set(['style', 'script', 'textarea', 'title', 'iframe', 'noscript']);
118
+ /** The raw-text elements whose text IS decoded — RCDATA. The rest mean their bytes. */
119
+ export const RCDATA_ELEMENTS = new Set(['textarea', 'title']);
120
+ /**
121
+ * **A parsed value starts by normalizing line breaks.** The input stream turns every CRLF and lone CR into LF before a
122
+ * token exists, so `a\r\nb` is `"a\nb"` as text, as an attribute value, as comment data and as raw text alike — while a
123
+ * REFERENCE to CR (`&#13;`) is decoded after that and stays a CR. So this runs on bytes, before any decoding.
124
+ */
125
+ export const normalizeNewlines = (raw) => (raw.includes('\r') ? raw.replace(/\r\n?/g, '\n') : raw);
126
+ /**
127
+ * **The line feed a parser takes.** Right after a `<pre>`, `<listing>` or `<textarea>` start tag the HTML parser drops
128
+ * ONE line feed: a raw LF, a CR or CRLF (the input stream normalizes both to LF first), or a reference to one
129
+ * (`&#10;`, `&#xA;`, `&NewLine;`). So content that BEGINS with a line feed loses it on the way in. The platform's own
130
+ * serialization does not guard against that — Chromium, Firefox, WebKit and jsdom all serialize a `<pre>` whose text is
131
+ * `"\nabc"` as `<pre>\nabc</pre>`, which parses back as `"abc"` (measured 2026-10-06) — so a server that writes what
132
+ * the platform writes ships content the client never had. Whatever this package writes for such an element puts one
133
+ * extra line feed in front of content that starts with one, for the parser to take.
134
+ */
135
+ export const NEWLINE_TAKERS = new Set(['pre', 'listing', 'textarea']);
136
+ /** A numeric reference may omit its `;`, a named one may not — and `&#100;` is not `&#10` followed by `0`. */
137
+ const LEADING_NEWLINE = /\r\n?|\n|&(?:#0*10(?![0-9]);?|#[xX]0*[aA](?![0-9a-fA-F]);?|NewLine;)/y;
138
+ /** How many characters at `at` form the line feed a parser takes there — `0` when it would take none. */
139
+ export const leadingNewline = (text, at) => {
140
+ const code = text.charCodeAt(at);
141
+ /** The characters themselves answer without the pattern; only a `&` can be a reference to one. */
142
+ if (code === 10)
143
+ return 1;
144
+ if (code === 13)
145
+ return text.charCodeAt(at + 1) === 10 ? 2 : 1;
146
+ if (code !== 38)
147
+ return 0;
148
+ LEADING_NEWLINE.lastIndex = at;
149
+ return LEADING_NEWLINE.exec(text)?.[0].length ?? 0;
150
+ };
151
+ /**
152
+ * Elements that have no end tag. Writing one is not merely redundant — a parser reads `</br>` as
153
+ * *another* `<br>`, so `appendChild(createElement('br'))` served `<br></br>` and rendered two line
154
+ * breaks where the client has one. The same content assigned as a markup string was already correct,
155
+ * so the two paths disagreed with each other as well as with the browser.
156
+ */
157
+ export const VOID_ELEMENTS = new Set([
158
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
159
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
160
+ ]);
161
+ /**
162
+ * **A URL a browser reads as `javascript:`** — the twin of `SCRIPT_URL` in `@verajs/shared-utils`,
163
+ * which this package cannot import (it publishes its `src` with no dependencies). Matched the way the
164
+ * URL Standard's parser reads a scheme: leading C0 controls and spaces stripped, ASCII tab, LF and CR
165
+ * removed anywhere, case-insensitive. A bound value that parses this way is code arriving as data, so
166
+ * the client refuses it — and a server that emitted it would serve the very link the client refuses,
167
+ * and a working exploit to anyone who never hydrates. `tests/url-sinks.test.mjs` drives both homes
168
+ * against one stated spec.
169
+ */
170
+ // eslint-disable-next-line no-control-regex
171
+ export const SCRIPT_URL = /^[\u0000- ]*j[\t\n\r]*a[\t\n\r]*v[\t\n\r]*a[\t\n\r]*s[\t\n\r]*c[\t\n\r]*r[\t\n\r]*i[\t\n\r]*p[\t\n\r]*t[\t\n\r]*:/i;
172
+ /**
173
+ * The names whose bound value is checked for `javascript:` — captured: checked from the start (where a browser
174
+ * navigates); not captured: an SVG animation's values, checked item by item. The twin of `URL_SINK` there.
175
+ */
176
+ export const URL_SINK = /^(?:(href|src|action|formaction|xlink:href|data)|to|from|by|values)$/i;
177
+ /** `SCRIPT_URL` at the start of any `;`-separated item — an animation's `values` list — the twin of `SCRIPT_URL_ITEM` there. */
178
+ // eslint-disable-next-line no-control-regex
179
+ export const SCRIPT_URL_ITEM = /(?:^|;)[\u0000- ]*j[\t\n\r]*a[\t\n\r]*v[\t\n\r]*a[\t\n\r]*s[\t\n\r]*c[\t\n\r]*r[\t\n\r]*i[\t\n\r]*p[\t\n\r]*t[\t\n\r]*:/i;
180
+ /** A bound inline event-handler attribute runs its value as code — the twin of `INLINE_HANDLER` there. */
181
+ export const INLINE_HANDLER = /^on./i;
182
+ /**
183
+ * The character references that can spell part of a scheme, decoded — enough to give the verdict a
184
+ * browser gives on an attribute's static text, without a full entity table. Numeric references (with
185
+ * or without their `;`) and the three named ones that are scheme-relevant (`&colon;`, `&Tab;`,
186
+ * `&NewLine;`); every other named reference decodes to a character that cannot be part of
187
+ * `javascript:`, so leaving it encoded gives the same verdict.
188
+ */
189
+ /**
190
+ * The C1 numbers a parser reads as Windows-1252: `&#128;` is `€`, not U+0080. The HTML standard's table, by
191
+ * offset from 0x80; the five holes (0x81, 0x8D, 0x8F, 0x90, 0x9D) keep their own code point.
192
+ */
193
+ const C1 = [0x20ac, 0x81, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021, 0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0x8d, 0x17d, 0x8f, 0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0x9d, 0x17e, 0x178];
194
+ /**
195
+ * **A numeric reference's character, exactly as a parser decodes it** — the one decoder every reader here uses: NUL, a
196
+ * surrogate or an out-of-range value is U+FFFD, and 0x80–0x9F map through `C1`. `String.fromCodePoint` THROWS past
197
+ * U+10FFFF, so the copies that called it directly took a whole render down on `&#1114112;` in markup.
198
+ */
199
+ export const decodeCodePoint = (code) => code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) || Number.isNaN(code)
200
+ ? '\ufffd'
201
+ : code >= 0x80 && code <= 0x9f
202
+ ? String.fromCharCode(C1[code - 0x80])
203
+ : String.fromCodePoint(code);
204
+ export const decodeSchemeReferences = (text) => text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(colon|Tab|NewLine));?/g, (whole, decimal, hex, name) => decimal !== undefined || hex !== undefined
205
+ ? /** One of the two matched, so `decimal ?? hex` is a string: the `!` restates what the test proved. */
206
+ decodeCodePoint(parseInt((decimal ?? hex), decimal !== undefined ? 10 : 16))
207
+ : name === 'colon' ? ':' : name === 'Tab' ? '\t' : name === 'NewLine' ? '\n' : whole);
208
+ /**
209
+ * Where a comment opened at `open` (the index of its `<!--`) ends, as the HTML tokenizer reads it: at `-->`, at
210
+ * `--!>`, or ABRUPTLY at `<!-->` and `<!--->`. Answers the index just past it, or `-1` when it runs to the end of the
211
+ * input — one number, never an allocation, since the component scan asks it for every comment of every render.
212
+ *
213
+ * Knowing only `-->` read `<p><!-->${value}</p>` as a comment swallowing the value, which the browser renders. Every
214
+ * scanner here that meets a comment asks this one rule, and the client's scanner holds its twin.
215
+ *
216
+ * @param markup
217
+ * @param open
218
+ * @returns The index past the comment, or `-1`. The declared `number` is what makes a caller still reading the old
219
+ * `[dataEnd, end]` shape a compile error; `server-content.test.mjs` also pins every comment shape before a script.
220
+ */
221
+ export const commentEnd = (markup, open) => {
222
+ const start = open + 4;
223
+ if (markup[start] === '>')
224
+ return start + 1;
225
+ if (markup[start] === '-' && markup[start + 1] === '>')
226
+ return start + 2;
227
+ /** `indexOf` for the `--`, then the one or two characters after it: a regex here cost the component scan about 1%. */
228
+ for (let at = markup.indexOf('--', start); at !== -1; at = markup.indexOf('--', at + 1)) {
229
+ if (markup[at + 2] === '>')
230
+ return at + 3;
231
+ if (markup[at + 2] === '!' && markup[at + 3] === '>')
232
+ return at + 4;
233
+ }
234
+ return -1;
235
+ };
236
+ /**
237
+ * Where a comment's TEXT stops, given the end `commentEnd` answered: before `-->`/`--!>`, or at once when abrupt.
238
+ *
239
+ * @param markup
240
+ * @param open
241
+ * @param end
242
+ */
243
+ export const commentDataEnd = (markup, open, end) => (end - open <= 6 ? open + 4 : markup[end - 2] === '!' ? end - 4 : end - 3);
244
+ /**
245
+ * **What a thrown value says, whatever was thrown — and it never throws itself.** JavaScript can throw anything, and
246
+ * the value comes from component code: `null`, `undefined`, an object with no prototype (`String()` finds no
247
+ * `toString`), one whose `toString` or `message` getter throws, a Proxy whose every trap throws. A message built from
248
+ * `(error as Error).message` crashed on the first two, and a careless formatter crashes on the rest — either way the
249
+ * real failure was replaced by an unrelated TypeError from inside the framework. So anything that cannot be read
250
+ * becomes a fixed phrase; `Object.prototype.toString` is no fallback, since it reads `Symbol.toStringTag` through a
251
+ * Proxy's trap too.
252
+ *
253
+ * **A deliberate duplicate of `thrownMessage` in `packages/shared-utils/src/utils.ts` — fix both copies.** This package
254
+ * is compiled per file with no bundling, so it cannot import that private, unpublished package at run time;
255
+ * `tests/thrown-message-copies.test.mjs` runs one table of thrown values against both, so they cannot drift.
256
+ */
257
+ export const thrownMessage = (error) => {
258
+ try {
259
+ if (error instanceof Error)
260
+ return String(error.message);
261
+ const message = error?.message;
262
+ return typeof message === 'string' ? message : String(error);
263
+ }
264
+ catch {
265
+ return '[unprintable value thrown]';
266
+ }
267
+ };
@@ -0,0 +1,41 @@
1
+ /** A listener as the platform takes one: a function, or an object whose `handleEvent` is called. */
2
+ type ListenerCallback = ((this: unknown, event: Event) => unknown) | {
3
+ handleEvent?(event: Event): unknown;
4
+ };
5
+ /** The options bag's members this registry honors. */
6
+ type ListenerOptionsBag = {
7
+ capture?: boolean;
8
+ once?: boolean;
9
+ signal?: AbortSignal | null;
10
+ };
11
+ /** The third argument as the platform takes it: a bare `capture` flag, or the bag. */
12
+ type ListenerOptions = boolean | ListenerOptionsBag | null | undefined;
13
+ /** One registration: the callback, the phase it listens in, and whether it removes itself after one call. */
14
+ type Listener = {
15
+ callback: ListenerCallback;
16
+ capture: boolean;
17
+ once: boolean;
18
+ };
19
+ /**
20
+ * A node as dispatch walks it — any of the shim's nodes, described by what this file touches: the
21
+ * listeners it keeps here, its parent, and on a shadow root the host it is attached to.
22
+ */
23
+ type EventNode = {
24
+ _listeners?: Map<string, Listener[]>;
25
+ readonly _parent?: EventNode | null;
26
+ readonly _host?: EventNode | null;
27
+ };
28
+ /**
29
+ * The path from a node out to its furthest ancestor, crossing a shadow boundary only for an event
30
+ * declared `composed` — which is the rule that keeps a component's internals private.
31
+ */
32
+ export declare const pathFrom: (node: EventNode, composed: boolean) => EventNode[];
33
+ export declare const addListener: (node: EventNode, type: string, callback: ListenerCallback | null | undefined, options?: ListenerOptions) => void;
34
+ export declare const removeListener: (node: EventNode, type: string, callback: ListenerCallback | null | undefined, options?: ListenerOptions) => void;
35
+ /**
36
+ * `event` is `unknown` because it is checked here: anything but an `Event` is refused, as every engine refuses it.
37
+ *
38
+ * @returns false when a cancelable event was prevented, as the platform reports
39
+ */
40
+ export declare const dispatch: (node: EventNode, event: unknown) => boolean;
41
+ export {};