@solidjs/web 2.0.0-rc.14 → 2.0.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +475 -591
  3. package/dist/server.js +459 -489
  4. package/dist/server.observe.js +459 -498
  5. package/dist/web.dev.js +206 -220
  6. package/dist/web.js +196 -208
  7. package/dist/web.observe.js +206 -213
  8. package/frames/dist/client.dev.js +664 -643
  9. package/frames/dist/client.js +593 -582
  10. package/frames/dist/client.observe.js +624 -589
  11. package/frames/dist/regions.js +43 -2
  12. package/frames/dist/server.dev.js +578 -450
  13. package/frames/dist/server.js +578 -397
  14. package/frames/dist/server.observe.js +578 -397
  15. package/frames/dist/trace.js +4 -1
  16. package/frames/dist/wire.js +371 -6
  17. package/package.json +13 -13
  18. package/serialization/dist/decode.js +11 -9
  19. package/serialization/dist/serialization.js +11 -9
  20. package/serialization/types/serializer-decode.d.ts +2 -2
  21. package/server-functions/dist/client.dev.js +5 -2
  22. package/server-functions/dist/client.js +3 -2
  23. package/server-functions/dist/client.observe.js +5 -2
  24. package/server-functions/dist/rich-args.js +33 -1
  25. package/server-functions/dist/server.dev.js +218 -35
  26. package/server-functions/dist/server.js +218 -35
  27. package/server-functions/dist/server.observe.js +218 -35
  28. package/skills/server-components/SKILL.md +74 -185
  29. package/types/client.d.ts +112 -10
  30. package/types/constants.d.ts +2 -1
  31. package/types/frames/assets-tier.d.ts +2 -2
  32. package/types/frames/client.d.ts +8 -3
  33. package/types/frames/frame-client.d.ts +121 -157
  34. package/types/frames/frame-morph.d.ts +28 -0
  35. package/types/frames/frame-sink.d.ts +13 -9
  36. package/types/frames/frame-transport.d.ts +30 -1
  37. package/types/frames/regions-tier.d.ts +15 -0
  38. package/types/frames/serializer-decode.d.ts +2 -2
  39. package/types/frames/server.d.ts +1 -53
  40. package/types/frames/wire-tier.d.ts +54 -1
  41. package/types/head.d.ts +1 -0
  42. package/types/index.d.ts +57 -50
  43. package/types/index.server.d.ts +3 -27
  44. package/types/jsx.d.ts +14 -17
  45. package/types/observe.d.ts +14 -7
  46. package/types/render.d.ts +3 -1
  47. package/types/response.d.ts +31 -8
  48. package/types/serializer-decode.d.ts +2 -2
  49. package/types/server-functions/argument-codec.d.ts +21 -0
  50. package/types/server-functions/client.d.ts +18 -5
  51. package/types/server-functions/server.d.ts +6 -2
  52. package/types/server-functions/shared.d.ts +19 -0
  53. package/types/server-mock.d.ts +9 -2
  54. package/types/server-observe.d.ts +3 -2
  55. package/types/server.d.ts +124 -67
  56. package/frames/dist/bind.dev.js +0 -326
  57. package/frames/dist/bind.js +0 -295
  58. package/types/frames/bind-tier.d.ts +0 -60
@@ -1,10 +1,9 @@
1
- import { getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, createSignal, createOwner } from 'solid-js';
2
- import { insert } from '@solidjs/web';
1
+ import { getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, onHydrationEnd, createSignal, createOwner } from 'solid-js';
2
+ import { installServerComponentHydration, insert } from '@solidjs/web';
3
3
  import { LIVE_WIRE, ChunkReader, frameAddress, SINGLE_FLIGHT_HEADER, deserializeStream, getServerFunctionsCodec, createChunk, deliverFlightData, ERROR_HEADER, hasFlightMetadata, configureServerFunctionsClient } from '@solidjs/web/server-functions/client';
4
- import { sharedConfig, createLoadingBoundary } from 'solid-js/internal';
4
+ import { setSignalIdentities, sharedConfig, createLoadingBoundary, setWriteHook, signalName, storeName } from 'solid-js/internal';
5
5
 
6
6
  const ELEMENT_NODE = 1;
7
- const TEXT_NODE = 3;
8
7
  const COMMENT_NODE = 8;
9
8
  const CLAIM_SEAM = Symbol.for("solid.element-claims");
10
9
  const CLAIMED_ELEMENTS = "a[href], form[action]";
@@ -12,110 +11,29 @@ function claimHandlers() {
12
11
  const handlers = globalThis[CLAIM_SEAM];
13
12
  return handlers !== undefined && handlers.length !== 0 ? handlers : undefined;
14
13
  }
15
- function claimNode(handlers, el) {
14
+ function claimNode(handlers, el, adopter) {
15
+ if (adopter) {
16
+ const by = adoptedBy.get(el);
17
+ if (by && liveFrames.has(by)) return;
18
+ adoptedBy.set(el, adopter);
19
+ }
16
20
  for (let i = 0; i < handlers.length; i++) handlers[i](el);
17
21
  }
18
- const claimedAttr = name => name === "href" || name === "action";
19
- function claimTree(handlers, root) {
22
+ function claimTree(handlers, root, adopter) {
20
23
  const isElement = root.nodeType === ELEMENT_NODE;
21
24
  if (!isElement && root.nodeType !== 11 ) return;
22
- if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root);
25
+ if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root, adopter);
23
26
  const found = root.querySelectorAll(CLAIMED_ELEMENTS);
24
- for (let i = 0; i < found.length; i++) claimNode(handlers, found[i]);
27
+ for (let i = 0; i < found.length; i++) claimNode(handlers, found[i], adopter);
25
28
  }
29
+ const adoptedBy = new WeakMap();
26
30
  const placeholderId = name => `pl-${name}`;
27
31
  const SLOT_START = /^slot:(.+):start$/;
28
32
  const SLOT_END = /^slot:(.+):end$/;
29
33
  const slotEnd = id => `slot:${id}:end`;
30
- const SLOT_MARKER = "_s:";
31
- const SLOT_TEXT = SLOT_MARKER + "t=";
32
- const SLOT_TEXT_END = "/" + SLOT_MARKER + "t";
33
- const isTextStart = n => n.nodeType === COMMENT_NODE && n.data.startsWith(SLOT_TEXT);
34
- function hasSlotMarker(el) {
35
- const attrs = el.attributes;
36
- for (let i = 0; i < attrs.length; i++) if (attrs[i].name.startsWith(SLOT_MARKER)) return true;
37
- return false;
38
- }
39
34
  function isAsyncValue(v) {
40
35
  return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
41
36
  }
42
- function chunkToRecords(chunk) {
43
- switch (chunk.type) {
44
- case "start":
45
- case "data":
46
- return {};
47
- case "html":
48
- return {
49
- "": {
50
- kind: "html",
51
- value: chunk.html,
52
- digest: chunk.digest,
53
- holes: chunk.holes
54
- }
55
- };
56
- case "fragment":
57
- return {
58
- [`seg:${chunk.key}`]: {
59
- kind: "html",
60
- value: chunk.html,
61
- digest: chunk.digest,
62
- holes: chunk.holes
63
- }
64
- };
65
- case "reveal":
66
- {
67
- const records = {};
68
- const gate = chunk.fallback ? "fallback" : "reveal";
69
- for (const key of chunk.keys) records[`seg:${key}:${gate}`] = true;
70
- return records;
71
- }
72
- case "assets":
73
- return {
74
- [`seg:${chunk.key}:assets`]: chunk
75
- };
76
- case "slot":
77
- return {
78
- [`slot:${chunk.key}`]: {
79
- kind: "slot",
80
- args: chunk.args
81
- }
82
- };
83
- case "hole":
84
- return {
85
- [`hole:${chunk.key}`]: {
86
- kind: "html",
87
- value: chunk.html,
88
- digest: chunk.digest,
89
- holes: chunk.holes
90
- }
91
- };
92
- case "attr":
93
- return {
94
- [`attr:${chunk.key}`]: {
95
- kind: "attrs",
96
- value: chunk.attrs,
97
- removed: chunk.removed,
98
- digest: chunk.digest
99
- }
100
- };
101
- case "ops":
102
- return Object.assign({}, ...chunk.ops.map(chunkToRecords));
103
- case "complete":
104
- return {
105
- ":complete": true,
106
- ":bound": chunk.bound
107
- };
108
- case "error":
109
- if (!chunk.key) return {
110
- ":error": chunk.error
111
- };
112
- return {
113
- [`${/^lha?:/.test(chunk.key) ? "hole" : "seg"}:${chunk.key}:error`]: chunk.error
114
- };
115
- default:
116
- return {};
117
- }
118
- }
119
37
  function createFrameHost(options = {}) {
120
38
  const frames = new Map();
121
39
  const stores = new Map();
@@ -144,15 +62,16 @@ function createFrameHost(options = {}) {
144
62
  }
145
63
  const assets = records["seg::assets"];
146
64
  const previous = assets && store.records["seg::assets"];
147
- if (!previous || previous === assets) {
148
- Object.assign(store.records, records);
149
- } else {
65
+ Object.assign(store.records, records);
66
+ if (previous && previous !== assets) {
67
+ const merged = {
68
+ ...previous
69
+ };
150
70
  for (const name in assets) {
151
71
  const values = assets[name];
152
- if (Array.isArray(values)) {
153
- previous[name] ? previous[name].push(...values) : previous[name] = values;
154
- }
72
+ if (Array.isArray(values)) merged[name] = previous[name] ? previous[name].concat(values) : values;
155
73
  }
74
+ store.records["seg::assets"] = merged;
156
75
  }
157
76
  return true;
158
77
  };
@@ -225,34 +144,43 @@ function createFrameHost(options = {}) {
225
144
  landings.delete(id);
226
145
  }
227
146
  },
