@barqjs/start 0.0.0-stage → 0.2.0-next.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.
- package/LICENSE +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
|
@@ -0,0 +1,1220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser half of frames: the component a server function's frame answer
|
|
3
|
+
* becomes, and the update that applies a new answer to every place it is
|
|
4
|
+
* mounted without building any of the page again.
|
|
5
|
+
*
|
|
6
|
+
* One component per address. Asking for a frame again hands back the SAME
|
|
7
|
+
* component, so a `dynamic` over it does not remount: the new markup is
|
|
8
|
+
* morphed into the region where it stands. Server nodes are patched in place,
|
|
9
|
+
* and a slot's content, which the browser owns, is kept, its arguments
|
|
10
|
+
* updated, and moved only when the server moved it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
type HeadTag,
|
|
15
|
+
bindEvent,
|
|
16
|
+
classToString,
|
|
17
|
+
delegate,
|
|
18
|
+
element,
|
|
19
|
+
insert,
|
|
20
|
+
isHydrating,
|
|
21
|
+
onHydrationEnd,
|
|
22
|
+
ref as bindRef,
|
|
23
|
+
setClass,
|
|
24
|
+
setProp,
|
|
25
|
+
setStyle,
|
|
26
|
+
useHead,
|
|
27
|
+
} from "@barqjs/web";
|
|
28
|
+
import {
|
|
29
|
+
type Owner,
|
|
30
|
+
block,
|
|
31
|
+
createRenderEffect,
|
|
32
|
+
createRoot,
|
|
33
|
+
createSignal,
|
|
34
|
+
getOwner,
|
|
35
|
+
onCleanup,
|
|
36
|
+
runWithOwner,
|
|
37
|
+
untrack,
|
|
38
|
+
} from "@barqjs/core";
|
|
39
|
+
import { withoutClaim } from "@barqjs/core/internal";
|
|
40
|
+
import { type Range, withRange } from "@barqjs/web/internal";
|
|
41
|
+
import { type AnySerializationAdapter, decodeWire } from "@barqjs/server/codec";
|
|
42
|
+
|
|
43
|
+
import { ServerFnError } from "./fn-error.ts";
|
|
44
|
+
import { LIVE_CALL, type LiveRequest, type Stub, clientStub } from "./stubs.ts";
|
|
45
|
+
import {
|
|
46
|
+
BIND_ATTRIBUTE,
|
|
47
|
+
BIND_EVENT,
|
|
48
|
+
BIND_TEXT_END,
|
|
49
|
+
type BindEntry,
|
|
50
|
+
FRAME,
|
|
51
|
+
FRAME_APPLIED_EVENT,
|
|
52
|
+
FRAME_TAG,
|
|
53
|
+
FLIGHT_TYPE,
|
|
54
|
+
FRAMES_BUDGET,
|
|
55
|
+
FRAME_VERSION,
|
|
56
|
+
type FramePayload,
|
|
57
|
+
type FrameRef,
|
|
58
|
+
PAYLOAD_TYPE,
|
|
59
|
+
REGION_TAG,
|
|
60
|
+
type SlotRecord,
|
|
61
|
+
bindEntries,
|
|
62
|
+
bindTextEntry,
|
|
63
|
+
isFrame,
|
|
64
|
+
slotClose,
|
|
65
|
+
slotEnd,
|
|
66
|
+
slotIndex,
|
|
67
|
+
slotOpen,
|
|
68
|
+
} from "./frames.ts";
|
|
69
|
+
|
|
70
|
+
/** What a frame renders as: a component taking the slots' content as props. */
|
|
71
|
+
export type FrameComponent = ((props: Record<string, unknown>) => Node) & {
|
|
72
|
+
readonly [FRAME]: FrameRef;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** One slot's content, owned by the browser. */
|
|
76
|
+
interface Occurrence {
|
|
77
|
+
readonly key: string;
|
|
78
|
+
readonly name: string;
|
|
79
|
+
readonly start: Comment;
|
|
80
|
+
readonly end: Comment;
|
|
81
|
+
readonly region: Element | null;
|
|
82
|
+
readonly setArgs: (args: Record<string, unknown>) => void;
|
|
83
|
+
readonly dispose: () => void;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* One binding slot occurrence: the page's fill, run once, and the positions of
|
|
88
|
+
* the server's markup its properties fill, by the node that carries each and
|
|
89
|
+
* the position's spelling.
|
|
90
|
+
*/
|
|
91
|
+
interface Binding {
|
|
92
|
+
readonly name: string;
|
|
93
|
+
readonly owner: Owner | null;
|
|
94
|
+
readonly values: Record<string, unknown> | null;
|
|
95
|
+
readonly setArgs: (args: Record<string, unknown>) => void;
|
|
96
|
+
readonly dispose: () => void;
|
|
97
|
+
readonly positions: Map<Node, Map<string, () => void>>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** One place a frame is mounted. */
|
|
101
|
+
interface Mount {
|
|
102
|
+
readonly host: Element;
|
|
103
|
+
/** The page is being claimed over this mount's server markup, slots included. */
|
|
104
|
+
claiming: boolean;
|
|
105
|
+
readonly owner: Owner | null;
|
|
106
|
+
readonly props: Record<string, unknown>;
|
|
107
|
+
readonly occurrences: Map<Comment, Occurrence>;
|
|
108
|
+
/** The binding slot occurrences, by key. */
|
|
109
|
+
bindings: Map<string, Binding>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface FrameState {
|
|
113
|
+
readonly ref: FrameRef;
|
|
114
|
+
payload: FramePayload | null;
|
|
115
|
+
/** The region's markup as the last answer carried it, for a mount that has none on the page. */
|
|
116
|
+
markup: string | null;
|
|
117
|
+
readonly mounts: Set<Mount>;
|
|
118
|
+
readonly head: () => readonly HeadTag[];
|
|
119
|
+
readonly setHead: (head: readonly HeadTag[]) => void;
|
|
120
|
+
readonly component: FrameComponent;
|
|
121
|
+
/** The live connection the page opened for a frame it was served, while one is open. */
|
|
122
|
+
connection: { readonly stop: () => void } | null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const FRAMES = new Map<string, FrameState>();
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Keep a frame the page was served through `live` current: the connection a
|
|
129
|
+
* `live` call in the browser would have opened, through the same stub and so
|
|
130
|
+
* its client middleware, opened once the page has been claimed and closed
|
|
131
|
+
* when the last place the frame is mounted goes.
|
|
132
|
+
*/
|
|
133
|
+
function connect(state: FrameState): void {
|
|
134
|
+
if (state.connection !== null || state.payload?.live !== true) return;
|
|
135
|
+
const stub = clientStub(state.ref.id) as Parameters<typeof liveIterable>[0] | undefined;
|
|
136
|
+
if (stub === undefined) return;
|
|
137
|
+
const options = {
|
|
138
|
+
data: state.payload.args === undefined ? undefined : decodeWire(state.payload.args),
|
|
139
|
+
};
|
|
140
|
+
const iterator = liveIterable(stub, options)[Symbol.asyncIterator]();
|
|
141
|
+
const connection = { stop: (): void => void iterator.return?.() };
|
|
142
|
+
state.connection = connection;
|
|
143
|
+
void (async () => {
|
|
144
|
+
try {
|
|
145
|
+
for (;;) if ((await iterator.next()).done === true) return;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
console.error(
|
|
148
|
+
`[barq] The live frame of ${JSON.stringify(state.ref.id)} could not stay connected, so it shows what it last received. The error:`,
|
|
149
|
+
error,
|
|
150
|
+
);
|
|
151
|
+
} finally {
|
|
152
|
+
if (state.connection === connection) state.connection = null;
|
|
153
|
+
}
|
|
154
|
+
})();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function stateFor(ref: FrameRef): FrameState {
|
|
158
|
+
const known = FRAMES.get(ref.address);
|
|
159
|
+
if (known !== undefined) return known;
|
|
160
|
+
const [head, setHead] = createSignal<readonly HeadTag[]>([], { ownedWrite: true });
|
|
161
|
+
const state: FrameState = {
|
|
162
|
+
ref,
|
|
163
|
+
payload: null,
|
|
164
|
+
markup: null,
|
|
165
|
+
mounts: new Set(),
|
|
166
|
+
head,
|
|
167
|
+
setHead,
|
|
168
|
+
component: null as never,
|
|
169
|
+
connection: null,
|
|
170
|
+
};
|
|
171
|
+
const component = (props: Record<string, unknown>): Node => mount(state, props);
|
|
172
|
+
(state as { component: FrameComponent }).component = Object.assign(component, { [FRAME]: ref });
|
|
173
|
+
FRAMES.set(ref.address, state);
|
|
174
|
+
return state;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* How a frame named in the page's seed becomes the component for the region
|
|
179
|
+
* the page already carries. The client entry installs it beside the
|
|
180
|
+
* application's own adapters, before the seed is read.
|
|
181
|
+
*/
|
|
182
|
+
export const frameAdapter: AnySerializationAdapter = {
|
|
183
|
+
key: "barq.frame",
|
|
184
|
+
test: isFrame,
|
|
185
|
+
toSerializable: (frame: FrameComponent): FrameRef => ({
|
|
186
|
+
id: frame[FRAME].id,
|
|
187
|
+
address: frame[FRAME].address,
|
|
188
|
+
}),
|
|
189
|
+
fromSerializable: (ref: FrameRef): FrameComponent => stateFor(ref).component,
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
function payloadOf(host: Element): FramePayload | null {
|
|
193
|
+
const script = host.firstElementChild;
|
|
194
|
+
if (script === null || script.localName !== "script") return null;
|
|
195
|
+
if (script.getAttribute("type") !== PAYLOAD_TYPE) return null;
|
|
196
|
+
const text = script.textContent ?? "";
|
|
197
|
+
return text === "" ? null : (JSON.parse(text) as FramePayload);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The frame's own script, which the morph leaves to `setPayload`. */
|
|
201
|
+
function isPayload(node: Node | null): node is Element {
|
|
202
|
+
return (
|
|
203
|
+
node !== null &&
|
|
204
|
+
node.nodeType === 1 &&
|
|
205
|
+
(node as Element).localName === "script" &&
|
|
206
|
+
(node as Element).getAttribute("type") === PAYLOAD_TYPE
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function setPayload(host: Element, payload: FramePayload): void {
|
|
211
|
+
const script = host.firstElementChild;
|
|
212
|
+
if (script !== null && isPayload(script)) script.textContent = JSON.stringify(payload);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function recordAt(payload: FramePayload, at: number): SlotRecord | undefined {
|
|
216
|
+
return payload.slots.find((record) => record.at === at);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The comment that closes the slot `start` opens, among its siblings. */
|
|
220
|
+
function closeOf(start: Comment): Comment | null {
|
|
221
|
+
const at = slotIndex(start.data);
|
|
222
|
+
for (let node = start.nextSibling; node !== null; node = node.nextSibling) {
|
|
223
|
+
if (node.nodeType === 8 && slotEnd((node as Comment).data) === at) return node as Comment;
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function between(start: Node, end: Node): Node[] {
|
|
229
|
+
const out: Node[] = [];
|
|
230
|
+
for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {
|
|
231
|
+
out.push(node);
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Every slot opening in `root` that no occurrence owns yet, in document order. */
|
|
237
|
+
function unfilled(root: Element, owned: Map<Comment, Occurrence>): Comment | null {
|
|
238
|
+
const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
|
|
239
|
+
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
|
|
240
|
+
const comment = node as Comment;
|
|
241
|
+
if (slotIndex(comment.data) !== -1 && !owned.has(comment)) return comment;
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function regionElement(key: string, markup: string): Element {
|
|
247
|
+
const region = document.createElement(REGION_TAG);
|
|
248
|
+
region.setAttribute("data-region", key);
|
|
249
|
+
region.setAttribute("style", "display:contents");
|
|
250
|
+
region.innerHTML = markup;
|
|
251
|
+
return region;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Fill one slot: the page's `children` where the server placed them, or the
|
|
256
|
+
* page's function for a named slot called with the occurrence's arguments.
|
|
257
|
+
*
|
|
258
|
+
* While the page is being claimed, the server's content for the slot is
|
|
259
|
+
* CLAIMED: the fill runs over a cursor on the slot's range, as the content of
|
|
260
|
+
* any other hole does, and takes the nodes the server wrote for it. Otherwise
|
|
261
|
+
* the slot is empty and the fill builds into it. A nested region the server
|
|
262
|
+
* wrote is handed to the fill as its children either way.
|
|
263
|
+
*/
|
|
264
|
+
function fill(site: Mount, start: Comment, record: SlotRecord): Occurrence | null {
|
|
265
|
+
const end = closeOf(start);
|
|
266
|
+
if (end === null) return null;
|
|
267
|
+
const parent = end.parentNode;
|
|
268
|
+
if (parent === null) return null;
|
|
269
|
+
const served = between(start, end);
|
|
270
|
+
const claiming = site.claiming && served.length > 0;
|
|
271
|
+
let region: Element | null = null;
|
|
272
|
+
if (record.hasRegion === true) {
|
|
273
|
+
for (const node of served) {
|
|
274
|
+
const found =
|
|
275
|
+
node.nodeType === 1 && (node as Element).localName === REGION_TAG
|
|
276
|
+
? (node as Element)
|
|
277
|
+
: node.nodeType === 1
|
|
278
|
+
? (node as Element).querySelector(REGION_TAG)
|
|
279
|
+
: null;
|
|
280
|
+
if (found !== null) {
|
|
281
|
+
region = found;
|
|
282
|
+
break;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (!claiming) region?.remove();
|
|
286
|
+
region ??= regionElement(String(record.at), record.region ?? "");
|
|
287
|
+
}
|
|
288
|
+
if (!claiming) for (const node of served) node.parentNode?.removeChild(node);
|
|
289
|
+
const [args, setArgs] = createSignal<Record<string, unknown>>(
|
|
290
|
+
record.args === undefined ? {} : decodeWire(record.args),
|
|
291
|
+
{ ownedWrite: true },
|
|
292
|
+
);
|
|
293
|
+
const given = site.props[record.name];
|
|
294
|
+
const content = (): unknown => {
|
|
295
|
+
if (record.name === "children") return given;
|
|
296
|
+
// A fill that takes nothing reaches the props as the Cell it is, so reading
|
|
297
|
+
// the prop is calling it.
|
|
298
|
+
const fn = typeof given === "function" ? untrack(given as () => unknown) : given;
|
|
299
|
+
if (typeof fn !== "function") return fn ?? null;
|
|
300
|
+
const props: Record<string, unknown> = {};
|
|
301
|
+
for (const key of Object.keys(untrack(args))) props[key] = (): unknown => args()[key];
|
|
302
|
+
if (region !== null) {
|
|
303
|
+
const placed = region;
|
|
304
|
+
props.children = block(() => placed);
|
|
305
|
+
}
|
|
306
|
+
return untrack(() => (fn as (props: Record<string, unknown>) => unknown)(props));
|
|
307
|
+
};
|
|
308
|
+
const range: Range = { open: start, close: end, parent, nodes: served };
|
|
309
|
+
const dispose = claiming
|
|
310
|
+
? runWithOwner(site.owner, () =>
|
|
311
|
+
createRoot((release) => {
|
|
312
|
+
withRange(range, () => {
|
|
313
|
+
const value = content();
|
|
314
|
+
// A Block is called with the scope it builds under, as `insert` calls one.
|
|
315
|
+
return typeof value === "function"
|
|
316
|
+
? (value as (scope: unknown) => unknown)(getOwner())
|
|
317
|
+
: value;
|
|
318
|
+
});
|
|
319
|
+
return release;
|
|
320
|
+
}),
|
|
321
|
+
)
|
|
322
|
+
: withoutClaim(() =>
|
|
323
|
+
runWithOwner(site.owner, () =>
|
|
324
|
+
createRoot((release) => {
|
|
325
|
+
insert(parent, content() as never, end);
|
|
326
|
+
return release;
|
|
327
|
+
}),
|
|
328
|
+
),
|
|
329
|
+
);
|
|
330
|
+
return { key: record.key, name: record.name, start, end, region, setArgs, dispose };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Fill every slot in the mount that has no content yet, outermost first. */
|
|
334
|
+
function fillAll(site: Mount, payload: FramePayload): void {
|
|
335
|
+
for (;;) {
|
|
336
|
+
const start = unfilled(site.host, site.occurrences);
|
|
337
|
+
if (start === null) return;
|
|
338
|
+
const record = recordAt(payload, slotIndex(start.data));
|
|
339
|
+
const occurrence = record === undefined ? null : fill(site, start, record);
|
|
340
|
+
// A marker with no record, or no close, is left as it is rather than filled.
|
|
341
|
+
site.occurrences.set(start, occurrence ?? DEAD);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const DEAD: Occurrence = {
|
|
346
|
+
key: "",
|
|
347
|
+
name: "",
|
|
348
|
+
start: null as never,
|
|
349
|
+
end: null as never,
|
|
350
|
+
region: null,
|
|
351
|
+
setArgs: () => {},
|
|
352
|
+
dispose: () => {},
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
function mount(state: FrameState, props: Record<string, unknown>): Node {
|
|
356
|
+
const owner = getOwner();
|
|
357
|
+
// The server's element when the page is being claimed: its region stays
|
|
358
|
+
// exactly as it is, and only the slots are filled.
|
|
359
|
+
const host = element(FRAME_TAG, {});
|
|
360
|
+
const adopted = host.getAttribute("data-frame") === state.ref.address && payloadOf(host) !== null;
|
|
361
|
+
if (!adopted) {
|
|
362
|
+
withoutClaim(() => {
|
|
363
|
+
host.setAttribute("data-frame", state.ref.address);
|
|
364
|
+
host.setAttribute("style", "display:contents");
|
|
365
|
+
host.innerHTML = `<script type="${PAYLOAD_TYPE}"></script>${state.markup ?? markupOnPage(state) ?? ""}`;
|
|
366
|
+
if (state.payload !== null) setPayload(host, state.payload);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
state.payload ??= payloadOf(host);
|
|
370
|
+
const payload = state.payload ?? { v: FRAME_VERSION, slots: [], head: [] };
|
|
371
|
+
if (untrack(state.head).length === 0 && payload.head.length > 0) state.setHead(payload.head);
|
|
372
|
+
const placed: Mount = {
|
|
373
|
+
host,
|
|
374
|
+
owner,
|
|
375
|
+
props,
|
|
376
|
+
occurrences: new Map(),
|
|
377
|
+
bindings: new Map(),
|
|
378
|
+
claiming: adopted && isHydrating(),
|
|
379
|
+
};
|
|
380
|
+
fillAll(placed, payload);
|
|
381
|
+
bindAll(placed, payload);
|
|
382
|
+
placed.claiming = false;
|
|
383
|
+
state.mounts.add(placed);
|
|
384
|
+
useHead(() => state.head());
|
|
385
|
+
if (adopted) onHydrationEnd(() => connect(state));
|
|
386
|
+
onCleanup(() => {
|
|
387
|
+
state.mounts.delete(placed);
|
|
388
|
+
for (const occurrence of placed.occurrences.values()) occurrence.dispose();
|
|
389
|
+
for (const binding of placed.bindings.values()) binding.dispose();
|
|
390
|
+
if (state.mounts.size === 0) state.connection?.stop();
|
|
391
|
+
});
|
|
392
|
+
return host;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* A frame the page carries but this mount was not claimed over: one that
|
|
397
|
+
* rendered on the server and is mounted again after the page started, from a
|
|
398
|
+
* seed that named it. Its markup is taken from the page.
|
|
399
|
+
*/
|
|
400
|
+
function markupOnPage(state: FrameState): string | null {
|
|
401
|
+
for (const candidate of document.querySelectorAll(FRAME_TAG)) {
|
|
402
|
+
if (candidate.getAttribute("data-frame") !== state.ref.address) continue;
|
|
403
|
+
state.payload ??= payloadOf(candidate);
|
|
404
|
+
const copy = candidate.cloneNode(true) as Element;
|
|
405
|
+
copy.firstElementChild?.remove();
|
|
406
|
+
for (const comment of commentsIn(copy)) {
|
|
407
|
+
const at = slotIndex(comment.data);
|
|
408
|
+
if (at === -1) continue;
|
|
409
|
+
const end = closeOf(comment);
|
|
410
|
+
if (end !== null)
|
|
411
|
+
for (const node of between(comment, end)) node.parentNode?.removeChild(node);
|
|
412
|
+
}
|
|
413
|
+
return copy.innerHTML;
|
|
414
|
+
}
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Every comment in `root`, collected before the caller changes the tree around them. */
|
|
419
|
+
function commentsIn(root: Node): Comment[] {
|
|
420
|
+
const walker = (root.ownerDocument ?? document).createTreeWalker(root, NodeFilter.SHOW_COMMENT);
|
|
421
|
+
const out: Comment[] = [];
|
|
422
|
+
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
|
|
423
|
+
out.push(node as Comment);
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ── binding slots ─────────────────────────────────────────────────────────
|
|
429
|
+
|
|
430
|
+
/** The page's fill for a binding slot, run once: the object whose properties fill its positions. */
|
|
431
|
+
function bindOccurrence(site: Mount, record: SlotRecord): Binding {
|
|
432
|
+
const [args, setArgs] = createSignal<Record<string, unknown>>(
|
|
433
|
+
record.args === undefined ? {} : decodeWire(record.args),
|
|
434
|
+
{ ownedWrite: true },
|
|
435
|
+
);
|
|
436
|
+
const given = site.props[record.name];
|
|
437
|
+
return runWithOwner(site.owner, () =>
|
|
438
|
+
createRoot((dispose): Binding => {
|
|
439
|
+
const props: Record<string, unknown> = {};
|
|
440
|
+
for (const key of Object.keys(untrack(args))) props[key] = (): unknown => args()[key];
|
|
441
|
+
// A fill that takes nothing reaches the props as the Cell it is, so
|
|
442
|
+
// reading the prop is calling it.
|
|
443
|
+
const result = withoutClaim(() =>
|
|
444
|
+
untrack(() => {
|
|
445
|
+
const fn = typeof given === "function" ? (given as () => unknown)() : given;
|
|
446
|
+
return typeof fn === "function"
|
|
447
|
+
? (fn as (props: Record<string, unknown>) => unknown)(props)
|
|
448
|
+
: fn;
|
|
449
|
+
}),
|
|
450
|
+
);
|
|
451
|
+
let values: Record<string, unknown> | null = null;
|
|
452
|
+
if (
|
|
453
|
+
typeof result === "object" &&
|
|
454
|
+
result !== null &&
|
|
455
|
+
!Array.isArray(result) &&
|
|
456
|
+
!(result instanceof Node)
|
|
457
|
+
) {
|
|
458
|
+
values = result as Record<string, unknown>;
|
|
459
|
+
} else if (given !== undefined) {
|
|
460
|
+
console.error(
|
|
461
|
+
`[barq] The page's \`${record.name}\` fill returned ${result === null ? "null" : Array.isArray(result) ? "an array" : typeof result} where the server component reads it as data. ` +
|
|
462
|
+
"A binding slot's fill returns a plain object whose properties fill the positions the server marked, so the server's values stay in place.",
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
const binding: Binding = {
|
|
466
|
+
name: record.name,
|
|
467
|
+
owner: getOwner(),
|
|
468
|
+
values,
|
|
469
|
+
setArgs,
|
|
470
|
+
positions: new Map(),
|
|
471
|
+
dispose: () => {
|
|
472
|
+
for (const at of binding.positions.values()) for (const release of at.values()) release();
|
|
473
|
+
binding.positions.clear();
|
|
474
|
+
dispose();
|
|
475
|
+
},
|
|
476
|
+
};
|
|
477
|
+
return binding;
|
|
478
|
+
}),
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
interface Found {
|
|
483
|
+
readonly node: Node;
|
|
484
|
+
readonly position: string;
|
|
485
|
+
readonly entry: BindEntry;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Every position marked in `root`, a nested frame's aside, in document order. */
|
|
489
|
+
function positionsIn(root: Element): Found[] {
|
|
490
|
+
const out: Found[] = [];
|
|
491
|
+
const walker = root.ownerDocument.createTreeWalker(
|
|
492
|
+
root,
|
|
493
|
+
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT,
|
|
494
|
+
{
|
|
495
|
+
acceptNode: (node) =>
|
|
496
|
+
node !== root && node.nodeType === 1 && (node as Element).localName === FRAME_TAG
|
|
497
|
+
? NodeFilter.FILTER_REJECT
|
|
498
|
+
: NodeFilter.FILTER_ACCEPT,
|
|
499
|
+
},
|
|
500
|
+
);
|
|
501
|
+
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
|
|
502
|
+
if (node.nodeType === 8) {
|
|
503
|
+
const entry = bindTextEntry((node as Comment).data);
|
|
504
|
+
if (entry !== null) out.push({ node, position: "", entry });
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
const element = node as Element;
|
|
508
|
+
for (const name of element.getAttributeNames()) {
|
|
509
|
+
if (!name.startsWith(BIND_ATTRIBUTE)) continue;
|
|
510
|
+
const position = name.slice(BIND_ATTRIBUTE.length);
|
|
511
|
+
for (const entry of bindEntries(element.getAttribute(name) ?? "")) {
|
|
512
|
+
out.push({ node, position, entry });
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Bring the binding slot occurrences up to date with a payload: a new one's
|
|
521
|
+
* fill runs, a kept one's arguments move and its fill is not run again, and
|
|
522
|
+
* each position in the markup is bound once, a position the morph replaced or
|
|
523
|
+
* dropped released.
|
|
524
|
+
*/
|
|
525
|
+
function bindAll(site: Mount, payload: FramePayload): void {
|
|
526
|
+
const byAt = new Map<number, Binding>();
|
|
527
|
+
const next = new Map<string, Binding>();
|
|
528
|
+
for (const record of payload.slots) {
|
|
529
|
+
if (record.bind !== true) continue;
|
|
530
|
+
let binding = site.bindings.get(record.key);
|
|
531
|
+
if (binding !== undefined && binding.name === record.name) {
|
|
532
|
+
if (record.args !== undefined) binding.setArgs(decodeWire(record.args));
|
|
533
|
+
} else {
|
|
534
|
+
binding = bindOccurrence(site, record);
|
|
535
|
+
}
|
|
536
|
+
next.set(record.key, binding);
|
|
537
|
+
byAt.set(record.at, binding);
|
|
538
|
+
}
|
|
539
|
+
for (const [key, binding] of site.bindings) if (next.get(key) !== binding) binding.dispose();
|
|
540
|
+
site.bindings = next;
|
|
541
|
+
if (next.size === 0) return;
|
|
542
|
+
|
|
543
|
+
const seen = new Map<Binding, Map<Node, Set<string>>>();
|
|
544
|
+
for (const found of positionsIn(site.host)) {
|
|
545
|
+
const binding = byAt.get(found.entry.at);
|
|
546
|
+
if (binding === undefined || binding.values === null) continue;
|
|
547
|
+
const id = `${found.position}|${found.entry.key}|${found.entry.member ?? ""}`;
|
|
548
|
+
let nodes = seen.get(binding);
|
|
549
|
+
if (nodes === undefined) seen.set(binding, (nodes = new Map<Node, Set<string>>()));
|
|
550
|
+
let ids = nodes.get(found.node);
|
|
551
|
+
if (ids === undefined) nodes.set(found.node, (ids = new Set()));
|
|
552
|
+
ids.add(id);
|
|
553
|
+
let at = binding.positions.get(found.node);
|
|
554
|
+
if (at === undefined) binding.positions.set(found.node, (at = new Map<string, () => void>()));
|
|
555
|
+
if (at.has(id)) continue;
|
|
556
|
+
const claiming = site.claiming;
|
|
557
|
+
const values = binding.values;
|
|
558
|
+
at.set(
|
|
559
|
+
id,
|
|
560
|
+
runWithOwner(binding.owner, () =>
|
|
561
|
+
createRoot((release) => {
|
|
562
|
+
bindPosition(found, values, claiming);
|
|
563
|
+
return release;
|
|
564
|
+
}),
|
|
565
|
+
),
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
for (const binding of next.values()) {
|
|
569
|
+
const nodes = seen.get(binding);
|
|
570
|
+
for (const [node, at] of binding.positions) {
|
|
571
|
+
const ids = nodes?.get(node);
|
|
572
|
+
for (const [id, release] of at) {
|
|
573
|
+
if (ids?.has(id) === true) continue;
|
|
574
|
+
release();
|
|
575
|
+
at.delete(id);
|
|
576
|
+
}
|
|
577
|
+
if (at.size === 0) binding.positions.delete(node);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function textOf(value: unknown): string {
|
|
583
|
+
return typeof value === "string"
|
|
584
|
+
? value
|
|
585
|
+
: typeof value === "number" || typeof value === "bigint"
|
|
586
|
+
? String(value)
|
|
587
|
+
: "";
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* A detached element for the style a claimed position already shows: what
|
|
592
|
+
* `setStyle` would have applied, without writing to the page's element.
|
|
593
|
+
*/
|
|
594
|
+
let scratch: HTMLElement | null = null;
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Fill one position from the fill's object. A value position follows the
|
|
598
|
+
* property, a handler and a ref are read once, as the page's own JSX reads
|
|
599
|
+
* them. While the page is claimed the server already wrote each value, so the
|
|
600
|
+
* first run writes nothing.
|
|
601
|
+
*/
|
|
602
|
+
function bindPosition(found: Found, values: Record<string, unknown>, claiming: boolean): void {
|
|
603
|
+
const { node, position, entry } = found;
|
|
604
|
+
const read = (): unknown => values[entry.key];
|
|
605
|
+
if (position === "") {
|
|
606
|
+
const start = node as Comment;
|
|
607
|
+
let text: Text;
|
|
608
|
+
if (start.nextSibling !== null && start.nextSibling.nodeType === 3) {
|
|
609
|
+
text = start.nextSibling as Text;
|
|
610
|
+
} else {
|
|
611
|
+
text = document.createTextNode("");
|
|
612
|
+
start.parentNode?.insertBefore(text, start.nextSibling);
|
|
613
|
+
}
|
|
614
|
+
createRenderEffect(
|
|
615
|
+
() => textOf(read()),
|
|
616
|
+
(value) => {
|
|
617
|
+
if (text.data !== value) text.data = value;
|
|
618
|
+
},
|
|
619
|
+
);
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
const element = node as Element;
|
|
623
|
+
if (position === "ref") {
|
|
624
|
+
bindRef(element, untrack(read));
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (position.startsWith(BIND_EVENT)) {
|
|
628
|
+
const type = position.slice(BIND_EVENT.length);
|
|
629
|
+
const capture = entry.member === "capture";
|
|
630
|
+
bindEvent(element, type, untrack(read), capture);
|
|
631
|
+
// A delegated handler is the element's own expando, which nothing else
|
|
632
|
+
// takes back when the position is released.
|
|
633
|
+
if (!capture) onCleanup(() => delegate(element, type, undefined));
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
if (position === "class" && entry.member !== undefined) {
|
|
637
|
+
const name = entry.member;
|
|
638
|
+
createRenderEffect(
|
|
639
|
+
() => Boolean(read()),
|
|
640
|
+
(on) => {
|
|
641
|
+
if (element.classList.contains(name) !== on) element.classList.toggle(name, on);
|
|
642
|
+
},
|
|
643
|
+
);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
// What the channel last applied, which `setStyle` and `setClass` diff against.
|
|
647
|
+
let applied: unknown;
|
|
648
|
+
let first = claiming;
|
|
649
|
+
if (position === "style") {
|
|
650
|
+
const member = entry.member;
|
|
651
|
+
createRenderEffect(
|
|
652
|
+
() => (member === undefined ? read() : { [member]: read() }),
|
|
653
|
+
(value) => {
|
|
654
|
+
if (first) {
|
|
655
|
+
first = false;
|
|
656
|
+
scratch ??= document.createElement("div");
|
|
657
|
+
scratch.removeAttribute("style");
|
|
658
|
+
applied = setStyle(scratch, "style", value);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
applied = setStyle(element, "style", value, applied);
|
|
662
|
+
},
|
|
663
|
+
);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (position === "class") {
|
|
667
|
+
createRenderEffect(read, (value) => {
|
|
668
|
+
if (first) {
|
|
669
|
+
first = false;
|
|
670
|
+
applied = classToString(value);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
applied = setClass(element, "class", value, applied);
|
|
674
|
+
});
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
createRenderEffect(read, (value) => {
|
|
678
|
+
if (first) {
|
|
679
|
+
first = false;
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
setProp(element, position, value);
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// ── the morph ─────────────────────────────────────────────────────────────
|
|
687
|
+
|
|
688
|
+
interface MorphContext {
|
|
689
|
+
readonly mount: Mount;
|
|
690
|
+
readonly payload: FramePayload;
|
|
691
|
+
/** The occurrences still to place, by key. */
|
|
692
|
+
readonly keep: Map<string, Occurrence>;
|
|
693
|
+
readonly used: Set<Occurrence>;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function sameNode(current: Node, next: Node): boolean {
|
|
697
|
+
if (current.nodeType !== next.nodeType) return false;
|
|
698
|
+
if (current.nodeType !== 1) return true;
|
|
699
|
+
const a = current as Element;
|
|
700
|
+
const b = next as Element;
|
|
701
|
+
return a.localName === b.localName && a.getAttribute("id") === b.getAttribute("id");
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* The positions of an element a binding slot fills, by its markers: whole
|
|
706
|
+
* attributes, and the class names and style properties it fills in object form.
|
|
707
|
+
*/
|
|
708
|
+
function ownedBy(element: Element): {
|
|
709
|
+
whole: Set<string>;
|
|
710
|
+
classes: Set<string>;
|
|
711
|
+
styles: Set<string>;
|
|
712
|
+
} {
|
|
713
|
+
const owned = { whole: new Set<string>(), classes: new Set<string>(), styles: new Set<string>() };
|
|
714
|
+
for (const name of element.getAttributeNames()) {
|
|
715
|
+
if (!name.startsWith(BIND_ATTRIBUTE)) continue;
|
|
716
|
+
const position = name.slice(BIND_ATTRIBUTE.length);
|
|
717
|
+
if (position === "ref" || position.startsWith(BIND_EVENT)) continue;
|
|
718
|
+
for (const entry of bindEntries(element.getAttribute(name) ?? "")) {
|
|
719
|
+
if (entry.member === undefined) owned.whole.add(position);
|
|
720
|
+
else if (position === "class") owned.classes.add(entry.member);
|
|
721
|
+
else if (position === "style") owned.styles.add(entry.member);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return owned;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* The server's attributes, written over the element's, except where the page
|
|
729
|
+
* fills a position: a whole attribute it fills is left as it stands, and the
|
|
730
|
+
* class names and style properties it fills keep their current state inside
|
|
731
|
+
* the server's new class and style.
|
|
732
|
+
*/
|
|
733
|
+
function patchAttributes(current: Element, next: Element): void {
|
|
734
|
+
const owned = ownedBy(next);
|
|
735
|
+
const classes = owned.classes.size > 0;
|
|
736
|
+
const styles = owned.styles.size > 0;
|
|
737
|
+
for (const name of current.getAttributeNames()) {
|
|
738
|
+
if (owned.whole.has(name) || (name === "class" && classes) || (name === "style" && styles)) {
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
if (!next.hasAttribute(name)) current.removeAttribute(name);
|
|
742
|
+
}
|
|
743
|
+
for (const name of next.getAttributeNames()) {
|
|
744
|
+
if (owned.whole.has(name) || (name === "class" && classes) || (name === "style" && styles)) {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
const value = next.getAttribute(name) ?? "";
|
|
748
|
+
if (current.getAttribute(name) !== value) current.setAttribute(name, value);
|
|
749
|
+
}
|
|
750
|
+
if (classes) {
|
|
751
|
+
const tokens = new Set((next.getAttribute("class") ?? "").split(/\s+/).filter(Boolean));
|
|
752
|
+
for (const name of owned.classes) {
|
|
753
|
+
if (current.classList.contains(name)) tokens.add(name);
|
|
754
|
+
else tokens.delete(name);
|
|
755
|
+
}
|
|
756
|
+
const value = [...tokens].join(" ");
|
|
757
|
+
if ((current.getAttribute("class") ?? "") !== value) current.setAttribute("class", value);
|
|
758
|
+
}
|
|
759
|
+
if (styles) {
|
|
760
|
+
const style = (current as HTMLElement).style;
|
|
761
|
+
const kept = new Map<string, string>();
|
|
762
|
+
for (const property of owned.styles) {
|
|
763
|
+
const css = cssProperty(property);
|
|
764
|
+
kept.set(css, style.getPropertyValue(css));
|
|
765
|
+
}
|
|
766
|
+
const value = next.getAttribute("style");
|
|
767
|
+
if (current.getAttribute("style") !== value) {
|
|
768
|
+
if (value === null) current.removeAttribute("style");
|
|
769
|
+
else current.setAttribute("style", value);
|
|
770
|
+
for (const [css, text] of kept) {
|
|
771
|
+
if (text === "") style.removeProperty(css);
|
|
772
|
+
else style.setProperty(css, text);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** A style object's key as the declaration's name, as `setStyle` writes it. */
|
|
779
|
+
function cssProperty(property: string): string {
|
|
780
|
+
return property.startsWith("--")
|
|
781
|
+
? property
|
|
782
|
+
: property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
function isTextEnd(node: Node | null): boolean {
|
|
786
|
+
return node !== null && node.nodeType === 8 && (node as Comment).data === BIND_TEXT_END;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function occurrenceAt(context: MorphContext, node: Node | null): Occurrence | null {
|
|
790
|
+
if (node === null || node.nodeType !== 8) return null;
|
|
791
|
+
const found = context.mount.occurrences.get(node as Comment);
|
|
792
|
+
return found === undefined || found === DEAD ? null : found;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** Move an occurrence's whole range, markers and content, to stand before `before`. */
|
|
796
|
+
function place(occurrence: Occurrence, parent: Node, before: Node | null): void {
|
|
797
|
+
const nodes = [occurrence.start, ...between(occurrence.start, occurrence.end), occurrence.end];
|
|
798
|
+
for (const node of nodes) parent.insertBefore(node, before);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function morphChildren(current: Node, next: Node, context: MorphContext): void {
|
|
802
|
+
let cursor: Node | null = current.firstChild;
|
|
803
|
+
if (isPayload(cursor)) cursor = cursor.nextSibling;
|
|
804
|
+
const incoming = [...next.childNodes];
|
|
805
|
+
for (let at = 0; at < incoming.length; at++) {
|
|
806
|
+
const node = incoming[at];
|
|
807
|
+
// An occurrence standing here that the server no longer puts here is
|
|
808
|
+
// stepped over: it is moved to where it now belongs, or removed after.
|
|
809
|
+
for (let standing = occurrenceAt(context, cursor); standing !== null;) {
|
|
810
|
+
cursor = standing.end.nextSibling;
|
|
811
|
+
standing = occurrenceAt(context, cursor);
|
|
812
|
+
}
|
|
813
|
+
const opening = node.nodeType === 8 ? slotIndex((node as Comment).data) : -1;
|
|
814
|
+
if (opening !== -1) {
|
|
815
|
+
let close = at + 1;
|
|
816
|
+
while (close < incoming.length) {
|
|
817
|
+
const candidate = incoming[close];
|
|
818
|
+
if (candidate.nodeType === 8 && slotEnd((candidate as Comment).data) === opening) break;
|
|
819
|
+
close++;
|
|
820
|
+
}
|
|
821
|
+
at = close;
|
|
822
|
+
const record = recordAt(context.payload, opening);
|
|
823
|
+
const kept = record === undefined ? undefined : context.keep.get(record.key);
|
|
824
|
+
if (kept !== undefined && kept.name === record!.name) {
|
|
825
|
+
context.keep.delete(kept.key);
|
|
826
|
+
context.used.add(kept);
|
|
827
|
+
if (kept.start.nextSibling !== cursor || kept.start.parentNode !== current) {
|
|
828
|
+
place(kept, current, cursor);
|
|
829
|
+
}
|
|
830
|
+
kept.start.data = slotOpen(opening);
|
|
831
|
+
kept.end.data = slotClose(opening);
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
current.insertBefore(document.createComment(slotOpen(opening)), cursor);
|
|
835
|
+
current.insertBefore(document.createComment(slotClose(opening)), cursor);
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
// A text position the page fills keeps the page's text: the server's
|
|
839
|
+
// pair has nothing between, and the morph steps over both.
|
|
840
|
+
if (
|
|
841
|
+
node.nodeType === 8 &&
|
|
842
|
+
bindTextEntry((node as Comment).data) !== null &&
|
|
843
|
+
cursor !== null &&
|
|
844
|
+
cursor.nodeType === 8 &&
|
|
845
|
+
(cursor as Comment).data === (node as Comment).data
|
|
846
|
+
) {
|
|
847
|
+
while (at + 1 < incoming.length && !isTextEnd(incoming[at])) at++;
|
|
848
|
+
let end: Node | null = cursor.nextSibling;
|
|
849
|
+
while (end !== null && !isTextEnd(end)) end = end.nextSibling;
|
|
850
|
+
cursor = end === null ? null : end.nextSibling;
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
if (cursor !== null && sameNode(cursor, node)) {
|
|
854
|
+
if (cursor.nodeType === 1) {
|
|
855
|
+
patchAttributes(cursor as Element, node as Element);
|
|
856
|
+
morphChildren(cursor, node, context);
|
|
857
|
+
} else if (cursor.nodeValue !== node.nodeValue) {
|
|
858
|
+
cursor.nodeValue = node.nodeValue;
|
|
859
|
+
}
|
|
860
|
+
cursor = cursor.nextSibling;
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
current.insertBefore(document.importNode(node, true), cursor);
|
|
864
|
+
}
|
|
865
|
+
// What is left is what the server no longer sends. An occurrence among it is
|
|
866
|
+
// kept in the tree for now: it may still be placed elsewhere.
|
|
867
|
+
while (cursor !== null) {
|
|
868
|
+
const standing = occurrenceAt(context, cursor);
|
|
869
|
+
if (standing !== null) {
|
|
870
|
+
cursor = standing.end.nextSibling;
|
|
871
|
+
continue;
|
|
872
|
+
}
|
|
873
|
+
const gone = cursor;
|
|
874
|
+
cursor = cursor.nextSibling;
|
|
875
|
+
current.removeChild(gone);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** Apply a new answer to one mount: morph the region, then bring the occurrences up to date. */
|
|
880
|
+
function update(site: Mount, payload: FramePayload, markup: string): void {
|
|
881
|
+
const next = document.createElement("template");
|
|
882
|
+
next.innerHTML = markup;
|
|
883
|
+
const keep = new Map<string, Occurrence>();
|
|
884
|
+
for (const occurrence of site.occurrences.values()) {
|
|
885
|
+
if (occurrence !== DEAD) keep.set(occurrence.key, occurrence);
|
|
886
|
+
}
|
|
887
|
+
const context: MorphContext = { mount: site, payload, keep, used: new Set() };
|
|
888
|
+
withoutClaim(() => {
|
|
889
|
+
morphChildren(site.host, next.content, context);
|
|
890
|
+
setPayload(site.host, payload);
|
|
891
|
+
});
|
|
892
|
+
const occurrences = new Map<Comment, Occurrence>();
|
|
893
|
+
for (const occurrence of context.used) {
|
|
894
|
+
occurrences.set(occurrence.start, occurrence);
|
|
895
|
+
const record = recordAt(payload, slotIndex(occurrence.start.data));
|
|
896
|
+
if (record === undefined) continue;
|
|
897
|
+
if (record.args !== undefined) occurrence.setArgs(decodeWire(record.args));
|
|
898
|
+
if (occurrence.region !== null && record.region !== undefined) {
|
|
899
|
+
const region = document.createElement("template");
|
|
900
|
+
region.innerHTML = record.region;
|
|
901
|
+
withoutClaim(() => morphChildren(occurrence.region!, region.content, context));
|
|
902
|
+
for (const nested of context.used) occurrences.set(nested.start, nested);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
for (const occurrence of site.occurrences.values()) {
|
|
906
|
+
if (occurrence === DEAD || context.used.has(occurrence)) continue;
|
|
907
|
+
occurrence.dispose();
|
|
908
|
+
for (const node of [
|
|
909
|
+
occurrence.start,
|
|
910
|
+
...between(occurrence.start, occurrence.end),
|
|
911
|
+
occurrence.end,
|
|
912
|
+
]) {
|
|
913
|
+
node.parentNode?.removeChild(node);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
site.occurrences.clear();
|
|
917
|
+
for (const [start, occurrence] of occurrences) site.occurrences.set(start, occurrence);
|
|
918
|
+
fillAll(site, payload);
|
|
919
|
+
bindAll(site, payload);
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// ── assets ────────────────────────────────────────────────────────────────
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* The region's stylesheets, loaded before it is shown: a region revealed
|
|
926
|
+
* before its styles is the flash a server render exists to prevent. Each is
|
|
927
|
+
* the element `useHead` takes over when the frame mounts.
|
|
928
|
+
*/
|
|
929
|
+
async function loadStylesheets(head: readonly HeadTag[]): Promise<void> {
|
|
930
|
+
const loading: Promise<void>[] = [];
|
|
931
|
+
for (const tag of head) {
|
|
932
|
+
const props = tag.props ?? {};
|
|
933
|
+
if (tag.tag !== "link" || props.rel !== "stylesheet" || typeof props.href !== "string")
|
|
934
|
+
continue;
|
|
935
|
+
const key = `link:stylesheet:${props.href}`;
|
|
936
|
+
let present = false;
|
|
937
|
+
for (const candidate of document.head.querySelectorAll("[data-bh]")) {
|
|
938
|
+
if (candidate.getAttribute("data-bh") === key) present = true;
|
|
939
|
+
}
|
|
940
|
+
if (present) continue;
|
|
941
|
+
const link = document.createElement("link");
|
|
942
|
+
link.rel = "stylesheet";
|
|
943
|
+
link.href = props.href;
|
|
944
|
+
link.setAttribute("data-bh", key);
|
|
945
|
+
loading.push(
|
|
946
|
+
new Promise<void>((resolve) => {
|
|
947
|
+
link.addEventListener("load", () => resolve(), { once: true });
|
|
948
|
+
link.addEventListener("error", () => resolve(), { once: true });
|
|
949
|
+
}),
|
|
950
|
+
);
|
|
951
|
+
// In front of the build's atoms, which win a property against a `css`
|
|
952
|
+
// block of the same specificity by being linked after it.
|
|
953
|
+
const atoms = document.head.querySelector('link[rel="stylesheet"][data-barq-atoms]');
|
|
954
|
+
if (atoms === null) document.head.appendChild(link);
|
|
955
|
+
else atoms.before(link);
|
|
956
|
+
}
|
|
957
|
+
await Promise.all(loading);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// ── the wire ──────────────────────────────────────────────────────────────
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Read a frame answer and apply it: the component for its address, the same
|
|
964
|
+
* one every time, with every place it is mounted morphed to the new markup
|
|
965
|
+
* once the region's stylesheets have loaded.
|
|
966
|
+
*/
|
|
967
|
+
export async function applyFrameResponse(response: Response): Promise<FrameComponent> {
|
|
968
|
+
const template = document.createElement("template");
|
|
969
|
+
template.innerHTML = await response.text();
|
|
970
|
+
return applyFrameMarkup(template.content.firstElementChild);
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** A frame's markup as text, a live event's, applied as a frame answer is. */
|
|
974
|
+
export function applyFrameText(markup: string): Promise<FrameComponent> {
|
|
975
|
+
const template = document.createElement("template");
|
|
976
|
+
template.innerHTML = markup;
|
|
977
|
+
return applyFrameMarkup(template.content.firstElementChild);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** One frame's markup, applied to every place its address is mounted. */
|
|
981
|
+
async function applyFrameMarkup(host: Element | null): Promise<FrameComponent> {
|
|
982
|
+
const address = host?.getAttribute("data-frame") ?? null;
|
|
983
|
+
const payload = host === null ? null : payloadOf(host);
|
|
984
|
+
if (host === null || address === null || payload === null) {
|
|
985
|
+
throw new Error(
|
|
986
|
+
"[barq] A server function answered with a frame whose markup has no `barq-frame` element and payload, so there is nothing to apply. " +
|
|
987
|
+
"The server and this page were built from different versions: reload the page.",
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
if (payload.v !== FRAME_VERSION) {
|
|
991
|
+
throw new Error(
|
|
992
|
+
`[barq] A server function answered with frame version ${payload.v}, and this page reads version ${FRAME_VERSION}. ` +
|
|
993
|
+
"The server was deployed after this page loaded: reload the page.",
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
host.firstElementChild?.remove();
|
|
997
|
+
const markup = host.innerHTML;
|
|
998
|
+
const id = address.slice(0, address.lastIndexOf("#"));
|
|
999
|
+
const state = stateFor({ id, address });
|
|
1000
|
+
await loadStylesheets(payload.head);
|
|
1001
|
+
state.payload = payload;
|
|
1002
|
+
state.markup = markup;
|
|
1003
|
+
state.setHead(payload.head);
|
|
1004
|
+
for (const placed of state.mounts) update(placed, payload, markup);
|
|
1005
|
+
document.dispatchEvent(new CustomEvent(FRAME_APPLIED_EVENT, { detail: { address } }));
|
|
1006
|
+
return state.component;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* What a mutation sends so its answer can carry the regions it changed: every
|
|
1011
|
+
* mounted frame's function and arguments, up to the budget, or `null` with
|
|
1012
|
+
* none mounted.
|
|
1013
|
+
*/
|
|
1014
|
+
export function mountedFramesHeader(): string | null {
|
|
1015
|
+
const out: { id: string; args: unknown }[] = [];
|
|
1016
|
+
for (const state of FRAMES.values()) {
|
|
1017
|
+
if (state.mounts.size === 0 || state.payload === null) continue;
|
|
1018
|
+
out.push({ id: state.ref.id, args: state.payload.args });
|
|
1019
|
+
if (out.length === FRAMES_BUDGET) break;
|
|
1020
|
+
}
|
|
1021
|
+
return out.length === 0 ? null : JSON.stringify(out);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* A mutation's single-flight answer: each region it carries applied where it
|
|
1026
|
+
* is mounted, then the value, which is what the caller is handed.
|
|
1027
|
+
*/
|
|
1028
|
+
export async function applyFlight(response: Response): Promise<unknown> {
|
|
1029
|
+
const template = document.createElement("template");
|
|
1030
|
+
template.innerHTML = await response.text();
|
|
1031
|
+
const script = template.content.firstElementChild;
|
|
1032
|
+
if (
|
|
1033
|
+
script === null ||
|
|
1034
|
+
script.localName !== "script" ||
|
|
1035
|
+
script.getAttribute("type") !== FLIGHT_TYPE
|
|
1036
|
+
) {
|
|
1037
|
+
throw new Error(
|
|
1038
|
+
"[barq] A server function answered with a single flight whose value script is missing, so there is no value to hand the caller. " +
|
|
1039
|
+
"The server and this page were built from different versions: reload the page.",
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
const value = decodeWire(JSON.parse(script.textContent ?? "null"));
|
|
1043
|
+
for (const host of template.content.children) {
|
|
1044
|
+
if (host.localName === FRAME_TAG) await applyFrameMarkup(host);
|
|
1045
|
+
}
|
|
1046
|
+
return value;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** Forget every frame, for a test that renders more than one page. */
|
|
1050
|
+
export function resetFrames(): void {
|
|
1051
|
+
FRAMES.clear();
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// ── live ──────────────────────────────────────────────────────────────────
|
|
1055
|
+
//
|
|
1056
|
+
// `live`'s loop, here because a frame the page was served through `live`
|
|
1057
|
+
// connects through it as well as a `live` call does.
|
|
1058
|
+
|
|
1059
|
+
/** What the loop says about its connection. */
|
|
1060
|
+
export type LiveStatus = "connected" | "reconnecting" | "closed";
|
|
1061
|
+
|
|
1062
|
+
export interface LiveIterable<T> extends AsyncIterable<T> {
|
|
1063
|
+
/** Told `"connected"` per connection, `"reconnecting"` with the error per death, `"closed"` at the end. */
|
|
1064
|
+
onstatus?: (status: LiveStatus, error?: unknown) => void;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
interface ServerEvent {
|
|
1068
|
+
readonly event: string;
|
|
1069
|
+
readonly id: string | null;
|
|
1070
|
+
readonly data: string;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** The events of a `text/event-stream` body, as the spec frames them. */
|
|
1074
|
+
async function* eventsOf(body: ReadableStream<Uint8Array>): AsyncGenerator<ServerEvent> {
|
|
1075
|
+
const reader = body.getReader();
|
|
1076
|
+
const decoder = new TextDecoder();
|
|
1077
|
+
let pending = "";
|
|
1078
|
+
let event = "message";
|
|
1079
|
+
let id: string | null = null;
|
|
1080
|
+
let data: string[] = [];
|
|
1081
|
+
try {
|
|
1082
|
+
for (;;) {
|
|
1083
|
+
const { done, value } = await reader.read();
|
|
1084
|
+
pending += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
1085
|
+
let end = pending.search(/\r\n|\r|\n/);
|
|
1086
|
+
while (end !== -1) {
|
|
1087
|
+
const line = pending.slice(0, end);
|
|
1088
|
+
pending = pending.slice(end + (pending.startsWith("\r\n", end) ? 2 : 1));
|
|
1089
|
+
if (line === "") {
|
|
1090
|
+
if (data.length > 0 || event !== "message") yield { event, id, data: data.join("\n") };
|
|
1091
|
+
event = "message";
|
|
1092
|
+
data = [];
|
|
1093
|
+
} else if (!line.startsWith(":")) {
|
|
1094
|
+
const colon = line.indexOf(":");
|
|
1095
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
1096
|
+
const text = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
1097
|
+
if (field === "data") data.push(text);
|
|
1098
|
+
else if (field === "event") event = text;
|
|
1099
|
+
else if (field === "id") id = text;
|
|
1100
|
+
}
|
|
1101
|
+
end = pending.search(/\r\n|\r|\n/);
|
|
1102
|
+
}
|
|
1103
|
+
if (done) return;
|
|
1104
|
+
}
|
|
1105
|
+
} finally {
|
|
1106
|
+
void reader.cancel().catch(() => {});
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/** Statuses that say "ask again" even though they refuse this time. */
|
|
1111
|
+
const RETRY = new Set([408, 425, 429]);
|
|
1112
|
+
|
|
1113
|
+
/** How long to wait before the next connection, the nth failure in a row. */
|
|
1114
|
+
function pause(failures: number, signal: AbortSignal): Promise<void> {
|
|
1115
|
+
const ms = Math.min(30_000, 250 * 2 ** failures);
|
|
1116
|
+
return new Promise<void>((resolve) => {
|
|
1117
|
+
const timer = setTimeout(done, ms);
|
|
1118
|
+
function done(): void {
|
|
1119
|
+
clearTimeout(timer);
|
|
1120
|
+
globalThis.removeEventListener?.("online", done);
|
|
1121
|
+
signal.removeEventListener("abort", done);
|
|
1122
|
+
resolve();
|
|
1123
|
+
}
|
|
1124
|
+
globalThis.addEventListener?.("online", done, { once: true });
|
|
1125
|
+
signal.addEventListener("abort", done, { once: true });
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
export type LiveStub = Stub & {
|
|
1130
|
+
readonly [LIVE_CALL]: (options: unknown, live: LiveRequest) => Promise<Response>;
|
|
1131
|
+
};
|
|
1132
|
+
|
|
1133
|
+
/** The reconnecting iteration of one live call. */
|
|
1134
|
+
export function liveIterable(stub: LiveStub, options: unknown): LiveIterable<unknown> {
|
|
1135
|
+
const iterable: LiveIterable<unknown> = {
|
|
1136
|
+
[Symbol.asyncIterator]: (): AsyncIterator<unknown> => {
|
|
1137
|
+
const controller = new AbortController();
|
|
1138
|
+
const running = loop(stub, options, iterable, controller);
|
|
1139
|
+
return {
|
|
1140
|
+
next: () => running.next(),
|
|
1141
|
+
// The connection is ended here, not when the generator gets round to
|
|
1142
|
+
// it: one waiting on a body that sends nothing would never get there.
|
|
1143
|
+
return: (value?: unknown) => {
|
|
1144
|
+
controller.abort();
|
|
1145
|
+
return running.return(value);
|
|
1146
|
+
},
|
|
1147
|
+
};
|
|
1148
|
+
},
|
|
1149
|
+
};
|
|
1150
|
+
return iterable;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
async function* loop(
|
|
1154
|
+
stub: LiveStub,
|
|
1155
|
+
options: unknown,
|
|
1156
|
+
told: LiveIterable<unknown>,
|
|
1157
|
+
controller: AbortController,
|
|
1158
|
+
): AsyncGenerator {
|
|
1159
|
+
let lastEventId: string | null = null;
|
|
1160
|
+
let failures = 0;
|
|
1161
|
+
let connected = false;
|
|
1162
|
+
try {
|
|
1163
|
+
for (;;) {
|
|
1164
|
+
let response: Response;
|
|
1165
|
+
try {
|
|
1166
|
+
response = await stub[LIVE_CALL](options, { lastEventId, signal: controller.signal });
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
if (controller.signal.aborted) return;
|
|
1169
|
+
if (!connected) throw error;
|
|
1170
|
+
told.onstatus?.("reconnecting", error);
|
|
1171
|
+
await pause(failures++, controller.signal);
|
|
1172
|
+
continue;
|
|
1173
|
+
}
|
|
1174
|
+
if (!response.ok || response.body === null) {
|
|
1175
|
+
const retries = RETRY.has(response.status) || response.headers.has("retry-after");
|
|
1176
|
+
const error = new ServerFnError(stub.meta.id, response.status, response);
|
|
1177
|
+
if (!connected || (!retries && response.status >= 400 && response.status < 500))
|
|
1178
|
+
throw error;
|
|
1179
|
+
told.onstatus?.("reconnecting", error);
|
|
1180
|
+
await pause(failures++, controller.signal);
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
connected = true;
|
|
1184
|
+
failures = 0;
|
|
1185
|
+
told.onstatus?.("connected");
|
|
1186
|
+
let yielded: unknown = undefined;
|
|
1187
|
+
let complete = false;
|
|
1188
|
+
let died: unknown = new Error(
|
|
1189
|
+
`[barq] The live connection of ${JSON.stringify(stub.meta.id)} ended before it was complete.`,
|
|
1190
|
+
);
|
|
1191
|
+
try {
|
|
1192
|
+
for await (const event of eventsOf(response.body)) {
|
|
1193
|
+
if (event.event === "complete") {
|
|
1194
|
+
complete = true;
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
if (event.id !== null) lastEventId = event.id;
|
|
1198
|
+
const data = JSON.parse(event.data) as unknown;
|
|
1199
|
+
if (event.event === "frame") {
|
|
1200
|
+
const component = await applyFrameText(data as string);
|
|
1201
|
+
if (component !== yielded) {
|
|
1202
|
+
yielded = component;
|
|
1203
|
+
yield component;
|
|
1204
|
+
}
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
yield decodeWire(data);
|
|
1208
|
+
}
|
|
1209
|
+
} catch (error) {
|
|
1210
|
+
died = error;
|
|
1211
|
+
}
|
|
1212
|
+
if (complete || controller.signal.aborted) return;
|
|
1213
|
+
told.onstatus?.("reconnecting", died);
|
|
1214
|
+
await pause(failures++, controller.signal);
|
|
1215
|
+
}
|
|
1216
|
+
} finally {
|
|
1217
|
+
controller.abort();
|
|
1218
|
+
told.onstatus?.("closed");
|
|
1219
|
+
}
|
|
1220
|
+
}
|