marko 6.1.3 → 6.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/html.js CHANGED
@@ -1,10 +1,4 @@
1
- let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
2
- let str = "", sep = "", part;
3
- if (val) if (typeof val != "object") str += val;
4
- else if (Array.isArray(val)) for (let v of val) part = toDelimitedString(v, delimiter, stringify), part && (str += sep + part, sep = delimiter);
5
- else for (let name in val) part = stringify(name, val[name]), part && (str += sep + part, sep = delimiter);
6
- return str;
7
- }, unsafeXMLReg = /[<&]/g, replaceUnsafeXML = (c) => c === "&" ? "&amp;" : "&lt;", escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str, unsafeScriptReg = /<\/script/gi, escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\x3C/script") : str, unsafeStyleReg = /<\/style/gi, escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C/style") : str, unsafeCommentReg = />/g, escapeCommentStr = (str) => unsafeCommentReg.test(str) ? str.replace(unsafeCommentReg, "&gt;") : str, kTouchedIterator = Symbol.for("marko.touchedIterator"), { hasOwnProperty } = {}, Generator = (function* () {})().constructor, AsyncGenerator = (async function* () {})().constructor, REGISTRY = /* @__PURE__ */ new WeakMap(), KNOWN_SYMBOLS = (() => {
1
+ let empty = [], rest = Symbol(), unsafeXMLReg = /[<&]/g, replaceUnsafeXML = (c) => c === "&" ? "&amp;" : "&lt;", escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str, unsafeScriptReg = /<\/script/gi, escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\x3C/script") : str, unsafeStyleReg = /<\/style/gi, escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C/style") : str, unsafeCommentReg = />/g, escapeCommentStr = (str) => unsafeCommentReg.test(str) ? str.replace(unsafeCommentReg, "&gt;") : str, K_SCOPE_ID = Symbol("Scope ID"), kTouchedIterator = Symbol.for("marko.touchedIterator"), { hasOwnProperty: hasOwnProperty$1 } = {}, Generator = (function* () {})().constructor, AsyncGenerator = (async function* () {})().constructor, REGISTRY = /* @__PURE__ */ new WeakMap(), KNOWN_SYMBOLS = (() => {
8
2
  let KNOWN_SYMBOLS = /* @__PURE__ */ new Map();
9
3
  for (let name of Object.getOwnPropertyNames(Symbol)) {
10
4
  let symbol = Symbol[name];
@@ -238,7 +232,16 @@ let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(
238
232
  [JSON, "JSON"],
239
233
  [Math, "Math"],
240
234
  [Reflect, "Reflect"]
241
- ]), $chunk, NOOP$2 = () => {}, K_SCOPE_ID = Symbol("Scope ID"), K_SCOPE_REFERENCED = Symbol("Scope Referenced"), kPendingContexts = Symbol("Pending Contexts"), kBranchId = Symbol("Branch Id"), kIsAsync = Symbol("Is Async"), writeScope = (scopeId, partialScope) => writeScopeToState($chunk.boundary.state, scopeId, partialScope), tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb)), tickQueue, kSelectedValue = Symbol("selectedValue"), checkedValuesRefs = /* @__PURE__ */ new WeakMap(), singleQuoteAttrReplacements = /'|&(?=#?\w+;)/g, doubleQuoteAttrReplacements = /"|&(?=#?\w+;)/g, needsQuotedAttr = /["'>\s]|&#?\w+;|\/$/g, SET_SCOPE_REGISTER_ID = "$C_s", voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/, _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => {
235
+ ]), toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
236
+ let str = "", sep = "", part;
237
+ if (val) if (typeof val != "object") str += val;
238
+ else if (Array.isArray(val)) for (let v of val) part = toDelimitedString(v, delimiter, stringify), part && (str += sep + part, sep = delimiter);
239
+ else for (let name in val) part = stringify(name, val[name]), part && (str += sep + part, sep = delimiter);
240
+ return str;
241
+ }, $chunk, NOOP$2 = () => {}, kPendingContexts = Symbol("Pending Contexts"), kBranchId = Symbol("Branch Id"), kIsAsync = Symbol("Is Async"), writeScope = (scopeId, partialScope) => {
242
+ let { state } = $chunk.boundary, target = $chunk.serializeState, scope = scopeWithId(state, scopeId), pending = target.writeScopes[scopeId];
243
+ return state.needsMainRuntime = !0, Object.assign(scope, partialScope), pending && pending !== partialScope ? Object.assign(pending, partialScope) : target.writeScopes[scopeId] = partialScope, target.flushScopes = !0, scope;
244
+ }, tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb)), tickQueue, kSelectedValue = Symbol("selectedValue"), checkedValuesRefs = /* @__PURE__ */ new WeakMap(), singleQuoteAttrReplacements = /'|&(?=#?\w+;)/g, doubleQuoteAttrReplacements = /"|&(?=#?\w+;)/g, needsQuotedAttr = /["'>\s]|&#?\w+;|\/$/g, voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/, _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => {
242
245
  let shouldResume = serializeReason !== 0, renderer = normalizeDynamicRenderer(tag), state = getState(), branchId = _peek_scope_id(), rendered, result;
243
246
  if (typeof renderer == "string") {
244
247
  let input = (inputIsArgs ? inputOrArgs[0] : inputOrArgs) || {};
@@ -252,7 +255,7 @@ let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(
252
255
  _html(`</${renderer}>`);
253
256
  }
254
257
  let childScope = getScopeById(branchId), needsScript = childScope && (childScope.Ia || childScope.Ea);
255
- needsScript && (childScope.R = renderer, _script(branchId, "d")), (shouldResume || needsScript) && _html(state.mark("'", scopeId + " " + accessor + " " + branchId));
258
+ needsScript && (writeScope(branchId, { R: renderer }), _script(branchId, "d")), (shouldResume || needsScript) && _html(state.mark("'", scopeId + " " + accessor + " " + branchId));
256
259
  } else {
257
260
  shouldResume && _html(state.mark("[", ""));
258
261
  let render = () => {
@@ -274,7 +277,7 @@ let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(
274
277
  let patched = patch(tag, scopeId, accessor);
275
278
  return patched !== tag && (patched.a = tag), originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, resume);
276
279
  };
277
- })(_dynamic_tag), K_TAGS_API_STATE = Symbol(), COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap(), compat = {
280
+ })(_dynamic_tag), _template = (templateId, renderer, page) => (renderer.render = render, renderer.i = !page, renderer._ = renderer, _content_resume(templateId, renderer)), kAssets = Symbol(), kBlockIndex = Symbol(), kDeferIndex = Symbol(), { hasOwnProperty } = {}, assetFlush, SET_SCOPE_REGISTER_ID = "$C_s", K_TAGS_API_STATE = Symbol(), COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap(), compat = {
278
281
  $global,
279
282
  fork: _await,
280
283
  write: _html,
@@ -302,26 +305,26 @@ let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(
302
305
  m5i
303
306
  }), _script(branchId, SET_SCOPE_REGISTER_ID);
304
307
  },
305
- toJSON(state) {
308
+ toJSON() {
306
309
  return function() {
307
310
  let compatRegistered = COMPAT_REGISTRY.get(this);
308
311
  if (!compatRegistered) {
309
312
  let registered = getRegistered(this);
310
313
  if (registered) {
311
314
  let scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
312
- scopeId !== void 0 && writeScopeToState(state, scopeId, {}), COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
315
+ scopeId !== void 0 && _script(scopeId, SET_SCOPE_REGISTER_ID), COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
313
316
  }
314
317
  }
315
318
  return compatRegistered;
316
319
  };
317
320
  },
318
321
  flushScript($global) {
319
- let boundary = new Boundary(this.ensureState($global));
322
+ let state = this.ensureState($global), boundary = new Boundary(state);
320
323
  if (boundary.flush() === 1) throw Error("Cannot serialize promise across tags/class compat layer.");
321
- return new Chunk(boundary, null, null).flushScript().scripts;
324
+ return new Chunk(boundary, null, null, state).flushScript().scripts;
322
325
  },
323
326
  render(renderer, willRerender, classAPIOut, component, input, completeChunks) {
324
- let boundary = new Boundary(this.ensureState(classAPIOut.global)), head = new Chunk(boundary, null, null), normalizedInput = input;
327
+ let state = this.ensureState(classAPIOut.global), boundary = new Boundary(state), head = new Chunk(boundary, null, null, state), normalizedInput = input;
325
328
  if ("renderBody" in input) {
326
329
  normalizedInput = {};
327
330
  for (let key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
@@ -343,18 +346,16 @@ let empty = [], rest = Symbol(), toDelimitedString = function toDelimitedString(
343
346
  });
344
347
  classAPIOut.onLast((next) => {
345
348
  (boundary.onNext = () => {
346
- boundary.signal.aborted ? (asyncOut.error(boundary.signal.reason), boundary.onNext = NOOP$1) : boundary.count || (boundary.onNext = NOOP$1, head = head.consume(), asyncOut.write(head.html), asyncOut.script(head.scripts), asyncOut.end(), head.html = head.scripts = "", completeChunks.push(head), next());
349
+ boundary.signal.aborted ? (asyncOut.error(boundary.signal.reason), boundary.onNext = NOOP) : boundary.count || (boundary.onNext = NOOP, head = head.consume(), asyncOut.write(head.html), asyncOut.script(head.scripts), asyncOut.end(), head.html = head.scripts = "", completeChunks.push(head), next());
347
350
  })();
348
351
  });
349
352
  });
350
353
  },
351
- registerRenderer(renderer, id) {
352
- return register("$C_r", renderer, register(id, () => {}));
353
- },
354
+ register,
354
355
  registerRenderBody(fn) {
355
356
  register("$C_b", fn);
356
357
  }
357
- }, _template = (templateId, renderer, page) => (renderer.render = render, renderer.i = !page, renderer._ = renderer, _content_resume(templateId, renderer));
358
+ };
358
359
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
359
360
  //#region src/common/attr-tag.ts