228
- apply(chunk) {
229
- if (chunk.type === "data") {
230
- const store = stores.get(chunk.id);
147
+ apply(msg) {
148
+ if (msg.type === "data") {
149
+ const store = stores.get(msg.id);
231
150
  const current = store && store.version;
232
- if (store && chunk.version < current) return;
233
- options.applyData && options.applyData(chunk, current);
151
+ if (store && msg.version < current) return;
152
+ options.applyData && options.applyData(msg, current);
234
153
  return;
235
154
  }
236
- const records = chunkToRecords(chunk);
237
- const store = storeFor(chunk.id);
238
- if (!write(store, chunk.version, records)) return;
239
- if (chunk.type === "slot") {
240
- const key = `slot:${chunk.key}`;
241
- settleArgs(store, key, records[key], chunk);
155
+ let records = msg.r || {};
156
+ let slots;
157
+ for (const key in records) if (key.startsWith("slot:")) {
158
+ if (!slots) records = {
159
+ ...records
160
+ };
161
+ (slots ??= []).push(key);
162
+ records[key] = {
163
+ ...records[key]
164
+ };
242
165
  }
166
+ const store = storeFor(msg.id);
167
+ if (!write(store, msg.version, records)) return;
168
+ if (slots) for (const key of slots) settleArgs(store, key, records[key], msg);
243
169
  let r = records;
244
- if (chunk.type === "start") store.open = true;else if (lands(records)) {
170
+ if (msg.type === "start") {
171
+ store.open = true;
172
+ } else if (lands(records)) {
245
173
  store.open = false;
246
174
  store.shown = r = store.records;
247
- store.shownVersion = chunk.version;
248
- const landed = landings.get(chunk.id);
175
+ store.shownVersion = msg.version;
176
+ const landed = landings.get(msg.id);
249
177
  if (landed && !(":complete" in records && ":error" in r)) {
250
- landings.delete(chunk.id);
178
+ landings.delete(msg.id);
251
179
  ":error" in records ? landed.j(records[":error"]) : landed.r();
252
180
  }
253
181
  }
254
- applyTo(chunk.id, chunk.version, r);
255
- if (":complete" in records || ":error" in records) options.closeData && options.closeData(chunk.id, chunk.version, records[":error"]);
182
+ applyTo(msg.id, msg.version, r);
183
+ if (":complete" in records || ":error" in records) options.closeData && options.closeData(msg.id, msg.version, records[":error"]);
256
184
  },
257
185
  landing(id) {
258
186
  const store = stores.get(id);
@@ -265,14 +193,17 @@ function createFrameHost(options = {}) {
265
193
  }
266
194
  return wait.p;
267
195
  },
268
- preview(chunk) {
269
- if (chunk.type !== "slot") return;
270
- const set = frames.get(chunk.id);
271
- if (!set) return;
272
- const records = chunkToRecords(chunk);
273
- const key = `slot:${chunk.key}`;
274
- settleArgs(storeFor(chunk.id), key, records[key], chunk);
275
- for (const frame of set) frame.preview && frame.preview(records);
196
+ preview(msg) {
197
+ const set = frames.get(msg.id);
198
+ if (!set || !msg.r) return;
199
+ let records;
200
+ for (const key in msg.r) if (key.startsWith("slot:")) {
201
+ const record = (records ??= {})[key] = {
202
+ ...msg.r[key]
203
+ };
204
+ settleArgs(storeFor(msg.id), key, record, msg);
205
+ }
206
+ if (records) for (const frame of set) frame.preview && frame.preview(records);
276
207
  },
277
208
  get(id) {
278
209
  const set = frames.get(id);
@@ -290,6 +221,26 @@ const FRAME_APPLIED_EVENT = "frame:applied";
290
221
  const tierLoaders = {};
291
222
  const tierLoads = {};
292
223
  const liveFrames = new Set();
224
+ let deferDriver = null;
225
+ function setDeferDriver(driver) {
226
+ deferDriver = driver;
227
+ }
228
+ function deferredFrames() {
229
+ return [...liveFrames].filter(f => f.deferred);
230
+ }
231
+ function releaseDeferHolds() {
232
+ for (const f of liveFrames) f.releaseDeferHold();
233
+ }
234
+ function hasSlotRange(root) {
235
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
236
+ for (let n; n = w.nextNode();) if (n.data.startsWith("slot:")) return true;
237
+ return false;
238
+ }
239
+ function liveFrameAt(node) {
240
+ let hit;
241
+ for (const f of liveFrames) if (f.el.contains(node) && (!hit || hit.el.contains(f.el))) hit = f;
242
+ return hit;
243
+ }
293
244
  function prepareTier(name) {
294
245
  let load = tierLoads[name];
295
246
  if (!load) {
@@ -305,6 +256,7 @@ function prepareTier(name) {
305
256
  }
306
257
  return load;
307
258
  }
259
+ const prepareMorph = () => liveFrames.size && prepareTier("wire");
308
260
  const tierReady = name => !tierLoaders[name] || prepareTier(name).r;
309
261
  const needsRegions = record => record.regions && !tierReady("regions");
310
262
  const carriesTrace = value => value != null && typeof value === "object" && (value.$tr != null || Object.values(value).some(carriesTrace));
@@ -315,10 +267,14 @@ class FrameImpl {
315
267
  #outer;
316
268
  #version;
317
269
  #store = Object.create(null);
270
+ #content = new Set();
318
271
  #appliedRoot;
319
272
  #appliedError;
320
273
  #hasContent = false;
321
274
  #appliedHoles = new Map();
275
+ #liveTargets = new Map();
276
+ #shows = {};
277
+ #liveMount;
322
278
  #slots;
323
279
  #mountedSlots = new Set();
324
280
  #slotCleanups = new Map();
@@ -326,11 +282,19 @@ class FrameImpl {
326
282
  #slotUpdaters = new Map();
327
283
  #hold;
328
284
  #heldRecords = new Map();
285
+ #found;
286
+ #waiting = new Set();
329
287
  #disposed = false;
330
- #claimTree = (node, direct) => {
288
+ #defers = false;
289
+ #deferred = false;
290
+ #deferFound;
291
+ #deferWaiting = false;
292
+ #deferMounted = new Map();
293
+ #deferHold;
294
+ #claimTree = (node, direct, adopter) => {
331
295
  const handlers = claimHandlers();
332
296
  if (!handlers) return;
333
- this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node));
297
+ this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node, adopter));
334
298
  };
335
299
  #scoped(fn) {
336
300
  const scope = this.#options.ownerScope;
@@ -345,11 +309,16 @@ class FrameImpl {
345
309
  if (options.adopt) {
346
310
  this.#hasContent = true;
347
311
  this.#claimContent();
312
+ this.#defers = !!deferDriver && !!(options.defer || this.#outer?.defers);
313
+ this.#deferred = this.#defers && !!(this.#slots || this.#outer) && hasSlotRange(element);
348
314
  }
349
315
  if (options.host && options.id !== undefined) {
350
316
  options.host.register(options.id, this);
351
317
  }
352
- if (options.adopt && this.#version === undefined) this.#syncSlots();
318
+ if (this.#deferred) {
319
+ this.#deferHold = options.hold?.();
320
+ deferDriver(this);
321
+ } else if (options.adopt && this.#version === undefined) this.#syncSlots();
353
322
  }
354
323
  #applied(version, reason) {
355
324
  this.#options.onApply?.({
@@ -389,8 +358,15 @@ class FrameImpl {
389
358
  this.#version = v;
390
359
  this.#resetStreamState();
391
360
  }
392
- for (const key in write.r) this.#store[key] = write.r[key];
393
- this.#flush();
361
+ let only = [];
362
+ for (const key in write.r) {
363
+ const prev = this.#store[key];
364
+ const occurrence = key.slice(5);
365
+ if (this.#deferred && prev?.kind === "slot" && !prev.pending && !this.#mountedSlots.has(occurrence)) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, prev);
366
+ this.#store[key] = write.r[key];
367
+ if (key.startsWith("slot:")) only?.push(occurrence);else this.#content.add(key), only = undefined;
368
+ }
369
+ this.#flush(only?.length ? only : undefined);
394
370
  }
395
371
  preview(records, inherited) {
396
372
  const adopted = new Set();
@@ -412,17 +388,25 @@ class FrameImpl {
412
388
  return adopted;
413
389
  }
414
390
  #resetStreamState() {
391
+ if (this.#hasContent) prepareTier("wire");
392
+ this.#found = undefined;
415
393
  this.#store = Object.create(null);
394
+ this.#content.clear();
416
395
  this.#appliedRoot = this.#appliedError = undefined;
417
396
  this.#appliedHoles.clear();
397
+ this.#liveTargets.clear();
398
+ this.#shows = {};
418
399
  }
419
- #flush() {
400
+ #flush(only) {
420
401
  if (this.#disposed) return;
421
402
  const version = this.#version;
422
403
  const root = this.#store[""];
404
+ const applied = this.#appliedRoot;
423
405
  if (root && root.kind === "html" && root !== this.#appliedRoot) {
424
- const reason = this.#hasContent ? "morph" : "materialize";
425
- this.#applyRoot(root.value);
406
+ const wire = this.#hasContent ? tierReady("wire") : null;
407
+ if (wire === undefined) return;
408
+ const reason = wire ? "morph" : "materialize";
409
+ this.#applyRoot(root.value, wire);
426
410
  this.#appliedRoot = root;
427
411
  this.#recordHave("", root);
428
412
  this.#applied(version, reason);
@@ -432,7 +416,7 @@ class FrameImpl {
432
416
  this.#appliedError = error;
433
417
  this.#applied(version, "error");
434
418
  }
435
- for (const key in this.#store) {
419
+ for (const key of this.#content) {
436
420
  const record = this.#store[key];
437
421
  if (!key.endsWith(":assets") || !record || this.#appliedHoles.get(key) === record) continue;
438
422
  const tier = tierReady("assets");
@@ -440,28 +424,57 @@ class FrameImpl {
440
424
  this.#appliedHoles.set(key, record);
441
425
  tier.apply(record);
442
426
  }
443
- this.#revealSegments();
427
+ const revealed = this.#revealSegments();
444
428
  let morphed = false;
445
- for (const key in this.#store) {
429
+ const index = {};
430
+ let wire;
431
+ for (const key of this.#content) {
446
432
  const record = this.#store[key];
447
433
  if (!record || this.#appliedHoles.get(key) === record) continue;
448
434
  if (key.startsWith("hole:")) {
449
435
  if (key.endsWith(":error")) {
450
436
  this.#appliedHoles.set(key, record);
451
- } else if (this.#applyHole(key.slice(5), record.value)) {
452
- this.#appliedHoles.set(key, record);
453
- this.#recordHave(key.slice(5), record);
454
- morphed = true;
455
- }
456
- } else if (key.startsWith("attr:")) {
457
- if (this.#applyAttrs(key.slice(5), record.value, record.removed)) {
458
- this.#appliedHoles.set(key, record);
459
- this.#recordHave("lha:" + key.slice(5), record);
460
- morphed = true;
437
+ continue;
461
438
  }
439
+ } else if (!key.startsWith("attr:")) continue;
440
+ if (!this.#hasContent || !(wire ??= tierReady("wire"))) continue;
441
+ const name = key.slice(5);
442
+ const attr = key[0] === "a";
443
+ if (!attr) this.#found = undefined;
444
+ if (attr ? wire.attrs(this.#live, name, record) : wire.hole(this.#live, name, record, index)) {
445
+ this.#appliedHoles.set(key, record);
446
+ this.#recordHave(attr ? "lha:" + name : name, record);
447
+ morphed = true;
462
448
  }
463
449
  }
450
+ if (index.r?.size) wire.graft(index.g, index.r);
464
451
  if (morphed) this.#applied(version, "morph");
452
+ if (this.#deferred) {
453
+ if (!morphed && this.#appliedRoot === applied) {
454
+ if (revealed || !only) this.#deferFound = undefined;
455
+ const mounted = only ? new Map() : new Map(this.#deferMounted);
456
+ if (only) for (const id of only) {
457
+ const start = this.#deferMounted.get(id);
458
+ if (start) mounted.set(id, start);else if (!this.#deferFound?.has(id)) this.#deferFound = undefined;
459
+ }
460
+ if (mounted.size) this.#deferWaiting = this.#mountFound(mounted) || this.#deferWaiting;
461
+ return;
462
+ }
463
+ this.#deferred = false;
464
+ this.#deferFound = undefined;
465
+ this.#deferMounted.clear();
466
+ }
467
+ const found = this.#found;
468
+ if (only && found && this.#appliedRoot === applied) {
469
+ const sub = new Map();
470
+ for (const id of only) {
471
+ const start = found.get(id);
472
+ if (!start?.isConnected) return this.#syncSlots();
473
+ sub.set(id, start);
474
+ }
475
+ this.#mountFound(sub);
476
+ return this.#holdIf(this.#waiting.size);
477
+ }
465
478
  this.#syncSlots();
466
479
  }
467
480
  #resolveSlot(prop) {
@@ -481,25 +494,36 @@ class FrameImpl {
481
494
  #syncSlots(root) {
482
495
  if (!this.#slots && !this.#outer) return;
483
496
  const found = new Map();
484
- if (root) collectSlots(root.firstChild, null, found, found);else this.#collectSlots(found, found);
497
+ this.#collectSlots(found, root);
498
+ if (root) this.#found = undefined;else this.#found = found, this.#waiting.clear();
499
+ const waiting = this.#mountFound(found);
500
+ if (!root) {
501
+ for (const occurrence of [...this.#mountedSlots]) {
502
+ if (!found.has(occurrence)) this.#unmountSlot(occurrence);
503
+ }
504
+ this.#holdIf(waiting);
505
+ }
506
+ }
507
+ #holdIf(waiting) {
508
+ if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
509
+ }
510
+ #mountFound(found) {
485
511
  let waiting = false;
486
512
  const R = tierLoads.regions?.r;
487
- const B = tierLoads.bind?.r;
488
513
  for (const [occurrence, start] of found) {
514
+ this.#waiting.delete(occurrence);
489
515
  const callback = this.#resolveSlot(propOf(occurrence));
490
- const consumers = Array.isArray(start) ? start : null;
491
- if (!callback) {
492
- continue;
493
- }
516
+ if (!callback) continue;
494
517
  const record = this.#resolveSlotRecord(occurrence);
495
518
  const mounted = this.#mountedSlots.has(occurrence);
496
519
  if (record === undefined && isCalled(occurrence)) {
497
- waiting ||= !mounted;
520
+ if (!mounted) waiting = true, this.#waiting.add(occurrence);
498
521
  continue;
499
522
  }
500
523
  if (!mounted && record && (record.pending || needsRegions(record) || needsTrace(record.args))) {
501
524
  waiting = true;
502
- if (this.#options.adopt && !consumers) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
525
+ this.#waiting.add(occurrence);
526
+ if (this.#options.adopt) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
503
527
  continue;
504
528
  }
505
529
  if (!mounted) {
@@ -507,12 +531,10 @@ class FrameImpl {
507
531
  this.#heldRecords.delete(occurrence);
508
532
  const mountRecord = held || record;
509
533
  this.#invokeSlot(occurrence, callback, mountRecord, start, this.#options.adopt);
510
- if (consumers) B.sync(this, occurrence, consumers);
511
534
  this.#mountedSlots.add(occurrence);
512
535
  R?.bind(this, occurrence);
513
536
  if (mountRecord === record || !record || record.kind !== "slot") continue;
514
537
  }
515
- if (consumers) B.sync(this, occurrence, consumers);
516
538
  if (record !== this.#slotArgs.get(occurrence)) {
517
539
  if (needsRegions(record) || needsTrace(record.args)) continue;
518
540
  const update = this.#slotUpdaters.get(occurrence);
@@ -527,13 +549,77 @@ class FrameImpl {
527
549
  R?.bind(this, occurrence);
528
550
  }
529
551
  }
530
- if (found.b && !tierReady("bind")) waiting = true;
531
- if (!root) {
532
- for (const occurrence of [...this.#mountedSlots]) {
533
- if (!found.has(occurrence)) this.#unmountSlot(occurrence);
552
+ return waiting;
553
+ }
554
+ get el() {
555
+ return this.#element;
556
+ }
557
+ get defers() {
558
+ return this.#defers;
559
+ }
560
+ get deferred() {
561
+ return this.#deferred;
562
+ }
563
+ mountEnclosing(target) {
564
+ if (!this.#deferred) return false;
565
+ const root = this.#element;
566
+ let outer;
567
+ for (let node = target; node && node !== root; node = node.parentNode) {
568
+ let depth = 0;
569
+ for (let s = node.previousSibling; s; s = s.previousSibling) {
570
+ if (s.nodeType !== COMMENT_NODE || !s.data.startsWith("slot:")) continue;
571
+ if (SLOT_END.test(s.data)) depth++;else if (depth) depth--;else outer = s;
534
572
  }
535
- if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
536
573
  }
574
+ const id = outer && slotStartId(outer);
575
+ if (!id || this.#mountedSlots.has(id)) return false;
576
+ return this.#mountOne(id, outer);
577
+ }
578
+ #mountOne(id, start) {
579
+ const mount = () => {
580
+ this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;
581
+ };
582
+ mount();
583
+ if (!this.#mountedSlots.has(id)) return false;
584
+ this.#deferMounted.set(id, start);
585
+ return true;
586
+ }
587
+ mountDeferred(deadline) {
588
+ if (!this.#deferred) return true;
589
+ let found = this.#deferFound;
590
+ if (!found) {
591
+ found = this.#deferFound = new Map();
592
+ this.#collectSlots(found);
593
+ }
594
+ for (const [id, start] of found) {
595
+ found.delete(id);
596
+ if (this.#mountedSlots.has(id)) this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;else this.#mountOne(id, start);
597
+ if (deadline !== undefined && found.size && performance.now() > deadline) return false;
598
+ }
599
+ this.#deferred = false;
600
+ this.#deferFound = undefined;
601
+ this.#deferMounted.clear();
602
+ if (this.#deferWaiting && !this.#hold) this.#hold = this.#options.hold?.();
603
+ return true;
604
+ }
605
+ mountOccurrence(id) {
606
+ if (!this.#deferred) return false;
607
+ if (this.#mountedSlots.has(id)) return true;
608
+ let found = this.#deferFound;
609
+ if (!found) {
610
+ found = this.#deferFound = new Map();
611
+ this.#collectSlots(found);
612
+ }
613
+ const start = found.get(id);
614
+ if (!start) return false;
615
+ found.delete(id);
616
+ this.#mountOne(id, start);
617
+ return true;
618
+ }
619
+ releaseDeferHold() {
620
+ const release = this.#deferHold;
621
+ this.#deferHold = undefined;
622
+ release && release();
537
623
  }
538
624
  #releaseHold() {
539
625
  const release = this.#hold;
@@ -545,8 +631,7 @@ class FrameImpl {
545
631
  const cleanups = this.#slotCleanups.get(occurrence) ?? [];
546
632
  let existing = [];
547
633
  let end = null;
548
- const positions = Array.isArray(start) ? start : undefined;
549
- if (start && !positions) end = eachInRange(start, occurrence, n => existing.push(n));
634
+ if (start) end = eachInRange(start, occurrence, n => existing.push(n));
550
635
  const ctx = {
551
636
  frame: this.#options.claimScope ?? this.#options.id,
552
637
  key: occurrence,
@@ -558,9 +643,7 @@ class FrameImpl {
558
643
  range: end ? {
559
644
  start,
560
645
  end
561
- } : undefined,
562
- positions,
563
- onRebind: positions ? fn => tierLoads.bind.r.rebinder(this, occurrence, fn) : undefined
646
+ } : undefined
564
647
  };
565
648
  const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record, adopted, start) : {};
566
649
  this.#scoped(() => callback(props, ctx));
@@ -575,7 +658,6 @@ class FrameImpl {
575
658
  this.#removeSlotRecord(key);
576
659
  this.#runSlotCleanups(key);
577
660
  tierLoads.regions?.r?.unmount(this, key);
578
- tierLoads.bind?.r?.unmount(this, key);
579
661
  }
580
662
  #runSlotCleanups(key) {
581
663
  const cleanups = this.#slotCleanups.get(key);
@@ -602,8 +684,8 @@ class FrameImpl {
602
684
  if (regions) tierLoads.regions.r.resolve(this, slotKey, regions, props, claiming && start);
603
685
  return props;
604
686
  }
605
- #collectSlots(found, elements) {
606
- collectSlots(this.#element.firstChild, null, found, elements);
687
+ #collectSlots(found, root) {
688
+ collectSlots(root || this.#element, found);
607
689
  }
608
690
  #findPlaceholder(name, root) {
609
691
  return findPlaceholder((root || this.#element).firstChild, null, placeholderId(name));
@@ -630,7 +712,23 @@ class FrameImpl {
630
712
  this.#resetStreamState();
631
713
  if (host) host.register(id, this);
632
714
  }
715
+ get #live() {
716
+ return this.#liveMount ??= {
717
+ e: this.#element,
718
+ t: this.#liveTargets,
719
+ c: this.#claimTree,
720
+ k: found => this.#collectSlots(found),
721
+ s: () => this.#shows,
722
+ x: (key, record) => (this.#appliedHoles.set(key, record), tierLoads.wire.r.cancel(this.#options.host, this.#options.id)),
723
+ w: false
724
+ };
725
+ }
633
726
  #recordHave(key, record) {
727
+ this.#shows = key ? Object.assign(this.#shows, {
728
+ [key]: record.digest
729
+ }, record.holes) : {
730
+ ...record.holes
731
+ };
634
732
  tierLoads.wire?.r?.have(this, key, record);
635
733
  }
636
734
  dispose() {
@@ -643,12 +741,16 @@ class FrameImpl {
643
741
  this.#disposed = true;
644
742
  liveFrames.delete(this);
645
743
  this.#releaseHold();
744
+ this.releaseDeferHold();
646
745
  for (const key of [...this.#slotCleanups.keys()]) this.#runSlotCleanups(key);
647
746
  for (const key of this.#mountedSlots) this.#removeSlotRecord(key);
648
747
  tierLoads.regions?.r?.unmount(this);
649
748
  this.#mountedSlots.clear();
650
749
  }
651
- #applyRoot(html) {
750
+ #applyRoot(html, wire) {
751
+ this.#found = undefined;
752
+ this.#liveTargets.clear();
753
+ this.#shows = {};
652
754
  const fragment = parseFragment(html);
653
755
  const parent = this.#element;
654
756
  if (!this.#hasContent) {
@@ -660,62 +762,16 @@ class FrameImpl {
660
762
  const claim = this.#claimTree;
661
763
  const ranges = new Map();
662
764
  this.#collectSlots(ranges);
663
- const grafts = [];
664
- reconcileChildren(parent, fragment, null, null, claim, ranges, grafts);
665
- if (ranges.size) for (const root of grafts) flushGrafts(root, ranges);
765
+ wire.morph(parent, fragment, claim, ranges);
666
766
  }
667
767
  }
668
- #applyHole(marker, html) {
669
- if (!this.#hasContent) return false;
670
- const open = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === COMMENT_NODE && n.data === marker);
671
- if (!open) return false;
672
- const close = rangeClose(open, "lh:/" + marker.slice(3));
673
- if (!close) {
674
- return false;
675
- }
676
- reconcileChildren(open.parentNode, parseFragment(html), open, close, this.#claimTree);
677
- return true;
678
- }
679
- #applyAttrs(addr, text, removed) {
680
- if (!this.#hasContent) return false;
681
- const el = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === ELEMENT_NODE && n.getAttribute("data-lha") === addr);
682
- if (!el) return false;
683
- const parsed = parseFragment(`<i${text}></i>`).firstChild;
684
- const keepOpen = preservesOpen(el);
685
- const owned = parsed ? ownedPositions(parsed) : null;
686
- const current = el.attributes;
687
- for (let i = current.length - 1; i >= 0; i--) {
688
- const name = current[i].name;
689
- if (name === "data-lha" || keepOpen && name === "open") continue;
690
- if (!parsed || !parsed.hasAttribute(name)) {
691
- if (applyOwned(el, name, "", owned) !== undefined) continue;
692
- el.removeAttribute(name);
693
- }
694
- }
695
- if (parsed) {
696
- for (let i = 0; i < parsed.attributes.length; i++) {
697
- const {
698
- name,
699
- value
700
- } = parsed.attributes[i];
701
- if (keepOpen && name === "open") continue;
702
- if (applyOwned(el, name, value, owned) !== undefined) continue;
703
- if (el.getAttribute(name) !== value) el.setAttribute(name, value);
704
- }
705
- }
706
- if (removed) for (const name of removed) {
707
- if (keepOpen && name === "open") continue;
708
- if (applyOwned(el, name, "", owned) !== undefined) continue;
709
- el.removeAttribute(name);
710
- }
711
- return true;
712
- }
713
768
  #claimContent() {
714
- for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n);
769
+ for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n, false, this);
715
770
  }
716
771
  #revealSegments(root) {
717
772
  const version = this.#version;
718
- for (const key in this.#store) {
773
+ let revealed = false;
774
+ for (const key of this.#content) {
719
775
  const record = this.#store[key];
720
776
  const name = segmentName(key);
721
777
  if (name === null || !record || this.#appliedHoles.get(key) === record) continue;
@@ -723,9 +779,10 @@ class FrameImpl {
723
779
  this.#appliedHoles.set(key, record);
724
780
  this.#revealSegment(name, root);
725
781
  this.#applied(version, "reveal");
782
+ revealed = true;
726
783
  }
727
784
  }
728
- for (const key in this.#store) {
785
+ for (const key of this.#content) {
729
786
  const m = /^seg:([^:]+):fallback$/.exec(key);
730
787
  if (!m || this.#appliedHoles.has(key) || this.#appliedHoles.has(`seg:${m[1]}`)) continue;
731
788
  if (this.#showFallback(m[1], root)) {
@@ -733,6 +790,7 @@ class FrameImpl {
733
790
  this.#applied(version, "reveal");
734
791
  }
735
792
  }
793
+ return revealed;
736
794
  }
737
795
  #segmentReady(name, root) {
738
796
  const content = this.#store[`seg:${name}`];
@@ -745,6 +803,7 @@ class FrameImpl {
745
803
  #revealSegment(name, root) {
746
804
  const tpl = this.#findPlaceholder(name, root);
747
805
  if (!tpl) return;
806
+ this.#found = undefined;
748
807
  const content = this.#store[`seg:${name}`];
749
808
  const closing = rangeClose(tpl, placeholderId(name));
750
809
  if (!closing) {
@@ -804,9 +863,6 @@ function makeFrameElement(id) {
804
863
  if (id !== undefined) el.setAttribute(FRAME_ID_ATTR, id);
805
864
  return el;
806
865
  }
807
- function isFrameElement(node) {
808
- return node.nodeType === ELEMENT_NODE && node.hasAttribute(FRAME_ID_ATTR);
809
- }
810
866
  function segmentName(key) {
811
867
  const m = /^seg:([^:]+)$/.exec(key);
812
868
  return m ? m[1] : null;
@@ -845,20 +901,6 @@ function rangeClose(start, id) {
845
901
  }
846
902
  return null;
847
903
  }
848
- function findLiveTarget(n, end, test) {
849
- while (n && n !== end) {
850
- if (n.nodeType === ELEMENT_NODE) {
851
- const fid = isFrameElement(n) ? n.getAttribute(FRAME_ID_ATTR) : null;
852
- if (fid === null || fid.includes(".")) {
853
- if (test(n)) return n;
854
- const found = findLiveTarget(n.firstChild, null, test);
855
- if (found) return found;
856
- }
857
- } else if (test(n)) return n;
858
- n = n.nextSibling;
859
- }
860
- return null;
861
- }
862
904
  function findPlaceholder(n, end, id) {
863
905
  while (n && n !== end) {
864
906
  if (isPlaceholderStart(n, id)) return n;
@@ -870,26 +912,25 @@ function findPlaceholder(n, end, id) {
870
912
  }
871
913
  return null;
872
914
  }
873
- function collectSlots(n, end, out, elements) {
874
- while (n && n !== end) {
915
+ function collectSlots(root, out) {
916
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
917
+ let n, p;
918
+ while (n = w.nextNode()) {
919
+ if (!n.data.startsWith("slot:")) continue;
875
920
  const id = slotStartId(n);
876
- if (id !== null) {
877
- if (!out.has(id)) out.set(id, n);
878
- n = afterRange(n, id);
921
+ if (!id) continue;
922
+ for (p = n.parentNode; p !== root; p = p.parentNode) if (p.hasAttribute(FRAME_ID_ATTR)) break;
923
+ if (p !== root) continue;
924
+ if (!out.has(id)) out.set(id, n);
925
+ const end = findMarker(n, slotEnd(id));
926
+ if (end) {
927
+ w.currentNode = end;
879
928
  continue;
880
929
  }
881
- if (elements !== undefined && isTextStart(n)) {
882
- const B = tierLoads.bind?.r;
883
- B ? B.text(n, elements) : elements.b = true;
884
- }
885
- if (n.nodeType === ELEMENT_NODE && !isFrameElement(n)) {
886
- if (elements !== undefined && n.hasAttributes()) {
887
- const B = tierLoads.bind?.r;
888
- B ? B.positions(n, elements) : hasSlotMarker(n) && (elements.b = true);
889
- }
890
- collectSlots(n.firstChild, null, out, elements);
891
- }
892
- n = n.nextSibling;
930
+ p = n.parentNode;
931
+ if (p === root) return;
932
+ while (p.lastChild) p = p.lastChild;
933
+ w.currentNode = p;
893
934
  }
894
935
  }
895
936
  function eachInRange(start, key, cb) {
@@ -907,239 +948,14 @@ function slotStartId(node) {
907
948
  const m = SLOT_START.exec(node.data);
908
949
  return m ? m[1] : null;
909
950
  }
910
- function isSlotMarker(node) {
911
- if (node.nodeType !== COMMENT_NODE) return false;
912
- const data = node.data;
913
- return SLOT_START.test(data) || SLOT_END.test(data);
914
- }
915
- function compatible(a, b) {
916
- if (a.nodeType !== b.nodeType) return false;
917
- if (a.nodeType === ELEMENT_NODE) return a.nodeName === b.nodeName && a.getAttribute("_key") === b.getAttribute("_key");
918
- return a.nodeType === TEXT_NODE || a.nodeType === COMMENT_NODE;
919
- }
920
- function preservesOpen(el) {
921
- const t = el.tagName;
922
- return t === "DETAILS" || t === "DIALOG";
923
- }
924
- const ownedPositions = el => {
925
- const B = tierLoads.bind?.r;
926
- return B ? B.owned(el) : null;
927
- };
928
- const applyOwned = (oldEl, name, value, owned) => owned === null ? undefined : tierLoads.bind.r.apply(oldEl, name, value, owned);
929
- function morphAttributes(oldEl, newEl, claim) {
930
- let reclaim = false;
931
- let changed = false;
932
- const keepOpen = preservesOpen(oldEl);
933
- const owned = ownedPositions(newEl);
934
- const oldAttrs = oldEl.attributes;
935
- for (let i = oldAttrs.length - 1; i >= 0; i--) {
936
- const name = oldAttrs[i].name;
937
- if (keepOpen && name === "open") continue;
938
- if (!newEl.hasAttribute(name)) {
939
- const handled = applyOwned(oldEl, name, "", owned);
940
- if (handled !== undefined) {
941
- changed = handled || changed;
942
- continue;
943
- }
944
- oldEl.removeAttribute(name);
945
- changed = true;
946
- reclaim ||= claimedAttr(name);
947
- }
948
- }
949
- const newAttrs = newEl.attributes;
950
- for (let i = 0; i < newAttrs.length; i++) {
951
- const attr = newAttrs[i];
952
- const name = attr.name;
953
- if (keepOpen && name === "open") continue;
954
- const handled = applyOwned(oldEl, name, attr.value, owned);
955
- if (handled !== undefined) {
956
- changed = handled || changed;
957
- continue;
958
- }
959
- if (oldEl.getAttribute(name) !== attr.value) {
960
- oldEl.setAttribute(name, attr.value);
961
- changed = true;
962
- reclaim ||= claimedAttr(name);
963
- }
964
- }
965
- if (claim && (reclaim || changed && oldEl.matches(CLAIMED_ELEMENTS))) claim(oldEl, true);
966
- }
967
- function morphNode(oldNode, newNode, claim, ranges, grafts) {
968
- if (oldNode.nodeType === ELEMENT_NODE) {
969
- if (oldNode.hasAttribute("data-preserve")) return;
970
- morphAttributes(oldNode, newNode, claim);
971
- reconcileChildren(oldNode, newNode, null, null, claim, ranges, grafts);
972
- } else if (oldNode.data !== newNode.data) {
973
- oldNode.data = newNode.data;
974
- }
975
- }
976
- const afterRange = (start, id) => afterMarker(start, slotEnd(id));
977
- const afterText = start => afterMarker(start, SLOT_TEXT_END);
978
- function afterMarker(start, end) {
951
+ function findMarker(start, end) {
979
952
  let n = start.nextSibling;
980
953
  while (n) {
981
- if (n.nodeType === COMMENT_NODE && n.data === end) return n.nextSibling;
954
+ if (n.nodeType === COMMENT_NODE && n.data === end) return n;
982
955
  n = n.nextSibling;
983
956
  }
984
957
  return null;
985
958
  }
986
- function findRangeStart(from, id, bound) {
987
- const target = `slot:${id}:start`;
988
- let n = from;
989
- while (n && n !== bound) {
990
- if (n.nodeType === COMMENT_NODE && n.data === target) return n;
991
- n = n.nextSibling;
992
- }
993
- return null;
994
- }
995
- function moveRangeBefore(parent, start, id, ref) {
996
- const end = slotEnd(id);
997
- let n = start;
998
- while (n) {
999
- const next = n.nextSibling;
1000
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1001
- parent.insertBefore(n, ref);
1002
- if (isEnd) break;
1003
- n = next;
1004
- }
1005
- }
1006
- function placeRange(parent, range, id, ref) {
1007
- if (range.nodeType === 11 ) {
1008
- parent.insertBefore(range, ref);
1009
- } else {
1010
- moveRangeBefore(parent, range, id, ref);
1011
- }
1012
- }
1013
- function adoptRange(parent, start, id, ref, claim) {
1014
- const end = slotEnd(id);
1015
- let n = start;
1016
- let after = null;
1017
- while (n) {
1018
- const next = n.nextSibling;
1019
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1020
- parent.insertBefore(n, ref);
1021
- if (claim) claim(n);
1022
- if (isEnd) {
1023
- after = next;
1024
- break;
1025
- }
1026
- n = next;
1027
- }
1028
- return after;
1029
- }
1030
- function reconcileChildren(parent, source, boundStart = null, boundEnd = null, claim = null, ranges = null, grafts = null) {
1031
- let oldChild = boundStart ? boundStart.nextSibling : parent.firstChild;
1032
- let newChild = source.firstChild;
1033
- while (newChild) {
1034
- const nextNew = newChild.nextSibling;
1035
- const pid = slotStartId(newChild);
1036
- const old = oldChild === boundEnd ? null : oldChild;
1037
- if (old && isTextStart(newChild) && old.nodeType === COMMENT_NODE && old.data === newChild.data) {
1038
- oldChild = afterText(old);
1039
- newChild = afterText(newChild);
1040
- continue;
1041
- }
1042
- if (pid !== null) {
1043
- if (old && slotStartId(old) === pid) {
1044
- oldChild = afterRange(old, pid);
1045
- newChild = afterRange(newChild, pid);
1046
- } else {
1047
- const displaced = ranges && ranges.get(pid);
1048
- const existing = displaced || findRangeStart(old, pid, boundEnd);
1049
- if (existing) {
1050
- if (ranges) ranges.delete(pid);
1051
- placeRange(parent, existing, pid, old ?? boundEnd);
1052
- newChild = afterRange(newChild, pid);
1053
- } else {
1054
- newChild = adoptRange(parent, newChild, pid, old ?? boundEnd, claim);
1055
- }
1056
- }
1057
- continue;
1058
- }
1059
- if (!old) {
1060
- parent.insertBefore(newChild, boundEnd);
1061
- if (claim) claim(newChild);
1062
- if (grafts) grafts.push(newChild);
1063
- newChild = nextNew;
1064
- continue;
1065
- }
1066
- if (isSlotMarker(old)) {
1067
- parent.insertBefore(newChild, old);
1068
- if (claim) claim(newChild);
1069
- if (grafts) grafts.push(newChild);
1070
- newChild = nextNew;
1071
- continue;
1072
- }
1073
- if (compatible(old, newChild)) {
1074
- morphNode(old, newChild, claim, ranges, grafts);
1075
- oldChild = old.nextSibling;
1076
- newChild = nextNew;
1077
- continue;
1078
- }
1079
- if (newChild.nodeType === 1) {
1080
- let ahead = old.nextSibling;
1081
- while (ahead && ahead !== boundEnd && !compatible(ahead, newChild)) {
1082
- const aheadPid = slotStartId(ahead);
1083
- ahead = aheadPid !== null ? afterRange(ahead, aheadPid) : ahead.nextSibling;
1084
- }
1085
- if (ahead && ahead !== boundEnd) {
1086
- parent.insertBefore(ahead, old);
1087
- morphNode(ahead, newChild, claim, ranges, grafts);
1088
- newChild = nextNew;
1089
- continue;
1090
- }
1091
- }
1092
- parent.insertBefore(newChild, old);
1093
- if (claim) claim(newChild);
1094
- if (grafts) grafts.push(newChild);
1095
- newChild = nextNew;
1096
- }
1097
- while (oldChild && oldChild !== boundEnd) {
1098
- const next = oldChild.nextSibling;
1099
- const pid = ranges ? slotStartId(oldChild) : null;
1100
- if (pid !== null && ranges.get(pid) === oldChild) {
1101
- const frag = document.createDocumentFragment();
1102
- const after = stashRange(frag, oldChild, pid);
1103
- ranges.set(pid, frag);
1104
- oldChild = after;
1105
- continue;
1106
- }
1107
- parent.removeChild(oldChild);
1108
- oldChild = next;
1109
- }
1110
- }
1111
- function flushGrafts(node, ranges) {
1112
- if (node.nodeType !== ELEMENT_NODE || isFrameElement(node)) return;
1113
- let n = node.firstChild;
1114
- while (n) {
1115
- const id = slotStartId(n);
1116
- if (id !== null) {
1117
- const next = afterRange(n, id);
1118
- const displaced = ranges.get(id);
1119
- if (displaced) {
1120
- ranges.delete(id);
1121
- placeRange(node, displaced, id, n);
1122
- stashRange(document.createDocumentFragment(), n, id);
1123
- }
1124
- n = next;
1125
- continue;
1126
- }
1127
- flushGrafts(n, ranges);
1128
- n = n.nextSibling;
1129
- }
1130
- }
1131
- function stashRange(frag, start, id) {
1132
- const end = slotEnd(id);
1133
- let n = start;
1134
- while (n) {
1135
- const next = n.nextSibling;
1136
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1137
- frag.appendChild(n);
1138
- if (isEnd) return next;
1139
- n = next;
1140
- }
1141
- return null;
1142
- }
1143
959
 
1144
960
  const FRAME_STREAM_HEADER = "X-Frame-Stream";
1145
961
  const FRAME_TIERS_HEADER = "X-Frame-Tiers";
@@ -1147,6 +963,11 @@ function isFrameStreamResponse(response) {
1147
963
  return response.headers.has(FRAME_STREAM_HEADER);
1148
964
  }
1149
965
  const applyFrameResponse = applyFrames;
966
+ const ends = msg => !!msg.r && (":complete" in msg.r || ":error" in msg.r);
967
+ const readsData = msg => {
968
+ for (const key in msg.r) if (key.startsWith("slot:")) for (const v of Object.values(msg.r[key].args)) if (v && v.$ref) return true;
969
+ return false;
970
+ };
1150
971
  function applyFrames(response, host, options = {}, observation) {
1151
972
  const rootId = response.headers.get(FRAME_STREAM_HEADER) ?? "";
1152
973
  response.headers.get(FRAME_TIERS_HEADER)?.split(",").forEach(prepareTier);
@@ -1156,11 +977,12 @@ function applyFrames(response, host, options = {}, observation) {
1156
977
  const reader = options[LIVE_WIRE] || new ChunkReader(response.body);
1157
978
  const open = new Map();
1158
979
  const errorRecord = (id, error) => ({
1159
- type: "error",
1160
980
  id,
1161
981
  version: open.get(id),
1162
- error: {
1163
- message: String(error && error.message)
982
+ r: {
983
+ ":error": {
984
+ message: String(error && error.message)
985
+ }
1164
986
  }
1165
987
  });
1166
988
  const drain = async () => {
@@ -1177,9 +999,9 @@ function applyFrames(response, host, options = {}, observation) {
1177
999
  if (v === undefined) perFrame.set(chunk.id, v = version(chunk.id));
1178
1000
  chunk.version = v;
1179
1001
  } else if (version !== undefined) chunk.version = version;
1180
- if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (chunk.type === "complete" || chunk.type === "error" && !chunk.key) open.delete(chunk.id);
1002
+ if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (ends(chunk)) open.delete(chunk.id);
1181
1003
  const needs = chunk.tiers?.map(prepareTier) || [];
1182
- if (chunk.type === "data" || chunk.type === "slot" && Object.values(chunk.args).some(v => v && v.$ref)) await Promise.all([host.prepareData?.(), ...needs]);
1004
+ if (chunk.type === "data" || readsData(chunk)) await Promise.all([host.prepareData?.(), ...needs]);
1183
1005
  host.apply(chunk);
1184
1006
  }
1185
1007
  result = await reader.next();
@@ -1339,7 +1161,7 @@ function createServerComponentHandler({
1339
1161
  return {
1340
1162
  intercept: intercept && (info => {
1341
1163
  const hit = intercept(info);
1342
- if (hit === undefined) return undefined;
1164
+ if (hit === undefined) return void prepareMorph();
1343
1165
  const address = frameAddress(info.id, info.args);
1344
1166
  if (!info.meta?.live) calls.set(address, info);
1345
1167
  const binding = () => bindingFor(address, info.id);
@@ -1368,13 +1190,14 @@ function createServerComponentHandler({
1368
1190
  const target = entry || host;
1369
1191
  const applied = applyFrameResponse(response, target, {
1370
1192
  as: address,
1371
- version
1193
+ version: frameId => frameId === address ? version : bump(frameId)
1372
1194
  }).catch(err => target.apply({
1373
- type: "error",
1374
1195
  id: address,
1375
1196
  version,
1376
- error: {
1377
- message: String(err && err.message)
1197
+ r: {
1198
+ ":error": {
1199
+ message: String(err && err.message)
1200
+ }
1378
1201
  }
1379
1202
  }));
1380
1203
  return entry ? applied.then(() => settled(address, binding)) : binding;
@@ -1436,7 +1259,6 @@ const TRACE_STATE = Symbol.for("solid.container-trace-state");
1436
1259
  tierLoaders.trace = () => import('@solidjs/web/frames/trace');
1437
1260
  tierLoaders.regions = () => import('@solidjs/web/frames/regions');
1438
1261
  tierLoaders.assets = () => import('@solidjs/web/frames/assets');
1439
- tierLoaders.bind = () => import('@solidjs/web/frames/bind');
1440
1262
  tierLoaders.wire = () => import('@solidjs/web/frames/wire');
1441
1263
  function asyncArg(value) {
1442
1264
  return value;
@@ -1468,23 +1290,22 @@ function followAddress(host, frame, binding) {
1468
1290
  });
1469
1291
  }
1470
1292
  function landing(host, address, value, failed) {
1471
- let thrown = host.get(address)?.error;
1293
+ let frame, thrown;
1294
+ const errored = () => (frame = host.get(address))?.error !== undefined && (thrown === (thrown = frame.version) ? 1 : 2);
1295
+ errored();
1472
1296
  return createMemo(() => {
1473
1297
  failed();
1474
- const error = host.get(address)?.error;
1475
- if (error !== undefined && error !== thrown) {
1476
- thrown = error;
1477
- throw error;
1478
- }
1298
+ const state = errored();
1299
+ if (state > 1) throw frame.error;
1479
1300
  const wait = host.landing(address);
1480
1301
  if (!wait) return value;
1481
- const asked = error !== undefined ? reask(address) : undefined;
1482
- return (asked ? asked.then(() => wait) : wait).then(() => value);
1302
+ const landed = (state ? reask(address, wait) : wait).then(() => value);
1303
+ return landed;
1483
1304
  });
1484
1305
  }
1485
- function reask(address) {
1306
+ function reask(address, wait) {
1486
1307
  const call = callFor(address);
1487
- return call && call.retry();
1308
+ return call ? call.retry().then(() => wait) : wait;
1488
1309
  }
1489
1310
  function failing() {
1490
1311
  const [failed, setFailed] = createSignal(0, {
@@ -1503,15 +1324,36 @@ function getFrameHost() {
1503
1324
  }
1504
1325
  return sharedHost;
1505
1326
  }
1506
- function claimRender(prefix, existing, render, scope, bound) {
1327
+ function claimScope(el) {
1328
+ const registry = sharedConfig.registry;
1329
+ const buckets = new Map();
1330
+ const bucketOf = key => key.slice(0, key.lastIndexOf("-") + 1);
1331
+ const index = root => {
1332
+ if (registry) for (const n of root.querySelectorAll("[_hk]")) {
1333
+ const p = bucketOf(n.getAttribute("_hk"));
1334
+ const b = buckets.get(p);
1335
+ b ? b.push(n) : buckets.set(p, [n]);
1336
+ }
1337
+ };
1338
+ index(el);
1339
+ return {
1340
+ registry,
1341
+ gather(id) {
1342
+ for (const n of buckets.get(bucketOf(id)) || []) {
1343
+ const k = n.getAttribute("_hk");
1344
+ if (k.startsWith(id) && n.isConnected && !registry.has(k)) registry.set(k, n);
1345
+ }
1346
+ },
1347
+ index
1348
+ };
1349
+ }
1350
+ function claimRender(prefix, owner, existing, render, scope, bound) {
1507
1351
  const sc = sharedConfig;
1508
- if (!sc.hydrateWindow || !sc.registry) return render();
1352
+ if (!sc.hydrateWindow || !sc.registry) return runWithOwner(owner, render);
1509
1353
  const prevRoots = sc.claimRoots;
1510
1354
  sc.claimRoots = existing;
1511
1355
  try {
1512
- return runWithOwner(createOwner({
1513
- id: prefix
1514
- }), () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1356
+ return runWithOwner(owner, () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1515
1357
  } finally {
1516
1358
  sc.claimRoots = prevRoots;
1517
1359
  }
@@ -1562,6 +1404,7 @@ function slotArgsProxy(args) {
1562
1404
  reads.set(key, read);
1563
1405
  }
1564
1406
  const v = read();
1407
+ if (v instanceof Element) tierLoads.regions.r.place(v);
1565
1408
  return v instanceof Boxed ? v.c : v;
1566
1409
  },
1567
1410
  has: (_, key) => key in args(),
@@ -1577,40 +1420,24 @@ function slotsFor(props, scope) {
1577
1420
  return new Proxy({}, {
1578
1421
  get(_, prop) {
1579
1422
  if (typeof prop !== "string" || !(prop in props)) return undefined;
1580
- return (slotProps, ctx) => {
1423
+ const mount = (slotProps, ctx) => {
1581
1424
  const key = ctx && ctx.key;
1582
1425
  const prevFill = key !== undefined && fillScopes.get(key);
1583
1426
  if (prevFill) {
1584
1427
  fillScopes.delete(key);
1585
1428
  prevFill.dispose();
1586
1429
  }
1587
- if (ctx && ctx.positions) {
1588
- const fill = props[prop];
1589
- if (typeof fill !== "function") {
1590
- return undefined;
1591
- }
1592
- const owner = createOwner();
1593
- fillScopes.set(key, owner);
1594
- ctx.onCleanup(() => {
1595
- if (fillScopes.get(key) === owner) fillScopes.delete(key);
1596
- owner.dispose();
1597
- });
1598
- runWithOwner(owner, () => {
1599
- const args = ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps);
1600
- tierLoads.bind.r.bind(fill, args, ctx, undefined);
1601
- });
1602
- return undefined;
1603
- }
1604
1430
  const range = ctx && ctx.range;
1605
1431
  if (!range) return undefined;
1606
1432
  const fillOwner = streamInvoke ? createOwner() : null;
1607
- if (fillOwner && key !== undefined && ctx) {
1608
- fillScopes.set(key, fillOwner);
1609
- ctx.onCleanup(() => {
1610
- if (fillScopes.get(key) === fillOwner) fillScopes.delete(key);
1611
- fillOwner.dispose();
1612
- });
1613
- }
1433
+ const owner = fillOwner || createOwner({
1434
+ transparent: true
1435
+ });
1436
+ fillScopes.set(key, owner);
1437
+ ctx.onCleanup(() => {
1438
+ if (fillScopes.get(key) === owner) fillScopes.delete(key);
1439
+ owner.dispose();
1440
+ });
1614
1441
  const evaluate = () => {
1615
1442
  const v = props[prop];
1616
1443
  if (typeof v === "function" && ctx && ctx.invoked) {
@@ -1621,22 +1448,19 @@ function slotsFor(props, scope) {
1621
1448
  };
1622
1449
  const adopted = !!(ctx && ctx.frame && ctx.adopted && ctx.existing && ctx.existing.length);
1623
1450
  const prefix = ctx && ctx.frame ? `sc-${ctx.frame}-${ctx.key}-` : "";
1624
- const value = fillOwner ? runWithOwner(fillOwner, () => adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate()) : adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate();
1625
- const owner = fillOwner || createOwner({
1626
- transparent: true
1627
- });
1628
- if (!fillOwner) {
1629
- fillScopes.set(key, owner);
1630
- ctx.onCleanup(() => {
1631
- if (fillScopes.get(key) === owner) fillScopes.delete(key);
1632
- owner.dispose();
1633
- });
1634
- }
1451
+ const claim = adopted && runWithOwner(owner, () => createOwner({
1452
+ id: prefix
1453
+ }));
1454
+ const value = adopted ? claimRender(prefix, claim, ctx.existing, evaluate, scope) : fillOwner ? runWithOwner(fillOwner, evaluate) : evaluate();
1635
1455
  const end = range.end;
1636
1456
  const bind = () => insert(end.parentNode, value, end, [...ctx.existing]);
1637
- runWithOwner(owner, () => adopted ? claimRender(prefix, ctx.existing, bind, scope, true) : bind());
1457
+ adopted ? claimRender(prefix, claim, ctx.existing, bind, scope, true) : runWithOwner(owner, bind);
1638
1458
  return undefined;
1639
1459
  };
1460
+ return (slotProps, ctx) => {
1461
+ const R = tierLoads.regions?.r;
1462
+ R ? R.nest(mount, slotProps, ctx) : mount(slotProps, ctx);
1463
+ };
1640
1464
  }
1641
1465
  });
1642
1466
  }
@@ -1690,7 +1514,12 @@ function pumpLiveChannel() {
1690
1514
  const pump = () => reader.read().then(r => {
1691
1515
  if (r.done) return;
1692
1516
  const op = r.value;
1693
- for (const m of op.type === "ops" ? op.ops : [op]) liveOps.set(`${m.type}:${m.fid || ""}:${m.key || ""}`, m);
1517
+ for (const key in op.r) liveOps.set(`${op.fid || ""}:${key}`, {
1518
+ fid: op.fid,
1519
+ r: {
1520
+ [key]: op.r[key]
1521
+ }
1522
+ });
1694
1523
  for (const apply of liveAppliers) apply(op);
1695
1524
  return pump();
1696
1525
  });
@@ -1705,12 +1534,19 @@ function indexBoundaries(root) {
1705
1534
  if (key && isBoundaryId(key) && !boundaryIndex.has(key)) boundaryIndex.set(key, el);
1706
1535
  });
1707
1536
  }
1708
- function findBoundaryElement(id) {
1537
+ function findBoundaryElement(id, address) {
1709
1538
  if (!boundaryIndex) {
1710
1539
  boundaryIndex = new Map();
1711
1540
  if (typeof document !== "undefined" && document.body) indexBoundaries(document.body);
1712
1541
  }
1713
- return boundaryIndex.get(id);
1542
+ const args = address && address.slice(id.length + 1);
1543
+ let first, el;
1544
+ for (let n = 0;; n++) {
1545
+ const key = n ? id + "~" + (n + 1) : id;
1546
+ if (claimedBoundaries.has(key)) continue;
1547
+ if (!(el = boundaryIndex.get(key)) || !args || el.dataset.fa == args) return el || first;
1548
+ first = first || el;
1549
+ }
1714
1550
  }
1715
1551
  const arrivals = new Map();
1716
1552
  const FRAME_SELECTOR = `[${FRAME_ID_ATTR}]`;
@@ -1720,19 +1556,32 @@ function awaitBoundary(id) {
1720
1556
  if (!arrival) {
1721
1557
  let resolve;
1722
1558
  const promise = new Promise(r => resolve = r);
1559
+ if (!resolve) return promise;
1723
1560
  arrivals.set(id, arrival = {
1724
1561
  promise,
1725
1562
  resolve
1726
1563
  });
1564
+ onHydrationEnd(releaseArrivals);
1727
1565
  }
1728
1566
  return arrival.promise;
1729
1567
  }
1568
+ function releaseArrivals() {
1569
+ if (!arrivals.size) return;
1570
+ const exhausted = !boundaryMayArrive();
1571
+ for (const [id, arrival] of arrivals) {
1572
+ const el = boundaryIndex && boundaryIndex.get(id);
1573
+ if (!el && !exhausted) continue;
1574
+ arrivals.delete(id);
1575
+ arrival.resolve(!!el);
1576
+ }
1577
+ }
1730
1578
  function boundaryMayArrive() {
1731
1579
  const hy = globalThis._$HY;
1732
1580
  if (!hy) return false;
1733
- return !hy.done || !!(hy.fr && hy.fr.pending());
1581
+ return !(hy.done || sharedConfig.done) || !!(hy.fr && hy.fr.pending());
1734
1582
  }
1735
1583
  function installRevealHook() {
1584
+ installServerComponentHydration();
1736
1585
  const hy = globalThis._$HY;
1737
1586
  if (!hy || hy.$sc || !hy.fr) return;
1738
1587
  hy.$sc = true;
@@ -1744,51 +1593,49 @@ function installRevealHook() {
1744
1593
  if (!boundaryIndex) return;
1745
1594
  const root = parent || (typeof document !== "undefined" ? document.body : null);
1746
1595
  if (root) indexBoundaries(root);
1747
- if (!arrivals.size) return;
1748
- const exhausted = hy.done && !hy.fr.pending();
1749
- for (const [id, arrival] of arrivals) {
1750
- const el = boundaryIndex && boundaryIndex.get(id);
1751
- if (!el && !exhausted) continue;
1752
- arrivals.delete(id);
1753
- arrival.resolve(!!el);
1754
- }
1596
+ releaseArrivals();
1755
1597
  });
1756
1598
  }
1757
1599
  function documentBoundary(host, id, props, binding) {
1758
1600
  installRevealHook();
1759
- const claimed = claimedBoundaries.has(id);
1760
- const el = !claimed ? findBoundaryElement(id) : undefined;
1601
+ const address = binding && contentAddress(binding());
1602
+ const el = findBoundaryElement(id, address);
1761
1603
  if (el) return adoptBoundary(host, id, el, props, binding);
1762
- if (!claimed && boundaryMayArrive()) {
1604
+ if (!claimedBoundaries.has(id) && boundaryMayArrive()) {
1763
1605
  const owner = getOwner();
1764
1606
  let live = true;
1765
1607
  onCleanup(() => live = false);
1766
1608
  return createMemo(() => awaitBoundary(id).then(() => live && runWithOwner(owner, () => {
1767
- const node = claimedBoundaries.has(id) ? undefined : findBoundaryElement(id);
1609
+ const node = findBoundaryElement(id, address);
1768
1610
  return node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding);
1769
1611
  })));
1770
1612
  }
1771
1613
  return boundaryComponent(host, id)(props, binding);
1772
1614
  }
1773
1615
  function adoptBoundary(host, id, el, props, binding) {
1774
- claimedBoundaries.add(id);
1616
+ const siteId = el.getAttribute(FRAME_ID_ATTR);
1617
+ claimedBoundaries.add(siteId);
1618
+ edgeRoots.set(siteId, el);
1775
1619
  const address = binding ? contentAddress(binding()) : id;
1776
1620
  const appliedRecords = new Set();
1777
1621
  const drainRecords = () => {
1778
1622
  const hy = globalThis._$HY;
1779
1623
  if (!hy || !hy.r) return;
1780
1624
  pumpLiveChannel();
1781
- const slotPrefix = `sc:slot:${id}:`;
1625
+ const slotPrefix = `sc:slot:${siteId}:`;
1782
1626
  for (const key of Object.keys(hy.r)) {
1783
1627
  if (appliedRecords.has(key)) continue;
1784
1628
  if (key.startsWith(slotPrefix)) {
1785
1629
  appliedRecords.add(key);
1786
1630
  const apply = args => host.apply({
1787
- type: "slot",
1788
1631
  id: address,
1789
1632
  version: 0,
1790
- key: key.slice(slotPrefix.length),
1791
- args
1633
+ r: {
1634
+ [`slot:${key.slice(slotPrefix.length)}`]: {
1635
+ kind: "slot",
1636
+ args
1637
+ }
1638
+ }
1792
1639
  });
1793
1640
  const value = hy.r[key];
1794
1641
  if (value && typeof value.then === "function") {
@@ -1796,24 +1643,30 @@ function adoptBoundary(host, id, el, props, binding) {
1796
1643
  } else apply(value);
1797
1644
  } else if (key.startsWith("sc:region:")) {
1798
1645
  const childId = key.slice("sc:region:".length);
1799
- if (childId.startsWith(id + ".")) {
1646
+ if (childId.startsWith(siteId + ".")) {
1800
1647
  appliedRecords.add(key);
1801
1648
  const val = hy.r[key];
1802
1649
  const apply = html => host.apply({
1803
- type: "html",
1804
1650
  id: childId,
1805
1651
  version: 0,
1806
- html
1652
+ r: {
1653
+ "": {
1654
+ kind: "html",
1655
+ value: html
1656
+ }
1657
+ }
1807
1658
  });
1808
1659
  val && typeof val.then === "function" ? val.then(apply) : apply(val);
1809
1660
  }
1810
1661
  }
1811
1662
  }
1812
1663
  };
1664
+ const scope = claimScope(el);
1813
1665
  const fr = globalThis._$HY?.fr;
1814
1666
  let frame;
1815
1667
  const unsubscribe = fr ? fr.subscribe((_fragId, parent) => {
1816
1668
  const inside = !!parent && el.contains(parent);
1669
+ inside && scope.index(parent);
1817
1670
  drainRecords();
1818
1671
  if (inside && frame) frame.apply({
1819
1672
  version: frame.version ?? 0,
@@ -1821,11 +1674,11 @@ function adoptBoundary(host, id, el, props, binding) {
1821
1674
  });
1822
1675
  }) : undefined;
1823
1676
  const applyLiveOp = op => {
1824
- if (op.fid && op.fid !== id) return;
1677
+ if (op.fid && op.fid !== siteId) return;
1825
1678
  host.apply({
1826
- ...op,
1827
1679
  id: address,
1828
- version: 0
1680
+ version: 0,
1681
+ r: op.r
1829
1682
  });
1830
1683
  };
1831
1684
  liveAppliers.add(applyLiveOp);
@@ -1840,18 +1693,16 @@ function adoptBoundary(host, id, el, props, binding) {
1840
1693
  const [failed, onApply] = failing();
1841
1694
  frame = createFrame(el, {
1842
1695
  adopt: true,
1696
+ defer: true,
1843
1697
  host,
1844
1698
  id: address,
1845
- slots: slotsFor(props, {
1846
- registry: sc.registry,
1847
- gather: sc.gather
1848
- }),
1699
+ slots: slotsFor(props, scope),
1849
1700
  ownerScope: boundaryScope(owner),
1850
1701
  reveal: revealSeam(owner),
1851
1702
  onApply,
1852
- hold: () => sc.isHydrationInProgress?.() ? runWithOwner(owner, () => untrack(() => sc.holdBoundary("sc:" + id))) : () => {},
1703
+ hold: () => sc.isHydrationInProgress?.() ? runWithOwner(owner, () => untrack(() => sc.holdBoundary("sc:" + siteId))) : () => {},
1853
1704
  ...{
1854
- claimScope: id
1705
+ claimScope: siteId
1855
1706
  }
1856
1707
  });
1857
1708
  if (binding) {
@@ -1866,6 +1717,163 @@ function adoptBoundary(host, id, el, props, binding) {
1866
1717
  });
1867
1718
  return el;
1868
1719
  }
1720
+ const DEFER_EVENTS = ["click", "input", "change", "keydown", "pointerdown", "submit", "focusin"];
1721
+ const DEFER_BUDGET = 8;
1722
+ let mounting = false;
1723
+ const idleTick = () => new Promise(r => typeof requestIdleCallback === "function" ? requestIdleCallback(() => r(), {
1724
+ timeout: 100
1725
+ }) : setTimeout(r, 0));
1726
+ function wakeAt(e) {
1727
+ const target = e.target;
1728
+ if (!target || mounting) return;
1729
+ mounting = true;
1730
+ try {
1731
+ for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1732
+ } finally {
1733
+ mounting = false;
1734
+ }
1735
+ deferDone();
1736
+ }
1737
+ function mountAllDeferred() {
1738
+ if (mounting || sharedConfig.hydrating) return;
1739
+ mounting = true;
1740
+ try {
1741
+ for (let frames; (frames = deferredFrames()).length;) for (const f of frames) f.mountDeferred();
1742
+ } finally {
1743
+ mounting = false;
1744
+ }
1745
+ deferDone();
1746
+ }
1747
+ const edgeRoots = new Map();
1748
+ let edgeIndex;
1749
+ const DEPS = "sc:deps:";
1750
+ function buildEdgeIndex() {
1751
+ const r = globalThis._$HY?.r;
1752
+ if (!r) return undefined;
1753
+ const idx = {
1754
+ readers: new Map(),
1755
+ wide: new Set(),
1756
+ untracked: [],
1757
+ sites: new Set(),
1758
+ starts: new Map()
1759
+ };
1760
+ for (const site of edgeRoots.keys()) for (let n = 0, batch; batch = r[DEPS + site + ":" + n]; n++) {
1761
+ if (typeof batch !== "object") return undefined;
1762
+ idx.sites.add(site);
1763
+ for (const sid in batch) {
1764
+ const occs = unpackOccurrences(batch[sid]);
1765
+ if (sid === "*") occs.forEach(w => idx.wide.add(w));else if (sid === "!") occs.forEach(o => idx.untracked.push([site, o]));else {
1766
+ let list = idx.readers.get(sid);
1767
+ if (!list) idx.readers.set(sid, list = []);
1768
+ for (const o of occs) list.push([site, o]);
1769
+ }
1770
+ }
1771
+ }
1772
+ return idx;
1773
+ }
1774
+ function unpackOccurrences(packed) {
1775
+ const out = [];
1776
+ for (const part of packed.split(" ")) {
1777
+ const m = /^(.*)#(\d+)-(\d+)$/.exec(part);
1778
+ if (!m) part && out.push(part);else for (let i = +m[2]; i <= +m[3]; i++) out.push(m[1] + "#" + i);
1779
+ }
1780
+ return out;
1781
+ }
1782
+ function startOf(idx, site, occ) {
1783
+ let m = idx.starts.get(site);
1784
+ if (!m) {
1785
+ idx.starts.set(site, m = new Map());
1786
+ const root = edgeRoots.get(site);
1787
+ if (root) {
1788
+ const w = document.createTreeWalker(root, 128 );
1789
+ for (let c = w.nextNode(); c; c = w.nextNode()) {
1790
+ const d = c.data;
1791
+ if (d.startsWith("slot:") && d.endsWith(":start")) m.set(d.slice(5, -6), c);
1792
+ }
1793
+ }
1794
+ }
1795
+ return m.get(occ);
1796
+ }
1797
+ function edgesCover(idx) {
1798
+ outer: for (const f of deferredFrames()) {
1799
+ for (const [site, root] of edgeRoots) if (idx.sites.has(site) && root.contains(f.el)) continue outer;
1800
+ return false;
1801
+ }
1802
+ return true;
1803
+ }
1804
+ function mountForWrite(node) {
1805
+ if (mounting || sharedConfig.hydrating) return;
1806
+ const sid = signalName(node) ?? storeName(node);
1807
+ if (sid === undefined || document.readyState === "loading") return mountAllDeferred();
1808
+ const idx = edgeIndex ||= buildEdgeIndex();
1809
+ if (!idx || idx.wide.has(sid) || !edgesCover(idx)) return mountAllDeferred();
1810
+ const readers = idx.readers.get(sid);
1811
+ if (!readers && !idx.untracked.length) return;
1812
+ mounting = true;
1813
+ try {
1814
+ for (const list of [readers || [], idx.untracked]) for (const [site, occ] of list) {
1815
+ const root = edgeRoots.get(site);
1816
+ if (root && deferredFrames().some(f => root.contains(f.el) && f.mountOccurrence(occ))) continue;
1817
+ const start = startOf(idx, site, occ);
1818
+ const target = start && (start.nextSibling || start);
1819
+ if (target) for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1820
+ }
1821
+ } finally {
1822
+ mounting = false;
1823
+ }
1824
+ deferDone();
1825
+ }
1826
+ let idlePass;
1827
+ function mountIdle() {
1828
+ return idlePass ||= (async () => {
1829
+ if (document.readyState !== "complete") await new Promise(r => addEventListener("load", r, {
1830
+ once: true
1831
+ }));
1832
+ globalThis._$HY?.r?.["sc:tiers"]?.forEach(prepareTier);
1833
+ await Promise.all(Object.values(tierLoads)).catch(() => {});
1834
+ for (let frames; (frames = deferredFrames()).length;) {
1835
+ await idleTick();
1836
+ const deadline = performance.now() + DEFER_BUDGET;
1837
+ mounting = true;
1838
+ try {
1839
+ for (const f of frames) if (!f.mountDeferred(deadline) || performance.now() > deadline) break;
1840
+ } finally {
1841
+ mounting = false;
1842
+ }
1843
+ }
1844
+ idlePass = undefined;
1845
+ deferDone();
1846
+ })();
1847
+ }
1848
+ function deferDone() {
1849
+ if (deferredFrames().length) return;
1850
+ if (deferring) {
1851
+ deferring = false;
1852
+ edgeIndex = undefined;
1853
+ setWriteHook(null);
1854
+ DEFER_EVENTS.forEach(t => document.removeEventListener(t, wakeAt, true));
1855
+ }
1856
+ releaseDeferHolds();
1857
+ }
1858
+ let deferHydration = true;
1859
+ function setDeferredHydration(on) {
1860
+ deferHydration = on;
1861
+ setDeferDriver(on && typeof document !== "undefined" ? deferFrame : null);
1862
+ setSignalIdentities(on && typeof document !== "undefined");
1863
+ }
1864
+ let deferring = false;
1865
+ function deferFrame(frame) {
1866
+ if (!deferring) {
1867
+ deferring = true;
1868
+ setWriteHook(mountForWrite);
1869
+ DEFER_EVENTS.forEach(t => document.addEventListener(t, wakeAt, true));
1870
+ }
1871
+ const queued = sharedConfig.events;
1872
+ if (queued && queued.length) for (const [el, e] of queued) if (frame.el.contains(el)) wakeAt({
1873
+ target: e.target ?? el
1874
+ });
1875
+ mountIdle();
1876
+ }
1869
1877
  function installServerComponents(host = getFrameHost(), options) {
1870
1878
  const g = globalThis;
1871
1879
  Object.assign(tierLoaders, options?.tiers);
@@ -1891,15 +1899,18 @@ function installServerComponents(host = getFrameHost(), options) {
1891
1899
  }
1892
1900
  g._$SC.impl = (id, props, binding) => documentBoundary(host, id, props, binding);
1893
1901
  installRevealHook();
1902
+ if (typeof document !== "undefined" && deferHydration) {
1903
+ setDeferDriver(deferFrame);
1904
+ setSignalIdentities(true);
1905
+ }
1894
1906
  const handler = createServerComponentHandler({
1895
1907
  host,
1896
1908
  component: fnId => g._$SC.r(fnId),
1897
1909
  intercept: ({
1898
1910
  id
1899
1911
  }) => {
1900
- if (claimedBoundaries.has(id)) return undefined;
1901
1912
  if (findBoundaryElement(id)) return true;
1902
- if (!boundaryMayArrive()) return undefined;
1913
+ if (claimedBoundaries.has(id) || !boundaryMayArrive()) return undefined;
1903
1914
  installRevealHook();
1904
1915
  return awaitBoundary(id);
1905
1916
  }
@@ -1913,4 +1924,4 @@ function installServerComponents(host = getFrameHost(), options) {
1913
1924
  });
1914
1925
  }
1915
1926
 
1916
- export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isAsyncValue, isFrameStreamResponse };
1927
+ export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isFrameStreamResponse, setDeferredHydration };