@verajs/ssr 0.2.0 → 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.
- package/README.md +510 -373
- package/dist/vera/diagnostics.d.ts +20 -0
- package/dist/vera/diagnostics.js +98 -0
- package/dist/vera/escaping.d.ts +142 -0
- package/dist/vera/escaping.js +267 -0
- package/dist/vera/events.d.ts +41 -0
- package/dist/vera/events.js +162 -0
- package/dist/vera/frames.d.ts +38 -0
- package/dist/vera/frames.js +195 -0
- package/dist/vera/index.d.ts +48 -0
- package/dist/vera/index.js +480 -0
- package/{types → dist/vera}/nodes.d.ts +397 -300
- package/dist/vera/nodes.js +2322 -0
- package/dist/vera/parse.d.ts +37 -0
- package/dist/vera/parse.js +390 -0
- package/dist/vera/reflections.d.ts +566 -0
- package/dist/vera/reflections.js +820 -0
- package/dist/vera/registry.d.ts +14 -0
- package/{src → dist}/vera/registry.js +5 -1
- package/dist/vera/report.d.ts +27 -0
- package/dist/vera/report.js +56 -0
- package/dist/vera/scan.d.ts +37 -0
- package/dist/vera/scan.js +143 -0
- package/dist/vera/select.d.ts +40 -0
- package/dist/vera/select.js +261 -0
- package/dist/vera/serializer.d.ts +39 -0
- package/dist/vera/serializer.js +1372 -0
- package/dist/vera/shim.d.ts +42 -0
- package/dist/vera/shim.js +853 -0
- package/dist/vera/slots.d.ts +5 -0
- package/dist/vera/slots.js +104 -0
- package/dist/vera/stylesheets.d.ts +62 -0
- package/dist/vera/stylesheets.js +180 -0
- package/dist/vera/tokenizer.d.ts +32 -0
- package/dist/vera/tokenizer.js +528 -0
- package/dist/vera/types.d.ts +117 -0
- package/dist/vera/views.d.ts +63 -0
- package/dist/vera/views.js +245 -0
- package/package.json +12 -13
- package/src/vera/escaping.js +0 -135
- package/src/vera/events.js +0 -164
- package/src/vera/frames.js +0 -102
- package/src/vera/index.js +0 -1171
- package/src/vera/nodes.js +0 -2270
- package/src/vera/parse.js +0 -381
- package/src/vera/reflections.js +0 -811
- package/src/vera/select.js +0 -234
- package/src/vera/serializer.js +0 -928
- package/src/vera/shim.js +0 -761
- package/src/vera/stylesheets.js +0 -155
- package/src/vera/views.js +0 -240
- package/types/escaping.d.ts +0 -27
- package/types/events.d.ts +0 -4
- package/types/frames.d.ts +0 -12
- package/types/index.d.ts +0 -13
- package/types/parse.d.ts +0 -19
- package/types/reflections.d.ts +0 -657
- package/types/registry.d.ts +0 -8
- package/types/select.d.ts +0 -5
- package/types/serializer.d.ts +0 -26
- package/types/shim.d.ts +0 -23
- package/types/stylesheets.d.ts +0 -53
- package/types/views.d.ts +0 -26
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vera-native SSR. Node resolves the module graph (`import()`), execution registers component classes
|
|
3
|
+
* (through `customElements.define`, which the shim owns), templates flatten through the sigil-aware
|
|
4
|
+
* serializer, and nested components are found by scanning the markup just written for tags the registry
|
|
5
|
+
* knows (`scan.js`) — never by parsing HTML. Client takeover is `hydration` (`@verajs/renderer/hydration`, wired beside
|
|
6
|
+
* the renderer), which adopts this markup in place, markerless but for light slots' region comments.
|
|
7
|
+
*
|
|
8
|
+
* Import THIS module first — before anything that imports `@verajs/renderer`, which needs the shims at
|
|
9
|
+
* import time.
|
|
10
|
+
*
|
|
11
|
+
* **One render at a time** (`takeTurn`): the per-render state below is module-level, so renders are
|
|
12
|
+
* queued rather than interleaved — synchronous and asynchronous alike. Everything a render touches that
|
|
13
|
+
* outlives it (the location, the document title, static mode) is applied inside that render's turn and
|
|
14
|
+
* restored in one `finally`, so no request can see another's.
|
|
15
|
+
*/
|
|
16
|
+
import { installShims, registry, hoistedStyles, escapeHtml, escapeStyleText, setRenderingTag, beginHoisting, flushFrames, flushFramesAsync, setCoreFlush, beginBudget, bounded, endBudget, pendingDefinitionNames, resetPendingDefinitions, pendingInstances, INSTANCE_ATTRIBUTE, LOCATION_PARTS, } from './shim.js';
|
|
17
|
+
import { serializeTemplate, serializeValue } from './serializer.js';
|
|
18
|
+
import { decode as decodeEntities } from './parse.js';
|
|
19
|
+
import { ATTRIBUTE, renderComponentTags } from './scan.js';
|
|
20
|
+
import { distributeLight } from './slots.js';
|
|
21
|
+
import { thrownMessage } from './escaping.js';
|
|
22
|
+
import { PROSE } from './diagnostics.js';
|
|
23
|
+
import { isOwn, once, own, quoted, ssrMisuse, ssrWarning } from './report.js';
|
|
24
|
+
installShims();
|
|
25
|
+
const { wire, inserts, flush } = await import('@verajs/core');
|
|
26
|
+
setCoreFlush(flush);
|
|
27
|
+
/** Core's server-render turn: what a render creates leaves every store when its turn ends. */
|
|
28
|
+
const serverTurnOf = inserts.$ss;
|
|
29
|
+
/**
|
|
30
|
+
* A server's DOCUMENT: modules that would touch a client's lifecycle (`@verajs/renderer/native-elements`) stand aside for
|
|
31
|
+
* its elements (`_$srv$`) — on the document, never the registry, so a process that also renders on a client DOM (a
|
|
32
|
+
* hydration test, a dev server) keeps its client elements' lifecycle.
|
|
33
|
+
*/
|
|
34
|
+
globalThis.document._$srv$ = true;
|
|
35
|
+
/** `static styles` are part of what a browser renders, so the server adopts them unconditionally. */
|
|
36
|
+
const { styles } = await import('@verajs/styles');
|
|
37
|
+
wire([styles]);
|
|
38
|
+
/* ── one render's state ──────────────────────────────────────────────────────────────────────── */
|
|
39
|
+
/** The tags this render touched — only their hoisted styles reach its page. */
|
|
40
|
+
const renderedTags = new Set();
|
|
41
|
+
/** The components whose wait the render's `timeout` cut — named by the warning, which otherwise named only the page. */
|
|
42
|
+
const timedOut = new Set();
|
|
43
|
+
/**
|
|
44
|
+
* **Every failure during a render, from every channel** — a hook (core's `'error'` insert), a frame
|
|
45
|
+
* callback, a `'settle'` handler. Collected rather than swallowed: on a server there is no next render
|
|
46
|
+
* to recover in, and serializing a component whose render threw ships it EMPTY into a 200. Thrown once
|
|
47
|
+
* the walk is over, naming every component that failed. The `'error'` insert is registered at priority
|
|
48
|
+
* 10 so an app's own reporter, at the default 50, is kept beside it.
|
|
49
|
+
*/
|
|
50
|
+
const failures = [];
|
|
51
|
+
const failed = (tag) => (error) => failures.push({ error, tag });
|
|
52
|
+
wire({ on: 'error', fn: (error, element) => failed(element?.localName)(error), priority: 10 });
|
|
53
|
+
/* ── the server renderer ─────────────────────────────────────────────────────────────────────── */
|
|
54
|
+
/**
|
|
55
|
+
* What this renderer last wrote into a container, and what sat in front of it. **`render()` owns its own
|
|
56
|
+
* range** on the client, and that holds over time: content already in the container stays before it, a
|
|
57
|
+
* node appended afterwards stays after it, across every re-render. The string form of a range is the text
|
|
58
|
+
* either side of it.
|
|
59
|
+
*/
|
|
60
|
+
const written = new WeakMap();
|
|
61
|
+
/**
|
|
62
|
+
* A template in, its markup into the container. Anything that is not a template flattens exactly as a
|
|
63
|
+
* child value does — so a returned string is escaped text, as it is on the client.
|
|
64
|
+
*/
|
|
65
|
+
const serverRenderer = (template, container) => {
|
|
66
|
+
const ours = template?.strings
|
|
67
|
+
? serializeTemplate(template)
|
|
68
|
+
: serializeValue(template);
|
|
69
|
+
const current = container.innerHTML;
|
|
70
|
+
const last = written.get(container);
|
|
71
|
+
/** Still shaped as we left it: our range is where we wrote it. Otherwise it is gone; start at the end. */
|
|
72
|
+
const before = last !== undefined && current.startsWith(last.before + last.ours) ? last.before : current;
|
|
73
|
+
const after = before === current ? '' : current.slice(before.length + last.ours.length);
|
|
74
|
+
container.innerHTML = before + ours + after;
|
|
75
|
+
written.set(container, { before, ours });
|
|
76
|
+
};
|
|
77
|
+
wire({ on: 'render', fn: serverRenderer, priority: 50 });
|
|
78
|
+
/* ── static mode, as a store module ──────────────────────────────────────────────────────────── */
|
|
79
|
+
/**
|
|
80
|
+
* **`static: true` — this page will not be interactive, so its stores need not be reactive.** A server
|
|
81
|
+
* render is one shot, and the proxy's tracking is the whole reactivity cost of one: turning it off is
|
|
82
|
+
* worth about 3x, with identical markup. A `'store'` insert wrapping every handler core or a module
|
|
83
|
+
* chooses, so a store's reads during a static render bypass tracking and a WRITE is refused by name —
|
|
84
|
+
* a write would change nothing anyone renders, silently. The flag is read at each operation, because a
|
|
85
|
+
* store module decides once per type and a store must be reactive again the moment the render ends.
|
|
86
|
+
*/
|
|
87
|
+
let staticRender = false;
|
|
88
|
+
const refuseStatic = (prop) => own(new TypeError(ssrMisuse('ssr-static-write', PROSE['ssr-static-write'](quoted(String(prop))))));
|
|
89
|
+
/**
|
|
90
|
+
* One static-aware handler per handler it wraps, never one per value: a copy per value cost a small
|
|
91
|
+
* render about 1.2 µs (a fifth of it) in allocation, and gave every nested proxy a handler of its own.
|
|
92
|
+
*/
|
|
93
|
+
const staticAware = new WeakMap();
|
|
94
|
+
const makeStaticAware = (handler) => {
|
|
95
|
+
const { get = Reflect.get, set = Reflect.set } = handler;
|
|
96
|
+
return {
|
|
97
|
+
...handler,
|
|
98
|
+
get: (obj, prop, receiver) => (staticRender ? Reflect.get : get)(obj, prop, receiver),
|
|
99
|
+
set: (obj, prop, next, receiver) => {
|
|
100
|
+
if (staticRender)
|
|
101
|
+
throw refuseStatic(prop);
|
|
102
|
+
return set(obj, prop, next, receiver);
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
wire({
|
|
107
|
+
on: 'store',
|
|
108
|
+
priority: 90,
|
|
109
|
+
fn: (type, handler) => {
|
|
110
|
+
if (!handler)
|
|
111
|
+
return handler;
|
|
112
|
+
let aware = staticAware.get(handler);
|
|
113
|
+
if (!aware)
|
|
114
|
+
staticAware.set(handler, (aware = makeStaticAware(handler)));
|
|
115
|
+
return aware;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
/* ── instances ───────────────────────────────────────────────────────────────────────────────── */
|
|
119
|
+
/** The chains, typed as this module reads them. */
|
|
120
|
+
const chain = (name) => (inserts.get(name) ?? []);
|
|
121
|
+
/**
|
|
122
|
+
* The element a component tag renders as. A component the PARENT built — a child it appended, or the
|
|
123
|
+
* instance its `.prop` bindings were delivered to — arrives as a marker attribute and is rendered as
|
|
124
|
+
* itself, carrying what the parent gave it; the marker must name this very tag. The markup's attributes
|
|
125
|
+
* land on it too (values decoded: they were read back out of markup this module escaped).
|
|
126
|
+
*/
|
|
127
|
+
const buildInstance = (tag, attrString) => {
|
|
128
|
+
/** A tag with no attributes — most of them — does no attribute work at all (`matchAll` copies its regex). */
|
|
129
|
+
const attributes = attrString
|
|
130
|
+
? [...attrString.matchAll(ATTRIBUTE)].map(([, name, quoted, single, bare]) => [
|
|
131
|
+
name,
|
|
132
|
+
decodeEntities(quoted ?? single ?? bare ?? ''),
|
|
133
|
+
])
|
|
134
|
+
: undefined;
|
|
135
|
+
const marker = attributes?.find(([name]) => name === INSTANCE_ATTRIBUTE)?.[1];
|
|
136
|
+
const pending = marker === undefined ? undefined : pendingInstances.get(marker);
|
|
137
|
+
const element = (pending?.localName === tag ? pending : new (registry.get(tag))());
|
|
138
|
+
/**
|
|
139
|
+
* Unregistered HERE, and only when picked up: a marker is an attribute, so a copy of it can sit on
|
|
140
|
+
* another tag, and unregistering whatever marker an element carries let that copy rob the instance
|
|
141
|
+
* it names of its pickup — rebuilt from the tag, without what the parent gave it.
|
|
142
|
+
*/
|
|
143
|
+
if (element === pending)
|
|
144
|
+
pendingInstances.delete(marker);
|
|
145
|
+
element.localName = tag;
|
|
146
|
+
if (attributes)
|
|
147
|
+
for (const [name, value] of attributes)
|
|
148
|
+
element.setAttribute(name, value);
|
|
149
|
+
return element;
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Before the lifecycle: the marker removed, `props` assigned, children placed — where a
|
|
153
|
+
* client parser would already have put them — and, for light-DOM slots, the host's children held out so
|
|
154
|
+
* the slots module can distribute them after the template renders.
|
|
155
|
+
*/
|
|
156
|
+
const prepareInstance = (element, tag, props, children) => {
|
|
157
|
+
element._rendered = true;
|
|
158
|
+
element.removeAttribute(INSTANCE_ATTRIBUTE);
|
|
159
|
+
if (props)
|
|
160
|
+
for (const [name, value] of Object.entries(props)) {
|
|
161
|
+
/** `__proto__` would REPLACE the element's prototype — `JSON.parse` makes it an ordinary own key. */
|
|
162
|
+
if (name === '__proto__')
|
|
163
|
+
continue;
|
|
164
|
+
try {
|
|
165
|
+
element[name] = value;
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
throw own(new TypeError(ssrMisuse('ssr-prop-refused', PROSE['ssr-prop-refused'](tag, quoted(thrownMessage(error)))), { cause: error }));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (children)
|
|
172
|
+
element.innerHTML = children;
|
|
173
|
+
if (chain('slot').length > 0) {
|
|
174
|
+
element._veraSlotSource = [...element.childNodes];
|
|
175
|
+
for (const node of element._veraSlotSource)
|
|
176
|
+
element.removeChild(node);
|
|
177
|
+
}
|
|
178
|
+
renderedTags.add(tag);
|
|
179
|
+
const previousTag = setRenderingTag(tag);
|
|
180
|
+
element.upgrade();
|
|
181
|
+
return previousTag;
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* After the lifecycle: the `'settle'` insert (the tree is final — `@verajs/directives` evaluates
|
|
185
|
+
* declarative directives into the markup here), then light-DOM slots distributed — or a SHADOW host's
|
|
186
|
+
* children put back as they were, since the platform projects those itself — and the element's two
|
|
187
|
+
* halves, still to be scanned for nested components.
|
|
188
|
+
*/
|
|
189
|
+
const finishInstance = (element, tag, previousTag) => {
|
|
190
|
+
try {
|
|
191
|
+
for (const settle of chain('settle'))
|
|
192
|
+
settle(element);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
failed(tag)(error);
|
|
196
|
+
}
|
|
197
|
+
setRenderingTag(previousTag);
|
|
198
|
+
const source = element._veraSlotSource;
|
|
199
|
+
if (source !== undefined) {
|
|
200
|
+
element._veraSlotSource = undefined;
|
|
201
|
+
if (element._shadowRoot)
|
|
202
|
+
for (const node of source)
|
|
203
|
+
element.appendChild(node);
|
|
204
|
+
else
|
|
205
|
+
distributeLight(element, source);
|
|
206
|
+
}
|
|
207
|
+
const root = element._shadowRoot;
|
|
208
|
+
return { open: element.openTag(), root, shadow: root?.innerHTML ?? '', light: element.innerHTML };
|
|
209
|
+
};
|
|
210
|
+
/**
|
|
211
|
+
* The element's markup: a declarative shadow template (a CLOSED root is serialized too — the mode governs
|
|
212
|
+
* who can reach in, not what is written) followed by the element's light DOM, or its light DOM alone.
|
|
213
|
+
*/
|
|
214
|
+
const assemble = ({ open, root }, shadow, light) => ({
|
|
215
|
+
open,
|
|
216
|
+
inner: root ? `<template${root.templateAttributes()}>${root.styleTags()}${shadow}</template>${light}` : light,
|
|
217
|
+
});
|
|
218
|
+
/** One component tag found by the synchronous scan. */
|
|
219
|
+
const emit = (tag, attrString, depth, children) => {
|
|
220
|
+
const { open, inner } = renderInstance(buildInstance(tag, attrString), tag, depth, undefined, children);
|
|
221
|
+
return open + inner;
|
|
222
|
+
};
|
|
223
|
+
/**
|
|
224
|
+
* The synchronous chain. An `async connectedCallback` returns a promise it cannot wait for — the markup
|
|
225
|
+
* would be empty — so it is refused by name; `renderToStringAsync` is the render that waits.
|
|
226
|
+
*/
|
|
227
|
+
const renderInstance = (element, tag, depth, props, children) => {
|
|
228
|
+
const previousTag = prepareInstance(element, tag, props, children);
|
|
229
|
+
const pending = element.connectedCallback?.();
|
|
230
|
+
flushFrames(failed(tag));
|
|
231
|
+
if (typeof pending?.then === 'function')
|
|
232
|
+
throw own(new Error(ssrMisuse('ssr-async-connected', PROSE['ssr-async-connected'](tag))));
|
|
233
|
+
const pieces = finishInstance(element, tag, previousTag);
|
|
234
|
+
return assemble(pieces, renderComponentTags(pieces.shadow, depth, emit), renderComponentTags(pieces.light, depth, emit));
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* The asynchronous chain: the lifecycle is awaited and frames drain with the microtask queue running
|
|
238
|
+
* between rounds. The scan stays synchronous — a component tag becomes a placeholder and its render a
|
|
239
|
+
* promise, substituted once everything beneath has settled — so both chains share one parser. The
|
|
240
|
+
* placeholder's name is random per process, so a component's own markup cannot contain one.
|
|
241
|
+
*/
|
|
242
|
+
const PLACEHOLDER = `vera-async-${crypto.randomUUID()}`;
|
|
243
|
+
const PLACEHOLDERS = new RegExp(`${PLACEHOLDER}(\\d+)_`, 'gu');
|
|
244
|
+
const scanAsync = async (markup, depth) => {
|
|
245
|
+
const pending = [];
|
|
246
|
+
const scanned = renderComponentTags(markup, depth, (tag, attrString, at, children) => {
|
|
247
|
+
pending.push(renderInstanceAsync(buildInstance(tag, attrString), tag, at, undefined, children).then((r) => r.open + r.inner));
|
|
248
|
+
return `${PLACEHOLDER}${pending.length - 1}_`;
|
|
249
|
+
});
|
|
250
|
+
if (!pending.length)
|
|
251
|
+
return scanned;
|
|
252
|
+
const parts = await Promise.all(pending);
|
|
253
|
+
return scanned.replace(PLACEHOLDERS, (_, index) => parts[Number(index)]);
|
|
254
|
+
};
|
|
255
|
+
const renderInstanceAsync = async (element, tag, depth, props, children) => {
|
|
256
|
+
const previousTag = prepareInstance(element, tag, props, children);
|
|
257
|
+
const cut = await bounded(element.connectedCallback?.());
|
|
258
|
+
if ((await flushFramesAsync(failed(tag))) || cut)
|
|
259
|
+
timedOut.add(tag);
|
|
260
|
+
const pieces = finishInstance(element, tag, previousTag);
|
|
261
|
+
return assemble(pieces, await scanAsync(pieces.shadow, depth), await scanAsync(pieces.light, depth));
|
|
262
|
+
};
|
|
263
|
+
/* ── the entry points ────────────────────────────────────────────────────────────────────────── */
|
|
264
|
+
/**
|
|
265
|
+
* The options, checked by one table: a wrong one otherwise surfaced as an internal
|
|
266
|
+
* (`markup.includes is not a function`, `Cannot find package 'undefined'`) naming nothing the caller did.
|
|
267
|
+
*/
|
|
268
|
+
const isUrl = (value) => typeof value === 'string' || value instanceof URL;
|
|
269
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
270
|
+
const CHECKS = [
|
|
271
|
+
{ name: 'url', valid: isUrl, expected: 'a module URL — a URL or a string' },
|
|
272
|
+
{
|
|
273
|
+
name: 'tag',
|
|
274
|
+
valid: (v) => v === undefined || typeof v === 'string',
|
|
275
|
+
expected: 'a custom element name',
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
name: 'attributes',
|
|
279
|
+
valid: (v) => typeof v === 'string' || isRecord(v),
|
|
280
|
+
expected: 'an object of names to values, or a string',
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
name: 'props',
|
|
284
|
+
valid: (v) => v === undefined || isRecord(v),
|
|
285
|
+
expected: 'an object of properties to assign',
|
|
286
|
+
},
|
|
287
|
+
{ name: 'children', valid: (v) => typeof v === 'string', expected: 'a markup string' },
|
|
288
|
+
{ name: 'seen', valid: (v) => v === undefined || v instanceof Set, expected: 'a Set' },
|
|
289
|
+
{ name: 'base', valid: (v) => v === undefined || isUrl(v), expected: 'a URL or a path string' },
|
|
290
|
+
{ name: 'location', valid: (v) => v === undefined || isUrl(v), expected: 'a URL or a path string' },
|
|
291
|
+
{ name: 'static', valid: (v) => typeof v === 'boolean', expected: 'true or false' },
|
|
292
|
+
/** Node turns a `setTimeout` past 2^31 − 1 ms into 1 ms, so that is the largest budget that means what it says. */
|
|
293
|
+
{
|
|
294
|
+
name: 'timeout',
|
|
295
|
+
valid: (v) => v === undefined || (typeof v === 'number' && v >= 0 && v <= 2 ** 31 - 1),
|
|
296
|
+
expected: 'a number of milliseconds, from 0 to 2147483647',
|
|
297
|
+
},
|
|
298
|
+
];
|
|
299
|
+
/**
|
|
300
|
+
* An attribute NAME that could not come out of one entry: the characters the engines' `setAttribute`
|
|
301
|
+
* refuses, so an object entry can never write a second attribute (`{ 'a=1 onload': v }`) or leave the tag.
|
|
302
|
+
*/
|
|
303
|
+
const BAD_ATTRIBUTE_NAME = /[\0-\x20"'>/=\x7f]/;
|
|
304
|
+
const attributeMarkup = (attributes) => typeof attributes === 'string'
|
|
305
|
+
? attributes
|
|
306
|
+
: Object.entries(attributes)
|
|
307
|
+
.filter(([, value]) => value != null && value !== false)
|
|
308
|
+
.map(([name, value]) => {
|
|
309
|
+
if (name === '' || BAD_ATTRIBUTE_NAME.test(name))
|
|
310
|
+
throw own(new TypeError(ssrMisuse('ssr-attribute-name', PROSE['ssr-attribute-name'](quoted(name)))));
|
|
311
|
+
return ` ${name}="${escapeHtml(value === true ? '' : value)}"`;
|
|
312
|
+
})
|
|
313
|
+
.join('');
|
|
314
|
+
/** The `timeout` an asynchronous render gets when none is given (see `beginBudget` in `frames.ts`). */
|
|
315
|
+
const DEFAULT_TIMEOUT = 2000;
|
|
316
|
+
/** `href -> entry tag`, so a module rendered again is not re-imported and re-searched. */
|
|
317
|
+
const entryTags = new Map();
|
|
318
|
+
/**
|
|
319
|
+
* **One render at a time**, so no render can see another's state — including a synchronous render fired
|
|
320
|
+
* inside an asynchronous one's pause. A failed render must not stop the queue.
|
|
321
|
+
*/
|
|
322
|
+
let turn = Promise.resolve();
|
|
323
|
+
const takeTurn = (work) => {
|
|
324
|
+
const mine = turn.then(work);
|
|
325
|
+
turn = mine.then(() => undefined, () => undefined);
|
|
326
|
+
return mine;
|
|
327
|
+
};
|
|
328
|
+
const renderModule = async (url, options = {}, isAsync) => {
|
|
329
|
+
/** From JavaScript, `options` can be anything; `null` used to surface as an unnamed destructuring error. */
|
|
330
|
+
if (!isRecord(options))
|
|
331
|
+
throw own(new TypeError(ssrMisuse('ssr-option', PROSE['ssr-option']('options', 'an object, or left out'))));
|
|
332
|
+
const { tag: chosen, attributes = '', children = '', props, seen, base, location, static: isStatic = false, timeout } = options;
|
|
333
|
+
const given = { url, tag: chosen, attributes, props, children, seen, base, location, static: isStatic, timeout };
|
|
334
|
+
/**
|
|
335
|
+
* Indexed, and objects rather than tuples: this runs once per render inside an async function, where V8
|
|
336
|
+
* did not remove a `for…of`'s per-step result objects, nor array destructuring's iterator — tuples cost
|
|
337
|
+
* ~1.4 KB of garbage per render, GC on every render after (+12% on a mixed load, measured).
|
|
338
|
+
*/
|
|
339
|
+
for (let i = 0; i < CHECKS.length; i++) {
|
|
340
|
+
const { name, valid, expected } = CHECKS[i];
|
|
341
|
+
if (!valid(given[name]))
|
|
342
|
+
throw own(new TypeError(ssrMisuse('ssr-option', PROSE['ssr-option'](name, expected))));
|
|
343
|
+
}
|
|
344
|
+
const href = url instanceof URL ? url.href : url;
|
|
345
|
+
/**
|
|
346
|
+
* **A module URL is bounded to `base` when one is given** — `import()` executes whatever it is handed,
|
|
347
|
+
* and `new URL` has already resolved any `../` by now. Read as a directory whether or not it was written
|
|
348
|
+
* as one: that can only tighten the bound.
|
|
349
|
+
*/
|
|
350
|
+
if (base !== undefined) {
|
|
351
|
+
const directory = String(base instanceof URL ? base.href : base);
|
|
352
|
+
const root = new URL('.', directory.endsWith('/') ? directory : `${directory}/`).href;
|
|
353
|
+
if (!href.startsWith(root))
|
|
354
|
+
throw own(new Error(ssrMisuse('ssr-url-refused', PROSE['ssr-url-refused'](quoted(href), quoted(root)))));
|
|
355
|
+
}
|
|
356
|
+
/** The entry is found by matching the module's EXPORTS to the registry — a registry diff around the
|
|
357
|
+
* import is unsound once two first renders overlap. */
|
|
358
|
+
if (!entryTags.has(href)) {
|
|
359
|
+
const module = await import(href);
|
|
360
|
+
let found = '';
|
|
361
|
+
for (const exported of [module.default, ...Object.values(module)])
|
|
362
|
+
for (const [name, Class] of registry)
|
|
363
|
+
if (!found && Class === exported)
|
|
364
|
+
found = name;
|
|
365
|
+
entryTags.set(href, found);
|
|
366
|
+
}
|
|
367
|
+
const tag = chosen || entryTags.get(href);
|
|
368
|
+
if (!tag || !registry.has(tag))
|
|
369
|
+
throw own(new Error(ssrMisuse('ssr-no-definition', PROSE['ssr-no-definition'](quoted(String(url))))));
|
|
370
|
+
const attrString = attributeMarkup(attributes);
|
|
371
|
+
/** An app that wired a renderer after this module was imported displaced the server's, and every
|
|
372
|
+
* component would render empty. */
|
|
373
|
+
if (!inserts.get('render')?.includes(serverRenderer))
|
|
374
|
+
throw own(new Error(ssrMisuse('ssr-renderer-replaced', PROSE['ssr-renderer-replaced']())));
|
|
375
|
+
/**
|
|
376
|
+
* The request's globals, applied inside this turn and restored in one `finally`, on every path. The
|
|
377
|
+
* location is saved only when it is replaced: reading every part of it cost more than a small render.
|
|
378
|
+
*/
|
|
379
|
+
const place = globalThis.location;
|
|
380
|
+
const title = globalThis.document.title;
|
|
381
|
+
const saved = location === undefined ? undefined : LOCATION_PARTS.map((part) => place[part]);
|
|
382
|
+
if (saved) {
|
|
383
|
+
const next = new URL(String(location), place.href);
|
|
384
|
+
for (const part of LOCATION_PARTS)
|
|
385
|
+
place[part] = next[part];
|
|
386
|
+
}
|
|
387
|
+
renderedTags.clear();
|
|
388
|
+
timedOut.clear();
|
|
389
|
+
failures.length = 0;
|
|
390
|
+
beginHoisting();
|
|
391
|
+
resetPendingDefinitions();
|
|
392
|
+
pendingInstances.clear();
|
|
393
|
+
staticRender = isStatic;
|
|
394
|
+
if (isAsync)
|
|
395
|
+
beginBudget(timeout ?? DEFAULT_TIMEOUT);
|
|
396
|
+
/**
|
|
397
|
+
* **This render's turn, for core** (2026-10-21): every hook the render creates links as usual — a write
|
|
398
|
+
* inside it must still re-render before serialization — and leaves every store when the turn ends (`$ss(-1)` below).
|
|
399
|
+
* Opened AFTER the module's import, so module-scope state (a store, a computed) is the process's, and stays live.
|
|
400
|
+
*/
|
|
401
|
+
serverTurnOf?.(1);
|
|
402
|
+
try {
|
|
403
|
+
const element = buildInstance(tag, attrString);
|
|
404
|
+
const { open, inner } = isAsync
|
|
405
|
+
? await renderInstanceAsync(element, tag, 0, props, children)
|
|
406
|
+
: renderInstance(element, tag, 0, props, children);
|
|
407
|
+
return finishPage(`${open}${inner}</${tag}>`, tag, seen);
|
|
408
|
+
}
|
|
409
|
+
finally {
|
|
410
|
+
/**
|
|
411
|
+
* Said in every build: a render that ran out of time served a different page than the one its code describes. It
|
|
412
|
+
* names the components still waiting — on a large page the page's own tag says nothing about where to look — and
|
|
413
|
+
* the commonest cause, a `whenDefined` wait for a tag the server never defines (lazily loaded, client-only or
|
|
414
|
+
* unregistered here), with its fix: RETURN before that wait on the server. That serves the component's state from
|
|
415
|
+
* before the wait, which is what a browser shows first, so hydration changes nothing. Skipping only the `await`
|
|
416
|
+
* serves the state after it instead, which the browser then replaces: measured, a visible flash.
|
|
417
|
+
*/
|
|
418
|
+
if (isAsync && endBudget()) {
|
|
419
|
+
const list = (names) => [...names].map((name) => `<${name}>`).join(', ');
|
|
420
|
+
const waits = pendingDefinitionNames();
|
|
421
|
+
if (once('ssr-timeout', tag))
|
|
422
|
+
console.warn(ssrWarning(`<${tag}>`, 'ssr-timeout', PROSE['ssr-timeout'](String(timeout ?? DEFAULT_TIMEOUT), list(timedOut), list(waits))));
|
|
423
|
+
}
|
|
424
|
+
staticRender = false;
|
|
425
|
+
globalThis.document.title = title;
|
|
426
|
+
saved?.forEach((value, i) => (place[LOCATION_PARTS[i]] = value));
|
|
427
|
+
serverTurnOf?.(-1);
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
/**
|
|
431
|
+
* The page: a marker nothing consumed (inside a template, a raw-text element) must not ship; the
|
|
432
|
+
* collected failures throw, naming every component; the styles this render is responsible for come back
|
|
433
|
+
* escaped — the caller places them into a `<style>`, which makes that their render boundary — with each
|
|
434
|
+
* component's styles once across a page of islands that share `seen`; and the title this render set.
|
|
435
|
+
*/
|
|
436
|
+
const finishPage = (rendered, tag, seen) => {
|
|
437
|
+
const html = pendingInstances.size ? rendered.replaceAll(new RegExp(` ${INSTANCE_ATTRIBUTE}="\\d+"`, 'g'), '') : rendered;
|
|
438
|
+
if (failures.length) {
|
|
439
|
+
const [first] = failures;
|
|
440
|
+
const others = failures.length > 1 ? ` (and ${failures.length - 1} more)` : '';
|
|
441
|
+
throw own(new Error(ssrMisuse('ssr-render-threw', PROSE['ssr-render-threw'](first.tag ?? tag, others, isOwn(first.error) ? first.error.message : quoted(String(first.error?.message ?? first.error)))), { cause: first.error }));
|
|
442
|
+
}
|
|
443
|
+
const css = [];
|
|
444
|
+
for (const done of renderedTags) {
|
|
445
|
+
if (seen?.has(done))
|
|
446
|
+
continue;
|
|
447
|
+
seen?.add(done);
|
|
448
|
+
css.push(...(hoistedStyles.get(done) ?? []));
|
|
449
|
+
}
|
|
450
|
+
return { html, styles: css.map(escapeStyleText).join('\n'), title: globalThis.document.title };
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Renders a component module to markup.
|
|
454
|
+
*
|
|
455
|
+
* @param url The component's module URL
|
|
456
|
+
* @param options
|
|
457
|
+
* @param options.tag Picks the element when the module defines several
|
|
458
|
+
* @param options.attributes The entry tag's attributes — an object,
|
|
459
|
+
* whose values are escaped and whose names are checked; a string is written through untouched (**a sink**:
|
|
460
|
+
* never put request data in the string form)
|
|
461
|
+
* @param options.props Properties assigned before `connectedCallback` — how
|
|
462
|
+
* structured data reaches a component
|
|
463
|
+
* @param options.children Markup placed inside the entry tag — what a `<slot>` renders
|
|
464
|
+
* (**raw markup**, a sink like the string form of `attributes`)
|
|
465
|
+
* @param options.seen Shared across renders so a page of islands ships each component's
|
|
466
|
+
* styles once
|
|
467
|
+
* @param options.base A directory the module must resolve inside — pass it whenever any
|
|
468
|
+
* part of `url` came from a request
|
|
469
|
+
* @param options.static This page will not be interactive: stores skip reactivity (~3x), and a
|
|
470
|
+
* write during the render throws
|
|
471
|
+
* @param options.location This request's URL, applied for the render and restored after
|
|
472
|
+
* @param options.timeout How long `renderToStringAsync` waits on what a component starts, in milliseconds (2000)
|
|
473
|
+
*/
|
|
474
|
+
export const renderToString = (url, options) => takeTurn(() => renderModule(url, options, false));
|
|
475
|
+
/**
|
|
476
|
+
* Renders a component module to markup, **awaiting its lifecycle** — an `async connectedCallback`, and
|
|
477
|
+
* work started inside a frame (a router's first navigation). Same options, same output.
|
|
478
|
+
*/
|
|
479
|
+
export const renderToStringAsync = (url, options) => takeTurn(() => renderModule(url, options, true));
|
|
480
|
+
export { registry, serializeTemplate };
|