marko 6.1.3 → 6.1.4

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.
@@ -61,51 +61,8 @@ function joinWithAnd(a) {
61
61
  }
62
62
  }
63
63
  //#endregion
64
- //#region src/common/helpers.ts
65
- const htmlAttrNameReg = /^[^a-z_]|[^a-z0-9._:-]/i;
66
- function stringifyClassObject(name, value) {
67
- return value ? name : "";
68
- }
69
- function stringifyStyleObject(name, value) {
70
- return value || value === 0 ? name + ":" + value : "";
71
- }
72
- const toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
73
- let str = "";
74
- let sep = "";
75
- let part;
76
- if (val) if (typeof val !== "object") str += val;
77
- else if (Array.isArray(val)) for (const v of val) {
78
- part = toDelimitedString(v, delimiter, stringify);
79
- if (part) {
80
- str += sep + part;
81
- sep = delimiter;
82
- }
83
- }
84
- else for (const name in val) {
85
- part = stringify(name, val[name]);
86
- if (part) {
87
- str += sep + part;
88
- sep = delimiter;
89
- }
90
- }
91
- return str;
92
- };
93
- function isEventHandler(name) {
94
- return /^on[A-Z-]/.test(name);
95
- }
96
- function getEventHandlerName(name) {
97
- return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
98
- }
99
- function isVoid(value) {
100
- return value == null || value === false;
101
- }
102
- function normalizeDynamicRenderer(value) {
103
- if (value) {
104
- if (typeof value === "string") return value;
105
- const normalized = value.content || value.default || value;
106
- if ("id" in normalized) return normalized;
107
- }
108
- }
64
+ //#region src/common/meta.ts
65
+ const DYNAMIC_TAG_SCRIPT_REGISTER_ID = "_dynamicTagScript";
109
66
  //#endregion
110
67
  //#region src/html/content.ts
