marko 6.1.2 → 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.
Files changed (38) hide show
  1. package/dist/common/accessor.d.ts +5 -0
  2. package/dist/common/accessor.debug.d.ts +5 -0
  3. package/dist/common/compat-meta.d.ts +0 -1
  4. package/dist/common/opt.d.ts +3 -1
  5. package/dist/common/types.d.ts +1 -1
  6. package/dist/debug/dom.js +315 -122
  7. package/dist/debug/dom.mjs +306 -123
  8. package/dist/debug/html.js +922 -712
  9. package/dist/debug/html.mjs +920 -713
  10. package/dist/dom/compat.d.ts +3 -2
  11. package/dist/dom/control-flow.d.ts +2 -1
  12. package/dist/dom/load.d.ts +23 -0
  13. package/dist/dom/queue.d.ts +4 -2
  14. package/dist/dom/resume.d.ts +10 -8
  15. package/dist/dom/signals.d.ts +4 -3
  16. package/dist/dom.d.ts +3 -2
  17. package/dist/dom.js +195 -66
  18. package/dist/dom.mjs +195 -66
  19. package/dist/html/assets.d.ts +47 -0
  20. package/dist/html/compat.d.ts +3 -2
  21. package/dist/html/inlined-runtimes.d.ts +1 -1
  22. package/dist/html/inlined-runtimes.debug.d.ts +1 -1
  23. package/dist/html/serializer.d.ts +14 -9
  24. package/dist/html/writer.d.ts +34 -15
  25. package/dist/html.d.ts +1 -0
  26. package/dist/html.js +502 -345
  27. package/dist/html.mjs +502 -345
  28. package/dist/translator/index.d.ts +1 -0
  29. package/dist/translator/index.js +342 -76
  30. package/dist/translator/interop/index.d.ts +1 -0
  31. package/dist/translator/util/marko-config.d.ts +2 -0
  32. package/dist/translator/util/references.d.ts +1 -5
  33. package/dist/translator/util/runtime.d.ts +1 -0
  34. package/dist/translator/util/tag-name-type.d.ts +2 -0
  35. package/dist/translator/util/walks.d.ts +1 -1
  36. package/dist/translator/visitors/import-declaration.d.ts +10 -1
  37. package/dist/translator/visitors/tag/custom-tag.d.ts +7 -0
  38. package/package.json +2 -2
@@ -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] || (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
- }
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(")");
636
453
  }
637
- result = "(";
638
- buf.push(")");
639
- } else {
640
- if (hadBuf) {
641
- buf.pop();
642
- writeAssigned(state);
643
- }
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,39 +564,54 @@ 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
  }
599
+ const STRING_DEDUP_LENGTH = 12;
764
600
  function writeString(state, val, parent, accessor) {
765
- if (val.length > 30) {
601
+ if (val.length > STRING_DEDUP_LENGTH) {
766
602
  const ref = state.strs.get(val);
767
- if (ref) state.buf.push(ensureId(state, ref));
768
- else {
769
- state.strs.set(val, new Reference(parent, accessor, state.flush, state.buf.length));
770
- state.buf.push(quote(val, 0));
603
+ if (ref) {
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);
771
612
  }
772
- } else state.buf.push(quote(val, 0));
613
+ }
614
+ state.buf.push(quote(val, 0));
773
615
  return true;
774
616
  }
775
617
  function writeNumber(state, val) {
@@ -891,7 +733,7 @@ function writeArray(state, val, ref) {
891
733
  return true;
892
734
  }
893
735
  function writeDate(state, val) {
894
- state.buf.push("new Date(\"" + val.toISOString() + "\")");
736
+ state.buf.push("new Date(" + +val + ")");
895
737
  return true;
896
738
  }
897
739
  function writeRegExp(state, val) {
@@ -899,23 +741,30 @@ function writeRegExp(state, val) {
899
741
  return true;
900
742
  }
901
743
  function writePromise(state, val, ref) {
902
- const { boundary } = state;
744
+ const { boundary, channel } = state;
903
745
  if (!boundary) return false;
904
746
  const pId = nextRefAccess(state);
905
- const pRef = new Reference(ref, null, state.flush, null, pId);
747
+ const handle = newAsyncHandle(state, ref, pId);
906
748
  state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()");
907
- 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));
908
750
  boundary.startAsync();
909
751
  return true;
910
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
+ }
911
760
  function writeMap(state, val, ref) {
912
761
  if (!val.size) {
913
762
  state.buf.push("new Map");
914
763
  return true;
915
764
  }
916
- const arrayRef = new Reference(ref, null, state.flush, null, nextRefAccess(state));
917
765
  const items = [];
918
766
  let assigns;
767
+ let needsId;
919
768
  let i = 0;
920
769
  if (val.size < 25) {
921
770
  for (let [itemKey, itemValue] of val) {
@@ -927,12 +776,10 @@ function writeMap(state, val, ref) {
927
776
  itemValue = void 0;
928
777
  (assigns ||= []).push("a[" + i + "][1]");
929
778
  }
779
+ needsId ||= isDedupedMember(itemKey) || isDedupedMember(itemValue);
930
780
  i = items.push(itemValue === void 0 ? itemKey === void 0 ? [] : [itemKey] : [itemKey, itemValue]);
931
781
  }
932
- if (assigns) state.buf.push("((m,a)=>(" + assignsToString(assigns, "m") + ",a.forEach(i=>m.set(i[0],i[1])),m))(new Map," + arrayRef.id + "=");
933
- else state.buf.push("new Map(" + arrayRef.id + "=");
934
- writeArray(state, items, arrayRef);
935
- state.buf.push(")");
782
+ writeArrayArg(state, ref, items, assigns && "((m,a)=>(" + assignsToString(assigns, "m") + ",a.forEach(i=>m.set(i[0],i[1])),m))(new Map,", "new Map(", needsId);
936
783
  } else {
937
784
  for (let [itemKey, itemValue] of val) {
938
785
  if (itemKey === val) {
@@ -943,12 +790,10 @@ function writeMap(state, val, ref) {
943
790
  itemValue = 0;
944
791
  (assigns ||= []).push("a[" + (i + 1) + "]");
945
792
  }
793
+ needsId ||= isDedupedMember(itemKey) || isDedupedMember(itemValue);
946
794
  i = items.push(itemKey, itemValue);
947
795
  }
948
- if (assigns) state.buf.push("(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1])," + assignsToString(assigns, "new Map") + "))(" + arrayRef.id + "=");
949
- else state.buf.push("(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1]),new Map))(" + arrayRef.id + "=");
950
- writeArray(state, items, arrayRef);
951
- state.buf.push(")");
796
+ writeArrayArg(state, ref, items, assigns && "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1])," + assignsToString(assigns, "new Map") + "))(", "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1]),new Map))(", needsId);
952
797
  }
953
798
  return true;
954
799
  }
@@ -959,20 +804,38 @@ function writeSet(state, val, ref) {
959
804
  }
960
805
  const items = [];
961
806
  let assigns;
807
+ let needsId;
962
808
  let i = 0;
963
809
  for (let item of val) {
964
810
  if (item === val) {
965
811
  item = 0;
966
812
  (assigns ||= []).push("i[" + i + "]");
967
- }
813
+ } else needsId ||= isDedupedMember(item);
968
814
  i = items.push(item);
969
815
  }
