@async/framework 0.11.16 → 0.11.18

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/framework.ts CHANGED
@@ -6263,7 +6263,19 @@ const __serverEntryModule = (() => {
6263
6263
  })();
6264
6264
 
6265
6265
  const __boundaryReceiverModule = (() => {
6266
+ const { normalizeAttributeConfig, readAttribute } = __attributesModule;
6267
+ const { renderTemplate } = __htmlModule;
6266
6268
  const defaultRecentLimit = 50;
6269
+ const builtBackpatchAttribute = "data-async-backpatch";
6270
+ const pendingTargetAttribute = "data-pending-id";
6271
+ const revealOrders = new Set(["as-ready", "forwards", "backwards", "together"]);
6272
+ const revealTails = new Set(["collapsed", "hidden"]);
6273
+ const structuralAttributeNames = new Set(["innerhtml", "outerhtml", "textcontent", "children", "childnodes"]);
6274
+
6275
+ const AsyncStream = Object.freeze({
6276
+ applyScript,
6277
+ applyCurrentScript
6278
+ });
6267
6279
 
6268
6280
  function createBoundaryReceiver(options = {}) {
6269
6281
  const loader = options.loader;
@@ -6271,6 +6283,7 @@ const __boundaryReceiverModule = (() => {
6271
6283
  const cache = options.cache ?? loader?.cache;
6272
6284
  const scheduler = options.scheduler ?? loader?.scheduler;
6273
6285
  const router = options.router ?? loader?.router;
6286
+ const attributes = normalizeAttributeConfig(options.attributes ?? loader?.attributes);
6274
6287
  const recentLimit = options.recentLimit ?? defaultRecentLimit;
6275
6288
  const throwOnError = options.throwOnError === true;
6276
6289
  const onApply = typeof options.onApply === "function" ? options.onApply : undefined;
@@ -6288,6 +6301,7 @@ const __boundaryReceiverModule = (() => {
6288
6301
  }
6289
6302
 
6290
6303
  const boundaries = new Map();
6304
+ const revealGroups = new Map();
6291
6305
  const recent = [];
6292
6306
  let destroyed = false;
6293
6307
 
@@ -6336,6 +6350,7 @@ const __boundaryReceiverModule = (() => {
6336
6350
  return {
6337
6351
  destroyed,
6338
6352
  boundaries: snapshot,
6353
+ reveal: inspectRevealGroups(revealGroups),
6339
6354
  recent: recent.map((entry) => ({ ...entry }))
6340
6355
  };
6341
6356
  },
@@ -6343,6 +6358,7 @@ const __boundaryReceiverModule = (() => {
6343
6358
  reset(boundary) {
6344
6359
  if (boundary === undefined) {
6345
6360
  boundaries.clear();
6361
+ revealGroups.clear();
6346
6362
  recent.length = 0;
6347
6363
  return receiver;
6348
6364
  }
@@ -6353,12 +6369,20 @@ const __boundaryReceiverModule = (() => {
6353
6369
  recent.splice(index, 1);
6354
6370
  }
6355
6371
  }
6372
+ for (const group of revealGroups.values()) {
6373
+ for (const [index, item] of group.pending) {
6374
+ if (item.normalized.boundary === boundary) {
6375
+ group.pending.delete(index);
6376
+ }
6377
+ }
6378
+ }
6356
6379
  return receiver;
6357
6380
  },
6358
6381
 
6359
6382
  destroy() {
6360
6383
  destroyed = true;
6361
6384
  boundaries.clear();
6385
+ revealGroups.clear();
6362
6386
  recent.length = 0;
6363
6387
  }
6364
6388
  };
@@ -6366,32 +6390,10 @@ const __boundaryReceiverModule = (() => {
6366
6390
  return receiver;
6367
6391
 
6368
6392
  async function applyBoundaryPatch(record, normalized, patch) {
6369
- if (normalized.seq <= record.lastSeq) {
6370
- const result = {
6371
- status: "ignored-stale",
6372
- boundary: normalized.boundary,
6373
- seq: normalized.seq,
6374
- lastSeq: record.lastSeq
6375
- };
6376
- record.ignored += 1;
6377
- record.lastStatus = result.status;
6378
- remember(result);
6379
- onIgnore?.(result, patch);
6380
- return result;
6381
- }
6382
-
6383
- if (normalized.parentScope !== undefined && isScopeDestroyed(normalized.parentScope)) {
6384
- const result = {
6385
- status: "ignored-destroyed",
6386
- boundary: normalized.boundary,
6387
- seq: normalized.seq,
6388
- parentScope: normalized.parentScope
6389
- };
6390
- record.ignored += 1;
6391
- record.lastStatus = result.status;
6392
- remember(result);
6393
- onIgnore?.(result, patch);
6394
- return result;
6393
+ const ignored = preflightIgnoredResult(record, normalized);
6394
+ if (ignored) {
6395
+ rememberIgnored(record, ignored, patch);
6396
+ return ignored;
6395
6397
  }
6396
6398
 
6397
6399
  if (Object.hasOwn(normalized, "error")) {
@@ -6413,35 +6415,91 @@ const __boundaryReceiverModule = (() => {
6413
6415
  return result;
6414
6416
  }
6415
6417
 
6416
- if (normalized.signals) {
6417
- if (!signals || typeof signals.set !== "function") {
6418
- throw new Error("Boundary patch includes signals, but no signal registry is available.");
6419
- }
6420
- for (const [path, value] of Object.entries(normalized.signals)) {
6421
- signals.set(path, value);
6422
- }
6418
+ applyStateEffects(normalized);
6419
+
6420
+ if (normalized.reveal) {
6421
+ return await applyRevealPatch(record, normalized, patch);
6423
6422
  }
6424
6423
 
6425
- if (normalized.cache?.browser) {
6426
- if (!cache || typeof cache.restore !== "function") {
6427
- throw new Error("Boundary patch includes browser cache, but no cache registry is available.");
6424
+ return await commitBoundaryPatch(record, normalized, patch, { stateApplied: true });
6425
+ }
6426
+
6427
+ async function applyRevealPatch(record, normalized, patch) {
6428
+ const group = revealGroup(normalized.reveal);
6429
+ const index = normalized.reveal.index;
6430
+ if (group.committed.has(index)) {
6431
+ throw new TypeError(`Reveal group "${group.id}" already committed index ${index}.`);
6432
+ }
6433
+ if (group.pending.has(index)) {
6434
+ throw new TypeError(`Reveal group "${group.id}" already has a pending patch for index ${index}.`);
6435
+ }
6436
+
6437
+ const item = { record, normalized, patch };
6438
+ group.pending.set(index, item);
6439
+ const ready = takeReadyRevealItems(group);
6440
+ if (!ready.includes(item)) {
6441
+ const result = {
6442
+ status: "buffered",
6443
+ boundary: normalized.boundary,
6444
+ seq: normalized.seq,
6445
+ reveal: revealResultMetadata(normalized.reveal)
6446
+ };
6447
+ record.lastStatus = result.status;
6448
+ remember(result);
6449
+ updateRevealTail(group);
6450
+ return result;
6451
+ }
6452
+
6453
+ let currentResult;
6454
+ for (const readyItem of ready) {
6455
+ const result = await commitBoundaryPatch(readyItem.record, readyItem.normalized, readyItem.patch, {
6456
+ stateApplied: true
6457
+ });
6458
+ group.committed.add(readyItem.normalized.reveal.index);
6459
+ if (readyItem === item) {
6460
+ currentResult = result;
6428
6461
  }
6429
- cache.restore(normalized.cache.browser);
6462
+ }
6463
+ updateRevealTail(group);
6464
+ return currentResult;
6465
+ }
6466
+
6467
+ async function commitBoundaryPatch(record, normalized, patch, options = {}) {
6468
+ const ignored = preflightIgnoredResult(record, normalized);
6469
+ if (ignored) {
6470
+ rememberIgnored(record, ignored, patch);
6471
+ return ignored;
6472
+ }
6473
+
6474
+ if (!options.stateApplied) {
6475
+ applyStateEffects(normalized);
6430
6476
  }
6431
6477
 
6478
+ let boundaryElement;
6479
+ let replacementCount = 0;
6432
6480
  if (normalized.html != null) {
6433
- loader.swap(normalized.boundary, normalized.html);
6481
+ boundaryElement = loader.swap(normalized.boundary, normalized.html);
6482
+ }
6483
+ if (normalized.replace) {
6484
+ boundaryElement ??= findBoundaryElement(loader.root, normalized.boundary, attributes);
6485
+ replacementCount = applyReplacements(boundaryElement, normalized.replace);
6486
+ }
6487
+
6488
+ let attrs;
6489
+ if (normalized.attrs) {
6490
+ boundaryElement ??= findBoundaryElement(loader.root, normalized.boundary, attributes);
6491
+ attrs = applyAttributePatches(boundaryElement, normalized.attrs);
6434
6492
  }
6435
6493
 
6436
6494
  await flushScheduler(scheduler, normalized.scope);
6437
6495
 
6438
6496
  if (normalized.redirect) {
6439
- const result = {
6497
+ const result = withPatchMetadata({
6440
6498
  status: "redirected",
6441
6499
  boundary: normalized.boundary,
6442
6500
  seq: normalized.seq,
6443
6501
  redirect: normalized.redirect
6444
- };
6502
+ }, attrs, replacementCount);
6445
6503
  await followRedirect(normalized.redirect, router, loader);
6446
6504
  record.applied += 1;
6447
6505
  record.lastSeq = normalized.seq;
@@ -6451,11 +6509,11 @@ const __boundaryReceiverModule = (() => {
6451
6509
  return result;
6452
6510
  }
6453
6511
 
6454
- const result = {
6512
+ const result = withPatchMetadata({
6455
6513
  status: "applied",
6456
6514
  boundary: normalized.boundary,
6457
6515
  seq: normalized.seq
6458
- };
6516
+ }, attrs, replacementCount);
6459
6517
  record.applied += 1;
6460
6518
  record.lastSeq = normalized.seq;
6461
6519
  record.lastStatus = result.status;
@@ -6464,6 +6522,157 @@ const __boundaryReceiverModule = (() => {
6464
6522
  return result;
6465
6523
  }
6466
6524
 
6525
+ function applyStateEffects(normalized) {
6526
+ if (normalized.signals) {
6527
+ if (!signals || typeof signals.set !== "function") {
6528
+ throw new Error("Boundary patch includes signals, but no signal registry is available.");
6529
+ }
6530
+ for (const [path, value] of Object.entries(normalized.signals)) {
6531
+ signals.set(path, value);
6532
+ }
6533
+ }
6534
+
6535
+ if (normalized.cache?.browser) {
6536
+ if (!cache || typeof cache.restore !== "function") {
6537
+ throw new Error("Boundary patch includes browser cache, but no cache registry is available.");
6538
+ }
6539
+ cache.restore(normalized.cache.browser);
6540
+ }
6541
+ }
6542
+
6543
+ function applyReplacements(boundaryElement, replacements) {
6544
+ let applied = 0;
6545
+ for (const replacement of replacements) {
6546
+ if (replacement.mode === "boundary") {
6547
+ const target = findBoundaryElement(loader.root, replacement.target, attributes);
6548
+ if (!containsOrEquals(boundaryElement, target)) {
6549
+ throw new Error(`Boundary replacement target "${replacement.target}" is outside boundary "${boundaryIdFor(boundaryElement, attributes)}".`);
6550
+ }
6551
+ loader.swap(replacement.target, replacement.html);
6552
+ applied += 1;
6553
+ continue;
6554
+ }
6555
+
6556
+ const target = findUniqueScopedElement(
6557
+ boundaryElement,
6558
+ (element) => element.getAttribute?.(pendingTargetAttribute) === replacement.target,
6559
+ `Pending replacement target "${replacement.target}"`
6560
+ );
6561
+ const fragment = toFragment(replacement.html, ownerDocumentOf(boundaryElement));
6562
+ const inserted = [...fragment.childNodes];
6563
+ target.replaceWith(fragment);
6564
+ for (const node of inserted) {
6565
+ if (node.nodeType === 1 || node.nodeType === 11) {
6566
+ loader.scan?.(node);
6567
+ }
6568
+ }
6569
+ applied += 1;
6570
+ }
6571
+ return applied;
6572
+ }
6573
+
6574
+ function applyAttributePatches(boundaryElement, attrs) {
6575
+ let applied = 0;
6576
+ for (const attr of attrs.items) {
6577
+ const target = attrs.kind === "built"
6578
+ ? resolveBuiltAttrTarget(boundaryElement, attr.target)
6579
+ : resolveNamedAttrTarget(boundaryElement, attr.target);
6580
+ setPatchedAttribute(target, attr.name, attr.value);
6581
+ applied += 1;
6582
+ }
6583
+ return {
6584
+ applied,
6585
+ ignored: 0
6586
+ };
6587
+ }
6588
+
6589
+ function resolveBuiltAttrTarget(boundaryElement, targetIndex) {
6590
+ const targets = scopedElements(boundaryElement)
6591
+ .filter((element) => element.hasAttribute?.(builtBackpatchAttribute));
6592
+ const target = targets[targetIndex];
6593
+ if (!target) {
6594
+ throw new Error(`Built attribute patch target ${targetIndex} was not found in boundary "${boundaryIdFor(boundaryElement, attributes)}".`);
6595
+ }
6596
+ return target;
6597
+ }
6598
+
6599
+ function resolveNamedAttrTarget(boundaryElement, targetName) {
6600
+ return findUniqueScopedElement(
6601
+ boundaryElement,
6602
+ (element) => readAttribute(element, attributes, "async", "patch") === targetName,
6603
+ `Attribute patch target "${targetName}"`
6604
+ );
6605
+ }
6606
+
6607
+ function findUniqueScopedElement(boundaryElement, predicate, label) {
6608
+ const matches = scopedElements(boundaryElement).filter(predicate);
6609
+ if (matches.length === 0) {
6610
+ throw new Error(`${label} was not found.`);
6611
+ }
6612
+ if (matches.length > 1) {
6613
+ throw new Error(`${label} is ambiguous.`);
6614
+ }
6615
+ return matches[0];
6616
+ }
6617
+
6618
+ function scopedElements(boundaryElement) {
6619
+ return elementsIn(boundaryElement)
6620
+ .filter((element) => !isNestedBoundaryElement(element, boundaryElement, attributes));
6621
+ }
6622
+
6623
+ function revealGroup(reveal) {
6624
+ const existing = revealGroups.get(reveal.group);
6625
+ if (existing) {
6626
+ if (existing.count !== reveal.count || existing.order !== reveal.order || existing.tail !== reveal.tail) {
6627
+ throw new TypeError(`Reveal group "${reveal.group}" metadata does not match earlier patches.`);
6628
+ }
6629
+ return existing;
6630
+ }
6631
+
6632
+ const group = {
6633
+ id: reveal.group,
6634
+ count: reveal.count,
6635
+ order: reveal.order,
6636
+ tail: reveal.tail,
6637
+ pending: new Map(),
6638
+ committed: new Set(),
6639
+ nextForward: 0,
6640
+ nextBackward: reveal.count - 1
6641
+ };
6642
+ revealGroups.set(reveal.group, group);
6643
+ return group;
6644
+ }
6645
+
6646
+ function updateRevealTail(group) {
6647
+ if (!group.tail) {
6648
+ return;
6649
+ }
6650
+ const container = findRevealContainer(loader.root, group.id, attributes);
6651
+ if (!container) {
6652
+ return;
6653
+ }
6654
+ const children = directChildBoundaryElements(container, attributes).slice(0, group.count);
6655
+ if (children.length === 0) {
6656
+ return;
6657
+ }
6658
+
6659
+ const pending = [];
6660
+ for (let index = 0; index < children.length; index += 1) {
6661
+ if (!group.committed.has(index)) {
6662
+ pending.push(index);
6663
+ } else {
6664
+ setTailHidden(children[index], false);
6665
+ }
6666
+ }
6667
+
6668
+ const visiblePending = group.tail === "collapsed" && pending.length > 0
6669
+ ? pendingOrderFor(group, pending)[0]
6670
+ : undefined;
6671
+ for (const index of pending) {
6672
+ setTailHidden(children[index], group.tail === "hidden" || index !== visiblePending);
6673
+ }
6674
+ }
6675
+
6467
6676
  function boundaryRecord(boundary) {
6468
6677
  if (!boundaries.has(boundary)) {
6469
6678
  boundaries.set(boundary, {
@@ -6478,6 +6687,34 @@ const __boundaryReceiverModule = (() => {
6478
6687
  return boundaries.get(boundary);
6479
6688
  }
6480
6689
 
6690
+ function preflightIgnoredResult(record, normalized) {
6691
+ if (normalized.seq <= record.lastSeq) {
6692
+ return {
6693
+ status: "ignored-stale",
6694
+ boundary: normalized.boundary,
6695
+ seq: normalized.seq,
6696
+ lastSeq: record.lastSeq
6697
+ };
6698
+ }
6699
+
6700
+ if (normalized.parentScope !== undefined && isScopeDestroyed(normalized.parentScope)) {
6701
+ return {
6702
+ status: "ignored-destroyed",
6703
+ boundary: normalized.boundary,
6704
+ seq: normalized.seq,
6705
+ parentScope: normalized.parentScope
6706
+ };
6707
+ }
6708
+ return null;
6709
+ }
6710
+
6711
+ function rememberIgnored(record, result, patch) {
6712
+ record.ignored += 1;
6713
+ record.lastStatus = result.status;
6714
+ remember(result);
6715
+ onIgnore?.(result, patch);
6716
+ }
6717
+
6481
6718
  function remember(result) {
6482
6719
  if (recentLimit === 0) {
6483
6720
  return;
@@ -6489,6 +6726,132 @@ const __boundaryReceiverModule = (() => {
6489
6726
  }
6490
6727
  }
6491
6728
 
6729
+ function applyScript(script, options = {}) {
6730
+ if (!script || typeof script !== "object" || typeof script.textContent !== "string") {
6731
+ throw new TypeError("AsyncStream.applyScript(script) requires a JSON script element.");
6732
+ }
6733
+ const attributes = normalizeAttributeConfig(options.attributes ?? options.receiver?.attributes);
6734
+ const patch = parseStreamPatch(script.textContent);
6735
+ const root = options.root ?? script.ownerDocument ?? globalThis.document;
6736
+ const resolved = resolveStreamPatch(patch, { root, attributes });
6737
+ const receiver = resolveReceiver(options);
6738
+ return receiver.apply(resolved);
6739
+ }
6740
+
6741
+ function applyCurrentScript(scriptOrOptions, maybeOptions) {
6742
+ const script = isElementLike(scriptOrOptions)
6743
+ ? scriptOrOptions
6744
+ : globalThis.document?.currentScript;
6745
+ const options = isElementLike(scriptOrOptions) ? maybeOptions ?? {} : scriptOrOptions ?? {};
6746
+ return applyScript(script, options);
6747
+ }
6748
+
6749
+ function resolveReceiver(options = {}) {
6750
+ if (options.receiver && typeof options.receiver.apply === "function") {
6751
+ return options.receiver;
6752
+ }
6753
+ const runtime = options.runtime ?? globalThis.Async?.runtime;
6754
+ const loader = options.loader ?? runtime?.loader;
6755
+ if (!loader) {
6756
+ throw new TypeError("AsyncStream requires receiver, loader, or runtime.loader.");
6757
+ }
6758
+ return createBoundaryReceiver({
6759
+ loader,
6760
+ signals: options.signals ?? runtime?.signals,
6761
+ cache: options.cache ?? runtime?.browser?.cache,
6762
+ scheduler: options.scheduler ?? runtime?.scheduler,
6763
+ router: options.router ?? runtime?.router,
6764
+ attributes: options.attributes ?? runtime?.attributes ?? loader.attributes
6765
+ });
6766
+ }
6767
+
6768
+ function parseStreamPatch(source) {
6769
+ try {
6770
+ return JSON.parse(source);
6771
+ } catch (error) {
6772
+ throw new TypeError(`Async stream patch JSON is invalid: ${error.message}`);
6773
+ }
6774
+ }
6775
+
6776
+ function resolveStreamPatch(patch, { root, attributes }) {
6777
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
6778
+ throw new TypeError("Async stream patch JSON must be an object.");
6779
+ }
6780
+ const resolved = { ...patch };
6781
+ if (patch.replace !== undefined) {
6782
+ resolved.replace = resolveStreamReplacements(patch.replace, root, attributes);
6783
+ }
6784
+ const synthesizedReveal = synthesizeRevealMetadata(resolved, root, attributes);
6785
+ if (patch.reveal !== undefined && synthesizedReveal && !sameRevealMetadata(patch.reveal, synthesizedReveal)) {
6786
+ throw new TypeError("Explicit stream reveal metadata conflicts with DOM reveal metadata.");
6787
+ }
6788
+ if (patch.reveal === undefined && synthesizedReveal) {
6789
+ resolved.reveal = synthesizedReveal;
6790
+ }
6791
+ return resolved;
6792
+ }
6793
+
6794
+ function resolveStreamReplacements(value, root, attributes) {
6795
+ const replacements = Array.isArray(value) ? value : [value];
6796
+ return replacements.map((replacement) => {
6797
+ if (!isPlainObject(replacement)) {
6798
+ throw new TypeError("Stream replacement records must be objects.");
6799
+ }
6800
+ if (replacement.template === undefined || Object.hasOwn(replacement, "html")) {
6801
+ return replacement;
6802
+ }
6803
+ const template = findStreamTemplate(root, replacement.template, attributes);
6804
+ if (!template) {
6805
+ throw new Error(`Stream template "${replacement.template}" was not found.`);
6806
+ }
6807
+ return {
6808
+ ...replacement,
6809
+ html: template.innerHTML
6810
+ };
6811
+ });
6812
+ }
6813
+
6814
+ function findStreamTemplate(root, id, attributes) {
6815
+ if (typeof id !== "string" || id.length === 0) {
6816
+ throw new TypeError("Stream replacement template must be a non-empty string.");
6817
+ }
6818
+ return elementsIn(root)
6819
+ .find((element) => element.tagName === "TEMPLATE" && readAttribute(element, attributes, "async", "stream-template") === id)
6820
+ ?? null;
6821
+ }
6822
+
6823
+ function synthesizeRevealMetadata(patch, root, attributes) {
6824
+ if (typeof patch.boundary !== "string" || patch.boundary.length === 0) {
6825
+ return null;
6826
+ }
6827
+ const boundary = findBoundaryElement(root, patch.boundary, attributes, { required: false });
6828
+ const container = boundary?.parentElement;
6829
+ const group = container ? readAttribute(container, attributes, "async", "reveal") : null;
6830
+ if (!group) {
6831
+ return null;
6832
+ }
6833
+ const children = directChildBoundaryElements(container, attributes);
6834
+ const index = children.indexOf(boundary);
6835
+ if (index === -1) {
6836
+ return null;
6837
+ }
6838
+ return {
6839
+ group,
6840
+ index,
6841
+ count: children.length,
6842
+ order: readAttribute(container, attributes, "async", "reveal-order") || "as-ready",
6843
+ tail: readAttribute(container, attributes, "async", "reveal-tail") || undefined
6844
+ };
6845
+ }
6846
+
6847
+ function sameRevealMetadata(left, right) {
6848
+ return left?.group === right.group &&
6849
+ left?.index === right.index &&
6850
+ left?.count === right.count &&
6851
+ (left?.order ?? "as-ready") === right.order &&
6852
+ left?.tail === right.tail;
6853
+ }
6854
+
6492
6855
  function validatePatch(patch) {
6493
6856
  if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
6494
6857
  throw new TypeError("receiver.apply(patch) requires a boundary patch object.");
@@ -6518,16 +6881,127 @@ const __boundaryReceiverModule = (() => {
6518
6881
  throw new TypeError("Boundary patch scope must be a string.");
6519
6882
  }
6520
6883
 
6884
+ const normalized = { ...patch };
6885
+ if (patch.attrs !== undefined) {
6886
+ normalized.attrs = normalizeAttributePatches(patch.attrs);
6887
+ }
6888
+ if (patch.replace !== undefined) {
6889
+ normalized.replace = normalizeReplacements(patch.replace);
6890
+ }
6891
+ if (patch.reveal !== undefined) {
6892
+ normalized.reveal = normalizeRevealMetadata(patch.reveal);
6893
+ }
6894
+
6521
6895
  const hasHtml = Object.hasOwn(patch, "html") && patch.html != null;
6522
6896
  const hasSignals = patch.signals && Object.keys(patch.signals).length > 0;
6523
6897
  const hasBrowserCache = patch.cache?.browser && Object.keys(patch.cache.browser).length > 0;
6524
6898
  const hasRedirect = Boolean(patch.redirect);
6525
6899
  const hasError = Object.hasOwn(patch, "error");
6526
- if (!hasHtml && !hasSignals && !hasBrowserCache && !hasRedirect && !hasError) {
6527
- throw new TypeError("Boundary patch must include html, signals, cache.browser, redirect, or error.");
6900
+ const hasAttrs = normalized.attrs?.items.length > 0;
6901
+ const hasReplace = normalized.replace?.length > 0;
6902
+ if (!hasHtml && !hasSignals && !hasBrowserCache && !hasRedirect && !hasError && !hasAttrs && !hasReplace) {
6903
+ throw new TypeError("Boundary patch must include html, replace, attrs, signals, cache.browser, redirect, or error.");
6528
6904
  }
6529
6905
 
6530
- return patch;
6906
+ return normalized;
6907
+ }
6908
+
6909
+ function normalizeAttributePatches(attrs) {
6910
+ if (!Array.isArray(attrs)) {
6911
+ throw new TypeError("Boundary patch attrs must be an array.");
6912
+ }
6913
+ if (attrs.length === 0) {
6914
+ return { kind: "built", items: [] };
6915
+ }
6916
+ const named = Array.isArray(attrs[0]);
6917
+ if (named) {
6918
+ return {
6919
+ kind: "named",
6920
+ items: attrs.map((tuple) => normalizeNamedAttributePatch(tuple))
6921
+ };
6922
+ }
6923
+ if (attrs.some(Array.isArray)) {
6924
+ throw new TypeError("Boundary patch attrs cannot mix built triples and no-build tuples.");
6925
+ }
6926
+ if (attrs.length % 3 !== 0) {
6927
+ throw new TypeError("Built attribute patch triples must have a length divisible by 3.");
6928
+ }
6929
+ const items = [];
6930
+ for (let index = 0; index < attrs.length; index += 3) {
6931
+ const target = attrs[index];
6932
+ const name = attrs[index + 1];
6933
+ const value = attrs[index + 2];
6934
+ assertBuiltTarget(target);
6935
+ assertAttributeName(name);
6936
+ assertAttributeValue(value);
6937
+ items.push({ target, name, value });
6938
+ }
6939
+ return { kind: "built", items };
6940
+ }
6941
+
6942
+ function normalizeNamedAttributePatch(tuple) {
6943
+ if (!Array.isArray(tuple) || tuple.length !== 3) {
6944
+ throw new TypeError("No-build attribute patches must be [targetName, attrName, value] tuples.");
6945
+ }
6946
+ const [target, name, value] = tuple;
6947
+ if (typeof target !== "string" || target.length === 0) {
6948
+ throw new TypeError("No-build attribute patch target names must be non-empty strings.");
6949
+ }
6950
+ assertAttributeName(name);
6951
+ assertAttributeValue(value);
6952
+ return { target, name, value };
6953
+ }
6954
+
6955
+ function normalizeReplacements(value) {
6956
+ const replacements = Array.isArray(value) ? value : [value];
6957
+ return replacements.map((replacement) => {
6958
+ if (!isPlainObject(replacement)) {
6959
+ throw new TypeError("Boundary patch replace records must be objects.");
6960
+ }
6961
+ if (typeof replacement.target !== "string" || replacement.target.length === 0) {
6962
+ throw new TypeError("Boundary patch replace target must be a non-empty string.");
6963
+ }
6964
+ if (replacement.mode !== undefined && replacement.mode !== "pending" && replacement.mode !== "boundary") {
6965
+ throw new TypeError("Boundary patch replace mode must be \"pending\" or \"boundary\".");
6966
+ }
6967
+ if (!Object.hasOwn(replacement, "html") || replacement.html == null) {
6968
+ throw new TypeError("Boundary patch replace records must include html.");
6969
+ }
6970
+ return {
6971
+ target: replacement.target,
6972
+ html: replacement.html,
6973
+ mode: replacement.mode ?? "pending"
6974
+ };
6975
+ });
6976
+ }
6977
+
6978
+ function normalizeRevealMetadata(reveal) {
6979
+ if (!isPlainObject(reveal)) {
6980
+ throw new TypeError("Boundary patch reveal metadata must be an object.");
6981
+ }
6982
+ const order = reveal.order ?? "as-ready";
6983
+ if (typeof reveal.group !== "string" || reveal.group.length === 0) {
6984
+ throw new TypeError("Reveal group must be a non-empty string.");
6985
+ }
6986
+ if (!Number.isInteger(reveal.count) || reveal.count < 1) {
6987
+ throw new TypeError("Reveal count must be a positive integer.");
6988
+ }
6989
+ if (!Number.isInteger(reveal.index) || reveal.index < 0 || reveal.index >= reveal.count) {
6990
+ throw new TypeError("Reveal index must be an integer from 0 to count - 1.");
6991
+ }
6992
+ if (!revealOrders.has(order)) {
6993
+ throw new TypeError("Reveal order must be as-ready, forwards, backwards, or together.");
6994
+ }
6995
+ if (reveal.tail !== undefined && !revealTails.has(reveal.tail)) {
6996
+ throw new TypeError("Reveal tail must be collapsed or hidden.");
6997
+ }
6998
+ return {
6999
+ group: reveal.group,
7000
+ index: reveal.index,
7001
+ count: reveal.count,
7002
+ order,
7003
+ tail: reveal.tail
7004
+ };
6531
7005
  }
6532
7006
 
6533
7007
  function assertBoundary(boundary) {
@@ -6536,6 +7010,41 @@ const __boundaryReceiverModule = (() => {
6536
7010
  }
6537
7011
  }
6538
7012
 
7013
+ function assertBuiltTarget(target) {
7014
+ if (!Number.isInteger(target) || target < 0) {
7015
+ throw new TypeError("Built attribute patch target indexes must be non-negative integers.");
7016
+ }
7017
+ }
7018
+
7019
+ function assertAttributeName(name) {
7020
+ if (typeof name !== "string" || name.length === 0) {
7021
+ throw new TypeError("Attribute patch names must be non-empty strings.");
7022
+ }
7023
+ const normalized = name.toLowerCase();
7024
+ if (
7025
+ normalized.startsWith("on") ||
7026
+ structuralAttributeNames.has(normalized) ||
7027
+ /[\s<>"'=]/.test(name)
7028
+ ) {
7029
+ throw new TypeError(`Attribute patch name "${name}" is not allowed.`);
7030
+ }
7031
+ }
7032
+
7033
+ function assertAttributeValue(value) {
7034
+ const type = typeof value;
7035
+ if (value != null && type !== "string" && type !== "number" && type !== "boolean") {
7036
+ throw new TypeError("Attribute patch values must be strings, numbers, booleans, null, or undefined.");
7037
+ }
7038
+ }
7039
+
7040
+ function setPatchedAttribute(element, name, value) {
7041
+ if (value === false || value == null) {
7042
+ element.removeAttribute(name);
7043
+ return;
7044
+ }
7045
+ element.setAttribute(name, value === true ? "" : String(value));
7046
+ }
7047
+
6539
7048
  async function flushScheduler(scheduler, scope) {
6540
7049
  if (!scheduler) {
6541
7050
  return;
@@ -6558,6 +7067,90 @@ const __boundaryReceiverModule = (() => {
6558
7067
  location?.assign?.(redirect);
6559
7068
  }
6560
7069
 
7070
+ function takeReadyRevealItems(group) {
7071
+ if (group.order === "as-ready") {
7072
+ return takePendingIndexes(group, [...group.pending.keys()].sort((left, right) => left - right));
7073
+ }
7074
+ if (group.order === "forwards") {
7075
+ const indexes = [];
7076
+ while (group.pending.has(group.nextForward)) {
7077
+ indexes.push(group.nextForward);
7078
+ group.nextForward += 1;
7079
+ }
7080
+ return takePendingIndexes(group, indexes);
7081
+ }
7082
+ if (group.order === "backwards") {
7083
+ const indexes = [];
7084
+ while (group.pending.has(group.nextBackward)) {
7085
+ indexes.push(group.nextBackward);
7086
+ group.nextBackward -= 1;
7087
+ }
7088
+ return takePendingIndexes(group, indexes);
7089
+ }
7090
+ if (group.committed.size + group.pending.size < group.count) {
7091
+ return [];
7092
+ }
7093
+ const indexes = [];
7094
+ for (let index = 0; index < group.count; index += 1) {
7095
+ if (group.pending.has(index)) {
7096
+ indexes.push(index);
7097
+ }
7098
+ }
7099
+ return takePendingIndexes(group, indexes);
7100
+ }
7101
+
7102
+ function takePendingIndexes(group, indexes) {
7103
+ const items = [];
7104
+ for (const index of indexes) {
7105
+ const item = group.pending.get(index);
7106
+ if (item) {
7107
+ group.pending.delete(index);
7108
+ items.push(item);
7109
+ }
7110
+ }
7111
+ return items;
7112
+ }
7113
+
7114
+ function pendingOrderFor(group, pending) {
7115
+ return group.order === "backwards"
7116
+ ? pending.slice().sort((left, right) => right - left)
7117
+ : pending.slice().sort((left, right) => left - right);
7118
+ }
7119
+
7120
+ function inspectRevealGroups(groups) {
7121
+ const inspected = {};
7122
+ for (const [id, group] of groups) {
7123
+ inspected[id] = {
7124
+ count: group.count,
7125
+ order: group.order,
7126
+ tail: group.tail,
7127
+ pending: [...group.pending.keys()].sort((left, right) => left - right),
7128
+ committed: [...group.committed].sort((left, right) => left - right)
7129
+ };
7130
+ }
7131
+ return inspected;
7132
+ }
7133
+
7134
+ function revealResultMetadata(reveal) {
7135
+ return {
7136
+ group: reveal.group,
7137
+ index: reveal.index,
7138
+ count: reveal.count,
7139
+ order: reveal.order,
7140
+ tail: reveal.tail
7141
+ };
7142
+ }
7143
+
7144
+ function withPatchMetadata(result, attrs, replacementCount) {
7145
+ if (attrs) {
7146
+ result.attrs = attrs;
7147
+ }
7148
+ if (replacementCount > 0) {
7149
+ result.replace = { applied: replacementCount };
7150
+ }
7151
+ return result;
7152
+ }
7153
+
6561
7154
  function toStableError(value) {
6562
7155
  if (value instanceof Error) {
6563
7156
  return value;
@@ -6583,13 +7176,118 @@ const __boundaryReceiverModule = (() => {
6583
7176
  if (result.status === "redirected") {
6584
7177
  entry.redirect = result.redirect;
6585
7178
  }
7179
+ if (result.status === "buffered") {
7180
+ entry.reveal = result.reveal;
7181
+ }
7182
+ if (result.attrs) {
7183
+ entry.attrs = { ...result.attrs };
7184
+ }
7185
+ if (result.replace) {
7186
+ entry.replace = { ...result.replace };
7187
+ }
6586
7188
  return entry;
6587
7189
  }
6588
7190
 
7191
+ function findBoundaryElement(root, boundaryId, attributes, options = {}) {
7192
+ const boundary = elementsIn(root)
7193
+ .find((element) => boundaryIdFor(element, attributes) === String(boundaryId));
7194
+ if (!boundary && options.required !== false) {
7195
+ throw new Error(`Boundary "${boundaryId}" was not found.`);
7196
+ }
7197
+ return boundary ?? null;
7198
+ }
7199
+
7200
+ function boundaryIdFor(element, attributes) {
7201
+ if (element?.tagName === "ASYNC-SUSPENSE" && element.hasAttribute?.("for")) {
7202
+ return element.getAttribute("for");
7203
+ }
7204
+ return readAttribute(element, attributes, "async", "boundary");
7205
+ }
7206
+
7207
+ function directChildBoundaryElements(container, attributes) {
7208
+ return [...(container?.children ?? [])]
7209
+ .filter((element) => boundaryIdFor(element, attributes) != null);
7210
+ }
7211
+
7212
+ function findRevealContainer(root, group, attributes) {
7213
+ return elementsIn(root)
7214
+ .find((element) => readAttribute(element, attributes, "async", "reveal") === group)
7215
+ ?? null;
7216
+ }
7217
+
7218
+ function isNestedBoundaryElement(element, boundaryElement, attributes) {
7219
+ if (element === boundaryElement) {
7220
+ return false;
7221
+ }
7222
+ if (boundaryIdFor(element, attributes) != null) {
7223
+ return true;
7224
+ }
7225
+ let parent = element.parentElement;
7226
+ while (parent && parent !== boundaryElement) {
7227
+ if (boundaryIdFor(parent, attributes) != null) {
7228
+ return true;
7229
+ }
7230
+ parent = parent.parentElement;
7231
+ }
7232
+ return false;
7233
+ }
7234
+
7235
+ function setTailHidden(element, hidden) {
7236
+ if (hidden) {
7237
+ element.setAttribute("hidden", "");
7238
+ if ("hidden" in element) {
7239
+ element.hidden = true;
7240
+ }
7241
+ return;
7242
+ }
7243
+ element.removeAttribute("hidden");
7244
+ if ("hidden" in element) {
7245
+ element.hidden = false;
7246
+ }
7247
+ }
7248
+
7249
+ function containsOrEquals(parent, child) {
7250
+ return parent === child || parent.contains?.(child);
7251
+ }
7252
+
7253
+ function ownerDocumentOf(element) {
7254
+ return element.ownerDocument ?? globalThis.document;
7255
+ }
7256
+
7257
+ function toFragment(value, documentRef) {
7258
+ if (value?.nodeType === 11) {
7259
+ return value.cloneNode(true);
7260
+ }
7261
+ if (value?.tagName === "TEMPLATE") {
7262
+ return value.content.cloneNode(true);
7263
+ }
7264
+ if (value?.nodeType) {
7265
+ const fragment = documentRef.createDocumentFragment();
7266
+ fragment.append(value.cloneNode(true));
7267
+ return fragment;
7268
+ }
7269
+ const template = documentRef.createElement("template");
7270
+ template.innerHTML = typeof value === "string" ? value : renderTemplate(value);
7271
+ return template.content.cloneNode(true);
7272
+ }
7273
+
7274
+ function elementsIn(scope) {
7275
+ const elements = [];
7276
+ if (scope?.nodeType === 1) {
7277
+ elements.push(scope);
7278
+ }
7279
+ elements.push(...(scope?.querySelectorAll?.("*") ?? []));
7280
+ return elements;
7281
+ }
7282
+
7283
+ function isElementLike(value) {
7284
+ return Boolean(value?.nodeType === 1 && typeof value.textContent === "string");
7285
+ }
7286
+
6589
7287
  function isPlainObject(value) {
6590
7288
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
6591
7289
  }
6592
- return { createBoundaryReceiver };
7290
+ return { createBoundaryReceiver, AsyncStream };
6593
7291
  })();
6594
7292
 
6595
7293
  const __delayModule = (() => {
@@ -6699,6 +7397,7 @@ const { defineApp: defineApp } = __serverEntryModule;
6699
7397
  const { readSnapshot: readSnapshot } = __serverEntryModule;
6700
7398
  const { attributeName: attributeName } = __attributesModule;
6701
7399
  const { defineAttributeConfig: defineAttributeConfig } = __attributesModule;
7400
+ const { AsyncStream: AsyncStream } = __boundaryReceiverModule;
6702
7401
  const { createBoundaryReceiver: createBoundaryReceiver } = __boundaryReceiverModule;
6703
7402
  const { createCacheRegistry: createCacheRegistry } = __cacheModule;
6704
7403
  const { defineCache: defineCache } = __cacheModule;
@@ -6733,4 +7432,4 @@ const { createSignalRegistry: createSignalRegistry } = __signalsModule;
6733
7432
  const { effect: effect } = __signalsModule;
6734
7433
  const { signal: signal } = __signalsModule;
6735
7434
 
6736
- export { asyncSignal, Async, createApp, defineApp, readSnapshot, attributeName, defineAttributeConfig, createBoundaryReceiver, createCacheRegistry, defineCache, component, createComponentRegistry, defineComponent, delay, defineAsyncContainerElement, defineAsyncSuspenseElement, createHandlerRegistry, html, createLazyRegistry, defineRegistrySnapshot, Loader, AsyncLoader, createPartialRegistry, createRegistryStore, createRouteRegistry, createRouter, defineRoute, route, createScheduler, createRequestContextStore, applyServerResult, createServerProxy, resolveServerCommandArguments, unwrapServerResult, createServerRegistry, computed, createSignal, createSignalRegistry, effect, signal };
7435
+ export { asyncSignal, Async, createApp, defineApp, readSnapshot, attributeName, defineAttributeConfig, AsyncStream, createBoundaryReceiver, createCacheRegistry, defineCache, component, createComponentRegistry, defineComponent, delay, defineAsyncContainerElement, defineAsyncSuspenseElement, createHandlerRegistry, html, createLazyRegistry, defineRegistrySnapshot, Loader, AsyncLoader, createPartialRegistry, createRegistryStore, createRouteRegistry, createRouter, defineRoute, route, createScheduler, createRequestContextStore, applyServerResult, createServerProxy, resolveServerCommandArguments, unwrapServerResult, createServerRegistry, computed, createSignal, createSignalRegistry, effect, signal };