111
68
  function _unescaped(val) {
@@ -133,145 +90,10 @@ function _escape_comment(val) {
133
90
  return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
134
91
  }
135
92
  //#endregion
136
- //#region src/common/for.ts
137
- function forIn(obj, cb) {
138
- for (const key in obj) cb(key, obj[key]);
139
- }
140
- function forOf(list, cb) {
141
- if (list) {
142
- let i = 0;
143
- for (const item of list) cb(item, i++);
144
- }
145
- }
146
- function forTo(to, from, step, cb) {
147
- const start = from || 0;
148
- const delta = step || 1;
149
- for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
150
- }
151
- function forUntil(until, from, step, cb) {
152
- const start = from || 0;
153
- const delta = step || 1;
154
- for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
155
- }
156
- //#endregion
157
- //#region src/common/opt.ts
158
- function push(opt, item) {
159
- return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
160
- }
161
- //#endregion
162
- //#region src/html/for.ts
163
- function forOfBy(by, item, index) {
164
- if (by) {
165
- if (typeof by === "string") return item[by];
166
- return by(item, index);
167
- }
168
- return index;
169
- }
170
- function forInBy(by, name, value) {
171
- if (by) return by(name, value);
172
- return name;
173
- }
174
- function forStepBy(by, index) {
175
- if (by) return by(index);
176
- return index;
177
- }
178
- //#endregion
179
- //#region src/html/inlined-runtimes.debug.ts
180
- const WALKER_RUNTIME_CODE = `((runtimeId) => (self[runtimeId] ||= (
181
- renderId,
182
- prefix = runtimeId + renderId,
183
- prefixLen = prefix.length,
184
- lookup = {},
185
- visits = [],
186
- doc = document,
187
- walker = doc.createTreeWalker(
188
- doc,
189
- 129 /* NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT */,
190
- ),
191
- ) =>
192
- doc = (self[runtimeId][renderId] = {
193
- i: prefix,
194
- d: doc,
195
- l: lookup,
196
- v: visits,
197
- x() {},
198
- w(node, op, id) {
199
- while ((node = walker.nextNode())) {
200
- doc.x(
201
- (op =
202
- (op = node.data) &&
203
- !op.indexOf(prefix) &&
204
- ((lookup[(id = op.slice(prefixLen + 1))] = node), op[prefixLen])),
205
- id,
206
- node,
207
- );
208
-
209
- if (op > "#") {
210
- visits.push(node);
211
- }
212
- }
213
- },
214
- })
215
- , self[runtimeId]))`;
216
- const REORDER_RUNTIME_CODE = `((runtime) => {
217
- if (runtime.j) return;
218
- let onNextSibling,
219
- placeholder,
220
- nextSibling,
221
- placeholders = runtime.p = {},
222
- replace = (id, container) => runtime.l[id].replaceWith(...container.childNodes);
223
- runtime.d.head.append(
224
- runtime.d.querySelector("style[" + runtime.i + "]") || ""
225
- );
226
- runtime.j = {};
227
- runtime.x = (op, id, node, placeholderRoot, placeholderCb) => {
228
- if (node == nextSibling) {
229
- onNextSibling();
230
- }
231
-
232
- if (op == "#") {
233
- (placeholders[id] = placeholder).i++;
234
- } else if (op == "!") {
235
- if (runtime.l[id] && placeholders[id]) {
236
- nextSibling = node.nextSibling;
237
- onNextSibling = () => placeholders[id].c();
238
- }
239
- } else if (node.tagName == "T" && (id = node.getAttribute(runtime.i))) {
240
- nextSibling = node.nextSibling;
241
- onNextSibling = () => {
242
- node.remove();
243
- placeholderRoot || replace(id, node);
244
- placeholder.c();
245
- };
246
- placeholder =
247
- placeholders[id] ||
248
- (placeholderRoot = placeholders[id] =
249
- {
250
- i: runtime.l[id] ? 1 : 2,
251
- c(start = runtime.l["^" + id]) {
252
- if (--placeholderRoot.i) return 1;
253
- for (
254
- ;
255
- (nextSibling =
256
- runtime.l[id].previousSibling || start).remove(),
257
- start != nextSibling;
258
-
259
- );
260
- replace(id, node);
261
- },
262
- });
263
- // repurpose "op" for callbacks ...carefully
264
- if ((op = runtime.j[id])) {
265
- placeholderCb = placeholder.c;
266
- placeholder.c = () => placeholderCb() || op(runtime.r);
267
- }
268
- }
269
- };
270
- })`;
271
- //#endregion
272
93
  //#region src/html/serializer.ts
94
+ const K_SCOPE_ID = Symbol("Scope ID");
273
95
  const kTouchedIterator = Symbol.for("marko.touchedIterator");
274
- const { hasOwnProperty } = {};
96
+ const { hasOwnProperty: hasOwnProperty$1 } = {};
275
97
  const Generator = (function* () {})().constructor;
276
98
  const AsyncGenerator = (async function* () {})().constructor;
277
99
  patchIteratorNext(Generator.prototype);
@@ -517,15 +339,14 @@ const KNOWN_OBJECTS = new Map([
517
339
  var State$1 = class {
518
340
  ids = 0;
519
341
  flush = 0;
520
- registerInstanceId = 0;
521
- flushed = false;
522
342
  wroteUndefined = false;
523
343
  buf = [];
524
344
  strs = /* @__PURE__ */ new Map();
525
345
  refs = /* @__PURE__ */ new WeakMap();
526
346
  assigned = /* @__PURE__ */ new Set();
527
- registered = [];
528
347
  boundary = void 0;
348
+ channel = void 0;
349
+ channelDeps = null;
529
350
  mutated = [];
530
351
  };
531
352
  var Reference = class {
@@ -534,19 +355,15 @@ var Reference = class {
534
355
  flush;
535
356
  pos;
536
357
  id;
537
- registered = null;
538
358
  assigns = null;
359
+ scopeId = void 0;
360
+ channel = void 0;
539
361
  constructor(parent, accessor, flush, pos = null, id = null) {
540
362
  this.parent = parent;
541
363
  this.accessor = accessor;
542
364
  this.flush = flush;
543
365
  this.pos = pos;
544
366
  this.id = id;
545
- this.parent = parent;
546
- this.accessor = accessor;
547
- this.flush = flush;
548
- this.pos = pos;
549
- this.id = id;
550
367
  }
551
368
  };
552
369
  const DEBUG = /* @__PURE__ */ new WeakMap();
@@ -559,57 +376,43 @@ function setDebugInfo(obj, file, loc, vars) {
559
376
  }
560
377
  var Serializer = class {
561
378
  #state = new State$1();
562
- get flushed() {
563
- return this.#state.flushed;
379
+ pending(channel) {
380
+ return hasMatchingMutations(this.#state.mutated, channel?.readyId);
564
381
  }
565
- stringify(val, boundary) {
382
+ pendingReadyChannel() {
383
+ for (const mutation of this.#state.mutated) if (mutation.channel?.readyId) return mutation.channel;
384
+ }
385
+ stringifyScopes(flushes, globals, boundary, channel) {
566
386
  try {
567
- this.#state.flushed = false;
568
387
  this.#state.boundary = boundary;
569
- return writeRoot(this.#state, val);
388
+ this.#state.channel = channel;
389
+ return writeScopesRoot(this.#state, flushes, globals);
570
390
  } finally {
571
391
  this.#state.flush++;
572
392
  this.#state.buf = [];
573
393
  }
574
394
  }
575
- nextId() {
576
- return nextId(this.#state);
395
+ written(val) {
396
+ return this.#state.refs.has(val);
577
397
  }
578
- symbol(id) {
579
- const symbol = Symbol();
580
- this.#state.refs.set(symbol, new Reference(null, null, 0, null, id));
581
- return symbol;
398
+ takeChannelDeps() {
399
+ const deps = this.#state.channelDeps;
400
+ this.#state.channelDeps = null;
401
+ return deps;
582
402
  }
583
- writeCall(value, object, property, spread) {
584
- const state = this.#state;
585
- state.mutated.push({
586
- type: 0,
403
+ writeCall(value, object, property, channel) {
404
+ this.#state.mutated.push({
587
405
  value,
588
406
  object,
589
407
  property,
590
- spread
591
- });
592
- state.flushed = true;
593
- }
594
- writeAssign(value, object, property) {
595
- const state = this.#state;
596
- state.mutated.push({
597
- type: 1,
598
- value,
599
- object,
600
- property
408
+ channel
601
409
  });
602
- state.flushed = true;
603
- }
604
- register(id, val, scope) {
605
- return register(id, val, scope, scope ? ++this.#state.registerInstanceId : 0);
606
410
  }
607
411
  };
608
- function register(id, val, scope, instanceId) {
412
+ function register(id, val, scope) {
609
413
  REGISTRY.set(val, {
610
414
  id,
611
415
  scope,
612
- instanceId: instanceId ?? 0,
613
416
  access: "_._" + toAccess(toObjectKey(id))
614
417
  });
615
418
  return val;
@@ -621,65 +424,70 @@ function getRegistered(val) {
621
424
  scope: registered.scope
622
425
  };
623
426
  }
624
- function writeRoot(state, root) {
427
+ function writeScopesRoot(state, flushes, globals) {
625
428
  const { buf } = state;
626
- const hadBuf = buf.length !== 0;
627
- let result;
628
- if (hadBuf) buf.push(",");
629
- if (writeProp(state, root, null, "")) {
630
- const rootRef = state.refs.get(root);
631
- if (rootRef) {
632
- const rootId = ensureId(state, rootRef);
633
- if (state.assigned.size || state.registered.length || state.mutated.length) {
634
- state.assigned.delete(rootRef);
635
- writeAssigned(state);
636
- buf.push("," + (rootRef.assigns ? assignsToString(rootRef.assigns, rootId) : rootId));
637
- }
638
- }
639
- result = "(";
640
- buf.push(")");
641
- } else {
642
- if (hadBuf) {
643
- buf.pop();
644
- writeAssigned(state);
429
+ let nextSlotId = -1;
430
+ let fillIndex = -1;
431
+ if (globals) {
432
+ fillIndex = buf.push("[0,") - 1;
433
+ writeProp(state, globals, null, "");
434
+ nextSlotId = 1;
435
+ }
436
+ for (const flush of flushes) {
437
+ const scopeId = flush[0];
438
+ const scope = flush[1];
439
+ const ref = state.refs.get(scope) || newScopeReference(state, scope, scopeId);
440
+ const openIndex = buf.push("") - 1;
441
+ if (writeObjectProps(state, flush[2], ref)) {
442
+ buf[openIndex] = nextSlotId === -1 ? "[" + scopeId + ",{" : (scopeId > nextSlotId ? "," + (scopeId - nextSlotId) : "") + ",{";
443
+ if (fillIndex === -1) fillIndex = openIndex;
444
+ nextSlotId = scopeId + 1;
445
+ buf.push("}");
446
+ } else buf.pop();
447
+ }
448
+ if (nextSlotId !== -1) buf.push("]");
449
+ let extras = "";
450
+ if (state.assigned.size || hasChannelMutations(state)) {
451
+ extras = ",0)";
452
+ if (fillIndex !== -1) {
453
+ buf[fillIndex] = "_(" + buf[fillIndex];
454
+ buf.push(")");
645
455
  }
646
- result = "{";
647
- buf.push("}");
456
+ writeAssigned(state);
648
457
  }
458
+ let result = extras && "(";
649
459
  for (const chunk of buf) result += chunk;
460
+ result += extras;
461
+ if (!result) return "";
650
462
  if (state.wroteUndefined) {
651
463
  state.wroteUndefined = false;
652
464
  return "(_,$)=>" + result;
653
465
  } else return "_=>" + result;
654
466
  }
655
467
  function writeAssigned(state) {
468
+ let sep = state.buf.length ? "," : "";
656
469
  if (state.assigned.size) {
657
470
  let buf = "";
658
471
  for (const ref of state.assigned) {
659
- buf += "," + assignsToString(ref.assigns, ref.id);
472
+ buf += sep + assignsToString(ref.assigns, ref.id);
660
473
  ref.assigns = null;
474
+ sep = ",";
661
475
  }
662
476
  state.buf.push(buf);
663
477
  state.assigned = /* @__PURE__ */ new Set();
664
478
  }
665
- if (state.registered.length) {
666
- let buf = "";
667
- for (const ref of state.registered.sort(compareRegisteredReferences)) {
668
- const scopeRef = state.refs.get(ref.registered.scope);
669
- buf += "," + assignsToString(ref.assigns, ref.registered.access + "(" + (scopeRef ? ensureId(state, scopeRef) : ref.assigns[0]) + ")");
670
- ref.assigns = null;
671
- ref.registered = null;
672
- }
673
- state.buf.push(buf);
674
- state.registered = [];
675
- }
676
- if (state.mutated.length) {
479
+ if (hasChannelMutations(state)) {
480
+ const remaining = [];
677
481
  for (const mutation of state.mutated) {
482
+ if (!mutationMatchesReadyId(mutation, state.channel?.readyId)) {
483
+ remaining.push(mutation);
484
+ continue;
485
+ }
678
486
  const hasSeen = state.refs.get(mutation.object)?.id;
679
487
  const objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
680
488
  if (writeProp(state, mutation.object, null, "")) {
681
489
  const objectRef = state.refs.get(mutation.object);
682
- if (objectRef) {
490
+ if (objectRef && objectRef.scopeId === void 0) {
683
491
  if (!objectRef.id) {
684
492
  objectRef.id = nextRefAccess(state);
685
493
  state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex];
@@ -690,21 +498,30 @@ function writeAssigned(state) {
690
498
  }
691
499
  }
692
500
  } else state.buf.push("void 0");
693
- const isCall = mutation.type === 0;
694
- const valueStartIndex = state.buf.push(isCall ? (mutation.property === void 0 ? "" : toAccess(toObjectKey(mutation.property))) + "(" + (mutation.spread ? "..." : "") : toAccess(toObjectKey(mutation.property)) + "=");
695
- if (writeProp(state, mutation.value, null, "")) {
501
+ const valueStartIndex = state.buf.push(toAccess(toObjectKey(mutation.property)) + "(");
502
+ if (mutation.value === void 0) {} else if (writeProp(state, mutation.value, null, "")) {
696
503
  const valueRef = state.refs.get(mutation.value);
697
- if (valueRef && !valueRef.id) {
698
- valueRef.id = nextRefAccess(state);
504
+ if (valueRef && !valueRef.id && valueRef.scopeId === void 0) {
505
+ valueRef.id = mutation.valueId || nextRefAccess(state);
699
506
  state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex];
700
507
  }
701
508
  } else state.buf.push("void 0");
702
- if (isCall) state.buf.push(")");
509
+ state.buf.push(")");
703
510
  }
704
- state.mutated = [];
705
- if (state.assigned.size || state.registered.length) writeAssigned(state);
511
+ state.mutated = remaining;
512
+ if (state.assigned.size) writeAssigned(state);
706
513
  }
707
514
  }
515
+ function hasChannelMutations(state) {
516
+ return hasMatchingMutations(state.mutated, state.channel?.readyId);
517
+ }
518
+ function hasMatchingMutations(mutated, readyId) {
519
+ for (const mutation of mutated) if (mutationMatchesReadyId(mutation, readyId)) return true;
520
+ return false;
521
+ }
522
+ function mutationMatchesReadyId(mutation, readyId) {
523
+ return mutation.channel?.readyId ? mutation.channel.readyId === readyId : !readyId;
524
+ }
708
525
  function writeProp(state, val, parent, accessor) {
709
526
  switch (typeof val) {
710
527
  case "string": return writeString(state, val, parent, accessor);
@@ -720,16 +537,26 @@ function writeProp(state, val, parent, accessor) {
720
537
  }
721
538
  }
722
539
  function writeReferenceOr(state, write, val, parent, accessor) {
540
+ const scopeId = val[K_SCOPE_ID];
541
+ if (scopeId !== void 0) {
542
+ trackScope(state, val, scopeId);
543
+ state.buf.push("_(" + scopeId + ")");
544
+ return true;
545
+ }
723
546
  let ref = state.refs.get(val);
724
547
  if (ref) {
548
+ if (!trackChannel(state, ref)) {
549
+ abortUnreachableChannel(state, val);
550
+ return false;
551
+ }
725
552
  if (parent) {
726
553
  if (ref.assigns) {
727
- addAssignment(ref, ensureId(state, parent) + toAccess(accessor));
554
+ addAssignment(ref, accessId(state, parent) + toAccess(accessor));
728
555
  return false;
729
556
  } else if (isCircular(parent, ref)) {
730
557
  ensureId(state, ref);
731
558
  state.assigned.add(ref);
732
- addAssignment(ref, ensureId(state, parent) + toAccess(accessor));
559
+ addAssignment(ref, accessId(state, parent) + toAccess(accessor));
733
560
  return false;
734
561
  }
735
562
  }
@@ -739,27 +566,35 @@ function writeReferenceOr(state, write, val, parent, accessor) {
739
566
  const registered = REGISTRY.get(val);
740
567
  if (registered) return writeRegistered(state, val, parent, accessor, registered);
741
568
  state.refs.set(val, ref = new Reference(parent, accessor, state.flush, state.buf.length));
569
+ ref.channel = state.channel;
742
570
  ref.debug = DEBUG.get(val);
743
571
  if (write(state, val, ref)) return true;
744
572
  state.refs.delete(val);
745
573
  return false;
746
574
  }
575
+ function trackScope(state, val, scopeId) {
576
+ const ref = state.refs.get(val);
577
+ if (ref) trackChannel(state, ref);
578
+ else newScopeReference(state, val, scopeId);
579
+ }
580
+ function newScopeReference(state, val, scopeId) {
581
+ const ref = new Reference(null, null, state.flush);
582
+ ref.scopeId = scopeId;
583
+ ref.channel = state.channel;
584
+ state.refs.set(val, ref);
585
+ ref.debug = DEBUG.get(val);
586
+ return ref;
587
+ }
747
588
  function writeRegistered(state, val, parent, accessor, registered) {
748
- if (parent && registered.scope) {
749
- if (!state.refs.has(registered.scope)) {
750
- state.buf.push(registered.access + "(");
751
- writeProp(state, registered.scope, null, "");
752
- state.buf.push(")");
753
- const scopeRef = state.refs.get(registered.scope);
754
- if (scopeRef) ensureId(state, scopeRef);
755
- return true;
756
- }
757
- const fnRef = new Reference(parent, accessor, state.flush, state.buf.length);
758
- fnRef.registered = registered;
759
- state.refs.set(val, fnRef);
760
- state.registered.push(fnRef);
761
- addAssignment(fnRef, ensureId(state, parent) + toAccess(accessor));
762
- return false;
589
+ const { scope } = registered;
590
+ if (scope) {
591
+ const ref = new Reference(parent, accessor, state.flush, state.buf.length);
592
+ ref.channel = state.channel;
593
+ state.refs.set(val, ref);
594
+ ref.debug = DEBUG.get(val);
595
+ const scopeId = scope[K_SCOPE_ID];
596
+ trackScope(state, scope, scopeId);
597
+ state.buf.push("_(" + scopeId + "," + quote(registered.id, 0) + ")");
763
598
  } else state.buf.push(registered.access);
764
599
  return true;
765
600
  }
@@ -768,9 +603,15 @@ function writeString(state, val, parent, accessor) {
768
603
  if (val.length > STRING_DEDUP_LENGTH) {
769
604
  const ref = state.strs.get(val);
770
605
  if (ref) {
771
- state.buf.push(ensureId(state, ref));
772
- return true;
773
- } else state.strs.set(val, new Reference(parent, accessor, state.flush, state.buf.length));
606
+ if (trackChannel(state, ref)) {
607
+ state.buf.push(ensureId(state, ref));
608
+ return true;
609
+ }
610
+ } else {
611
+ const ref = new Reference(parent, accessor, state.flush, state.buf.length);
612
+ ref.channel = state.channel;
613
+ state.strs.set(val, ref);
614
+ }
774
615
  }
775
616
  state.buf.push(quote(val, 0));
776
617
  return true;
@@ -902,15 +743,22 @@ function writeRegExp(state, val) {
902
743
  return true;
903
744
  }
904
745
  function writePromise(state, val, ref) {
905
- const { boundary } = state;
746
+ const { boundary, channel } = state;
906
747
  if (!boundary) return false;
907
748
  const pId = nextRefAccess(state);
908
- const pRef = new Reference(ref, null, state.flush, null, pId);
749
+ const handle = newAsyncHandle(state, ref, pId);
909
750
  state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()");
910
- val.then((v) => writeAsyncCall(state, boundary, pRef, "f", v, pId), (v) => writeAsyncCall(state, boundary, pRef, "r", v, pId));
751
+ val.then((v) => writeAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => writeAsyncCall(state, boundary, handle, "r", v, channel, pId));
911
752
  boundary.startAsync();
912
753
  return true;
913
754
  }
755
+ function newAsyncHandle(state, parent, id) {
756
+ const handle = {};
757
+ const handleRef = new Reference(parent, null, state.flush, null, id);
758
+ handleRef.channel = state.channel;
759
+ state.refs.set(handle, handleRef);
760
+ return handle;
761
+ }
914
762
  function writeMap(state, val, ref) {
915
763
  if (!val.size) {
916
764
  state.buf.push("new Map");
@@ -983,7 +831,7 @@ function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
983
831
  }
984
832
  function isDedupedMember(val) {
985
833
  switch (typeof val) {
986
- case "object": return val !== null;
834
+ case "object": return val !== null && val[K_SCOPE_ID] === void 0;
987
835
  case "function":
988
836
  case "symbol": return true;
989
837
  case "string": return val.length > STRING_DEDUP_LENGTH;
@@ -1136,21 +984,21 @@ function writeResponse(state, val, ref) {
1136
984
  return true;
1137
985
  }
1138
986
  function writeReadableStream(state, val, ref) {
1139
- const { boundary } = state;
987
+ const { boundary, channel } = state;
1140
988
  if (!boundary || val.locked) return false;
1141
989
  const reader = val.getReader();
1142
990
  const iterId = nextRefAccess(state);
1143
- const iterRef = new Reference(ref, null, state.flush, null, iterId);
991
+ const handle = newAsyncHandle(state, ref, iterId);
1144
992
  const onFulfilled = ({ value, done }) => {
1145
- if (done) writeAsyncCall(state, boundary, iterRef, "r", value);
993
+ if (done) writeAsyncCall(state, boundary, handle, "r", value, channel);
1146
994
  else if (!boundary.signal.aborted) {
1147
995
  reader.read().then(onFulfilled, onRejected);
1148
996
  boundary.startAsync();
1149
- writeAsyncCall(state, boundary, iterRef, "f", value);
997
+ writeAsyncCall(state, boundary, handle, "f", value, channel);
1150
998
  }
1151
999
  };
1152
1000
  const onRejected = (reason) => {
1153
- writeAsyncCall(state, boundary, iterRef, "j", reason);
1001
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
1154
1002
  };
1155
1003
  state.buf.push("new ReadableStream({start(c){(async(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()]))=>{for(i of a)v=await i,i==l?c.close():c.enqueue(v)})(" + iterId + "={}).catch(e=>c.error(e))}})");
1156
1004
  reader.read().then(onFulfilled, onRejected);
@@ -1188,20 +1036,20 @@ function writeAsyncGenerator(state, iter, ref) {
1188
1036
  state.buf.push("(async function*(){}())");
1189
1037
  return true;
1190
1038
  }
1191
- const { boundary } = state;
1039
+ const { boundary, channel } = state;
1192
1040
  if (!boundary) return false;
1193
1041
  const iterId = nextRefAccess(state);
1194
- const iterRef = new Reference(ref, null, state.flush, null, iterId);
1042
+ const handle = newAsyncHandle(state, ref, iterId);
1195
1043
  const onFulfilled = ({ value, done }) => {
1196
- if (done) writeAsyncCall(state, boundary, iterRef, "r", value);
1044
+ if (done) writeAsyncCall(state, boundary, handle, "r", value, channel);
1197
1045
  else if (!boundary.signal.aborted) {
1198
1046
  iter.next().then(onFulfilled, onRejected);
1199
1047
  boundary.startAsync();
1200
- writeAsyncCall(state, boundary, iterRef, "f", value);
1048
+ writeAsyncCall(state, boundary, handle, "f", value, channel);
1201
1049
  }
1202
1050
  };
1203
1051
  const onRejected = (reason) => {
1204
- writeAsyncCall(state, boundary, iterRef, "j", reason);
1052
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
1205
1053
  };
1206
1054
  state.buf.push("(async function*(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()])){for(i of a)v=await i,i!=l&&(yield v);return v})(" + iterId + "={})");
1207
1055
  iter.next().then(onFulfilled, onRejected);
@@ -1215,7 +1063,7 @@ function writeNullObject(state, val, ref) {
1215
1063
  }
1216
1064
  function writeObjectProps(state, val, ref) {
1217
1065
  let sep = "";
1218
- for (const key in val) if (hasOwnProperty.call(val, key)) {
1066
+ for (const key in val) if (hasOwnProperty$1.call(val, key)) {
1219
1067
  const escapedKey = toObjectKey(key);
1220
1068
  state.buf.push(sep + escapedKey + ":");
1221
1069
  if (writeProp(state, val[key], ref, escapedKey)) sep = ",";
@@ -1236,18 +1084,15 @@ function writeObjectProps(state, val, ref) {
1236
1084
  }
1237
1085
  return sep;
1238
1086
  }
1239
- function writeAsyncCall(state, boundary, ref, method, value, preferredValueId = null) {
1087
+ function writeAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
1240
1088
  if (boundary.signal.aborted) return;
1241
- state.flushed = true;
1242
- const valueStartIndex = state.buf.push((state.buf.length === 0 ? "" : ",") + ref.id + "." + method + "(");
1243
- if (writeProp(state, value, ref, "")) {
1244
- const valueRef = state.refs.get(value);
1245
- if (valueRef && !valueRef.id) {
1246
- valueRef.id = preferredValueId || nextRefAccess(state);
1247
- state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex];
1248
- }
1249
- }
1250
- state.buf.push(")");
1089
+ state.mutated.push({
1090
+ value,
1091
+ object: handle,
1092
+ property: method,
1093
+ channel,
1094
+ valueId
1095
+ });
1251
1096
  boundary.endAsync();
1252
1097
  }
1253
1098
  function throwUnserializable(state, cause, ref = null, accessor = "") {
@@ -1279,6 +1124,26 @@ function throwUnserializable(state, cause, ref = null, accessor = "") {
1279
1124
  state.boundary.abort(err);
1280
1125
  }
1281
1126
  }
1127
+ function trackChannel(state, ref) {
1128
+ const refReadyId = ref.channel?.readyId;
1129
+ if (!refReadyId || refReadyId === state.channel?.readyId) return true;
1130
+ let cur = state.channel?.parent;
1131
+ while (cur) {
1132
+ if (cur.readyId === refReadyId) {
1133
+ (state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId);
1134
+ return true;
1135
+ }
1136
+ cur = cur.parent;
1137
+ }
1138
+ return false;
1139
+ }
1140
+ function abortUnreachableChannel(state, val) {
1141
+ if (state.boundary?.abort) {
1142
+ const err = new TypeError("Unable to serialize a value shared between independently lazy loaded content. Values shared this way must also be serialized by content that is not lazily loaded, or by a common parent.", { cause: val });
1143
+ err.stack = void 0;
1144
+ state.boundary.abort(err);
1145
+ }
1146
+ }
1282
1147
  function isCircular(parent, ref) {
1283
1148
  let cur = parent;
1284
1149
  while (cur) {
@@ -1338,7 +1203,19 @@ function quote(str, startPos) {
1338
1203
  return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
1339
1204
  }
1340
1205
  function ensureId(state, ref) {
1341
- return ref.id || assignId(state, ref);
1206
+ if (ref.scopeId !== void 0) {
1207
+ trackChannel(state, ref);
1208
+ return "_(" + ref.scopeId + ")";
1209
+ }
1210
+ if (ref.id) {
1211
+ trackChannel(state, ref);
1212
+ return ref.id;
1213
+ }
1214
+ return assignId(state, ref);
1215
+ }
1216
+ function accessId(state, ref) {
1217
+ const id = ensureId(state, ref);
1218
+ return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
1342
1219
  }
1343
1220
  function assignId(state, ref) {
1344
1221
  const { pos } = ref;
@@ -1348,17 +1225,20 @@ function assignId(state, ref) {
1348
1225
  else state.buf[pos - 1] += ref.id + "=";
1349
1226
  return ref.id;
1350
1227
  }
1228
+ ref.channel = state.channel;
1351
1229
  let cur = ref;
1352
1230
  let accessPrevValue = "";
1353
1231
  do {
1354
1232
  accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
1355
1233
  const parent = cur.parent;
1356
1234
  if (parent.id) {
1357
- accessPrevValue = parent.id + accessPrevValue;
1358
- break;
1235
+ if (trackChannel(state, parent) || !parent.parent) {
1236
+ accessPrevValue = parent.id + accessPrevValue;
1237
+ break;
1238
+ }
1359
1239
  }
1360
- if (parent.flush === state.flush) {
1361
- accessPrevValue = ensureId(state, parent) + accessPrevValue;
1240
+ if (parent.flush === state.flush || parent.scopeId !== void 0) {
1241
+ accessPrevValue = accessId(state, parent) + accessPrevValue;
1362
1242
  break;
1363
1243
  }
1364
1244
  cur = parent;
@@ -1427,18 +1307,209 @@ function patchIteratorNext(proto) {
1427
1307
  };
1428
1308
  proto.next[kTouchedIterator] = true;
1429
1309
  }
1430
- function compareRegisteredReferences(a, b) {
1431
- return a.registered.instanceId - b.registered.instanceId;
1432
- }
1433
1310
  //#endregion
1434
- //#region src/html/writer.ts
1435
- let $chunk;
1436
- const NOOP$2 = () => {};
1437
- const K_SCOPE_ID = Symbol("Scope ID");
1438
- const K_SCOPE_REFERENCED = Symbol("Scope Referenced");
1439
- function getChunk() {
1440
- return $chunk;
1441
- }
1311
+ //#region src/common/helpers.ts
1312
+ const htmlAttrNameReg = /^[^a-z_]|[^a-z0-9._:-]/i;
1313
+ function stringifyClassObject(name, value) {
1314
+ return value ? name : "";
1315
+ }
1316
+ function stringifyStyleObject(name, value) {
1317
+ return value || value === 0 ? name + ":" + value : "";
1318
+ }
1319
+ const toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
1320
+ let str = "";
1321
+ let sep = "";
1322
+ let part;
1323
+ if (val) if (typeof val !== "object") str += val;
1324
+ else if (Array.isArray(val)) for (const v of val) {
1325
+ part = toDelimitedString(v, delimiter, stringify);
1326
+ if (part) {
1327
+ str += sep + part;
1328
+ sep = delimiter;
1329
+ }
1330
+ }
1331
+ else for (const name in val) {
1332
+ part = stringify(name, val[name]);
1333
+ if (part) {
1334
+ str += sep + part;
1335
+ sep = delimiter;
1336
+ }
1337
+ }
1338
+ return str;
1339
+ };
1340
+ function isEventHandler(name) {
1341
+ return /^on[A-Z-]/.test(name);
1342
+ }
1343
+ function getEventHandlerName(name) {
1344
+ return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
1345
+ }
1346
+ function isVoid(value) {
1347
+ return value == null || value === false;
1348
+ }
1349
+ function normalizeDynamicRenderer(value) {
1350
+ if (value) {
1351
+ if (typeof value === "string") return value;
1352
+ const normalized = value.content || value.default || value;
1353
+ if ("id" in normalized) return normalized;
1354
+ }
1355
+ }
1356
+ //#endregion
1357
+ //#region src/common/for.ts
1358
+ function forIn(obj, cb) {
1359
+ for (const key in obj) cb(key, obj[key]);
1360
+ }
1361
+ function forOf(list, cb) {
1362
+ if (list) {
1363
+ let i = 0;
1364
+ for (const item of list) cb(item, i++);
1365
+ }
1366
+ }
1367
+ function forTo(to, from, step, cb) {
1368
+ const start = from || 0;
1369
+ const delta = step || 1;
1370
+ for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
1371
+ }
1372
+ function forUntil(until, from, step, cb) {
1373
+ const start = from || 0;
1374
+ const delta = step || 1;
1375
+ for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
1376
+ }
1377
+ //#endregion
1378
+ //#region src/common/opt.ts
1379
+ function forEach(opt, cb) {
1380
+ if (opt) if (Array.isArray(opt)) for (const item of opt) cb(item);
1381
+ else cb(opt);
1382
+ }
1383
+ function push(opt, item) {
1384
+ return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
1385
+ }
1386
+ function concat(opt, other) {
1387
+ if (!opt) return other;
1388
+ if (!other) return opt;
1389
+ if (Array.isArray(opt)) {
1390
+ if (Array.isArray(other)) for (const item of other) opt.push(item);
1391
+ else opt.push(other);
1392
+ return opt;
1393
+ }
1394
+ return Array.isArray(other) ? [opt, ...other] : [opt, other];
1395
+ }
1396
+ //#endregion
1397
+ //#region src/html/for.ts
1398
+ function forOfBy(by, item, index) {
1399
+ if (by) {
1400
+ if (typeof by === "string") return item[by];
1401
+ return by(item, index);
1402
+ }
1403
+ return index;
1404
+ }
1405
+ function forInBy(by, name, value) {
1406
+ if (by) return by(name, value);
1407
+ return name;
1408
+ }
1409
+ function forStepBy(by, index) {
1410
+ if (by) return by(index);
1411
+ return index;
1412
+ }
1413
+ //#endregion
1414
+ //#region src/html/inlined-runtimes.debug.ts
1415
+ const WALKER_RUNTIME_CODE = `((runtimeId) => (self[runtimeId] ||= (
1416
+ renderId,
1417
+ prefix = runtimeId + renderId,
1418
+ prefixLen = prefix.length,
1419
+ lookup = {},
1420
+ visits = [],
1421
+ doc = document,
1422
+ walker = doc.createTreeWalker(
1423
+ doc,
1424
+ 129 /* NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT */,
1425
+ ),
1426
+ ) =>
1427
+ doc = (self[runtimeId][renderId] = {
1428
+ i: prefix,
1429
+ d: doc,
1430
+ l: lookup,
1431
+ v: visits,
1432
+ x() {},
1433
+ w(node, op, id) {
1434
+ while ((node = walker.nextNode())) {
1435
+ doc.x(
1436
+ (op =
1437
+ (op = node.data) &&
1438
+ !op.indexOf(prefix) &&
1439
+ ((lookup[(id = op.slice(prefixLen + 1))] = node), op[prefixLen])),
1440
+ id,
1441
+ node,
1442
+ );
1443
+
1444
+ if (op > "#") {
1445
+ visits.push(node);
1446
+ }
1447
+ }
1448
+ },
1449
+ })
1450
+ , self[runtimeId]))`;
1451
+ const REORDER_RUNTIME_CODE = `((runtime) => {
1452
+ if (runtime.j) return;
1453
+ let onNextSibling,
1454
+ placeholder,
1455
+ nextSibling,
1456
+ placeholders = runtime.p = {},
1457
+ replace = (id, container) => runtime.l[id].replaceWith(...container.childNodes);
1458
+ runtime.d.head.append(
1459
+ runtime.d.querySelector("style[" + runtime.i + "]") || ""
1460
+ );
1461
+ runtime.j = {};
1462
+ runtime.x = (op, id, node, placeholderRoot, placeholderCb) => {
1463
+ if (node == nextSibling) {
1464
+ onNextSibling();
1465
+ }
1466
+
1467
+ if (op == "#") {
1468
+ (placeholders[id] = placeholder).i++;
1469
+ } else if (op == "!") {
1470
+ if (runtime.l[id] && placeholders[id]) {
1471
+ nextSibling = node.nextSibling;
1472
+ onNextSibling = () => placeholders[id].c();
1473
+ }
1474
+ } else if (node.tagName == "T" && (id = node.getAttribute(runtime.i))) {
1475
+ nextSibling = node.nextSibling;
1476
+ onNextSibling = () => {
1477
+ node.remove();
1478
+ placeholderRoot || replace(id, node);
1479
+ placeholder.c();
1480
+ };
1481
+ placeholder =
1482
+ placeholders[id] ||
1483
+ (placeholderRoot = placeholders[id] =
1484
+ {
1485
+ i: runtime.l[id] ? 1 : 2,
1486
+ c(start = runtime.l["^" + id]) {
1487
+ if (--placeholderRoot.i) return 1;
1488
+ for (
1489
+ ;
1490
+ (nextSibling =
1491
+ runtime.l[id].previousSibling || start).remove(),
1492
+ start != nextSibling;
1493
+
1494
+ );
1495
+ replace(id, node);
1496
+ },
1497
+ });
1498
+ // repurpose "op" for callbacks ...carefully
1499
+ if ((op = runtime.j[id])) {
1500
+ placeholderCb = placeholder.c;
1501
+ placeholder.c = () => placeholderCb() || op(runtime.r);
1502
+ }
1503
+ }
1504
+ };
1505
+ })`;
1506
+ //#endregion
1507
+ //#region src/html/writer.ts
1508
+ let $chunk;
1509
+ const NOOP$2 = () => {};
1510
+ function getChunk() {
1511
+ return $chunk;
1512
+ }
1442
1513
  function getContext(key) {
1443
1514
  return $chunk.context?.[key];
1444
1515
  }
@@ -1454,8 +1525,28 @@ function _html(html) {
1454
1525
  function writeScript(script) {
1455
1526
  $chunk.writeScript(script);
1456
1527
  }
1528
+ function writeWaitReady(readyId, renderer, input) {
1529
+ const chunk = $chunk;
1530
+ const { boundary } = chunk;
1531
+ const body = new Chunk(boundary, null, chunk.context, {
1532
+ readyId,
1533
+ parent: chunk.serializeState,
1534
+ resumes: "",
1535
+ writeScopes: {},
1536
+ flushScopes: false
1537
+ });
1538
+ const bodyEnd = body.render(renderer, input);
1539
+ if (body === bodyEnd) {
1540
+ chunk.writeHTML(body.html);
1541
+ body.deferOwnReady();
1542
+ chunk.deferredReady = push(chunk.deferredReady, body);
1543
+ } else {
1544
+ bodyEnd.next = $chunk = chunk.fork(boundary, chunk.next);
1545
+ chunk.next = body;
1546
+ }
1547
+ }
1457
1548
  function _script(scopeId, registryId) {
1458
- if ($chunk.context?.[kIsAsync]) _resume_branch(scopeId);
1549
+ if ($chunk.serializeState.readyId || $chunk.context?.[kIsAsync]) _resume_branch(scopeId);
1459
1550
  $chunk.boundary.state.needsMainRuntime = true;
1460
1551
  $chunk.writeEffect(scopeId, registryId);
1461
1552
  }
@@ -1467,7 +1558,7 @@ function _attr_content(nodeAccessor, scopeId, content, serializeReason) {
1467
1558
  else render();
1468
1559
  if (_peek_scope_id() !== branchId) {
1469
1560
  if (shouldResume) writeScope(scopeId, {
1470
- ["BranchScopes:" + nodeAccessor]: referenceScope(writeScope(branchId, {})),
1561
+ ["BranchScopes:" + nodeAccessor]: writeScope(branchId, {}),
1471
1562
  ["ConditionalRenderer:" + nodeAccessor]: render?.["id"]
1472
1563
  });
1473
1564
  } else _scope_id();
@@ -1491,13 +1582,20 @@ function withContext(key, value, cb, cbValue) {
1491
1582
  }
1492
1583
  }
1493
1584
  function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
1494
- _scope_with_id(parentScopeId)[scopeOffsetAccessor] = _scope_id();
1495
- const childScope = _scope_with_id(childScopeId);
1496
- childScope["#TagVariable"] = _resume({}, registryId, parentScopeId);
1585
+ writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
1586
+ const childScope = writeScopePassive(childScopeId, { ["#TagVariable"]: _resume({}, registryId, parentScopeId) });
1497
1587
  if (nodeAccessor !== void 0) writeScope(parentScopeId, { ["BranchScopes:" + nodeAccessor]: childScope });
1498
1588
  }
1589
+ function writeScopePassive(scopeId, partialScope) {
1590
+ const target = $chunk.serializeState;
1591
+ const scope = _scope_with_id(scopeId);
1592
+ const passive = target.passiveScopes ||= {};
1593
+ Object.assign(scope, partialScope);
1594
+ passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope);
1595
+ return scope;
1596
+ }
1499
1597
  function _resume(val, id, scopeId) {
1500
- return scopeId === void 0 ? register(id, val) : $chunk.boundary.state.serializer.register(id, val, _scope_with_id(scopeId));
1598
+ return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId));
1501
1599
  }
1502
1600
  function _id() {
1503
1601
  const state = $chunk.boundary.state;
@@ -1608,7 +1706,7 @@ function forBranches(by, iterate, scopeId, accessor, serializeBranch, serializeM
1608
1706
  withBranchId(branchId, () => {
1609
1707
  render();
1610
1708
  const branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { ["#LoopKey"]: itemKey } : {});
1611
- if (!resumeMarker) loopScopes = push(loopScopes, referenceScope(branchScope));
1709
+ if (!resumeMarker) loopScopes = push(loopScopes, branchScope);
1612
1710
  });
1613
1711
  });
1614
1712
  if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
@@ -1624,7 +1722,7 @@ function _if(cb, scopeId, accessor, serializeBranch, serializeMarker, serializeS
1624
1722
  const shouldWriteBranch = resumeBranch && branchIndex !== void 0;
1625
1723
  if (shouldWriteBranch && (branchIndex || !resumeMarker)) writeScope(scopeId, {
1626
1724
  ["ConditionalRenderer:" + accessor]: branchIndex || void 0,
1627
- ["BranchScopes:" + accessor]: resumeMarker ? void 0 : referenceScope(writeScope(branchId, {}))
1725
+ ["BranchScopes:" + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
1628
1726
  });
1629
1727
  writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
1630
1728
  }
@@ -1637,46 +1735,34 @@ function writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, p
1637
1735
  } else $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
1638
1736
  else $chunk.writeHTML(endTag);
1639
1737
  }
1640
- function scopeHasReference(scope) {
1641
- return !!scope[K_SCOPE_REFERENCED];
1642
- }
1643
- function referenceScope(scope) {
1644
- scope[K_SCOPE_REFERENCED] = 1;
1645
- return scope;
1646
- }
1647
1738
  let writeScope = (scopeId, partialScope) => {
1648
- return writeScopeToState($chunk.boundary.state, scopeId, partialScope);
1649
- };
1650
- function writeScopeToState(state, scopeId, partialScope) {
1651
- const { scopes } = state;
1652
- let scope = scopes.get(scopeId);
1739
+ const { state } = $chunk.boundary;
1740
+ const target = $chunk.serializeState;
1741
+ const scope = scopeWithId(state, scopeId);
1742
+ const pending = target.writeScopes[scopeId];
1653
1743
  state.needsMainRuntime = true;
1654
- if (scope) Object.assign(scope, partialScope);
1655
- else {
1656
- scope = partialScope;
1657
- scope[K_SCOPE_ID] = scopeId;
1658
- state.scopes.set(scopeId, scope);
1659
- }
1660
- if (state.writeScopes) state.writeScopes[scopeId] = scope;
1661
- else state.writeScopes = { [scopeId]: scope };
1744
+ Object.assign(scope, partialScope);
1745
+ if (pending && pending !== partialScope) Object.assign(pending, partialScope);
1746
+ else target.writeScopes[scopeId] = partialScope;
1747
+ target.flushScopes = true;
1662
1748
  return scope;
1663
- }
1749
+ };
1664
1750
  writeScope = ((writeScope) => (scopeId, partialScope, file, loc, vars) => {
1665
1751
  const scope = writeScope(scopeId, partialScope);
1666
1752
  if (file && loc !== void 0) setDebugInfo(scope, file, loc, vars);
1667
1753
  return scope;
1668
1754
  })(writeScope);
1669
1755
  function _existing_scope(scopeId) {
1670
- return writeScope(scopeId, _scope_with_id(scopeId));
1756
+ return writeScope(scopeId, {});
1671
1757
  }
1672
1758
  function _scope_with_id(scopeId) {
1673
- const { state } = $chunk.boundary;
1674
- let scope = state.scopes.get(scopeId);
1675
- if (!scope) {
1676
- scope = { [K_SCOPE_ID]: scopeId };
1677
- state.scopes.set(scopeId, scope);
1678
- }
1679
- return referenceScope(scope);
1759
+ return scopeWithId($chunk.boundary.state, scopeId);
1760
+ }
1761
+ function scopeWithId(state, scopeId) {
1762
+ const { scopes } = state;
1763
+ let scope = scopes.get(scopeId);
1764
+ if (!scope) scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId });
1765
+ return scope;
1680
1766
  }
1681
1767
  function $global() {
1682
1768
  return $chunk.boundary.state.$global;
@@ -1694,7 +1780,7 @@ function _await(scopeId, accessor, promise, content, serializeMarker) {
1694
1780
  }
1695
1781
  const chunk = $chunk;
1696
1782
  const { boundary } = chunk;
1697
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context);
1783
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next);
1698
1784
  chunk.async = true;
1699
1785
  if (chunk.context?.[kPendingContexts]) chunk.context = {
1700
1786
  ...chunk.context,
@@ -1739,22 +1825,24 @@ function _try(scopeId, accessor, content, input) {
1739
1825
  function tryPlaceholder(content, placeholder, branchId) {
1740
1826
  const chunk = $chunk;
1741
1827
  const { boundary } = chunk;
1742
- const body = new Chunk(boundary, null, chunk.context);
1828
+ const body = chunk.fork(boundary, null);
1743
1829
  if (body === body.render(content)) {
1744
1830
  chunk.append(body);
1745
1831
  return;
1746
1832
  }
1747
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context);
1748
- chunk.placeholderBody = body;
1749
- chunk.placeholderRender = placeholder;
1750
- chunk.placeholderBranchId = branchId;
1833
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next);
1834
+ chunk.placeholder = {
1835
+ body,
1836
+ render: placeholder,
1837
+ branchId
1838
+ };
1751
1839
  }
1752
1840
  function tryCatch(content, catchContent) {
1753
1841
  const chunk = $chunk;
1754
1842
  const { boundary } = chunk;
1755
1843
  const { state } = boundary;
1756
1844
  const catchBoundary = new Boundary(state);
1757
- const body = new Chunk(catchBoundary, null, chunk.context);
1845
+ const body = chunk.fork(catchBoundary, null);
1758
1846
  const bodyEnd = body.render(content);
1759
1847
  if (catchBoundary.signal.aborted) {
1760
1848
  catchContent(catchBoundary.signal.reason);
@@ -1766,7 +1854,7 @@ function tryCatch(content, catchContent) {
1766
1854
  }
1767
1855
  const reorderId = state.nextReorderId();
1768
1856
  const endMarker = state.mark("!", reorderId);
1769
- const bodyNext = bodyEnd.next = $chunk = new Chunk(boundary, chunk.next, body.context);
1857
+ const bodyNext = bodyEnd.next = $chunk = body.fork(boundary, chunk.next);
1770
1858
  chunk.next = body;
1771
1859
  chunk.writeHTML(state.mark("!^", reorderId));
1772
1860
  bodyEnd.writeHTML(endMarker);
@@ -1787,12 +1875,12 @@ function tryCatch(content, catchContent) {
1787
1875
  cur.needsWalk = true;
1788
1876
  cur.html = endMarker;
1789
1877
  cur.scripts = cur.effects = cur.lastEffect = "";
1790
- cur.placeholderBody = cur.placeholderRender = cur.reorderId = null;
1878
+ cur.placeholder = cur.reorderId = cur.deferredReady = null;
1791
1879
  }
1792
1880
  cur = next;
1793
1881
  } while (cur !== bodyNext);
1794
1882
  }
1795
- const catchChunk = new Chunk(boundary, null, chunk.context);
1883
+ const catchChunk = chunk.fork(boundary, null);
1796
1884
  catchChunk.reorderId = reorderId;
1797
1885
  catchChunk.render(catchContent, catchBoundary.signal.reason);
1798
1886
  state.reorder(catchChunk);
@@ -1806,10 +1894,11 @@ var State = class {
1806
1894
  tagId = 1;
1807
1895
  scopeId = 1;
1808
1896
  reorderId = 1;
1809
- lastSerializedScopeId = this.scopeId;
1897
+ readyGate = 1;
1810
1898
  hasGlobals = false;
1811
1899
  needsMainRuntime = false;
1812
1900
  hasMainRuntime = false;
1901
+ hasReadyRuntime = false;
1813
1902
  hasReorderRuntime = false;
1814
1903
  hasWrittenResume = false;
1815
1904
  walkOnNextFlush = false;
@@ -1819,11 +1908,11 @@ var State = class {
1819
1908
  serializer = new Serializer();
1820
1909
  writeReorders = null;
1821
1910
  scopes = /* @__PURE__ */ new Map();
1822
- writeScopes = null;
1823
- ensureReady = null;
1911
+ flushScopes = false;
1912
+ writeScopes = {};
1913
+ readyIds = null;
1824
1914
  serializeReason;
1825
1915
  constructor($global) {
1826
- this.$global = $global;
1827
1916
  this.$global = $global;
1828
1917
  if ($global.cspNonce) this.nonceAttr = " nonce" + attrAssignment($global.cspNonce);
1829
1918
  }
@@ -1842,6 +1931,17 @@ var State = class {
1842
1931
  this.writeReorders = [chunk];
1843
1932
  }
1844
1933
  }
1934
+ writeReady(id, resumes) {
1935
+ const readyKey = toObjectKey(id);
1936
+ if (this.readyIds?.has(id)) return this.readyAccess(readyKey) + ".push(" + resumes + ")";
1937
+ (this.readyIds ||= /* @__PURE__ */ new Set()).add(id);
1938
+ if (this.hasReadyRuntime) return this.readyAccess(readyKey) + "=[" + resumes + "]";
1939
+ this.hasReadyRuntime = true;
1940
+ return this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}";
1941
+ }
1942
+ readyAccess(readyKey) {
1943
+ return this.runtimePrefix + ".b" + toAccess(readyKey);
1944
+ }
1845
1945
  nextReorderId() {
1846
1946
  const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
1847
1947
  let n = this.reorderId++;
@@ -1860,7 +1960,6 @@ var Boundary = class extends AbortController {
1860
1960
  constructor(state, parent) {
1861
1961
  super();
1862
1962
  this.state = state;
1863
- this.state = state;
1864
1963
  this.signal.addEventListener("abort", () => {
1865
1964
  this.count = 0;
1866
1965
  this.state = new State(this.state.$global);
@@ -1872,7 +1971,7 @@ var Boundary = class extends AbortController {
1872
1971
  });
1873
1972
  }
1874
1973
  flush() {
1875
- if (!this.signal.aborted) flushSerializer(this);
1974
+ if (!this.signal.aborted) flushSerializer(this, this.state);
1876
1975
  return this.count ? 1 : this.signal.aborted ? 2 : 0;
1877
1976
  }
1878
1977
  startAsync() {
@@ -1886,10 +1985,11 @@ var Boundary = class extends AbortController {
1886
1985
  }
1887
1986
  }
1888
1987
  };
1889
- var Chunk = class {
1988
+ var Chunk = class Chunk {
1890
1989
  boundary;
1891
1990
  next;
1892
1991
  context;
1992
+ serializeState;
1893
1993
  html = "";
1894
1994
  scripts = "";
1895
1995
  effects = "";
@@ -1898,16 +1998,16 @@ var Chunk = class {
1898
1998
  consumed = false;
1899
1999
  needsWalk = false;
1900
2000
  reorderId = null;
1901
- placeholderBody = null;
1902
- placeholderRender = null;
1903
- placeholderBranchId = null;
1904
- constructor(boundary, next, context) {
1905
- this.boundary = boundary;
1906
- this.next = next;
1907
- this.context = context;
2001
+ deferredReady = null;
2002
+ placeholder = null;
2003
+ constructor(boundary, next, context, serializeState) {
1908
2004
  this.boundary = boundary;
1909
2005
  this.next = next;
1910
2006
  this.context = context;
2007
+ this.serializeState = serializeState;
2008
+ }
2009
+ fork(boundary, next) {
2010
+ return new Chunk(boundary, next, this.context, this.serializeState);
1911
2011
  }
1912
2012
  writeHTML(html) {
1913
2013
  this.html += html;
@@ -1927,16 +2027,31 @@ var Chunk = class {
1927
2027
  this.effects = concatEffects(this.effects, chunk.effects);
1928
2028
  this.scripts = concatScripts(this.scripts, chunk.scripts);
1929
2029
  this.lastEffect = chunk.lastEffect || this.lastEffect;
2030
+ this.deferredReady = concat(this.deferredReady, chunk.takeDeferredReady());
2031
+ }
2032
+ takeDeferredReady() {
2033
+ const { deferredReady } = this;
2034
+ this.deferredReady = null;
2035
+ return deferredReady;
2036
+ }
2037
+ deferOwnReady() {
2038
+ if (this.serializeState.readyId && (this.effects || this.scripts || this.serializeState.flushScopes)) {
2039
+ const deferred = this.fork(this.boundary, null);
2040
+ deferred.effects = this.effects;
2041
+ deferred.scripts = this.scripts;
2042
+ this.effects = this.scripts = this.lastEffect = "";
2043
+ this.deferredReady = concat(deferred, this.deferredReady);
2044
+ }
1930
2045
  }
1931
2046
  flushPlaceholder() {
1932
- if (this.placeholderBody) {
1933
- const body = this.placeholderBody.consume();
2047
+ const { placeholder } = this;
2048
+ if (placeholder) {
2049
+ const body = placeholder.body.consume();
1934
2050
  if (body.async) {
1935
2051
  const { state } = this.boundary;
1936
- const reorderId = body.reorderId = this.placeholderBranchId ? this.placeholderBranchId + "" : state.nextReorderId();
1937
- this.placeholderBranchId = null;
2052
+ const reorderId = body.reorderId = placeholder.branchId ? placeholder.branchId + "" : state.nextReorderId();
1938
2053
  this.writeHTML(state.mark("!^", reorderId));
1939
- const after = this.render(this.placeholderRender);
2054
+ const after = this.render(placeholder.render);
1940
2055
  if (after !== this) this.boundary.abort(/* @__PURE__ */ new Error("An @placeholder cannot contain async content."));
1941
2056
  after.writeHTML(state.mark("!", reorderId));
1942
2057
  state.reorder(body);
@@ -1944,33 +2059,38 @@ var Chunk = class {
1944
2059
  body.next = this.next;
1945
2060
  this.next = body;
1946
2061
  }
1947
- this.placeholderRender = this.placeholderBody = null;
2062
+ this.placeholder = null;
1948
2063
  }
1949
2064
  }
1950
2065
  consume() {
1951
2066
  let cur = this;
1952
- let needsWalk = cur.needsWalk;
1953
- if (cur.next && !cur.async) {
1954
- let html = "";
1955
- let effects = "";
1956
- let scripts = "";
1957
- let lastEffect = "";
1958
- do {
1959
- cur.flushPlaceholder();
1960
- needsWalk ||= cur.needsWalk;
1961
- html += cur.html;
2067
+ let html = "";
2068
+ let effects = "";
2069
+ let scripts = "";
2070
+ let lastEffect = "";
2071
+ let needsWalk = false;
2072
+ let deferredReady;
2073
+ while (cur.next && !cur.async) {
2074
+ cur.flushPlaceholder();
2075
+ needsWalk ||= cur.needsWalk;
2076
+ html += cur.html;
2077
+ if (cur.serializeState.readyId) deferredReady = push(deferredReady, cur);
2078
+ else {
1962
2079
  effects = concatEffects(effects, cur.effects);
1963
2080
  scripts = concatScripts(scripts, cur.scripts);
1964
2081
  lastEffect = cur.lastEffect || lastEffect;
1965
- cur.consumed = true;
1966
- cur = cur.next;
1967
- } while (cur.next && !cur.async);
1968
- cur.needsWalk = needsWalk;
1969
- cur.html = html + cur.html;
1970
- cur.effects = concatEffects(effects, cur.effects);
1971
- cur.scripts = concatScripts(scripts, cur.scripts);
1972
- cur.lastEffect = lastEffect;
2082
+ }
2083
+ deferredReady = concat(deferredReady, cur.takeDeferredReady());
2084
+ cur.consumed = true;
2085
+ cur = cur.next;
1973
2086
  }
2087
+ cur.deferOwnReady();
2088
+ cur.deferredReady = concat(deferredReady, cur.deferredReady);
2089
+ cur.needsWalk ||= needsWalk;
2090
+ cur.html = html + cur.html;
2091
+ cur.effects = concatEffects(effects, cur.effects);
2092
+ cur.scripts = concatScripts(scripts, cur.scripts);
2093
+ cur.lastEffect ||= lastEffect;
1974
2094
  return cur;
1975
2095
  }
1976
2096
  render(content, val) {
@@ -1986,28 +2106,57 @@ var Chunk = class {
1986
2106
  $chunk = prev;
1987
2107
  }
1988
2108
  }
2109
+ flushReadyScripts(reservations) {
2110
+ const { boundary, serializeState } = this;
2111
+ const { readyId } = serializeState;
2112
+ let scripts = "";
2113
+ forEach(this.takeDeferredReady(), (chunk) => {
2114
+ scripts = concatScripts(scripts, chunk.flushReadyScripts(reservations));
2115
+ });
2116
+ if (readyId && !this.async) {
2117
+ const { state } = boundary;
2118
+ flushSerializer(boundary, serializeState);
2119
+ const deps = state.serializer.takeChannelDeps();
2120
+ const { effects } = this;
2121
+ const { resumes } = serializeState;
2122
+ const chunkScripts = this.scripts;
2123
+ serializeState.resumes = "";
2124
+ this.effects = this.scripts = "";
2125
+ this.lastEffect = "";
2126
+ if (resumes || effects) {
2127
+ state.needsMainRuntime = true;
2128
+ const batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
2129
+ if (reservations) {
2130
+ const gate = state.readyGate++;
2131
+ reservations.push(state.writeReady(readyId, gate + ""));
2132
+ scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
2133
+ } else scripts = concatScripts(scripts, state.writeReady(readyId, batch));
2134
+ }
2135
+ scripts = concatScripts(scripts, chunkScripts);
2136
+ }
2137
+ return scripts;
2138
+ }
1989
2139
  flushScript() {
1990
- const { boundary, effects } = this;
2140
+ const { boundary } = this;
1991
2141
  const { state } = boundary;
1992
2142
  const { $global, runtimePrefix, nonceAttr } = state;
1993
- let { html, scripts } = this;
1994
2143
  let needsWalk = state.walkOnNextFlush;
1995
2144
  if (needsWalk) state.walkOnNextFlush = false;
2145
+ let readyResumeScripts = this.flushReadyScripts();
2146
+ for (let channel; channel = state.serializer.pendingReadyChannel();) {
2147
+ const resumes = state.serializer.stringifyScopes([], 0, boundary, channel);
2148
+ const deps = state.serializer.takeChannelDeps();
2149
+ state.needsMainRuntime = true;
2150
+ readyResumeScripts = concatScripts(readyResumeScripts, state.writeReady(channel.readyId, concatSequence(depsMarker(deps), resumes)));
2151
+ }
2152
+ if (readyResumeScripts) needsWalk = true;
2153
+ const { effects } = this;
2154
+ let { html, scripts } = this;
1996
2155
  if (state.needsMainRuntime && !state.hasMainRuntime) {
1997
2156
  state.hasMainRuntime = true;
1998
2157
  scripts = concatScripts(scripts, WALKER_RUNTIME_CODE + "(\"" + $global.runtimeId + "\")(\"" + $global.renderId + "\")");
1999
2158
  }
2000
- if (state.ensureReady && state.hasMainRuntime) {
2001
- let first = true;
2002
- for (const id in state.ensureReady) {
2003
- if (state.ensureReady[id]) {
2004
- state.ensureReady[id] = 0;
2005
- if (first) scripts = concatScripts(scripts, "(" + runtimePrefix + ".b={})" + toAccess(toObjectKey(id)) + "=1");
2006
- else scripts = concatScripts(scripts, runtimePrefix + ".b" + toAccess(toObjectKey(id)) + "=1");
2007
- }
2008
- first = false;
2009
- }
2010
- }
2159
+ scripts = concatScripts(scripts, readyResumeScripts);
2011
2160
  if (effects) {
2012
2161
  needsWalk = true;
2013
2162
  state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"";
@@ -2026,6 +2175,7 @@ var Chunk = class {
2026
2175
  }
2027
2176
  for (const reorderedChunk of state.writeReorders) {
2028
2177
  const { reorderId } = reorderedChunk;
2178
+ const readyReservations = [];
2029
2179
  let reorderHTML = "";
2030
2180
  let reorderEffects = "";
2031
2181
  let reorderScripts = "";
@@ -2033,11 +2183,13 @@ var Chunk = class {
2033
2183
  reorderedChunk.reorderId = null;
2034
2184
  for (;;) {
2035
2185
  cur.flushPlaceholder();
2186
+ cur.deferOwnReady();
2036
2187
  const { next } = cur;
2188
+ const readyResumeScripts = cur.flushReadyScripts(readyReservations);
2037
2189
  cur.consumed = true;
2038
2190
  reorderHTML += cur.html;
2039
2191
  reorderEffects = concatEffects(reorderEffects, cur.effects);
2040
- reorderScripts = concatScripts(reorderScripts, cur.scripts);
2192
+ reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts));
2041
2193
  if (cur.async) {
2042
2194
  reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId());
2043
2195
  cur.html = cur.effects = cur.scripts = cur.lastEffect = "";
@@ -2053,6 +2205,7 @@ var Chunk = class {
2053
2205
  }
2054
2206
  reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")");
2055
2207
  }
2208
+ for (const reservation of readyReservations) scripts = concatScripts(scripts, reservation);
2056
2209
  scripts = concatScripts(scripts, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}");
2057
2210
  html += "<t " + state.commentPrefix + "=" + reorderId + ">" + reorderHTML + "</t>";
2058
2211
  }
@@ -2086,35 +2239,60 @@ var Chunk = class {
2086
2239
  return html;
2087
2240
  }
2088
2241
  };
2089
- function flushSerializer(boundary) {
2242
+ function flushSerializer(boundary, serializeState) {
2090
2243
  const { state } = boundary;
2091
- const { writeScopes, serializer } = state;
2092
- const { flushed } = serializer;
2093
- if (writeScopes || flushed) {
2094
- let shouldSerialize = false;
2095
- const serializeData = [];
2096
- let { lastSerializedScopeId } = state;
2097
- if (!state.hasGlobals) {
2244
+ const { serializer } = state;
2245
+ const pending = serializer.pending(serializeState);
2246
+ if (serializeState.flushScopes || pending) {
2247
+ const { writeScopes, passiveScopes } = serializeState;
2248
+ const isBlockingState = serializeState !== state;
2249
+ const flushes = [];
2250
+ let globals = 0;
2251
+ if (passiveScopes) for (const key in passiveScopes) {
2252
+ const props = writeScopes[key];
2253
+ if (props) {
2254
+ writeScopes[key] = Object.assign(passiveScopes[key], props);
2255
+ delete passiveScopes[key];
2256
+ }
2257
+ }
2258
+ if (!isBlockingState && !state.hasGlobals) {
2098
2259
  state.hasGlobals = true;
2099
- serializeData.push(getFilteredGlobals(state.$global));
2100
- shouldSerialize = true;
2260
+ globals = getFilteredGlobals(state.$global);
2101
2261
  }
2102
2262
  for (const key in writeScopes) {
2103
- const scope = writeScopes[key];
2104
- if (scopeHasReference(scope) || Object.getOwnPropertyNames(scope).length) {
2105
- const scopeId = getScopeId(scope);
2106
- const scopeIdDelta = scopeId - lastSerializedScopeId;
2107
- lastSerializedScopeId = scopeId + 1;
2108
- if (scopeIdDelta) serializeData.push(scopeIdDelta);
2109
- serializeData.push(scope);
2110
- shouldSerialize = true;
2111
- }
2263
+ const scopeId = +key;
2264
+ const props = writeScopes[scopeId];
2265
+ if (Object.getOwnPropertyNames(props).length) flushes.push([
2266
+ scopeId,
2267
+ state.scopes.get(scopeId),
2268
+ props
2269
+ ]);
2270
+ }
2271
+ if (flushes.length || globals || pending) {
2272
+ if (isBlockingState && !state.hasGlobals) flushSerializerGlobals(boundary);
2273
+ serializeState.resumes = concatSequence(serializeState.resumes, serializer.stringifyScopes(flushes, globals, boundary, serializeState));
2112
2274
  }
2113
- if (shouldSerialize) state.resumes = concatSequence(state.resumes, serializer.stringify(serializeData, boundary));
2114
- state.lastSerializedScopeId = lastSerializedScopeId;
2115
- state.writeScopes = null;
2116
- if (flushed) state.walkOnNextFlush = true;
2275
+ serializeState.writeScopes = {};
2276
+ serializeState.flushScopes = false;
2277
+ if (pending) state.walkOnNextFlush = true;
2278
+ }
2279
+ }
2280
+ function flushSerializerGlobals(boundary) {
2281
+ const { state } = boundary;
2282
+ const globals = getFilteredGlobals(state.$global);
2283
+ if (globals) {
2284
+ state.hasGlobals = true;
2285
+ state.needsMainRuntime = true;
2286
+ state.resumes = concatSequence(state.resumes, state.serializer.stringifyScopes([], globals, boundary));
2287
+ }
2288
+ }
2289
+ function depsMarker(deps) {
2290
+ let marker = "";
2291
+ if (deps) {
2292
+ for (const dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
2293
+ marker += "]";
2117
2294
  }
2295
+ return marker;
2118
2296
  }
2119
2297
  function _trailers(html) {
2120
2298
  $chunk.boundary.state.trailerHTML += html;
@@ -2166,8 +2344,12 @@ function getFilteredGlobals($global) {
2166
2344
  return filtered;
2167
2345
  }
2168
2346
  function _subscribe(subscribers, scope) {
2169
- if (subscribers) $chunk.boundary.state.serializer.writeCall(scope, subscribers, "add");
2170
- return referenceScope(scope);
2347
+ if (subscribers) {
2348
+ const { serializer } = $chunk.boundary.state;
2349
+ if (!$chunk.serializeState.readyId && !serializer.written(subscribers)) subscribers.add(scope);
2350
+ else serializer.writeCall(scope, subscribers, "add", $chunk.serializeState);
2351
+ }
2352
+ return scope;
2171
2353
  }
2172
2354
  //#endregion
2173
2355
  //#region src/html/attrs.ts
@@ -2350,14 +2532,6 @@ function normalizeBoolAttrValue(value) {
2350
2532
  if (value != null && value !== false) return true;
2351
2533
  }
2352
2534
  //#endregion
2353
- //#region src/common/compat-meta.ts
2354
- const RENDERER_REGISTER_ID = "$compat_renderer";
2355
- const SET_SCOPE_REGISTER_ID = "$compat_setScope";
2356
- const RENDER_BODY_ID = "$compat_renderBody";
2357
- //#endregion
2358
- //#region src/common/meta.ts
2359
- const DYNAMIC_TAG_SCRIPT_REGISTER_ID = "_dynamicTagScript";
2360
- //#endregion
2361
2535
  //#region src/html/dynamic-tag.ts
2362
2536
  const voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/;
2363
2537
  let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => {
@@ -2389,7 +2563,7 @@ let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, s
2389
2563
  const childScope = getScopeById(branchId);
2390
2564
  const needsScript = childScope && (childScope[`EventAttributes:#${renderer}/0`] || childScope[`ControlledHandler:#${renderer}/0`]);
2391
2565
  if (needsScript) {
2392
- childScope["#Renderer"] = renderer;
2566
+ writeScope(branchId, { ["#Renderer"]: renderer });
2393
2567
  _script(branchId, DYNAMIC_TAG_SCRIPT_REGISTER_ID);
2394
2568
  }
2395
2569
  if (shouldResume || needsScript) _html(state.mark("'", scopeId + " " + accessor + " " + branchId));
@@ -2431,115 +2605,6 @@ const patchDynamicTag = ((originalDynamicTag) => (patch) => {
2431
2605
  };
2432
2606
  })(_dynamic_tag);
2433
2607
  //#endregion
2434
- //#region src/html/compat.ts
2435
- const K_TAGS_API_STATE = Symbol();
2436
- const COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap();
2437
- const compat = {
2438
- $global,
2439
- fork: _await,
2440
- write: _html,
2441
- writeScript,
2442
- nextScopeId: _scope_id,
2443
- peekNextScopeId: _peek_scope_id,
2444
- isInResumedBranch,
2445
- ensureState($global) {
2446
- let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state;
2447
- if (!state) {
2448
- $global.runtimeId ||= "M";
2449
- $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_";
2450
- $global[K_TAGS_API_STATE] = state = new State($global);
2451
- }
2452
- return state;
2453
- },
2454
- isTagsAPI(fn) {
2455
- return !!fn["id"];
2456
- },
2457
- onFlush(fn) {
2458
- const { flushHTML } = Chunk.prototype;
2459
- Chunk.prototype.flushHTML = function() {
2460
- fn(this);
2461
- return flushHTML.call(this);
2462
- };
2463
- },
2464
- patchDynamicTag,
2465
- writeSetScopeForComponent(branchId, m5c, m5i) {
2466
- writeScope(branchId, {
2467
- m5c,
2468
- m5i
2469
- });
2470
- _script(branchId, SET_SCOPE_REGISTER_ID);
2471
- },
2472
- toJSON(state) {
2473
- return function toJSON() {
2474
- let compatRegistered = COMPAT_REGISTRY.get(this);
2475
- if (!compatRegistered) {
2476
- const registered = getRegistered(this);
2477
- if (registered) {
2478
- const scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
2479
- if (scopeId !== void 0) writeScopeToState(state, scopeId, {});
2480
- COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
2481
- }
2482
- }
2483
- return compatRegistered;
2484
- };
2485
- },
2486
- flushScript($global) {
2487
- const boundary = new Boundary(this.ensureState($global));
2488
- if (boundary.flush() === 1) throw new Error("Cannot serialize promise across tags/class compat layer.");
2489
- return new Chunk(boundary, null, null).flushScript().scripts;
2490
- },
2491
- render(renderer, willRerender, classAPIOut, component, input, completeChunks) {
2492
- const boundary = new Boundary(this.ensureState(classAPIOut.global));
2493
- let head = new Chunk(boundary, null, null);
2494
- let normalizedInput = input;
2495
- if ("renderBody" in input) {
2496
- normalizedInput = {};
2497
- for (const key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
2498
- }
2499
- head.render(() => {
2500
- if (willRerender) {
2501
- const scopeId = _peek_scope_id();
2502
- writeScope(scopeId, { m5c: component.id });
2503
- _script(scopeId, SET_SCOPE_REGISTER_ID);
2504
- }
2505
- _set_serialize_reason(willRerender ? 1 : 0);
2506
- try {
2507
- renderer(normalizedInput);
2508
- } finally {
2509
- _set_serialize_reason(void 0);
2510
- }
2511
- const asyncOut = classAPIOut.beginAsync({
2512
- last: true,
2513
- timeout: -1
2514
- });
2515
- classAPIOut.onLast((next) => {
2516
- (boundary.onNext = () => {
2517
- if (boundary.signal.aborted) {
2518
- asyncOut.error(boundary.signal.reason);
2519
- boundary.onNext = NOOP$1;
2520
- } else if (!boundary.count) {
2521
- boundary.onNext = NOOP$1;
2522
- head = head.consume();
2523
- asyncOut.write(head.html);
2524
- asyncOut.script(head.scripts);
2525
- asyncOut.end();
2526
- head.html = head.scripts = "";
2527
- completeChunks.push(head);
2528
- next();
2529
- }
2530
- })();
2531
- });
2532
- });
2533
- },
2534
- registerRenderer(renderer, id) {
2535
- return register(RENDERER_REGISTER_ID, renderer, register(id, () => {}));
2536
- },
2537
- registerRenderBody(fn) {
2538
- register(RENDER_BODY_ID, fn);
2539
- }
2540
- };
2541
- function NOOP$1() {}
2542
- //#endregion
2543
2608
  //#region src/html/template.ts
2544
2609
  const _template = (templateId, renderer, page) => {
2545
2610
  renderer.render = render;
@@ -2566,9 +2631,9 @@ function render(input = {}) {
2566
2631
  renderId: getDefaultRenderId(this)
2567
2632
  };
2568
2633
  const state = new State($global);
2569
- const head = new Chunk(new Boundary(state, $global.signal), null, null);
2570
- if (this["embed"]) (state.ensureReady ||= {})[this["id"]] = 1;
2571
- head.render(this, input);
2634
+ const head = new Chunk(new Boundary(state, $global.signal), null, null, state);
2635
+ if (this["embed"]) head.render(() => writeWaitReady(this["id"], this, input));
2636
+ else head.render(this, input);
2572
2637
  return new ServerRendered(head);
2573
2638
  }
2574
2639
  function getDefaultRenderId(template) {
@@ -2704,7 +2769,7 @@ var ServerRendered = class {
2704
2769
  (boundary.onNext = () => {
2705
2770
  switch (!boundary.count && boundary.flush()) {
2706
2771
  case 2:
2707
- boundary.onNext = NOOP;
2772
+ boundary.onNext = NOOP$1;
2708
2773
  reject(boundary.signal.reason);
2709
2774
  break;
2710
2775
  case 0:
@@ -2727,7 +2792,7 @@ var ServerRendered = class {
2727
2792
  const status = boundary.flush();
2728
2793
  if (status === 2) {
2729
2794
  if (!tick) offTick(onNext);
2730
- boundary.onNext = NOOP;
2795
+ boundary.onNext = NOOP$1;
2731
2796
  onAbort(boundary.signal.reason);
2732
2797
  } else if (write || status === 0) {
2733
2798
  const html = (head = head.consume()).flushHTML();
@@ -2756,6 +2821,208 @@ var ServerRendered = class {
2756
2821
  return head.consume().flushHTML();
2757
2822
  }
2758
2823
  };
2824
+ function NOOP$1() {}
2825
+ //#endregion
2826
+ //#region src/html/assets.ts
2827
+ const kAssets = Symbol();
2828
+ const kBlockIndex = Symbol();
2829
+ const kDeferIndex = Symbol();
2830
+ const { hasOwnProperty } = {};
2831
+ let assetFlush;
2832
+ function withLoadAssets(renderer, assetId, triggers) {
2833
+ return Object.assign((input) => {
2834
+ const g = $global();
2835
+ addAsset(g, assetId, triggers);
2836
+ _html(flush(g, ""));
2837
+ return writeWaitReady(assetId, renderer, input);
2838
+ }, renderer);
2839
+ }
2840
+ function withPageAssets(template, runtime, assetId, runtimeId) {
2841
+ assetFlush = runtime;
2842
+ return Object.assign((input) => {
2843
+ const g = $global();
2844
+ if (runtimeId) {
2845
+ if (g.runtimeId !== "M" && g.runtimeId !== runtimeId) throw new Error(`$global.runtimeId ("${g.runtimeId}") conflicts with the runtimeId this entry was compiled with ("${runtimeId}").`);
2846
+ g.runtimeId = runtimeId;
2847
+ }
2848
+ addAsset(g, assetId);
2849
+ if (g.__flush__) {
2850
+ _html(flush(g, ""));
2851
+ return writeWaitReady(assetId, template, input);
2852
+ }
2853
+ g.__flush__ = flush;
2854
+ return template(input);
2855
+ }, template);
2856
+ }
2857
+ function _flush_head() {
2858
+ const g = $global();
2859
+ return g[kAssets] ? flush(g, "") : "";
2860
+ }
2861
+ function flush(g, html) {
2862
+ let result = "";
2863
+ const assets = g[kAssets];
2864
+ const { length } = assets;
2865
+ let bi = g[kBlockIndex];
2866
+ let di = g[kDeferIndex];
2867
+ for (; bi < length; bi++) result += assetFlush(g, "block", assets[bi].id);
2868
+ for (; di < length; di++) {
2869
+ const { id, triggers } = assets[di];
2870
+ const deferHTML = assetFlush(g, "defer", id);
2871
+ if (triggers) {
2872
+ if (deferHTML) writeTriggerScript(deferHTML, triggers);
2873
+ } else result += deferHTML;
2874
+ }
2875
+ g[kBlockIndex] = bi;
2876
+ g[kDeferIndex] = di;
2877
+ return result + html;
2878
+ }
2879
+ function addAsset(g, id, triggers) {
2880
+ const assets = g[kAssets];
2881
+ if (!assets) {
2882
+ g[kAssets] = [{
2883
+ id,
2884
+ triggers
2885
+ }];
2886
+ g[kBlockIndex] = g[kDeferIndex] = 0;
2887
+ } else if (!assets.find((a) => a.id === id)) assets.push({
2888
+ id,
2889
+ triggers
2890
+ });
2891
+ }
2892
+ function writeTriggerScript(html, triggers) {
2893
+ const htmlStr = _escape_script(JSON.stringify(html));
2894
+ const exprs = triggers.map((trigger) => {
2895
+ const options = trigger.options && toObjectExpression(trigger.options);
2896
+ switch (trigger.type) {
2897
+ case "visible": return `(e=>e&&new IntersectionObserver((e,i)=>e.some(e=>e.isIntersecting)&&i.disconnect()+l()${options ? `,${options}` : ""}).observe(e))(document.querySelector(${JSON.stringify(trigger.selector)})||l())`;
2898
+ case "idle": return `(self.requestIdleCallback||l)(l${options ? `,${options}` : ""})`;
2899
+ case "media": return `(m=>m.matches?l():m.addEventListener("change",l,{once:1}))(matchMedia(${JSON.stringify(trigger.selector)}))`;
2900
+ default: return `(e=>e?.addEventListener("${trigger.type.slice(3)}",l,{once:1}))(document.querySelector(${JSON.stringify(trigger.selector)})||l())`;
2901
+ }
2902
+ });
2903
+ writeScript(`((p,h,d,l=$=>d||p.insertAdjacentHTML("afterend",d=h))=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(document.currentScript,${htmlStr})`);
2904
+ }
2905
+ function toObjectExpression(options) {
2906
+ let result = "{";
2907
+ let sep = "";
2908
+ for (const key in options) if (hasOwnProperty.call(options, key)) {
2909
+ result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]);
2910
+ sep = ",";
2911
+ }
2912
+ return result + "}";
2913
+ }
2914
+ //#endregion
2915
+ //#region src/common/compat-meta.ts
2916
+ const SET_SCOPE_REGISTER_ID = "$compat_setScope";
2917
+ const RENDER_BODY_ID = "$compat_renderBody";
2918
+ //#endregion
2919
+ //#region src/html/compat.ts
2920
+ const K_TAGS_API_STATE = Symbol();
2921
+ const COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap();
2922
+ const compat = {
2923
+ $global,
2924
+ fork: _await,
2925
+ write: _html,
2926
+ writeScript,
2927
+ nextScopeId: _scope_id,
2928
+ peekNextScopeId: _peek_scope_id,
2929
+ isInResumedBranch,
2930
+ ensureState($global) {
2931
+ let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state;
2932
+ if (!state) {
2933
+ $global.runtimeId ||= "M";
2934
+ $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_";
2935
+ $global[K_TAGS_API_STATE] = state = new State($global);
2936
+ }
2937
+ return state;
2938
+ },
2939
+ isTagsAPI(fn) {
2940
+ return !!fn["id"];
2941
+ },
2942
+ onFlush(fn) {
2943
+ const { flushHTML } = Chunk.prototype;
2944
+ Chunk.prototype.flushHTML = function() {
2945
+ fn(this);
2946
+ return flushHTML.call(this);
2947
+ };
2948
+ },
2949
+ patchDynamicTag,
2950
+ writeSetScopeForComponent(branchId, m5c, m5i) {
2951
+ writeScope(branchId, {
2952
+ m5c,
2953
+ m5i
2954
+ });
2955
+ _script(branchId, SET_SCOPE_REGISTER_ID);
2956
+ },
2957
+ toJSON() {
2958
+ return function toJSON() {
2959
+ let compatRegistered = COMPAT_REGISTRY.get(this);
2960
+ if (!compatRegistered) {
2961
+ const registered = getRegistered(this);
2962
+ if (registered) {
2963
+ const scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
2964
+ if (scopeId !== void 0) _script(scopeId, SET_SCOPE_REGISTER_ID);
2965
+ COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
2966
+ }
2967
+ }
2968
+ return compatRegistered;
2969
+ };
2970
+ },
2971
+ flushScript($global) {
2972
+ const state = this.ensureState($global);
2973
+ const boundary = new Boundary(state);
2974
+ if (boundary.flush() === 1) throw new Error("Cannot serialize promise across tags/class compat layer.");
2975
+ return new Chunk(boundary, null, null, state).flushScript().scripts;
2976
+ },
2977
+ render(renderer, willRerender, classAPIOut, component, input, completeChunks) {
2978
+ const state = this.ensureState(classAPIOut.global);
2979
+ const boundary = new Boundary(state);
2980
+ let head = new Chunk(boundary, null, null, state);
2981
+ let normalizedInput = input;
2982
+ if ("renderBody" in input) {
2983
+ normalizedInput = {};
2984
+ for (const key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
2985
+ }
2986
+ head.render(() => {
2987
+ if (willRerender) {
2988
+ const scopeId = _peek_scope_id();
2989
+ writeScope(scopeId, { m5c: component.id });
2990
+ _script(scopeId, SET_SCOPE_REGISTER_ID);
2991
+ }
2992
+ _set_serialize_reason(willRerender ? 1 : 0);
2993
+ try {
2994
+ renderer(normalizedInput);
2995
+ } finally {
2996
+ _set_serialize_reason(void 0);
2997
+ }
2998
+ const asyncOut = classAPIOut.beginAsync({
2999
+ last: true,
3000
+ timeout: -1
3001
+ });
3002
+ classAPIOut.onLast((next) => {
3003
+ (boundary.onNext = () => {
3004
+ if (boundary.signal.aborted) {
3005
+ asyncOut.error(boundary.signal.reason);
3006
+ boundary.onNext = NOOP;
3007
+ } else if (!boundary.count) {
3008
+ boundary.onNext = NOOP;
3009
+ head = head.consume();
3010
+ asyncOut.write(head.html);
3011
+ asyncOut.script(head.scripts);
3012
+ asyncOut.end();
3013
+ head.html = head.scripts = "";
3014
+ completeChunks.push(head);
3015
+ next();
3016
+ }
3017
+ })();
3018
+ });
3019
+ });
3020
+ },
3021
+ register,
3022
+ registerRenderBody(fn) {
3023
+ register(RENDER_BODY_ID, fn);
3024
+ }
3025
+ };
2759
3026
  function NOOP() {}
2760
3027
  //#endregion
2761
3028
  exports.$global = $global;
@@ -2794,6 +3061,7 @@ exports._escape_comment = _escape_comment;
2794
3061
  exports._escape_script = _escape_script;
2795
3062
  exports._escape_style = _escape_style;
2796
3063
  exports._existing_scope = _existing_scope;
3064
+ exports._flush_head = _flush_head;
2797
3065
  exports._for_in = _for_in;
2798
3066
  exports._for_of = _for_of;
2799
3067
  exports._for_to = _for_to;
@@ -2836,3 +3104,5 @@ exports.forOfBy = forOfBy;
2836
3104
  exports.forStepBy = forStepBy;
2837
3105
  exports.forTo = forTo;
2838
3106
  exports.forUntil = forUntil;
3107
+ exports.withLoadAssets = withLoadAssets;
3108
+ exports.withPageAssets = withPageAssets;