360
361
  function attrTag(attrs) {
@@ -372,30 +373,6 @@ function _el_read_error() {}
372
373
  function _hoist_read_error() {}
373
374
  function _assert_hoist(value) {}
374
375
  //#endregion
375
- //#region src/common/helpers.ts
376
- function stringifyClassObject(name, value) {
377
- return value ? name : "";
378
- }
379
- function stringifyStyleObject(name, value) {
380
- return value || value === 0 ? name + ":" + value : "";
381
- }
382
- function isEventHandler(name) {
383
- return /^on[A-Z-]/.test(name);
384
- }
385
- function getEventHandlerName(name) {
386
- return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
387
- }
388
- function isVoid(value) {
389
- return value == null || value === !1;
390
- }
391
- function normalizeDynamicRenderer(value) {
392
- if (value) {
393
- if (typeof value == "string") return value;
394
- let normalized = value.content || value.default || value;
395
- if ("a" in normalized) return normalized;
396
- }
397
- }
398
- //#endregion
399
376
  //#region src/html/content.ts
400
377
  function _unescaped(val) {
401
378
  return val ? val + "" : val === 0 ? "0" : "";
@@ -412,54 +389,18 @@ function _escape_style(val) {
412
389
  function _escape_comment(val) {
413
390
  return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
414
391
  }
415
- //#endregion
416
- //#region src/common/for.ts
417
- function forIn(obj, cb) {
418
- for (let key in obj) cb(key, obj[key]);
419
- }
420
- function forOf(list, cb) {
421
- if (list) {
422
- let i = 0;
423
- for (let item of list) cb(item, i++);
424
- }
425
- }
426
- function forTo(to, from, step, cb) {
427
- let start = from || 0, delta = step || 1;
428
- for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
429
- }
430
- function forUntil(until, from, step, cb) {
431
- let start = from || 0, delta = step || 1;
432
- for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
433
- }
434
- //#endregion
435
- //#region src/common/opt.ts
436
- function push(opt, item) {
437
- return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
438
- }
439
- //#endregion
440
- //#region src/html/for.ts
441
- function forOfBy(by, item, index) {
442
- return by ? typeof by == "string" ? item[by] : by(item, index) : index;
443
- }
444
- function forInBy(by, name, value) {
445
- return by ? by(name, value) : name;
446
- }
447
- function forStepBy(by, index) {
448
- return by ? by(index) : index;
449
- }
450
392
  patchIteratorNext(Generator.prototype), patchIteratorNext(AsyncGenerator.prototype);
451
393
  var State$1 = class {
452
394
  ids = 0;
453
395
  flush = 0;
454
- registerInstanceId = 0;
455
- flushed = !1;
456
396
  wroteUndefined = !1;
457
397
  buf = [];
458
398
  strs = /* @__PURE__ */ new Map();
459
399
  refs = /* @__PURE__ */ new WeakMap();
460
400
  assigned = /* @__PURE__ */ new Set();
461
- registered = [];
462
401
  boundary = void 0;
402
+ channel = void 0;
403
+ channelDeps = null;
463
404
  mutated = [];
464
405
  }, Reference = class {
465
406
  parent;
@@ -467,58 +408,47 @@ var State$1 = class {
467
408
  flush;
468
409
  pos;
469
410
  id;
470
- registered = null;
471
411
  assigns = null;
412
+ scopeId = void 0;
413
+ channel = void 0;
472
414
  constructor(parent, accessor, flush, pos = null, id = null) {
473
- this.parent = parent, this.accessor = accessor, this.flush = flush, this.pos = pos, this.id = id, this.parent = parent, this.accessor = accessor, this.flush = flush, this.pos = pos, this.id = id;
415
+ this.parent = parent, this.accessor = accessor, this.flush = flush, this.pos = pos, this.id = id;
474
416
  }
475
417
  }, Serializer = class {
476
418
  #state = new State$1();
477
- get flushed() {
478
- return this.#state.flushed;
419
+ pending(channel) {
420
+ return hasMatchingMutations(this.#state.mutated, channel?.readyId);
421
+ }
422
+ pendingReadyChannel() {
423
+ for (let mutation of this.#state.mutated) if (mutation.channel?.readyId) return mutation.channel;
479
424
  }
480
- stringify(val, boundary) {
425
+ stringifyScopes(flushes, globals, boundary, channel) {
481
426
  try {
482
- return this.#state.flushed = !1, this.#state.boundary = boundary, writeRoot(this.#state, val);
427
+ return this.#state.boundary = boundary, this.#state.channel = channel, writeScopesRoot(this.#state, flushes, globals);
483
428
  } finally {
484
429
  this.#state.flush++, this.#state.buf = [];
485
430
  }
486
431
  }
487
- nextId() {
488
- return nextId(this.#state);
432
+ written(val) {
433
+ return this.#state.refs.has(val);
489
434
  }
490
- symbol(id) {
491
- let symbol = Symbol();
492
- return this.#state.refs.set(symbol, new Reference(null, null, 0, null, id)), symbol;
435
+ takeChannelDeps() {
436
+ let deps = this.#state.channelDeps;
437
+ return this.#state.channelDeps = null, deps;
493
438
  }
494
- writeCall(value, object, property, spread) {
495
- let state = this.#state;
496
- state.mutated.push({
497
- type: 0,
439
+ writeCall(value, object, property, channel) {
440
+ this.#state.mutated.push({
498
441
  value,
499
442
  object,
500
443
  property,
501
- spread
502
- }), state.flushed = !0;
503
- }
504
- writeAssign(value, object, property) {
505
- let state = this.#state;
506
- state.mutated.push({
507
- type: 1,
508
- value,
509
- object,
510
- property
511
- }), state.flushed = !0;
512
- }
513
- register(id, val, scope) {
514
- return register(id, val, scope, scope ? ++this.#state.registerInstanceId : 0);
444
+ channel
445
+ });
515
446
  }
516
447
  };
517
- function register(id, val, scope, instanceId) {
448
+ function register(id, val, scope) {
518
449
  return REGISTRY.set(val, {
519
450
  id,
520
451
  scope,
521
- instanceId: instanceId ?? 0,
522
452
  access: "_._" + toAccess(toObjectKey(id))
523
453
  }), val;
524
454
  }
@@ -529,50 +459,59 @@ function getRegistered(val) {
529
459
  scope: registered.scope
530
460
  };
531
461
  }
532
- function writeRoot(state, root) {
533
- let { buf } = state, hadBuf = buf.length !== 0, result;
534
- if (hadBuf && buf.push(","), writeProp(state, root, null, "")) {
535
- let rootRef = state.refs.get(root);
536
- if (rootRef) {
537
- let rootId = ensureId(state, rootRef);
538
- (state.assigned.size || state.registered.length || state.mutated.length) && (state.assigned.delete(rootRef), writeAssigned(state), buf.push("," + (rootRef.assigns ? assignsToString(rootRef.assigns, rootId) : rootId)));
539
- }
540
- result = "(", buf.push(")");
541
- } else hadBuf && (buf.pop(), writeAssigned(state)), result = "{", buf.push("}");
462
+ function writeScopesRoot(state, flushes, globals) {
463
+ let { buf } = state, nextSlotId = -1, fillIndex = -1;
464
+ globals && (fillIndex = buf.push("[0,") - 1, writeProp(state, globals, null, ""), nextSlotId = 1);
465
+ for (let flush of flushes) {
466
+ let scopeId = flush[0], scope = flush[1], ref = state.refs.get(scope) || newScopeReference(state, scope, scopeId), openIndex = buf.push("") - 1;
467
+ writeObjectProps(state, flush[2], ref) ? (buf[openIndex] = nextSlotId === -1 ? "[" + scopeId + ",{" : (scopeId > nextSlotId ? "," + (scopeId - nextSlotId) : "") + ",{", fillIndex === -1 && (fillIndex = openIndex), nextSlotId = scopeId + 1, buf.push("}")) : buf.pop();
468
+ }
469
+ nextSlotId !== -1 && buf.push("]");
470
+ let extras = "";
471
+ (state.assigned.size || hasChannelMutations(state)) && (extras = ",0)", fillIndex !== -1 && (buf[fillIndex] = "_(" + buf[fillIndex], buf.push(")")), writeAssigned(state));
472
+ let result = extras && "(";
542
473
  for (let chunk of buf) result += chunk;
543
- return state.wroteUndefined ? (state.wroteUndefined = !1, "(_,$)=>" + result) : "_=>" + result;
474
+ return result += extras, result ? state.wroteUndefined ? (state.wroteUndefined = !1, "(_,$)=>" + result) : "_=>" + result : "";
544
475
  }
545
476
  function writeAssigned(state) {
477
+ let sep = state.buf.length ? "," : "";
546
478
  if (state.assigned.size) {
547
479
  let buf = "";
548
- for (let ref of state.assigned) buf += "," + assignsToString(ref.assigns, ref.id), ref.assigns = null;
480
+ for (let ref of state.assigned) buf += sep + assignsToString(ref.assigns, ref.id), ref.assigns = null, sep = ",";
549
481
  state.buf.push(buf), state.assigned = /* @__PURE__ */ new Set();
550
482
  }
551
- if (state.registered.length) {
552
- let buf = "";
553
- for (let ref of state.registered.sort(compareRegisteredReferences)) {
554
- let scopeRef = state.refs.get(ref.registered.scope);
555
- buf += "," + assignsToString(ref.assigns, ref.registered.access + "(" + (scopeRef ? ensureId(state, scopeRef) : ref.assigns[0]) + ")"), ref.assigns = null, ref.registered = null;
556
- }
557
- state.buf.push(buf), state.registered = [];
558
- }
559
- if (state.mutated.length) {
483
+ if (hasChannelMutations(state)) {
484
+ let remaining = [];
560
485
  for (let mutation of state.mutated) {
486
+ if (!mutationMatchesReadyId(mutation, state.channel?.readyId)) {
487
+ remaining.push(mutation);
488
+ continue;
489
+ }
561
490
  let hasSeen = state.refs.get(mutation.object)?.id, objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
562
491
  if (writeProp(state, mutation.object, null, "")) {
563
492
  let objectRef = state.refs.get(mutation.object);
564
- objectRef && (objectRef.id ? hasSeen || (state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex], state.buf.push(")")) : (objectRef.id = nextRefAccess(state), state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex], state.buf.push(")")));
493
+ objectRef && objectRef.scopeId === void 0 && (objectRef.id ? hasSeen || (state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex], state.buf.push(")")) : (objectRef.id = nextRefAccess(state), state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex], state.buf.push(")")));
565
494
  } else state.buf.push("void 0");
566
- let isCall = mutation.type === 0, valueStartIndex = state.buf.push(isCall ? (mutation.property === void 0 ? "" : toAccess(toObjectKey(mutation.property))) + "(" + (mutation.spread ? "..." : "") : toAccess(toObjectKey(mutation.property)) + "=");
567
- if (writeProp(state, mutation.value, null, "")) {
495
+ let valueStartIndex = state.buf.push(toAccess(toObjectKey(mutation.property)) + "(");
496
+ if (mutation.value !== void 0) if (writeProp(state, mutation.value, null, "")) {
568
497
  let valueRef = state.refs.get(mutation.value);
569
- valueRef && !valueRef.id && (valueRef.id = nextRefAccess(state), state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex]);
498
+ valueRef && !valueRef.id && valueRef.scopeId === void 0 && (valueRef.id = mutation.valueId || nextRefAccess(state), state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex]);
570
499
  } else state.buf.push("void 0");
571
- isCall && state.buf.push(")");
500
+ state.buf.push(")");
572
501
  }
573
- state.mutated = [], (state.assigned.size || state.registered.length) && writeAssigned(state);
502
+ state.mutated = remaining, state.assigned.size && writeAssigned(state);
574
503
  }
575
504
  }
505
+ function hasChannelMutations(state) {
506
+ return hasMatchingMutations(state.mutated, state.channel?.readyId);
507
+ }
508
+ function hasMatchingMutations(mutated, readyId) {
509
+ for (let mutation of mutated) if (mutationMatchesReadyId(mutation, readyId)) return !0;
510
+ return !1;
511
+ }
512
+ function mutationMatchesReadyId(mutation, readyId) {
513
+ return mutation.channel?.readyId ? mutation.channel.readyId === readyId : !readyId;
514
+ }
576
515
  function writeProp(state, val, parent, accessor) {
577
516
  switch (typeof val) {
578
517
  case "string": return writeString(state, val, parent, accessor);
@@ -586,34 +525,47 @@ function writeProp(state, val, parent, accessor) {
586
525
  }
587
526
  }
588
527
  function writeReferenceOr(state, write, val, parent, accessor) {
528
+ let scopeId = val[K_SCOPE_ID];
529
+ if (scopeId !== void 0) return trackScope(state, val, scopeId), state.buf.push("_(" + scopeId + ")"), !0;
589
530
  let ref = state.refs.get(val);
590
531
  if (ref) {
532
+ if (!trackChannel(state, ref)) return !1;
591
533
  if (parent) {
592
- if (ref.assigns) return addAssignment(ref, ensureId(state, parent) + toAccess(accessor)), !1;
593
- if (isCircular(parent, ref)) return ensureId(state, ref), state.assigned.add(ref), addAssignment(ref, ensureId(state, parent) + toAccess(accessor)), !1;
534
+ if (ref.assigns) return addAssignment(ref, accessId(state, parent) + toAccess(accessor)), !1;
535
+ if (isCircular(parent, ref)) return ensureId(state, ref), state.assigned.add(ref), addAssignment(ref, accessId(state, parent) + toAccess(accessor)), !1;
594
536
  }
595
537
  return state.buf.push(ensureId(state, ref)), !0;
596
538
  }
597
539
  let registered = REGISTRY.get(val);
598
- return registered ? writeRegistered(state, val, parent, accessor, registered) : (state.refs.set(val, ref = new Reference(parent, accessor, state.flush, state.buf.length)), write(state, val, ref) ? !0 : (state.refs.delete(val), !1));
540
+ return registered ? writeRegistered(state, val, parent, accessor, registered) : (state.refs.set(val, ref = new Reference(parent, accessor, state.flush, state.buf.length)), ref.channel = state.channel, write(state, val, ref) ? !0 : (state.refs.delete(val), !1));
541
+ }
542
+ function trackScope(state, val, scopeId) {
543
+ let ref = state.refs.get(val);
544
+ ref ? trackChannel(state, ref) : newScopeReference(state, val, scopeId);
545
+ }
546
+ function newScopeReference(state, val, scopeId) {
547
+ let ref = new Reference(null, null, state.flush);
548
+ return ref.scopeId = scopeId, ref.channel = state.channel, state.refs.set(val, ref), ref;
599
549
  }
600
550
  function writeRegistered(state, val, parent, accessor, registered) {
601
- if (parent && registered.scope) {
602
- if (!state.refs.has(registered.scope)) {
603
- state.buf.push(registered.access + "("), writeProp(state, registered.scope, null, ""), state.buf.push(")");
604
- let scopeRef = state.refs.get(registered.scope);
605
- return scopeRef && ensureId(state, scopeRef), !0;
606
- }
607
- let fnRef = new Reference(parent, accessor, state.flush, state.buf.length);
608
- return fnRef.registered = registered, state.refs.set(val, fnRef), state.registered.push(fnRef), addAssignment(fnRef, ensureId(state, parent) + toAccess(accessor)), !1;
551
+ let { scope } = registered;
552
+ if (scope) {
553
+ let ref = new Reference(parent, accessor, state.flush, state.buf.length);
554
+ ref.channel = state.channel, state.refs.set(val, ref);
555
+ let scopeId = scope[K_SCOPE_ID];
556
+ trackScope(state, scope, scopeId), state.buf.push("_(" + scopeId + "," + quote(registered.id, 0) + ")");
609
557
  } else state.buf.push(registered.access);
610
558
  return !0;
611
559
  }
612
560
  function writeString(state, val, parent, accessor) {
613
561
  if (val.length > 12) {
614
562
  let ref = state.strs.get(val);
615
- if (ref) return state.buf.push(ensureId(state, ref)), !0;
616
- state.strs.set(val, new Reference(parent, accessor, state.flush, state.buf.length));
563
+ if (ref) {
564
+ if (trackChannel(state, ref)) return state.buf.push(ensureId(state, ref)), !0;
565
+ } else {
566
+ let ref = new Reference(parent, accessor, state.flush, state.buf.length);
567
+ ref.channel = state.channel, state.strs.set(val, ref);
568
+ }
617
569
  }
618
570
  return state.buf.push(quote(val, 0)), !0;
619
571
  }
@@ -710,10 +662,14 @@ function writeRegExp(state, val) {
710
662
  return state.buf.push(val + ""), !0;
711
663
  }
712
664
  function writePromise(state, val, ref) {
713
- let { boundary } = state;
665
+ let { boundary, channel } = state;
714
666
  if (!boundary) return !1;
715
- let pId = nextRefAccess(state), pRef = new Reference(ref, null, state.flush, null, pId);
716
- return state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()"), val.then((v) => writeAsyncCall(state, boundary, pRef, "f", v, pId), (v) => writeAsyncCall(state, boundary, pRef, "r", v, pId)), boundary.startAsync(), !0;
667
+ let pId = nextRefAccess(state), handle = newAsyncHandle(state, ref, pId);
668
+ return state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()"), val.then((v) => writeAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => writeAsyncCall(state, boundary, handle, "r", v, channel, pId)), boundary.startAsync(), !0;
669
+ }
670
+ function newAsyncHandle(state, parent, id) {
671
+ let handle = {}, handleRef = new Reference(parent, null, state.flush, null, id);
672
+ return handleRef.channel = state.channel, state.refs.set(handle, handleRef), handle;
717
673
  }
718
674
  function writeMap(state, val, ref) {
719
675
  if (!val.size) return state.buf.push("new Map"), !0;
@@ -742,7 +698,7 @@ function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
742
698
  }
743
699
  function isDedupedMember(val) {
744
700
  switch (typeof val) {
745
- case "object": return val !== null;
701
+ case "object": return val !== null && val[K_SCOPE_ID] === void 0;
746
702
  case "function":
747
703
  case "symbol": return !0;
748
704
  case "string": return val.length > 12;
@@ -804,12 +760,12 @@ function writeResponse(state, val, ref) {
804
760
  return state.refs.set(val.headers, new Reference(ref, "headers", state.flush, null)), headers && (options += sep + "headers:{" + headers + "}"), !val.body || val.bodyUsed ? state.buf.push("new Response" + (options ? "(null,{" + options + "})" : "")) : (state.buf.push("new Response("), state.buf.push((writeProp(state, val.body, ref, "body") ? "" : "null") + (options ? ",{" + options + "})" : ")"))), !0;
805
761
  }
806
762
  function writeReadableStream(state, val, ref) {
807
- let { boundary } = state;
763
+ let { boundary, channel } = state;
808
764
  if (!boundary || val.locked) return !1;
809
- let reader = val.getReader(), iterId = nextRefAccess(state), iterRef = new Reference(ref, null, state.flush, null, iterId), onFulfilled = ({ value, done }) => {
810
- done ? writeAsyncCall(state, boundary, iterRef, "r", value) : boundary.signal.aborted || (reader.read().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, iterRef, "f", value));
765
+ let reader = val.getReader(), iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
766
+ done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (reader.read().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel));
811
767
  }, onRejected = (reason) => {
812
- writeAsyncCall(state, boundary, iterRef, "j", reason);
768
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
813
769
  };
814
770
  return 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))}})"), reader.read().then(onFulfilled, onRejected), boundary.startAsync(), !0;
815
771
  }
@@ -828,12 +784,12 @@ function writeGenerator(state, iter, ref) {
828
784
  }
829
785
  function writeAsyncGenerator(state, iter, ref) {
830
786
  if (iter[kTouchedIterator]) return state.buf.push("(async function*(){}())"), !0;
831
- let { boundary } = state;
787
+ let { boundary, channel } = state;
832
788
  if (!boundary) return !1;
833
- let iterId = nextRefAccess(state), iterRef = new Reference(ref, null, state.flush, null, iterId), onFulfilled = ({ value, done }) => {
834
- done ? writeAsyncCall(state, boundary, iterRef, "r", value) : boundary.signal.aborted || (iter.next().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, iterRef, "f", value));
789
+ let iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
790
+ done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (iter.next().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel));
835
791
  }, onRejected = (reason) => {
836
- writeAsyncCall(state, boundary, iterRef, "j", reason);
792
+ writeAsyncCall(state, boundary, handle, "j", reason, channel);
837
793
  };
838
794
  return 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 + "={})"), iter.next().then(onFulfilled, onRejected), boundary.startAsync(), !0;
839
795
  }
@@ -842,7 +798,7 @@ function writeNullObject(state, val, ref) {
842
798
  }
843
799
  function writeObjectProps(state, val, ref) {
844
800
  let sep = "";
845
- for (let key in val) if (hasOwnProperty.call(val, key)) {
801
+ for (let key in val) if (hasOwnProperty$1.call(val, key)) {
846
802
  let escapedKey = toObjectKey(key);
847
803
  state.buf.push(sep + escapedKey + ":"), writeProp(state, val[key], ref, escapedKey) ? sep = "," : state.buf.pop();
848
804
  }
@@ -857,15 +813,24 @@ function writeObjectProps(state, val, ref) {
857
813
  }
858
814
  return sep;
859
815
  }
860
- function writeAsyncCall(state, boundary, ref, method, value, preferredValueId = null) {
861
- if (boundary.signal.aborted) return;
862
- state.flushed = !0;
863
- let valueStartIndex = state.buf.push((state.buf.length === 0 ? "" : ",") + ref.id + "." + method + "(");
864
- if (writeProp(state, value, ref, "")) {
865
- let valueRef = state.refs.get(value);
866
- valueRef && !valueRef.id && (valueRef.id = preferredValueId || nextRefAccess(state), state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex]);
816
+ function writeAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
817
+ boundary.signal.aborted || (state.mutated.push({
818
+ value,
819
+ object: handle,
820
+ property: method,
821
+ channel,
822
+ valueId
823
+ }), boundary.endAsync());
824
+ }
825
+ function trackChannel(state, ref) {
826
+ let refReadyId = ref.channel?.readyId;
827
+ if (!refReadyId || refReadyId === state.channel?.readyId) return !0;
828
+ let cur = state.channel?.parent;
829
+ for (; cur;) {
830
+ if (cur.readyId === refReadyId) return (state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId), !0;
831
+ cur = cur.parent;
867
832
  }
868
- state.buf.push(")"), boundary.endAsync();
833
+ return !1;
869
834
  }
870
835
  function isCircular(parent, ref) {
871
836
  let cur = parent;
@@ -924,21 +889,26 @@ function quote(str, startPos) {
924
889
  return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
925
890
  }
926
891
  function ensureId(state, ref) {
927
- return ref.id || assignId(state, ref);
892
+ return ref.scopeId === void 0 ? ref.id ? (trackChannel(state, ref), ref.id) : assignId(state, ref) : (trackChannel(state, ref), "_(" + ref.scopeId + ")");
893
+ }
894
+ function accessId(state, ref) {
895
+ let id = ensureId(state, ref);
896
+ return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
928
897
  }
929
898
  function assignId(state, ref) {
930
899
  let { pos } = ref;
931
900
  if (ref.id = nextRefAccess(state), pos !== null && ref.flush === state.flush) return pos === 0 ? state.buf[0] = ref.id + "=" + state.buf[0] : state.buf[pos - 1] += ref.id + "=", ref.id;
901
+ ref.channel = state.channel;
932
902
  let cur = ref, accessPrevValue = "";
933
903
  do {
934
904
  accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
935
905
  let parent = cur.parent;
936
- if (parent.id) {
906
+ if (parent.id && (trackChannel(state, parent) || !parent.parent)) {
937
907
  accessPrevValue = parent.id + accessPrevValue;
938
908
  break;
939
909
  }
940
- if (parent.flush === state.flush) {
941
- accessPrevValue = ensureId(state, parent) + accessPrevValue;
910
+ if (parent.flush === state.flush || parent.scopeId !== void 0) {
911
+ accessPrevValue = accessId(state, parent) + accessPrevValue;
942
912
  break;
943
913
  }
944
914
  cur = parent;
@@ -992,10 +962,82 @@ function patchIteratorNext(proto) {
992
962
  return this[kTouchedIterator] = 1, next.call(this, value);
993
963
  }, proto.next[kTouchedIterator] = !0;
994
964
  }
995
- function compareRegisteredReferences(a, b) {
996
- return a.registered.instanceId - b.registered.instanceId;
965
+ //#endregion
966
+ //#region src/common/helpers.ts
967
+ function stringifyClassObject(name, value) {
968
+ return value ? name : "";
969
+ }
970
+ function stringifyStyleObject(name, value) {
971
+ return value || value === 0 ? name + ":" + value : "";
972
+ }
973
+ function isEventHandler(name) {
974
+ return /^on[A-Z-]/.test(name);
975
+ }
976
+ function getEventHandlerName(name) {
977
+ return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
978
+ }
979
+ function isVoid(value) {
980
+ return value == null || value === !1;
981
+ }
982
+ function normalizeDynamicRenderer(value) {
983
+ if (value) {
984
+ if (typeof value == "string") return value;
985
+ let normalized = value.content || value.default || value;
986
+ if ("a" in normalized) return normalized;
987
+ }
988
+ }
989
+ //#endregion
990
+ //#region src/common/for.ts
991
+ function forIn(obj, cb) {
992
+ for (let key in obj) cb(key, obj[key]);
993
+ }
994
+ function forOf(list, cb) {
995
+ if (list) {
996
+ let i = 0;
997
+ for (let item of list) cb(item, i++);
998
+ }
999
+ }
1000
+ function forTo(to, from, step, cb) {
1001
+ let start = from || 0, delta = step || 1;
1002
+ for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
1003
+ }
1004
+ function forUntil(until, from, step, cb) {
1005
+ let start = from || 0, delta = step || 1;
1006
+ for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
1007
+ }
1008
+ //#endregion
1009
+ //#region src/common/opt.ts
1010
+ function forEach(opt, cb) {
1011
+ if (opt) if (Array.isArray(opt)) for (let item of opt) cb(item);
1012
+ else cb(opt);
1013
+ }
1014
+ function push(opt, item) {
1015
+ return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
1016
+ }
1017
+ function concat(opt, other) {
1018
+ if (!opt) return other;
1019
+ if (!other) return opt;
1020
+ if (Array.isArray(opt)) {
1021
+ if (Array.isArray(other)) for (let item of other) opt.push(item);
1022
+ else opt.push(other);
1023
+ return opt;
1024
+ }
1025
+ return Array.isArray(other) ? [opt, ...other] : [opt, other];
1026
+ }
1027
+ //#endregion
1028
+ //#region src/html/for.ts
1029
+ function forOfBy(by, item, index) {
1030
+ return by ? typeof by == "string" ? item[by] : by(item, index) : index;
1031
+ }
1032
+ function forInBy(by, name, value) {
1033
+ return by ? by(name, value) : name;
1034
+ }
1035
+ function forStepBy(by, index) {
1036
+ return by ? by(index) : index;
997
1037
  }
998
1038
  //#endregion
1039
+ //#region src/html/inlined-runtimes.ts
1040
+ //#endregion
999
1041
  //#region src/html/writer.ts
1000
1042
  function getChunk() {
1001
1043
  return $chunk;
@@ -1015,13 +1057,23 @@ function _html(html) {
1015
1057
  function writeScript(script) {
1016
1058
  $chunk.writeScript(script);
1017
1059
  }
1060
+ function writeWaitReady(readyId, renderer, input) {
1061
+ let chunk = $chunk, { boundary } = chunk, body = new Chunk(boundary, null, chunk.context, {
1062
+ readyId,
1063
+ parent: chunk.serializeState,
1064
+ resumes: "",
1065
+ writeScopes: {},
1066
+ flushScopes: !1
1067
+ }), bodyEnd = body.render(renderer, input);
1068
+ body === bodyEnd ? (chunk.writeHTML(body.html), body.deferOwnReady(), chunk.deferredReady = push(chunk.deferredReady, body)) : (bodyEnd.next = $chunk = chunk.fork(boundary, chunk.next), chunk.next = body);
1069
+ }
1018
1070
  function _script(scopeId, registryId) {
1019
- $chunk.context?.[kIsAsync] && _resume_branch(scopeId), $chunk.boundary.state.needsMainRuntime = !0, $chunk.writeEffect(scopeId, registryId);
1071
+ ($chunk.serializeState.readyId || $chunk.context?.[kIsAsync]) && _resume_branch(scopeId), $chunk.boundary.state.needsMainRuntime = !0, $chunk.writeEffect(scopeId, registryId);
1020
1072
  }
1021
1073
  function _attr_content(nodeAccessor, scopeId, content, serializeReason) {
1022
1074
  let shouldResume = serializeReason !== 0, render = normalizeServerRender(content), branchId = _peek_scope_id();
1023
1075
  render && (shouldResume ? withBranchId(branchId, render) : render()), _peek_scope_id() === branchId ? _scope_id() : shouldResume && writeScope(scopeId, {
1024
- ["A" + nodeAccessor]: referenceScope(writeScope(branchId, {})),
1076
+ ["A" + nodeAccessor]: writeScope(branchId, {}),
1025
1077
  ["D" + nodeAccessor]: render?.a
1026
1078
  });
1027
1079
  }
@@ -1039,12 +1091,16 @@ function withContext(key, value, cb, cbValue) {
1039
1091
  }
1040
1092
  }
1041
1093
  function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
1042
- _scope_with_id(parentScopeId)[scopeOffsetAccessor] = _scope_id();
1043
- let childScope = _scope_with_id(childScopeId);
1044
- childScope.T = _resume({}, registryId, parentScopeId), nodeAccessor !== void 0 && writeScope(parentScopeId, { ["A" + nodeAccessor]: childScope });
1094
+ writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
1095
+ let childScope = writeScopePassive(childScopeId, { T: _resume({}, registryId, parentScopeId) });
1096
+ nodeAccessor !== void 0 && writeScope(parentScopeId, { ["A" + nodeAccessor]: childScope });
1097
+ }
1098
+ function writeScopePassive(scopeId, partialScope) {
1099
+ let target = $chunk.serializeState, scope = _scope_with_id(scopeId), passive = target.passiveScopes ||= {};
1100
+ return Object.assign(scope, partialScope), passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope), scope;
1045
1101
  }
1046
1102
  function _resume(val, id, scopeId) {
1047
- return scopeId === void 0 ? register(id, val) : $chunk.boundary.state.serializer.register(id, val, _scope_with_id(scopeId));
1103
+ return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId));
1048
1104
  }
1049
1105
  function _id() {
1050
1106
  let state = $chunk.boundary.state, { $global } = state;
@@ -1134,7 +1190,7 @@ function forBranches(by, iterate, scopeId, accessor, serializeBranch, serializeM
1134
1190
  resumeMarker && (singleNode ? flushBranchIds = " " + branchId + flushBranchIds : ($chunk.writeHTML(state.mark("[", flushBranchIds)), flushBranchIds = branchId + "")), withBranchId(branchId, () => {
1135
1191
  render();
1136
1192
  let branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { M: itemKey } : {});
1137
- resumeMarker || (loopScopes = push(loopScopes, referenceScope(branchScope)));
1193
+ resumeMarker || (loopScopes = push(loopScopes, branchScope));
1138
1194
  });
1139
1195
  }), loopScopes && writeScope(scopeId, { ["A" + accessor]: loopScopes }), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
1140
1196
  }
@@ -1144,7 +1200,7 @@ function _if(cb, scopeId, accessor, serializeBranch, serializeMarker, serializeS
1144
1200
  let branchIndex = resumeBranch ? withBranchId(branchId, cb) : cb(), shouldWriteBranch = resumeBranch && branchIndex !== void 0;
1145
1201
  shouldWriteBranch && (branchIndex || !resumeMarker) && writeScope(scopeId, {
1146
1202
  ["D" + accessor]: branchIndex || void 0,
1147
- ["A" + accessor]: resumeMarker ? void 0 : referenceScope(writeScope(branchId, {}))
1203
+ ["A" + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
1148
1204
  }), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
1149
1205
  }
1150
1206
  function writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, branchIds) {
@@ -1155,22 +1211,15 @@ function writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, p
1155
1211
  } else $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
1156
1212
  else $chunk.writeHTML(endTag);
1157
1213
  }
1158
- function scopeHasReference(scope) {
1159
- return !!scope[K_SCOPE_REFERENCED];
1160
- }
1161
- function referenceScope(scope) {
1162
- return scope[K_SCOPE_REFERENCED] = 1, scope;
1163
- }
1164
- function writeScopeToState(state, scopeId, partialScope) {
1165
- let { scopes } = state, scope = scopes.get(scopeId);
1166
- return state.needsMainRuntime = !0, scope ? Object.assign(scope, partialScope) : (scope = partialScope, scope[K_SCOPE_ID] = scopeId, state.scopes.set(scopeId, scope)), state.writeScopes ? state.writeScopes[scopeId] = scope : state.writeScopes = { [scopeId]: scope }, scope;
1167
- }
1168
1214
  function _existing_scope(scopeId) {
1169
- return writeScope(scopeId, _scope_with_id(scopeId));
1215
+ return writeScope(scopeId, {});
1170
1216
  }
1171
1217
  function _scope_with_id(scopeId) {
1172
- let { state } = $chunk.boundary, scope = state.scopes.get(scopeId);
1173
- return scope || (scope = { [K_SCOPE_ID]: scopeId }, state.scopes.set(scopeId, scope)), referenceScope(scope);
1218
+ return scopeWithId($chunk.boundary.state, scopeId);
1219
+ }
1220
+ function scopeWithId(state, scopeId) {
1221
+ let { scopes } = state, scope = scopes.get(scopeId);
1222
+ return scope || scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId }), scope;
1174
1223
  }
