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