970
- const arrayRef = new Reference(ref, null, state.flush, null, nextRefAccess(state));
971
- state.buf.push((assigns ? "((s,i)=>(" + assignsToString(assigns, "s") + ",i.forEach(i=>s.add(i)),s))(new Set," : "new Set(") + arrayRef.id + "=");
972
- writeArray(state, items, arrayRef);
973
- state.buf.push(")");
816
+ writeArrayArg(state, ref, items, assigns && "((s,i)=>(" + assignsToString(assigns, "s") + ",i.forEach(i=>s.add(i)),s))(new Set,", "new Set(", needsId);
974
817
  return true;
975
818
  }
819
+ function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
820
+ if (assignsPrefix || needsId) {
821
+ const arrayRef = new Reference(ref, null, state.flush, null, nextRefAccess(state));
822
+ state.buf.push((assignsPrefix || plainPrefix) + arrayRef.id + "=");
823
+ writeArray(state, items, arrayRef);
824
+ } else {
825
+ state.buf.push(plainPrefix);
826
+ writeArray(state, items, new Reference(ref, null, state.flush, state.buf.length));
827
+ }
828
+ state.buf.push(")");
829
+ }
830
+ function isDedupedMember(val) {
831
+ switch (typeof val) {
832
+ case "object": return val !== null && val[K_SCOPE_ID] === void 0;
833
+ case "function":
834
+ case "symbol": return true;
835
+ case "string": return val.length > STRING_DEDUP_LENGTH;
836
+ default: return false;
837
+ }
838
+ }
976
839
  function writeArrayBuffer(state, val) {
977
840
  let result;
978
841
  if (val.byteLength) {
@@ -1119,21 +982,21 @@ function writeResponse(state, val, ref) {
1119
982
  return true;
1120
983
  }
1121
984
  function writeReadableStream(state, val, ref) {
1122
- const { boundary } = state;
985
+ const { boundary, channel } = state;
1123
986
  if (!boundary || val.locked) return false;
1124
987
  const reader = val.getReader();
1125
988
  const iterId = nextRefAccess(state);
1126
- const iterRef = new Reference(ref, null, state.flush, null, iterId);
989
+ const handle = newAsyncHandle(state, ref, iterId);
1127
990
  const onFulfilled = ({ value, done }) => {
1128
- if (done) writeAsyncCall(state, boundary, iterRef, "r", value);
991
+ if (done) writeAsyncCall(state, boundary, handle, "r", value, channel);
1129
992
  else if (!boundary.signal.aborted) {
1130
993
  reader.read().then(onFulfilled, onRejected);
1131
994
  boundary.startAsync();
1132
- writeAsyncCall(state, boundary, iterRef, "f", value);
995
+ writeAsyncCall(state, boundary, handle, "f", value, channel);
1133
996
  }
1134
997
  };
1135
998
  const onRejected = (reason) => {
1136
- writeAsyncCall(state, boundary, iterRef, "j", reason);
999
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
1137
1000
  };
1138
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))}})");
1139
1002
  reader.read().then(onFulfilled, onRejected);
@@ -1171,20 +1034,20 @@ function writeAsyncGenerator(state, iter, ref) {
1171
1034
  state.buf.push("(async function*(){}())");
1172
1035
  return true;
1173
1036
  }
1174
- const { boundary } = state;
1037
+ const { boundary, channel } = state;
1175
1038
  if (!boundary) return false;
1176
1039
  const iterId = nextRefAccess(state);
1177
- const iterRef = new Reference(ref, null, state.flush, null, iterId);
1040
+ const handle = newAsyncHandle(state, ref, iterId);
1178
1041
  const onFulfilled = ({ value, done }) => {
1179
- if (done) writeAsyncCall(state, boundary, iterRef, "r", value);
1042
+ if (done) writeAsyncCall(state, boundary, handle, "r", value, channel);
1180
1043
  else if (!boundary.signal.aborted) {
1181
1044
  iter.next().then(onFulfilled, onRejected);
1182
1045
  boundary.startAsync();
1183
- writeAsyncCall(state, boundary, iterRef, "f", value);
1046
+ writeAsyncCall(state, boundary, handle, "f", value, channel);
1184
1047
  }
1185
1048
  };
1186
1049
  const onRejected = (reason) => {
1187
- writeAsyncCall(state, boundary, iterRef, "j", reason);
1050
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
1188
1051
  };
1189
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 + "={})");
1190
1053
  iter.next().then(onFulfilled, onRejected);
@@ -1198,45 +1061,36 @@ function writeNullObject(state, val, ref) {
1198
1061
  }
1199
1062
  function writeObjectProps(state, val, ref) {
1200
1063
  let sep = "";
1201
- for (const key in val) if (hasOwnProperty.call(val, key)) {
1064
+ for (const key in val) if (hasOwnProperty$1.call(val, key)) {
1202
1065
  const escapedKey = toObjectKey(key);
1203
1066
  state.buf.push(sep + escapedKey + ":");
1204
1067
  if (writeProp(state, val[key], ref, escapedKey)) sep = ",";
1205
1068
  else state.buf.pop();
1206
1069
  }
1207
1070
  if (hasSymbolIterator(val)) {
1208
- const iterArr = [...val];
1209
- switch (iterArr.length) {
1210
- case 0:
1211
- state.buf.push(sep + "*[Symbol.iterator](){}");
1212
- break;
1213
- case 1:
1214
- state.buf.push(sep + "*[Symbol.iterator](){yield " + (iterArr[0] === val ? "this" : ensureId(state, ref)) + "}");
1215
- break;
1216
- default: {
1217
- const iterRef = new Reference(ref, null, state.flush, null, nextRefAccess(state));
1218
- state.buf.push(sep + "*[(" + iterRef.id + "=");
1219
- writeArray(state, iterArr, iterRef);
1220
- state.buf.push(",Symbol.iterator)](){yield*" + iterRef.id + "}");
1221
- break;
1222
- }
1223
- }
1071
+ let yieldSelf = "";
1072
+ const iterArr = [];
1073
+ for (const item of val) if (item === val && !(yieldSelf || iterArr.length)) yieldSelf = "yield this;";
1074
+ else iterArr.push(item);
1075
+ if (iterArr.length) {
1076
+ const iterRef = new Reference(ref, null, state.flush, null, nextRefAccess(state));
1077
+ state.buf.push(sep + "*[(" + iterRef.id + "=");
1078
+ writeArray(state, iterArr, iterRef);
1079
+ state.buf.push(",Symbol.iterator)](){" + yieldSelf + "yield*" + iterRef.id + "}");
1080
+ } else state.buf.push(sep + "*[Symbol.iterator](){" + yieldSelf.slice(0, -1) + "}");
1224
1081
  sep = ",";
1225
1082
  }
1226
1083
  return sep;
1227
1084
  }
1228
- function writeAsyncCall(state, boundary, ref, method, value, preferredValueId = null) {
1085
+ function writeAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
1229
1086
  if (boundary.signal.aborted) return;
1230
- state.flushed = true;
1231
- const valueStartIndex = state.buf.push((state.buf.length === 0 ? "" : ",") + ref.id + "." + method + "(");
1232
- if (writeProp(state, value, ref, "")) {
1233
- const valueRef = state.refs.get(value);
1234
- if (valueRef && !valueRef.id) {
1235
- valueRef.id = preferredValueId || nextRefAccess(state);
1236
- state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex];
1237
- }
1238
- }
1239
- state.buf.push(")");
1087
+ state.mutated.push({
1088
+ value,
1089
+ object: handle,
1090
+ property: method,
1091
+ channel,
1092
+ valueId
1093
+ });
1240
1094
  boundary.endAsync();
1241
1095
  }