1175
1224
  function $global() {
1176
1225
  return $chunk.boundary.state.$global;
@@ -1185,7 +1234,7 @@ function _await(scopeId, accessor, promise, content, serializeMarker) {
1185
1234
  return;
1186
1235
  }
1187
1236
  let chunk = $chunk, { boundary } = chunk;
1188
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context), chunk.async = !0, chunk.context?.[kPendingContexts] && (chunk.context = {
1237
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next), chunk.async = !0, chunk.context?.[kPendingContexts] && (chunk.context = {
1189
1238
  ...chunk.context,
1190
1239
  [kPendingContexts]: 0
1191
1240
  }), boundary.startAsync(), promise.then((value) => {
@@ -1210,15 +1259,19 @@ function _try(scopeId, accessor, content, input) {
1210
1259
  }), $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
1211
1260
  }
1212
1261
  function tryPlaceholder(content, placeholder, branchId) {
1213
- let chunk = $chunk, { boundary } = chunk, body = new Chunk(boundary, null, chunk.context);
1262
+ let chunk = $chunk, { boundary } = chunk, body = chunk.fork(boundary, null);
1214
1263
  if (body === body.render(content)) {
1215
1264
  chunk.append(body);
1216
1265
  return;
1217
1266
  }
1218
- chunk.next = $chunk = new Chunk(boundary, chunk.next, chunk.context), chunk.placeholderBody = body, chunk.placeholderRender = placeholder, chunk.placeholderBranchId = branchId;
1267
+ chunk.next = $chunk = chunk.fork(boundary, chunk.next), chunk.placeholder = {
1268
+ body,
1269
+ render: placeholder,
1270
+ branchId
1271
+ };
1219
1272
  }
1220
1273
  function tryCatch(content, catchContent) {
1221
- let chunk = $chunk, { boundary } = chunk, { state } = boundary, catchBoundary = new Boundary(state), body = new Chunk(catchBoundary, null, chunk.context), bodyEnd = body.render(content);
1274
+ let chunk = $chunk, { boundary } = chunk, { state } = boundary, catchBoundary = new Boundary(state), body = chunk.fork(catchBoundary, null), bodyEnd = body.render(content);
1222
1275
  if (catchBoundary.signal.aborted) {
1223
1276
  catchContent(catchBoundary.signal.reason);
1224
1277
  return;
@@ -1227,17 +1280,17 @@ function tryCatch(content, catchContent) {
1227
1280
  chunk.append(body);
1228
1281
  return;
1229
1282
  }
1230
- let reorderId = state.nextReorderId(), endMarker = state.mark("!", reorderId), bodyNext = bodyEnd.next = $chunk = new Chunk(boundary, chunk.next, body.context);
1283
+ let reorderId = state.nextReorderId(), endMarker = state.mark("!", reorderId), bodyNext = bodyEnd.next = $chunk = body.fork(boundary, chunk.next);
1231
1284
  chunk.next = body, chunk.writeHTML(state.mark("!^", reorderId)), bodyEnd.writeHTML(endMarker), boundary.startAsync(), catchBoundary.onNext = () => {
1232
1285
  if (!boundary.signal.aborted) if (catchBoundary.signal.aborted) {
1233
1286
  if (!bodyEnd.consumed) {
1234
1287
  let cur = body, writeMarker = !0;
1235
1288
  do {
1236
1289
  let next = cur.next;
1237
- cur.boundary !== catchBoundary && cur.boundary.abort(catchBoundary.signal.reason), writeMarker && !cur.consumed && (writeMarker = !1, cur.async = !1, cur.next = bodyNext, cur.needsWalk = !0, cur.html = endMarker, cur.scripts = cur.effects = cur.lastEffect = "", cur.placeholderBody = cur.placeholderRender = cur.reorderId = null), cur = next;
1290
+ cur.boundary !== catchBoundary && cur.boundary.abort(catchBoundary.signal.reason), writeMarker && !cur.consumed && (writeMarker = !1, cur.async = !1, cur.next = bodyNext, cur.needsWalk = !0, cur.html = endMarker, cur.scripts = cur.effects = cur.lastEffect = "", cur.placeholder = cur.reorderId = cur.deferredReady = null), cur = next;
1238
1291
  } while (cur !== bodyNext);
1239
1292
  }
1240
- let catchChunk = new Chunk(boundary, null, chunk.context);
1293
+ let catchChunk = chunk.fork(boundary, null);
1241
1294
  catchChunk.reorderId = reorderId, catchChunk.render(catchContent, catchBoundary.signal.reason), state.reorder(catchChunk), boundary.endAsync();
1242
1295
  } else catchBoundary.count ? boundary.onNext() : boundary.endAsync();
1243
1296
  };
@@ -1247,10 +1300,11 @@ var State = class {
1247
1300
  tagId = 1;
1248
1301
  scopeId = 1;
1249
1302
  reorderId = 1;
1250
- lastSerializedScopeId = this.scopeId;
1303
+ readyGate = 1;
1251
1304
  hasGlobals = !1;
1252
1305
  needsMainRuntime = !1;
1253
1306
  hasMainRuntime = !1;
1307
+ hasReadyRuntime = !1;
1254
1308
  hasReorderRuntime = !1;
1255
1309
  hasWrittenResume = !1;
1256
1310
  walkOnNextFlush = !1;
@@ -1260,11 +1314,12 @@ var State = class {
1260
1314
  serializer = new Serializer();
1261
1315
  writeReorders = null;
1262
1316
  scopes = /* @__PURE__ */ new Map();
1263
- writeScopes = null;
1264
- ensureReady = null;
1317
+ flushScopes = !1;
1318
+ writeScopes = {};
1319
+ readyIds = null;
1265
1320
  serializeReason;
1266
1321
  constructor($global) {
1267
- this.$global = $global, this.$global = $global, $global.cspNonce && (this.nonceAttr = " nonce" + attrAssignment($global.cspNonce));
1322
+ this.$global = $global, $global.cspNonce && (this.nonceAttr = " nonce" + attrAssignment($global.cspNonce));
1268
1323
  }
1269
1324
  get runtimePrefix() {
1270
1325
  let { $global } = this;
@@ -1277,6 +1332,13 @@ var State = class {
1277
1332
  reorder(chunk) {
1278
1333
  this.writeReorders ? this.writeReorders.push(chunk) : (this.needsMainRuntime = !0, this.writeReorders = [chunk]);
1279
1334
  }
1335
+ writeReady(id, resumes) {
1336
+ let readyKey = toObjectKey(id);
1337
+ return this.readyIds?.has(id) ? this.readyAccess(readyKey) + ".push(" + resumes + ")" : ((this.readyIds ||= /* @__PURE__ */ new Set()).add(id), this.hasReadyRuntime ? this.readyAccess(readyKey) + "=[" + resumes + "]" : (this.hasReadyRuntime = !0, this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}"));
1338
+ }
1339
+ readyAccess(readyKey) {
1340
+ return this.runtimePrefix + ".b" + toAccess(readyKey);
1341
+ }
1280
1342
  nextReorderId() {
1281
1343
  let c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789", n = this.reorderId++, r = c[n % 54];
1282
1344
  for (n = n / 54 | 0; n; n >>>= 6) r += c[n & 63];
@@ -1290,14 +1352,14 @@ var State = class {
1290
1352
  onNext = NOOP$2;
1291
1353
  count = 0;
1292
1354
  constructor(state, parent) {
1293
- super(), this.state = state, this.state = state, this.signal.addEventListener("abort", () => {
1355
+ super(), this.state = state, this.signal.addEventListener("abort", () => {
1294
1356
  this.count = 0, this.state = new State(this.state.$global), this.onNext();
1295
1357
  }), parent && (parent.aborted ? this.abort(parent.reason) : parent.addEventListener("abort", () => {
1296
1358
  this.abort(parent.reason);
1297
1359
  }));
1298
1360
  }
1299
1361
  flush() {
1300
- return this.signal.aborted || flushSerializer(this), this.count ? 1 : this.signal.aborted ? 2 : 0;
1362
+ return this.signal.aborted || flushSerializer(this, this.state), this.count ? 1 : this.signal.aborted ? 2 : 0;
1301
1363
  }
1302
1364
  startAsync() {
1303
1365
  this.signal.aborted || this.count++;
@@ -1305,10 +1367,11 @@ var State = class {
1305
1367
  endAsync(chunk) {
1306
1368
  !this.signal.aborted && this.count && (this.count--, chunk?.reorderId && this.state.reorder(chunk), this.onNext());
1307
1369
  }
1308
- }, Chunk = class {
1370
+ }, Chunk = class Chunk {
1309
1371
  boundary;
1310
1372
  next;
1311
1373
  context;
1374
+ serializeState;
1312
1375
  html = "";
1313
1376
  scripts = "";
1314
1377
  effects = "";
@@ -1317,11 +1380,13 @@ var State = class {
1317
1380
  consumed = !1;
1318
1381
  needsWalk = !1;
1319
1382
  reorderId = null;
1320
- placeholderBody = null;
1321
- placeholderRender = null;
1322
- placeholderBranchId = null;
1323
- constructor(boundary, next, context) {
1324
- this.boundary = boundary, this.next = next, this.context = context, this.boundary = boundary, this.next = next, this.context = context;
1383
+ deferredReady = null;
1384
+ placeholder = null;
1385
+ constructor(boundary, next, context, serializeState) {
1386
+ this.boundary = boundary, this.next = next, this.context = context, this.serializeState = serializeState;
1387
+ }
1388
+ fork(boundary, next) {
1389
+ return new Chunk(boundary, next, this.context, this.serializeState);
1325
1390
  }
1326
1391
  writeHTML(html) {
1327
1392
  this.html += html;
@@ -1333,30 +1398,35 @@ var State = class {
1333
1398
  this.scripts = concatScripts(this.scripts, script);
1334
1399
  }
1335
1400
  append(chunk) {
1336
- this.html += chunk.html, this.effects = concatEffects(this.effects, chunk.effects), this.scripts = concatScripts(this.scripts, chunk.scripts), this.lastEffect = chunk.lastEffect || this.lastEffect;
1401
+ this.html += chunk.html, this.effects = concatEffects(this.effects, chunk.effects), this.scripts = concatScripts(this.scripts, chunk.scripts), this.lastEffect = chunk.lastEffect || this.lastEffect, this.deferredReady = concat(this.deferredReady, chunk.takeDeferredReady());
1402
+ }
1403
+ takeDeferredReady() {
1404
+ let { deferredReady } = this;
1405
+ return this.deferredReady = null, deferredReady;
1406
+ }
1407
+ deferOwnReady() {
1408
+ if (this.serializeState.readyId && (this.effects || this.scripts || this.serializeState.flushScopes)) {
1409
+ let deferred = this.fork(this.boundary, null);
1410
+ deferred.effects = this.effects, deferred.scripts = this.scripts, this.effects = this.scripts = this.lastEffect = "", this.deferredReady = concat(deferred, this.deferredReady);
1411
+ }
1337
1412
  }
1338
1413
  flushPlaceholder() {
1339
- if (this.placeholderBody) {
1340
- let body = this.placeholderBody.consume();
1414
+ let { placeholder } = this;
1415
+ if (placeholder) {
1416
+ let body = placeholder.body.consume();
1341
1417
  if (body.async) {
1342
- let { state } = this.boundary, reorderId = body.reorderId = this.placeholderBranchId ? this.placeholderBranchId + "" : state.nextReorderId();
1343
- this.placeholderBranchId = null, this.writeHTML(state.mark("!^", reorderId));
1344
- let after = this.render(this.placeholderRender);
1418
+ let { state } = this.boundary, reorderId = body.reorderId = placeholder.branchId ? placeholder.branchId + "" : state.nextReorderId();
1419
+ this.writeHTML(state.mark("!^", reorderId));
1420
+ let after = this.render(placeholder.render);
1345
1421
  after !== this && this.boundary.abort(/* @__PURE__ */ Error("An @placeholder cannot contain async content.")), after.writeHTML(state.mark("!", reorderId)), state.reorder(body);
1346
1422
  } else body.next = this.next, this.next = body;
1347
- this.placeholderRender = this.placeholderBody = null;
1423
+ this.placeholder = null;
1348
1424
  }
1349
1425
  }
1350
1426
  consume() {
1351
- let cur = this, needsWalk = cur.needsWalk;
1352
- if (cur.next && !cur.async) {
1353
- let html = "", effects = "", scripts = "", lastEffect = "";
1354
- do
1355
- cur.flushPlaceholder(), needsWalk ||= cur.needsWalk, html += cur.html, effects = concatEffects(effects, cur.effects), scripts = concatScripts(scripts, cur.scripts), lastEffect = cur.lastEffect || lastEffect, cur.consumed = !0, cur = cur.next;
1356
- while (cur.next && !cur.async);
1357
- cur.needsWalk = needsWalk, cur.html = html + cur.html, cur.effects = concatEffects(effects, cur.effects), cur.scripts = concatScripts(scripts, cur.scripts), cur.lastEffect = lastEffect;
1358
- }
1359
- return cur;
1427
+ let cur = this, html = "", effects = "", scripts = "", lastEffect = "", needsWalk = !1, deferredReady;
1428
+ for (; cur.next && !cur.async;) cur.flushPlaceholder(), needsWalk ||= cur.needsWalk, html += cur.html, cur.serializeState.readyId ? deferredReady = push(deferredReady, cur) : (effects = concatEffects(effects, cur.effects), scripts = concatScripts(scripts, cur.scripts), lastEffect = cur.lastEffect || lastEffect), deferredReady = concat(deferredReady, cur.takeDeferredReady()), cur.consumed = !0, cur = cur.next;
1429
+ return cur.deferOwnReady(), cur.deferredReady = concat(deferredReady, cur.deferredReady), cur.needsWalk ||= needsWalk, cur.html = html + cur.html, cur.effects = concatEffects(effects, cur.effects), cur.scripts = concatScripts(scripts, cur.scripts), cur.lastEffect ||= lastEffect, cur;
1360
1430
  }
1361
1431
  render(content, val) {
1362
1432
  let prev = $chunk;
@@ -1369,23 +1439,49 @@ var State = class {
1369
1439
  $chunk = prev;
1370
1440
  }
1371
1441
  }
1442
+ flushReadyScripts(reservations) {
1443
+ let { boundary, serializeState } = this, { readyId } = serializeState, scripts = "";
1444
+ if (forEach(this.takeDeferredReady(), (chunk) => {
1445
+ scripts = concatScripts(scripts, chunk.flushReadyScripts(reservations));
1446
+ }), readyId && !this.async) {
1447
+ let { state } = boundary;
1448
+ flushSerializer(boundary, serializeState);
1449
+ let deps = state.serializer.takeChannelDeps(), { effects } = this, { resumes } = serializeState, chunkScripts = this.scripts;
1450
+ if (serializeState.resumes = "", this.effects = this.scripts = "", this.lastEffect = "", resumes || effects) {
1451
+ state.needsMainRuntime = !0;
1452
+ let batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
1453
+ if (reservations) {
1454
+ let gate = state.readyGate++;
1455
+ reservations.push(state.writeReady(readyId, gate + "")), scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
1456
+ } else scripts = concatScripts(scripts, state.writeReady(readyId, batch));
1457
+ }
1458
+ scripts = concatScripts(scripts, chunkScripts);
1459
+ }
1460
+ return scripts;
1461
+ }
1372
1462
  flushScript() {
1373
- let { boundary, effects } = this, { state } = boundary, { $global, runtimePrefix, nonceAttr } = state, { html, scripts } = this, needsWalk = state.walkOnNextFlush;
1374
- if (needsWalk && (state.walkOnNextFlush = !1), state.needsMainRuntime && !state.hasMainRuntime && (state.hasMainRuntime = !0, scripts = concatScripts(scripts, "(e=>(self[e]||=(l,f=e+l,s=f.length,a={},d=[],t=document,n=t.createTreeWalker(t,129))=>t=self[e][l]={i:f,d:t,l:a,v:d,x(){},w(e,l,r){for(;e=n.nextNode();)t.x(l=(l=e.data)&&!l.indexOf(f)&&(a[r=l.slice(s+1)]=e,l[s]),r,e),l>\"#\"&&d.push(e)}},self[e]))(\"" + $global.runtimeId + "\")(\"" + $global.renderId + "\")")), state.ensureReady && state.hasMainRuntime) {
1375
- let first = !0;
1376
- for (let id in state.ensureReady) state.ensureReady[id] && (state.ensureReady[id] = 0, scripts = first ? concatScripts(scripts, "(" + runtimePrefix + ".b={})" + toAccess(toObjectKey(id)) + "=1") : concatScripts(scripts, runtimePrefix + ".b" + toAccess(toObjectKey(id)) + "=1")), first = !1;
1463
+ let { boundary } = this, { state } = boundary, { $global, runtimePrefix, nonceAttr } = state, needsWalk = state.walkOnNextFlush;
1464
+ needsWalk && (state.walkOnNextFlush = !1);
1465
+ let readyResumeScripts = this.flushReadyScripts();
1466
+ for (let channel; channel = state.serializer.pendingReadyChannel();) {
1467
+ let resumes = state.serializer.stringifyScopes([], 0, boundary, channel), deps = state.serializer.takeChannelDeps();
1468
+ state.needsMainRuntime = !0, readyResumeScripts = concatScripts(readyResumeScripts, state.writeReady(channel.readyId, concatSequence(depsMarker(deps), resumes)));
1377
1469
  }
1378
- if (effects && (needsWalk = !0, state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\""), state.resumes && (state.hasWrittenResume ? scripts = concatScripts(scripts, runtimePrefix + ".r.push(" + state.resumes + ")") : (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[" + state.resumes + "]"))), state.writeReorders) {
1470
+ readyResumeScripts && (needsWalk = !0);
1471
+ let { effects } = this, { html, scripts } = this;
1472
+ if (state.needsMainRuntime && !state.hasMainRuntime && (state.hasMainRuntime = !0, scripts = concatScripts(scripts, "(e=>(self[e]||=(l,f=e+l,s=f.length,a={},d=[],t=document,n=t.createTreeWalker(t,129))=>t=self[e][l]={i:f,d:t,l:a,v:d,x(){},w(e,l,r){for(;e=n.nextNode();)t.x(l=(l=e.data)&&!l.indexOf(f)&&(a[r=l.slice(s+1)]=e,l[s]),r,e),l>\"#\"&&d.push(e)}},self[e]))(\"" + $global.runtimeId + "\")(\"" + $global.renderId + "\")")), scripts = concatScripts(scripts, readyResumeScripts), effects && (needsWalk = !0, state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\""), state.resumes && (state.hasWrittenResume ? scripts = concatScripts(scripts, runtimePrefix + ".r.push(" + state.resumes + ")") : (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[" + state.resumes + "]"))), state.writeReorders) {
1379
1473
  needsWalk = !0, state.hasReorderRuntime || (state.hasReorderRuntime = !0, html += "<style " + state.commentPrefix + nonceAttr + ">t{display:none}</style>", scripts = concatScripts(scripts, "(e=>{if(e.j)return;let i,l,r,t=e.p={},c=(i,l)=>e.l[i].replaceWith(...l.childNodes);e.d.head.append(e.d.querySelector(\"style[\"+e.i+\"]\")||\"\"),e.j={},e.x=(n,a,d,o,g)=>{d==r&&i(),\"#\"==n?(t[a]=l).i++:\"!\"==n?e.l[a]&&t[a]&&(r=d.nextSibling,i=()=>t[a].c()):\"T\"==d.tagName&&(a=d.getAttribute(e.i))&&(r=d.nextSibling,i=()=>{d.remove(),o||c(a,d),l.c()},l=t[a]||(o=t[a]={i:e.l[a]?1:2,c(i=e.l[\"^\"+a]){if(--o.i)return 1;for(;(r=e.l[a].previousSibling||i).remove(),i!=r;);c(a,d)}}),(n=e.j[a])&&(g=l.c,l.c=()=>g()||n(e.r)))}})(" + runtimePrefix + ")"));
1380
1474
  for (let reorderedChunk of state.writeReorders) {
1381
- let { reorderId } = reorderedChunk, reorderHTML = "", reorderEffects = "", reorderScripts = "", cur = reorderedChunk;
1475
+ let { reorderId } = reorderedChunk, readyReservations = [], reorderHTML = "", reorderEffects = "", reorderScripts = "", cur = reorderedChunk;
1382
1476
  for (reorderedChunk.reorderId = null;;) {
1383
- cur.flushPlaceholder();
1384
- let { next } = cur;
1385
- if (cur.consumed = !0, reorderHTML += cur.html, reorderEffects = concatEffects(reorderEffects, cur.effects), reorderScripts = concatScripts(reorderScripts, cur.scripts), cur.async && (reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId()), cur.html = cur.effects = cur.scripts = cur.lastEffect = "", cur.next = null), next) cur = next;
1477
+ cur.flushPlaceholder(), cur.deferOwnReady();
1478
+ let { next } = cur, readyResumeScripts = cur.flushReadyScripts(readyReservations);
1479
+ if (cur.consumed = !0, reorderHTML += cur.html, reorderEffects = concatEffects(reorderEffects, cur.effects), reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts)), cur.async && (reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId()), cur.html = cur.effects = cur.scripts = cur.lastEffect = "", cur.next = null), next) cur = next;
1386
1480
  else break;
1387
1481
  }
1388
- reorderEffects && (state.hasWrittenResume || (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[]")), reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")")), scripts = concatScripts(scripts, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}"), html += "<t " + state.commentPrefix + "=" + reorderId + ">" + reorderHTML + "</t>";
1482
+ reorderEffects && (state.hasWrittenResume || (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[]")), reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")"));
1483
+ for (let reservation of readyReservations) scripts = concatScripts(scripts, reservation);
1484
+ scripts = concatScripts(scripts, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}"), html += "<t " + state.commentPrefix + "=" + reorderId + ">" + reorderHTML + "</t>";
1389
1485
  }
1390
1486
  state.writeReorders = null;
1391
1487
  }
@@ -1398,20 +1494,37 @@ var State = class {
1398
1494
  return this.html = this.scripts = "", scripts && (html += "<script" + nonceAttr + ">" + scripts + "<\/script>"), __flush__ && ($global.__flush__ = void 0, html = __flush__($global, html)), boundary.count || (html += state.trailerHTML), html;
1399
1495
  }
1400
1496
  };
1401
- function flushSerializer(boundary) {
1402
- let { state } = boundary, { writeScopes, serializer } = state, { flushed } = serializer;
1403
- if (writeScopes || flushed) {
1404
- let shouldSerialize = !1, serializeData = [], { lastSerializedScopeId } = state;
1405
- state.hasGlobals || (state.hasGlobals = !0, serializeData.push(getFilteredGlobals(state.$global)), shouldSerialize = !0);
1497
+ function flushSerializer(boundary, serializeState) {
1498
+ let { state } = boundary, { serializer } = state, pending = serializer.pending(serializeState);
1499
+ if (serializeState.flushScopes || pending) {
1500
+ let { writeScopes, passiveScopes } = serializeState, isBlockingState = serializeState !== state, flushes = [], globals = 0;
1501
+ if (passiveScopes) for (let key in passiveScopes) {
1502
+ let props = writeScopes[key];
1503
+ props && (writeScopes[key] = Object.assign(passiveScopes[key], props), delete passiveScopes[key]);
1504
+ }
1505
+ !isBlockingState && !state.hasGlobals && (state.hasGlobals = !0, globals = getFilteredGlobals(state.$global));
1406
1506
  for (let key in writeScopes) {
1407
- let scope = writeScopes[key];
1408
- if (scopeHasReference(scope) || Object.getOwnPropertyNames(scope).length) {
1409
- let scopeId = getScopeId(scope), scopeIdDelta = scopeId - lastSerializedScopeId;
1410
- lastSerializedScopeId = scopeId + 1, scopeIdDelta && serializeData.push(scopeIdDelta), serializeData.push(scope), shouldSerialize = !0;
1411
- }
1507
+ let scopeId = +key, props = writeScopes[scopeId];
1508
+ Object.getOwnPropertyNames(props).length && flushes.push([
1509
+ scopeId,
1510
+ state.scopes.get(scopeId),
1511
+ props
1512
+ ]);
1412
1513
  }
1413
- shouldSerialize && (state.resumes = concatSequence(state.resumes, serializer.stringify(serializeData, boundary))), state.lastSerializedScopeId = lastSerializedScopeId, state.writeScopes = null, flushed && (state.walkOnNextFlush = !0);
1514
+ (flushes.length || globals || pending) && (isBlockingState && !state.hasGlobals && flushSerializerGlobals(boundary), serializeState.resumes = concatSequence(serializeState.resumes, serializer.stringifyScopes(flushes, globals, boundary, serializeState))), serializeState.writeScopes = {}, serializeState.flushScopes = !1, pending && (state.walkOnNextFlush = !0);
1515
+ }
1516
+ }
1517
+ function flushSerializerGlobals(boundary) {
1518
+ let { state } = boundary, globals = getFilteredGlobals(state.$global);
1519
+ globals && (state.hasGlobals = !0, state.needsMainRuntime = !0, state.resumes = concatSequence(state.resumes, state.serializer.stringifyScopes([], globals, boundary)));
1520
+ }
1521
+ function depsMarker(deps) {
1522
+ let marker = "";
1523
+ if (deps) {
1524
+ for (let dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
1525
+ marker += "]";
1414
1526
  }
1527
+ return marker;
1415
1528
  }
1416
1529
  function _trailers(html) {
1417
1530
  $chunk.boundary.state.trailerHTML += html;
@@ -1455,7 +1568,11 @@ function getFilteredGlobals($global) {
1455
1568
  return filtered;
1456
1569
  }
1457
1570
  function _subscribe(subscribers, scope) {
1458
- return subscribers && $chunk.boundary.state.serializer.writeCall(scope, subscribers, "add"), referenceScope(scope);
1571
+ if (subscribers) {
1572
+ let { serializer } = $chunk.boundary.state;
1573
+ !$chunk.serializeState.readyId && !serializer.written(subscribers) ? subscribers.add(scope) : serializer.writeCall(scope, subscribers, "add", $chunk.serializeState);
1574
+ }
1575
+ return scope;
1459
1576
  }
1460
1577
  //#endregion
1461
1578
  //#region src/html/attrs.ts
@@ -1603,8 +1720,6 @@ function normalizeBoolAttrValue(value) {
1603
1720
  if (value != null && value !== !1) return !0;
1604
1721
  }
1605
1722
  //#endregion
1606
- //#region src/common/compat-meta.ts
1607
- //#endregion
1608
1723
  //#region src/html/dynamic-tag.ts
1609
1724
  function _content(id, fn) {
1610
1725
  return fn.a = id, fn;
@@ -1613,9 +1728,6 @@ function _content_resume(id, fn, scopeId) {
1613
1728
  return _resume(_content(id, fn), id, scopeId);
1614
1729
  }
1615
1730
  //#endregion
1616
- //#region src/html/compat.ts
1617
- function NOOP$1() {}
1618
- //#endregion
1619
1731
  //#region src/html/template.ts
1620
1732
  function render(input = {}) {
1621
1733
  let { $global } = input;
@@ -1627,8 +1739,8 @@ function render(input = {}) {
1627
1739
  runtimeId: "M",
1628
1740
  renderId: getDefaultRenderId(this)
1629
1741
  };
1630
- let state = new State($global), head = new Chunk(new Boundary(state, $global.signal), null, null);
1631
- return this.i && ((state.ensureReady ||= {})[this.a] = 1), head.render(this, input), new ServerRendered(head);
1742
+ let state = new State($global), head = new Chunk(new Boundary(state, $global.signal), null, null, state);
1743
+ return this.i ? head.render(() => writeWaitReady(this.a, this, input)) : head.render(this, input), new ServerRendered(head);
1632
1744
  }
1633
1745
  function getDefaultRenderId(template) {
1634
1746
  if (template.i) {
@@ -1734,7 +1846,7 @@ var ServerRendered = class {
1734
1846
  (boundary.onNext = () => {
1735
1847
  switch (!boundary.count && boundary.flush()) {
1736
1848
  case 2:
1737
- boundary.onNext = NOOP, reject(boundary.signal.reason);
1849
+ boundary.onNext = NOOP$1, reject(boundary.signal.reason);
1738
1850
  break;
1739
1851
  case 0:
1740
1852
  resolve(head.consume().flushHTML());
@@ -1751,7 +1863,7 @@ var ServerRendered = class {
1751
1863
  }
1752
1864
  let { boundary } = head, onNext = boundary.onNext = (write) => {
1753
1865
  let status = boundary.flush();
1754
- if (status === 2) tick || offTick(onNext), boundary.onNext = NOOP, onAbort(boundary.signal.reason);
1866
+ if (status === 2) tick || offTick(onNext), boundary.onNext = NOOP$1, onAbort(boundary.signal.reason);
1755
1867
  else if (write || status === 0) {
1756
1868
  let html = (head = head.consume()).flushHTML();
1757
1869
  html && onWrite(html), status === 0 ? (tick || offTick(onNext), onClose()) : tick = !0;
@@ -1770,10 +1882,69 @@ var ServerRendered = class {
1770
1882
  return head.consume().flushHTML();
1771
1883
  }
1772
1884
  };
1885
+ function NOOP$1() {}
1886
+ //#endregion
1887
+ //#region src/html/assets.ts
1888
+ function withLoadAssets(renderer, assetId, triggers) {
1889
+ return Object.assign((input) => {
1890
+ let g = $global();
1891
+ return addAsset(g, assetId, triggers), _html(flush(g, "")), writeWaitReady(assetId, renderer, input);
1892
+ }, renderer);
1893
+ }
1894
+ function withPageAssets(template, runtime, assetId, runtimeId) {
1895
+ return assetFlush = runtime, Object.assign((input) => {
1896
+ let g = $global();
1897
+ return runtimeId && (g.runtimeId = runtimeId), addAsset(g, assetId), g.__flush__ ? (_html(flush(g, "")), writeWaitReady(assetId, template, input)) : (g.__flush__ = flush, template(input));
1898
+ }, template);
1899
+ }
1900
+ function _flush_head() {
1901
+ let g = $global();
1902
+ return g[kAssets] ? flush(g, "") : "";
1903
+ }
1904
+ function flush(g, html) {
1905
+ let result = "", assets = g[kAssets], { length } = assets, bi = g[kBlockIndex], di = g[kDeferIndex];
1906
+ for (; bi < length; bi++) result += assetFlush(g, "block", assets[bi].id);
1907
+ for (; di < length; di++) {
1908
+ let { id, triggers } = assets[di], deferHTML = assetFlush(g, "defer", id);
1909
+ triggers ? deferHTML && writeTriggerScript(deferHTML, triggers) : result += deferHTML;
1910
+ }
1911
+ return g[kBlockIndex] = bi, g[kDeferIndex] = di, result + html;
1912
+ }
1913
+ function addAsset(g, id, triggers) {
1914
+ let assets = g[kAssets];
1915
+ assets ? assets.find((a) => a.id === id) || assets.push({
1916
+ id,
1917
+ triggers
1918
+ }) : (g[kAssets] = [{
1919
+ id,
1920
+ triggers
1921
+ }], g[kBlockIndex] = g[kDeferIndex] = 0);
1922
+ }
1923
+ function writeTriggerScript(html, triggers) {
1924
+ let htmlStr = _escape_script(JSON.stringify(html)), exprs = triggers.map((trigger) => {
1925
+ let options = trigger.options && toObjectExpression(trigger.options);
1926
+ switch (trigger.type) {
1927
+ 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())`;
1928
+ case "idle": return `(self.requestIdleCallback||l)(l${options ? `,${options}` : ""})`;
1929
+ case "media": return `(m=>m.matches?l():m.addEventListener("change",l,{once:1}))(matchMedia(${JSON.stringify(trigger.selector)}))`;
1930
+ default: return `(e=>e?.addEventListener("${trigger.type.slice(3)}",l,{once:1}))(document.querySelector(${JSON.stringify(trigger.selector)})||l())`;
1931
+ }
1932
+ });
1933
+ writeScript(`((p,h,d,l=$=>d||p.insertAdjacentHTML("afterend",d=h))=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(document.currentScript,${htmlStr})`);
1934
+ }
1935
+ function toObjectExpression(options) {
1936
+ let result = "{", sep = "";
1937
+ for (let key in options) hasOwnProperty.call(options, key) && (result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]), sep = ",");
1938
+ return result + "}";
1939
+ }
1940
+ //#endregion
1941
+ //#region src/common/compat-meta.ts
1942
+ //#endregion
1943
+ //#region src/html/compat.ts
1773
1944
  function NOOP() {}
1774
1945
  exports.$global = $global, exports._assert_hoist = _assert_hoist, exports._attr = _attr, exports._attr_class = _attr_class, exports._attr_content = _attr_content, exports._attr_details_open = _attr_details_or_dialog_open, exports._attr_dialog_open = _attr_details_or_dialog_open, exports._attr_input_checked = _attr_input_checked, exports._attr_input_checkedValue = _attr_input_checkedValue, exports._attr_input_value = _attr_input_value, exports._attr_nonce = _attr_nonce, exports._attr_option_value = _attr_option_value, exports._attr_select_value = _attr_select_value, exports._attr_style = _attr_style, exports._attr_textarea_value = _attr_textarea_value, exports._attrs = _attrs, exports._attrs_content = _attrs_content, exports._attrs_partial = _attrs_partial, exports._attrs_partial_content = _attrs_partial_content, exports._await = _await, exports._content = _content, exports._content_resume = _content_resume, Object.defineProperty(exports, "_dynamic_tag", {
1775
1946
  enumerable: !0,
1776
1947
  get: function() {
1777
1948
  return _dynamic_tag;
1778
1949
  }
1779
- }), exports._el = _el, exports._el_read_error = _el_read_error, exports._el_resume = _el_resume, exports._escape = _escape, exports._escape_comment = _escape_comment, exports._escape_script = _escape_script, exports._escape_style = _escape_style, exports._existing_scope = _existing_scope, exports._for_in = _for_in, exports._for_of = _for_of, exports._for_to = _for_to, exports._for_until = _for_until, exports._hoist = _hoist, exports._hoist_read_error = _hoist_read_error, exports._html = _html, exports._id = _id, exports._if = _if, exports._peek_scope_id = _peek_scope_id, exports._resume = _resume, exports._resume_branch = _resume_branch, exports._scope = writeScope, exports._scope_id = _scope_id, exports._scope_reason = _scope_reason, exports._scope_with_id = _scope_with_id, exports._script = _script, exports._sep = _sep, exports._serialize_guard = _serialize_guard, exports._serialize_if = _serialize_if, exports._set_serialize_reason = _set_serialize_reason, exports._subscribe = _subscribe, exports._template = _template, exports._trailers = _trailers, exports._try = _try, exports._unescaped = _unescaped, exports._var = _var, exports.attrTag = attrTag, exports.attrTags = attrTags, exports.compat = compat, exports.forIn = forIn, exports.forInBy = forInBy, exports.forOf = forOf, exports.forOfBy = forOfBy, exports.forStepBy = forStepBy, exports.forTo = forTo, exports.forUntil = forUntil;
1950
+ }), exports._el = _el, exports._el_read_error = _el_read_error, exports._el_resume = _el_resume, exports._escape = _escape, exports._escape_comment = _escape_comment, exports._escape_script = _escape_script, exports._escape_style = _escape_style, exports._existing_scope = _existing_scope, exports._flush_head = _flush_head, exports._for_in = _for_in, exports._for_of = _for_of, exports._for_to = _for_to, exports._for_until = _for_until, exports._hoist = _hoist, exports._hoist_read_error = _hoist_read_error, exports._html = _html, exports._id = _id, exports._if = _if, exports._peek_scope_id = _peek_scope_id, exports._resume = _resume, exports._resume_branch = _resume_branch, exports._scope = writeScope, exports._scope_id = _scope_id, exports._scope_reason = _scope_reason, exports._scope_with_id = _scope_with_id, exports._script = _script, exports._sep = _sep, exports._serialize_guard = _serialize_guard, exports._serialize_if = _serialize_if, exports._set_serialize_reason = _set_serialize_reason, exports._subscribe = _subscribe, exports._template = _template, exports._trailers = _trailers, exports._try = _try, exports._unescaped = _unescaped, exports._var = _var, exports.attrTag = attrTag, exports.attrTags = attrTags, exports.compat = compat, exports.forIn = forIn, exports.forInBy = forInBy, exports.forOf = forOf, exports.forOfBy = forOfBy, exports.forStepBy = forStepBy, exports.forTo = forTo, exports.forUntil = forUntil, exports.withLoadAssets = withLoadAssets, exports.withPageAssets = withPageAssets;