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