1242
1096
  function throwUnserializable(state, cause, ref = null, accessor = "") {
@@ -1268,6 +1122,26 @@ function throwUnserializable(state, cause, ref = null, accessor = "") {
1268
1122
  state.boundary.abort(err);
1269
1123
  }
1270
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
+ }
1271
1145
  function isCircular(parent, ref) {
1272
1146
  let cur = parent;
1273
1147
  while (cur) {
@@ -1327,7 +1201,19 @@ function quote(str, startPos) {
1327
1201
  return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
1328
1202
  }
1329
1203
  function ensureId(state, ref) {
1330
- 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 + ")";
1331
1217
  }
1332
1218
  function assignId(state, ref) {
1333
1219
  const { pos } = ref;
@@ -1337,17 +1223,20 @@ function assignId(state, ref) {
1337
1223
  else state.buf[pos - 1] += ref.id + "=";
1338
1224
  return ref.id;
1339
1225
  }
1226
+ ref.channel = state.channel;
1340
1227
  let cur = ref;
1341
1228
  let accessPrevValue = "";
1342
1229
  do {
1343
1230
  accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
1344
1231
  const parent = cur.parent;
1345
1232
  if (parent.id) {
1346
- accessPrevValue = parent.id + accessPrevValue;
1347
- break;
1233
+ if (trackChannel(state, parent) || !parent.parent) {
1234
+ accessPrevValue = parent.id + accessPrevValue;
1235
+ break;
1236
+ }
1348
1237
  }
1349
- if (parent.flush === state.flush) {
1350
- accessPrevValue = ensureId(state, parent) + accessPrevValue;
1238
+ if (parent.flush === state.flush || parent.scopeId !== void 0) {
1239
+ accessPrevValue = accessId(state, parent) + accessPrevValue;
1351
1240
  break;
1352
1241
  }
1353
1242
  cur = parent;
@@ -1416,15 +1305,206 @@ function patchIteratorNext(proto) {
1416
1305
  };
1417
1306
  proto.next[kTouchedIterator] = true;
1418
1307
  }
1419
- function compareRegisteredReferences(a, b) {
1420
- return a.registered.instanceId - b.registered.instanceId;
1308
+ //#endregion
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
+ }
1421
1353
  }
1422
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
1423
1505
  //#region src/html/writer.ts
1424
1506
  let $chunk;
1425
1507
  const NOOP$2 = () => {};
1426
- const K_SCOPE_ID = Symbol("Scope ID");
1427
- const K_SCOPE_REFERENCED = Symbol("Scope Referenced");
1428
1508
  function getChunk() {
1429
1509
  return $chunk;
1430
1510
  }
@@ -1443,8 +1523,28 @@ function _html(html) {
1443
1523
  function writeScript(script) {
1444
1524
  $chunk.writeScript(script);
1445
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
+ }
1446
1546
  function _script(scopeId, registryId) {
1447
- if ($chunk.context?.[kIsAsync]) _resume_branch(scopeId);
1547
+ if ($chunk.serializeState.readyId || $chunk.context?.[kIsAsync]) _resume_branch(scopeId);
1448
1548
  $chunk.boundary.state.needsMainRuntime = true;
1449
1549
  $chunk.writeEffect(scopeId, registryId);
1450
1550
  }
@@ -1456,7 +1556,7 @@ function _attr_content(nodeAccessor, scopeId, content, serializeReason) {
1456
1556
  else render();
1457
1557
  if (_peek_scope_id() !== branchId) {
1458
1558
  if (shouldResume) writeScope(scopeId, {
1459
- ["BranchScopes:" + nodeAccessor]: referenceScope(writeScope(branchId, {})),
1559
+ ["BranchScopes:" + nodeAccessor]: writeScope(branchId, {}),
1460
1560
  ["ConditionalRenderer:" + nodeAccessor]: render?.["id"]
1461
1561
  });
1462
1562
  } else _scope_id();
@@ -1480,13 +1580,20 @@ function withContext(key, value, cb, cbValue) {
1480
1580
  }
1481
1581
  }
1482
1582
  function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
1483
- _scope_with_id(parentScopeId)[scopeOffsetAccessor] = _scope_id();
1484
- const childScope = _scope_with_id(childScopeId);
1485
- childScope["#TagVariable"] = _resume({}, registryId, parentScopeId);
1583
+ writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
1584
+ const childScope = writeScopePassive(childScopeId, { ["#TagVariable"]: _resume({}, registryId, parentScopeId) });
1486
1585
  if (nodeAccessor !== void 0) writeScope(parentScopeId, { ["BranchScopes:" + nodeAccessor]: childScope });
1487
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
+ }
1488
1595
  function _resume(val, id, scopeId) {
1489
- 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));
1490
1597
  }
1491
1598
  function _id() {
1492
1599
  const state = $chunk.boundary.state;
@@ -1514,7 +1621,7 @@ function _serialize_if(condition, key) {
1514
1621
  return condition && (condition === 1 || condition[key]) ? 1 : void 0;
1515
1622
  }
1516
1623
  function _serialize_guard(condition, key) {
1517
- return condition && (condition === 1 || condition[key]) ? 1 : 0;
1624
+ return _serialize_if(condition, key) || 0;
1518
1625
  }
1519
1626
  function _el_resume(scopeId, accessor, shouldResume) {
1520
1627
  if (shouldResume === 0) return "";
@@ -1549,127 +1656,58 @@ function withIsAsync(cb, value) {
1549
1656
  return withContext(kIsAsync, true, cb, value);
1550
1657
  }
1551
1658
  function _for_of(list, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
1552
- const { state } = $chunk.boundary;
1553
- const resumeKeys = serializeMarker !== 0;
1554
- const resumeMarker = serializeMarker !== 0 && (!parentEndTag || serializeStateful !== 0);
1555
- let flushBranchIds = "";
1556
- if (serializeBranch !== 0) {
1557
- let loopScopes;
1558
- var seenKeys = /* @__PURE__ */ new Set();
1559
- forOf(list, (item, index) => {
1560
- const branchId = _peek_scope_id();
1561
- const itemKey = forOfBy(by, item, index);
1562
- if (by) {
1563
- if (seenKeys.has(itemKey)) console.error(`A <for> tag's \`by\` attribute must return a unique value for each item, but a duplicate was found matching:`, itemKey);
1564
- seenKeys.add(itemKey);
1565
- }
1566
- if (resumeMarker) if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
1567
- else {
1568
- $chunk.writeHTML(state.mark("[", flushBranchIds));
1569
- flushBranchIds = branchId + "";
1570
- }
1571
- withBranchId(branchId, () => {
1572
- cb(item, index);
1573
- const branchScope = writeScope(branchId, {});
1574
- if (resumeKeys && itemKey !== index) branchScope["#LoopKey"] = itemKey;
1575
- if (!resumeMarker) loopScopes = push(loopScopes, referenceScope(branchScope));
1576
- });
1577
- });
1578
- if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
1579
- } else forOf(list, cb);
1580
- writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
1659
+ forBranches(by, (each) => each ? forOf(list, (item, index) => {
1660
+ const itemKey = forOfBy(by, item, index);
1661
+ each(itemKey, itemKey === index, () => cb(item, index));
1662
+ }) : forOf(list, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
1581
1663
  }
1582
1664
  function _for_in(obj, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
1583
- const { state } = $chunk.boundary;
1584
- const resumeKeys = serializeMarker !== 0;
1585
- const resumeMarker = serializeMarker !== 0 && (!parentEndTag || serializeStateful !== 0);
1586
- let flushBranchIds = "";
1587
- if (serializeBranch !== 0) {
1588
- let loopScopes;
1589
- var seenKeys = /* @__PURE__ */ new Set();
1590
- forIn(obj, (key, value) => {
1591
- const branchId = _peek_scope_id();
1592
- const itemKey = forInBy(by, key, value);
1593
- if (by) {
1594
- if (seenKeys.has(itemKey)) console.error(`A <for> tag's \`by\` attribute must return a unique value for each item, but a duplicate was found matching:`, itemKey);
1595
- seenKeys.add(itemKey);
1596
- }
1597
- if (resumeMarker) if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
1598
- else {
1599
- $chunk.writeHTML(state.mark("[", flushBranchIds));
1600
- flushBranchIds = branchId + "";
1601
- }
1602
- withBranchId(branchId, () => {
1603
- cb(key, value);
1604
- const branchScope = writeScope(branchId, {});
1605
- if (resumeKeys) branchScope["#LoopKey"] = itemKey;
1606
- if (!resumeMarker) loopScopes = push(loopScopes, referenceScope(branchScope));
1607
- });
1608
- });
1609
- if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
1610
- } else forIn(obj, cb);
1611
- writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
1665
+ forBranches(by, (each) => each ? forIn(obj, (key, value) => {
1666
+ each(forInBy(by, key, value), false, () => cb(key, value));
1667
+ }) : forIn(obj, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
1612
1668
  }
1613
1669
  function _for_to(to, from, step, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
1614
- const { state } = $chunk.boundary;
1615
- const resumeKeys = serializeMarker !== 0;
1616
- const resumeMarker = serializeMarker !== 0 && (!parentEndTag || serializeStateful !== 0);
1617
- let flushBranchIds = "";
1618
- if (serializeBranch !== 0) {
1619
- let loopScopes;
1620
- var seenKeys = /* @__PURE__ */ new Set();
1621
- forTo(to, from, step, (i) => {
1622
- const branchId = _peek_scope_id();
1623
- const itemKey = forStepBy(by, i);
1624
- if (by) {
1625
- if (seenKeys.has(itemKey)) console.error(`A <for> tag's \`by\` attribute must return a unique value for each item, but a duplicate was found matching:`, itemKey);
1626
- seenKeys.add(itemKey);
1627
- }
1628
- if (resumeMarker) if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
1629
- else {
1630
- $chunk.writeHTML(state.mark("[", flushBranchIds));
1631
- flushBranchIds = branchId + "";
1632
- }
1633
- withBranchId(branchId, () => {
1634
- cb(i);
1635
- const branchScope = writeScope(branchId, {});
1636
- if (resumeKeys && itemKey !== i) branchScope["#LoopKey"] = itemKey;
1637
- if (!resumeMarker) loopScopes = push(loopScopes, referenceScope(branchScope));
1638
- });
1639
- });
1640
- if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
1641
- } else forTo(to, from, step, cb);
1642
- writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
1670
+ forBranches(by, (each) => each ? forTo(to, from, step, (i) => {
1671
+ const itemKey = forStepBy(by, i);
1672
+ each(itemKey, itemKey === i, () => cb(i));
1673
+ }) : forTo(to, from, step, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
1643
1674
  }
1644
1675
  function _for_until(to, from, step, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
1676
+ forBranches(by, (each) => each ? forUntil(to, from, step, (i) => {
1677
+ const itemKey = forStepBy(by, i);
1678
+ each(itemKey, itemKey === i, () => cb(i));
1679
+ }) : forUntil(to, from, step, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
1680
+ }
1681
+ function forBranches(by, iterate, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
1682
+ if (serializeBranch === 0) {
1683
+ iterate(0);
1684
+ writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, "");
1685
+ return;
1686
+ }
1645
1687
  const { state } = $chunk.boundary;
1646
1688
  const resumeKeys = serializeMarker !== 0;
1647
1689
  const resumeMarker = serializeMarker !== 0 && (!parentEndTag || serializeStateful !== 0);
1648
1690
  let flushBranchIds = "";
1649
- if (serializeBranch !== 0) {
1650
- let loopScopes;
1651
- var seenKeys = /* @__PURE__ */ new Set();
1652
- forUntil(to, from, step, (i) => {
1653
- const branchId = _peek_scope_id();
1654
- const itemKey = forStepBy(by, i);
1655
- if (by) {
1656
- if (seenKeys.has(itemKey)) console.error(`A <for> tag's \`by\` attribute must return a unique value for each item, but a duplicate was found matching:`, itemKey);
1657
- seenKeys.add(itemKey);
1658
- }
1659
- if (resumeMarker) if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
1660
- else {
1661
- $chunk.writeHTML(state.mark("[", flushBranchIds));
1662
- flushBranchIds = branchId + "";
1663
- }
1664
- withBranchId(branchId, () => {
1665
- cb(i);
1666
- const branchScope = writeScope(branchId, {});
1667
- if (resumeKeys && itemKey !== i) branchScope["#LoopKey"] = itemKey;
1668
- if (!resumeMarker) loopScopes = push(loopScopes, referenceScope(branchScope));
1669
- });
1691
+ let loopScopes;
1692
+ var seenKeys = /* @__PURE__ */ new Set();
1693
+ iterate((itemKey, sameAsIndex, render) => {
1694
+ const branchId = _peek_scope_id();
1695
+ if (by) {
1696
+ if (seenKeys.has(itemKey)) console.error(`A <for> tag's \`by\` attribute must return a unique value for each item, but a duplicate was found matching:`, itemKey);
1697
+ seenKeys.add(itemKey);
1698
+ }
1699
+ if (resumeMarker) if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
1700
+ else {
1701
+ $chunk.writeHTML(state.mark("[", flushBranchIds));
1702
+ flushBranchIds = branchId + "";
1703
+ }
1704
+ withBranchId(branchId, () => {
1705
+ render();
1706
+ const branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { ["#LoopKey"]: itemKey } : {});
1707
+ if (!resumeMarker) loopScopes = push(loopScopes, branchScope);
1670
1708
  });
1671
- if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
1672
- } else forUntil(to, from, step, cb);
1709
+ });
1710
+ if (loopScopes) writeScope(scopeId, { ["BranchScopes:" + accessor]: loopScopes });
1673
1711
  writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
1674
1712
  }
1675
1713
  function _if(cb, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
@@ -1682,7 +1720,7 @@ function _if(cb, scopeId, accessor, serializeBranch, serializeMarker, serializeS
1682
1720
  const shouldWriteBranch = resumeBranch && branchIndex !== void 0;
1683
1721
  if (shouldWriteBranch && (branchIndex || !resumeMarker)) writeScope(scopeId, {
1684
1722
  ["ConditionalRenderer:" + accessor]: branchIndex || void 0,
1685
- ["BranchScopes:" + accessor]: resumeMarker ? void 0 : referenceScope(writeScope(branchId, {}))
1723
+ ["BranchScopes:" + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
1686
1724
  });
1687
1725
  writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
1688
1726
  }
@@ -1695,46 +1733,34 @@ function writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, p
1695
1733
  } else $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
1696
1734
  else $chunk.writeHTML(endTag);
1697
1735
  }
1698
- function scopeHasReference(scope) {
1699
- return !!scope[K_SCOPE_REFERENCED];
1700
- }
1701
- function referenceScope(scope) {
1702
- scope[K_SCOPE_REFERENCED] = 1;
1703
- return scope;
1704
- }
1705
1736
  let writeScope = (scopeId, partialScope) => {
1706
- return writeScopeToState($chunk.boundary.state, scopeId, partialScope);
1707
- };
1708
- function writeScopeToState(state, scopeId, partialScope) {
1709
- const { scopes } = state;
1710
- 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];
1711
1741
  state.needsMainRuntime = true;
1712
- if (scope) Object.assign(scope, partialScope);
1713
- else {
1714
- scope = partialScope;
1715
- scope[K_SCOPE_ID] = scopeId;
1716
- state.scopes.set(scopeId, scope);
1717
- }
1718
- if (state.writeScopes) state.writeScopes[scopeId] = scope;
1719
- 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;
1720
1746
  return scope;
1721
- }
1747
+ };
1722
1748
  writeScope = ((writeScope) => (scopeId, partialScope, file, loc, vars) => {
1723
1749
  const scope = writeScope(scopeId, partialScope);
1724
1750
  if (file && loc !== void 0) setDebugInfo(scope, file, loc, vars);
1725
1751
  return scope;
1726
1752
  })(writeScope);
1727
1753
  function _existing_scope(scopeId) {
1728
- return writeScope(scopeId, _scope_with_id(scopeId));
1754
+ return writeScope(scopeId, {});
1729
1755
  }
1730
1756
  function _scope_with_id(scopeId) {
1731
- const { state } = $chunk.boundary;
1732
- let scope = state.scopes.get(scopeId);
1733
- if (!scope) {
1734
- scope = { [K_SCOPE_ID]: scopeId };
1735
- state.scopes.set(scopeId, scope);
1736
- }
1737
- 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;
1738
1764
  }
1739
1765
  function $global() {
1740
1766
  return $chunk.boundary.state.$global;
@@ -1752,7 +1778,7 @@ function _await(scopeId, accessor, promise, content, serializeMarker) {
1752
1778
  }
1753
1779
  const chunk = $chunk;
1754
1780
  const { boundary } = chunk;
1755
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context);
1781
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next);
1756
1782
  chunk.async = true;
1757
1783
  if (chunk.context?.[kPendingContexts]) chunk.context = {
1758
1784
  ...chunk.context,
@@ -1797,22 +1823,24 @@ function _try(scopeId, accessor, content, input) {
1797
1823
  function tryPlaceholder(content, placeholder, branchId) {
1798
1824
  const chunk = $chunk;
1799
1825
  const { boundary } = chunk;
1800
- const body = new Chunk(boundary, null, chunk.context);
1826
+ const body = chunk.fork(boundary, null);
1801
1827
  if (body === body.render(content)) {
1802
1828
  chunk.append(body);
1803
1829
  return;
1804
1830
  }
1805
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context);
1806
- chunk.placeholderBody = body;
1807
- chunk.placeholderRender = placeholder;
1808
- chunk.placeholderBranchId = branchId;
1831
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next);
1832
+ chunk.placeholder = {
1833
+ body,
1834
+ render: placeholder,
1835
+ branchId
1836
+ };
1809
1837
  }
1810
1838
  function tryCatch(content, catchContent) {
1811
1839
  const chunk = $chunk;
1812
1840
  const { boundary } = chunk;
1813
1841
  const { state } = boundary;
1814
1842
  const catchBoundary = new Boundary(state);
1815
- const body = new Chunk(catchBoundary, null, chunk.context);
1843
+ const body = chunk.fork(catchBoundary, null);
1816
1844
  const bodyEnd = body.render(content);
1817
1845
  if (catchBoundary.signal.aborted) {
1818
1846
  catchContent(catchBoundary.signal.reason);
@@ -1824,7 +1852,7 @@ function tryCatch(content, catchContent) {
1824
1852
  }
1825
1853
  const reorderId = state.nextReorderId();
1826
1854
  const endMarker = state.mark("!", reorderId);
1827
- const bodyNext = bodyEnd.next = $chunk = new Chunk(boundary, chunk.next, body.context);
1855
+ const bodyNext = bodyEnd.next = $chunk = body.fork(boundary, chunk.next);
1828
1856
  chunk.next = body;
1829
1857
  chunk.writeHTML(state.mark("!^", reorderId));
1830
1858
  bodyEnd.writeHTML(endMarker);
@@ -1845,12 +1873,12 @@ function tryCatch(content, catchContent) {
1845
1873
  cur.needsWalk = true;
1846
1874
  cur.html = endMarker;
1847
1875
  cur.scripts = cur.effects = cur.lastEffect = "";
1848
- cur.placeholderBody = cur.placeholderRender = cur.reorderId = null;
1876
+ cur.placeholder = cur.reorderId = cur.deferredReady = null;
1849
1877
  }
1850
1878
  cur = next;
1851
1879
  } while (cur !== bodyNext);
1852
1880
  }
1853
- const catchChunk = new Chunk(boundary, null, chunk.context);
1881
+ const catchChunk = chunk.fork(boundary, null);
1854
1882
  catchChunk.reorderId = reorderId;
1855
1883
  catchChunk.render(catchContent, catchBoundary.signal.reason);
1856
1884
  state.reorder(catchChunk);
@@ -1864,10 +1892,11 @@ var State = class {
1864
1892
  tagId = 1;
1865
1893
  scopeId = 1;
1866
1894
  reorderId = 1;
1867
- lastSerializedScopeId = this.scopeId;
1895
+ readyGate = 1;
1868
1896
  hasGlobals = false;
1869
1897
  needsMainRuntime = false;
1870
1898
  hasMainRuntime = false;
1899
+ hasReadyRuntime = false;
1871
1900
  hasReorderRuntime = false;
1872
1901
  hasWrittenResume = false;
1873
1902
  walkOnNextFlush = false;
@@ -1877,11 +1906,11 @@ var State = class {
1877
1906
  serializer = new Serializer();
1878
1907
  writeReorders = null;
1879
1908
  scopes = /* @__PURE__ */ new Map();
1880
- writeScopes = null;
1881
- ensureReady = null;
1909
+ flushScopes = false;
1910
+ writeScopes = {};
1911
+ readyIds = null;
1882
1912
  serializeReason;
1883
1913
  constructor($global) {
1884
- this.$global = $global;
1885
1914
  this.$global = $global;
1886
1915
  if ($global.cspNonce) this.nonceAttr = " nonce" + attrAssignment($global.cspNonce);
1887
1916
  }
@@ -1900,6 +1929,17 @@ var State = class {
1900
1929
  this.writeReorders = [chunk];
1901
1930
  }
1902
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
+ }
1903
1943
  nextReorderId() {
1904
1944
  const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
1905
1945
  let n = this.reorderId++;
@@ -1918,7 +1958,6 @@ var Boundary = class extends AbortController {
1918
1958
  constructor(state, parent) {
1919
1959
  super();
1920
1960
  this.state = state;
1921
- this.state = state;
1922
1961
  this.signal.addEventListener("abort", () => {
1923
1962
  this.count = 0;
1924
1963
  this.state = new State(this.state.$global);
@@ -1930,7 +1969,7 @@ var Boundary = class extends AbortController {
1930
1969
  });
1931
1970
  }
1932
1971
  flush() {
1933
- if (!this.signal.aborted) flushSerializer(this);
1972
+ if (!this.signal.aborted) flushSerializer(this, this.state);
1934
1973
  return this.count ? 1 : this.signal.aborted ? 2 : 0;
1935
1974
  }
1936
1975
  startAsync() {
@@ -1944,10 +1983,11 @@ var Boundary = class extends AbortController {
1944
1983
  }
1945
1984
  }
1946
1985
  };
1947
- var Chunk = class {
1986
+ var Chunk = class Chunk {
1948
1987
  boundary;
1949
1988
  next;
1950
1989
  context;
1990
+ serializeState;
1951
1991
  html = "";
1952
1992
  scripts = "";
1953
1993
  effects = "";
@@ -1956,16 +1996,16 @@ var Chunk = class {
1956
1996
  consumed = false;
1957
1997
  needsWalk = false;
1958
1998
  reorderId = null;
1959
- placeholderBody = null;
1960
- placeholderRender = null;
1961
- placeholderBranchId = null;
1962
- constructor(boundary, next, context) {
1963
- this.boundary = boundary;
1964
- this.next = next;
1965
- this.context = context;
1999
+ deferredReady = null;
2000
+ placeholder = null;
2001
+ constructor(boundary, next, context, serializeState) {
1966
2002
  this.boundary = boundary;
1967
2003
  this.next = next;
1968
2004
  this.context = context;
2005
+ this.serializeState = serializeState;
2006
+ }
2007
+ fork(boundary, next) {
2008
+ return new Chunk(boundary, next, this.context, this.serializeState);
1969
2009
  }
1970
2010
  writeHTML(html) {
1971
2011
  this.html += html;
@@ -1985,16 +2025,31 @@ var Chunk = class {
1985
2025
  this.effects = concatEffects(this.effects, chunk.effects);
1986
2026
  this.scripts = concatScripts(this.scripts, chunk.scripts);
1987
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
+ }
1988
2043
  }
1989
2044
  flushPlaceholder() {
1990
- if (this.placeholderBody) {
1991
- const body = this.placeholderBody.consume();
2045
+ const { placeholder } = this;
2046
+ if (placeholder) {
2047
+ const body = placeholder.body.consume();
1992
2048
  if (body.async) {
1993
2049
  const { state } = this.boundary;
1994
- const reorderId = body.reorderId = this.placeholderBranchId ? this.placeholderBranchId + "" : state.nextReorderId();
1995
- this.placeholderBranchId = null;
2050
+ const reorderId = body.reorderId = placeholder.branchId ? placeholder.branchId + "" : state.nextReorderId();
1996
2051
  this.writeHTML(state.mark("!^", reorderId));
1997
- const after = this.render(this.placeholderRender);
2052
+ const after = this.render(placeholder.render);
1998
2053
  if (after !== this) this.boundary.abort(/* @__PURE__ */ new Error("An @placeholder cannot contain async content."));
1999
2054
  after.writeHTML(state.mark("!", reorderId));
2000
2055
  state.reorder(body);
@@ -2002,33 +2057,38 @@ var Chunk = class {
2002
2057
  body.next = this.next;
2003
2058
  this.next = body;
2004
2059
  }
2005
- this.placeholderRender = this.placeholderBody = null;
2060
+ this.placeholder = null;
2006
2061
  }
2007
2062
  }
2008
2063
  consume() {
2009
2064
  let cur = this;
2010
- let needsWalk = cur.needsWalk;
2011
- if (cur.next && !cur.async) {
2012
- let html = "";
2013
- let effects = "";
2014
- let scripts = "";
2015
- let lastEffect = "";
2016
- do {
2017
- cur.flushPlaceholder();
2018
- needsWalk ||= cur.needsWalk;
2019
- 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 {
2020
2077
  effects = concatEffects(effects, cur.effects);
2021
2078
  scripts = concatScripts(scripts, cur.scripts);
2022
2079
  lastEffect = cur.lastEffect || lastEffect;
2023
- cur.consumed = true;
2024
- cur = cur.next;
2025
- } while (cur.next && !cur.async);
2026
- cur.needsWalk = needsWalk;
2027
- cur.html = html + cur.html;
2028
- cur.effects = concatEffects(effects, cur.effects);
2029
- cur.scripts = concatScripts(scripts, cur.scripts);
2030
- cur.lastEffect = lastEffect;
2080
+ }
2081
+ deferredReady = concat(deferredReady, cur.takeDeferredReady());
2082
+ cur.consumed = true;
2083
+ cur = cur.next;
2031
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;
2032
2092
  return cur;
2033
2093
  }
2034
2094
  render(content, val) {
@@ -2044,28 +2104,57 @@ var Chunk = class {
2044
2104
  $chunk = prev;
2045
2105
  }
2046
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
+ }
2047
2137
  flushScript() {
2048
- const { boundary, effects } = this;
2138
+ const { boundary } = this;
2049
2139
  const { state } = boundary;
2050
2140
  const { $global, runtimePrefix, nonceAttr } = state;
2051
- let { html, scripts } = this;
2052
2141
  let needsWalk = state.walkOnNextFlush;
2053
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;
2054
2153
  if (state.needsMainRuntime && !state.hasMainRuntime) {
2055
2154
  state.hasMainRuntime = true;
2056
2155
  scripts = concatScripts(scripts, WALKER_RUNTIME_CODE + "(\"" + $global.runtimeId + "\")(\"" + $global.renderId + "\")");
2057
2156
  }
2058
- if (state.ensureReady && state.hasMainRuntime) {
2059
- let first = true;
2060
- for (const id in state.ensureReady) {
2061
- if (state.ensureReady[id]) {
2062
- state.ensureReady[id] = 0;
2063
- if (first) scripts = concatScripts(scripts, "(" + runtimePrefix + ".b={})" + toAccess(toObjectKey(id)) + "=1");
2064
- else scripts = concatScripts(scripts, runtimePrefix + ".b" + toAccess(toObjectKey(id)) + "=1");
2065
- }
2066
- first = false;
2067
- }
2068
- }
2157
+ scripts = concatScripts(scripts, readyResumeScripts);
2069
2158
  if (effects) {
2070
2159
  needsWalk = true;
2071
2160
  state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"";
@@ -2084,6 +2173,7 @@ var Chunk = class {
2084
2173
  }
2085
2174
  for (const reorderedChunk of state.writeReorders) {
2086
2175
  const { reorderId } = reorderedChunk;
2176
+ const readyReservations = [];
2087
2177
  let reorderHTML = "";
2088
2178
  let reorderEffects = "";
2089
2179
  let reorderScripts = "";
@@ -2091,11 +2181,13 @@ var Chunk = class {
2091
2181
  reorderedChunk.reorderId = null;
2092
2182
  for (;;) {
2093
2183
  cur.flushPlaceholder();
2184
+ cur.deferOwnReady();
2094
2185
  const { next } = cur;
2186
+ const readyResumeScripts = cur.flushReadyScripts(readyReservations);
2095
2187
  cur.consumed = true;
2096
2188
  reorderHTML += cur.html;
2097
2189
  reorderEffects = concatEffects(reorderEffects, cur.effects);
2098
- reorderScripts = concatScripts(reorderScripts, cur.scripts);
2190
+ reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts));
2099
2191
  if (cur.async) {
2100
2192
  reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId());
2101
2193
  cur.html = cur.effects = cur.scripts = cur.lastEffect = "";
@@ -2111,6 +2203,7 @@ var Chunk = class {
2111
2203
  }
2112
2204
  reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")");
2113
2205
  }
2206
+ for (const reservation of readyReservations) scripts = concatScripts(scripts, reservation);
2114
2207
  scripts = concatScripts(scripts, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}");
2115
2208
  html += "<t " + state.commentPrefix + "=" + reorderId + ">" + reorderHTML + "</t>";
2116
2209
  }
@@ -2144,35 +2237,60 @@ var Chunk = class {
2144
2237
  return html;
2145
2238
  }
2146
2239
  };
2147
- function flushSerializer(boundary) {
2240
+ function flushSerializer(boundary, serializeState) {
2148
2241
  const { state } = boundary;
2149
- const { writeScopes, serializer } = state;
2150
- const { flushed } = serializer;
2151
- if (writeScopes || flushed) {
2152
- let shouldSerialize = false;
2153
- const serializeData = [];
2154
- let { lastSerializedScopeId } = state;
2155
- 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) {
2156
2257
  state.hasGlobals = true;
2157
- serializeData.push(getFilteredGlobals(state.$global));
2158
- shouldSerialize = true;
2258
+ globals = getFilteredGlobals(state.$global);
2159
2259
  }
2160
2260
  for (const key in writeScopes) {
2161
- const scope = writeScopes[key];
2162
- if (scopeHasReference(scope) || Object.getOwnPropertyNames(scope).length) {
2163
- const scopeId = getScopeId(scope);
2164
- const scopeIdDelta = scopeId - lastSerializedScopeId;
2165
- lastSerializedScopeId = scopeId + 1;
2166
- if (scopeIdDelta) serializeData.push(scopeIdDelta);
2167
- serializeData.push(scope);
2168
- shouldSerialize = true;
2169
- }
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));
2170
2272
  }
2171
- if (shouldSerialize) state.resumes = concatSequence(state.resumes, serializer.stringify(serializeData, boundary));
2172
- state.lastSerializedScopeId = lastSerializedScopeId;
2173
- state.writeScopes = null;
2174
- 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 += "]";
2175
2292
  }
2293
+ return marker;
2176
2294
  }
2177
2295
  function _trailers(html) {
2178
2296
  $chunk.boundary.state.trailerHTML += html;
@@ -2224,8 +2342,12 @@ function getFilteredGlobals($global) {
2224
2342
  return filtered;
2225
2343
  }
2226
2344
  function _subscribe(subscribers, scope) {
2227
- if (subscribers) $chunk.boundary.state.serializer.writeCall(scope, subscribers, "add");
2228
- 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;
2229
2351
  }
2230
2352
  //#endregion
2231
2353
  //#region src/html/attrs.ts
@@ -2408,14 +2530,6 @@ function normalizeBoolAttrValue(value) {
2408
2530
  if (value != null && value !== false) return true;
2409
2531
  }
2410
2532
  //#endregion
2411
- //#region src/common/compat-meta.ts
2412
- const RENDERER_REGISTER_ID = "$compat_renderer";
2413
- const SET_SCOPE_REGISTER_ID = "$compat_setScope";
2414
- const RENDER_BODY_ID = "$compat_renderBody";
2415
- //#endregion
2416
- //#region src/common/meta.ts
2417
- const DYNAMIC_TAG_SCRIPT_REGISTER_ID = "_dynamicTagScript";
2418
- //#endregion
2419
2533
  //#region src/html/dynamic-tag.ts
2420
2534
  const voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/;
2421
2535
  let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => {
@@ -2447,7 +2561,7 @@ let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, s
2447
2561
  const childScope = getScopeById(branchId);
2448
2562
  const needsScript = childScope && (childScope[`EventAttributes:#${renderer}/0`] || childScope[`ControlledHandler:#${renderer}/0`]);
2449
2563
  if (needsScript) {
2450
- childScope["#Renderer"] = renderer;
2564
+ writeScope(branchId, { ["#Renderer"]: renderer });
2451
2565
  _script(branchId, DYNAMIC_TAG_SCRIPT_REGISTER_ID);
2452
2566
  }
2453
2567
  if (shouldResume || needsScript) _html(state.mark("'", scopeId + " " + accessor + " " + branchId));
@@ -2489,115 +2603,6 @@ const patchDynamicTag = ((originalDynamicTag) => (patch) => {
2489
2603
  };
2490
2604
  })(_dynamic_tag);
2491
2605
  //#endregion
2492
- //#region src/html/compat.ts
2493
- const K_TAGS_API_STATE = Symbol();
2494
- const COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap();
2495
- const compat = {
2496
- $global,
2497
- fork: _await,
2498
- write: _html,
2499
- writeScript,
2500
- nextScopeId: _scope_id,
2501
- peekNextScopeId: _peek_scope_id,
2502
- isInResumedBranch,
2503
- ensureState($global) {
2504
- let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state;
2505
- if (!state) {
2506
- $global.runtimeId ||= "M";
2507
- $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_";
2508
- $global[K_TAGS_API_STATE] = state = new State($global);
2509
- }
2510
- return state;
2511
- },
2512
- isTagsAPI(fn) {
2513
- return !!fn["id"];
2514
- },
2515
- onFlush(fn) {
2516
- const { flushHTML } = Chunk.prototype;
2517
- Chunk.prototype.flushHTML = function() {
2518
- fn(this);
2519
- return flushHTML.call(this);
2520
- };
2521
- },
2522
- patchDynamicTag,
2523
- writeSetScopeForComponent(branchId, m5c, m5i) {
2524
- writeScope(branchId, {
2525
- m5c,
2526
- m5i
2527
- });
2528
- _script(branchId, SET_SCOPE_REGISTER_ID);
2529
- },
2530
- toJSON(state) {
2531
- return function toJSON() {
2532
- let compatRegistered = COMPAT_REGISTRY.get(this);
2533
- if (!compatRegistered) {
2534
- const registered = getRegistered(this);
2535
- if (registered) {
2536
- const scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
2537
- if (scopeId !== void 0) writeScopeToState(state, scopeId, {});
2538
- COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
2539
- }
2540
- }
2541
- return compatRegistered;
2542
- };
2543
- },
2544
- flushScript($global) {
2545
- const boundary = new Boundary(this.ensureState($global));
2546
- if (boundary.flush() === 1) throw new Error("Cannot serialize promise across tags/class compat layer.");
2547
- return new Chunk(boundary, null, null).flushScript().scripts;
2548
- },
2549
- render(renderer, willRerender, classAPIOut, component, input, completeChunks) {
2550
- const boundary = new Boundary(this.ensureState(classAPIOut.global));
2551
- let head = new Chunk(boundary, null, null);
2552
- let normalizedInput = input;
2553
- if ("renderBody" in input) {
2554
- normalizedInput = {};
2555
- for (const key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
2556
- }
2557
- head.render(() => {
2558
- if (willRerender) {
2559
- const scopeId = _peek_scope_id();
2560
- writeScope(scopeId, { m5c: component.id });
2561
- _script(scopeId, SET_SCOPE_REGISTER_ID);
2562
- }
2563
- _set_serialize_reason(willRerender ? 1 : 0);
2564
- try {
2565
- renderer(normalizedInput);
2566
- } finally {
2567
- _set_serialize_reason(void 0);
2568
- }
2569
- const asyncOut = classAPIOut.beginAsync({
2570
- last: true,
2571
- timeout: -1
2572
- });
2573
- classAPIOut.onLast((next) => {
2574
- (boundary.onNext = () => {
2575
- if (boundary.signal.aborted) {
2576
- asyncOut.error(boundary.signal.reason);
2577
- boundary.onNext = NOOP$1;
2578
- } else if (!boundary.count) {
2579
- boundary.onNext = NOOP$1;
2580
- head = head.consume();
2581
- asyncOut.write(head.html);
2582
- asyncOut.script(head.scripts);
2583
- asyncOut.end();
2584
- head.html = head.scripts = "";
2585
- completeChunks.push(head);
2586
- next();
2587
- }
2588
- })();
2589
- });
2590
- });
2591
- },
2592
- registerRenderer(renderer, id) {
2593
- return register(RENDERER_REGISTER_ID, renderer, register(id, () => {}));
2594
- },
2595
- registerRenderBody(fn) {
2596
- register(RENDER_BODY_ID, fn);
2597
- }
2598
- };
2599
- function NOOP$1() {}
2600
- //#endregion
2601
2606
  //#region src/html/template.ts
2602
2607
  const _template = (templateId, renderer, page) => {
2603
2608
  renderer.render = render;
@@ -2624,9 +2629,9 @@ function render(input = {}) {
2624
2629
  renderId: getDefaultRenderId(this)
2625
2630
  };
2626
2631
  const state = new State($global);
2627
- const head = new Chunk(new Boundary(state, $global.signal), null, null);
2628
- if (this["embed"]) (state.ensureReady ||= {})[this["id"]] = 1;
2629
- 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);
2630
2635
  return new ServerRendered(head);
2631
2636
  }
2632
2637
  function getDefaultRenderId(template) {
@@ -2762,7 +2767,7 @@ var ServerRendered = class {
2762
2767
  (boundary.onNext = () => {
2763
2768
  switch (!boundary.count && boundary.flush()) {
2764
2769
  case 2:
2765
- boundary.onNext = NOOP;
2770
+ boundary.onNext = NOOP$1;
2766
2771
  reject(boundary.signal.reason);
2767
2772
  break;
2768
2773
  case 0:
@@ -2785,7 +2790,7 @@ var ServerRendered = class {
2785
2790
  const status = boundary.flush();
2786
2791
  if (status === 2) {
2787
2792
  if (!tick) offTick(onNext);
2788
- boundary.onNext = NOOP;
2793
+ boundary.onNext = NOOP$1;
2789
2794
  onAbort(boundary.signal.reason);
2790
2795
  } else if (write || status === 0) {
2791
2796
  const html = (head = head.consume()).flushHTML();
@@ -2814,6 +2819,208 @@ var ServerRendered = class {
2814
2819
  return head.consume().flushHTML();
2815
2820
  }
2816
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
+ };
2817
3024
  function NOOP() {}
2818
3025
  //#endregion
2819
- 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 };