@verajs/ssr 0.2.1 → 0.3.1

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 +522 -390
  2. package/dist/vera/diagnostics.d.ts +20 -0
  3. package/dist/vera/diagnostics.js +102 -0
  4. package/dist/vera/escaping.d.ts +155 -0
  5. package/dist/vera/escaping.js +293 -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 +2339 -0
  14. package/dist/vera/parse.d.ts +53 -0
  15. package/dist/vera/parse.js +485 -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 +1521 -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 +553 -0
  36. package/dist/vera/types.d.ts +121 -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
package/src/vera/shim.js DELETED
@@ -1,761 +0,0 @@
1
- /**
2
- * Installs the server environment: the globals a component finds when it runs outside a browser.
3
- *
4
- * Import this **before anything that imports `@verajs/core`** — core evaluates against these, and
5
- * `@verajs/ssr` does it for you. What each global is, and why it answers the way it does, lives
6
- * with the thing it is made of: the nodes in `./nodes.js`, escaping in `./escaping.js`, the frame
7
- * queue in `./frames.js`, stylesheets in `./stylesheets.js`, the registry in `./registry.js`.
8
- *
9
- * The rule every one of them follows: **answer honestly or do not exist** — and its corollary,
10
- * **where the platform throws, this throws.** A server that is lenient about an error does not make
11
- * anything work: it moves the failure to the client, strips the context that would have explained
12
- * it, and in the meantime writes markup no browser would have produced from the same call. That
13
- * corollary has found more defects here than asking whether a member is present, because a member
14
- * that is present and too permissive looks exactly like one that is correct. A detached element has no
15
- * parent, no siblings and no box, and a browser returns exactly what these do. Where a server cannot
16
- * answer at all — `localStorage` is one browser's state — the global stays undefined, because
17
- * `typeof localStorage === 'undefined'` is the guard the ecosystem already writes and it only works
18
- * if this does not lie. `tests/ssr-dom-surface.test.mjs` enforces both halves.
19
- */
20
- import { escapeHtml, escapeStyleText, escapeRawText, RAW_TEXT_ELEMENTS } from './escaping.js';
21
- import { hoistedStyles, setRenderingTag, StyleSheetShim, hoist, beginHoisting } from './stylesheets.js';
22
- import { frames, flushFrames, flushFramesAsync } from './frames.js';
23
- import { registry } from './registry.js';
24
- import {
25
- TextShim,
26
- CommentShim,
27
- ContainerShim,
28
- FragmentShim,
29
- ShadowRootShim,
30
- ElementShim,
31
- createElement,
32
- pendingInstances,
33
- INSTANCE_ATTRIBUTE,
34
- NODE_CONSTANTS,
35
- } from './nodes.js';
36
-
37
- /** The eight hyphenated names SVG and MathML already define, which a custom element may not take. */
38
- const RESERVED_NAMES = new Set([
39
- 'annotation-xml',
40
- 'color-profile',
41
- 'font-face',
42
- 'font-face-src',
43
- 'font-face-uri',
44
- 'font-face-format',
45
- 'font-face-name',
46
- 'missing-glyph',
47
- ]);
48
-
49
- /**
50
- * Re-exported so a consumer of the server environment has one import, not seven. The homes above are
51
- * where the code lives; this is the door.
52
- */
53
- export {
54
- escapeHtml,
55
- escapeStyleText,
56
- escapeRawText,
57
- RAW_TEXT_ELEMENTS,
58
- hoistedStyles,
59
- beginHoisting,
60
- setRenderingTag,
61
- flushFrames,
62
- flushFramesAsync,
63
- registry,
64
- pendingInstances,
65
- INSTANCE_ATTRIBUTE,
66
- };
67
-
68
- /**
69
- * The three event methods, bound to a real `EventTarget`, ready to spread onto a plain-object shim.
70
- *
71
- * `document` and `window` are object literals rather than classes, so they cannot simply extend
72
- * `EventTarget` the way the containers do. They still have to *work*: both were no-ops that
73
- * reported every event delivered.
74
- *
75
- * The dispatched event's `target` is corrected to the shim, because the listener reads it and
76
- * `document` is the answer it expects — not the private object the listeners happen to live on.
77
- * An own property shadows `Event`'s prototype getter, which is read-only.
78
- *
79
- * @param {EventTarget} target
80
- * @param {() => unknown} self What the event should report as its target, resolved at dispatch
81
- * because `document` does not exist yet when this is called.
82
- */
83
- const delegateEvents = (target, self) => ({
84
- addEventListener: target.addEventListener.bind(target),
85
- removeEventListener: target.removeEventListener.bind(target),
86
- dispatchEvent: (event) => {
87
- for (const name of ['target', 'currentTarget'])
88
- Object.defineProperty(event, name, { value: self(), configurable: true });
89
- return target.dispatchEvent(event);
90
- },
91
- });
92
-
93
- /** `window` and the global scope are the same object here, so they share one target. */
94
- const windowEvents = new EventTarget();
95
-
96
- /** Idempotent. Installs the server environment; the registry is filled as modules execute. */
97
- /**
98
- * The roots a document-level query has to cover. `documentElement` and `body` are separate elements
99
- * here rather than one nested pair, so every query walks both — `documentElement` first, which is
100
- * where a real document would find anything under `<html>` before reaching `<body>`.
101
- */
102
- /**
103
- * Shared by `createTreeWalker` and `createNodeIterator`, which differ in surface rather than in what
104
- * they visit: a tree walker can also be steered with `parentNode`/`firstChild`/`nextSibling`, while
105
- * an iterator only goes forwards and backwards. Both honour `whatToShow` and a filter, and both
106
- * visit in document order — the root included for an iterator and not for a walker, which is the
107
- * one behavioural difference between them.
108
- *
109
- * @param {any} root @param {number} [whatToShow] @param {any} [filter] @param {boolean} [isWalker]
110
- */
111
- const makeWalker = (root, whatToShow = 0xffffffff, filter, isWalker = true) => {
112
- const accepts = (node) => {
113
- const bit = node.nodeType === 1 ? 1 : node.nodeType === 3 ? 4 : node.nodeType === 8 ? 128 : 0;
114
- // eslint-disable-next-line no-bitwise -- whatToShow is the platform's own NodeFilter bitmask
115
- if (!(whatToShow & bit)) return false;
116
- const verdict = typeof filter === 'function' ? filter(node) : filter?.acceptNode?.(node);
117
- return verdict === undefined || verdict === 1;
118
- };
119
- /** Document order, depth first — the order both of these are defined to visit in. */
120
- const flatten = (node, out = []) => {
121
- /** `childNodes` rather than `_entries`: it is what makes markup held as a string get parsed. */
122
- for (const child of node.childNodes ?? []) {
123
- out.push(child);
124
- flatten(child, out);
125
- }
126
- return out;
127
- };
128
- const all = () => (isWalker ? flatten(root) : [root, ...flatten(root)]).filter(accepts);
129
- let current = isWalker ? root : null;
130
- const step = (direction) => {
131
- const nodes = all();
132
- const index = current === null ? -1 : nodes.indexOf(current);
133
- const next = direction > 0 ? nodes[index + 1] : nodes[index - 1];
134
- if (!next) return null;
135
- current = next;
136
- return next;
137
- };
138
- return {
139
- root,
140
- whatToShow,
141
- filter: filter ?? null,
142
- get currentNode() {
143
- return current;
144
- },
145
- set currentNode(node) {
146
- current = node;
147
- },
148
- nextNode: () => step(1),
149
- previousNode: () => step(-1),
150
- parentNode: () => {
151
- const parent = current?._parent;
152
- if (!parent || !accepts(parent)) return null;
153
- current = parent;
154
- return parent;
155
- },
156
- firstChild: () => {
157
- const first = (current?.childNodes ?? []).find((entry) => accepts(entry));
158
- if (!first) return null;
159
- current = first;
160
- return first;
161
- },
162
- lastChild: () => {
163
- const kids = (current?.childNodes ?? []).filter((entry) => accepts(entry));
164
- if (!kids.length) return null;
165
- current = kids[kids.length - 1];
166
- return current;
167
- },
168
- nextSibling: () => {
169
- const sibling = current?.nextSibling;
170
- if (!sibling || !accepts(sibling)) return null;
171
- current = sibling;
172
- return sibling;
173
- },
174
- previousSibling: () => {
175
- const sibling = current?.previousSibling;
176
- if (!sibling || !accepts(sibling)) return null;
177
- current = sibling;
178
- return sibling;
179
- },
180
- };
181
- };
182
-
183
- const documentRoots = () =>
184
- /** @type {Array<any>} */ ([globalThis.document.documentElement, globalThis.document.body]);
185
-
186
- /**
187
- * Which parts of a URL `location` carries — the one place that knows.
188
- *
189
- * `index.js` kept its own copy for `applyLocation`/`restoreLocation` to walk. They agreed, and
190
- * nothing made them: a part added to one list would be installed and never restored, or restored
191
- * from a property the install never wrote. Same single fact, same reasoning as `RAW_TEXT_ELEMENTS`
192
- * below it — CODE-PRINCIPLES #5.
193
- */
194
- export const LOCATION_PARTS = ['href', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash', 'origin'];
195
-
196
- export const installShims = () => {
197
- if (globalThis.__veraSsrShimmed) return registry;
198
- globalThis.__veraSsrShimmed = true;
199
-
200
- /**
201
- * Every assignment here is a deliberate lie: a shim is not an `HTMLElement`, and saying so is the
202
- * point — elements hold strings, not trees. The casts mark each one as intended rather than
203
- * missed, which is what type-checking this package is for. Anything a component genuinely reaches
204
- * for is on `ElementShim`; anything else was never going to work server-side anyway.
205
- */
206
- globalThis.HTMLElement = /** @type {any} */ (ElementShim);
207
- globalThis.CSSStyleSheet = /** @type {any} */ (StyleSheetShim);
208
- /**
209
- * The DOM interfaces, so `instanceof` answers correctly.
210
- *
211
- * `value instanceof Node` is how ordinary code tells a node from a string — the renderer's own
212
- * text-vs-node decision is that test — and `Node` being undefined made it a `ReferenceError`
213
- * rather than `false`. These are the real shim classes, so an element made here *is* a `Node`,
214
- * an `Element` and an `HTMLElement`, exactly as it would be in a browser.
215
- */
216
- globalThis.Node = /** @type {any} */ (ContainerShim);
217
- globalThis.Element = /** @type {any} */ (ElementShim);
218
- globalThis.ShadowRoot = /** @type {any} */ (ShadowRootShim);
219
- /**
220
- * `Document` exists so that **feature detection** can read it.
221
- *
222
- * The standard constructed-stylesheet probe is
223
- * `ShadowRoot && 'adoptedStyleSheets' in Document.prototype && 'replace' in CSSStyleSheet.prototype`
224
- * — lit's, and everyone else's. Defining `ShadowRoot` without `Document` moved that probe from
225
- * "no shadow DOM at all" to "shadow DOM, now read `Document.prototype`", which threw. Every
226
- * clause is true of this environment, so all three are answerable and the probe takes the branch
227
- * this shim actually supports.
228
- *
229
- * The document is a literal rather than a class — it has one instance and no subclasses — so it
230
- * is given this prototype rather than built from it.
231
- */
232
- globalThis.Document = /** @type {any} */ (class Document {});
233
- Object.defineProperty(globalThis.Document.prototype, 'adoptedStyleSheets', { value: [], writable: true });
234
- globalThis.DocumentFragment = /** @type {any} */ (FragmentShim);
235
- /** `new Image()` is a spelling of `createElement('img')`, and `Audio` of `createElement('audio')`. */
236
- globalThis.Image = /** @type {any} */ (class Image extends ElementShim {
237
- constructor() {
238
- super('img');
239
- }
240
- });
241
- globalThis.Audio = /** @type {any} */ (class Audio extends ElementShim {
242
- constructor() {
243
- super('audio');
244
- }
245
- });
246
-
247
- /**
248
- * The observers, inert.
249
- *
250
- * Every one of them observes something a server does not have — a viewport, a box, a live tree —
251
- * so none can ever fire here. What matters is that constructing one does not throw: a component
252
- * that lazy-loads on intersection, or watches its own size, is written for a browser and must
253
- * still *render* on a server. `@verajs/autoloader` builds a `MutationObserver`, which made an app
254
- * entry that wires it unrenderable.
255
- */
256
- for (const name of ['IntersectionObserver', 'ResizeObserver', 'MutationObserver', 'PerformanceObserver'])
257
- globalThis[name] = /** @type {any} */ (class Observer {
258
- observe() {}
259
- unobserve() {}
260
- disconnect() {}
261
- takeRecords() {
262
- return [];
263
- }
264
- });
265
-
266
- /**
267
- * A media query with no viewport to match matches nothing, which is what every server renderer
268
- * answers and what hydration then corrects. Absent, it was a `TypeError` in `connectedCallback`.
269
- */
270
- globalThis.matchMedia = /** @type {any} */ (
271
- (media) => ({
272
- media,
273
- matches: false,
274
- addEventListener: () => {},
275
- removeEventListener: () => {},
276
- addListener: () => {},
277
- removeListener: () => {},
278
- dispatchEvent: () => true,
279
- onchange: null,
280
- })
281
- );
282
-
283
- /** No layout means no computed value; a browser gives a detached element nothing useful either. */
284
- globalThis.getComputedStyle = /** @type {any} */ (
285
- () => ({
286
- getPropertyValue: () => '',
287
- getPropertyPriority: () => '',
288
- length: 0,
289
- item: () => '',
290
- })
291
- );
292
- globalThis.getSelection = () => null;
293
-
294
- /**
295
- * Idle time joins the frame queue rather than inventing a second one — the render is over when
296
- * `flushFrames` runs out, and work deferred to "when the browser is free" has to land before
297
- * then or it lands nowhere.
298
- */
299
- globalThis.requestIdleCallback = /** @type {any} */ (
300
- (fn) => frames.push(() => fn({ didTimeout: false, timeRemaining: () => 0 }))
301
- );
302
- globalThis.cancelIdleCallback = /** @type {any} */ ((id) => {
303
- frames[id - 1] = null;
304
- });
305
- /** Defined so core's `@scope` support check passes — SSR output gets scoped light-DOM CSS. */
306
- globalThis.CSSScopeRule = /** @type {any} */ (function CSSScopeRule() {});
307
-
308
- globalThis.customElements = /** @type {any} */ ({
309
- /**
310
- * Refused on a second definition, exactly as the platform does. The registry used to overwrite
311
- * silently, so a module defining a tag twice rendered fine on the server and threw
312
- * `NotSupportedError` in the browser — the server being lenient about an error is the server
313
- * hiding it.
314
- */
315
- define: (name, Class) => {
316
- /**
317
- * **A name the browser will refuse is refused here too**, or the server renders markup the
318
- * client can never upgrade: `customElements.define('nodash', …)` throws `SyntaxError` in every
319
- * engine, and this accepted it — so the component rendered server-side, shipped, and the
320
- * client threw on the very line that was supposed to bring it to life.
321
- *
322
- * The rule is the spec's: starts with a lowercase ASCII letter, contains a hyphen, contains no
323
- * uppercase, and is not one of the eight names SVG and MathML already use.
324
- */
325
- if (typeof name !== 'string' || !/^[a-z][^A-Z]*-[^A-Z]*$/.test(name) || RESERVED_NAMES.has(name))
326
- throw new DOMException(
327
- `Failed to execute 'define' on 'CustomElementRegistry': "${String(name)}" is not a valid custom element name`,
328
- 'SyntaxError'
329
- );
330
- if (registry.has(name)) {
331
- throw new DOMException(
332
- `Failed to execute 'define' on 'CustomElementRegistry': the name "${name}" has already been used with this registry`,
333
- 'NotSupportedError'
334
- );
335
- }
336
- registry.set(name, Class);
337
- },
338
- get: (name) => registry.get(name),
339
- whenDefined: () => Promise.resolve(),
340
- });
341
-
342
- /**
343
- * The document, with the surface a component reaches for.
344
- *
345
- * `body`, `documentElement` and `title` are real enough to be written to — a component setting
346
- * `document.title` or appending to `document.body` is ordinary code, and losing the assignment
347
- * silently is the failure mode this package keeps producing. Queries answer emptily for the same
348
- * reason the containers do: this holds strings, not a tree.
349
- */
350
- globalThis.document = /** @type {any} */ ({
351
- title: '',
352
- body: new ElementShim('body'),
353
- documentElement: new ElementShim('html'),
354
- /**
355
- * **`body` is what a browser reports when nothing has focus**, and it never answers `null` for a
356
- * document that exists. `null` here meant `document.activeElement.tagName` — ordinary code —
357
- * threw on the server and worked in the browser.
358
- */
359
- get activeElement() {
360
- return globalThis.document.body;
361
- },
362
- /**
363
- * This document *has* a `documentElement`, so saying it has no children contradicted itself —
364
- * the same shape as `document.contains` answering `false` while every element reported
365
- * `isConnected`. One element, first and last, exactly as a real document reports.
366
- */
367
- get firstElementChild() {
368
- return globalThis.document.documentElement;
369
- },
370
- get lastElementChild() {
371
- return globalThis.document.documentElement;
372
- },
373
- get childElementCount() {
374
- return 1;
375
- },
376
- createElement: (localName) => createElement(localName),
377
- createElementNS: (namespace, localName) => createElement(localName, namespace),
378
- createTextNode: (text) => new TextShim(text),
379
- createDocumentFragment: () => new FragmentShim(),
380
- /**
381
- * **The document's queries search the document.** Each answered nothing whatever it was asked,
382
- * because there was no tree to search; `document.getElementById('x')` was `null` for an element
383
- * that had been appended to `body` moments earlier.
384
- *
385
- * `documentElement` and `body` are separate roots here rather than one nested pair, so each
386
- * query covers both — the order is `documentElement` first, which is where a real document would
387
- * have found anything under `<html>` before reaching `<body>`.
388
- */
389
- querySelector: (selector) => {
390
- for (const root of documentRoots()) {
391
- const found = root.querySelector(selector);
392
- if (found) return found;
393
- }
394
- return null;
395
- },
396
- querySelectorAll: (selector) => documentRoots().flatMap((root) => root.querySelectorAll(selector)),
397
- getElementById: (id) => {
398
- for (const root of documentRoots()) {
399
- const found = root.getElementById(id);
400
- if (found) return found;
401
- }
402
- return null;
403
- },
404
- ...NODE_CONSTANTS,
405
- getElementsByTagName: (name) => documentRoots().flatMap((root) => root.getElementsByTagName(name)),
406
- getElementsByTagNameNS: (namespace, name) =>
407
- documentRoots().flatMap((root) => root.getElementsByTagNameNS(namespace, name)),
408
- getElementsByClassName: (names) => documentRoots().flatMap((root) => root.getElementsByClassName(names)),
409
- getElementsByName: (name) =>
410
- globalThis.document.querySelectorAll(`[name="${`${name}`.replace(/"/gu, '\\"')}"]`),
411
- /**
412
- * **`complete`, because nothing more is coming.** `loading` is the truthful description of a
413
- * document still being assembled, and it is the wrong answer to give a component: the guard
414
- * everyone writes is `if (readyState === 'loading') addEventListener('DOMContentLoaded', boot)`,
415
- * and this DOM never fires that event — so `loading` meant the callback was registered and never
416
- * ran, and the component silently rendered nothing. `@verajs/jsx/standalone` is written exactly
417
- * that way. `complete` sends the same code down the branch that runs `boot()` now, which is what
418
- * the browser ends up doing too.
419
- */
420
- readyState: 'complete',
421
- visibilityState: 'visible',
422
- hidden: false,
423
- characterSet: 'UTF-8',
424
- inputEncoding: 'UTF-8',
425
- charset: 'UTF-8',
426
- contentType: 'text/html',
427
- compatMode: 'CSS1Compat',
428
- dir: '',
429
- designMode: 'off',
430
- nodeType: 9,
431
- nodeName: '#document',
432
- currentScript: null,
433
- /**
434
- * **`documentElement`, because this document declares standards mode.** `null` is the answer a
435
- * *quirks-mode* document gives, so returning it beside `compatMode: 'CSS1Compat'` two lines up
436
- * was a document contradicting itself — and a component reading
437
- * `document.scrollingElement.scrollTop`, which every engine allows, crashed on the server with
438
- * a `TypeError` and worked in the browser. Measured on Chromium, Firefox and WebKit: all three
439
- * answer `documentElement`.
440
- */
441
- get scrollingElement() {
442
- return globalThis.document.documentElement;
443
- },
444
- fullscreenElement: null,
445
- pointerLockElement: null,
446
- pictureInPictureElement: null,
447
- /**
448
- * The output is an HTML document, so it has a doctype. A browser reports these three fields and
449
- * an empty public and system id, which is exactly what `<!doctype html>` means.
450
- */
451
- doctype: { name: 'html', publicId: '', systemId: '' },
452
- children: [],
453
- childNodes: [],
454
- styleSheets: [],
455
- forms: [],
456
- images: [],
457
- links: [],
458
- scripts: [],
459
- embeds: [],
460
- plugins: [],
461
- anchors: [],
462
- hasFocus: () => false,
463
- createComment: (text) => new CommentShim(text),
464
- getSelection: () => null,
465
- /**
466
- * An empty walk over an empty tree, which is the truthful answer for a DOM that holds strings.
467
- *
468
- * `@verajs/renderer` builds two shared `TreeWalker`s **at import time**, so importing it threw
469
- * here — and a component doing nothing unusual imports it: `keyed` and `hold` are exported from
470
- * that entry, and a keyed list is the renderer's headline feature. Any component using either
471
- * could not be server-rendered at all. Nothing walks this DOM (`@verajs/ssr` has its own
472
- * renderer and never uses these), so an inert walker is the whole requirement.
473
- */
474
- /**
475
- * **The walkers walk.** Both existed and answered `null` to everything, whatever the tree held —
476
- * a stub that reported "no more nodes" from the first call, so a component walking its own
477
- * subtree found it empty and did nothing, on the server only. There is a tree to walk now.
478
- */
479
- createTreeWalker: (root, whatToShow, filter) => makeWalker(root, whatToShow, filter, true),
480
- createNodeIterator: (root, whatToShow, filter) => makeWalker(root, whatToShow, filter, false),
481
- elementFromPoint: () => null,
482
- elementsFromPoint: () => [],
483
- /**
484
- * Everything this DOM builds is in the document — the shim sets `isConnected` on every element
485
- * for the same reason, since a server render is exactly the case where the tree *is* live. A
486
- * flat `false` contradicted that, and `if (!document.contains(el)) return;` is ordinary
487
- * defensive code that bailed out of a render that was in fact perfectly connected.
488
- */
489
- contains: (node) => node?.isConnected === true,
490
- /**
491
- * `importNode` CLONES — the spec's "import" is a copy into this document, never the node
492
- * itself. The identity it used to return was a lie with teeth: a caller mutates the "copy"
493
- * and corrupts the original (for the renderer's Instance, the template's canonical content —
494
- * every later render of that template starts from the corrupted tree). Element, text and
495
- * comment shims clone for real; a kind without `cloneNode` (a fragment) refuses loudly, which
496
- * is this DOM's posture — decline what cannot be reproduced, never hand back an alias.
497
- * `adoptNode` stays the identity: adopting MOVES a node and nothing here owns another
498
- * document, so the node itself is the correct answer there.
499
- */
500
- importNode: (node, deep) => node.cloneNode(deep === true),
501
- adoptNode: (node) => node,
502
- get defaultView() {
503
- return globalThis.window;
504
- },
505
- get URL() {
506
- return globalThis.location?.href ?? '';
507
- },
508
- get documentURI() {
509
- return globalThis.location?.href ?? '';
510
- },
511
- get baseURI() {
512
- return globalThis.location?.href ?? '';
513
- },
514
- get referrer() {
515
- return '';
516
- },
517
- /**
518
- * Real listeners here too, delegated to an `EventTarget` of the document's own. A component
519
- * that listens on `document` and dispatches there — a store broadcasting, a dialog closing on
520
- * `keydown` it fires itself — behaved one way in a browser and not at all here.
521
- */
522
- ...delegateEvents(new EventTarget(), () => globalThis.document),
523
- /** Light-DOM styles hoist here — `adoptStyles`' constructed-sheet path. */
524
- get adoptedStyleSheets() {
525
- return [];
526
- },
527
- set adoptedStyleSheets(sheets) {
528
- const added = sheets[sheets.length - 1];
529
- if (added?.cssText) hoist(added.cssText);
530
- },
531
- head: {
532
- appendChild: (node) => {
533
- if (node?.innerHTML) hoist(node.innerHTML);
534
- return node;
535
- },
536
- },
537
- });
538
- /** Given `Document.prototype` here, where the document it describes finally exists. */
539
- Object.setPrototypeOf(globalThis.document, globalThis.Document.prototype);
540
-
541
- /**
542
- * Enough `window` for `@verajs/router` to initialise.
543
- *
544
- * Without it, a component calling `initRouter` threw `window is not defined` and could not be
545
- * server-rendered at all — which rules out the app shell of every routed app, the exact thing
546
- * server rendering is for. The router is careful to be *importable* in Node and says so; nothing
547
- * made it *runnable*.
548
- *
549
- * Listeners are real — a component that dispatches a window event and listens for it, which is
550
- * how loosely coupled components talk to each other, used to be talking into a no-op. Nothing on
551
- * a server *navigates*, so `popstate` and friends still never arrive on their own. `location`
552
- * describes the page being rendered, so a route resolves against a real path; set
553
- * `globalThis.location.pathname` before `renderToString` to render a route other than `/`.
554
- * `history` is inert: a server has no session history to push onto. A **per-request** URL belongs
555
- * in `renderToString`'s `location` option, which applies it after every await and restores it
556
- * afterwards; assigning to this global directly is safe only until two requests overlap.
557
- */
558
- globalThis.window = /** @type {any} */ (globalThis);
559
- /**
560
- * `self` is the other name for the global, and UMD bundles feature-detect on it. `window` is
561
- * already defined here, so those bundles have taken the browser branch regardless — leaving `self`
562
- * undefined only made the two disagree.
563
- *
564
- * **`??=`, because a Web Worker already has one and it is read-only.** Assigning threw
565
- * `Cannot set property self of #<WorkerGlobalScope> which has only a getter`, which is where this
566
- * shim stopped when it was first run off the main thread. Nothing is lost by skipping it there:
567
- * in a worker `self` already *is* the global, which is exactly what this line wanted. Node
568
- * defines no `self` on the main thread or inside `worker_threads`, so the server still assigns.
569
- */
570
- globalThis.self ??= /** @type {any} */ (globalThis);
571
- /**
572
- * Every part, built from a real `URL`, so the default is as complete as the one `renderToString`'s
573
- * `location` option installs. It used to carry four properties — `pathname`, `search`, `hash`,
574
- * `href` — so `location.origin`, `.protocol`, `.host` and `.hostname` read `undefined` until a
575
- * render supplied a URL, and then started working. Two different shapes for the same object
576
- * depending on when you looked at it.
577
- */
578
- /**
579
- * **Installed as an own, writable property rather than assigned, because `applyLocation` mutates
580
- * it and not every environment's `location` can be mutated.** `renderToString`'s `location` option
581
- * writes each part in place, which a plain object takes and a Web Worker's real `WorkerLocation`
582
- * refuses — every property is a getter, so a per-request URL threw
583
- * `Cannot set property href of [object WorkerLocation]`. `??=` could not see that: a worker *has*
584
- * a location, so it short-circuited and left the read-only one in place. Rendering one route per
585
- * URL is the whole point of the option, so this is the difference between the option working and
586
- * not.
587
- *
588
- * Seeded from whatever the environment describes, so a worker keeps its real URL as the default
589
- * instead of being told it is localhost. Node has no `location` at all, on the main thread or in
590
- * `worker_threads`, so the server gets the identical localhost object it got before — a writable,
591
- * configurable own property is what a plain assignment already produced.
592
- */
593
- Object.defineProperty(globalThis, 'location', {
594
- value: /** @type {any} */ (
595
- (() => {
596
- const url = new URL(globalThis.location?.href ?? 'http://localhost/');
597
- return Object.fromEntries(LOCATION_PARTS.map((part) => [part, url[part]]));
598
- })()
599
- ),
600
- writable: true,
601
- configurable: true,
602
- });
603
- globalThis.history = /** @type {any} */ ({
604
- scrollRestoration: 'auto',
605
- pushState: () => {},
606
- replaceState: () => {},
607
- go: () => {},
608
- back: () => {},
609
- forward: () => {},
610
- });
611
- Object.assign(globalThis, delegateEvents(windowEvents, () => globalThis.window));
612
- /**
613
- * **A server render is a top-level, unframed, open window — and saying nothing says otherwise.**
614
- *
615
- * This is the one place where *absence* gives the wrong answer rather than no answer.
616
- * `window.top === window` is how a page asks "am I in an iframe"; with `top` undefined that
617
- * comparison is **false**, so a component concludes it *is* framed and takes the branch meant for
618
- * a page it does not control. Every value here is what a browser reports for a page that is not
619
- * framed, which is exactly the situation a server render is in.
620
- */
621
- globalThis.top = /** @type {any} */ (globalThis);
622
- globalThis.parent = /** @type {any} */ (globalThis);
623
- globalThis.frames = /** @type {any} */ (globalThis);
624
- globalThis.frameElement = null;
625
- globalThis.opener = null;
626
- globalThis.length = 0;
627
- globalThis.closed = false;
628
- /** `name` is `Window`'s, not `globalThis`'s, so TypeScript needs telling which one this is. */
629
- /** @type {any} */ (globalThis).name ??= '';
630
-
631
- /**
632
- * Derived from `location` rather than stored, so the two cannot disagree — `renderToString`'s
633
- * `location` option rewrites the URL per request, and a copied-at-install `origin` would answer
634
- * for whichever request installed the shim.
635
- */
636
- Object.defineProperty(globalThis, 'origin', {
637
- get: () => globalThis.location?.origin ?? '',
638
- configurable: true,
639
- });
640
-
641
- /**
642
- * **Inert, because a server has no user and no window to move** — the same reason the observers
643
- * are inert and `scrollTo` already was. A browser does not throw for any of these, so neither can
644
- * this: a component that calls one during setup would work in the browser and crash here, which
645
- * is the divergence this package exists to remove.
646
- *
647
- * The ones with a return value get the answer a browser gives when the thing did not happen —
648
- * `confirm` when the user declines, `prompt` when they cancel, `open` when the browser refuses,
649
- * `find` when there is no match. None of those is invented; each is a real outcome of the call.
650
- */
651
- for (const name of [
652
- 'alert', 'print', 'blur', 'focus', 'close', 'stop', 'scroll', 'scrollBy', 'scrollTo',
653
- 'moveBy', 'moveTo', 'resizeBy', 'resizeTo', 'captureEvents', 'releaseEvents',
654
- ])
655
- globalThis[name] = () => {};
656
- /**
657
- * **`postMessage` is `??=` and the rest are not, because in a Web Worker it is the only channel
658
- * back to the page.** Replacing it with a no-op does not throw and does not stop the render — it
659
- * silently severs the host's reporting, so a worker that rendered perfectly looks exactly like one
660
- * that crashed. That cost two debugging rounds the first time this shim ran off the main thread.
661
- *
662
- * **`close` deliberately stays unconditional**, which is the same reasoning arriving at the
663
- * opposite answer: in a worker `close()` *terminates* it, so a component calling `window.close()`
664
- * during setup would kill the render. A no-op is both what a browser does for a page it did not
665
- * open and what protects the render; a host still terminates its worker from the outside.
666
- *
667
- * Node defines neither name — on the main thread or inside `worker_threads` — so the server
668
- * assigns both exactly as before.
669
- */
670
- globalThis.postMessage ??= /** @type {any} */ (() => {});
671
- globalThis.confirm = () => false;
672
- globalThis.prompt = () => null;
673
- globalThis.find = () => false;
674
- globalThis.open = () => null;
675
-
676
- /**
677
- * `reportError` hands an error to the page's error handling. A no-op would **swallow** it, which
678
- * is the one outcome worse than not having the function — so it goes where every other unhandled
679
- * failure in this package goes.
680
- */
681
- globalThis.reportError ??= (error) => console.error(error);
682
-
683
- /**
684
- * The `NodeFilter` constants, because `createTreeWalker` is provided and these are what it takes.
685
- * `@verajs/renderer` passes the numbers directly, so nothing here needs them — but a component
686
- * writing `NodeFilter.SHOW_ELEMENT` is writing ordinary DOM code, and these are facts rather than
687
- * answers this DOM has to invent.
688
- */
689
- globalThis.NodeFilter = /** @type {any} */ (
690
- Object.assign(function NodeFilter() {
691
- throw new TypeError('Illegal constructor');
692
- }, {
693
- FILTER_ACCEPT: 1,
694
- FILTER_REJECT: 2,
695
- FILTER_SKIP: 3,
696
- SHOW_ALL: 0xffffffff,
697
- SHOW_ELEMENT: 1,
698
- SHOW_ATTRIBUTE: 2,
699
- SHOW_TEXT: 4,
700
- SHOW_CDATA_SECTION: 8,
701
- SHOW_ENTITY_REFERENCE: 16,
702
- SHOW_ENTITY: 32,
703
- SHOW_PROCESSING_INSTRUCTION: 64,
704
- SHOW_COMMENT: 128,
705
- SHOW_DOCUMENT: 256,
706
- SHOW_DOCUMENT_TYPE: 512,
707
- SHOW_DOCUMENT_FRAGMENT: 1024,
708
- SHOW_NOTATION: 2048,
709
- })
710
- );
711
- Object.freeze(globalThis.NodeFilter);
712
- /**
713
- * Node supplies `Event` and `CustomEvent`; this fills in only where it does not, and matches the
714
- * shape `EventTarget` dispatches.
715
- */
716
- globalThis.CustomEvent ??= /** @type {any} */ (
717
- class CustomEvent extends Event {
718
- constructor(type, init = {}) {
719
- super(type, init);
720
- this.detail = init.detail ?? null;
721
- }
722
- }
723
- );
724
- /**
725
- * **The phase constants belong on the prototype, not only on the interface.** Node puts
726
- * `CAPTURING_PHASE` and friends on `Event` alone; all three engines put them on `Event.prototype`
727
- * too, so `event.AT_TARGET` reads `2` in a browser and `undefined` here. That matters because
728
- * `event.eventPhase === event.AT_TARGET` is how the comparison is normally written, and against
729
- * `undefined` it is `false` for every phase — the test silently never matches instead of failing.
730
- */
731
- for (const [name, value] of [['NONE', 0], ['CAPTURING_PHASE', 1], ['AT_TARGET', 2], ['BUBBLING_PHASE', 3]])
732
- if (!(name in Event.prototype))
733
- Object.defineProperty(Event.prototype, name, { value, enumerable: false, configurable: true });
734
-
735
-
736
- /**
737
- * Frames are queued and drained once the component's `connectedCallback` has returned — see
738
- * `flushFrames`.
739
- *
740
- * This deferred to `setTimeout`, which ran every scheduled callback long after the response was
741
- * built. Core's render scheduler is `requestAnimationFrame`, so any state a component settled
742
- * after its first `render()` — the ordinary `render(); this.state.x = fromAttribute` shape —
743
- * was dropped, and every `useEffect` was too. Both landed on the client instead, so the server
744
- * shipped one page and the browser immediately replaced it with a different one.
745
- *
746
- * Shimmed rather than left undefined so that unguarded callers — `@verajs/router`'s initial
747
- * navigation, any third-party component measuring itself — run instead of throwing.
748
- */
749
- /** A browser raises `TypeError` for a non-callable, and a silent no-op here is a frame that never runs. */
750
- globalThis.requestAnimationFrame = (fn) => {
751
- if (typeof fn !== 'function')
752
- throw new TypeError(
753
- `Failed to execute 'requestAnimationFrame' on 'Window': parameter 1 is not of type 'Function'.`
754
- );
755
- return frames.push(fn);
756
- };
757
- globalThis.cancelAnimationFrame = (id) => {
758
- frames[id - 1] = null;
759
- };
760
- return registry;
761
- };