@verajs/ssr 0.1.4 → 0.2.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.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The custom-element registry: the definitions this process has seen.
3
+ *
4
+ * Filled as component modules execute, since `customElements.define` is how a component announces
5
+ * itself, and read by the nested-component scan to decide whether a tag in emitted markup is
6
+ * something to render or something to leave alone.
7
+ */
8
+
9
+ export const registry = new Map();
@@ -0,0 +1,234 @@
1
+ /**
2
+ * A selector matcher for the node view.
3
+ *
4
+ * **It answers, or it refuses — it never guesses.** Every query used to return `null` or an empty
5
+ * list whatever was asked, so `this.matches('[data-open]')` was `false` on an element that plainly
6
+ * had the attribute and a component branched the wrong way with nothing said. Replacing that with a
7
+ * matcher that silently mishandles `:hover` would be the same defect in a new place, so anything
8
+ * outside the grammar below throws and names itself.
9
+ *
10
+ * ## What it accepts
11
+ *
12
+ * Type, universal, class, id, every attribute operator with the `i`/`s` flag, `:not()` over one
13
+ * compound, and all four combinators — descendant, `>`, `+`, `~`.
14
+ *
15
+ * ## What it refuses, and why that is two different reasons
16
+ *
17
+ * Most refusals need something a server does not have: user state (`:hover`, `:focus`, `:checked`),
18
+ * layout (`:visible`), or a document (`:root`, `:target`).
19
+ *
20
+ * **But not all of them, and the difference used to be papered over.** `:first-child`,
21
+ * `:last-child`, `:nth-child()`, `:only-child`, `:empty`, `:first-of-type` and `:nth-of-type()` are
22
+ * pure structure — this DOM has everything needed to answer them — and they are refused too, because
23
+ * this matcher does not implement them. So are `:is()`, `:where()` and `:has()`.
24
+ *
25
+ * Saying only "a pseudo-class needs user state, layout or a document" made that sound like a
26
+ * property of servers rather than a limit of this file, and a reader following the rule would predict
27
+ * `:first-child` works. Refusing is still the right behaviour — it is loud, and a wrong answer would
28
+ * not be — but the reason has to be the true one. Implementing the structural set is a **feature**,
29
+ * not a fix, and is not being done here on the way past.
30
+ *
31
+ * `tests/ssr-selector-grammar.test.mjs` holds the boundary as a list, so a selector moving from one side
32
+ * to the other is a decision rather than a surprise.
33
+ */
34
+
35
+ /** `[name op "value" i]` — every attribute operator the platform defines. */
36
+ const ATTRIBUTE = /^\[\s*([^\s\]~^$*|=]+)\s*(?:([~^$*|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]*))\s*)?(?:([iIsS])\s*)?\]/;
37
+ const NAME = /^[*]|^[a-zA-Z][\w-]*/;
38
+ const CLASS = /^\.([\w-]+)/;
39
+ const ID = /^#([\w-]+)/;
40
+ const NOT = /^:not\(/i;
41
+
42
+ /** @param {string} selector */
43
+ const refuse = (selector, why) => {
44
+ throw new Error(
45
+ `ssr: this DOM cannot answer the selector ${JSON.stringify(selector)} — ${why}. It matches on ` +
46
+ `structure and attributes only. Rather than return a wrong answer it says so.`
47
+ );
48
+ };
49
+
50
+ /**
51
+ * One compound selector — `div.a#b[c=d]:not(.e)` — as a list of tests.
52
+ * Returns the parsed compound and how much of the string it consumed.
53
+ */
54
+ const parseCompound = (source, selector) => {
55
+ const tests = [];
56
+ let rest = source;
57
+ let consumed = 0;
58
+ /** Every branch below assigns this before it is read; `refuse` throws rather than falling through. */
59
+ let /** @type {any} */ match;
60
+ for (;;) {
61
+ if (rest === '' || /^[\s,>+~)]/.test(rest)) break;
62
+ if ((match = NAME.exec(rest))) {
63
+ const name = match[0].toLowerCase();
64
+ if (name !== '*') tests.push((element) => element.localName === name);
65
+ } else if ((match = CLASS.exec(rest))) {
66
+ const wanted = match[1];
67
+ tests.push((element) => (element.getAttribute('class') ?? '').split(/\s+/u).includes(wanted));
68
+ } else if ((match = ID.exec(rest))) {
69
+ const wanted = match[1];
70
+ tests.push((element) => element.getAttribute('id') === wanted);
71
+ } else if ((match = NOT.exec(rest))) {
72
+ const inner = parseCompound(rest.slice(match[0].length), selector);
73
+ const after = rest.slice(match[0].length + inner.consumed);
74
+ if (!after.startsWith(')')) refuse(selector, ':not() takes a single compound selector here');
75
+ tests.push((element, scope) => !inner.tests.every((test) => test(element, scope)));
76
+ match = { 0: rest.slice(0, match[0].length + inner.consumed + 1) };
77
+ } else if ((match = ATTRIBUTE.exec(rest))) {
78
+ const [, name, operator, quoted, single, bare, flag] = match;
79
+ const wanted = quoted ?? single ?? bare ?? '';
80
+ const fold = flag && flag.toLowerCase() === 'i';
81
+ tests.push((element) => {
82
+ let actual = element.getAttribute(name);
83
+ if (actual === null) return false;
84
+ if (!operator) return true;
85
+ let target = wanted;
86
+ if (fold) {
87
+ actual = actual.toLowerCase();
88
+ target = target.toLowerCase();
89
+ }
90
+ switch (operator) {
91
+ case '=':
92
+ return actual === target;
93
+ case '~=':
94
+ return target !== '' && actual.split(/\s+/u).includes(target);
95
+ case '|=':
96
+ return actual === target || actual.startsWith(`${target}-`);
97
+ case '^=':
98
+ return target !== '' && actual.startsWith(target);
99
+ case '$=':
100
+ return target !== '' && actual.endsWith(target);
101
+ case '*=':
102
+ return target !== '' && actual.includes(target);
103
+ default:
104
+ return false;
105
+ }
106
+ });
107
+ } else if (/^:scope\b/iu.test(rest)) {
108
+ /**
109
+ * **`:scope` is the element the query started from**, which is knowable here — unlike the
110
+ * pseudo-classes below it, which need user state, layout or a document. It is what makes
111
+ * `element.querySelector(':scope > b')` mean "a direct child", the usual reason to reach for
112
+ * a pseudo-class in a server render at all.
113
+ */
114
+ tests.push((element, scope) => element === scope);
115
+ match = { 0: rest.slice(0, ':scope'.length) };
116
+ } else if (rest.startsWith(':')) {
117
+ refuse(selector, 'a pseudo-class needs user state, layout or a document, and a server has none');
118
+ } else {
119
+ refuse(selector, 'it is not a selector this parser understands');
120
+ }
121
+ rest = rest.slice(match[0].length);
122
+ consumed += match[0].length;
123
+ }
124
+ if (tests.length === 0 && consumed === 0) refuse(selector, 'it is empty');
125
+ return { tests, consumed };
126
+ };
127
+
128
+ /** A full complex selector — compounds joined by combinators — parsed right to left for matching. */
129
+ const parseComplex = (selector) => {
130
+ const steps = [];
131
+ let rest = selector.trim();
132
+ let combinator = null;
133
+ for (;;) {
134
+ rest = rest.replace(/^\s+/u, '');
135
+ if (rest === '') break;
136
+ const compound = parseCompound(rest, selector);
137
+ steps.push({ tests: compound.tests, combinator });
138
+ rest = rest.slice(compound.consumed).replace(/^\s*/u, '');
139
+ if (rest === '') break;
140
+ const symbol = /^[>+~]/.exec(rest);
141
+ if (symbol) {
142
+ combinator = symbol[0];
143
+ rest = rest.slice(1);
144
+ } else {
145
+ combinator = ' ';
146
+ }
147
+ if (rest.replace(/^\s+/u, '') === '') refuse(selector, 'it ends with a combinator');
148
+ }
149
+ if (steps.length === 0) refuse(selector, 'it is empty');
150
+ return steps;
151
+ };
152
+
153
+ const cache = new Map();
154
+ const compile = (selector) => {
155
+ if (typeof selector !== 'string') selector = `${selector}`;
156
+ let compiled = cache.get(selector);
157
+ if (compiled) return compiled;
158
+ compiled = selector.split(',').map((one) => {
159
+ if (one.trim() === '') refuse(selector, 'it has an empty item in its list');
160
+ return parseComplex(one);
161
+ });
162
+ cache.set(selector, compiled);
163
+ return compiled;
164
+ };
165
+
166
+ /** **Elements only.** A selector matches elements; text and comment nodes are not candidates. */
167
+ const childrenOf = (node) =>
168
+ (node?._entries ?? []).filter((entry) => typeof entry !== 'string' && entry.openTag);
169
+ const siblingsOf = (element) => childrenOf(element._parent);
170
+
171
+ /** Match one complex selector against one element, walking its steps from right to left. */
172
+ const matchesComplex = (element, steps, scope) => {
173
+ const last = steps[steps.length - 1];
174
+ if (!last.tests.every((test) => test(element, scope))) return false;
175
+
176
+ let current = element;
177
+ for (let i = steps.length - 2; i >= 0; i--) {
178
+ const step = steps[i];
179
+ const combinator = steps[i + 1].combinator;
180
+ const passes = (candidate) => candidate && step.tests.every((test) => test(candidate, scope));
181
+ if (combinator === '>') {
182
+ current = current._parent;
183
+ if (!passes(current)) return false;
184
+ } else if (combinator === '+') {
185
+ const siblings = siblingsOf(current);
186
+ current = siblings[siblings.indexOf(current) - 1];
187
+ if (!passes(current)) return false;
188
+ } else if (combinator === '~') {
189
+ const siblings = siblingsOf(current);
190
+ const before = siblings.slice(0, siblings.indexOf(current)).reverse().find(passes);
191
+ if (!before) return false;
192
+ current = before;
193
+ } else {
194
+ let above = current._parent;
195
+ while (above && !passes(above)) above = above._parent;
196
+ if (!above) return false;
197
+ current = above;
198
+ }
199
+ }
200
+ return true;
201
+ };
202
+
203
+ /** @param {any} element @param {string} selector */
204
+ export const matches = (element, selector, scope = element) =>
205
+ compile(selector).some((steps) => matchesComplex(element, steps, scope));
206
+
207
+ /** Every descendant, in document order. */
208
+ const descendants = (node, out = []) => {
209
+ for (const child of childrenOf(node)) {
210
+ out.push(child);
211
+ descendants(child, out);
212
+ }
213
+ return out;
214
+ };
215
+
216
+ /** Every descendant element, in document order — shared with the collection queries. */
217
+ export const descendantsOf = (node) => descendants(node);
218
+
219
+ export const querySelectorAll = (node, selector) => {
220
+ const compiled = compile(selector);
221
+ return descendants(node).filter((element) => compiled.some((steps) => matchesComplex(element, steps, node)));
222
+ };
223
+
224
+ export const querySelector = (node, selector) => {
225
+ const compiled = compile(selector);
226
+ return descendants(node).find((element) => compiled.some((steps) => matchesComplex(element, steps, node))) ?? null;
227
+ };
228
+
229
+ export const closest = (element, selector) => {
230
+ const compiled = compile(selector);
231
+ for (let current = element; current; current = current._parent)
232
+ if (current.localName && compiled.some((steps) => matchesComplex(current, steps, element))) return current;
233
+ return null;
234
+ };