@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,164 @@
1
+ /**
2
+ * Event dispatch with a propagation path.
3
+ *
4
+ * **Bubbling was absent, and the README said why**: this DOM held children as a string, so there was
5
+ * no ancestor chain to walk and an event reached its own target's listeners and stopped. Child nodes
6
+ * are retained now, so the chain exists and the reason has expired — a component dispatching a
7
+ * `CustomEvent` that a parent listens for worked in the browser and did nothing on the server.
8
+ *
9
+ * The listeners live here rather than in the `EventTarget` these classes extend, because that one
10
+ * cannot be asked to run *only* its capturing listeners: a direct dispatch runs them all, so the
11
+ * three phases could not be told apart. What it did give — `once`, `handleEvent` objects, and a
12
+ * return value reflecting `preventDefault` — is reproduced here and covered by the same tests.
13
+ */
14
+
15
+ /** @param {any} options */
16
+ const capturing = (options) => (typeof options === 'boolean' ? options : Boolean(options?.capture));
17
+
18
+ /**
19
+ * The path from a node out to its furthest ancestor, crossing a shadow boundary only for an event
20
+ * declared `composed` — which is the rule that keeps a component's internals private.
21
+ *
22
+ * @param {any} node @param {boolean} composed
23
+ */
24
+ export const pathFrom = (node, composed) => {
25
+ const path = [];
26
+ for (let current = node; current; ) {
27
+ path.push(current);
28
+ if (current._parent) {
29
+ current = current._parent;
30
+ continue;
31
+ }
32
+ current = composed && current._host ? current._host : null;
33
+ }
34
+ return path;
35
+ };
36
+
37
+ /** @param {any} node */
38
+ export const addListener = (node, type, callback, options) => {
39
+ if (!callback) return;
40
+ const listeners = (node._listeners ??= new Map());
41
+ const key = `${type}`;
42
+ const entries = listeners.get(key) ?? [];
43
+ const capture = capturing(options);
44
+ /** The platform ignores a duplicate registration of the same callback in the same phase. */
45
+ if (entries.some((entry) => entry.callback === callback && entry.capture === capture)) return;
46
+ entries.push({ callback, capture, once: Boolean(options?.once) });
47
+ listeners.set(key, entries);
48
+ options?.signal?.addEventListener?.('abort', () => removeListener(node, type, callback, options));
49
+ };
50
+
51
+ /** @param {any} node */
52
+ export const removeListener = (node, type, callback, options) => {
53
+ const entries = node._listeners?.get(`${type}`);
54
+ if (!entries) return;
55
+ const capture = capturing(options);
56
+ const index = entries.findIndex((entry) => entry.callback === callback && entry.capture === capture);
57
+ if (index !== -1) entries.splice(index, 1);
58
+ };
59
+
60
+ /**
61
+ * `Event.CAPTURING_PHASE`, `AT_TARGET`, `BUBBLING_PHASE` — the numbers every engine reports, and
62
+ * which `installShims` also puts on `Event.prototype` where a browser has them and Node does not.
63
+ */
64
+ const PHASES = { capture: 1, target: 2, bubble: 3 };
65
+
66
+ /**
67
+ * Run the listeners registered on one node for one phase.
68
+ *
69
+ * @param {any} node @param {any} event @param {'capture' | 'target' | 'bubble'} phase
70
+ * @param {() => boolean} immediatelyStopped
71
+ */
72
+ const runListeners = (node, event, phase, immediatelyStopped) => {
73
+ const entries = node._listeners?.get(event.type);
74
+ if (!entries?.length) return;
75
+ Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
76
+ /**
77
+ * **`eventPhase` said `NONE` for the whole dispatch**, where every engine reports 1, 2 and 3.
78
+ * `event.eventPhase === event.AT_TARGET` is the ordinary way a component asks "was this mine, or
79
+ * a descendant's?", so the server took the other branch from the client for an event both of them
80
+ * dispatched — with nothing to show for it until the two renders disagreed somewhere else.
81
+ */
82
+ Object.defineProperty(event, 'eventPhase', { value: PHASES[phase], configurable: true });
83
+ /** A copy, because a listener may add or remove listeners while this runs. */
84
+ for (const entry of [...entries]) {
85
+ if (phase === 'capture' && !entry.capture) continue;
86
+ if (phase === 'bubble' && entry.capture) continue;
87
+ if (entry.once) removeListener(node, event.type, entry.callback, entry.capture);
88
+ try {
89
+ if (typeof entry.callback === 'function') entry.callback.call(node, event);
90
+ else entry.callback?.handleEvent?.(event);
91
+ } catch (error) {
92
+ /** A listener that throws must not take the dispatch down, exactly as in a browser. */
93
+ console.error('[vera] ssr: a listener threw', error);
94
+ }
95
+ if (immediatelyStopped()) return;
96
+ }
97
+ };
98
+
99
+ /**
100
+ * @param {any} node @param {any} event
101
+ * @returns {boolean} false when a cancelable event was prevented, as the platform reports
102
+ */
103
+ export const dispatch = (node, event) => {
104
+ /**
105
+ * **An `Event`, not something shaped like one.** This checked `typeof event.type === 'string'`,
106
+ * which `{ type: 'click' }` satisfies — so the server accepted a dispatch every engine refuses
107
+ * with a `TypeError`, and the code that made it got as far as the client before failing. Being
108
+ * lenient here does not make anything work; it moves the failure and strips the context.
109
+ */
110
+ if (!(event instanceof Event))
111
+ throw new TypeError(`Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.`);
112
+
113
+ const path = pathFrom(node, Boolean(event.composed));
114
+ let stopped = false;
115
+ let immediate = false;
116
+
117
+ /**
118
+ * Wrapped rather than read back: `cancelBubble` reflects `stopPropagation` on this platform's
119
+ * `Event`, but nothing exposes `stopImmediatePropagation`, and the two have to be told apart —
120
+ * one ends the walk, the other ends only the current node's listeners.
121
+ */
122
+ const original = {
123
+ stop: event.stopPropagation?.bind(event),
124
+ immediate: event.stopImmediatePropagation?.bind(event),
125
+ };
126
+ Object.defineProperty(event, 'stopPropagation', {
127
+ value: () => {
128
+ stopped = true;
129
+ original.stop?.();
130
+ },
131
+ configurable: true,
132
+ });
133
+ Object.defineProperty(event, 'stopImmediatePropagation', {
134
+ value: () => {
135
+ stopped = true;
136
+ immediate = true;
137
+ original.immediate?.();
138
+ },
139
+ configurable: true,
140
+ });
141
+ Object.defineProperty(event, 'target', { value: node, configurable: true });
142
+ Object.defineProperty(event, 'composedPath', { value: () => [...path], configurable: true });
143
+
144
+ const immediatelyStopped = () => {
145
+ if (!immediate) return false;
146
+ immediate = false;
147
+ return true;
148
+ };
149
+
150
+ /** Capturing runs outermost first, and never on the target itself. */
151
+ for (let index = path.length - 1; index >= 1 && !stopped; index--)
152
+ runListeners(path[index], event, 'capture', immediatelyStopped);
153
+
154
+ if (!stopped) runListeners(path[0], event, 'target', immediatelyStopped);
155
+
156
+ if (event.bubbles)
157
+ for (let index = 1; index < path.length && !stopped; index++)
158
+ runListeners(path[index], event, 'bubble', immediatelyStopped);
159
+
160
+ Object.defineProperty(event, 'currentTarget', { value: null, configurable: true });
161
+ /** Back to `NONE` once the dispatch is over, as the platform reports for a finished event. */
162
+ Object.defineProperty(event, 'eventPhase', { value: 0, configurable: true });
163
+ return !event.defaultPrevented;
164
+ };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `requestAnimationFrame` on a machine that has no frames.
3
+ *
4
+ * A server render is one shot: nothing scheduled after the markup is built can reach it. Callbacks
5
+ * are queued here and drained by `flushFrames` once a component's `connectedCallback` has returned,
6
+ * which is where a browser would run them — deferring is what makes a component's own ordering hold,
7
+ * and draining *repeatedly* is what makes the markup match where the client settles.
8
+ */
9
+
10
+ /** Callbacks awaiting a frame that will not arrive on its own. See `flushFrames`. */
11
+ export const frames = [];
12
+
13
+ /**
14
+ * How many rounds of frames a single server render will run.
15
+ *
16
+ * Deferring until after `connectedCallback` is what a browser does, and it is what makes a
17
+ * component's own ordering hold: work scheduled before `render()` still sees the template. Draining
18
+ * *repeatedly* is what makes the markup match where the client settles — an effect that derives
19
+ * state schedules a re-render, which is another frame, and stopping after one would ship the
20
+ * half-settled DOM this whole area exists to avoid.
21
+ *
22
+ * The bound is for the component that schedules a frame from inside a frame forever: an animation
23
+ * loop, which is browser-only code that happens to be reachable here. It runs a few times and stops
24
+ * rather than hanging the request.
25
+ */
26
+ const FRAME_ROUNDS = 20;
27
+
28
+ /**
29
+ * Runs everything waiting on a frame, and everything those schedule in turn.
30
+ *
31
+ * Called once per component, after `connectedCallback` — not inside `requestAnimationFrame` itself.
32
+ * Running each callback immediately looked equivalent and was not: two state changes in a row
33
+ * re-rendered twice where a browser coalesces them into one, and anything scheduled before
34
+ * `render()` ran against a component that had not drawn yet.
35
+ */
36
+ export const flushFrames = (report) => {
37
+ for (let round = 0; round < FRAME_ROUNDS && frames.length; round++) {
38
+ const batch = frames.splice(0, frames.length);
39
+ for (const frame of batch) {
40
+ /**
41
+ * One failing callback does not take the others down, because a browser runs each frame
42
+ * callback independently and reports a throw rather than abandoning the frame. It is not
43
+ * *swallowed* either — `report` collects it, and the render fails at the end naming the
44
+ * component, the same way a hook error does.
45
+ */
46
+ try {
47
+ frame?.(performance.now());
48
+ } catch (error) {
49
+ report?.(error);
50
+ }
51
+ }
52
+ }
53
+ /** A loop that never settles leaves work queued; it must not reach the next component. */
54
+ frames.length = 0;
55
+ };
56
+
57
+
58
+ /**
59
+ * The same drain, for a render that is allowed to wait.
60
+ *
61
+ * A frame callback that starts asynchronous work — `navigate()` is the one that matters, and it is
62
+ * why a routed component renders an empty outlet today — returns a promise the synchronous drain
63
+ * cannot see. Letting the microtask queue run between rounds is what allows that work to finish and
64
+ * whatever it schedules to be picked up by the next round.
65
+ *
66
+ * `await null` rather than a timer: it yields to the microtask queue, which is where a settled
67
+ * promise's continuation is waiting, without handing control to the event loop and letting an
68
+ * unrelated request interleave more than it already can.
69
+ */
70
+ export const flushFramesAsync = async (report) => {
71
+ /**
72
+ * **An empty queue is not the end.** Work started inside a frame may still be in flight — a
73
+ * `navigate()` awaits its guards and its route module before it renders anything — so stopping at
74
+ * the first empty round ended the drain while the thing it was waiting for had not finished. It
75
+ * takes a few consecutive empty turns to conclude that nothing more is coming.
76
+ */
77
+ let idle = 0;
78
+ for (let round = 0; round < FRAME_ROUNDS; round++) {
79
+ /** Anything already queued runs first, then whatever it scheduled becomes the next round. */
80
+ await null;
81
+ if (!frames.length) {
82
+ if (++idle >= 3) break;
83
+ continue;
84
+ }
85
+ idle = 0;
86
+ const batch = frames.splice(0, frames.length);
87
+ for (const frame of batch) {
88
+ try {
89
+ /**
90
+ * **Awaited, unlike the synchronous drain.** A frame callback that returns a promise is
91
+ * doing work the markup depends on — the router's initial `navigate()` is exactly that — and
92
+ * ignoring it let the render finish while the route was still resolving. The callback ran,
93
+ * the route resolved a moment later, and the outlet went out empty.
94
+ */
95
+ await frame?.(performance.now());
96
+ } catch (error) {
97
+ report?.(error);
98
+ }
99
+ }
100
+ }
101
+ frames.length = 0;
102
+ };