@superdoc/mcp 1.6.0-next.7 → 1.6.0-next.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1789 -1278
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -31443,7 +31443,7 @@ var init_host = __esm(() => {
31443
31443
  });
31444
31444
 
31445
31445
  // ../../packages/sdk/langs/node/src/runtime/sdk-version.generated.ts
31446
- var SDK_VERSION = "2.19.0-next.7";
31446
+ var SDK_VERSION = "2.19.0-next.9";
31447
31447
 
31448
31448
  // ../../packages/sdk/langs/node/src/runtime/embedded-platform.ts
31449
31449
  import { accessSync, chmodSync, constants, existsSync, statSync } from "node:fs";
@@ -129520,709 +129520,6 @@ var init_content_control_rewrite = __esm(() => {
129520
129520
  TD4 = new TextDecoder;
129521
129521
  });
129522
129522
 
129523
- // ../../../v2/editor-core/dist/document/transactions/header-footer-update.js
129524
- function prepareHeaderFooterUpdate(state, source, perPart, historyDirection) {
129525
- if (source.operationId !== "watermarks-apply" || source.family !== "storyImage" || source.changeMode === "tracked" || !state.mainStoryId)
129526
- return null;
129527
- const headerUris = Object.keys(perPart).filter((uri) => /^\/word\/header\d+\.xml$/.test(uri));
129528
- if (headerUris.length === 0 || Object.keys(perPart).some((uri) => uri !== DOCUMENT && uri !== "[Content_Types].xml" && uri !== "/[Content_Types].xml" && uri !== "/word/_rels/document.xml.rels" && !headerUris.includes(uri) && !/^\/word\/_rels\/header\d+\.xml\.rels$/.test(uri) && !uri.startsWith("/word/media/")))
129529
- return null;
129530
- const headers = [];
129531
- for (const partUri of headerUris) {
129532
- const current = state.packageBytes.get(partUri);
129533
- const next = applyEntry(current, perPart[partUri]);
129534
- if (next === undefined)
129535
- return null;
129536
- const before = current ? readHeader(current) : null;
129537
- const after = next ? readHeader(next) : null;
129538
- if (current && !before || next && !after)
129539
- return null;
129540
- if (before && after) {
129541
- if (before.shell !== after.shell)
129542
- return null;
129543
- const requiredBindings = historyDirection === "undo" ? after.namespaces : before.namespaces;
129544
- const retainedBindings = historyDirection === "undo" ? before.namespaces : after.namespaces;
129545
- if (Object.entries(requiredBindings).some(([prefix, uri]) => retainedBindings[prefix] !== uri))
129546
- return null;
129547
- }
129548
- const oldBlocks = new Map(before?.paragraphs.map((p) => [p.id, p.xml]) ?? []);
129549
- const newBlocks = new Map(after?.paragraphs.map((p) => [p.id, p.xml]) ?? []);
129550
- const oldOrder = [...oldBlocks.keys()].filter((id) => newBlocks.has(id));
129551
- const newOrder = [...newBlocks.keys()].filter((id) => oldBlocks.has(id));
129552
- if (oldOrder.some((id, index) => newOrder[index] !== id))
129553
- return null;
129554
- headers.push({
129555
- partUri,
129556
- storyId: `header:${partUri}`,
129557
- created: !current && next != null,
129558
- removed: next == null,
129559
- addedBlockIds: [...newBlocks.keys()].filter((id) => !oldBlocks.has(id)),
129560
- removedBlockIds: [...oldBlocks.keys()].filter((id) => !newBlocks.has(id)),
129561
- changedBlockIds: [...newBlocks.keys()].filter((id) => oldBlocks.get(id) !== newBlocks.get(id))
129562
- });
129563
- }
129564
- let sectionBlockIds = [];
129565
- let finalSectionChanged = false;
129566
- if (perPart[DOCUMENT]) {
129567
- const current = state.packageBytes.get(DOCUMENT);
129568
- const next = applyEntry(current, perPart[DOCUMENT]);
129569
- if (!current || !next)
129570
- return null;
129571
- const before = readSections(TD5.decode(current));
129572
- const after = readSections(TD5.decode(next));
129573
- if (!before || !after || before.shell !== after.shell || before.sections.length !== after.sections.length)
129574
- return null;
129575
- for (let index = 0;index < before.sections.length; index++) {
129576
- const previous = before.sections[index];
129577
- const following = after.sections[index];
129578
- if (previous.blockId !== following.blockId)
129579
- return null;
129580
- if (previous.xml === following.xml)
129581
- continue;
129582
- if (previous.blockId == null)
129583
- finalSectionChanged = true;
129584
- else
129585
- sectionBlockIds.push(previous.blockId);
129586
- }
129587
- sectionBlockIds = [...new Set(sectionBlockIds)];
129588
- }
129589
- return { mainStoryId: state.mainStoryId, headers, sectionBlockIds, finalSectionChanged };
129590
- }
129591
- function applyEntry(current, entry) {
129592
- if (entry.kind === "remove")
129593
- return current ? null : undefined;
129594
- if (entry.kind === "create")
129595
- return current ? undefined : entry.bytes;
129596
- if (!current)
129597
- return;
129598
- const normalized = normalizePartPatches([...entry.patches]);
129599
- if (!normalized.ok)
129600
- return;
129601
- const applied = applyNormalizedPatches({ bytes: current, patches: normalized.value });
129602
- return applied.ok ? applied.value : undefined;
129603
- }
129604
- function paragraphId(range) {
129605
- return range.tag.attributes.find((attr) => attr.namespaceUri === W142 && attr.localName === "paraId")?.value ?? null;
129606
- }
129607
- function readHeader(bytes) {
129608
- const xml = TD5.decode(bytes);
129609
- const parsed = collectXmlElementRanges(xml);
129610
- if (parsed.errors.length)
129611
- return null;
129612
- const roots = parsed.ranges.filter((range) => range.tag.namespaceUri === W2 && range.tag.localName === "hdr");
129613
- const root = roots[0];
129614
- if (roots.length !== 1 || !root || parsed.ranges.some((range) => range.start < root.start || range.end > root.end))
129615
- return null;
129616
- const all = parsed.ranges.filter((range) => range.tag.namespaceUri === W2 && range.tag.localName === "p").sort((a, b) => a.start - b.start);
129617
- const topLevel = [];
129618
- for (const range of all)
129619
- if (range.start >= (topLevel.at(-1)?.end ?? -1))
129620
- topLevel.push(range);
129621
- const paragraphs = [];
129622
- const rootOpening = xml.slice(root.start, root.openEnd).replace(/\s+xmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g, "");
129623
- let shell = xml.slice(0, root.start) + rootOpening;
129624
- let cursor = root.openEnd;
129625
- for (const range of topLevel) {
129626
- const id = paragraphId(range);
129627
- if (!id || paragraphs.some((p) => p.id === id))
129628
- return null;
129629
- paragraphs.push({ id, xml: xml.slice(range.start, range.end) });
129630
- shell += xml.slice(cursor, range.start);
129631
- cursor = range.end;
129632
- }
129633
- shell += xml.slice(cursor);
129634
- return { paragraphs, shell, namespaces: root.namespaceBindings };
129635
- }
129636
- function readSections(xml) {
129637
- const parsed = collectXmlElementRanges(xml);
129638
- if (parsed.errors.length)
129639
- return null;
129640
- const ranges = parsed.ranges.filter((range) => range.tag.namespaceUri === W2 && range.tag.localName === "sectPr").sort((a, b) => a.start - b.start);
129641
- const sections = [];
129642
- let shell = "";
129643
- let cursor = 0;
129644
- for (const range of ranges) {
129645
- if (range.start < cursor)
129646
- return null;
129647
- const parent = parsed.ranges.filter((candidate) => candidate.start < range.start && candidate.end > range.end).sort((a, b) => b.start - a.start)[0];
129648
- if (!parent || parent.tag.namespaceUri !== W2 || !["body", "pPr"].includes(parent.tag.localName))
129649
- return null;
129650
- const paragraph = parent.tag.localName === "pPr" ? parsed.ranges.find((candidate) => candidate.tag.namespaceUri === W2 && candidate.tag.localName === "p" && candidate.start < parent.start && candidate.end > parent.end) : null;
129651
- const blockId = paragraph ? paragraphId(paragraph) : null;
129652
- if (parent.tag.localName === "pPr" && !blockId)
129653
- return null;
129654
- sections.push({ blockId, xml: xml.slice(range.start, range.end) });
129655
- const refs = parsed.ranges.filter((candidate) => candidate.start > range.start && candidate.end <= range.closeStart && candidate.tag.namespaceUri === W2 && candidate.tag.localName === "headerReference");
129656
- let inner = "";
129657
- let innerCursor = range.openEnd;
129658
- for (const ref3 of refs.sort((a, b) => a.start - b.start)) {
129659
- const enclosing = parsed.ranges.some((candidate) => candidate.start > range.start && candidate.start < ref3.start && candidate.end > ref3.end);
129660
- if (enclosing)
129661
- return null;
129662
- inner += xml.slice(innerCursor, ref3.start);
129663
- innerCursor = ref3.end;
129664
- }
129665
- inner += xml.slice(innerCursor, range.closeStart);
129666
- const opening = xml.slice(range.start, range.openEnd).replace(/\s*\/>$/, ">");
129667
- shell += xml.slice(cursor, range.start) + opening + inner + `</${range.tag.name}>`;
129668
- cursor = range.end;
129669
- }
129670
- shell += xml.slice(cursor);
129671
- return { sections, shell };
129672
- }
129673
- var TD5, W2 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", W142 = "http://schemas.microsoft.com/office/word/2010/wordml", DOCUMENT = "/word/document.xml";
129674
- var init_header_footer_update = __esm(() => {
129675
- init_xml_sax();
129676
- init_patch_substrate();
129677
- TD5 = new TextDecoder;
129678
- });
129679
-
129680
- // ../../../v2/editor-core/dist/scan/wml-paragraph-spans.js
129681
- function scanWmlParagraphSpans(xml, options = {}) {
129682
- const collector = createParagraphSpanCollector(options);
129683
- const result = walkXmlElements(xml, collector.walkOptions);
129684
- return collector.finish(result.errors);
129685
- }
129686
- async function scanWmlParagraphSpansCooperatively(xml, yieldPoint, options = {}) {
129687
- const collector = createParagraphSpanCollector(options);
129688
- const result = await walkXmlElementsCooperatively(xml, {
129689
- ...collector.walkOptions,
129690
- yieldPoint
129691
- });
129692
- return collector.finish(result.errors);
129693
- }
129694
- function createParagraphSpanCollector(options) {
129695
- const paragraphs = [];
129696
- const bookmarkStarts = [];
129697
- const bookmarkEnds = [];
129698
- const openParagraphs = [];
129699
- let storyRoot = null;
129700
- const walkOptions = {
129701
- fragment: options.fragment,
129702
- additionalNamespaces: options.additionalNamespaces,
129703
- onOpenTag(event) {
129704
- if (!storyRoot && event.tag.namespaceUri === NS_W && STORY_ROOT_LOCAL_NAMES.has(event.tag.localName)) {
129705
- storyRoot = rootFromEvent(event);
129706
- }
129707
- if (isWmlParagraph(event)) {
129708
- const paraIdAttributes = readXmlAttributes(event.tag, NS_W14, "paraId");
129709
- const span = {
129710
- openStart: event.start,
129711
- openEnd: event.end,
129712
- closeStart: event.end,
129713
- closeEnd: event.end,
129714
- selfClosing: event.tag.isSelfClosing,
129715
- paraId: paraIdAttributes.length === 1 && paraIdAttributes[0].value ? paraIdAttributes[0].value : null,
129716
- paraIdAttributes,
129717
- namespaceBindings: event.namespaceBindings
129718
- };
129719
- paragraphs.push(span);
129720
- if (!event.tag.isSelfClosing)
129721
- openParagraphs.push(paragraphs.length - 1);
129722
- return;
129723
- }
129724
- if (openParagraphs.length > 0 && event.tag.namespaceUri === NS_W && (event.tag.localName === "bookmarkStart" || event.tag.localName === "bookmarkEnd")) {
129725
- const markers = event.tag.localName === "bookmarkStart" ? bookmarkStarts : bookmarkEnds;
129726
- markers.push({
129727
- paragraphNamespaceBindings: paragraphs[openParagraphs.at(-1)].namespaceBindings,
129728
- openStart: event.start,
129729
- openEnd: event.end,
129730
- namespaceBindings: event.namespaceBindings
129731
- });
129732
- }
129733
- },
129734
- onCloseTag(event) {
129735
- if (event.tag.isSelfClosing || !isWmlParagraph(event))
129736
- return;
129737
- const index = openParagraphs.pop();
129738
- if (index == null)
129739
- return;
129740
- const span = paragraphs[index];
129741
- span.closeStart = event.start;
129742
- span.closeEnd = event.end;
129743
- }
129744
- };
129745
- return {
129746
- walkOptions,
129747
- finish(errors4) {
129748
- return {
129749
- paragraphs,
129750
- bookmarkStarts,
129751
- bookmarkEnds,
129752
- storyRoot,
129753
- errors: errors4,
129754
- ok: errors4.length === 0 && openParagraphs.length === 0
129755
- };
129756
- }
129757
- };
129758
- }
129759
- function findContainingWmlParagraph(paragraphs, offset) {
129760
- let low = 0;
129761
- let high = paragraphs.length;
129762
- while (low < high) {
129763
- const mid = low + high >>> 1;
129764
- if (paragraphs[mid].openStart <= offset)
129765
- low = mid + 1;
129766
- else
129767
- high = mid;
129768
- }
129769
- for (let index = low - 1;index >= 0; index -= 1) {
129770
- const paragraph = paragraphs[index];
129771
- if (paragraph.openStart > offset)
129772
- continue;
129773
- if (paragraph.openEnd <= offset && offset < paragraph.closeEnd)
129774
- return paragraph;
129775
- }
129776
- return null;
129777
- }
129778
- function findFirstWmlParagraphInRange(paragraphs, start, end) {
129779
- const low = lowerBoundParagraphStart(paragraphs, start);
129780
- const paragraph = paragraphs[low];
129781
- return paragraph && paragraph.openStart < end && paragraph.closeEnd <= end ? paragraph : null;
129782
- }
129783
- function findWmlParagraphsInRange(paragraphs, start, end) {
129784
- const out = [];
129785
- for (let index = lowerBoundParagraphStart(paragraphs, start);index < paragraphs.length; index += 1) {
129786
- const paragraph = paragraphs[index];
129787
- if (paragraph.openStart >= end)
129788
- break;
129789
- if (paragraph.closeEnd <= end)
129790
- out.push(paragraph);
129791
- }
129792
- return out;
129793
- }
129794
- function isWmlParagraph(event) {
129795
- return event.tag.namespaceUri === NS_W && event.tag.localName === "p";
129796
- }
129797
- function rootFromEvent(event) {
129798
- return {
129799
- start: event.start,
129800
- end: event.end,
129801
- namespaceBindings: event.namespaceBindings
129802
- };
129803
- }
129804
- function lowerBoundParagraphStart(paragraphs, start) {
129805
- let low = 0;
129806
- let high = paragraphs.length;
129807
- while (low < high) {
129808
- const mid = low + high >>> 1;
129809
- if (paragraphs[mid].openStart < start)
129810
- low = mid + 1;
129811
- else
129812
- high = mid;
129813
- }
129814
- return low;
129815
- }
129816
- var STORY_ROOT_LOCAL_NAMES;
129817
- var init_wml_paragraph_spans = __esm(() => {
129818
- init_xml_sax();
129819
- STORY_ROOT_LOCAL_NAMES = new Set([
129820
- "document",
129821
- "hdr",
129822
- "ftr",
129823
- "footnotes",
129824
- "endnotes"
129825
- ]);
129826
- });
129827
-
129828
- // ../../../v2/editor-core/dist/document/session-hyperlink-metadata.js
129829
- function createSessionHyperlinkReviewTracker(state) {
129830
- const links = state.sessionHyperlinkMetadata?.links;
129831
- return links?.length ? { links, changed: new Set } : null;
129832
- }
129833
- function trackSessionHyperlinkReviewSplice(tracker, partUri, xml, start, end, replacement) {
129834
- if (!tracker || !tracker.links.some((link) => link.anchors.some((anchor) => anchor.partUri === partUri)))
129835
- return;
129836
- const startByte = utf8Length(xml, start);
129837
- const endByte = startByte + utf8Length(xml.slice(start, end));
129838
- let beforeBytes;
129839
- const patch = {
129840
- kind: "replaceBytes",
129841
- order: 0,
129842
- startByte,
129843
- endByte,
129844
- bytes: encoder.encode(replacement)
129845
- };
129846
- tracker.links = tracker.links.flatMap((link) => {
129847
- const anchors = link.anchors.flatMap((anchor) => {
129848
- if (anchor.partUri !== partUri)
129849
- return [anchor];
129850
- const mapped = mapThroughPatches(anchor, (offset) => {
129851
- beforeBytes ?? (beforeBytes = encoder.encode(xml.slice(start, end)));
129852
- return beforeBytes[offset - startByte];
129853
- }, [patch], true);
129854
- return mapped ? [mapped] : [];
129855
- });
129856
- if (anchors.length === link.anchors.length && anchors.every((anchor, index) => sameAnchor(anchor, link.anchors[index])))
129857
- return [link];
129858
- tracker.changed.add(link.id);
129859
- return anchors.length ? [{ ...link, anchors }] : [];
129860
- });
129861
- }
129862
- function bindSessionHyperlinkReviewCoordinates(group, tracker) {
129863
- if (!tracker?.changed.size)
129864
- return;
129865
- reviewCoordinates.set(group, [...tracker.changed].map((id) => ({
129866
- id,
129867
- value: tracker.links.find((link) => link.id === id) ?? null
129868
- })));
129869
- }
129870
- function utf8Length(value, end = value.length) {
129871
- let length = 0;
129872
- for (let index = 0;index < end; index++) {
129873
- const code = value.charCodeAt(index);
129874
- if (code < 128)
129875
- length++;
129876
- else if (code < 2048)
129877
- length += 2;
129878
- else if (code >= 55296 && code <= 56319 && index + 1 < end && value.charCodeAt(index + 1) >= 56320 && value.charCodeAt(index + 1) <= 57343) {
129879
- length += 4;
129880
- index++;
129881
- } else
129882
- length += 3;
129883
- }
129884
- return length;
129885
- }
129886
- function metadata(state) {
129887
- return state.sessionHyperlinkMetadata ?? (state.sessionHyperlinkMetadata = { nextId: 1, links: [], replay: new WeakMap });
129888
- }
129889
- function hasPendingSessionHyperlinkEffects(state) {
129890
- return Boolean(state.sessionHyperlinkMetadata?.pending?.length);
129891
- }
129892
- function sameAnchor(a, b) {
129893
- return a.partUri === b.partUri && a.startByte === b.startByte && a.endByte === b.endByte;
129894
- }
129895
- function readSessionHyperlinkRel(state, anchor) {
129896
- const store = state.sessionHyperlinkMetadata;
129897
- if (!store?.links.length)
129898
- return;
129899
- if (store.lookup?.links !== store.links) {
129900
- const values = new Map;
129901
- for (const link of store.links) {
129902
- for (const carrier of link.anchors)
129903
- values.set(anchorKey(carrier), link.rel);
129904
- }
129905
- store.lookup = { links: store.links, values };
129906
- }
129907
- return store.lookup.values.get(anchorKey(anchor));
129908
- }
129909
- function anchorKey(anchor) {
129910
- return `${anchor.partUri}\x00${anchor.startByte}\x00${anchor.endByte}`;
129911
- }
129912
- function withSessionHyperlinkEffects(state, effects2, commit) {
129913
- const store = metadata(state);
129914
- if (store.pending)
129915
- throw new Error("Nested session hyperlink effects are unsupported.");
129916
- store.pending = effects2.map((effect) => ({
129917
- ...effect,
129918
- ...effect.before ? { before: { ...effect.before } } : {},
129919
- ...effect.after ? { after: { ...effect.after } } : {}
129920
- }));
129921
- try {
129922
- return commit();
129923
- } finally {
129924
- store.pending = undefined;
129925
- }
129926
- }
129927
- function bindSessionHyperlinkCarriers(group, effects2) {
129928
- compilerEffects.set(group, effects2);
129929
- }
129930
- function prepareSessionHyperlinkMetadata(state, group) {
129931
- const store = state.sessionHyperlinkMetadata;
129932
- if (!store || !store.links.length && !store.pending?.length && !store.replay.has(group))
129933
- return null;
129934
- const replay = store.replay.get(group);
129935
- if (replay) {
129936
- const replacements = new Map(replay.map((delta) => [delta.id, delta.value]));
129937
- const after2 = store.links.filter((link) => !replacements.has(link.id));
129938
- for (const delta of replay)
129939
- if (delta.value)
129940
- after2.push(delta.value);
129941
- return { before: store.links, after: after2, nextId: store.nextId };
129942
- }
129943
- const boundCoordinates = new Map((reviewCoordinates.get(group) ?? []).map((delta) => [delta.id, delta.value]));
129944
- const after = store.links.flatMap((link) => {
129945
- if (boundCoordinates.has(link.id)) {
129946
- const bound = boundCoordinates.get(link.id);
129947
- return bound ? [bound] : [];
129948
- }
129949
- const anchors = link.anchors.flatMap((anchor) => {
129950
- if (!(anchor.partUri in group.perPart))
129951
- return [anchor];
129952
- const entry = group.perPart[anchor.partUri];
129953
- if (entry.kind !== "modify")
129954
- return [];
129955
- const payload = state.packageBytes.getPayload(anchor.partUri);
129956
- if (!payload)
129957
- return [];
129958
- const proof = group.derivedIndexProofs?.exactPartMutations?.find((candidate) => candidate.partUri === anchor.partUri);
129959
- const whole = entry.patches.length === 1 ? entry.patches[0] : undefined;
129960
- const patches = proof && whole?.kind === "replaceBytes" && whole.startByte === 0 && whole.endByte === proof.beforeByteLength && whole.bytes.length === proof.afterByteLength ? proof.splices.map((splice, order) => ({
129961
- kind: "replaceBytes",
129962
- order,
129963
- startByte: splice.beforeStart,
129964
- endByte: splice.beforeEnd,
129965
- bytes: whole.bytes.subarray(splice.afterStart, splice.afterEnd)
129966
- })) : entry.patches;
129967
- const moved = mapThroughPatches(anchor, boundedPayloadReader(payload), patches, Boolean(proof)) ?? mapMovedParagraphAnchor(state, anchor, patches);
129968
- return moved ? [moved] : [];
129969
- });
129970
- return anchors.length ? [
129971
- anchors.length === link.anchors.length && anchors.every((anchor, i) => sameAnchor(anchor, link.anchors[i])) ? link : { ...link, anchors }
129972
- ] : [];
129973
- });
129974
- const bindings = compilerEffects.get(group) ?? [];
129975
- const pending = store.pending ?? [];
129976
- const effects2 = bindings.map((binding, index) => ({
129977
- ...binding,
129978
- ...pending[index],
129979
- after: pending[index]?.after ?? binding.after
129980
- }));
129981
- effects2.push(...pending.slice(bindings.length));
129982
- let nextId = store.nextId;
129983
- for (const effect of effects2) {
129984
- if (!effect.after)
129985
- throw new Error("Session hyperlink effect has no compiler-bound destination.");
129986
- const destinationLength = resultingPartLength(state, group, effect.after.partUri);
129987
- if (destinationLength === null || effect.after.startByte < 0 || effect.after.endByte <= effect.after.startByte || effect.after.endByte > destinationLength)
129988
- throw new Error("Invalid session hyperlink destination.");
129989
- const original = effect.before && store.links.find((link) => link.anchors.some((anchor) => sameAnchor(anchor, effect.before)));
129990
- const current = original ? after.findIndex((link) => link.id === original.id) : -1;
129991
- const rel = effect.rel === undefined ? original?.rel : effect.rel || undefined;
129992
- const mappedAliases = current >= 0 ? after[current].anchors : [];
129993
- if (current >= 0)
129994
- after.splice(current, 1);
129995
- if (rel)
129996
- after.push({
129997
- id: original?.id ?? nextId++,
129998
- anchors: [
129999
- effect.after,
130000
- ...(effect.survivingAlternates ?? mappedAliases).filter((anchor) => !sameAnchor(anchor, effect.after))
130001
- ],
130002
- rel
130003
- });
130004
- }
130005
- return { before: store.links, after, nextId };
130006
- }
130007
- function commitSessionHyperlinkMetadata(state, prepared, forward, inverse) {
130008
- if (!prepared)
130009
- return;
130010
- const store = metadata(state);
130011
- store.links = prepared.after;
130012
- store.lookup = undefined;
130013
- store.nextId = prepared.nextId;
130014
- const before = new Map(prepared.before.map((link) => [link.id, link]));
130015
- const after = new Map(prepared.after.map((link) => [link.id, link]));
130016
- const changed = [...new Set([...before.keys(), ...after.keys()])].filter((id) => before.get(id) !== after.get(id));
130017
- store.replay.set(forward, changed.map((id) => ({ id, value: after.get(id) ?? null })));
130018
- store.replay.set(inverse, changed.map((id) => ({ id, value: before.get(id) ?? null })));
130019
- }
130020
- function composeSessionHyperlinkHistory(state, captured, forward) {
130021
- const store = state.sessionHyperlinkMetadata;
130022
- if (!store)
130023
- return false;
130024
- const final = new Map;
130025
- for (const group of captured)
130026
- for (const delta of store.replay.get(group) ?? [])
130027
- final.set(delta.id, delta.value);
130028
- const changes = [];
130029
- for (const [id, value] of final) {
130030
- const current = store.links.find((link) => link.id === id) ?? null;
130031
- if (current === value || current && value && current.rel === value.rel && current.anchors.length === value.anchors.length && current.anchors.every((anchor, index) => sameAnchor(anchor, value.anchors[index])))
130032
- continue;
130033
- changes.push({ id, value });
130034
- }
130035
- if (!changes.length)
130036
- return false;
130037
- store.replay.set(forward, changes);
130038
- return true;
130039
- }
130040
- function resultingPartLength(state, group, partUri) {
130041
- const entry = group.perPart[partUri];
130042
- if (entry?.kind === "remove")
130043
- return null;
130044
- if (entry?.kind === "create")
130045
- return entry.bytes.length;
130046
- const payload = state.packageBytes.getPayload(partUri);
130047
- if (!payload)
130048
- return null;
130049
- return payloadLength(payload) + (entry?.kind === "modify" ? entry.patches.reduce((delta, patch) => delta + (patch.kind === "deleteBytes" ? 0 : patch.bytes.length) - (patch.kind === "insertBytes" ? 0 : patch.endByte - patch.startByte), 0) : 0);
130050
- }
130051
- function boundedPayloadReader(payload) {
130052
- let start = -1;
130053
- let bytes = new Uint8Array;
130054
- return (offset) => {
130055
- if (offset < start || offset >= start + bytes.length) {
130056
- start = Math.floor(offset / 4096) * 4096;
130057
- bytes = payloadSubarray(payload, start, Math.min(start + 4096, payloadLength(payload)));
130058
- }
130059
- return bytes[offset - start];
130060
- };
130061
- }
130062
- function mapMovedParagraphAnchor(state, anchor, patches) {
130063
- const owner = findAnchorParagraph(state, anchor);
130064
- if (!owner?.blockId)
130065
- return null;
130066
- const payload = state.packageBytes.getPayload(anchor.partUri);
130067
- if (!payload)
130068
- return null;
130069
- const oldBytes = payloadSubarray(payload, owner.byteStart, owner.byteEnd);
130070
- const candidates = [];
130071
- let delta = 0;
130072
- for (const patch of patches) {
130073
- const start = patch.kind === "insertBytes" ? patch.atByte : patch.startByte;
130074
- const end = patch.kind === "insertBytes" ? start : patch.endByte;
130075
- if (patch.kind !== "deleteBytes") {
130076
- const xml = decoder2.decode(patch.bytes);
130077
- for (const paragraph of scanWmlParagraphSpans(xml, {
130078
- fragment: true,
130079
- additionalNamespaces: {
130080
- w: "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
130081
- w14: "http://schemas.microsoft.com/office/word/2010/wordml"
130082
- }
130083
- }).paragraphs) {
130084
- if (paragraph.paraId !== owner.blockId)
130085
- continue;
130086
- const newBytes = encoder.encode(xml.slice(paragraph.openStart, paragraph.closeEnd));
130087
- const local = mapThroughPatches({
130088
- ...anchor,
130089
- startByte: anchor.startByte - owner.byteStart,
130090
- endByte: anchor.endByte - owner.byteStart
130091
- }, (offset) => oldBytes[offset], [
130092
- {
130093
- kind: "replaceBytes",
130094
- order: 0,
130095
- startByte: 0,
130096
- endByte: oldBytes.length,
130097
- bytes: newBytes
130098
- }
130099
- ]);
130100
- if (local) {
130101
- const base2 = start + delta + encoder.encode(xml.slice(0, paragraph.openStart)).length;
130102
- candidates.push({
130103
- ...local,
130104
- startByte: local.startByte + base2,
130105
- endByte: local.endByte + base2
130106
- });
130107
- }
130108
- }
130109
- }
130110
- delta += (patch.kind === "deleteBytes" ? 0 : patch.bytes.length) - (end - start);
130111
- }
130112
- return candidates.length === 1 ? candidates[0] : null;
130113
- }
130114
- function findAnchorParagraph(state, anchor) {
130115
- for (const index of state.paragraphIndexes.values()) {
130116
- if (index.entries[0]?.partUri !== anchor.partUri)
130117
- continue;
130118
- let low = 0;
130119
- let high = index.entries.length;
130120
- while (low < high) {
130121
- const middle = Math.floor((low + high) / 2);
130122
- if (index.entries[middle].byteStart <= anchor.startByte)
130123
- low = middle + 1;
130124
- else
130125
- high = middle;
130126
- }
130127
- const owner = index.entries[low - 1];
130128
- if (owner && owner.byteStart <= anchor.startByte && owner.byteEnd >= anchor.endByte)
130129
- return owner;
130130
- }
130131
- return null;
130132
- }
130133
- function mapThroughPatches(anchor, readBefore, patches, allowRetainedCarrier = false) {
130134
- let startByte = anchor.startByte;
130135
- let endByte = anchor.endByte;
130136
- for (const patch of patches) {
130137
- let start = patch.kind === "insertBytes" ? patch.atByte : patch.startByte;
130138
- let end = patch.kind === "insertBytes" ? start : patch.endByte;
130139
- let replacement = patch.kind === "deleteBytes" ? new Uint8Array : patch.bytes;
130140
- const rawDelta = replacement.length - (end - start);
130141
- if (end <= anchor.startByte) {
130142
- startByte += rawDelta;
130143
- endByte += rawDelta;
130144
- continue;
130145
- }
130146
- if (start >= anchor.endByte)
130147
- continue;
130148
- if (start > anchor.startByte && end < anchor.endByte) {
130149
- endByte += rawDelta;
130150
- continue;
130151
- }
130152
- if (allowRetainedCarrier && start <= anchor.startByte && end >= anchor.endByte) {
130153
- const length = anchor.endByte - anchor.startByte;
130154
- const retainedAt = uniqueByteWindow(replacement.length, (offset) => replacement[offset], length, (offset) => readBefore(anchor.startByte + offset));
130155
- const originalAt = retainedAt === null ? null : uniqueByteWindow(end - start, (offset) => readBefore(start + offset), length, (offset) => readBefore(anchor.startByte + offset));
130156
- if (retainedAt !== null && originalAt === anchor.startByte - start) {
130157
- const shift = start + retainedAt - anchor.startByte;
130158
- startByte += shift;
130159
- endByte += shift;
130160
- continue;
130161
- }
130162
- }
130163
- let prefix = 0;
130164
- while (start + prefix < end && prefix < replacement.length && readBefore(start + prefix) === replacement[prefix])
130165
- prefix++;
130166
- start += prefix;
130167
- replacement = replacement.subarray(prefix);
130168
- let suffix = 0;
130169
- while (end - suffix > start && suffix < replacement.length && readBefore(end - suffix - 1) === replacement[replacement.length - suffix - 1])
130170
- suffix++;
130171
- end -= suffix;
130172
- replacement = replacement.subarray(0, replacement.length - suffix);
130173
- if (start === end && !replacement.length)
130174
- continue;
130175
- const delta = replacement.length - (end - start);
130176
- if (end <= anchor.startByte) {
130177
- startByte += delta;
130178
- endByte += delta;
130179
- } else if (start >= anchor.endByte)
130180
- continue;
130181
- else if (start > anchor.startByte && end < anchor.endByte)
130182
- endByte += delta;
130183
- else
130184
- return null;
130185
- }
130186
- return { ...anchor, startByte, endByte };
130187
- }
130188
- function uniqueByteWindow(haystackLength, haystack, needleLength, needle) {
130189
- if (needleLength === 0 || needleLength > haystackLength)
130190
- return null;
130191
- const bytes = Uint8Array.from({ length: needleLength }, (_, index) => needle(index));
130192
- const prefix = new Uint32Array(needleLength);
130193
- for (let index = 1, matched = 0;index < needleLength; index++) {
130194
- while (matched > 0 && bytes[index] !== bytes[matched])
130195
- matched = prefix[matched - 1];
130196
- if (bytes[index] === bytes[matched])
130197
- matched++;
130198
- prefix[index] = matched;
130199
- }
130200
- let match = null;
130201
- for (let index = 0, matched = 0;index < haystackLength; index++) {
130202
- const byte = haystack(index);
130203
- while (matched > 0 && byte !== bytes[matched])
130204
- matched = prefix[matched - 1];
130205
- if (byte === bytes[matched])
130206
- matched++;
130207
- if (matched === needleLength) {
130208
- if (match !== null)
130209
- return null;
130210
- match = index - needleLength + 1;
130211
- matched = prefix[matched - 1];
130212
- }
130213
- }
130214
- return match;
130215
- }
130216
- var encoder, decoder2, compilerEffects, reviewCoordinates;
130217
- var init_session_hyperlink_metadata = __esm(() => {
130218
- init_part_payload();
130219
- init_wml_paragraph_spans();
130220
- encoder = new TextEncoder;
130221
- decoder2 = new TextDecoder;
130222
- compilerEffects = new WeakMap;
130223
- reviewCoordinates = new WeakMap;
130224
- });
130225
-
130226
129523
  // ../../../v2/editor-core/dist/scan/body-boundary-scan.js
130227
129524
  function isResumablePrefixBodyScanError(scan) {
130228
129525
  return scan?.bodyFound === true && scan.wrapper.bodyContentEnd == null && !scan.fullForwardScanCompleted && scan.parseError?.startsWith("unterminated-child:") === true;
@@ -130500,7 +129797,7 @@ function readMceIgnorable(tag, frame) {
130500
129797
  return [];
130501
129798
  }
130502
129799
  function strSlice(buf, start, end) {
130503
- return TD6.decode(buf.subarray(start, end));
129800
+ return TD5.decode(buf.subarray(start, end));
130504
129801
  }
130505
129802
  function parseWrapperContext(buf, limit, diagnostics) {
130506
129803
  const wrapper = {
@@ -132913,7 +132210,7 @@ async function streamEmptyOrTriviaBody(args) {
132913
132210
  const m = args.noteMetrics();
132914
132211
  return { spine: result, prefixScan: args.prefixScan, cancelled: false, ...m };
132915
132212
  }
132916
- var NS_W2, NS_MC2, DEFAULT_SOURCE_BOOTSTRAP_POLICY, B, TD6, NEEDLE_COMMENT_END, NEEDLE_CDATA_END, NEEDLE_PI_END, NEEDLE_LT_BANG_CDATA, NEEDLE_LT_BANG_DASH, RANGE_MARKER_LOCAL_NAMES, REVISION_CONTAINER_LOCAL_NAMES, STORY_SPINE_DEFAULTS, DEFAULT_STREAMING_SCAN_CHUNK_BYTES, DEFAULT_STREAMING_SCAN_WINDOW_CEILING_BYTES, STREAM_NEED_MORE = -2;
132213
+ var NS_W2, NS_MC2, DEFAULT_SOURCE_BOOTSTRAP_POLICY, B, TD5, NEEDLE_COMMENT_END, NEEDLE_CDATA_END, NEEDLE_PI_END, NEEDLE_LT_BANG_CDATA, NEEDLE_LT_BANG_DASH, RANGE_MARKER_LOCAL_NAMES, REVISION_CONTAINER_LOCAL_NAMES, STORY_SPINE_DEFAULTS, DEFAULT_STREAMING_SCAN_CHUNK_BYTES, DEFAULT_STREAMING_SCAN_WINDOW_CEILING_BYTES, STREAM_NEED_MORE = -2;
132917
132214
  var init_body_boundary_scan = __esm(() => {
132918
132215
  init_xml_sax();
132919
132216
  init_paragraph_scan_count();
@@ -132950,7 +132247,7 @@ var init_body_boundary_scan = __esm(() => {
132950
132247
  B2[B2["Underscore"] = 95] = "Underscore";
132951
132248
  B2[B2["Dot"] = 46] = "Dot";
132952
132249
  })(B || (B = {}));
132953
- TD6 = new TextDecoder("utf-8", { fatal: false });
132250
+ TD5 = new TextDecoder("utf-8", { fatal: false });
132954
132251
  NEEDLE_COMMENT_END = [B.Dash, B.Dash, B.Gt];
132955
132252
  NEEDLE_CDATA_END = [B.RBracket, B.RBracket, B.Gt];
132956
132253
  NEEDLE_PI_END = [B.Question, B.Gt];
@@ -132989,6 +132286,154 @@ var init_body_boundary_scan = __esm(() => {
132989
132286
  DEFAULT_STREAMING_SCAN_WINDOW_CEILING_BYTES = 96 * 1024 * 1024;
132990
132287
  });
132991
132288
 
132289
+ // ../../../v2/editor-core/dist/scan/wml-paragraph-spans.js
132290
+ function scanWmlParagraphSpans(xml, options = {}) {
132291
+ const collector = createParagraphSpanCollector(options);
132292
+ const result = walkXmlElements(xml, collector.walkOptions);
132293
+ return collector.finish(result.errors);
132294
+ }
132295
+ async function scanWmlParagraphSpansCooperatively(xml, yieldPoint, options = {}) {
132296
+ const collector = createParagraphSpanCollector(options);
132297
+ const result = await walkXmlElementsCooperatively(xml, {
132298
+ ...collector.walkOptions,
132299
+ yieldPoint
132300
+ });
132301
+ return collector.finish(result.errors);
132302
+ }
132303
+ function createParagraphSpanCollector(options) {
132304
+ const paragraphs = [];
132305
+ const bookmarkStarts = [];
132306
+ const bookmarkEnds = [];
132307
+ const openParagraphs = [];
132308
+ let storyRoot = null;
132309
+ const walkOptions = {
132310
+ fragment: options.fragment,
132311
+ additionalNamespaces: options.additionalNamespaces,
132312
+ onOpenTag(event) {
132313
+ if (!storyRoot && event.tag.namespaceUri === NS_W && STORY_ROOT_LOCAL_NAMES.has(event.tag.localName)) {
132314
+ storyRoot = rootFromEvent(event);
132315
+ }
132316
+ if (isWmlParagraph(event)) {
132317
+ const paraIdAttributes = readXmlAttributes(event.tag, NS_W14, "paraId");
132318
+ const span = {
132319
+ openStart: event.start,
132320
+ openEnd: event.end,
132321
+ closeStart: event.end,
132322
+ closeEnd: event.end,
132323
+ selfClosing: event.tag.isSelfClosing,
132324
+ paraId: paraIdAttributes.length === 1 && paraIdAttributes[0].value ? paraIdAttributes[0].value : null,
132325
+ paraIdAttributes,
132326
+ namespaceBindings: event.namespaceBindings
132327
+ };
132328
+ paragraphs.push(span);
132329
+ if (!event.tag.isSelfClosing)
132330
+ openParagraphs.push(paragraphs.length - 1);
132331
+ return;
132332
+ }
132333
+ if (openParagraphs.length > 0 && event.tag.namespaceUri === NS_W && (event.tag.localName === "bookmarkStart" || event.tag.localName === "bookmarkEnd")) {
132334
+ const markers = event.tag.localName === "bookmarkStart" ? bookmarkStarts : bookmarkEnds;
132335
+ markers.push({
132336
+ paragraphNamespaceBindings: paragraphs[openParagraphs.at(-1)].namespaceBindings,
132337
+ openStart: event.start,
132338
+ openEnd: event.end,
132339
+ namespaceBindings: event.namespaceBindings
132340
+ });
132341
+ }
132342
+ },
132343
+ onCloseTag(event) {
132344
+ if (event.tag.isSelfClosing || !isWmlParagraph(event))
132345
+ return;
132346
+ const index = openParagraphs.pop();
132347
+ if (index == null)
132348
+ return;
132349
+ const span = paragraphs[index];
132350
+ span.closeStart = event.start;
132351
+ span.closeEnd = event.end;
132352
+ }
132353
+ };
132354
+ return {
132355
+ walkOptions,
132356
+ finish(errors4) {
132357
+ return {
132358
+ paragraphs,
132359
+ bookmarkStarts,
132360
+ bookmarkEnds,
132361
+ storyRoot,
132362
+ errors: errors4,
132363
+ ok: errors4.length === 0 && openParagraphs.length === 0
132364
+ };
132365
+ }
132366
+ };
132367
+ }
132368
+ function findContainingWmlParagraph(paragraphs, offset) {
132369
+ let low = 0;
132370
+ let high = paragraphs.length;
132371
+ while (low < high) {
132372
+ const mid = low + high >>> 1;
132373
+ if (paragraphs[mid].openStart <= offset)
132374
+ low = mid + 1;
132375
+ else
132376
+ high = mid;
132377
+ }
132378
+ for (let index = low - 1;index >= 0; index -= 1) {
132379
+ const paragraph = paragraphs[index];
132380
+ if (paragraph.openStart > offset)
132381
+ continue;
132382
+ if (paragraph.openEnd <= offset && offset < paragraph.closeEnd)
132383
+ return paragraph;
132384
+ }
132385
+ return null;
132386
+ }
132387
+ function findFirstWmlParagraphInRange(paragraphs, start, end) {
132388
+ const low = lowerBoundParagraphStart(paragraphs, start);
132389
+ const paragraph = paragraphs[low];
132390
+ return paragraph && paragraph.openStart < end && paragraph.closeEnd <= end ? paragraph : null;
132391
+ }
132392
+ function findWmlParagraphsInRange(paragraphs, start, end) {
132393
+ const out = [];
132394
+ for (let index = lowerBoundParagraphStart(paragraphs, start);index < paragraphs.length; index += 1) {
132395
+ const paragraph = paragraphs[index];
132396
+ if (paragraph.openStart >= end)
132397
+ break;
132398
+ if (paragraph.closeEnd <= end)
132399
+ out.push(paragraph);
132400
+ }
132401
+ return out;
132402
+ }
132403
+ function isWmlParagraph(event) {
132404
+ return event.tag.namespaceUri === NS_W && event.tag.localName === "p";
132405
+ }
132406
+ function rootFromEvent(event) {
132407
+ return {
132408
+ start: event.start,
132409
+ end: event.end,
132410
+ namespaceBindings: event.namespaceBindings
132411
+ };
132412
+ }
132413
+ function lowerBoundParagraphStart(paragraphs, start) {
132414
+ let low = 0;
132415
+ let high = paragraphs.length;
132416
+ while (low < high) {
132417
+ const mid = low + high >>> 1;
132418
+ if (paragraphs[mid].openStart < start)
132419
+ low = mid + 1;
132420
+ else
132421
+ high = mid;
132422
+ }
132423
+ return low;
132424
+ }
132425
+ var STORY_ROOT_LOCAL_NAMES;
132426
+ var init_wml_paragraph_spans = __esm(() => {
132427
+ init_xml_sax();
132428
+ STORY_ROOT_LOCAL_NAMES = new Set([
132429
+ "document",
132430
+ "hdr",
132431
+ "ftr",
132432
+ "footnotes",
132433
+ "endnotes"
132434
+ ]);
132435
+ });
132436
+
132992
132437
  // ../../../v2/editor-core/dist/document/transactions/tx-perf-probe.js
132993
132438
  function createSDTxPerfProbe() {
132994
132439
  return {
@@ -133890,13 +133335,13 @@ function storyPartUriFromStoryId(storyId) {
133890
133335
  uri = uri.slice(0, hashIdx);
133891
133336
  return uri.startsWith("/") ? uri : `/${uri}`;
133892
133337
  }
133893
- var TD7, SEARCH_TEXT_INDEX_REGISTRY_PREFIX = "__sd:search-text-index:", SEARCH_TEXT_INDEX_TAG, SEARCH_TEXT_INDEX_DEFERRED_PREFIX = "__sd:search-text-index-deferred:", SEARCH_TEXT_INDEX_PART_GENERATION_PREFIX = "__sd:search-text-generation:", SEARCH_TEXT_INDEX_PART_GENERATION_TAG, INITIAL_SEARCH_TEXT_INDEX_PART_GENERATION, SEARCH_TEXT_INDEX_DELETED_SUFFIX = "#deleted";
133338
+ var TD6, SEARCH_TEXT_INDEX_REGISTRY_PREFIX = "__sd:search-text-index:", SEARCH_TEXT_INDEX_TAG, SEARCH_TEXT_INDEX_DEFERRED_PREFIX = "__sd:search-text-index-deferred:", SEARCH_TEXT_INDEX_PART_GENERATION_PREFIX = "__sd:search-text-generation:", SEARCH_TEXT_INDEX_PART_GENERATION_TAG, INITIAL_SEARCH_TEXT_INDEX_PART_GENERATION, SEARCH_TEXT_INDEX_DELETED_SUFFIX = "#deleted";
133894
133339
  var init_search_text_index = __esm(() => {
133895
133340
  init_sd_document_state();
133896
133341
  init_inline_text_extraction();
133897
133342
  init_lazy_indexes();
133898
133343
  init_paragraph_index();
133899
- TD7 = new TextDecoder;
133344
+ TD6 = new TextDecoder;
133900
133345
  SEARCH_TEXT_INDEX_TAG = Symbol.for("@superdoc/v2/search-text-index");
133901
133346
  SEARCH_TEXT_INDEX_PART_GENERATION_TAG = Symbol.for("@superdoc/v2/search-text-index-part-generation");
133902
133347
  INITIAL_SEARCH_TEXT_INDEX_PART_GENERATION = Object.freeze({
@@ -135527,7 +134972,7 @@ var init_run_signature = __esm(() => {
135527
134972
 
135528
134973
  // ../../../v2/document-compare/src/inline-control-removal.ts
135529
134974
  function elements(xml, namespaces = {}, allowText = false) {
135530
- const prefix = `<replay xmlns:w="${W3}">`;
134975
+ const prefix = `<replay xmlns:w="${W2}">`;
135531
134976
  const source = prefix + xml + "</replay>";
135532
134977
  const parser = new import_saxes3.SaxesParser({ xmlns: true, additionalNamespaces: namespaces });
135533
134978
  const stack = [];
@@ -135581,11 +135026,11 @@ function numericIdentity(value) {
135581
135026
  function safeRun(element) {
135582
135027
  if (!is(element, "r"))
135583
135028
  return false;
135584
- const safeProperty = (property) => property.tag.uri === W3 && RUN_PROPERTIES.has(property.tag.local) && property.children.length === 0;
135585
- return element.children.every((child) => is(child, "rPr") ? child.children.every(safeProperty) : child.tag.uri === W3 && ["t", "tab", "br", "cr"].includes(child.tag.local) && child.children.length === 0);
135029
+ const safeProperty = (property) => property.tag.uri === W2 && RUN_PROPERTIES.has(property.tag.local) && property.children.length === 0;
135030
+ return element.children.every((child) => is(child, "rPr") ? child.children.every(safeProperty) : child.tag.uri === W2 && ["t", "tab", "br", "cr"].includes(child.tag.local) && child.children.length === 0);
135586
135031
  }
135587
135032
  function safeProofingBoundary(element) {
135588
- return is(element, "proofErr") && element.tag.isSelfClosing && element.children.length === 0 && ["spellStart", "spellEnd", "gramStart", "gramEnd"].includes(attr(element, "type") ?? "") && Object.values(element.tag.attributes).every((attribute) => attribute.uri === "http://www.w3.org/2000/xmlns/" || attribute.uri === W3 && attribute.local === "type");
135033
+ return is(element, "proofErr") && element.tag.isSelfClosing && element.children.length === 0 && ["spellStart", "spellEnd", "gramStart", "gramEnd"].includes(attr(element, "type") ?? "") && Object.values(element.tag.attributes).every((attribute) => attribute.uri === "http://www.w3.org/2000/xmlns/" || attribute.uri === W2 && attribute.local === "type");
135589
135034
  }
135590
135035
  function safeControlContent(children, isRun) {
135591
135036
  const open = new Set;
@@ -135621,7 +135066,7 @@ function control(xml, element) {
135621
135066
  return null;
135622
135067
  const locks = children.filter((child) => is(child, "lock"));
135623
135068
  const deletable = locks.every((lock) => attr(lock, "val") === "unlocked" || attr(lock, "val") === "contentLocked");
135624
- const supportedProperties = children.every((child) => child.tag.uri === W3 ? ["id", "tag", "alias", "text", "richText", "lock", "rPr", "placeholder", "showingPlcHdr", "temporary"].includes(child.tag.local) : child.tag.uri === "http://schemas.microsoft.com/office/word/2012/wordml" && child.tag.local === "appearance");
135069
+ const supportedProperties = children.every((child) => child.tag.uri === W2 ? ["id", "tag", "alias", "text", "richText", "lock", "rPr", "placeholder", "showingPlcHdr", "temporary"].includes(child.tag.local) : child.tag.uri === "http://schemas.microsoft.com/office/word/2012/wordml" && child.tag.local === "appearance");
135625
135070
  const contentXml = xml.slice(content[0].start, content[0].end);
135626
135071
  const contentOpenEnd = contentXml.indexOf(">") + 1;
135627
135072
  const contentCloseStart = contentXml.lastIndexOf("</");
@@ -135737,10 +135182,10 @@ function inspectInlineControlReplay(beforeXml, afterXml, namespaces = {}) {
135737
135182
  return null;
135738
135183
  const xmlns = "http://www.w3.org/2000/xmlns/";
135739
135184
  const attributes = (root, allowed) => Object.values(root.tag.attributes).every((attribute) => attribute.uri === xmlns || allowed(attribute.uri, attribute.local));
135740
- const runProperties = (root) => is(root, "rPr") && attributes(root, () => false) && root.children.every((child) => child.tag.uri === W3 && RUN_PROPERTIES.has(child.tag.local) && !child.children.length && attributes(child, (uri) => uri === W3));
135741
- const simpleRun = (root) => safeRun(root) && attributes(root, (uri, local) => uri === W3 && ["rsidR", "rsidRPr", "rsidDel"].includes(local)) && root.children.filter((child) => is(child, "t")).length === 1 && root.children.every((child) => runProperties(child) || is(child, "t") && !child.tag.isSelfClosing && attributes(child, (uri, local) => uri === "http://www.w3.org/XML/1998/namespace" && local === "space"));
135185
+ const runProperties = (root) => is(root, "rPr") && attributes(root, () => false) && root.children.every((child) => child.tag.uri === W2 && RUN_PROPERTIES.has(child.tag.local) && !child.children.length && attributes(child, (uri) => uri === W2));
135186
+ const simpleRun = (root) => safeRun(root) && attributes(root, (uri, local) => uri === W2 && ["rsidR", "rsidRPr", "rsidDel"].includes(local)) && root.children.filter((child) => is(child, "t")).length === 1 && root.children.every((child) => runProperties(child) || is(child, "t") && !child.tag.isSelfClosing && attributes(child, (uri, local) => uri === "http://www.w3.org/XML/1998/namespace" && local === "space"));
135742
135187
  const safeControlProperties = (root) => {
135743
- if (!attributes(root, (uri, local) => uri === W3 && ["rsidR", "rsidRPr", "rsidDel"].includes(local)))
135188
+ if (!attributes(root, (uri, local) => uri === W2 && ["rsidR", "rsidRPr", "rsidDel"].includes(local)))
135744
135189
  return false;
135745
135190
  const properties = root.children.find((child) => is(child, "sdtPr"));
135746
135191
  const content = root.children.find((child) => is(child, "sdtContent"));
@@ -135753,13 +135198,13 @@ function inspectInlineControlReplay(beforeXml, afterXml, namespaces = {}) {
135753
135198
  if (seen.has(child.tag.name))
135754
135199
  return false;
135755
135200
  seen.add(child.tag.name);
135756
- if (!attributes(child, (uri) => uri === W3 || uri === child.tag.uri))
135201
+ if (!attributes(child, (uri) => uri === W2 || uri === child.tag.uri))
135757
135202
  return false;
135758
135203
  if (is(child, "rPr")) {
135759
135204
  if (!runProperties(child))
135760
135205
  return false;
135761
135206
  } else if (is(child, "placeholder")) {
135762
- if (child.children.some((item) => !is(item, "docPart") || item.children.length || !attributes(item, (uri) => uri === W3)))
135207
+ if (child.children.some((item) => !is(item, "docPart") || item.children.length || !attributes(item, (uri) => uri === W2)))
135763
135208
  return false;
135764
135209
  } else if (child.children.length)
135765
135210
  return false;
@@ -135899,7 +135344,7 @@ function bodyOperationsCoverInlineControlReplay(base2, target, operations, match
135899
135344
  }
135900
135345
  return covered.size === changes.length && changes.every((entry) => entry.targetId !== null && covered.get(entry.targetId) === entry.disposition);
135901
135346
  }
135902
- var import_saxes3, W3 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", attr = (element, name) => Object.values(element.tag.attributes).find((attribute) => attribute.uri === W3 && attribute.local === name)?.value, is = (element, name) => element.tag.uri === W3 && element.tag.local === name, fragment2 = (xml, element) => xml.slice(element.start, element.end), signature = (xml) => canonicalizeXmlForSignature(xml), RUN_PROPERTIES;
135347
+ var import_saxes3, W2 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", attr = (element, name) => Object.values(element.tag.attributes).find((attribute) => attribute.uri === W2 && attribute.local === name)?.value, is = (element, name) => element.tag.uri === W2 && element.tag.local === name, fragment2 = (xml, element) => xml.slice(element.start, element.end), signature = (xml) => canonicalizeXmlForSignature(xml), RUN_PROPERTIES;
135903
135348
  var init_inline_control_removal = __esm(() => {
135904
135349
  init_run_signature();
135905
135350
  import_saxes3 = __toESM(require_saxes(), 1);
@@ -136985,13 +136430,13 @@ function projectCapturedNoteStoryEntries(value) {
136985
136430
  const parts = directParagraphParts(paragraphXml, range.namespaceBindings);
136986
136431
  const paragraphPropertiesXml = parts.properties;
136987
136432
  const runXml = parts.runs;
136988
- const metadata2 = paragraphPropertiesMetadata(paragraphPropertiesXml);
136433
+ const metadata = paragraphPropertiesMetadata(paragraphPropertiesXml);
136989
136434
  return [{
136990
136435
  blockId: range.paraId ?? `${SYNTHETIC_BLOCK_PREFIX}${ordinal}`,
136991
136436
  ordinal,
136992
136437
  text: visibleParagraphText(paragraphXml, range.namespaceBindings),
136993
- headingLevel: metadata2.headingLevel,
136994
- styleId: metadata2.styleId,
136438
+ headingLevel: metadata.headingLevel,
136439
+ styleId: metadata.styleId,
136995
136440
  runXml,
136996
136441
  paragraphPropertiesXml,
136997
136442
  paragraphPropertiesSignature: computeParagraphPropertiesSignature(paragraphPropertiesXml)
@@ -141415,7 +140860,7 @@ function buildTrackedChangeCatalog(state, options = {}) {
141415
140860
  continue;
141416
140861
  const revision = state.parts.get(partUri)?.descriptor.revision;
141417
140862
  const cachedScan = !hasByteOverride && revision ? partScanCache.byPart.get(partUri) : undefined;
141418
- const scan = cachedScan && cachedScan.revision === revision ? cachedScan.scan : scanFragments(TD8.decode(bytes), partUri, storyId, leadingUtf8BomLength2(bytes));
140863
+ const scan = cachedScan && cachedScan.revision === revision ? cachedScan.scan : scanFragments(TD7.decode(bytes), partUri, storyId, leadingUtf8BomLength2(bytes));
141419
140864
  if (!hasByteOverride && revision && cachedScan?.revision !== revision) {
141420
140865
  partScanCache.byPart.set(partUri, { revision, scan });
141421
140866
  }
@@ -142817,7 +142262,7 @@ function synthesizeTrackedChangeRsid(input) {
142817
142262
  return `sd:${input.storyId}|${input.kind}|${input.author}|${input.date}|#${input.occurrence}`;
142818
142263
  }
142819
142264
  function synthesizeTrackedChangeRsidFromRawMetadata(input) {
142820
- const metadata2 = semanticTrackedChangeMetadata({
142265
+ const metadata = semanticTrackedChangeMetadata({
142821
142266
  author: input.author,
142822
142267
  initials: null,
142823
142268
  authorEmail: null,
@@ -142825,8 +142270,8 @@ function synthesizeTrackedChangeRsidFromRawMetadata(input) {
142825
142270
  });
142826
142271
  return synthesizeTrackedChangeRsid({
142827
142272
  ...input,
142828
- author: metadata2.author,
142829
- date: metadata2.date,
142273
+ author: metadata.author,
142274
+ date: metadata.date,
142830
142275
  wId: canonicalTrackedTextRevisionWId(input.wId)
142831
142276
  });
142832
142277
  }
@@ -142841,7 +142286,7 @@ function normalizeTrackedChangeRsid(input) {
142841
142286
  const parsed = parseRevisionWId(suffix);
142842
142287
  return parsed === null ? decoded : `${decoded.slice(0, suffixStart)}${parsed}`;
142843
142288
  }
142844
- var TD8, TE2, TRACKED_CHANGE_CATALOG_REGISTRY_KEY = "__sd:tracked-change-rsid-catalog", TRACKED_CHANGE_PART_SCAN_REGISTRY_KEY = "__sd:tracked-change-part-scan-cache", TRACKED_CHANGE_CATALOG_TAG, TRACKED_CHANGE_PART_SCAN_TAG, TRACKED_CHANGE_MARKUP_LOCAL_NAMES, TRACKED_CHANGE_ELEMENT_CANDIDATE;
142289
+ var TD7, TE2, TRACKED_CHANGE_CATALOG_REGISTRY_KEY = "__sd:tracked-change-rsid-catalog", TRACKED_CHANGE_PART_SCAN_REGISTRY_KEY = "__sd:tracked-change-part-scan-cache", TRACKED_CHANGE_CATALOG_TAG, TRACKED_CHANGE_PART_SCAN_TAG, TRACKED_CHANGE_MARKUP_LOCAL_NAMES, TRACKED_CHANGE_ELEMENT_CANDIDATE;
142845
142290
  var init_catalog3 = __esm(() => {
142846
142291
  init_empty_paragraph_move();
142847
142292
  init_native_sdt_ownership();
@@ -142851,7 +142296,7 @@ var init_catalog3 = __esm(() => {
142851
142296
  init_wml_paragraph_spans();
142852
142297
  init_xml_sax();
142853
142298
  init_lazy_indexes();
142854
- TD8 = new TextDecoder;
142299
+ TD7 = new TextDecoder;
142855
142300
  TE2 = new TextEncoder;
142856
142301
  TRACKED_CHANGE_CATALOG_TAG = Symbol.for("@superdoc/v2/tracked-change-rsid-catalog");
142857
142302
  TRACKED_CHANGE_PART_SCAN_TAG = Symbol.for("@superdoc/v2/tracked-change-part-scan-cache");
@@ -142900,16 +142345,42 @@ function normalizePartUri(uri) {
142900
142345
  out = out.replace(/\/+/g, "/");
142901
142346
  return out;
142902
142347
  }
142903
- function resolveTargetUri(baseUri, target, targetMode) {
142348
+ function partUriComparisonKey(uri) {
142349
+ return normalizePartUri(uri).replace(/[A-Z]/g, (letter) => letter.toLowerCase());
142350
+ }
142351
+ function resolveRegisteredPartUri(uri, parts) {
142352
+ const normalized = normalizePartUri(uri);
142353
+ if (!parts || parts.has(normalized))
142354
+ return normalized;
142355
+ const key2 = partUriComparisonKey(normalized);
142356
+ for (const partUri of parts.keys()) {
142357
+ if (partUriComparisonKey(partUri) === key2)
142358
+ return partUri;
142359
+ }
142360
+ return normalized;
142361
+ }
142362
+ function findPartUriCollisions(uris) {
142363
+ const seen = new Set;
142364
+ const collisions = [];
142365
+ for (const uri of uris) {
142366
+ const key2 = partUriComparisonKey(uri);
142367
+ if (seen.has(key2))
142368
+ collisions.push(uri);
142369
+ else
142370
+ seen.add(key2);
142371
+ }
142372
+ return collisions;
142373
+ }
142374
+ function resolveTargetUri(baseUri, target, targetMode, parts) {
142904
142375
  if (targetMode === "External")
142905
142376
  return target;
142906
142377
  if (target.startsWith("/"))
142907
- return normalizePartUri(target);
142378
+ return resolveRegisteredPartUri(target, parts);
142908
142379
  const base2 = normalizePartUri(baseUri);
142909
142380
  const baseDir = base2.replace(/\/[^/]*$/, "");
142910
- const parts = (baseDir + "/" + target).split("/");
142381
+ const segments = (baseDir + "/" + target).split("/");
142911
142382
  const stack = [];
142912
- for (const p of parts) {
142383
+ for (const p of segments) {
142913
142384
  if (p === "" || p === ".")
142914
142385
  continue;
142915
142386
  if (p === "..") {
@@ -142918,7 +142389,7 @@ function resolveTargetUri(baseUri, target, targetMode) {
142918
142389
  }
142919
142390
  stack.push(p);
142920
142391
  }
142921
- return "/" + stack.join("/");
142392
+ return resolveRegisteredPartUri("/" + stack.join("/"), parts);
142922
142393
  }
142923
142394
  function partDirOf(uri) {
142924
142395
  const n = normalizePartUri(uri);
@@ -144330,10 +143801,10 @@ function scanMaxNumericXmlId(xml) {
144330
143801
  return max;
144331
143802
  }
144332
143803
  function scanMaxWordIdInBytes(bytes) {
144333
- return scanMaxNumericXmlId(TD9.decode(bytes));
143804
+ return scanMaxNumericXmlId(TD8.decode(bytes));
144334
143805
  }
144335
143806
  function observeRevisionWIdsFromBytes(state, bytes) {
144336
- observeRevisionWIdsFromXml(state, TD9.decode(bytes));
143807
+ observeRevisionWIdsFromXml(state, TD8.decode(bytes));
144337
143808
  }
144338
143809
  function observeRevisionWIdsFromXml(state, xml) {
144339
143810
  const reservation = state.idReservations.revisionWIds;
@@ -144348,11 +143819,11 @@ function observeRevisionWIdsFromXml(state, xml) {
144348
143819
  if (max > reservation.max)
144349
143820
  reservation.max = max;
144350
143821
  }
144351
- var TD9, NUMERIC_XML_ID_RE, CONTENT_CONTROL_ID_RE;
143822
+ var TD8, NUMERIC_XML_ID_RE, CONTENT_CONTROL_ID_RE;
144352
143823
  var init_revision_wid_scan = __esm(() => {
144353
143824
  init_src2();
144354
143825
  init_xml_text();
144355
- TD9 = new TextDecoder;
143826
+ TD8 = new TextDecoder;
144356
143827
  NUMERIC_XML_ID_RE = /\b(?:[\w.-]+:)?id\s*=\s*(["'])([^"']*)\1/g;
144357
143828
  CONTENT_CONTROL_ID_RE = /<(?:[\w.-]+:)?id(?=[\s/>])[^>]*?\b(?:[\w.-]+:)?val\s*=\s*(["'])([^"']*)\1/g;
144358
143829
  });
@@ -144440,7 +143911,7 @@ function normalizeParagraphParaIds(xml, allocatorSeedXml, options = {}) {
144440
143911
  };
144441
143912
  }
144442
143913
  function bindParagraphIndexScanFacts(sourceBytes, facts) {
144443
- const encoder2 = new TextEncoder;
143914
+ const encoder = new TextEncoder;
144444
143915
  const offsets = new Set([0, facts.sourceXml.length]);
144445
143916
  for (const paragraph of facts.paragraphs) {
144446
143917
  if (!Number.isSafeInteger(paragraph.start) || !Number.isSafeInteger(paragraph.openEnd) || !Number.isSafeInteger(paragraph.end) || paragraph.start < 0 || paragraph.openEnd <= paragraph.start || paragraph.end < paragraph.openEnd || paragraph.end > facts.sourceXml.length)
@@ -144468,7 +143939,7 @@ function bindParagraphIndexScanFacts(sourceBytes, facts) {
144468
143939
  for (const charOffset of [...offsets].sort((left, right) => left - right)) {
144469
143940
  if (charOffset < charCursor)
144470
143941
  return null;
144471
- const encoded = encoder2.encode(facts.sourceXml.slice(charCursor, charOffset));
143942
+ const encoded = encoder.encode(facts.sourceXml.slice(charCursor, charOffset));
144472
143943
  if (byteCursor + encoded.byteLength > sourceBytes.byteLength)
144473
143944
  return null;
144474
143945
  for (let index = 0;index < encoded.byteLength; index += 1) {
@@ -145648,7 +145119,7 @@ function normalizeForCompare(uri) {
145648
145119
  return uri.startsWith("/") ? uri : `/${uri}`;
145649
145120
  }
145650
145121
  function scanTextboxes(input) {
145651
- const xml = TD10.decode(input.bytes);
145122
+ const xml = TD9.decode(input.bytes);
145652
145123
  return scanTextboxesFromXml({
145653
145124
  xml,
145654
145125
  byteLength: input.bytes.byteLength,
@@ -145847,7 +145318,7 @@ function lastIndexOfRegex(s, re) {
145847
145318
  function leadingUtf8BomLength3(bytes) {
145848
145319
  return bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? 3 : 0;
145849
145320
  }
145850
- var TEXTBOX_FAMILY_POLICY, TD10;
145321
+ var TEXTBOX_FAMILY_POLICY, TD9;
145851
145322
  var init_textbox_discovery = __esm(() => {
145852
145323
  TEXTBOX_FAMILY_POLICY = {
145853
145324
  "drawingml-body": { supported: true, rejection: null },
@@ -145860,12 +145331,12 @@ var init_textbox_discovery = __esm(() => {
145860
145331
  "mce-fallback": { supported: false, rejection: "textbox-mce-fallback" },
145861
145332
  unknown: { supported: false, rejection: "textbox-unknown-shape-unsupported" }
145862
145333
  };
145863
- TD10 = new TextDecoder("utf-8", { fatal: false });
145334
+ TD9 = new TextDecoder("utf-8", { fatal: false });
145864
145335
  });
145865
145336
 
145866
145337
  // ../../../v2/editor-core/dist/document/textbox-paragraph-signature.js
145867
145338
  function textboxParagraphLogicalSignature(bytes, namespaceBindings = COMMON_NAMESPACE_BINDINGS) {
145868
- const paragraphXml = TD11.decode(bytes);
145339
+ const paragraphXml = TD10.decode(bytes);
145869
145340
  const paragraphNamespaceBindings = textboxNamespaceBindingsFromXml(paragraphXml, namespaceBindings);
145870
145341
  const model = parseParagraphInlineMap(paragraphXml);
145871
145342
  return JSON.stringify({
@@ -145876,7 +145347,7 @@ function textboxParagraphLogicalSignature(bytes, namespaceBindings = COMMON_NAME
145876
145347
  }
145877
145348
  function textboxNamespaceBindingsFromPartBytes(bytes) {
145878
145349
  const rootPrefix = bytes.subarray(0, Math.min(bytes.byteLength, 64 * 1024));
145879
- return textboxNamespaceBindingsFromPartXml(TD11.decode(rootPrefix));
145350
+ return textboxNamespaceBindingsFromPartXml(TD10.decode(rootPrefix));
145880
145351
  }
145881
145352
  function textboxNamespaceBindingsFromPartXml(xml) {
145882
145353
  const rootTag = /<(?:[\w.-]+:)?(?:document|hdr|ftr)\b[^>]*>/iu.exec(xml)?.[0];
@@ -145960,7 +145431,7 @@ function containerSemanticMetadata(piece, namespaceBindings) {
145960
145431
  return null;
145961
145432
  }
145962
145433
  function canonicalXmlMetadata(xml, namespaceBindings, defaultAttributeValues) {
145963
- const metadata2 = [];
145434
+ const metadata = [];
145964
145435
  const trimmedXml = xml.trim();
145965
145436
  const parseableXml = /^<[^>]+>$/u.test(trimmedXml) && !/\/>$/u.test(trimmedXml) ? trimmedXml.replace(/>$/u, "/>") : xml;
145966
145437
  const result = walkXmlElements(parseableXml, {
@@ -145971,7 +145442,7 @@ function canonicalXmlMetadata(xml, namespaceBindings, defaultAttributeValues) {
145971
145442
  expandedXmlName(attribute.namespaceUri, attribute.localName, attribute.name),
145972
145443
  attribute.value
145973
145444
  ]).filter(([name, value]) => defaultAttributeValues?.get(name) !== value).sort(([leftName, leftValue], [rightName, rightValue]) => leftName.localeCompare(rightName) || leftValue.localeCompare(rightValue));
145974
- metadata2.push({
145445
+ metadata.push({
145975
145446
  name: expandedXmlName(tag.namespaceUri, tag.localName, tag.name),
145976
145447
  selfClosing: tag.isSelfClosing,
145977
145448
  attributes
@@ -145980,13 +145451,13 @@ function canonicalXmlMetadata(xml, namespaceBindings, defaultAttributeValues) {
145980
145451
  onCloseTag: ({ tag }) => {
145981
145452
  if (tag.isSelfClosing)
145982
145453
  return;
145983
- metadata2.push({
145454
+ metadata.push({
145984
145455
  name: expandedXmlName(tag.namespaceUri, tag.localName, tag.name),
145985
145456
  closing: true
145986
145457
  });
145987
145458
  }
145988
145459
  });
145989
- return result.errors.length === 0 ? metadata2 : [{ rawXml: xml }];
145460
+ return result.errors.length === 0 ? metadata : [{ rawXml: xml }];
145990
145461
  }
145991
145462
  function expandedXmlName(namespaceUri, localName2, qualifiedName) {
145992
145463
  return namespaceUri ? `{${namespaceUri}}${localName2}` : qualifiedName;
@@ -146008,11 +145479,11 @@ function textboxNamespaceBindingsFromXml(xml, inheritedBindings) {
146008
145479
  function unhandledPiece(piece) {
146009
145480
  throw new Error(`Unhandled textbox paragraph piece: ${JSON.stringify(piece)}`);
146010
145481
  }
146011
- var TD11, XMLNS_NAMESPACE2 = "http://www.w3.org/2000/xmlns/", COMMON_NAMESPACE_BINDINGS, BREAK_DEFAULT_ATTRIBUTE_VALUES;
145482
+ var TD10, XMLNS_NAMESPACE2 = "http://www.w3.org/2000/xmlns/", COMMON_NAMESPACE_BINDINGS, BREAK_DEFAULT_ATTRIBUTE_VALUES;
146012
145483
  var init_textbox_paragraph_signature = __esm(() => {
146013
145484
  init_paragraph_inline_model();
146014
145485
  init_xml_sax();
146015
- TD11 = new TextDecoder;
145486
+ TD10 = new TextDecoder;
146016
145487
  COMMON_NAMESPACE_BINDINGS = {
146017
145488
  w: NS_W,
146018
145489
  r: NS_R
@@ -146316,12 +145787,12 @@ var init_exact_part_mutation_proof = __esm(() => {
146316
145787
 
146317
145788
  // ../../../v2/editor-core/dist/document/textbox-registry.js
146318
145789
  function containsTextboxContent(bytes) {
146319
- return containsTextboxContentXml(TD12.decode(bytes));
145790
+ return containsTextboxContentXml(TD11.decode(bytes));
146320
145791
  }
146321
145792
  function buildTextboxRegistry(parts) {
146322
145793
  const records = [];
146323
145794
  for (const part of parts) {
146324
- const xml = TD12.decode(part.bytes);
145795
+ const xml = TD11.decode(part.bytes);
146325
145796
  if (!containsTextboxContentXml(xml))
146326
145797
  continue;
146327
145798
  const bomLength = leadingUtf8BomLength4(part.bytes);
@@ -147809,14 +147280,14 @@ var __classPrivateFieldSet4 = function(receiver, state, value, kind, f) {
147809
147280
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
147810
147281
  throw new TypeError("Cannot read private member from an object whose class did not declare it");
147811
147282
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
147812
- }, _SDLazyReadonlyMap_source, _SDLazyReadonlyMap_resolve, TD12, TE4, MIN_COORDINATE_EMU = -27273042329600, MAX_COORDINATE_EMU = 27273042316900, TEXTBOX_REGISTRY_RANGE_PLANE, EMPTY_TEXTBOX_STORY_RANGES, EMPTY_TEXTBOX_AUXILIARY_STORY_EFFECTS, SDLazyReadonlyMap;
147283
+ }, _SDLazyReadonlyMap_source, _SDLazyReadonlyMap_resolve, TD11, TE4, MIN_COORDINATE_EMU = -27273042329600, MAX_COORDINATE_EMU = 27273042316900, TEXTBOX_REGISTRY_RANGE_PLANE, EMPTY_TEXTBOX_STORY_RANGES, EMPTY_TEXTBOX_AUXILIARY_STORY_EFFECTS, SDLazyReadonlyMap;
147813
147284
  var init_textbox_registry = __esm(() => {
147814
147285
  init_textbox_discovery();
147815
147286
  init_paragraph_index();
147816
147287
  init_sha256_sync();
147817
147288
  init_textbox_paragraph_signature();
147818
147289
  init_exact_part_mutation_proof();
147819
- TD12 = new TextDecoder("utf-8", { fatal: false });
147290
+ TD11 = new TextDecoder("utf-8", { fatal: false });
147820
147291
  TE4 = new TextEncoder;
147821
147292
  TEXTBOX_REGISTRY_RANGE_PLANE = Symbol("textbox-registry-range-plane");
147822
147293
  EMPTY_TEXTBOX_STORY_RANGES = new Map;
@@ -148460,13 +147931,13 @@ function emptyPageNumbering() {
148460
147931
  };
148461
147932
  }
148462
147933
  function decodeRange(buf, start, end) {
148463
- return TD13.decode(buf.subarray(start, end));
147934
+ return TD12.decode(buf.subarray(start, end));
148464
147935
  }
148465
- var TD13;
147936
+ var TD12;
148466
147937
  var init_sectpr_parser = __esm(() => {
148467
147938
  init_xml_sax();
148468
147939
  init_diagnostics();
148469
- TD13 = new TextDecoder("utf-8", { fatal: false });
147940
+ TD12 = new TextDecoder("utf-8", { fatal: false });
148470
147941
  });
148471
147942
 
148472
147943
  // ../../../v2/editor-core/dist/document/source-signals/chunk-scanner.js
@@ -148483,7 +147954,7 @@ function scanChunkXml(buf, chunk, documentStartTagXml, bodyStartTagXml, options
148483
147954
  result.hadDiagnostics = true;
148484
147955
  return result;
148485
147956
  }
148486
- const xml = TD14.decode(buf.subarray(chunk.byteStart, chunk.byteEnd));
147957
+ const xml = TD13.decode(buf.subarray(chunk.byteStart, chunk.byteEnd));
148487
147958
  const bodyOpen = normalizeOpenStartTag(bodyStartTagXml);
148488
147959
  const bodyQ = qnameFromStartTag(bodyOpen);
148489
147960
  const docQ = qnameFromStartTag(documentStartTagXml);
@@ -148940,10 +148411,10 @@ function normalizeOpenStartTag(startTagXml) {
148940
148411
  function readRelationshipAttrValue(tag, local) {
148941
148412
  return readXmlAttribute(tag, NS_R, local)?.value ?? readXmlAttribute(tag, NS_RSTRICT, local)?.value ?? null;
148942
148413
  }
148943
- var TD14;
148414
+ var TD13;
148944
148415
  var init_chunk_scanner = __esm(() => {
148945
148416
  init_xml_sax();
148946
- TD14 = new TextDecoder("utf-8", { fatal: false });
148417
+ TD13 = new TextDecoder("utf-8", { fatal: false });
148947
148418
  });
148948
148419
 
148949
148420
  // ../../../v2/editor-core/dist/document/source-signals/section-coordinate-plane.js
@@ -149765,18 +149236,18 @@ function normalizeResidentBootstrapSliceParagraphIds(state, input) {
149765
149236
  const paragraphNamespaces = readyParagraphNamespaceBindings(input.sourceBytes, input.scan);
149766
149237
  if (!paragraphNamespaces || paragraphNamespaces.length !== input.index.entries.length)
149767
149238
  return null;
149768
- const decoder3 = new TextDecoder("utf-8", { fatal: false });
149239
+ const decoder2 = new TextDecoder("utf-8", { fatal: false });
149769
149240
  const seeds = [];
149770
149241
  for (const [uri, part2] of state.parts) {
149771
149242
  if (!["document", "header", "footer", "footnotes", "endnotes"].includes(part2.descriptor.kind))
149772
149243
  continue;
149773
149244
  const bytes = uri === input.partUri ? input.sourceBytes : state.packageBytes.get(uri);
149774
149245
  if (bytes)
149775
- seeds.push(decoder3.decode(bytes));
149246
+ seeds.push(decoder2.decode(bytes));
149776
149247
  }
149777
149248
  const allocParaId = createImportParaIdAllocator(seeds);
149778
149249
  const replacements = [];
149779
- const encoder2 = new TextEncoder;
149250
+ const encoder = new TextEncoder;
149780
149251
  for (let entryOrdinal = 0;entryOrdinal < source.length; entryOrdinal += 1) {
149781
149252
  if (!source.readInto(entryOrdinal, entry))
149782
149253
  return null;
@@ -149786,7 +149257,7 @@ function normalizeResidentBootstrapSliceParagraphIds(state, input) {
149786
149257
  if (!fragmentNamespaces)
149787
149258
  return null;
149788
149259
  const paragraphBytes = input.sourceBytes.subarray(entry.byteStart, entry.byteEnd);
149789
- const normalized = ensureParagraphParaIds(decoder3.decode(paragraphBytes), allocParaId, {
149260
+ const normalized = ensureParagraphParaIds(decoder2.decode(paragraphBytes), allocParaId, {
149790
149261
  namespacePlacement: "paragraph-local",
149791
149262
  fragmentNamespaces
149792
149263
  });
@@ -149796,7 +149267,7 @@ function normalizeResidentBootstrapSliceParagraphIds(state, input) {
149796
149267
  currentStart: entry.byteStart,
149797
149268
  currentEnd: entry.byteEnd,
149798
149269
  bodyChildOrdinal: entry.containingBodyChildOrdinal,
149799
- bytes: encoder2.encode(normalized.xml)
149270
+ bytes: encoder.encode(normalized.xml)
149800
149271
  });
149801
149272
  }
149802
149273
  const staged = stageSDSourceBackedOverlayReplacements({ overlay, replacements });
@@ -150093,7 +149564,7 @@ function attachChunkBodyChildOrdinals(records, bytes, chunk) {
150093
149564
  if (records.length === 0)
150094
149565
  return [];
150095
149566
  const xml = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
150096
- const encoder2 = new TextEncoder;
149567
+ const encoder = new TextEncoder;
150097
149568
  const children = [];
150098
149569
  let cursor = 0;
150099
149570
  let charCursor = 0;
@@ -150109,9 +149580,9 @@ function attachChunkBodyChildOrdinals(records, bytes, chunk) {
150109
149580
  continue;
150110
149581
  }
150111
149582
  if (node2.kind === "element") {
150112
- relativeByteCursor += encoder2.encode(xml.slice(charCursor, startChar)).byteLength;
149583
+ relativeByteCursor += encoder.encode(xml.slice(charCursor, startChar)).byteLength;
150113
149584
  const start = chunk.byteStart + relativeByteCursor;
150114
- relativeByteCursor += encoder2.encode(xml.slice(startChar, node2.end)).byteLength;
149585
+ relativeByteCursor += encoder.encode(xml.slice(startChar, node2.end)).byteLength;
150115
149586
  children.push({
150116
149587
  byteStart: start,
150117
149588
  byteEnd: chunk.byteStart + relativeByteCursor,
@@ -150789,11 +150260,11 @@ function rebaseDocumentOverviewCoordinates(overview, previousStory, currentStory
150789
150260
  const likelyExhibits = rebaseDisjointStorySourceSignals(overview.likelyExhibits, previousStory, currentStory.storyRevision, partRevision, splice);
150790
150261
  if (headings.length > 0 && headings === overview.headings || likelyExhibits.length > 0 && likelyExhibits === overview.likelyExhibits)
150791
150262
  return overview;
150792
- const anchorKey2 = (anchor) => anchor.stability === "byte-span" ? `${anchor.storyId}:${anchor.partId}:${anchor.byteSpan[0]}:${anchor.byteSpan[1]}` : null;
150263
+ const anchorKey = (anchor) => anchor.stability === "byte-span" ? `${anchor.storyId}:${anchor.partId}:${anchor.byteSpan[0]}:${anchor.byteSpan[1]}` : null;
150793
150264
  const evidenceAnchors = new Map;
150794
150265
  for (const [before, after] of [[overview.headings, headings], [overview.likelyExhibits, likelyExhibits]]) {
150795
150266
  for (let index = 0;index < before.length; index += 1) {
150796
- const key2 = anchorKey2(before[index].sourceAnchor);
150267
+ const key2 = anchorKey(before[index].sourceAnchor);
150797
150268
  if (key2)
150798
150269
  evidenceAnchors.set(key2, after[index].sourceAnchor);
150799
150270
  }
@@ -150804,9 +150275,9 @@ function rebaseDocumentOverviewCoordinates(overview, previousStory, currentStory
150804
150275
  const index = sectionOrdinals.get(summary.sectionId);
150805
150276
  const before = index == null ? undefined : previousStory.sections[index];
150806
150277
  const after = index == null ? undefined : currentStory.sections[index];
150807
- if (!before || !after || anchorKey2(summary.sourceAnchor) !== anchorKey2(before.sourceAnchor) || after.sourceAnchor.stability !== "byte-span" || after.sourceAnchor.storyRevision !== currentStory.storyRevision || after.sourceAnchor.partRevision !== partRevision)
150278
+ if (!before || !after || anchorKey(summary.sourceAnchor) !== anchorKey(before.sourceAnchor) || after.sourceAnchor.stability !== "byte-span" || after.sourceAnchor.storyRevision !== currentStory.storyRevision || after.sourceAnchor.partRevision !== partRevision)
150808
150279
  return overview;
150809
- const evidenceKey = summary.title.evidenceAnchor ? anchorKey2(summary.title.evidenceAnchor) : null;
150280
+ const evidenceKey = summary.title.evidenceAnchor ? anchorKey(summary.title.evidenceAnchor) : null;
150810
150281
  const evidenceAnchor = evidenceKey ? evidenceAnchors.get(evidenceKey) : null;
150811
150282
  if (summary.title.evidenceAnchor && !evidenceAnchor)
150812
150283
  return overview;
@@ -151154,9 +150625,9 @@ function locateFinalSectPrInRetainedChunk(bytes, chunkStart, chunkEnd) {
151154
150625
  const node2 = readXmlNodeAt(chunkXml, startChar);
151155
150626
  if (node2?.kind !== "element" || node2.qname.split(":").at(-1) !== "sectPr")
151156
150627
  return null;
151157
- const encoder2 = new TextEncoder;
151158
- const byteStart = chunkStart + encoder2.encode(chunkXml.slice(0, startChar)).byteLength;
151159
- const byteEnd = byteStart + encoder2.encode(chunkXml.slice(startChar, node2.end)).byteLength;
150628
+ const encoder = new TextEncoder;
150629
+ const byteStart = chunkStart + encoder.encode(chunkXml.slice(0, startChar)).byteLength;
150630
+ const byteEnd = byteStart + encoder.encode(chunkXml.slice(startChar, node2.end)).byteLength;
151160
150631
  if (byteEnd !== chunkEnd)
151161
150632
  return null;
151162
150633
  return { xml: chunkXml.slice(startChar, node2.end), byteStart, byteEnd };
@@ -151172,7 +150643,7 @@ function resolveRefreshedHeaderFooterRefs(state, ownerPartId, sectionId, refs) {
151172
150643
  const parsed = parseRelationshipsXml(new TextDecoder("utf-8", { fatal: false }).decode(relsBytes), {
151173
150644
  ownerPartUri: ownerPartId,
151174
150645
  relsUri: ownerRelsUri,
151175
- resolveTarget: (target, mode) => resolveTargetUri(ownerPartId, target, mode)
150646
+ resolveTarget: (target, mode) => resolveTargetUri(ownerPartId, target, mode, state.parts)
151176
150647
  });
151177
150648
  if (parsed.parseError || parsed.duplicateIds.length > 0) {
151178
150649
  return refs.map((ref3) => ({ ...ref3, sectionId, targetStatus: "failed" }));
@@ -152302,15 +151773,15 @@ function mergeMainStoryPayloadIntoState(state, partUri, bytes, options = {}) {
152302
151773
  options.onParagraphIndexFactsOutcome?.("not-applicable");
152303
151774
  return null;
152304
151775
  }
152305
- const decoder3 = new TextDecoder("utf-8", { fatal: false });
152306
- const xml = decoder3.decode(bytes);
151776
+ const decoder2 = new TextDecoder("utf-8", { fatal: false });
151777
+ const xml = decoder2.decode(bytes);
152307
151778
  const allocatorSeedXml = [];
152308
151779
  for (const [uri, part] of state.parts) {
152309
151780
  if (uri === partUri || !PARA_ID_SEED_PART_KINDS.has(part.descriptor.kind))
152310
151781
  continue;
152311
151782
  const partBytes = state.packageBytes.get(uri);
152312
151783
  if (partBytes)
152313
- allocatorSeedXml.push(decoder3.decode(partBytes));
151784
+ allocatorSeedXml.push(decoder2.decode(partBytes));
152314
151785
  }
152315
151786
  const normalized = normalizeParagraphParaIds(xml, allocatorSeedXml, {
152316
151787
  ...options.preserveBootstrapSliceOffsets ? { namespacePlacement: "paragraph-local" } : {},
@@ -152470,6 +151941,596 @@ var init_sd_document_state = __esm(() => {
152470
151941
  PARA_ID_SEED_PART_KINDS = new Set(["document", "header", "footer", "footnotes", "endnotes"]);
152471
151942
  });
152472
151943
 
151944
+ // ../../../v2/editor-core/dist/document/transactions/whole-body-text-replacement.js
151945
+ function prepareWholeBodyTextReplacement(state, source, perPart, retainedProof) {
151946
+ if (source.operationId !== "range-ref-whole-body-replace" || source.family !== "storyBlocks" || source.storyIds.length !== 1 || source.storyPartOwnership.length !== 1 || Object.keys(perPart).length !== 1)
151947
+ return null;
151948
+ const storyId = source.storyIds[0];
151949
+ const owner = source.storyPartOwnership[0];
151950
+ const story = state.stories.get(storyId);
151951
+ if (owner.storyId !== storyId || owner.partUri !== "/word/document.xml" || story?.descriptor.storyKind !== "main" || story.descriptor.ownerPartUri !== owner.partUri)
151952
+ return null;
151953
+ const bytes = state.packageBytes.get(owner.partUri);
151954
+ const entry = perPart[owner.partUri];
151955
+ if (!bytes || entry?.kind !== "modify" || entry.patches.length !== 1)
151956
+ return null;
151957
+ const patch = entry.patches[0];
151958
+ if (retainedProof && retainedProof.storyId !== storyId)
151959
+ return null;
151960
+ if (patch.kind === "insertBytes") {
151961
+ if (!retainedProof || patch.atByte < 0 || patch.atByte > bytes.length)
151962
+ return null;
151963
+ } else {
151964
+ if (patch.startByte < 0 || patch.endByte < patch.startByte || patch.endByte > bytes.length)
151965
+ return null;
151966
+ if (!retainedProof && (patch.kind !== "replaceBytes" || patch.startByte !== 0 || patch.endByte !== bytes.length))
151967
+ return null;
151968
+ }
151969
+ const index = getStoryParagraphIndexFromState(state, storyId);
151970
+ const targets = new Set(source.targetBlockIds);
151971
+ if (!index?.entries.length || index.entries.some((paragraph) => !targets.has(paragraph.blockId)))
151972
+ return null;
151973
+ return { storyId };
151974
+ }
151975
+ var init_whole_body_text_replacement = __esm(() => {
151976
+ init_sd_document_state();
151977
+ });
151978
+
151979
+ // ../../../v2/editor-core/dist/document/transactions/header-footer-update.js
151980
+ function prepareHeaderFooterUpdate(state, source, perPart, historyDirection) {
151981
+ if (source.operationId !== "watermarks-apply" || source.family !== "storyImage" || source.changeMode === "tracked" || !state.mainStoryId)
151982
+ return null;
151983
+ const headerUris = Object.keys(perPart).filter((uri) => /^\/word\/header\d+\.xml$/.test(uri));
151984
+ if (headerUris.length === 0 || Object.keys(perPart).some((uri) => uri !== DOCUMENT && uri !== "[Content_Types].xml" && uri !== "/[Content_Types].xml" && uri !== "/word/_rels/document.xml.rels" && !headerUris.includes(uri) && !/^\/word\/_rels\/header\d+\.xml\.rels$/.test(uri) && !uri.startsWith("/word/media/")))
151985
+ return null;
151986
+ const headers = [];
151987
+ for (const partUri of headerUris) {
151988
+ const current = state.packageBytes.get(partUri);
151989
+ const next = applyEntry(current, perPart[partUri]);
151990
+ if (next === undefined)
151991
+ return null;
151992
+ const before = current ? readHeader(current) : null;
151993
+ const after = next ? readHeader(next) : null;
151994
+ if (current && !before || next && !after)
151995
+ return null;
151996
+ if (before && after) {
151997
+ if (before.shell !== after.shell)
151998
+ return null;
151999
+ const requiredBindings = historyDirection === "undo" ? after.namespaces : before.namespaces;
152000
+ const retainedBindings = historyDirection === "undo" ? before.namespaces : after.namespaces;
152001
+ if (Object.entries(requiredBindings).some(([prefix, uri]) => retainedBindings[prefix] !== uri))
152002
+ return null;
152003
+ }
152004
+ const oldBlocks = new Map(before?.paragraphs.map((p) => [p.id, p.xml]) ?? []);
152005
+ const newBlocks = new Map(after?.paragraphs.map((p) => [p.id, p.xml]) ?? []);
152006
+ const oldOrder = [...oldBlocks.keys()].filter((id) => newBlocks.has(id));
152007
+ const newOrder = [...newBlocks.keys()].filter((id) => oldBlocks.has(id));
152008
+ if (oldOrder.some((id, index) => newOrder[index] !== id))
152009
+ return null;
152010
+ headers.push({
152011
+ partUri,
152012
+ storyId: `header:${partUri}`,
152013
+ created: !current && next != null,
152014
+ removed: next == null,
152015
+ addedBlockIds: [...newBlocks.keys()].filter((id) => !oldBlocks.has(id)),
152016
+ removedBlockIds: [...oldBlocks.keys()].filter((id) => !newBlocks.has(id)),
152017
+ changedBlockIds: [...newBlocks.keys()].filter((id) => oldBlocks.get(id) !== newBlocks.get(id))
152018
+ });
152019
+ }
152020
+ let sectionBlockIds = [];
152021
+ let finalSectionChanged = false;
152022
+ if (perPart[DOCUMENT]) {
152023
+ const current = state.packageBytes.get(DOCUMENT);
152024
+ const next = applyEntry(current, perPart[DOCUMENT]);
152025
+ if (!current || !next)
152026
+ return null;
152027
+ const before = readSections(TD14.decode(current));
152028
+ const after = readSections(TD14.decode(next));
152029
+ if (!before || !after || before.shell !== after.shell || before.sections.length !== after.sections.length)
152030
+ return null;
152031
+ for (let index = 0;index < before.sections.length; index++) {
152032
+ const previous = before.sections[index];
152033
+ const following = after.sections[index];
152034
+ if (previous.blockId !== following.blockId)
152035
+ return null;
152036
+ if (previous.xml === following.xml)
152037
+ continue;
152038
+ if (previous.blockId == null)
152039
+ finalSectionChanged = true;
152040
+ else
152041
+ sectionBlockIds.push(previous.blockId);
152042
+ }
152043
+ sectionBlockIds = [...new Set(sectionBlockIds)];
152044
+ }
152045
+ return { mainStoryId: state.mainStoryId, headers, sectionBlockIds, finalSectionChanged };
152046
+ }
152047
+ function applyEntry(current, entry) {
152048
+ if (entry.kind === "remove")
152049
+ return current ? null : undefined;
152050
+ if (entry.kind === "create")
152051
+ return current ? undefined : entry.bytes;
152052
+ if (!current)
152053
+ return;
152054
+ const normalized = normalizePartPatches([...entry.patches]);
152055
+ if (!normalized.ok)
152056
+ return;
152057
+ const applied = applyNormalizedPatches({ bytes: current, patches: normalized.value });
152058
+ return applied.ok ? applied.value : undefined;
152059
+ }
152060
+ function paragraphId(range) {
152061
+ return range.tag.attributes.find((attr2) => attr2.namespaceUri === W142 && attr2.localName === "paraId")?.value ?? null;
152062
+ }
152063
+ function readHeader(bytes) {
152064
+ const xml = TD14.decode(bytes);
152065
+ const parsed = collectXmlElementRanges(xml);
152066
+ if (parsed.errors.length)
152067
+ return null;
152068
+ const roots = parsed.ranges.filter((range) => range.tag.namespaceUri === W3 && range.tag.localName === "hdr");
152069
+ const root = roots[0];
152070
+ if (roots.length !== 1 || !root || parsed.ranges.some((range) => range.start < root.start || range.end > root.end))
152071
+ return null;
152072
+ const all = parsed.ranges.filter((range) => range.tag.namespaceUri === W3 && range.tag.localName === "p").sort((a, b) => a.start - b.start);
152073
+ const topLevel = [];
152074
+ for (const range of all)
152075
+ if (range.start >= (topLevel.at(-1)?.end ?? -1))
152076
+ topLevel.push(range);
152077
+ const paragraphs = [];
152078
+ const rootOpening = xml.slice(root.start, root.openEnd).replace(/\s+xmlns(?::[\w.-]+)?\s*=\s*(?:"[^"]*"|'[^']*')/g, "");
152079
+ let shell = xml.slice(0, root.start) + rootOpening;
152080
+ let cursor = root.openEnd;
152081
+ for (const range of topLevel) {
152082
+ const id = paragraphId(range);
152083
+ if (!id || paragraphs.some((p) => p.id === id))
152084
+ return null;
152085
+ paragraphs.push({ id, xml: xml.slice(range.start, range.end) });
152086
+ shell += xml.slice(cursor, range.start);
152087
+ cursor = range.end;
152088
+ }
152089
+ shell += xml.slice(cursor);
152090
+ return { paragraphs, shell, namespaces: root.namespaceBindings };
152091
+ }
152092
+ function readSections(xml) {
152093
+ const parsed = collectXmlElementRanges(xml);
152094
+ if (parsed.errors.length)
152095
+ return null;
152096
+ const ranges = parsed.ranges.filter((range) => range.tag.namespaceUri === W3 && range.tag.localName === "sectPr").sort((a, b) => a.start - b.start);
152097
+ const sections = [];
152098
+ let shell = "";
152099
+ let cursor = 0;
152100
+ for (const range of ranges) {
152101
+ if (range.start < cursor)
152102
+ return null;
152103
+ const parent = parsed.ranges.filter((candidate) => candidate.start < range.start && candidate.end > range.end).sort((a, b) => b.start - a.start)[0];
152104
+ if (!parent || parent.tag.namespaceUri !== W3 || !["body", "pPr"].includes(parent.tag.localName))
152105
+ return null;
152106
+ const paragraph = parent.tag.localName === "pPr" ? parsed.ranges.find((candidate) => candidate.tag.namespaceUri === W3 && candidate.tag.localName === "p" && candidate.start < parent.start && candidate.end > parent.end) : null;
152107
+ const blockId = paragraph ? paragraphId(paragraph) : null;
152108
+ if (parent.tag.localName === "pPr" && !blockId)
152109
+ return null;
152110
+ sections.push({ blockId, xml: xml.slice(range.start, range.end) });
152111
+ const refs = parsed.ranges.filter((candidate) => candidate.start > range.start && candidate.end <= range.closeStart && candidate.tag.namespaceUri === W3 && candidate.tag.localName === "headerReference");
152112
+ let inner = "";
152113
+ let innerCursor = range.openEnd;
152114
+ for (const ref3 of refs.sort((a, b) => a.start - b.start)) {
152115
+ const enclosing = parsed.ranges.some((candidate) => candidate.start > range.start && candidate.start < ref3.start && candidate.end > ref3.end);
152116
+ if (enclosing)
152117
+ return null;
152118
+ inner += xml.slice(innerCursor, ref3.start);
152119
+ innerCursor = ref3.end;
152120
+ }
152121
+ inner += xml.slice(innerCursor, range.closeStart);
152122
+ const opening = xml.slice(range.start, range.openEnd).replace(/\s*\/>$/, ">");
152123
+ shell += xml.slice(cursor, range.start) + opening + inner + `</${range.tag.name}>`;
152124
+ cursor = range.end;
152125
+ }
152126
+ shell += xml.slice(cursor);
152127
+ return { sections, shell };
152128
+ }
152129
+ var TD14, W3 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", W142 = "http://schemas.microsoft.com/office/word/2010/wordml", DOCUMENT = "/word/document.xml";
152130
+ var init_header_footer_update = __esm(() => {
152131
+ init_xml_sax();
152132
+ init_patch_substrate();
152133
+ TD14 = new TextDecoder;
152134
+ });
152135
+
152136
+ // ../../../v2/editor-core/dist/document/session-hyperlink-metadata.js
152137
+ function createSessionHyperlinkReviewTracker(state) {
152138
+ const links = state.sessionHyperlinkMetadata?.links;
152139
+ return links?.length ? { links, changed: new Set } : null;
152140
+ }
152141
+ function trackSessionHyperlinkReviewSplice(tracker, partUri, xml, start, end, replacement) {
152142
+ if (!tracker || !tracker.links.some((link) => link.anchors.some((anchor) => anchor.partUri === partUri)))
152143
+ return;
152144
+ const startByte = utf8Length(xml, start);
152145
+ const endByte = startByte + utf8Length(xml.slice(start, end));
152146
+ let beforeBytes;
152147
+ const patch = {
152148
+ kind: "replaceBytes",
152149
+ order: 0,
152150
+ startByte,
152151
+ endByte,
152152
+ bytes: encoder.encode(replacement)
152153
+ };
152154
+ tracker.links = tracker.links.flatMap((link) => {
152155
+ const anchors = link.anchors.flatMap((anchor) => {
152156
+ if (anchor.partUri !== partUri)
152157
+ return [anchor];
152158
+ const mapped = mapThroughPatches(anchor, (offset) => {
152159
+ beforeBytes ?? (beforeBytes = encoder.encode(xml.slice(start, end)));
152160
+ return beforeBytes[offset - startByte];
152161
+ }, [patch], true);
152162
+ return mapped ? [mapped] : [];
152163
+ });
152164
+ if (anchors.length === link.anchors.length && anchors.every((anchor, index) => sameAnchor(anchor, link.anchors[index])))
152165
+ return [link];
152166
+ tracker.changed.add(link.id);
152167
+ return anchors.length ? [{ ...link, anchors }] : [];
152168
+ });
152169
+ }
152170
+ function bindSessionHyperlinkReviewCoordinates(group, tracker) {
152171
+ if (!tracker?.changed.size)
152172
+ return;
152173
+ reviewCoordinates.set(group, [...tracker.changed].map((id) => ({
152174
+ id,
152175
+ value: tracker.links.find((link) => link.id === id) ?? null
152176
+ })));
152177
+ }
152178
+ function utf8Length(value, end = value.length) {
152179
+ let length = 0;
152180
+ for (let index = 0;index < end; index++) {
152181
+ const code = value.charCodeAt(index);
152182
+ if (code < 128)
152183
+ length++;
152184
+ else if (code < 2048)
152185
+ length += 2;
152186
+ else if (code >= 55296 && code <= 56319 && index + 1 < end && value.charCodeAt(index + 1) >= 56320 && value.charCodeAt(index + 1) <= 57343) {
152187
+ length += 4;
152188
+ index++;
152189
+ } else
152190
+ length += 3;
152191
+ }
152192
+ return length;
152193
+ }
152194
+ function metadata(state) {
152195
+ return state.sessionHyperlinkMetadata ?? (state.sessionHyperlinkMetadata = { nextId: 1, links: [], replay: new WeakMap });
152196
+ }
152197
+ function hasPendingSessionHyperlinkEffects(state) {
152198
+ return Boolean(state.sessionHyperlinkMetadata?.pending?.length);
152199
+ }
152200
+ function sameAnchor(a, b) {
152201
+ return a.partUri === b.partUri && a.startByte === b.startByte && a.endByte === b.endByte;
152202
+ }
152203
+ function readSessionHyperlinkRel(state, anchor) {
152204
+ const store = state.sessionHyperlinkMetadata;
152205
+ if (!store?.links.length)
152206
+ return;
152207
+ if (store.lookup?.links !== store.links) {
152208
+ const values = new Map;
152209
+ for (const link of store.links) {
152210
+ for (const carrier of link.anchors)
152211
+ values.set(anchorKey(carrier), link.rel);
152212
+ }
152213
+ store.lookup = { links: store.links, values };
152214
+ }
152215
+ return store.lookup.values.get(anchorKey(anchor));
152216
+ }
152217
+ function anchorKey(anchor) {
152218
+ return `${anchor.partUri}\x00${anchor.startByte}\x00${anchor.endByte}`;
152219
+ }
152220
+ function withSessionHyperlinkEffects(state, effects2, commit) {
152221
+ const store = metadata(state);
152222
+ if (store.pending)
152223
+ throw new Error("Nested session hyperlink effects are unsupported.");
152224
+ store.pending = effects2.map((effect) => ({
152225
+ ...effect,
152226
+ ...effect.before ? { before: { ...effect.before } } : {},
152227
+ ...effect.after ? { after: { ...effect.after } } : {}
152228
+ }));
152229
+ try {
152230
+ return commit();
152231
+ } finally {
152232
+ store.pending = undefined;
152233
+ }
152234
+ }
152235
+ function bindSessionHyperlinkCarriers(group, effects2) {
152236
+ compilerEffects.set(group, effects2);
152237
+ }
152238
+ function prepareSessionHyperlinkMetadata(state, group) {
152239
+ const store = state.sessionHyperlinkMetadata;
152240
+ if (!store || !store.links.length && !store.pending?.length && !store.replay.has(group))
152241
+ return null;
152242
+ const replay = store.replay.get(group);
152243
+ if (replay) {
152244
+ const replacements = new Map(replay.map((delta) => [delta.id, delta.value]));
152245
+ const after2 = store.links.filter((link) => !replacements.has(link.id));
152246
+ for (const delta of replay)
152247
+ if (delta.value)
152248
+ after2.push(delta.value);
152249
+ return { before: store.links, after: after2, nextId: store.nextId };
152250
+ }
152251
+ const boundCoordinates = new Map((reviewCoordinates.get(group) ?? []).map((delta) => [delta.id, delta.value]));
152252
+ const after = store.links.flatMap((link) => {
152253
+ if (boundCoordinates.has(link.id)) {
152254
+ const bound = boundCoordinates.get(link.id);
152255
+ return bound ? [bound] : [];
152256
+ }
152257
+ const anchors = link.anchors.flatMap((anchor) => {
152258
+ if (!(anchor.partUri in group.perPart))
152259
+ return [anchor];
152260
+ const entry = group.perPart[anchor.partUri];
152261
+ if (entry.kind !== "modify")
152262
+ return [];
152263
+ const payload = state.packageBytes.getPayload(anchor.partUri);
152264
+ if (!payload)
152265
+ return [];
152266
+ const proof = group.derivedIndexProofs?.exactPartMutations?.find((candidate) => candidate.partUri === anchor.partUri);
152267
+ const whole = entry.patches.length === 1 ? entry.patches[0] : undefined;
152268
+ const patches = proof && whole?.kind === "replaceBytes" && whole.startByte === 0 && whole.endByte === proof.beforeByteLength && whole.bytes.length === proof.afterByteLength ? proof.splices.map((splice, order) => ({
152269
+ kind: "replaceBytes",
152270
+ order,
152271
+ startByte: splice.beforeStart,
152272
+ endByte: splice.beforeEnd,
152273
+ bytes: whole.bytes.subarray(splice.afterStart, splice.afterEnd)
152274
+ })) : entry.patches;
152275
+ const moved = mapThroughPatches(anchor, boundedPayloadReader(payload), patches, Boolean(proof)) ?? mapMovedParagraphAnchor(state, anchor, patches);
152276
+ return moved ? [moved] : [];
152277
+ });
152278
+ return anchors.length ? [
152279
+ anchors.length === link.anchors.length && anchors.every((anchor, i) => sameAnchor(anchor, link.anchors[i])) ? link : { ...link, anchors }
152280
+ ] : [];
152281
+ });
152282
+ const bindings = compilerEffects.get(group) ?? [];
152283
+ const pending = store.pending ?? [];
152284
+ const effects2 = bindings.map((binding, index) => ({
152285
+ ...binding,
152286
+ ...pending[index],
152287
+ after: pending[index]?.after ?? binding.after
152288
+ }));
152289
+ effects2.push(...pending.slice(bindings.length));
152290
+ let nextId = store.nextId;
152291
+ for (const effect of effects2) {
152292
+ if (!effect.after)
152293
+ throw new Error("Session hyperlink effect has no compiler-bound destination.");
152294
+ const destinationLength = resultingPartLength(state, group, effect.after.partUri);
152295
+ if (destinationLength === null || effect.after.startByte < 0 || effect.after.endByte <= effect.after.startByte || effect.after.endByte > destinationLength)
152296
+ throw new Error("Invalid session hyperlink destination.");
152297
+ const original = effect.before && store.links.find((link) => link.anchors.some((anchor) => sameAnchor(anchor, effect.before)));
152298
+ const current = original ? after.findIndex((link) => link.id === original.id) : -1;
152299
+ const rel = effect.rel === undefined ? original?.rel : effect.rel || undefined;
152300
+ const mappedAliases = current >= 0 ? after[current].anchors : [];
152301
+ if (current >= 0)
152302
+ after.splice(current, 1);
152303
+ if (rel)
152304
+ after.push({
152305
+ id: original?.id ?? nextId++,
152306
+ anchors: [
152307
+ effect.after,
152308
+ ...(effect.survivingAlternates ?? mappedAliases).filter((anchor) => !sameAnchor(anchor, effect.after))
152309
+ ],
152310
+ rel
152311
+ });
152312
+ }
152313
+ return { before: store.links, after, nextId };
152314
+ }
152315
+ function commitSessionHyperlinkMetadata(state, prepared, forward, inverse) {
152316
+ if (!prepared)
152317
+ return;
152318
+ const store = metadata(state);
152319
+ store.links = prepared.after;
152320
+ store.lookup = undefined;
152321
+ store.nextId = prepared.nextId;
152322
+ const before = new Map(prepared.before.map((link) => [link.id, link]));
152323
+ const after = new Map(prepared.after.map((link) => [link.id, link]));
152324
+ const changed = [...new Set([...before.keys(), ...after.keys()])].filter((id) => before.get(id) !== after.get(id));
152325
+ store.replay.set(forward, changed.map((id) => ({ id, value: after.get(id) ?? null })));
152326
+ store.replay.set(inverse, changed.map((id) => ({ id, value: before.get(id) ?? null })));
152327
+ }
152328
+ function composeSessionHyperlinkHistory(state, captured, forward) {
152329
+ const store = state.sessionHyperlinkMetadata;
152330
+ if (!store)
152331
+ return false;
152332
+ const final = new Map;
152333
+ for (const group of captured)
152334
+ for (const delta of store.replay.get(group) ?? [])
152335
+ final.set(delta.id, delta.value);
152336
+ const changes = [];
152337
+ for (const [id, value] of final) {
152338
+ const current = store.links.find((link) => link.id === id) ?? null;
152339
+ if (current === value || current && value && current.rel === value.rel && current.anchors.length === value.anchors.length && current.anchors.every((anchor, index) => sameAnchor(anchor, value.anchors[index])))
152340
+ continue;
152341
+ changes.push({ id, value });
152342
+ }
152343
+ if (!changes.length)
152344
+ return false;
152345
+ store.replay.set(forward, changes);
152346
+ return true;
152347
+ }
152348
+ function resultingPartLength(state, group, partUri) {
152349
+ const entry = group.perPart[partUri];
152350
+ if (entry?.kind === "remove")
152351
+ return null;
152352
+ if (entry?.kind === "create")
152353
+ return entry.bytes.length;
152354
+ const payload = state.packageBytes.getPayload(partUri);
152355
+ if (!payload)
152356
+ return null;
152357
+ return payloadLength(payload) + (entry?.kind === "modify" ? entry.patches.reduce((delta, patch) => delta + (patch.kind === "deleteBytes" ? 0 : patch.bytes.length) - (patch.kind === "insertBytes" ? 0 : patch.endByte - patch.startByte), 0) : 0);
152358
+ }
152359
+ function boundedPayloadReader(payload) {
152360
+ let start = -1;
152361
+ let bytes = new Uint8Array;
152362
+ return (offset) => {
152363
+ if (offset < start || offset >= start + bytes.length) {
152364
+ start = Math.floor(offset / 4096) * 4096;
152365
+ bytes = payloadSubarray(payload, start, Math.min(start + 4096, payloadLength(payload)));
152366
+ }
152367
+ return bytes[offset - start];
152368
+ };
152369
+ }
152370
+ function mapMovedParagraphAnchor(state, anchor, patches) {
152371
+ const owner = findAnchorParagraph(state, anchor);
152372
+ if (!owner?.blockId)
152373
+ return null;
152374
+ const payload = state.packageBytes.getPayload(anchor.partUri);
152375
+ if (!payload)
152376
+ return null;
152377
+ const oldBytes = payloadSubarray(payload, owner.byteStart, owner.byteEnd);
152378
+ const candidates = [];
152379
+ let delta = 0;
152380
+ for (const patch of patches) {
152381
+ const start = patch.kind === "insertBytes" ? patch.atByte : patch.startByte;
152382
+ const end = patch.kind === "insertBytes" ? start : patch.endByte;
152383
+ if (patch.kind !== "deleteBytes") {
152384
+ const xml = decoder2.decode(patch.bytes);
152385
+ for (const paragraph of scanWmlParagraphSpans(xml, {
152386
+ fragment: true,
152387
+ additionalNamespaces: {
152388
+ w: "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
152389
+ w14: "http://schemas.microsoft.com/office/word/2010/wordml"
152390
+ }
152391
+ }).paragraphs) {
152392
+ if (paragraph.paraId !== owner.blockId)
152393
+ continue;
152394
+ const newBytes = encoder.encode(xml.slice(paragraph.openStart, paragraph.closeEnd));
152395
+ const local = mapThroughPatches({
152396
+ ...anchor,
152397
+ startByte: anchor.startByte - owner.byteStart,
152398
+ endByte: anchor.endByte - owner.byteStart
152399
+ }, (offset) => oldBytes[offset], [
152400
+ {
152401
+ kind: "replaceBytes",
152402
+ order: 0,
152403
+ startByte: 0,
152404
+ endByte: oldBytes.length,
152405
+ bytes: newBytes
152406
+ }
152407
+ ]);
152408
+ if (local) {
152409
+ const base2 = start + delta + encoder.encode(xml.slice(0, paragraph.openStart)).length;
152410
+ candidates.push({
152411
+ ...local,
152412
+ startByte: local.startByte + base2,
152413
+ endByte: local.endByte + base2
152414
+ });
152415
+ }
152416
+ }
152417
+ }
152418
+ delta += (patch.kind === "deleteBytes" ? 0 : patch.bytes.length) - (end - start);
152419
+ }
152420
+ return candidates.length === 1 ? candidates[0] : null;
152421
+ }
152422
+ function findAnchorParagraph(state, anchor) {
152423
+ for (const index of state.paragraphIndexes.values()) {
152424
+ if (index.entries[0]?.partUri !== anchor.partUri)
152425
+ continue;
152426
+ let low = 0;
152427
+ let high = index.entries.length;
152428
+ while (low < high) {
152429
+ const middle = Math.floor((low + high) / 2);
152430
+ if (index.entries[middle].byteStart <= anchor.startByte)
152431
+ low = middle + 1;
152432
+ else
152433
+ high = middle;
152434
+ }
152435
+ const owner = index.entries[low - 1];
152436
+ if (owner && owner.byteStart <= anchor.startByte && owner.byteEnd >= anchor.endByte)
152437
+ return owner;
152438
+ }
152439
+ return null;
152440
+ }
152441
+ function mapThroughPatches(anchor, readBefore, patches, allowRetainedCarrier = false) {
152442
+ let startByte = anchor.startByte;
152443
+ let endByte = anchor.endByte;
152444
+ for (const patch of patches) {
152445
+ let start = patch.kind === "insertBytes" ? patch.atByte : patch.startByte;
152446
+ let end = patch.kind === "insertBytes" ? start : patch.endByte;
152447
+ let replacement = patch.kind === "deleteBytes" ? new Uint8Array : patch.bytes;
152448
+ const rawDelta = replacement.length - (end - start);
152449
+ if (end <= anchor.startByte) {
152450
+ startByte += rawDelta;
152451
+ endByte += rawDelta;
152452
+ continue;
152453
+ }
152454
+ if (start >= anchor.endByte)
152455
+ continue;
152456
+ if (start > anchor.startByte && end < anchor.endByte) {
152457
+ endByte += rawDelta;
152458
+ continue;
152459
+ }
152460
+ if (allowRetainedCarrier && start <= anchor.startByte && end >= anchor.endByte) {
152461
+ const length = anchor.endByte - anchor.startByte;
152462
+ const retainedAt = uniqueByteWindow(replacement.length, (offset) => replacement[offset], length, (offset) => readBefore(anchor.startByte + offset));
152463
+ const originalAt = retainedAt === null ? null : uniqueByteWindow(end - start, (offset) => readBefore(start + offset), length, (offset) => readBefore(anchor.startByte + offset));
152464
+ if (retainedAt !== null && originalAt === anchor.startByte - start) {
152465
+ const shift = start + retainedAt - anchor.startByte;
152466
+ startByte += shift;
152467
+ endByte += shift;
152468
+ continue;
152469
+ }
152470
+ }
152471
+ let prefix = 0;
152472
+ while (start + prefix < end && prefix < replacement.length && readBefore(start + prefix) === replacement[prefix])
152473
+ prefix++;
152474
+ start += prefix;
152475
+ replacement = replacement.subarray(prefix);
152476
+ let suffix = 0;
152477
+ while (end - suffix > start && suffix < replacement.length && readBefore(end - suffix - 1) === replacement[replacement.length - suffix - 1])
152478
+ suffix++;
152479
+ end -= suffix;
152480
+ replacement = replacement.subarray(0, replacement.length - suffix);
152481
+ if (start === end && !replacement.length)
152482
+ continue;
152483
+ const delta = replacement.length - (end - start);
152484
+ if (end <= anchor.startByte) {
152485
+ startByte += delta;
152486
+ endByte += delta;
152487
+ } else if (start >= anchor.endByte)
152488
+ continue;
152489
+ else if (start > anchor.startByte && end < anchor.endByte)
152490
+ endByte += delta;
152491
+ else
152492
+ return null;
152493
+ }
152494
+ return { ...anchor, startByte, endByte };
152495
+ }
152496
+ function uniqueByteWindow(haystackLength, haystack, needleLength, needle) {
152497
+ if (needleLength === 0 || needleLength > haystackLength)
152498
+ return null;
152499
+ const bytes = Uint8Array.from({ length: needleLength }, (_, index) => needle(index));
152500
+ const prefix = new Uint32Array(needleLength);
152501
+ for (let index = 1, matched = 0;index < needleLength; index++) {
152502
+ while (matched > 0 && bytes[index] !== bytes[matched])
152503
+ matched = prefix[matched - 1];
152504
+ if (bytes[index] === bytes[matched])
152505
+ matched++;
152506
+ prefix[index] = matched;
152507
+ }
152508
+ let match = null;
152509
+ for (let index = 0, matched = 0;index < haystackLength; index++) {
152510
+ const byte = haystack(index);
152511
+ while (matched > 0 && byte !== bytes[matched])
152512
+ matched = prefix[matched - 1];
152513
+ if (byte === bytes[matched])
152514
+ matched++;
152515
+ if (matched === needleLength) {
152516
+ if (match !== null)
152517
+ return null;
152518
+ match = index - needleLength + 1;
152519
+ matched = prefix[matched - 1];
152520
+ }
152521
+ }
152522
+ return match;
152523
+ }
152524
+ var encoder, decoder2, compilerEffects, reviewCoordinates;
152525
+ var init_session_hyperlink_metadata = __esm(() => {
152526
+ init_part_payload();
152527
+ init_wml_paragraph_spans();
152528
+ encoder = new TextEncoder;
152529
+ decoder2 = new TextDecoder;
152530
+ compilerEffects = new WeakMap;
152531
+ reviewCoordinates = new WeakMap;
152532
+ });
152533
+
152473
152534
  // ../../../v2/editor-core/dist/document/transactions/history-text-replay.js
152474
152535
  function readOwner(state, owner) {
152475
152536
  if (isSyntheticParagraphBlockId(owner.blockId))
@@ -154076,6 +154137,7 @@ var init_zip_inventory = __esm(() => {
154076
154137
  function parseContentTypes(xml) {
154077
154138
  const defaults = new Map;
154078
154139
  const overrides = new Map;
154140
+ const overridePartNames = new Map;
154079
154141
  let parseError = null;
154080
154142
  const parser = createXmlSaxParser({ namespaceAware: true });
154081
154143
  parser.on("error", (err2) => {
@@ -154094,8 +154156,15 @@ function parseContentTypes(xml) {
154094
154156
  } else if (local === "Override") {
154095
154157
  const part = readXmlAttribute(tag, "", "PartName")?.value;
154096
154158
  const ct = readXmlAttribute(tag, "", "ContentType")?.value;
154097
- if (part && ct)
154098
- overrides.set(part, ct);
154159
+ if (part && ct) {
154160
+ const key2 = partUriComparisonKey(part);
154161
+ if (overridePartNames.has(key2)) {
154162
+ parseError ?? (parseError = `Duplicate content type override for ${part}`);
154163
+ } else {
154164
+ overridePartNames.set(key2, part);
154165
+ overrides.set(part, ct);
154166
+ }
154167
+ }
154099
154168
  }
154100
154169
  });
154101
154170
  try {
@@ -154105,12 +154174,23 @@ function parseContentTypes(xml) {
154105
154174
  if (!parseError)
154106
154175
  parseError = err2 instanceof Error ? err2.message : String(err2);
154107
154176
  }
154108
- return { defaults, overrides, parseError };
154177
+ return { defaults, overrides, overridePartNames, parseError };
154109
154178
  }
154110
154179
  function resolveContentType(reg, partUri) {
154111
154180
  const ov = reg.overrides.get(partUri);
154112
154181
  if (ov)
154113
154182
  return ov;
154183
+ const key2 = partUriComparisonKey(partUri);
154184
+ if (reg.overridePartNames) {
154185
+ const authoredName = reg.overridePartNames.get(key2);
154186
+ if (authoredName != null)
154187
+ return reg.overrides.get(authoredName) ?? null;
154188
+ } else {
154189
+ for (const [authoredName, contentType] of reg.overrides) {
154190
+ if (partUriComparisonKey(authoredName) === key2)
154191
+ return contentType;
154192
+ }
154193
+ }
154114
154194
  const dot = partUri.lastIndexOf(".");
154115
154195
  if (dot < 0)
154116
154196
  return null;
@@ -154190,6 +154270,15 @@ function openPackageFromZipInventory(zip, containerKind, rawBytesRead, options =
154190
154270
  }
154191
154271
  }
154192
154272
  const parts = new Map;
154273
+ for (const uri of findPartUriCollisions(zip.entries.filter((entry) => !entry.isDirectory).map((entry) => entry.name))) {
154274
+ diagnostics.push({
154275
+ code: "part-name-collision",
154276
+ category: "package-integrity",
154277
+ severity: "error",
154278
+ message: `Package contains case-equivalent part names for ${uri}.`,
154279
+ partUri: normalizePartUri(uri)
154280
+ });
154281
+ }
154193
154282
  for (const entry of zip.entries) {
154194
154283
  if (entry.isDirectory)
154195
154284
  continue;
@@ -154227,7 +154316,7 @@ function openPackageFromZipInventory(zip, containerKind, rawBytesRead, options =
154227
154316
  relsParts.set(relsUri, parseRelationshipsXml(decode3(payload), {
154228
154317
  ownerPartUri,
154229
154318
  relsUri,
154230
- resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode)
154319
+ resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode, parts)
154231
154320
  }));
154232
154321
  }
154233
154322
  const rootRelationships = relsParts.get("/_rels/.rels") ?? null;
@@ -154374,7 +154463,7 @@ function openPackageFromZipInventory(zip, containerKind, rawBytesRead, options =
154374
154463
  });
154375
154464
  }
154376
154465
  for (const partName of contentTypes.overrides.keys()) {
154377
- const uri = normalizePartUri(partName);
154466
+ const uri = resolveRegisteredPartUri(partName, parts);
154378
154467
  if (!parts.has(uri)) {
154379
154468
  diagnostics.push({
154380
154469
  code: "dangling-content-type-override",
@@ -154749,6 +154838,8 @@ function evaluatePackageInvariants(open) {
154749
154838
  hard.push("package-not-zip");
154750
154839
  if (pkg.contentTypes.parseError)
154751
154840
  hard.push("content-types-unparseable");
154841
+ if (pkg.diagnostics.some((diagnostic) => diagnostic.code === "part-name-collision"))
154842
+ hard.push("part-name-collision");
154752
154843
  if (!pkg.rootRelationships || pkg.rootRelationships.parseError)
154753
154844
  hard.push("root-rels-unparseable");
154754
154845
  if (!pkg.mainDocumentPartUri) {
@@ -155704,6 +155795,12 @@ async function openPackageFromSource(input, options = {}) {
155704
155795
  telemetry
155705
155796
  };
155706
155797
  }
155798
+ const hardInvariants = [];
155799
+ const partUris = zip.entries.filter((entry) => !entry.isDirectory).map((entry) => normalizePartUri(entry.name));
155800
+ const registeredParts = new Set(partUris);
155801
+ if (findPartUriCollisions(partUris).length > 0) {
155802
+ pushHard(diagnostics, hardInvariants, "part-name-collision", "Package contains case-equivalent part names.");
155803
+ }
155707
155804
  const ctBytes = await zip.readEntry("[Content_Types].xml", options.signal);
155708
155805
  note(ctBytes?.byteLength);
155709
155806
  let contentTypes;
@@ -155725,7 +155822,7 @@ async function openPackageFromSource(input, options = {}) {
155725
155822
  rootRelationships = parseRelationshipsXml(TEXT_DECODER3.decode(rootRelsBytes), {
155726
155823
  ownerPartUri: "/",
155727
155824
  relsUri: "/_rels/.rels",
155728
- resolveTarget: (target, mode) => resolveTargetUri("/", target, mode)
155825
+ resolveTarget: (target, mode) => resolveTargetUri("/", target, mode, registeredParts)
155729
155826
  });
155730
155827
  } else {
155731
155828
  diagnostics.push({
@@ -155754,11 +155851,10 @@ async function openPackageFromSource(input, options = {}) {
155754
155851
  mainDocumentRelationships = parseRelationshipsXml(TEXT_DECODER3.decode(mainRelsBytes), {
155755
155852
  ownerPartUri,
155756
155853
  relsUri: mainRelsUri,
155757
- resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode)
155854
+ resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode, registeredParts)
155758
155855
  });
155759
155856
  }
155760
155857
  }
155761
- const hardInvariants = [];
155762
155858
  const nonDirEntries = zip.entries.filter((e) => !e.isDirectory);
155763
155859
  if (nonDirEntries.length > DEFAULT_PACKAGE_PAYLOAD_LIMITS.zipEntryCount) {
155764
155860
  pushHard(diagnostics, hardInvariants, "PKG-payload-zip-entries-exceeded", `ZIP entry count ${nonDirEntries.length} exceeds safety limit.`);
@@ -163418,7 +163514,7 @@ function resolveHeaderFooterRef(ref3, pkg, diagnostics) {
163418
163514
  if (found.targetMode === "External") {
163419
163515
  return { ...ref3, targetStatus: "external" };
163420
163516
  }
163421
- const targetUri = normalizePartUri(found.resolvedTarget);
163517
+ const targetUri = resolveRegisteredPartUri(found.resolvedTarget, pkg.parts);
163422
163518
  const targetPart = pkg.parts.get(targetUri);
163423
163519
  if (!targetPart)
163424
163520
  return { ...ref3, targetStatus: "missing" };
@@ -163881,7 +163977,7 @@ function captureRenderSourceSnapshot(state, snapshotId, currentSections) {
163881
163977
  return bytes ? parseRelationshipsXml(new TextDecoder().decode(bytes), {
163882
163978
  ownerPartUri,
163883
163979
  relsUri,
163884
- resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode)
163980
+ resolveTarget: (target, mode) => resolveTargetUri(ownerPartUri, target, mode, partsById)
163885
163981
  }) : null;
163886
163982
  }
163887
163983
  async function buildSections() {
@@ -186169,6 +186265,44 @@ var init_table_catalog = __esm(() => {
186169
186265
  TABLE_CATALOG_PARAGRAPH_UNSAFE_MARKER_RE = /<\/?(?:[\w.-]+:)?(?:tbl|tr|tc|tblGrid|gridCol|gridSpan|vMerge|sdt|drawing|object|hyperlink|oMath|oMathPara)\b/;
186170
186266
  });
186171
186267
 
186268
+ // ../../../v2/editor-core/dist/document/transactions/text-edit-validation-state.js
186269
+ function createTextEditValidationState(state, packageBytes = state.packageBytes.detached()) {
186270
+ const validation = {
186271
+ ...state,
186272
+ packageBytes,
186273
+ partRegistries: new Map(state.partRegistries),
186274
+ idReservations: {
186275
+ ...state.idReservations,
186276
+ revisionWIds: {
186277
+ ...state.idReservations.revisionWIds,
186278
+ issued: new Set(state.idReservations.revisionWIds.issued),
186279
+ replayOwners: new Map([...state.idReservations.revisionWIds.replayOwners].map(([id, owners]) => [
186280
+ id,
186281
+ new Set(owners)
186282
+ ])),
186283
+ conflictedReserved: new Set(state.idReservations.revisionWIds.conflictedReserved)
186284
+ },
186285
+ comments: {
186286
+ wIds: new Set(state.idReservations.comments.wIds),
186287
+ repairedSourceWIds: new Map(state.idReservations.comments.repairedSourceWIds),
186288
+ paraIds: new Set(state.idReservations.comments.paraIds),
186289
+ durableIds: new Set(state.idReservations.comments.durableIds)
186290
+ }
186291
+ }
186292
+ };
186293
+ isolateLazyIndexTelemetry(validation);
186294
+ isolateTableCatalogCache(validation);
186295
+ isolatePartWmlScanCache(validation);
186296
+ isolateTrackedChangePartScanCache(validation);
186297
+ return validation;
186298
+ }
186299
+ var init_text_edit_validation_state = __esm(() => {
186300
+ init_lazy_indexes();
186301
+ init_part_wml_scan_cache();
186302
+ init_table_catalog();
186303
+ init_catalog3();
186304
+ });
186305
+
186172
186306
  // ../../../v2/editor-core/dist/document/transactions/incremental-index-refresh.js
186173
186307
  function recordRefreshEntry(entry) {
186174
186308
  const probe = activeProbe2;
@@ -195328,14 +195462,19 @@ function tryContinueDirectInsertionInAdjacentPlainRun(input, allTokens, touched)
195328
195462
  }
195329
195463
  return null;
195330
195464
  }
195465
+ function canTrackForeignMultiRunCrossing(input, token) {
195466
+ const classification = token._classification;
195467
+ return input.changeMode === "tracked" && classification != null && classification !== "same-user" && token.commentedBoundary == null && token.innerRuns != null && token.innerRuns.every((run) => !run.controlXml) && (token.nestedDeletions?.length ?? 0) === 0;
195468
+ }
195331
195469
  function tryPureDeleteAcrossTokens(input, allTokens, touched, touchedBreaks = []) {
195332
195470
  if (input.newText.length !== 0 || input.rangeStart >= input.rangeEnd)
195333
195471
  return null;
195334
195472
  const touchedInsertions = touched.filter((entry) => entry.token.kind === "ins");
195335
- if (touchedInsertions.some(({ token }) => token.innerRuns && token.innerRuns.length > 0 || token.nestedDeletions && token.nestedDeletions.length > 0)) {
195473
+ if (touchedInsertions.some(({ token }) => token.innerRuns && token.innerRuns.length > 0 && !canTrackForeignMultiRunCrossing(input, token) || token.nestedDeletions && token.nestedDeletions.length > 0)) {
195336
195474
  return null;
195337
195475
  }
195338
- return input.changeMode === "tracked" ? authorTrackedPureDelete(input, allTokens, touched, touchedBreaks) : authorDirectPureDelete(input, allTokens, touched, touchedBreaks);
195476
+ const result = input.changeMode === "tracked" ? authorTrackedPureDelete(input, allTokens, touched, touchedBreaks) : authorDirectPureDelete(input, allTokens, touched, touchedBreaks);
195477
+ return result?.ok && input.changeMode === "tracked" && touchedInsertions.some(({ token }) => (token.innerRuns?.length ?? 0) > 0) ? { ...result, requiresCollaborationSessionSync: true } : result;
195339
195478
  }
195340
195479
  function tryRangeReplacementAcrossTokens(input, allTokens, touched) {
195341
195480
  if (input.newText.length === 0 || input.rangeStart >= input.rangeEnd)
@@ -195352,7 +195491,7 @@ function tryRangeReplacementAcrossTokens(input, allTokens, touched) {
195352
195491
  if (!firstSelected)
195353
195492
  return null;
195354
195493
  const touchedInsertions = touched.filter((entry) => entry.token.kind === "ins");
195355
- if (touchedInsertions.some(({ token }) => token.innerRuns && token.innerRuns.length > 0 && (token !== firstSelected.token || token.commentedBoundary != null) || token.nestedDeletions && token.nestedDeletions.length > 0)) {
195494
+ if (touchedInsertions.some(({ token }) => token.innerRuns && token.innerRuns.length > 0 && (token !== firstSelected.token && !canTrackForeignMultiRunCrossing(input, token) || token.commentedBoundary != null) || token.nestedDeletions && token.nestedDeletions.length > 0)) {
195356
195495
  return null;
195357
195496
  }
195358
195497
  const result = input.changeMode === "tracked" ? authorTrackedPureDelete(input, allTokens, touched) : authorDirectPureDelete(input, allTokens, touched);
@@ -198198,6 +198337,9 @@ function allocateDistinctBatchRsids(state, txId, count) {
198198
198337
  return allocated;
198199
198338
  }
198200
198339
  function runEditTextCommit(input) {
198340
+ if (input.validateOnly && input.op.edits) {
198341
+ input = { ...input, state: createTextEditValidationState(input.state) };
198342
+ }
198201
198343
  const { state, txId, op } = input;
198202
198344
  if (op.edits) {
198203
198345
  return op.changeMode === "tracked" ? runTrackedEditTextBatchCommit(input, op.edits) : runDirectEditTextBatchCommit(input, op.edits);
@@ -198541,6 +198683,8 @@ function runDirectEditTextBatchCommit(input, edits) {
198541
198683
  actorAttribution: { actorType: input.options.actorTag ?? "code" }
198542
198684
  }
198543
198685
  };
198686
+ if (input.validateOnly)
198687
+ return { txId, status: "committed" };
198544
198688
  return commitPreparedMutation(state, prepared, { pushHistory: input.pushHistory });
198545
198689
  }
198546
198690
  function rewritePlainTrackedTextBatch(paragraphBytes, edits, stampByEdit, stamping) {
@@ -198678,6 +198822,13 @@ function runTrackedEditTextBatchCommit(input, edits) {
198678
198822
  byBlock.set(edit.on.startBlockId, entries);
198679
198823
  }
198680
198824
  const plannedWIds = planRevisionWIdBlock(state, ordered.length * 2);
198825
+ const additionalWIds = [];
198826
+ let nextAdditionalWId = plannedWIds[plannedWIds.length - 1] + 1;
198827
+ const planAdditionalWId = () => {
198828
+ const id = nextAdditionalWId++;
198829
+ additionalWIds.push(id);
198830
+ return id;
198831
+ };
198681
198832
  const plannedRsids = allocateDistinctBatchRsids(state, txId, ordered.length);
198682
198833
  const stampByEdit = new Map(ordered.map((edit, ordinal) => [edit, {
198683
198834
  rsid: edit.rsid ?? plannedRsids[ordinal],
@@ -198801,7 +198952,7 @@ function runTrackedEditTextBatchCommit(input, edits) {
198801
198952
  wId: stamp.wId,
198802
198953
  author: stamping.author,
198803
198954
  date: stamping.date
198804
- });
198955
+ }, undefined, undefined, planAdditionalWId);
198805
198956
  if (!overlap.ok)
198806
198957
  return rejected2(txId, overlap.reason);
198807
198958
  afterBytes = overlap.bytes;
@@ -198933,7 +199084,7 @@ function runTrackedEditTextBatchCommit(input, edits) {
198933
199084
  baseRevisions: forwardPatchGroup.baseRevisions,
198934
199085
  reservations: {
198935
199086
  conflictRule: "first-choice-strict",
198936
- revisionWIds: plannedWIds
199087
+ revisionWIds: [...plannedWIds, ...additionalWIds]
198937
199088
  },
198938
199089
  localApplyBundle: forwardPatchGroup,
198939
199090
  semanticDelta: {
@@ -198984,6 +199135,8 @@ function runTrackedEditTextBatchCommit(input, edits) {
198984
199135
  actorAttribution: { actorType: input.options.actorTag ?? "code" }
198985
199136
  }
198986
199137
  };
199138
+ if (input.validateOnly)
199139
+ return { txId, status: "committed" };
198987
199140
  return commitPreparedMutation(state, prepared, { pushHistory: input.pushHistory });
198988
199141
  }
198989
199142
  function resolveTextEditPartView(state, op) {
@@ -200790,7 +200943,7 @@ function tryOverlapRewriteDirect(input, bytes, window2, byteBase, inheritedNames
200790
200943
  requiresCollaborationSessionSync: compiled.requiresCollaborationSessionSync
200791
200944
  };
200792
200945
  }
200793
- function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inlineContext, inheritedNamespaceBindings) {
200946
+ function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inlineContext, inheritedNamespaceBindings, planAdditionalWId) {
200794
200947
  const op = input.op;
200795
200948
  let paragraphXml = inlineContext?.paragraphXml ?? TD42.decode(bytes.subarray(window2.byteStart, window2.byteEnd));
200796
200949
  const namespaceBindings = inheritedNamespaceBindings ?? textTargetNamespaceBindings(input, window2, byteBase);
@@ -200811,7 +200964,7 @@ function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inline
200811
200964
  rsid: stamp.rsid,
200812
200965
  insRsid: stamp.insRsid,
200813
200966
  nextWId: stamp.wId,
200814
- reserveWId: () => reserveRevisionWIdBlock(input.state, 1),
200967
+ reserveWId: planAdditionalWId ?? (() => reserveRevisionWIdBlock(input.state, 1)),
200815
200968
  revisionOccurrenceAt: createRevisionOccurrenceResolver(input, bytes, window2, byteBase, paragraphXml)
200816
200969
  });
200817
200970
  let compiled = compile(true);
@@ -203733,6 +203886,7 @@ function collectPerPartRevisions(state, partUris) {
203733
203886
  }
203734
203887
  var TD42, TE16, TRACKED_WRAPPER_OPEN_RE, INLINE_CONTROL_PLACEHOLDER = "";
203735
203888
  var init_compile_edit_text = __esm(() => {
203889
+ init_text_edit_validation_state();
203736
203890
  init_rewrite_groups();
203737
203891
  init_comparison_hunk_groups();
203738
203892
  init_word_text_payload();
@@ -223185,8 +223339,13 @@ function runStorySurfaceRewriteCommit(input) {
223185
223339
  }
223186
223340
  const headerFooterUpdate = prepareHeaderFooterUpdate(input.state, op, effectivePerPart);
223187
223341
  const exactParagraphRenderRange = contentControlRewrite ? resolveExactCheckboxParagraphRenderRange(input.state, op, contentControlRewrite) : null;
223342
+ const wholeBodyTextReplacement = prepareWholeBodyTextReplacement(input.state, op, effectivePerPart);
223343
+ if (op.operationId === "range-ref-whole-body-replace" && !wholeBodyTextReplacement) {
223344
+ return rejected11(input.txId, "unsupported-context");
223345
+ }
223188
223346
  const storySurface = {
223189
223347
  family,
223348
+ ...wholeBodyTextReplacement ? { wholeBodyTextReplacement } : {},
223190
223349
  ...contentControlRewrite ? { contentControlRewrite } : {},
223191
223350
  storyLocal: op.storyLocal,
223192
223351
  ...op.changeMode ? { changeMode: op.changeMode } : {},
@@ -223227,6 +223386,7 @@ function runStorySurfaceRewriteCommit(input) {
223227
223386
  },
223228
223387
  replayInputs: {
223229
223388
  source: op,
223389
+ ...wholeBodyTextReplacement ? { wholeBodyTextReplacement } : {},
223230
223390
  inverseDescriptor: createPreparedInverseDescriptor(op, storyPartOwnership)
223231
223391
  },
223232
223392
  backendExtensions: {
@@ -223673,6 +223833,7 @@ var init_compile_story_surface_rewrite = __esm(() => {
223673
223833
  init_session_hyperlink_metadata();
223674
223834
  init_sectpr_parser();
223675
223835
  init_content_control_rewrite();
223836
+ init_whole_body_text_replacement();
223676
223837
  init_header_footer_update();
223677
223838
  init_compile_paste_notes();
223678
223839
  init_commit_prepared_mutation();
@@ -244467,28 +244628,7 @@ function preflightDirectTextEdit(input) {
244467
244628
  const validationView = createDirectTextEditValidationView(input);
244468
244629
  if (!validationView.ok)
244469
244630
  return validationView.reason;
244470
- const validationState = {
244471
- ...input.state,
244472
- packageBytes: validationView.packageBytes,
244473
- partRegistries: new Map(input.state.partRegistries),
244474
- idReservations: {
244475
- ...input.state.idReservations,
244476
- revisionWIds: {
244477
- ...input.state.idReservations.revisionWIds,
244478
- issued: new Set(input.state.idReservations.revisionWIds.issued)
244479
- },
244480
- comments: {
244481
- wIds: new Set(input.state.idReservations.comments.wIds),
244482
- repairedSourceWIds: new Map(input.state.idReservations.comments.repairedSourceWIds),
244483
- paraIds: new Set(input.state.idReservations.comments.paraIds),
244484
- durableIds: new Set(input.state.idReservations.comments.durableIds)
244485
- }
244486
- }
244487
- };
244488
- isolateLazyIndexTelemetry(validationState);
244489
- isolateTableCatalogCache(validationState);
244490
- isolatePartWmlScanCache(validationState);
244491
- isolateTrackedChangePartScanCache(validationState);
244631
+ const validationState = createTextEditValidationState(input.state, validationView.packageBytes);
244492
244632
  if (validationView.omittedByteRangeCount > 0) {
244493
244633
  invalidateTrackedChangeCatalogIfTouched(validationState, [input.on.partUri]);
244494
244634
  }
@@ -244511,6 +244651,28 @@ function preflightDirectTextEdit(input) {
244511
244651
  });
244512
244652
  return receipt2.status === "rejected" ? receipt2.rejectedReason ?? "internal-error" : null;
244513
244653
  }
244654
+ function preflightTextEditRanges(input) {
244655
+ const txId = "v2-text-batch-dry-run";
244656
+ const receipt2 = runEditTextCommit({
244657
+ state: input.state,
244658
+ txId,
244659
+ author: input.author,
244660
+ authorOverride: null,
244661
+ txTimestamp: "1970-01-01T00:00:00.000Z",
244662
+ options: {},
244663
+ op: {
244664
+ kind: "editText",
244665
+ changeMode: input.changeMode,
244666
+ on: input.edits[0].on,
244667
+ newText: input.edits[0].newText,
244668
+ edits: input.edits,
244669
+ rsid: allocateTxRsid(txId)
244670
+ },
244671
+ pushHistory: () => {},
244672
+ validateOnly: true
244673
+ });
244674
+ return receipt2.status === "rejected" ? receipt2.rejectedReason ?? "internal-error" : null;
244675
+ }
244514
244676
  function createDirectTextEditValidationView(input) {
244515
244677
  const packageBytes = input.state.packageBytes.detached();
244516
244678
  const ranges = input.validationByteRangesToOmit ?? [];
@@ -248136,10 +248298,8 @@ function emptyHeaderFooterSkeleton(kind) {
248136
248298
  }
248137
248299
  var TE38, TD70, nextTx = 0, CONTENT_TYPES_PART_URI12 = "/[Content_Types].xml", DOCUMENT_RELS_PART_URI10 = "/word/_rels/document.xml.rels", COMMENTS_PART_URI3 = "/word/comments.xml", COMMENTS_IDS_PART_URI3 = "/word/commentsIds.xml", COMMENTS_EXTENDED_PART_URI3 = "/word/commentsExtended.xml", SDCOM_COMMENTS_NS_URI = "http://superdoc.dev/2024/comments", COMMENT_ELEMENT_RE, RUN_HAS_TEXT_LEAF_VISIBLE_RE, RUN_HAS_TEXT_LEAF_TRACKED_RE, RUN_CONTROL_LEAF_RE, RUN_TEXT_LEAF_RE_VISIBLE, RUN_TEXT_LEAF_RE_TRACKED;
248138
248300
  var init_tx_context = __esm(() => {
248139
- init_part_wml_scan_cache();
248301
+ init_text_edit_validation_state();
248140
248302
  init_part_payload();
248141
- init_lazy_indexes();
248142
- init_table_catalog();
248143
248303
  init_catalog3();
248144
248304
  init_sd_document_state();
248145
248305
  init_paragraph_index();
@@ -253426,11 +253586,14 @@ function listSDDocumentSessionInternalPartRelationships(session, ownerPartUri) {
253426
253586
  const parsed = parseRelationshipsXml(xml, {
253427
253587
  ownerPartUri: normalizedOwner,
253428
253588
  relsUri,
253429
- resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode)
253589
+ resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode, internal.state.parts)
253430
253590
  });
253431
253591
  return parsed.relationships;
253432
253592
  }
253433
253593
  function listSDDocumentSessionInternalCapturePartRelationships(session, ownerPartUri) {
253594
+ const internal = INTERNALS.get(session);
253595
+ if (!internal)
253596
+ throw new Error("internal: unknown SDDocumentSession instance");
253434
253597
  const normalizedOwner = normalizePartUri(ownerPartUri);
253435
253598
  const relsUri = relsUriFor(normalizedOwner);
253436
253599
  const bytes = getSDDocumentSessionInternalCapturePartBytes(session, relsUri);
@@ -253439,7 +253602,7 @@ function listSDDocumentSessionInternalCapturePartRelationships(session, ownerPar
253439
253602
  const parsed = parseRelationshipsXml(RELS_DECODER.decode(bytes), {
253440
253603
  ownerPartUri: normalizedOwner,
253441
253604
  relsUri,
253442
- resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode)
253605
+ resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode, internal.state.parts)
253443
253606
  });
253444
253607
  return parsed.relationships;
253445
253608
  }
@@ -254730,6 +254893,12 @@ function preflightSDDocumentSessionInternalDirectTextEdit(session, input) {
254730
254893
  ...input.validationByteRangesToOmit ? { validationByteRangesToOmit: input.validationByteRangesToOmit } : {}
254731
254894
  });
254732
254895
  }
254896
+ function preflightSDDocumentSessionInternalTextEditRanges(session, input) {
254897
+ const internal = INTERNALS.get(session);
254898
+ if (!internal)
254899
+ throw new Error("internal: unknown SDDocumentSession instance");
254900
+ return preflightTextEditRanges({ state: internal.state, author: internal.author, ...input });
254901
+ }
254733
254902
  function validateSDDocumentSessionInternalImageMove(session, input) {
254734
254903
  const internal = INTERNALS.get(session);
254735
254904
  if (!internal)
@@ -255243,6 +255412,9 @@ function applyHistoryEntryThroughBackend(state, entry, direction) {
255243
255412
  if (!patchGroup)
255244
255413
  return { status: "rejected", rejectedReason: "patch-precondition-failed" };
255245
255414
  const prepared = prepareHistoryReplayMutation(state, entry, direction, patchGroup);
255415
+ if (entry.preparedReplayInputs?.wholeBodyTextReplacement && !prepared.backendExtensions.storySurface?.wholeBodyTextReplacement) {
255416
+ return { status: "rejected", rejectedReason: "patch-precondition-failed" };
255417
+ }
255246
255418
  const exactRender = prepareExactHistoryRenderInput(state, prepared, entry, direction);
255247
255419
  const result = getMutationExecutionBackend(state).apply(prepared);
255248
255420
  if (result.status !== "committed" || !result.applyResult) {
@@ -255464,6 +255636,7 @@ function prepareHistoryReplayMutation(state, entry, direction, patchGroup) {
255464
255636
  const controlOwner = storyPartOwnership[0];
255465
255637
  const controlBytes = controlOwner && state.packageBytes.get(controlOwner.partUri);
255466
255638
  const controlPatch = controlOwner && patchGroup.perPart[controlOwner.partUri];
255639
+ const wholeBodyTextReplacement = patchGroup.source.kind === "storySurfaceRewrite" ? prepareWholeBodyTextReplacement(state, patchGroup.source, patchGroup.perPart, entry.preparedReplayInputs?.wholeBodyTextReplacement) : null;
255467
255640
  const contentControlRewrite = patchGroup.source.kind === "storySurfaceRewrite" && patchGroup.source.contentControlRewrite && controlBytes && controlPatch ? prepareContentControlRewrite(controlBytes, controlPatch) : null;
255468
255641
  const declaredStoryTargetBlockIds = patchGroup.source.kind === "storySurfaceRewrite" || patchGroup.source.kind === "storyFormatMutation" ? [...new Set(patchGroup.source.targetBlockIds)] : [];
255469
255642
  const compareParagraphInsertions = entry.preparedReplayInputs?.compareParagraphInsertions ?? [];
@@ -255522,7 +255695,8 @@ function prepareHistoryReplayMutation(state, entry, direction, patchGroup) {
255522
255695
  backendExtensions: {
255523
255696
  ...patchGroup.storiesTouched.length > 0 ? {
255524
255697
  storySurface: {
255525
- family: patchGroup.source.kind === "storySurfaceRewrite" && patchGroup.source.contentControlRewrite ? "storyBlocks" : inferHistoryStorySurfaceFamily(String(patchGroup.source.kind)),
255698
+ family: wholeBodyTextReplacement || patchGroup.source.kind === "storySurfaceRewrite" && patchGroup.source.contentControlRewrite ? "storyBlocks" : inferHistoryStorySurfaceFamily(String(patchGroup.source.kind)),
255699
+ ...wholeBodyTextReplacement ? { wholeBodyTextReplacement } : {},
255526
255700
  ...contentControlRewrite ? { contentControlRewrite } : {},
255527
255701
  ...patchGroup.source.kind === "storySurfaceRewrite" ? { headerFooterUpdate: prepareHeaderFooterUpdate(state, patchGroup.source, patchGroup.perPart, direction) ?? undefined } : {},
255528
255702
  storyLocal: !touchesPackageSidecar,
@@ -257505,6 +257679,7 @@ var init_sd_document_session = __esm(() => {
257505
257679
  init_textbox_atom_replacement();
257506
257680
  init_paragraph_signal_index();
257507
257681
  init_content_control_rewrite();
257682
+ init_whole_body_text_replacement();
257508
257683
  init_header_footer_update();
257509
257684
  init_session_hyperlink_metadata();
257510
257685
  init_history_text_replay();
@@ -258804,6 +258979,63 @@ var init_textbox_registry_session = __esm(() => {
258804
258979
  init_sd_document_session();
258805
258980
  });
258806
258981
 
258982
+ // ../../../v2/editor-core/dist/document/transactions/selection-text-replacement-preflight.js
258983
+ function validateSelectionTextReplacement(input) {
258984
+ const { bytes, index, on } = input;
258985
+ const start = index.byParaId(on.startBlockId);
258986
+ const end = index.byParaId(on.endBlockId);
258987
+ if (!start || !end || start.ordinal > end.ordinal || start.partUri !== end.partUri || start.storyId !== end.storyId || index.duplicateParaIds.size > 0)
258988
+ return "invalid-range";
258989
+ const integrity = validateParagraphRangeIntegrity({
258990
+ bytes,
258991
+ index,
258992
+ ...on,
258993
+ fieldCatalog: buildFieldCatalog({ bytes, storyId: start.storyId, partUri: start.partUri }),
258994
+ ...input.removedByteRange ? { removedByteRange: input.removedByteRange } : {}
258995
+ });
258996
+ if (!integrity.ok) {
258997
+ if (integrity.reason === "partial-bookmark")
258998
+ return "text-range-in-bookmark";
258999
+ if (integrity.reason === "partial-range-marker")
259000
+ return "text-range-in-range-marker";
259001
+ if (integrity.reason === "unresolved-range")
259002
+ return "invalid-range";
259003
+ return "text-range-in-field";
259004
+ }
259005
+ const map3 = buildStructuralBoundaryMap(bytes);
259006
+ const firstContext = map3.byBlockId(start.blockId);
259007
+ if (!firstContext)
259008
+ return "invalid-range";
259009
+ for (const entry of index.entries) {
259010
+ if (entry.ordinal < start.ordinal || entry.ordinal > end.ordinal)
259011
+ continue;
259012
+ const context = map3.byBlockId(entry.blockId);
259013
+ if (!context)
259014
+ return "invalid-range";
259015
+ if (context.blockSdtPath.length)
259016
+ return "text-range-cross-block-sdt";
259017
+ if (context.blockCustomXmlPath.length)
259018
+ return "text-range-cross-block-custom-xml";
259019
+ if (context.sectionIndex !== firstContext.sectionIndex || context.carriesSectionBreak)
259020
+ return "text-range-cross-section-boundary";
259021
+ if (context.hasObjectAnchor)
259022
+ return "text-range-cross-object-anchor";
259023
+ if (context.hasMathObject)
259024
+ return "text-range-in-equation";
259025
+ }
259026
+ return input.removedByteRange ? validateRangeInlineSdtProtection(bytes, index.entries, start, end, {
259027
+ startOffset: on.startOffset,
259028
+ endOffset: on.endOffset,
259029
+ deleteFullBlocks: true
259030
+ }) : null;
259031
+ }
259032
+ var init_selection_text_replacement_preflight = __esm(() => {
259033
+ init_structural_boundary_map();
259034
+ init_field_catalog();
259035
+ init_range_integrity();
259036
+ init_compile_paragraph_ops();
259037
+ });
259038
+
258807
259039
  // ../../../v2/editor-core/dist/document/sd-document-session-internal.js
258808
259040
  var init_sd_document_session_internal = __esm(() => {
258809
259041
  init_core_properties();
@@ -258883,6 +259115,7 @@ var init_sd_document_session_internal = __esm(() => {
258883
259115
  init_bibliography_style();
258884
259116
  init_bibliography_review_resources();
258885
259117
  init_compile_compare_apply();
259118
+ init_selection_text_replacement_preflight();
258886
259119
  });
258887
259120
 
258888
259121
  // ../../../v2/document-api-v2-adapter/dist/address/story-identity.js
@@ -331009,9 +331242,60 @@ var init_tracked_body_replacement = __esm(() => {
331009
331242
  function rewriteWholeBodySelectionText(bytes, index2, text4) {
331010
331243
  const first = index2.entries[0];
331011
331244
  const last = index2.entries[index2.entries.length - 1];
331012
- if (!first || !last || !directBodyRangeIsStructurallyPlain(bytes, index2.entries, first, last, "tracked")) {
331245
+ if (!first || !last)
331246
+ return { ok: false, reason: "invalid-range" };
331247
+ if (directBodyRangeIsStructurallyPlain(bytes, index2.entries, first, last, "tracked")) {
331248
+ const reason = validateSelectionTextReplacement({
331249
+ bytes,
331250
+ index: index2,
331251
+ on: {
331252
+ startBlockId: first.blockId,
331253
+ startOffset: 0,
331254
+ endBlockId: last.blockId,
331255
+ endOffset: last.textLength
331256
+ }
331257
+ });
331258
+ return reason ? { ok: false, reason } : rewritePlainBody(bytes, index2, text4);
331259
+ }
331260
+ const sourceXml = decoder6.decode(bytes);
331261
+ const parsed = collectXmlElementRanges(sourceXml);
331262
+ if (parsed.errors.length)
331263
+ return { ok: false, reason: "invalid-range" };
331264
+ const document5 = parsed.ranges.find((range) => range.tag.namespaceUri === word3 && range.tag.localName === "document");
331265
+ if (!document5)
331266
+ return { ok: false, reason: "invalid-range" };
331267
+ const body = directChildren3(sourceXml, document5, parsed.ranges)?.find((range) => range.tag.namespaceUri === word3 && range.tag.localName === "body");
331268
+ if (!body || body.tag.isSelfClosing)
331269
+ return { ok: false, reason: "invalid-range" };
331270
+ const children2 = directChildren3(sourceXml, body, parsed.ranges);
331271
+ if (!children2?.length)
331272
+ return { ok: false, reason: "unsupported-context" };
331273
+ const section = children2.at(-1);
331274
+ const contentEnd = section?.tag.namespaceUri === word3 && section.tag.localName === "sectPr" ? section.start : body.closeStart;
331275
+ if (children2.some((child) => child.start < contentEnd && (child.tag.namespaceUri !== word3 || !["p", "tbl"].includes(child.tag.localName)))) {
331013
331276
  return { ok: false, reason: "unsupported-context" };
331014
331277
  }
331278
+ const protection = validateSelectionTextReplacement({
331279
+ bytes,
331280
+ index: index2,
331281
+ on: {
331282
+ startBlockId: first.blockId,
331283
+ startOffset: 0,
331284
+ endBlockId: last.blockId,
331285
+ endOffset: last.textLength
331286
+ },
331287
+ removedByteRange: {
331288
+ startByte: encoder2.encode(sourceXml.slice(0, body.openEnd)).length,
331289
+ endByte: encoder2.encode(sourceXml.slice(0, contentEnd)).length
331290
+ }
331291
+ });
331292
+ if (protection)
331293
+ return { ok: false, reason: protection };
331294
+ return rewriteMixedBody(sourceXml, body, contentEnd, parsed.ranges, first.byteStart, text4);
331295
+ }
331296
+ function rewritePlainBody(bytes, index2, text4) {
331297
+ const first = index2.entries[0];
331298
+ const last = index2.entries[index2.entries.length - 1];
331015
331299
  const firstXml = decoder6.decode(bytes.subarray(first.byteStart, first.byteEnd));
331016
331300
  const lastXml = decoder6.decode(bytes.subarray(last.byteStart, last.byteEnd));
331017
331301
  let splitExistingRevision = false;
@@ -331056,10 +331340,68 @@ function rewriteWholeBodySelectionText(bytes, index2, text4) {
331056
331340
  xml: decoder6.decode(bytes.subarray(0, first.byteStart)) + rewritten.xml + decoder6.decode(bytes.subarray(last.byteEnd))
331057
331341
  };
331058
331342
  }
331059
- var decoder6;
331343
+ function directChildren3(xml, parent, ranges) {
331344
+ const children2 = [];
331345
+ let cursor = parent.openEnd;
331346
+ for (const range of [...ranges].sort((a, b) => a.start - b.start || b.end - a.end)) {
331347
+ if (range.start < cursor || range.end > parent.closeStart)
331348
+ continue;
331349
+ if (xml.slice(cursor, range.start).trim())
331350
+ return null;
331351
+ children2.push(range);
331352
+ cursor = range.end;
331353
+ }
331354
+ return xml.slice(cursor, parent.closeStart).trim() ? null : children2;
331355
+ }
331356
+ function rewriteMixedBody(xml, body, contentEnd, ranges, firstByteStart, text4) {
331357
+ const unsupported4 = new Set([
331358
+ "sectPr",
331359
+ "ins",
331360
+ "del",
331361
+ "moveFrom",
331362
+ "moveTo",
331363
+ "pPrChange",
331364
+ "tblPrChange",
331365
+ "trPrChange",
331366
+ "tcPrChange",
331367
+ "tblGridChange"
331368
+ ]);
331369
+ if (ranges.some((range) => range.start >= body.openEnd && range.end <= contentEnd && range.tag.namespaceUri === word3 && unsupported4.has(range.tag.localName))) {
331370
+ return { ok: false, reason: "unsupported-context" };
331371
+ }
331372
+ const beforeXml = xml.slice(body.openEnd, contentEnd);
331373
+ if (!prepareTrackedBlockXmlReplacement({
331374
+ beforeXml,
331375
+ afterXml: "",
331376
+ namespaceBindings: new Map(Object.entries(body.namespaceBindings)),
331377
+ stamp: { revisionId: 0, author: { name: "Preview" }, date: "1970-01-01T00:00:00.000Z" }
331378
+ }))
331379
+ return { ok: false, reason: "unsupported-context" };
331380
+ const firstStart = decoder6.decode(encoder2.encode(xml).subarray(0, firstByteStart)).length;
331381
+ const first = ranges.find((range) => range.start === firstStart && range.tag.namespaceUri === word3 && range.tag.localName === "p");
331382
+ if (!first || first.start < body.openEnd || first.end > contentEnd)
331383
+ return { ok: false, reason: "invalid-range" };
331384
+ const firstChildren = first.tag.isSelfClosing ? [] : directChildren3(xml, first, ranges);
331385
+ if (!firstChildren)
331386
+ return { ok: false, reason: "invalid-range" };
331387
+ const properties = firstChildren[0]?.tag.namespaceUri === word3 && firstChildren[0].tag.localName === "pPr" ? xml.slice(firstChildren[0].start, firstChildren[0].end) : "";
331388
+ const prefix = first.tag.prefix ? first.tag.prefix + ":" : "";
331389
+ const escaped = text4.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
331390
+ const run = "<" + prefix + "r><" + prefix + 't xml:space="preserve">' + escaped + "</" + prefix + "t></" + prefix + "r>";
331391
+ const paragraph3 = xml.slice(first.start, first.openEnd).replace(/\/>$/, ">") + properties + run + "</" + first.tag.name + ">";
331392
+ const relocated = closeNamespaceScope(paragraph3, first.namespaceBindings, body.namespaceBindings);
331393
+ if (relocated === null)
331394
+ return { ok: false, reason: "invalid-range" };
331395
+ const result = xml.slice(0, body.openEnd) + relocated + xml.slice(contentEnd);
331396
+ if (collectXmlElementRanges(result).errors.length)
331397
+ return { ok: false, reason: "invalid-range" };
331398
+ return { ok: true, xml: result };
331399
+ }
331400
+ var decoder6, encoder2, word3 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
331060
331401
  var init_whole_body_selection_text = __esm(() => {
331061
331402
  init_sd_document_session_internal();
331062
331403
  decoder6 = new TextDecoder;
331404
+ encoder2 = new TextEncoder;
331063
331405
  });
331064
331406
 
331065
331407
  // ../../../v2/document-api-v2-adapter/dist/selection-mutation/cross-cell-delete.js
@@ -331930,6 +332272,13 @@ class V2SelectionMutationAdapter {
331930
332272
  resolution: edits[0].resolution
331931
332273
  };
331932
332274
  }
332275
+ if (options?.dryRun) {
332276
+ const reason = preflightSDDocumentSessionInternalTextEditRanges(this.context.session, {
332277
+ changeMode: options.changeMode ?? "direct",
332278
+ edits: [kernelEdits[0], ...kernelEdits.slice(1)]
332279
+ });
332280
+ return reason ? { success: false, failure: { code: mapRejectionReason(reason), message: reason }, resolution: edits[0].resolution } : { success: true, resolution: edits[0].resolution };
332281
+ }
331933
332282
  begun.tx.editTextRanges({
331934
332283
  changeMode: options?.changeMode ?? "direct",
331935
332284
  edits: kernelEdits
@@ -332112,30 +332461,21 @@ class V2SelectionMutationAdapter {
332112
332461
  if ("error" in wholeStory) {
332113
332462
  return failureWithoutResolution(wholeStory.error, wholeStory.message);
332114
332463
  }
332115
- if (request.text.length > 0 && wholeStory.crossParagraph) {
332464
+ if (request.text.length > 0) {
332116
332465
  if (!isDirectTextPayload(request.text)) {
332117
332466
  return failureWithoutResolution("INVALID_PAYLOAD", "replacement text contains unsupported control characters for direct text replace.");
332118
332467
  }
332119
- const plan = resolveCrossParagraphSelectionPlan({
332120
- target: wholeStory.normalizedTarget,
332121
- index: index2,
332122
- readPartBytes: (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri),
332123
- buildOffsetMap: buildOffsetMapForCoordinateSpace3,
332124
- ...offsetSpace ? { offsetSpace } : {}
332125
- });
332126
- if ("error" in plan)
332127
- return failureWithoutResolution(plan.error, plan.message);
332128
- const preflight = preflightSelectionRangeCollapse({ context: this.context, index: index2, changeMode: "tracked" }, plan);
332129
- if (preflight)
332130
- return failureWithoutResolution(preflight.failure.code, preflight.failure.message);
332131
- return this.executeWholeBodyTextReplace({
332132
- ...wholeStory.normalizedTarget,
332133
- start: { kind: "text", blockId: plan.startBlockId, offset: plan.startOffset },
332134
- end: { kind: "text", blockId: plan.endBlockId, offset: plan.endOffset }
332135
- }, storyLocator, request.text, options, plan);
332136
- }
332137
- if (request.text.length > 0) {
332138
- return failureWithoutResolution("CAPABILITY_UNAVAILABLE", "whole-body replacement requires direct body paragraphs.");
332468
+ const plan = {
332469
+ kind: "cross-paragraph",
332470
+ startBlockId: wholeStory.resolved.startBlockId,
332471
+ endBlockId: wholeStory.resolved.endBlockId,
332472
+ startOffset: wholeStory.resolved.startOffset,
332473
+ endOffset: wholeStory.resolved.endOffset,
332474
+ startTextLength: index2.entries[0].textLength,
332475
+ normalizedTarget: wholeStory.normalizedTarget,
332476
+ resolved: wholeStory.resolved
332477
+ };
332478
+ return this.executeWholeBodyTextReplace(wholeStory.normalizedTarget, storyLocator, request.text, options, plan);
332139
332479
  }
332140
332480
  const effectiveStory2 = effectiveResolutionStory(story, storyLocator);
332141
332481
  const selectedText2 = wholeStory.crossParagraph ? readResolvedMultiParagraphText(index2, this.context.session, wholeStory.resolved) : readResolvedSelectionText(index2, this.context.session, wholeStory.resolved);
@@ -332168,6 +332508,17 @@ class V2SelectionMutationAdapter {
332168
332508
  });
332169
332509
  }
332170
332510
  }
332511
+ if (request.text.length > 0 && target.start.kind === "text" && target.end.kind === "text" && target.start.blockId !== target.end.blockId && selectionCrossesTableCells(index2, (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri), target)) {
332512
+ return this.executeCrossTableTextReplace({
332513
+ target,
332514
+ index: index2,
332515
+ text: request.text,
332516
+ story: effectiveResolutionStory(story, storyLocator),
332517
+ storyLocator,
332518
+ offsetSpace,
332519
+ options
332520
+ });
332521
+ }
332171
332522
  if (target.start.kind === "text" && target.end.kind === "text" && target.start.blockId !== target.end.blockId && (request.text === "" || (options?.changeMode ?? "direct") === "direct")) {
332172
332523
  const readPartBytes3 = (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri);
332173
332524
  if (request.text === "" && (options?.changeMode ?? "direct") === "direct" && selectionCrossesTableCells(index2, readPartBytes3, target)) {
@@ -332455,6 +332806,90 @@ class V2SelectionMutationAdapter {
332455
332806
  buildInsertedTextEffectMs
332456
332807
  });
332457
332808
  }
332809
+ executeCrossTableTextReplace(input) {
332810
+ const { target, index: index2, text: text4, story, storyLocator, offsetSpace, options } = input;
332811
+ if (target.coordinateSpace === "tracked") {
332812
+ return failureWithoutResolution("CAPABILITY_UNAVAILABLE", "text-range-cross-paragraph-tracked-coordinate-unsupported");
332813
+ }
332814
+ if (!isDirectTextPayload(text4))
332815
+ return failureWithoutResolution("INVALID_PAYLOAD", "text-payload-unsupported-control-char");
332816
+ const plan = resolveCrossCellDeletePlan({
332817
+ context: this.context,
332818
+ storyLocator,
332819
+ offsetSpace,
332820
+ buildOffsetMap: buildOffsetMapForCoordinateSpace3
332821
+ }, index2, target);
332822
+ if ("error" in plan)
332823
+ return failureWithoutResolution(plan.error, plan.message);
332824
+ if (plan.segments.some((segment) => segment.firstBlockId !== segment.lastBlockId || segment.selectedObjects.length > 0)) {
332825
+ return failureWithoutResolution("CAPABILITY_UNAVAILABLE", "table text replacement requires one text paragraph per selected container.");
332826
+ }
332827
+ const first = index2.byParaId(plan.startBlockId);
332828
+ const bytes = getSDDocumentSessionInternalPartBytes(this.context.session, first.partUri);
332829
+ if (!bytes)
332830
+ return failureWithoutResolution("PRECONDITION_FAILED", "selection story bytes are unavailable.");
332831
+ const globalFailure = validateSelectionTextReplacement({ bytes, index: index2, on: plan });
332832
+ if (globalFailure)
332833
+ return failureWithoutResolution(mapRejectionReason(globalFailure), globalFailure);
332834
+ const edits = [];
332835
+ for (const [ordinal, segment] of plan.segments.entries()) {
332836
+ const segmentTarget = {
332837
+ kind: "selection",
332838
+ start: { kind: "text", blockId: segment.firstBlockId, offset: segment.firstOffset },
332839
+ end: { kind: "text", blockId: segment.lastBlockId, offset: segment.lastOffset },
332840
+ ...target.story ? { story: target.story } : {}
332841
+ };
332842
+ const on = resolveSelectionTargetToRange({
332843
+ target: segmentTarget,
332844
+ index: index2,
332845
+ readPartBytes: (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri),
332846
+ readPartRange: (partUri, start, end) => getSDDocumentSessionInternalPartRange(this.context.session, partUri, start, end),
332847
+ buildOffsetMap: buildOffsetMapForCoordinateSpace3,
332848
+ offsetSpace: "kernel"
332849
+ });
332850
+ if ("error" in on)
332851
+ return failureWithoutResolution(on.error, on.message);
332852
+ const selectedText = readResolvedSelectionText(index2, this.context.session, on);
332853
+ edits.push({
332854
+ on,
332855
+ newText: ordinal === 0 ? text4 : "",
332856
+ resolution: buildResolution2({ target: segmentTarget, story, selectedText, resolved: on }),
332857
+ rewriteIntent: true
332858
+ });
332859
+ }
332860
+ if (!edits.length)
332861
+ return failureWithoutResolution("INVALID_TARGET", "selection contains no editable text range.");
332862
+ const ranges = [edits[0], ...edits.slice(1)];
332863
+ const preview = this.executeResolvedTextRewrites(ranges, { ...options, dryRun: true });
332864
+ if (!preview.success)
332865
+ return preview;
332866
+ const resolved = { ...edits[0].on, endBlockId: plan.endBlockId, endOffset: plan.endOffset, endByte: plan.endByte };
332867
+ const resolution = buildCrossParagraphResolution({
332868
+ plan: { kind: "cross-paragraph", ...plan, resolved },
332869
+ story,
332870
+ selectedText: readResolvedMultiParagraphText(index2, this.context.session, plan)
332871
+ });
332872
+ if (options?.dryRun)
332873
+ return { success: true, resolution };
332874
+ const receipt3 = this.executeResolvedTextRewrites(ranges, options);
332875
+ receipt3.resolution = resolution;
332876
+ if (receipt3.success) {
332877
+ if (receipt3.trackedChangeRefs?.length)
332878
+ receipt3.inserted = receipt3.trackedChangeRefs;
332879
+ const effects2 = buildInsertedTextEffect({
332880
+ blockId: plan.startBlockId,
332881
+ baseOffset: plan.startOffset,
332882
+ paintedBaseOffset: plan.normalizedTarget.start.kind === "text" ? plan.normalizedTarget.start.offset : plan.startOffset,
332883
+ text: text4,
332884
+ story,
332885
+ changeMode: options?.changeMode ?? "direct",
332886
+ coordinateSpace: "visible"
332887
+ });
332888
+ if (effects2)
332889
+ receipt3.effects = effects2;
332890
+ }
332891
+ return receipt3;
332892
+ }
332458
332893
  executeCrossParagraphReplace(input) {
332459
332894
  const { target, index: index2, story, storyLocator, text: text4, startedAt, storyResolveMs, offsetSpace, options, atomicFieldDelete } = input;
332460
332895
  if (target.coordinateSpace === "tracked") {
@@ -333489,10 +333924,10 @@ class V2SelectionMutationAdapter {
333489
333924
  return failureWithoutResolution(mapRejectionReason(rewritten.reason), rewritten.reason);
333490
333925
  nextXml = rewritten.xml;
333491
333926
  } else {
333492
- nextXml = rewriteBodyToSingleTextParagraph(sourceXml, first.blockId, replacementText);
333493
- }
333494
- if (nextXml == null) {
333495
- return failureWithoutResolution("INTERNAL_ERROR", "document body could not be rewritten.");
333927
+ const rewritten = rewriteBodyToSingleTextParagraph(sourceXml, first.blockId, replacementText);
333928
+ if (rewritten == null)
333929
+ return failureWithoutResolution("INTERNAL_ERROR", "document body could not be rewritten.");
333930
+ nextXml = rewritten;
333496
333931
  }
333497
333932
  const changeMode = options?.changeMode ?? "direct";
333498
333933
  let replacementParagraphId = first.blockId;
@@ -333543,7 +333978,10 @@ class V2SelectionMutationAdapter {
333543
333978
  },
333544
333979
  storySurface: {
333545
333980
  family: "storyBlocks",
333546
- targetBlockIds: [first.blockId],
333981
+ targetBlockIds: [
333982
+ ...index2.entries.map((entry) => entry.blockId),
333983
+ ...createdRefs.flatMap((ref5) => ref5.kind === "block" ? [ref5.nodeId] : [])
333984
+ ],
333547
333985
  changeMode
333548
333986
  }
333549
333987
  });
@@ -333555,12 +333993,12 @@ class V2SelectionMutationAdapter {
333555
333993
  };
333556
333994
  }
333557
333995
  const storyRef = { kind: "story", storyType: "body" };
333558
- const effects2 = buildInsertedTextEffect({
333996
+ const effects2 = buildCreatedTextEffect({
333559
333997
  blockId: replacementParagraphId,
333560
- baseOffset: 0,
333998
+ start: 0,
333999
+ paintedStart: 0,
333561
334000
  text: replacementText,
333562
- story: storyRef,
333563
- changeMode
334001
+ story: storyRef
333564
334002
  });
333565
334003
  const inserted = projectTrackedStructuralEntityIds(this.context, createdRefs.flatMap((ref5) => ref5.kind === "trackedChange" ? [ref5.entityId] : [])).map((entityId) => ({ kind: "entity", entityType: "trackedChange", entityId }));
333566
334004
  return {
@@ -333752,8 +334190,20 @@ function buildInsertedTextEffect(input) {
333752
334190
  }
333753
334191
  start = proof.startOffset;
333754
334192
  }
334193
+ return buildCreatedTextEffect({
334194
+ blockId: input.blockId,
334195
+ start,
334196
+ paintedStart: input.paintedBaseOffset ?? input.baseOffset,
334197
+ text: input.text,
334198
+ story: input.story
334199
+ });
334200
+ }
334201
+ function buildCreatedTextEffect(input) {
334202
+ if (!input.text.length)
334203
+ return;
334204
+ const start = input.start;
333755
334205
  const end = start + input.text.length;
333756
- const paintedStart = input.paintedBaseOffset ?? input.baseOffset;
334206
+ const paintedStart = input.paintedStart;
333757
334207
  const paintedEnd = paintedStart + input.text.length;
333758
334208
  const storyPart = input.story ? { story: input.story } : {};
333759
334209
  const target = {
@@ -366755,7 +367205,7 @@ function isStructurallyBlankStoryParagraph(input) {
366755
367205
  function positiveNoteCaptures(bytes, family) {
366756
367206
  const xml = new TextDecoder().decode(bytes);
366757
367207
  const bomLength = bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? 3 : 0;
366758
- const encoder2 = new TextEncoder;
367208
+ const encoder3 = new TextEncoder;
366759
367209
  const local = family === "footnotes" ? "footnote" : "endnote";
366760
367210
  const parsed = collectXmlElementRanges(xml);
366761
367211
  if (parsed.errors.length > 0)
@@ -366770,13 +367220,13 @@ function positiveNoteCaptures(bytes, family) {
366770
367220
  if (!id || !Number.isSafeInteger(Number(id)) || Number(id) <= 0)
366771
367221
  continue;
366772
367222
  const noteXml = xml.slice(range.start, range.end);
366773
- const byteStart = bomLength + encoder2.encode(xml.slice(0, range.start)).length;
367223
+ const byteStart = bomLength + encoder3.encode(xml.slice(0, range.start)).length;
366774
367224
  result.push({
366775
367225
  noteId: id,
366776
367226
  noteXml,
366777
367227
  rootOpenTag,
366778
367228
  byteStart,
366779
- byteEnd: byteStart + encoder2.encode(noteXml).length
367229
+ byteEnd: byteStart + encoder3.encode(noteXml).length
366780
367230
  });
366781
367231
  }
366782
367232
  return result;
@@ -400739,167 +401189,167 @@ class StringEncoder {
400739
401189
  this.lensE.write(string7.length);
400740
401190
  }
400741
401191
  toUint8Array() {
400742
- const encoder2 = new Encoder;
401192
+ const encoder3 = new Encoder;
400743
401193
  this.sarr.push(this.s);
400744
401194
  this.s = "";
400745
- writeVarString(encoder2, this.sarr.join(""));
400746
- writeUint8Array(encoder2, this.lensE.toUint8Array());
400747
- return toUint8Array(encoder2);
401195
+ writeVarString(encoder3, this.sarr.join(""));
401196
+ writeUint8Array(encoder3, this.lensE.toUint8Array());
401197
+ return toUint8Array(encoder3);
400748
401198
  }
400749
401199
  }
400750
- var createEncoder = () => new Encoder, length = (encoder2) => {
400751
- let len = encoder2.cpos;
400752
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
400753
- len += encoder2.bufs[i2].length;
401200
+ var createEncoder = () => new Encoder, length = (encoder3) => {
401201
+ let len = encoder3.cpos;
401202
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
401203
+ len += encoder3.bufs[i2].length;
400754
401204
  }
400755
401205
  return len;
400756
- }, toUint8Array = (encoder2) => {
400757
- const uint8arr = new Uint8Array(length(encoder2));
401206
+ }, toUint8Array = (encoder3) => {
401207
+ const uint8arr = new Uint8Array(length(encoder3));
400758
401208
  let curPos = 0;
400759
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
400760
- const d = encoder2.bufs[i2];
401209
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
401210
+ const d = encoder3.bufs[i2];
400761
401211
  uint8arr.set(d, curPos);
400762
401212
  curPos += d.length;
400763
401213
  }
400764
- uint8arr.set(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos), curPos);
401214
+ uint8arr.set(new Uint8Array(encoder3.cbuf.buffer, 0, encoder3.cpos), curPos);
400765
401215
  return uint8arr;
400766
- }, verifyLen = (encoder2, len) => {
400767
- const bufferLen = encoder2.cbuf.length;
400768
- if (bufferLen - encoder2.cpos < len) {
400769
- encoder2.bufs.push(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos));
400770
- encoder2.cbuf = new Uint8Array(max2(bufferLen, len) * 2);
400771
- encoder2.cpos = 0;
400772
- }
400773
- }, write = (encoder2, num) => {
400774
- const bufferLen = encoder2.cbuf.length;
400775
- if (encoder2.cpos === bufferLen) {
400776
- encoder2.bufs.push(encoder2.cbuf);
400777
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
400778
- encoder2.cpos = 0;
400779
- }
400780
- encoder2.cbuf[encoder2.cpos++] = num;
400781
- }, writeUint8, writeVarUint = (encoder2, num) => {
401216
+ }, verifyLen = (encoder3, len) => {
401217
+ const bufferLen = encoder3.cbuf.length;
401218
+ if (bufferLen - encoder3.cpos < len) {
401219
+ encoder3.bufs.push(new Uint8Array(encoder3.cbuf.buffer, 0, encoder3.cpos));
401220
+ encoder3.cbuf = new Uint8Array(max2(bufferLen, len) * 2);
401221
+ encoder3.cpos = 0;
401222
+ }
401223
+ }, write = (encoder3, num) => {
401224
+ const bufferLen = encoder3.cbuf.length;
401225
+ if (encoder3.cpos === bufferLen) {
401226
+ encoder3.bufs.push(encoder3.cbuf);
401227
+ encoder3.cbuf = new Uint8Array(bufferLen * 2);
401228
+ encoder3.cpos = 0;
401229
+ }
401230
+ encoder3.cbuf[encoder3.cpos++] = num;
401231
+ }, writeUint8, writeVarUint = (encoder3, num) => {
400782
401232
  while (num > BITS7) {
400783
- write(encoder2, BIT8 | BITS7 & num);
401233
+ write(encoder3, BIT8 | BITS7 & num);
400784
401234
  num = floor(num / 128);
400785
401235
  }
400786
- write(encoder2, BITS7 & num);
400787
- }, writeVarInt = (encoder2, num) => {
401236
+ write(encoder3, BITS7 & num);
401237
+ }, writeVarInt = (encoder3, num) => {
400788
401238
  const isNegative = isNegativeZero(num);
400789
401239
  if (isNegative) {
400790
401240
  num = -num;
400791
401241
  }
400792
- write(encoder2, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
401242
+ write(encoder3, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
400793
401243
  num = floor(num / 64);
400794
401244
  while (num > 0) {
400795
- write(encoder2, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
401245
+ write(encoder3, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
400796
401246
  num = floor(num / 128);
400797
401247
  }
400798
- }, _strBuffer, _maxStrBSize, _writeVarStringNative = (encoder2, str) => {
401248
+ }, _strBuffer, _maxStrBSize, _writeVarStringNative = (encoder3, str) => {
400799
401249
  if (str.length < _maxStrBSize) {
400800
401250
  const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
400801
- writeVarUint(encoder2, written);
401251
+ writeVarUint(encoder3, written);
400802
401252
  for (let i2 = 0;i2 < written; i2++) {
400803
- write(encoder2, _strBuffer[i2]);
401253
+ write(encoder3, _strBuffer[i2]);
400804
401254
  }
400805
401255
  } else {
400806
- writeVarUint8Array(encoder2, encodeUtf8(str));
401256
+ writeVarUint8Array(encoder3, encodeUtf8(str));
400807
401257
  }
400808
- }, _writeVarStringPolyfill = (encoder2, str) => {
401258
+ }, _writeVarStringPolyfill = (encoder3, str) => {
400809
401259
  const encodedString = unescape(encodeURIComponent(str));
400810
401260
  const len = encodedString.length;
400811
- writeVarUint(encoder2, len);
401261
+ writeVarUint(encoder3, len);
400812
401262
  for (let i2 = 0;i2 < len; i2++) {
400813
- write(encoder2, encodedString.codePointAt(i2));
401263
+ write(encoder3, encodedString.codePointAt(i2));
400814
401264
  }
400815
- }, writeVarString, writeUint8Array = (encoder2, uint8Array) => {
400816
- const bufferLen = encoder2.cbuf.length;
400817
- const cpos = encoder2.cpos;
401265
+ }, writeVarString, writeUint8Array = (encoder3, uint8Array) => {
401266
+ const bufferLen = encoder3.cbuf.length;
401267
+ const cpos = encoder3.cpos;
400818
401268
  const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
400819
401269
  const rightCopyLen = uint8Array.length - leftCopyLen;
400820
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
400821
- encoder2.cpos += leftCopyLen;
401270
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
401271
+ encoder3.cpos += leftCopyLen;
400822
401272
  if (rightCopyLen > 0) {
400823
- encoder2.bufs.push(encoder2.cbuf);
400824
- encoder2.cbuf = new Uint8Array(max2(bufferLen * 2, rightCopyLen));
400825
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
400826
- encoder2.cpos = rightCopyLen;
400827
- }
400828
- }, writeVarUint8Array = (encoder2, uint8Array) => {
400829
- writeVarUint(encoder2, uint8Array.byteLength);
400830
- writeUint8Array(encoder2, uint8Array);
400831
- }, writeOnDataView = (encoder2, len) => {
400832
- verifyLen(encoder2, len);
400833
- const dview = new DataView(encoder2.cbuf.buffer, encoder2.cpos, len);
400834
- encoder2.cpos += len;
401273
+ encoder3.bufs.push(encoder3.cbuf);
401274
+ encoder3.cbuf = new Uint8Array(max2(bufferLen * 2, rightCopyLen));
401275
+ encoder3.cbuf.set(uint8Array.subarray(leftCopyLen));
401276
+ encoder3.cpos = rightCopyLen;
401277
+ }
401278
+ }, writeVarUint8Array = (encoder3, uint8Array) => {
401279
+ writeVarUint(encoder3, uint8Array.byteLength);
401280
+ writeUint8Array(encoder3, uint8Array);
401281
+ }, writeOnDataView = (encoder3, len) => {
401282
+ verifyLen(encoder3, len);
401283
+ const dview = new DataView(encoder3.cbuf.buffer, encoder3.cpos, len);
401284
+ encoder3.cpos += len;
400835
401285
  return dview;
400836
- }, writeFloat32 = (encoder2, num) => writeOnDataView(encoder2, 4).setFloat32(0, num, false), writeFloat64 = (encoder2, num) => writeOnDataView(encoder2, 8).setFloat64(0, num, false), writeBigInt64 = (encoder2, num) => writeOnDataView(encoder2, 8).setBigInt64(0, num, false), floatTestBed, isFloat32 = (num) => {
401286
+ }, writeFloat32 = (encoder3, num) => writeOnDataView(encoder3, 4).setFloat32(0, num, false), writeFloat64 = (encoder3, num) => writeOnDataView(encoder3, 8).setFloat64(0, num, false), writeBigInt64 = (encoder3, num) => writeOnDataView(encoder3, 8).setBigInt64(0, num, false), floatTestBed, isFloat32 = (num) => {
400837
401287
  floatTestBed.setFloat32(0, num);
400838
401288
  return floatTestBed.getFloat32(0) === num;
400839
- }, writeAny = (encoder2, data) => {
401289
+ }, writeAny = (encoder3, data) => {
400840
401290
  switch (typeof data) {
400841
401291
  case "string":
400842
- write(encoder2, 119);
400843
- writeVarString(encoder2, data);
401292
+ write(encoder3, 119);
401293
+ writeVarString(encoder3, data);
400844
401294
  break;
400845
401295
  case "number":
400846
401296
  if (isInteger2(data) && abs(data) <= BITS31) {
400847
- write(encoder2, 125);
400848
- writeVarInt(encoder2, data);
401297
+ write(encoder3, 125);
401298
+ writeVarInt(encoder3, data);
400849
401299
  } else if (isFloat32(data)) {
400850
- write(encoder2, 124);
400851
- writeFloat32(encoder2, data);
401300
+ write(encoder3, 124);
401301
+ writeFloat32(encoder3, data);
400852
401302
  } else {
400853
- write(encoder2, 123);
400854
- writeFloat64(encoder2, data);
401303
+ write(encoder3, 123);
401304
+ writeFloat64(encoder3, data);
400855
401305
  }
400856
401306
  break;
400857
401307
  case "bigint":
400858
- write(encoder2, 122);
400859
- writeBigInt64(encoder2, data);
401308
+ write(encoder3, 122);
401309
+ writeBigInt64(encoder3, data);
400860
401310
  break;
400861
401311
  case "object":
400862
401312
  if (data === null) {
400863
- write(encoder2, 126);
401313
+ write(encoder3, 126);
400864
401314
  } else if (isArray(data)) {
400865
- write(encoder2, 117);
400866
- writeVarUint(encoder2, data.length);
401315
+ write(encoder3, 117);
401316
+ writeVarUint(encoder3, data.length);
400867
401317
  for (let i2 = 0;i2 < data.length; i2++) {
400868
- writeAny(encoder2, data[i2]);
401318
+ writeAny(encoder3, data[i2]);
400869
401319
  }
400870
401320
  } else if (data instanceof Uint8Array) {
400871
- write(encoder2, 116);
400872
- writeVarUint8Array(encoder2, data);
401321
+ write(encoder3, 116);
401322
+ writeVarUint8Array(encoder3, data);
400873
401323
  } else {
400874
- write(encoder2, 118);
401324
+ write(encoder3, 118);
400875
401325
  const keys = Object.keys(data);
400876
- writeVarUint(encoder2, keys.length);
401326
+ writeVarUint(encoder3, keys.length);
400877
401327
  for (let i2 = 0;i2 < keys.length; i2++) {
400878
401328
  const key2 = keys[i2];
400879
- writeVarString(encoder2, key2);
400880
- writeAny(encoder2, data[key2]);
401329
+ writeVarString(encoder3, key2);
401330
+ writeAny(encoder3, data[key2]);
400881
401331
  }
400882
401332
  }
400883
401333
  break;
400884
401334
  case "boolean":
400885
- write(encoder2, data ? 120 : 121);
401335
+ write(encoder3, data ? 120 : 121);
400886
401336
  break;
400887
401337
  default:
400888
- write(encoder2, 127);
401338
+ write(encoder3, 127);
400889
401339
  }
400890
- }, RleEncoder, flushUintOptRleEncoder = (encoder2) => {
400891
- if (encoder2.count > 0) {
400892
- writeVarInt(encoder2.encoder, encoder2.count === 1 ? encoder2.s : -encoder2.s);
400893
- if (encoder2.count > 1) {
400894
- writeVarUint(encoder2.encoder, encoder2.count - 2);
401340
+ }, RleEncoder, flushUintOptRleEncoder = (encoder3) => {
401341
+ if (encoder3.count > 0) {
401342
+ writeVarInt(encoder3.encoder, encoder3.count === 1 ? encoder3.s : -encoder3.s);
401343
+ if (encoder3.count > 1) {
401344
+ writeVarUint(encoder3.encoder, encoder3.count - 2);
400895
401345
  }
400896
401346
  }
400897
- }, flushIntDiffOptRleEncoder = (encoder2) => {
400898
- if (encoder2.count > 0) {
400899
- const encodedDiff = encoder2.diff * 2 + (encoder2.count === 1 ? 0 : 1);
400900
- writeVarInt(encoder2.encoder, encodedDiff);
400901
- if (encoder2.count > 1) {
400902
- writeVarUint(encoder2.encoder, encoder2.count - 2);
401347
+ }, flushIntDiffOptRleEncoder = (encoder3) => {
401348
+ if (encoder3.count > 0) {
401349
+ const encodedDiff = encoder3.diff * 2 + (encoder3.count === 1 ? 0 : 1);
401350
+ writeVarInt(encoder3.encoder, encodedDiff);
401351
+ if (encoder3.count > 1) {
401352
+ writeVarUint(encoder3.encoder, encoder3.count - 2);
400903
401353
  }
400904
401354
  }
400905
401355
  };
@@ -401678,11 +402128,11 @@ class PermanentUserData {
401678
402128
  user.get("ids").push([clientid2]);
401679
402129
  }
401680
402130
  });
401681
- const encoder2 = new DSEncoderV1;
402131
+ const encoder3 = new DSEncoderV1;
401682
402132
  const ds = this.dss.get(userDescription);
401683
402133
  if (ds) {
401684
- writeDeleteSet(encoder2, ds);
401685
- user.get("ds").push([encoder2.toUint8Array()]);
402134
+ writeDeleteSet(encoder3, ds);
402135
+ user.get("ds").push([encoder3.toUint8Array()]);
401686
402136
  }
401687
402137
  }
401688
402138
  }, 0);
@@ -401692,9 +402142,9 @@ class PermanentUserData {
401692
402142
  const yds = user.get("ds");
401693
402143
  const ds = transaction.deleteSet;
401694
402144
  if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {
401695
- const encoder2 = new DSEncoderV1;
401696
- writeDeleteSet(encoder2, ds);
401697
- yds.push([encoder2.toUint8Array()]);
402145
+ const encoder3 = new DSEncoderV1;
402146
+ writeDeleteSet(encoder3, ds);
402147
+ yds.push([encoder3.toUint8Array()]);
401698
402148
  }
401699
402149
  });
401700
402150
  });
@@ -401813,11 +402263,11 @@ class LazyStructReader {
401813
402263
  }
401814
402264
 
401815
402265
  class LazyStructWriter {
401816
- constructor(encoder2) {
402266
+ constructor(encoder3) {
401817
402267
  this.currClient = 0;
401818
402268
  this.startClock = 0;
401819
402269
  this.written = 0;
401820
- this.encoder = encoder2;
402270
+ this.encoder = encoder3;
401821
402271
  this.clientStructs = [];
401822
402272
  }
401823
402273
  }
@@ -402054,7 +402504,7 @@ class AbstractStruct {
402054
402504
  mergeWith(right) {
402055
402505
  return false;
402056
402506
  }
402057
- write(encoder2, offset, encodingRef) {
402507
+ write(encoder3, offset, encodingRef) {
402058
402508
  throw methodUnimplemented();
402059
402509
  }
402060
402510
  integrate(transaction, offset) {
@@ -402087,8 +402537,8 @@ class ContentBinary {
402087
402537
  integrate(transaction, item) {}
402088
402538
  delete(transaction) {}
402089
402539
  gc(store) {}
402090
- write(encoder2, offset) {
402091
- encoder2.writeBuf(this.content);
402540
+ write(encoder3, offset) {
402541
+ encoder3.writeBuf(this.content);
402092
402542
  }
402093
402543
  getRef() {
402094
402544
  return 3;
@@ -402126,8 +402576,8 @@ class ContentDeleted {
402126
402576
  }
402127
402577
  delete(transaction) {}
402128
402578
  gc(store) {}
402129
- write(encoder2, offset) {
402130
- encoder2.writeLen(this.len - offset);
402579
+ write(encoder3, offset) {
402580
+ encoder3.writeLen(this.len - offset);
402131
402581
  }
402132
402582
  getRef() {
402133
402583
  return 1;
@@ -402185,9 +402635,9 @@ class ContentDoc {
402185
402635
  }
402186
402636
  }
402187
402637
  gc(store) {}
402188
- write(encoder2, offset) {
402189
- encoder2.writeString(this.doc.guid);
402190
- encoder2.writeAny(this.opts);
402638
+ write(encoder3, offset) {
402639
+ encoder3.writeString(this.doc.guid);
402640
+ encoder3.writeAny(this.opts);
402191
402641
  }
402192
402642
  getRef() {
402193
402643
  return 9;
@@ -402219,8 +402669,8 @@ class ContentEmbed {
402219
402669
  integrate(transaction, item) {}
402220
402670
  delete(transaction) {}
402221
402671
  gc(store) {}
402222
- write(encoder2, offset) {
402223
- encoder2.writeJSON(this.embed);
402672
+ write(encoder3, offset) {
402673
+ encoder3.writeJSON(this.embed);
402224
402674
  }
402225
402675
  getRef() {
402226
402676
  return 5;
@@ -402257,9 +402707,9 @@ class ContentFormat {
402257
402707
  }
402258
402708
  delete(transaction) {}
402259
402709
  gc(store) {}
402260
- write(encoder2, offset) {
402261
- encoder2.writeKey(this.key);
402262
- encoder2.writeJSON(this.value);
402710
+ write(encoder3, offset) {
402711
+ encoder3.writeKey(this.key);
402712
+ encoder3.writeJSON(this.value);
402263
402713
  }
402264
402714
  getRef() {
402265
402715
  return 6;
@@ -402294,12 +402744,12 @@ class ContentJSON {
402294
402744
  integrate(transaction, item) {}
402295
402745
  delete(transaction) {}
402296
402746
  gc(store) {}
402297
- write(encoder2, offset) {
402747
+ write(encoder3, offset) {
402298
402748
  const len = this.arr.length;
402299
- encoder2.writeLen(len - offset);
402749
+ encoder3.writeLen(len - offset);
402300
402750
  for (let i2 = offset;i2 < len; i2++) {
402301
402751
  const c = this.arr[i2];
402302
- encoder2.writeString(c === undefined ? "undefined" : JSON.stringify(c));
402752
+ encoder3.writeString(c === undefined ? "undefined" : JSON.stringify(c));
402303
402753
  }
402304
402754
  }
402305
402755
  getRef() {
@@ -402336,12 +402786,12 @@ class ContentAny {
402336
402786
  integrate(transaction, item) {}
402337
402787
  delete(transaction) {}
402338
402788
  gc(store) {}
402339
- write(encoder2, offset) {
402789
+ write(encoder3, offset) {
402340
402790
  const len = this.arr.length;
402341
- encoder2.writeLen(len - offset);
402791
+ encoder3.writeLen(len - offset);
402342
402792
  for (let i2 = offset;i2 < len; i2++) {
402343
402793
  const c = this.arr[i2];
402344
- encoder2.writeAny(c);
402794
+ encoder3.writeAny(c);
402345
402795
  }
402346
402796
  }
402347
402797
  getRef() {
@@ -402382,8 +402832,8 @@ class ContentString {
402382
402832
  integrate(transaction, item) {}
402383
402833
  delete(transaction) {}
402384
402834
  gc(store) {}
402385
- write(encoder2, offset) {
402386
- encoder2.writeString(offset === 0 ? this.str : this.str.slice(offset));
402835
+ write(encoder3, offset) {
402836
+ encoder3.writeString(offset === 0 ? this.str : this.str.slice(offset));
402387
402837
  }
402388
402838
  getRef() {
402389
402839
  return 4;
@@ -402449,8 +402899,8 @@ class ContentType {
402449
402899
  });
402450
402900
  this.type._map = new Map;
402451
402901
  }
402452
- write(encoder2, offset) {
402453
- this.type._write(encoder2);
402902
+ write(encoder3, offset) {
402903
+ this.type._write(encoder3);
402454
402904
  }
402455
402905
  getRef() {
402456
402906
  return 7;
@@ -402542,17 +402992,17 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402542
402992
  }
402543
402993
  });
402544
402994
  return ds;
402545
- }, writeDeleteSet = (encoder2, ds) => {
402546
- writeVarUint(encoder2.restEncoder, ds.clients.size);
402995
+ }, writeDeleteSet = (encoder3, ds) => {
402996
+ writeVarUint(encoder3.restEncoder, ds.clients.size);
402547
402997
  from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => {
402548
- encoder2.resetDsCurVal();
402549
- writeVarUint(encoder2.restEncoder, client);
402998
+ encoder3.resetDsCurVal();
402999
+ writeVarUint(encoder3.restEncoder, client);
402550
403000
  const len = dsitems.length;
402551
- writeVarUint(encoder2.restEncoder, len);
403001
+ writeVarUint(encoder3.restEncoder, len);
402552
403002
  for (let i2 = 0;i2 < len; i2++) {
402553
403003
  const item = dsitems[i2];
402554
- encoder2.writeDsClock(item.clock);
402555
- encoder2.writeDsLen(item.len);
403004
+ encoder3.writeDsClock(item.clock);
403005
+ encoder3.writeDsLen(item.len);
402556
403006
  }
402557
403007
  });
402558
403008
  }, readDeleteSet = (decoder9) => {
@@ -402617,18 +403067,18 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402617
403067
  return ds.toUint8Array();
402618
403068
  }
402619
403069
  return null;
402620
- }, generateNewClientId, Doc2, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, writeStructs = (encoder2, structs, client, clock) => {
403070
+ }, generateNewClientId, Doc2, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, writeStructs = (encoder3, structs, client, clock) => {
402621
403071
  clock = max2(clock, structs[0].id.clock);
402622
403072
  const startNewStructs = findIndexSS(structs, clock);
402623
- writeVarUint(encoder2.restEncoder, structs.length - startNewStructs);
402624
- encoder2.writeClient(client);
402625
- writeVarUint(encoder2.restEncoder, clock);
403073
+ writeVarUint(encoder3.restEncoder, structs.length - startNewStructs);
403074
+ encoder3.writeClient(client);
403075
+ writeVarUint(encoder3.restEncoder, clock);
402626
403076
  const firstStruct = structs[startNewStructs];
402627
- firstStruct.write(encoder2, clock - firstStruct.id.clock);
403077
+ firstStruct.write(encoder3, clock - firstStruct.id.clock);
402628
403078
  for (let i2 = startNewStructs + 1;i2 < structs.length; i2++) {
402629
- structs[i2].write(encoder2, 0);
403079
+ structs[i2].write(encoder3, 0);
402630
403080
  }
402631
- }, writeClientsStructs = (encoder2, store, _sm) => {
403081
+ }, writeClientsStructs = (encoder3, store, _sm) => {
402632
403082
  const sm = new Map;
402633
403083
  _sm.forEach((clock, client) => {
402634
403084
  if (getState(store, client) > clock) {
@@ -402640,9 +403090,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402640
403090
  sm.set(client, 0);
402641
403091
  }
402642
403092
  });
402643
- writeVarUint(encoder2.restEncoder, sm.size);
403093
+ writeVarUint(encoder3.restEncoder, sm.size);
402644
403094
  from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
402645
- writeStructs(encoder2, store.clients.get(client), client, clock);
403095
+ writeStructs(encoder3, store.clients.get(client), client, clock);
402646
403096
  });
402647
403097
  }, readClientsStructRefs = (decoder9, doc2) => {
402648
403098
  const clientRefs = create();
@@ -402770,13 +403220,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402770
403220
  }
402771
403221
  }
402772
403222
  if (restStructs.clients.size > 0) {
402773
- const encoder2 = new UpdateEncoderV2;
402774
- writeClientsStructs(encoder2, restStructs, new Map);
402775
- writeVarUint(encoder2.restEncoder, 0);
402776
- return { missing: missingSV, update: encoder2.toUint8Array() };
403223
+ const encoder3 = new UpdateEncoderV2;
403224
+ writeClientsStructs(encoder3, restStructs, new Map);
403225
+ writeVarUint(encoder3.restEncoder, 0);
403226
+ return { missing: missingSV, update: encoder3.toUint8Array() };
402777
403227
  }
402778
403228
  return null;
402779
- }, writeStructsFromTransaction = (encoder2, transaction) => writeClientsStructs(encoder2, transaction.doc.store, transaction.beforeState), readUpdateV2 = (decoder9, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder9)) => transact(ydoc, (transaction) => {
403229
+ }, writeStructsFromTransaction = (encoder3, transaction) => writeClientsStructs(encoder3, transaction.doc.store, transaction.beforeState), readUpdateV2 = (decoder9, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder9)) => transact(ydoc, (transaction) => {
402780
403230
  transaction.local = false;
402781
403231
  let retry = false;
402782
403232
  const doc2 = transaction.doc;
@@ -402824,13 +403274,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402824
403274
  }, transactionOrigin, false), applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
402825
403275
  const decoder9 = createDecoder(update);
402826
403276
  readUpdateV2(decoder9, ydoc, transactionOrigin, new YDecoder(decoder9));
402827
- }, applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1), writeStateAsUpdate = (encoder2, doc2, targetStateVector = new Map) => {
402828
- writeClientsStructs(encoder2, doc2.store, targetStateVector);
402829
- writeDeleteSet(encoder2, createDeleteSetFromStructStore(doc2.store));
402830
- }, encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder2 = new UpdateEncoderV2) => {
403277
+ }, applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1), writeStateAsUpdate = (encoder3, doc2, targetStateVector = new Map) => {
403278
+ writeClientsStructs(encoder3, doc2.store, targetStateVector);
403279
+ writeDeleteSet(encoder3, createDeleteSetFromStructStore(doc2.store));
403280
+ }, encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder3 = new UpdateEncoderV2) => {
402831
403281
  const targetStateVector = decodeStateVector(encodedTargetStateVector);
402832
- writeStateAsUpdate(encoder2, doc2, targetStateVector);
402833
- const updates = [encoder2.toUint8Array()];
403282
+ writeStateAsUpdate(encoder3, doc2, targetStateVector);
403283
+ const updates = [encoder3.toUint8Array()];
402834
403284
  if (doc2.store.pendingDs) {
402835
403285
  updates.push(doc2.store.pendingDs);
402836
403286
  }
@@ -402838,9 +403288,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402838
403288
  updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector));
402839
403289
  }
402840
403290
  if (updates.length > 1) {
402841
- if (encoder2.constructor === UpdateEncoderV1) {
403291
+ if (encoder3.constructor === UpdateEncoderV1) {
402842
403292
  return mergeUpdates(updates.map((update, i2) => i2 === 0 ? update : convertUpdateFormatV2ToV1(update)));
402843
- } else if (encoder2.constructor === UpdateEncoderV2) {
403293
+ } else if (encoder3.constructor === UpdateEncoderV2) {
402844
403294
  return mergeUpdatesV2(updates);
402845
403295
  }
402846
403296
  }
@@ -402854,20 +403304,20 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402854
403304
  ss.set(client, clock);
402855
403305
  }
402856
403306
  return ss;
402857
- }, decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))), writeStateVector = (encoder2, sv) => {
402858
- writeVarUint(encoder2.restEncoder, sv.size);
403307
+ }, decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))), writeStateVector = (encoder3, sv) => {
403308
+ writeVarUint(encoder3.restEncoder, sv.size);
402859
403309
  from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
402860
- writeVarUint(encoder2.restEncoder, client);
402861
- writeVarUint(encoder2.restEncoder, clock);
403310
+ writeVarUint(encoder3.restEncoder, client);
403311
+ writeVarUint(encoder3.restEncoder, clock);
402862
403312
  });
402863
- return encoder2;
402864
- }, writeDocumentStateVector = (encoder2, doc2) => writeStateVector(encoder2, getStateVector(doc2.store)), encodeStateVectorV2 = (doc2, encoder2 = new DSEncoderV2) => {
403313
+ return encoder3;
403314
+ }, writeDocumentStateVector = (encoder3, doc2) => writeStateVector(encoder3, getStateVector(doc2.store)), encodeStateVectorV2 = (doc2, encoder3 = new DSEncoderV2) => {
402865
403315
  if (doc2 instanceof Map) {
402866
- writeStateVector(encoder2, doc2);
403316
+ writeStateVector(encoder3, doc2);
402867
403317
  } else {
402868
- writeDocumentStateVector(encoder2, doc2);
403318
+ writeDocumentStateVector(encoder3, doc2);
402869
403319
  }
402870
- return encoder2.toUint8Array();
403320
+ return encoder3.toUint8Array();
402871
403321
  }, encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1), createEventHandler = () => new EventHandler, addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f), removeEventHandlerListener = (eventHandler, f) => {
402872
403322
  const l = eventHandler.l;
402873
403323
  const len = l.length;
@@ -402875,9 +403325,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402875
403325
  if (len === eventHandler.l.length) {
402876
403326
  console.error("[yjs] Tried to remove event handler that doesn't exist.");
402877
403327
  }
402878
- }, callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]), compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock, createID = (client, clock) => new ID(client, clock), writeID = (encoder2, id2) => {
402879
- writeVarUint(encoder2, id2.client);
402880
- writeVarUint(encoder2, id2.clock);
403328
+ }, callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]), compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock, createID = (client, clock) => new ID(client, clock), writeID = (encoder3, id2) => {
403329
+ writeVarUint(encoder3, id2.client);
403330
+ writeVarUint(encoder3, id2.clock);
402881
403331
  }, readID = (decoder9) => createID(readVarUint(decoder9), readVarUint(decoder9)), findRootTypeKey = (type) => {
402882
403332
  for (const [key2, value2] of type.doc.share.entries()) {
402883
403333
  if (value2 === type) {
@@ -402923,26 +403373,26 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402923
403373
  t = t.right;
402924
403374
  }
402925
403375
  return createRelativePosition(type, null, assoc);
402926
- }, writeRelativePosition = (encoder2, rpos) => {
403376
+ }, writeRelativePosition = (encoder3, rpos) => {
402927
403377
  const { type, tname, item, assoc } = rpos;
402928
403378
  if (item !== null) {
402929
- writeVarUint(encoder2, 0);
402930
- writeID(encoder2, item);
403379
+ writeVarUint(encoder3, 0);
403380
+ writeID(encoder3, item);
402931
403381
  } else if (tname !== null) {
402932
- writeUint8(encoder2, 1);
402933
- writeVarString(encoder2, tname);
403382
+ writeUint8(encoder3, 1);
403383
+ writeVarString(encoder3, tname);
402934
403384
  } else if (type !== null) {
402935
- writeUint8(encoder2, 2);
402936
- writeID(encoder2, type);
403385
+ writeUint8(encoder3, 2);
403386
+ writeID(encoder3, type);
402937
403387
  } else {
402938
403388
  throw unexpectedCase();
402939
403389
  }
402940
- writeVarInt(encoder2, assoc);
402941
- return encoder2;
403390
+ writeVarInt(encoder3, assoc);
403391
+ return encoder3;
402942
403392
  }, encodeRelativePosition = (rpos) => {
402943
- const encoder2 = createEncoder();
402944
- writeRelativePosition(encoder2, rpos);
402945
- return toUint8Array(encoder2);
403393
+ const encoder3 = createEncoder();
403394
+ writeRelativePosition(encoder3, rpos);
403395
+ return toUint8Array(encoder3);
402946
403396
  }, readRelativePosition = (decoder9) => {
402947
403397
  let type = null;
402948
403398
  let tname = null;
@@ -403018,10 +403468,10 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403018
403468
  }
403019
403469
  }
403020
403470
  return createAbsolutePosition(type, index2, rpos.assoc);
403021
- }, encodeSnapshotV2 = (snapshot2, encoder2 = new DSEncoderV2) => {
403022
- writeDeleteSet(encoder2, snapshot2.ds);
403023
- writeStateVector(encoder2, snapshot2.sv);
403024
- return encoder2.toUint8Array();
403471
+ }, encodeSnapshotV2 = (snapshot2, encoder3 = new DSEncoderV2) => {
403472
+ writeDeleteSet(encoder3, snapshot2.ds);
403473
+ writeStateVector(encoder3, snapshot2.sv);
403474
+ return encoder3.toUint8Array();
403025
403475
  }, encodeSnapshot = (snapshot2) => encodeSnapshotV2(snapshot2, new DSEncoderV1), createSnapshot = (ds, sm) => new Snapshot(ds, sm), emptySnapshot, snapshot2 = (doc2) => createSnapshot(createDeleteSetFromStructStore(doc2.store), getStateVector(doc2.store)), isVisible = (item, snapshot3) => snapshot3 === undefined ? !item.deleted : snapshot3.sv.has(item.id.client) && (snapshot3.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot3.ds, item.id), splitSnapshotAffectedStructs = (transaction, snapshot3) => {
403026
403476
  const meta3 = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
403027
403477
  const store = transaction.doc.store;
@@ -403122,13 +403572,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403122
403572
  }
403123
403573
  f(struct);
403124
403574
  } while (index2 < structs.length && structs[index2].id.clock < clockEnd);
403125
- }, writeUpdateMessageFromTransaction = (encoder2, transaction) => {
403575
+ }, writeUpdateMessageFromTransaction = (encoder3, transaction) => {
403126
403576
  if (transaction.deleteSet.clients.size === 0 && !any3(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
403127
403577
  return false;
403128
403578
  }
403129
403579
  sortAndMergeDeleteSet(transaction.deleteSet);
403130
- writeStructsFromTransaction(encoder2, transaction);
403131
- writeDeleteSet(encoder2, transaction.deleteSet);
403580
+ writeStructsFromTransaction(encoder3, transaction);
403581
+ writeDeleteSet(encoder3, transaction.deleteSet);
403132
403582
  return true;
403133
403583
  }, addChangedTypeToTransaction = (transaction, type, parentSub) => {
403134
403584
  const item = type._item;
@@ -403256,17 +403706,17 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403256
403706
  }
403257
403707
  doc2.emit("afterTransactionCleanup", [transaction, doc2]);
403258
403708
  if (doc2._observers.has("update")) {
403259
- const encoder2 = new UpdateEncoderV1;
403260
- const hasContent2 = writeUpdateMessageFromTransaction(encoder2, transaction);
403709
+ const encoder3 = new UpdateEncoderV1;
403710
+ const hasContent2 = writeUpdateMessageFromTransaction(encoder3, transaction);
403261
403711
  if (hasContent2) {
403262
- doc2.emit("update", [encoder2.toUint8Array(), transaction.origin, doc2, transaction]);
403712
+ doc2.emit("update", [encoder3.toUint8Array(), transaction.origin, doc2, transaction]);
403263
403713
  }
403264
403714
  }
403265
403715
  if (doc2._observers.has("updateV2")) {
403266
- const encoder2 = new UpdateEncoderV2;
403267
- const hasContent2 = writeUpdateMessageFromTransaction(encoder2, transaction);
403716
+ const encoder3 = new UpdateEncoderV2;
403717
+ const hasContent2 = writeUpdateMessageFromTransaction(encoder3, transaction);
403268
403718
  if (hasContent2) {
403269
- doc2.emit("updateV2", [encoder2.toUint8Array(), transaction.origin, doc2, transaction]);
403719
+ doc2.emit("updateV2", [encoder3.toUint8Array(), transaction.origin, doc2, transaction]);
403270
403720
  }
403271
403721
  }
403272
403722
  const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
@@ -403477,8 +403927,8 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403477
403927
  return updateEncoder.toUint8Array();
403478
403928
  }, diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
403479
403929
  const state = decodeStateVector(sv);
403480
- const encoder2 = new YEncoder;
403481
- const lazyStructWriter = new LazyStructWriter(encoder2);
403930
+ const encoder3 = new YEncoder;
403931
+ const lazyStructWriter = new LazyStructWriter(encoder3);
403482
403932
  const decoder9 = new YDecoder(createDecoder(update));
403483
403933
  const reader = new LazyStructReader(decoder9, false);
403484
403934
  while (reader.curr) {
@@ -403504,8 +403954,8 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403504
403954
  }
403505
403955
  finishLazyStructWriting(lazyStructWriter);
403506
403956
  const ds = readDeleteSet(decoder9);
403507
- writeDeleteSet(encoder2, ds);
403508
- return encoder2.toUint8Array();
403957
+ writeDeleteSet(encoder3, ds);
403958
+ return encoder3.toUint8Array();
403509
403959
  }, flushLazyStructWriter = (lazyWriter) => {
403510
403960
  if (lazyWriter.written > 0) {
403511
403961
  lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
@@ -404701,19 +405151,19 @@ var init_yjs = __esm(() => {
404701
405151
  this.lenEncoder = new UintOptRleEncoder;
404702
405152
  }
404703
405153
  toUint8Array() {
404704
- const encoder2 = createEncoder();
404705
- writeVarUint(encoder2, 0);
404706
- writeVarUint8Array(encoder2, this.keyClockEncoder.toUint8Array());
404707
- writeVarUint8Array(encoder2, this.clientEncoder.toUint8Array());
404708
- writeVarUint8Array(encoder2, this.leftClockEncoder.toUint8Array());
404709
- writeVarUint8Array(encoder2, this.rightClockEncoder.toUint8Array());
404710
- writeVarUint8Array(encoder2, toUint8Array(this.infoEncoder));
404711
- writeVarUint8Array(encoder2, this.stringEncoder.toUint8Array());
404712
- writeVarUint8Array(encoder2, toUint8Array(this.parentInfoEncoder));
404713
- writeVarUint8Array(encoder2, this.typeRefEncoder.toUint8Array());
404714
- writeVarUint8Array(encoder2, this.lenEncoder.toUint8Array());
404715
- writeUint8Array(encoder2, toUint8Array(this.restEncoder));
404716
- return toUint8Array(encoder2);
405154
+ const encoder3 = createEncoder();
405155
+ writeVarUint(encoder3, 0);
405156
+ writeVarUint8Array(encoder3, this.keyClockEncoder.toUint8Array());
405157
+ writeVarUint8Array(encoder3, this.clientEncoder.toUint8Array());
405158
+ writeVarUint8Array(encoder3, this.leftClockEncoder.toUint8Array());
405159
+ writeVarUint8Array(encoder3, this.rightClockEncoder.toUint8Array());
405160
+ writeVarUint8Array(encoder3, toUint8Array(this.infoEncoder));
405161
+ writeVarUint8Array(encoder3, this.stringEncoder.toUint8Array());
405162
+ writeVarUint8Array(encoder3, toUint8Array(this.parentInfoEncoder));
405163
+ writeVarUint8Array(encoder3, this.typeRefEncoder.toUint8Array());
405164
+ writeVarUint8Array(encoder3, this.lenEncoder.toUint8Array());
405165
+ writeUint8Array(encoder3, toUint8Array(this.restEncoder));
405166
+ return toUint8Array(encoder3);
404717
405167
  }
404718
405168
  writeLeftID(id2) {
404719
405169
  this.clientEncoder.write(id2.client);
@@ -404990,8 +405440,8 @@ var init_yjs = __esm(() => {
404990
405440
  [Symbol.iterator]() {
404991
405441
  return typeListCreateIterator(this);
404992
405442
  }
404993
- _write(encoder2) {
404994
- encoder2.writeTypeRef(YArrayRefID);
405443
+ _write(encoder3) {
405444
+ encoder3.writeTypeRef(YArrayRefID);
404995
405445
  }
404996
405446
  };
404997
405447
  YMapEvent = class YMapEvent extends YEvent {
@@ -405100,8 +405550,8 @@ var init_yjs = __esm(() => {
405100
405550
  this._prelimContent.clear();
405101
405551
  }
405102
405552
  }
405103
- _write(encoder2) {
405104
- encoder2.writeTypeRef(YMapRefID);
405553
+ _write(encoder3) {
405554
+ encoder3.writeTypeRef(YMapRefID);
405105
405555
  }
405106
405556
  };
405107
405557
  YTextEvent = class YTextEvent extends YEvent {
@@ -405548,8 +405998,8 @@ var init_yjs = __esm(() => {
405548
405998
  getAttributes() {
405549
405999
  return typeMapGetAll(this);
405550
406000
  }
405551
- _write(encoder2) {
405552
- encoder2.writeTypeRef(YTextRefID);
406001
+ _write(encoder3) {
406002
+ encoder3.writeTypeRef(YTextRefID);
405553
406003
  }
405554
406004
  };
405555
406005
  YXmlTreeWalker = class YXmlTreeWalker {
@@ -405707,8 +406157,8 @@ var init_yjs = __esm(() => {
405707
406157
  forEach(f) {
405708
406158
  typeListForEach(this, f);
405709
406159
  }
405710
- _write(encoder2) {
405711
- encoder2.writeTypeRef(YXmlFragmentRefID);
406160
+ _write(encoder3) {
406161
+ encoder3.writeTypeRef(YXmlFragmentRefID);
405712
406162
  }
405713
406163
  };
405714
406164
  YXmlElement = class YXmlElement extends YXmlFragment {
@@ -405805,9 +406255,9 @@ var init_yjs = __esm(() => {
405805
406255
  }
405806
406256
  return dom;
405807
406257
  }
405808
- _write(encoder2) {
405809
- encoder2.writeTypeRef(YXmlElementRefID);
405810
- encoder2.writeKey(this.nodeName);
406258
+ _write(encoder3) {
406259
+ encoder3.writeTypeRef(YXmlElementRefID);
406260
+ encoder3.writeKey(this.nodeName);
405811
406261
  }
405812
406262
  };
405813
406263
  YXmlEvent = class YXmlEvent extends YEvent {
@@ -405853,9 +406303,9 @@ var init_yjs = __esm(() => {
405853
406303
  }
405854
406304
  return dom;
405855
406305
  }
405856
- _write(encoder2) {
405857
- encoder2.writeTypeRef(YXmlHookRefID);
405858
- encoder2.writeKey(this.hookName);
406306
+ _write(encoder3) {
406307
+ encoder3.writeTypeRef(YXmlHookRefID);
406308
+ encoder3.writeKey(this.hookName);
405859
406309
  }
405860
406310
  };
405861
406311
  YXmlText = class YXmlText extends YText {
@@ -405914,8 +406364,8 @@ var init_yjs = __esm(() => {
405914
406364
  toJSON() {
405915
406365
  return this.toString();
405916
406366
  }
405917
- _write(encoder2) {
405918
- encoder2.writeTypeRef(YXmlTextRefID);
406367
+ _write(encoder3) {
406368
+ encoder3.writeTypeRef(YXmlTextRefID);
405919
406369
  }
405920
406370
  };
405921
406371
  GC = class GC extends AbstractStruct {
@@ -405937,9 +406387,9 @@ var init_yjs = __esm(() => {
405937
406387
  }
405938
406388
  addStruct(transaction.doc.store, this);
405939
406389
  }
405940
- write(encoder2, offset) {
405941
- encoder2.writeInfo(structGCRefNumber);
405942
- encoder2.writeLen(this.length - offset);
406390
+ write(encoder3, offset) {
406391
+ encoder3.writeInfo(structGCRefNumber);
406392
+ encoder3.writeLen(this.length - offset);
405943
406393
  }
405944
406394
  getMissing(transaction, store) {
405945
406395
  return null;
@@ -406185,17 +406635,17 @@ var init_yjs = __esm(() => {
406185
406635
  this.content = new ContentDeleted(this.length);
406186
406636
  }
406187
406637
  }
406188
- write(encoder2, offset) {
406638
+ write(encoder3, offset) {
406189
406639
  const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
406190
406640
  const rightOrigin = this.rightOrigin;
406191
406641
  const parentSub = this.parentSub;
406192
406642
  const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | (rightOrigin === null ? 0 : BIT7) | (parentSub === null ? 0 : BIT6);
406193
- encoder2.writeInfo(info);
406643
+ encoder3.writeInfo(info);
406194
406644
  if (origin !== null) {
406195
- encoder2.writeLeftID(origin);
406645
+ encoder3.writeLeftID(origin);
406196
406646
  }
406197
406647
  if (rightOrigin !== null) {
406198
- encoder2.writeRightID(rightOrigin);
406648
+ encoder3.writeRightID(rightOrigin);
406199
406649
  }
406200
406650
  if (origin === null && rightOrigin === null) {
406201
406651
  const parent = this.parent;
@@ -406203,26 +406653,26 @@ var init_yjs = __esm(() => {
406203
406653
  const parentItem = parent._item;
406204
406654
  if (parentItem === null) {
406205
406655
  const ykey = findRootTypeKey(parent);
406206
- encoder2.writeParentInfo(true);
406207
- encoder2.writeString(ykey);
406656
+ encoder3.writeParentInfo(true);
406657
+ encoder3.writeString(ykey);
406208
406658
  } else {
406209
- encoder2.writeParentInfo(false);
406210
- encoder2.writeLeftID(parentItem.id);
406659
+ encoder3.writeParentInfo(false);
406660
+ encoder3.writeLeftID(parentItem.id);
406211
406661
  }
406212
406662
  } else if (parent.constructor === String) {
406213
- encoder2.writeParentInfo(true);
406214
- encoder2.writeString(parent);
406663
+ encoder3.writeParentInfo(true);
406664
+ encoder3.writeString(parent);
406215
406665
  } else if (parent.constructor === ID) {
406216
- encoder2.writeParentInfo(false);
406217
- encoder2.writeLeftID(parent);
406666
+ encoder3.writeParentInfo(false);
406667
+ encoder3.writeLeftID(parent);
406218
406668
  } else {
406219
406669
  unexpectedCase();
406220
406670
  }
406221
406671
  if (parentSub !== null) {
406222
- encoder2.writeString(parentSub);
406672
+ encoder3.writeString(parentSub);
406223
406673
  }
406224
406674
  }
406225
- this.content.write(encoder2, offset);
406675
+ this.content.write(encoder3, offset);
406226
406676
  }
406227
406677
  };
406228
406678
  contentRefs = [
@@ -406257,9 +406707,9 @@ var init_yjs = __esm(() => {
406257
406707
  integrate(transaction, offset) {
406258
406708
  unexpectedCase();
406259
406709
  }
406260
- write(encoder2, offset) {
406261
- encoder2.writeInfo(structSkipRefNumber);
406262
- writeVarUint(encoder2.restEncoder, this.length - offset);
406710
+ write(encoder3, offset) {
406711
+ encoder3.writeInfo(structSkipRefNumber);
406712
+ writeVarUint(encoder3.restEncoder, this.length - offset);
406263
406713
  }
406264
406714
  getMissing(transaction, store) {
406265
406715
  return null;
@@ -406319,14 +406769,14 @@ var init_broadcastchannel = __esm(() => {
406319
406769
  });
406320
406770
 
406321
406771
  // ../../../v2/node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.31/node_modules/y-protocols/sync.js
406322
- var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writeSyncStep1 = (encoder2, doc2) => {
406323
- writeVarUint(encoder2, messageYjsSyncStep1);
406772
+ var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writeSyncStep1 = (encoder3, doc2) => {
406773
+ writeVarUint(encoder3, messageYjsSyncStep1);
406324
406774
  const sv = encodeStateVector(doc2);
406325
- writeVarUint8Array(encoder2, sv);
406326
- }, writeSyncStep2 = (encoder2, doc2, encodedStateVector) => {
406327
- writeVarUint(encoder2, messageYjsSyncStep2);
406328
- writeVarUint8Array(encoder2, encodeStateAsUpdate(doc2, encodedStateVector));
406329
- }, readSyncStep1 = (decoder9, encoder2, doc2) => writeSyncStep2(encoder2, doc2, readVarUint8Array(decoder9)), readSyncStep2 = (decoder9, doc2, transactionOrigin, errorHandler) => {
406775
+ writeVarUint8Array(encoder3, sv);
406776
+ }, writeSyncStep2 = (encoder3, doc2, encodedStateVector) => {
406777
+ writeVarUint(encoder3, messageYjsSyncStep2);
406778
+ writeVarUint8Array(encoder3, encodeStateAsUpdate(doc2, encodedStateVector));
406779
+ }, readSyncStep1 = (decoder9, encoder3, doc2) => writeSyncStep2(encoder3, doc2, readVarUint8Array(decoder9)), readSyncStep2 = (decoder9, doc2, transactionOrigin, errorHandler) => {
406330
406780
  try {
406331
406781
  applyUpdate(doc2, readVarUint8Array(decoder9), transactionOrigin);
406332
406782
  } catch (error48) {
@@ -406334,14 +406784,14 @@ var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writ
406334
406784
  errorHandler(error48);
406335
406785
  console.error("Caught error while handling a Yjs update", error48);
406336
406786
  }
406337
- }, writeUpdate = (encoder2, update) => {
406338
- writeVarUint(encoder2, messageYjsUpdate);
406339
- writeVarUint8Array(encoder2, update);
406340
- }, readUpdate, readSyncMessage = (decoder9, encoder2, doc2, transactionOrigin, errorHandler) => {
406787
+ }, writeUpdate = (encoder3, update) => {
406788
+ writeVarUint(encoder3, messageYjsUpdate);
406789
+ writeVarUint8Array(encoder3, update);
406790
+ }, readUpdate, readSyncMessage = (decoder9, encoder3, doc2, transactionOrigin, errorHandler) => {
406341
406791
  const messageType = readVarUint(decoder9);
406342
406792
  switch (messageType) {
406343
406793
  case messageYjsSyncStep1:
406344
- readSyncStep1(decoder9, encoder2, doc2);
406794
+ readSyncStep1(decoder9, encoder3, doc2);
406345
406795
  break;
406346
406796
  case messageYjsSyncStep2:
406347
406797
  readSyncStep2(decoder9, doc2, transactionOrigin, errorHandler);
@@ -406395,17 +406845,17 @@ var outdatedTimeout = 30000, Awareness, removeAwarenessStates = (awareness, clie
406395
406845
  }
406396
406846
  }, encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
406397
406847
  const len = clients.length;
406398
- const encoder2 = createEncoder();
406399
- writeVarUint(encoder2, len);
406848
+ const encoder3 = createEncoder();
406849
+ writeVarUint(encoder3, len);
406400
406850
  for (let i2 = 0;i2 < len; i2++) {
406401
406851
  const clientID = clients[i2];
406402
406852
  const state = states.get(clientID) || null;
406403
406853
  const clock = awareness.meta.get(clientID).clock;
406404
- writeVarUint(encoder2, clientID);
406405
- writeVarUint(encoder2, clock);
406406
- writeVarString(encoder2, JSON.stringify(state));
406854
+ writeVarUint(encoder3, clientID);
406855
+ writeVarUint(encoder3, clock);
406856
+ writeVarString(encoder3, JSON.stringify(state));
406407
406857
  }
406408
- return toUint8Array(encoder2);
406858
+ return toUint8Array(encoder3);
406409
406859
  }, applyAwarenessUpdate = (awareness, update, origin) => {
406410
406860
  const decoder9 = createDecoder(update);
406411
406861
  const timestamp = getUnixTime();
@@ -406565,15 +407015,15 @@ var init_url = __esm(() => {
406565
407015
  var messageSync = 0, messageQueryAwareness = 3, messageAwareness = 1, messageAuth = 2, messageHandlers, messageReconnectTimeout = 30000, permissionDeniedHandler = (provider, reason) => console.warn(`Permission denied to access ${provider.url}.
406566
407016
  ${reason}`), readMessage = (provider, buf, emitSynced) => {
406567
407017
  const decoder9 = createDecoder(buf);
406568
- const encoder2 = createEncoder();
407018
+ const encoder3 = createEncoder();
406569
407019
  const messageType = readVarUint(decoder9);
406570
407020
  const messageHandler = provider.messageHandlers[messageType];
406571
407021
  if (messageHandler) {
406572
- messageHandler(encoder2, decoder9, provider, emitSynced, messageType);
407022
+ messageHandler(encoder3, decoder9, provider, emitSynced, messageType);
406573
407023
  } else {
406574
407024
  console.error("Unable to compute message");
406575
407025
  }
406576
- return encoder2;
407026
+ return encoder3;
406577
407027
  }, closeWebsocketConnection = (provider, ws, event) => {
406578
407028
  if (ws === provider.ws) {
406579
407029
  provider.emit("connection-close", [event, provider]);
@@ -406602,9 +407052,9 @@ ${reason}`), readMessage = (provider, buf, emitSynced) => {
406602
407052
  provider.synced = false;
406603
407053
  websocket.onmessage = (event) => {
406604
407054
  provider.wsLastMessageReceived = getUnixTime();
406605
- const encoder2 = readMessage(provider, new Uint8Array(event.data), true);
406606
- if (length(encoder2) > 1) {
406607
- websocket.send(toUint8Array(encoder2));
407055
+ const encoder3 = readMessage(provider, new Uint8Array(event.data), true);
407056
+ if (length(encoder3) > 1) {
407057
+ websocket.send(toUint8Array(encoder3));
406608
407058
  }
406609
407059
  };
406610
407060
  websocket.onerror = (event) => {
@@ -406621,10 +407071,10 @@ ${reason}`), readMessage = (provider, buf, emitSynced) => {
406621
407071
  provider.emit("status", [{
406622
407072
  status: "connected"
406623
407073
  }]);
406624
- const encoder2 = createEncoder();
406625
- writeVarUint(encoder2, messageSync);
406626
- writeSyncStep1(encoder2, provider.doc);
406627
- websocket.send(toUint8Array(encoder2));
407074
+ const encoder3 = createEncoder();
407075
+ writeVarUint(encoder3, messageSync);
407076
+ writeSyncStep1(encoder3, provider.doc);
407077
+ websocket.send(toUint8Array(encoder3));
406628
407078
  if (provider.awareness.getLocalState() !== null) {
406629
407079
  const encoderAwarenessState = createEncoder();
406630
407080
  writeVarUint(encoderAwarenessState, messageAwareness);
@@ -406660,16 +407110,16 @@ var init_y_websocket = __esm(() => {
406660
407110
  init_url();
406661
407111
  init_environment();
406662
407112
  messageHandlers = [];
406663
- messageHandlers[messageSync] = (encoder2, decoder9, provider, emitSynced, _messageType) => {
406664
- writeVarUint(encoder2, messageSync);
406665
- const syncMessageType = readSyncMessage(decoder9, encoder2, provider.doc, provider);
407113
+ messageHandlers[messageSync] = (encoder3, decoder9, provider, emitSynced, _messageType) => {
407114
+ writeVarUint(encoder3, messageSync);
407115
+ const syncMessageType = readSyncMessage(decoder9, encoder3, provider.doc, provider);
406666
407116
  if (emitSynced && syncMessageType === messageYjsSyncStep2 && !provider.synced) {
406667
407117
  provider.synced = true;
406668
407118
  }
406669
407119
  };
406670
- messageHandlers[messageQueryAwareness] = (encoder2, _decoder, provider, _emitSynced, _messageType) => {
406671
- writeVarUint(encoder2, messageAwareness);
406672
- writeVarUint8Array(encoder2, encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
407120
+ messageHandlers[messageQueryAwareness] = (encoder3, _decoder, provider, _emitSynced, _messageType) => {
407121
+ writeVarUint(encoder3, messageAwareness);
407122
+ writeVarUint8Array(encoder3, encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
406673
407123
  };
406674
407124
  messageHandlers[messageAwareness] = (_encoder, decoder9, provider, _emitSynced, _messageType) => {
406675
407125
  applyAwarenessUpdate(provider.awareness, readVarUint8Array(decoder9), provider);
@@ -406715,36 +407165,36 @@ var init_y_websocket = __esm(() => {
406715
407165
  if (resyncInterval > 0) {
406716
407166
  this._resyncInterval = setInterval(() => {
406717
407167
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
406718
- const encoder2 = createEncoder();
406719
- writeVarUint(encoder2, messageSync);
406720
- writeSyncStep1(encoder2, doc2);
406721
- this.ws.send(toUint8Array(encoder2));
407168
+ const encoder3 = createEncoder();
407169
+ writeVarUint(encoder3, messageSync);
407170
+ writeSyncStep1(encoder3, doc2);
407171
+ this.ws.send(toUint8Array(encoder3));
406722
407172
  }
406723
407173
  }, resyncInterval);
406724
407174
  }
406725
407175
  this._bcSubscriber = (data, origin) => {
406726
407176
  if (origin !== this) {
406727
- const encoder2 = readMessage(this, new Uint8Array(data), false);
406728
- if (length(encoder2) > 1) {
406729
- publish(this.bcChannel, toUint8Array(encoder2), this);
407177
+ const encoder3 = readMessage(this, new Uint8Array(data), false);
407178
+ if (length(encoder3) > 1) {
407179
+ publish(this.bcChannel, toUint8Array(encoder3), this);
406730
407180
  }
406731
407181
  }
406732
407182
  };
406733
407183
  this._updateHandler = (update, origin) => {
406734
407184
  if (origin !== this) {
406735
- const encoder2 = createEncoder();
406736
- writeVarUint(encoder2, messageSync);
406737
- writeUpdate(encoder2, update);
406738
- broadcastMessage(this, toUint8Array(encoder2));
407185
+ const encoder3 = createEncoder();
407186
+ writeVarUint(encoder3, messageSync);
407187
+ writeUpdate(encoder3, update);
407188
+ broadcastMessage(this, toUint8Array(encoder3));
406739
407189
  }
406740
407190
  };
406741
407191
  this.doc.on("update", this._updateHandler);
406742
407192
  this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {
406743
407193
  const changedClients = added.concat(updated).concat(removed);
406744
- const encoder2 = createEncoder();
406745
- writeVarUint(encoder2, messageAwareness);
406746
- writeVarUint8Array(encoder2, encodeAwarenessUpdate(awareness, changedClients));
406747
- broadcastMessage(this, toUint8Array(encoder2));
407194
+ const encoder3 = createEncoder();
407195
+ writeVarUint(encoder3, messageAwareness);
407196
+ writeVarUint8Array(encoder3, encodeAwarenessUpdate(awareness, changedClients));
407197
+ broadcastMessage(this, toUint8Array(encoder3));
406748
407198
  };
406749
407199
  this._exitHandler = () => {
406750
407200
  removeAwarenessStates(this.awareness, [doc2.clientID], "app closed");
@@ -406816,12 +407266,12 @@ var init_y_websocket = __esm(() => {
406816
407266
  publish(this.bcChannel, toUint8Array(encoderAwarenessState), this);
406817
407267
  }
406818
407268
  disconnectBc() {
406819
- const encoder2 = createEncoder();
406820
- writeVarUint(encoder2, messageAwareness);
406821
- writeVarUint8Array(encoder2, encodeAwarenessUpdate(this.awareness, [
407269
+ const encoder3 = createEncoder();
407270
+ writeVarUint(encoder3, messageAwareness);
407271
+ writeVarUint8Array(encoder3, encodeAwarenessUpdate(this.awareness, [
406822
407272
  this.doc.clientID
406823
407273
  ], new Map));
406824
- broadcastMessage(this, toUint8Array(encoder2));
407274
+ broadcastMessage(this, toUint8Array(encoder3));
406825
407275
  if (this.bcconnected) {
406826
407276
  unsubscribe(this.bcChannel, this._bcSubscriber);
406827
407277
  this.bcconnected = false;
@@ -407363,53 +407813,53 @@ var floor2, min2 = (a, b) => a < b ? a : b, max3 = (a, b) => a > b ? a : b, BIT8
407363
407813
  buf[i2] = encodedString.codePointAt(i2);
407364
407814
  }
407365
407815
  return buf;
407366
- }, utf8TextEncoder2, _encodeUtf8Native2 = (str) => utf8TextEncoder2.encode(str), encodeUtf82, utf8TextDecoder2, write2 = (encoder2, num) => {
407367
- const bufferLen = encoder2.cbuf.length;
407368
- if (encoder2.cpos === bufferLen) {
407369
- encoder2.bufs.push(encoder2.cbuf);
407370
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
407371
- encoder2.cpos = 0;
407372
- }
407373
- encoder2.cbuf[encoder2.cpos++] = num;
407374
- }, writeVarUint2 = (encoder2, num) => {
407816
+ }, utf8TextEncoder2, _encodeUtf8Native2 = (str) => utf8TextEncoder2.encode(str), encodeUtf82, utf8TextDecoder2, write2 = (encoder3, num) => {
407817
+ const bufferLen = encoder3.cbuf.length;
407818
+ if (encoder3.cpos === bufferLen) {
407819
+ encoder3.bufs.push(encoder3.cbuf);
407820
+ encoder3.cbuf = new Uint8Array(bufferLen * 2);
407821
+ encoder3.cpos = 0;
407822
+ }
407823
+ encoder3.cbuf[encoder3.cpos++] = num;
407824
+ }, writeVarUint2 = (encoder3, num) => {
407375
407825
  while (num > BITS72) {
407376
- write2(encoder2, BIT82 | BITS72 & num);
407826
+ write2(encoder3, BIT82 | BITS72 & num);
407377
407827
  num = floor2(num / 128);
407378
407828
  }
407379
- write2(encoder2, BITS72 & num);
407380
- }, _strBuffer2, _maxStrBSize2, _writeVarStringNative2 = (encoder2, str) => {
407829
+ write2(encoder3, BITS72 & num);
407830
+ }, _strBuffer2, _maxStrBSize2, _writeVarStringNative2 = (encoder3, str) => {
407381
407831
  if (str.length < _maxStrBSize2) {
407382
407832
  const written = utf8TextEncoder2.encodeInto(str, _strBuffer2).written || 0;
407383
- writeVarUint2(encoder2, written);
407833
+ writeVarUint2(encoder3, written);
407384
407834
  for (let i2 = 0;i2 < written; i2++) {
407385
- write2(encoder2, _strBuffer2[i2]);
407835
+ write2(encoder3, _strBuffer2[i2]);
407386
407836
  }
407387
407837
  } else {
407388
- writeVarUint8Array2(encoder2, encodeUtf82(str));
407838
+ writeVarUint8Array2(encoder3, encodeUtf82(str));
407389
407839
  }
407390
- }, _writeVarStringPolyfill2 = (encoder2, str) => {
407840
+ }, _writeVarStringPolyfill2 = (encoder3, str) => {
407391
407841
  const encodedString = unescape(encodeURIComponent(str));
407392
407842
  const len = encodedString.length;
407393
- writeVarUint2(encoder2, len);
407843
+ writeVarUint2(encoder3, len);
407394
407844
  for (let i2 = 0;i2 < len; i2++) {
407395
- write2(encoder2, encodedString.codePointAt(i2));
407845
+ write2(encoder3, encodedString.codePointAt(i2));
407396
407846
  }
407397
- }, writeVarString2, writeUint8Array2 = (encoder2, uint8Array) => {
407398
- const bufferLen = encoder2.cbuf.length;
407399
- const cpos = encoder2.cpos;
407847
+ }, writeVarString2, writeUint8Array2 = (encoder3, uint8Array) => {
407848
+ const bufferLen = encoder3.cbuf.length;
407849
+ const cpos = encoder3.cpos;
407400
407850
  const leftCopyLen = min2(bufferLen - cpos, uint8Array.length);
407401
407851
  const rightCopyLen = uint8Array.length - leftCopyLen;
407402
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
407403
- encoder2.cpos += leftCopyLen;
407852
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
407853
+ encoder3.cpos += leftCopyLen;
407404
407854
  if (rightCopyLen > 0) {
407405
- encoder2.bufs.push(encoder2.cbuf);
407406
- encoder2.cbuf = new Uint8Array(max3(bufferLen * 2, rightCopyLen));
407407
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
407408
- encoder2.cpos = rightCopyLen;
407409
- }
407410
- }, writeVarUint8Array2 = (encoder2, uint8Array) => {
407411
- writeVarUint2(encoder2, uint8Array.byteLength);
407412
- writeUint8Array2(encoder2, uint8Array);
407855
+ encoder3.bufs.push(encoder3.cbuf);
407856
+ encoder3.cbuf = new Uint8Array(max3(bufferLen * 2, rightCopyLen));
407857
+ encoder3.cbuf.set(uint8Array.subarray(leftCopyLen));
407858
+ encoder3.cpos = rightCopyLen;
407859
+ }
407860
+ }, writeVarUint8Array2 = (encoder3, uint8Array) => {
407861
+ writeVarUint2(encoder3, uint8Array.byteLength);
407862
+ writeUint8Array2(encoder3, uint8Array);
407413
407863
  }, create6 = (s) => new Error(s), errorUnexpectedEndOfArray2, errorIntegerOutOfRange2, readUint8Array2 = (decoder9, len) => {
407414
407864
  const view = new Uint8Array(decoder9.arr.buffer, decoder9.pos + decoder9.arr.byteOffset, len);
407415
407865
  decoder9.pos += len;
@@ -407451,9 +407901,9 @@ var floor2, min2 = (a, b) => a < b ? a : b, max3 = (a, b) => a > b ? a : b, BIT8
407451
407901
  }
407452
407902
  return decodeURIComponent(escape(encodedString));
407453
407903
  }
407454
- }, _readVarStringNative2 = (decoder9) => utf8TextDecoder2.decode(readVarUint8Array2(decoder9)), readVarString2, AuthMessageType, writeAuthentication = (encoder2, auth) => {
407455
- writeVarUint2(encoder2, AuthMessageType.Token);
407456
- writeVarString2(encoder2, auth);
407904
+ }, _readVarStringNative2 = (decoder9) => utf8TextDecoder2.decode(readVarUint8Array2(decoder9)), readVarString2, AuthMessageType, writeAuthentication = (encoder3, auth) => {
407905
+ writeVarUint2(encoder3, AuthMessageType.Token);
407906
+ writeVarString2(encoder3, auth);
407457
407907
  }, readAuthMessage2 = (decoder9, permissionDeniedHandler2, authenticatedHandler) => {
407458
407908
  switch (readVarUint2(decoder9)) {
407459
407909
  case AuthMessageType.PermissionDenied: {
@@ -408028,69 +408478,69 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
408028
408478
  }
408029
408479
  }
408030
408480
  return params2;
408031
- }, hasParam3 = (name) => computeParams2().has(name), getVariable2 = (name) => isNode2 ? undefinedToNull2(process.env[name.toUpperCase()]) : undefinedToNull2(varStorage2.getItem(name)), hasConf2 = (name) => hasParam3("--" + name) || getVariable2(name) !== null, forceColor2, floor3, min3 = (a, b) => a < b ? a : b, max4 = (a, b) => a > b ? a : b, BIT72 = 64, BIT83 = 128, BITS62 = 63, BITS73 = 127, MAX_SAFE_INTEGER3, createEncoder2 = () => new Encoder2, length2 = (encoder2) => {
408032
- let len = encoder2.cpos;
408033
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
408034
- len += encoder2.bufs[i2].length;
408481
+ }, hasParam3 = (name) => computeParams2().has(name), getVariable2 = (name) => isNode2 ? undefinedToNull2(process.env[name.toUpperCase()]) : undefinedToNull2(varStorage2.getItem(name)), hasConf2 = (name) => hasParam3("--" + name) || getVariable2(name) !== null, forceColor2, floor3, min3 = (a, b) => a < b ? a : b, max4 = (a, b) => a > b ? a : b, BIT72 = 64, BIT83 = 128, BITS62 = 63, BITS73 = 127, MAX_SAFE_INTEGER3, createEncoder2 = () => new Encoder2, length2 = (encoder3) => {
408482
+ let len = encoder3.cpos;
408483
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
408484
+ len += encoder3.bufs[i2].length;
408035
408485
  }
408036
408486
  return len;
408037
- }, toUint8Array2 = (encoder2) => {
408038
- const uint8arr = new Uint8Array(length2(encoder2));
408487
+ }, toUint8Array2 = (encoder3) => {
408488
+ const uint8arr = new Uint8Array(length2(encoder3));
408039
408489
  let curPos = 0;
408040
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
408041
- const d = encoder2.bufs[i2];
408490
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
408491
+ const d = encoder3.bufs[i2];
408042
408492
  uint8arr.set(d, curPos);
408043
408493
  curPos += d.length;
408044
408494
  }
408045
- uint8arr.set(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos), curPos);
408495
+ uint8arr.set(new Uint8Array(encoder3.cbuf.buffer, 0, encoder3.cpos), curPos);
408046
408496
  return uint8arr;
408047
- }, write3 = (encoder2, num) => {
408048
- const bufferLen = encoder2.cbuf.length;
408049
- if (encoder2.cpos === bufferLen) {
408050
- encoder2.bufs.push(encoder2.cbuf);
408051
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
408052
- encoder2.cpos = 0;
408053
- }
408054
- encoder2.cbuf[encoder2.cpos++] = num;
408055
- }, writeVarUint3 = (encoder2, num) => {
408497
+ }, write3 = (encoder3, num) => {
408498
+ const bufferLen = encoder3.cbuf.length;
408499
+ if (encoder3.cpos === bufferLen) {
408500
+ encoder3.bufs.push(encoder3.cbuf);
408501
+ encoder3.cbuf = new Uint8Array(bufferLen * 2);
408502
+ encoder3.cpos = 0;
408503
+ }
408504
+ encoder3.cbuf[encoder3.cpos++] = num;
408505
+ }, writeVarUint3 = (encoder3, num) => {
408056
408506
  while (num > BITS73) {
408057
- write3(encoder2, BIT83 | BITS73 & num);
408507
+ write3(encoder3, BIT83 | BITS73 & num);
408058
408508
  num = floor3(num / 128);
408059
408509
  }
408060
- write3(encoder2, BITS73 & num);
408061
- }, _strBuffer3, _maxStrBSize3, _writeVarStringNative3 = (encoder2, str) => {
408510
+ write3(encoder3, BITS73 & num);
408511
+ }, _strBuffer3, _maxStrBSize3, _writeVarStringNative3 = (encoder3, str) => {
408062
408512
  if (str.length < _maxStrBSize3) {
408063
408513
  const written = utf8TextEncoder3.encodeInto(str, _strBuffer3).written || 0;
408064
- writeVarUint3(encoder2, written);
408514
+ writeVarUint3(encoder3, written);
408065
408515
  for (let i2 = 0;i2 < written; i2++) {
408066
- write3(encoder2, _strBuffer3[i2]);
408516
+ write3(encoder3, _strBuffer3[i2]);
408067
408517
  }
408068
408518
  } else {
408069
- writeVarUint8Array3(encoder2, encodeUtf83(str));
408519
+ writeVarUint8Array3(encoder3, encodeUtf83(str));
408070
408520
  }
408071
- }, _writeVarStringPolyfill3 = (encoder2, str) => {
408521
+ }, _writeVarStringPolyfill3 = (encoder3, str) => {
408072
408522
  const encodedString = unescape(encodeURIComponent(str));
408073
408523
  const len = encodedString.length;
408074
- writeVarUint3(encoder2, len);
408524
+ writeVarUint3(encoder3, len);
408075
408525
  for (let i2 = 0;i2 < len; i2++) {
408076
- write3(encoder2, encodedString.codePointAt(i2));
408526
+ write3(encoder3, encodedString.codePointAt(i2));
408077
408527
  }
408078
- }, writeVarString3, writeUint8Array3 = (encoder2, uint8Array) => {
408079
- const bufferLen = encoder2.cbuf.length;
408080
- const cpos = encoder2.cpos;
408528
+ }, writeVarString3, writeUint8Array3 = (encoder3, uint8Array) => {
408529
+ const bufferLen = encoder3.cbuf.length;
408530
+ const cpos = encoder3.cpos;
408081
408531
  const leftCopyLen = min3(bufferLen - cpos, uint8Array.length);
408082
408532
  const rightCopyLen = uint8Array.length - leftCopyLen;
408083
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
408084
- encoder2.cpos += leftCopyLen;
408533
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
408534
+ encoder3.cpos += leftCopyLen;
408085
408535
  if (rightCopyLen > 0) {
408086
- encoder2.bufs.push(encoder2.cbuf);
408087
- encoder2.cbuf = new Uint8Array(max4(bufferLen * 2, rightCopyLen));
408088
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
408089
- encoder2.cpos = rightCopyLen;
408090
- }
408091
- }, writeVarUint8Array3 = (encoder2, uint8Array) => {
408092
- writeVarUint3(encoder2, uint8Array.byteLength);
408093
- writeUint8Array3(encoder2, uint8Array);
408536
+ encoder3.bufs.push(encoder3.cbuf);
408537
+ encoder3.cbuf = new Uint8Array(max4(bufferLen * 2, rightCopyLen));
408538
+ encoder3.cbuf.set(uint8Array.subarray(leftCopyLen));
408539
+ encoder3.cpos = rightCopyLen;
408540
+ }
408541
+ }, writeVarUint8Array3 = (encoder3, uint8Array) => {
408542
+ writeVarUint3(encoder3, uint8Array.byteLength);
408543
+ writeUint8Array3(encoder3, uint8Array);
408094
408544
  }, create7 = (s) => new Error(s), errorUnexpectedEndOfArray3, errorIntegerOutOfRange3, createDecoder2 = (uint8Array) => new Decoder2(uint8Array), readUint8Array3 = (decoder9, len) => {
408095
408545
  const view = new Uint8Array(decoder9.arr.buffer, decoder9.pos + decoder9.arr.byteOffset, len);
408096
408546
  decoder9.pos += len;
@@ -408233,17 +408683,17 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
408233
408683
  }
408234
408684
  }, encodeAwarenessUpdate2 = (awareness, clients, states = awareness.states) => {
408235
408685
  const len = clients.length;
408236
- const encoder2 = createEncoder2();
408237
- writeVarUint3(encoder2, len);
408686
+ const encoder3 = createEncoder2();
408687
+ writeVarUint3(encoder3, len);
408238
408688
  for (let i2 = 0;i2 < len; i2++) {
408239
408689
  const clientID = clients[i2];
408240
408690
  const state = states.get(clientID) || null;
408241
408691
  const clock = awareness.meta.get(clientID).clock;
408242
- writeVarUint3(encoder2, clientID);
408243
- writeVarUint3(encoder2, clock);
408244
- writeVarString3(encoder2, JSON.stringify(state));
408692
+ writeVarUint3(encoder3, clientID);
408693
+ writeVarUint3(encoder3, clock);
408694
+ writeVarString3(encoder3, JSON.stringify(state));
408245
408695
  }
408246
- return toUint8Array2(encoder2);
408696
+ return toUint8Array2(encoder3);
408247
408697
  }, applyAwarenessUpdate2 = (awareness, update, origin) => {
408248
408698
  const decoder9 = createDecoder2(update);
408249
408699
  const timestamp = getUnixTime2();
@@ -408299,27 +408749,27 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
408299
408749
  removed
408300
408750
  }, origin]);
408301
408751
  }
408302
- }, encodeQueryParams2 = (params3) => map4(params3, (val, key2) => `${encodeURIComponent(key2)}=${encodeURIComponent(val)}`).join("&"), MessageType, WebSocketStatus, HocuspocusProviderWebsocket, messageYjsSyncStep12 = 0, messageYjsSyncStep22 = 1, messageYjsUpdate2 = 2, writeSyncStep12 = (encoder2, doc2) => {
408303
- writeVarUint3(encoder2, messageYjsSyncStep12);
408752
+ }, encodeQueryParams2 = (params3) => map4(params3, (val, key2) => `${encodeURIComponent(key2)}=${encodeURIComponent(val)}`).join("&"), MessageType, WebSocketStatus, HocuspocusProviderWebsocket, messageYjsSyncStep12 = 0, messageYjsSyncStep22 = 1, messageYjsUpdate2 = 2, writeSyncStep12 = (encoder3, doc2) => {
408753
+ writeVarUint3(encoder3, messageYjsSyncStep12);
408304
408754
  const sv = encodeStateVector(doc2);
408305
- writeVarUint8Array3(encoder2, sv);
408306
- }, writeSyncStep22 = (encoder2, doc2, encodedStateVector) => {
408307
- writeVarUint3(encoder2, messageYjsSyncStep22);
408308
- writeVarUint8Array3(encoder2, encodeStateAsUpdate(doc2, encodedStateVector));
408309
- }, readSyncStep12 = (decoder9, encoder2, doc2) => writeSyncStep22(encoder2, doc2, readVarUint8Array3(decoder9)), readSyncStep22 = (decoder9, doc2, transactionOrigin) => {
408755
+ writeVarUint8Array3(encoder3, sv);
408756
+ }, writeSyncStep22 = (encoder3, doc2, encodedStateVector) => {
408757
+ writeVarUint3(encoder3, messageYjsSyncStep22);
408758
+ writeVarUint8Array3(encoder3, encodeStateAsUpdate(doc2, encodedStateVector));
408759
+ }, readSyncStep12 = (decoder9, encoder3, doc2) => writeSyncStep22(encoder3, doc2, readVarUint8Array3(decoder9)), readSyncStep22 = (decoder9, doc2, transactionOrigin) => {
408310
408760
  try {
408311
408761
  applyUpdate(doc2, readVarUint8Array3(decoder9), transactionOrigin);
408312
408762
  } catch (error48) {
408313
408763
  console.error("Caught error while handling a Yjs update", error48);
408314
408764
  }
408315
- }, writeUpdate2 = (encoder2, update) => {
408316
- writeVarUint3(encoder2, messageYjsUpdate2);
408317
- writeVarUint8Array3(encoder2, update);
408318
- }, readUpdate2, readSyncMessage2 = (decoder9, encoder2, doc2, transactionOrigin) => {
408765
+ }, writeUpdate2 = (encoder3, update) => {
408766
+ writeVarUint3(encoder3, messageYjsUpdate2);
408767
+ writeVarUint8Array3(encoder3, update);
408768
+ }, readUpdate2, readSyncMessage2 = (decoder9, encoder3, doc2, transactionOrigin) => {
408319
408769
  const messageType = readVarUint3(decoder9);
408320
408770
  switch (messageType) {
408321
408771
  case messageYjsSyncStep12:
408322
- readSyncStep12(decoder9, encoder2, doc2);
408772
+ readSyncStep12(decoder9, encoder3, doc2);
408323
408773
  break;
408324
408774
  case messageYjsSyncStep22:
408325
408775
  readSyncStep22(decoder9, doc2, transactionOrigin);
@@ -409332,7 +409782,7 @@ function createHocuspocusSingleDocAdapter(config2) {
409332
409782
  hooks: {
409333
409783
  attach({ ydoc, providerRoomName, onSynced, onDegraded, onReconnecting, onFailed, onStateless }) {
409334
409784
  let hasSynced = false;
409335
- const provider = new HocuspocusProvider({
409785
+ const provider = new V2HocuspocusProvider({
409336
409786
  url: config2.url,
409337
409787
  name: providerRoomName,
409338
409788
  document: ydoc,
@@ -409341,11 +409791,17 @@ function createHocuspocusSingleDocAdapter(config2) {
409341
409791
  preserveConnection: false,
409342
409792
  broadcast: config2.broadcast ?? true,
409343
409793
  quiet: true,
409344
- onSynced() {
409794
+ onSynced({ state }) {
409795
+ if (!state) {
409796
+ if (hasSynced)
409797
+ onDegraded();
409798
+ return;
409799
+ }
409345
409800
  hasSynced = true;
409346
409801
  onSynced();
409347
409802
  },
409348
409803
  onAuthenticationFailed() {
409804
+ provider.disconnect();
409349
409805
  onFailed({
409350
409806
  providerFamily: "hocuspocus",
409351
409807
  reason: "authentication_failed"
@@ -409362,6 +409818,7 @@ function createHocuspocusSingleDocAdapter(config2) {
409362
409818
  onClose(data) {
409363
409819
  const code2 = data.event?.code;
409364
409820
  if (code2 === 4401 || code2 === 4403) {
409821
+ provider.disconnect();
409365
409822
  onFailed({ providerFamily: "hocuspocus", code: code2 });
409366
409823
  return;
409367
409824
  }
@@ -409401,11 +409858,37 @@ function createHocuspocusSingleDocAdapter(config2) {
409401
409858
  }
409402
409859
  });
409403
409860
  }
409861
+ var V2HocuspocusProvider;
409404
409862
  var init_hocuspocus_single_doc = __esm(() => {
409405
409863
  init_hocuspocus_provider_esm();
409864
+ init_decoding();
409406
409865
  init_capability_matrix();
409407
409866
  init_diagnostics2();
409408
409867
  init_runtime4();
409868
+ V2HocuspocusProvider = class V2HocuspocusProvider extends HocuspocusProvider {
409869
+ onMessage(event) {
409870
+ const data = event.data;
409871
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null;
409872
+ if (!bytes) {
409873
+ super.onMessage(event);
409874
+ return;
409875
+ }
409876
+ const decoder9 = createDecoder(bytes);
409877
+ if (readVarString(decoder9) !== this.configuration.name)
409878
+ return;
409879
+ const type = readVarUint(decoder9);
409880
+ if (type === 7) {
409881
+ readVarString(decoder9);
409882
+ this.isAuthenticated = false;
409883
+ this.synced = false;
409884
+ this.configuration.websocketProvider.webSocket?.close(4205, "Reset Connection");
409885
+ return;
409886
+ }
409887
+ if (type !== 0 && type !== 1 && type !== 2 && type !== 3 && type !== 5 && type !== 8)
409888
+ return;
409889
+ super.onMessage(event);
409890
+ }
409891
+ };
409409
409892
  });
409410
409893
 
409411
409894
  // ../../../v2/node_modules/.pnpm/@liveblocks+core@3.15.5_@types+json-schema@7.0.15/node_modules/@liveblocks/core/dist/index.js
@@ -418713,8 +419196,8 @@ function clean(...arrays) {
418713
419196
  function createView(arr) {
418714
419197
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
418715
419198
  }
418716
- function rotr(word3, shift) {
418717
- return word3 << 32 - shift | word3 >>> shift;
419199
+ function rotr(word4, shift) {
419200
+ return word4 << 32 - shift | word4 >>> shift;
418718
419201
  }
418719
419202
  function utf8ToBytes(str) {
418720
419203
  if (typeof str !== "string")
@@ -422536,8 +423019,8 @@ function parseParagraphXml(xml, inheritedNamespaceBindings = {}, trackedWrapperI
422536
423019
  if (trackedWrapperIdentityState) {
422537
423020
  advanceTrackedWrapperIdentityState(pPrSpan.xml, paragraphNamespaceBindings, trackedWrapperIdentityState);
422538
423021
  }
422539
- const directChildren3 = readDirectPPrChildren(pPrSpan.xml);
422540
- for (const [prop, child] of directChildren3) {
423022
+ const directChildren4 = readDirectPPrChildren(pPrSpan.xml);
423023
+ for (const [prop, child] of directChildren4) {
422541
423024
  if (prop === "pStyle" || prop === "numPr")
422542
423025
  continue;
422543
423026
  pPr[prop] = child;
@@ -429543,7 +430026,7 @@ function canonicalize2(value2) {
429543
430026
  }
429544
430027
  function reservationDigest(bundle) {
429545
430028
  const canonical = canonicalJson2(bundle);
429546
- return sha256Hex2(encoder2.encode(canonical));
430029
+ return sha256Hex2(encoder3.encode(canonical));
429547
430030
  }
429548
430031
  function shardReservationDigest(bundle, shardId) {
429549
430032
  const slice = {};
@@ -429572,10 +430055,10 @@ function shardReservationDigest(bundle, shardId) {
429572
430055
  }
429573
430056
  return reservationDigest({ shardId, slice });
429574
430057
  }
429575
- var encoder2;
430058
+ var encoder3;
429576
430059
  var init_digest2 = __esm(() => {
429577
430060
  init_hash();
429578
- encoder2 = new TextEncoder;
430061
+ encoder3 = new TextEncoder;
429579
430062
  });
429580
430063
 
429581
430064
  // ../../../v2/collaboration-v2/dist/journal/schema.js
@@ -433358,10 +433841,10 @@ function paragraphEmissionNames(context, preservedXml) {
433358
433841
  bindings[prefix] = namespace;
433359
433842
  return prefix;
433360
433843
  };
433361
- const word3 = choose("w", WORD_NAMESPACE7);
433844
+ const word4 = choose("w", WORD_NAMESPACE7);
433362
433845
  const word2010 = choose("w14", WORD_2010_NAMESPACE3);
433363
433846
  const declarations = Object.entries({ "": "", ...bindings }).filter(([prefix, uri]) => prefix !== "xml" && (context.inherited[prefix] ?? "") !== uri).sort(([left], [right]) => left.localeCompare(right)).map(([prefix, uri]) => ` xmlns${prefix ? `:${prefix}` : ""}="${xmlEscape(uri)}"`).join("");
433364
- return { word: word3, word2010, declarations };
433847
+ return { word: word4, word2010, declarations };
433365
433848
  }
433366
433849
  var WORD_NAMESPACE7 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", WORD_2010_NAMESPACE3 = "http://schemas.microsoft.com/office/word/2010/wordml", CANONICAL_NAMESPACES;
433367
433850
  var init_xml_emission_context = __esm(() => {
@@ -433505,7 +433988,7 @@ function materializeProjection(input) {
433505
433988
  const tableReplacements = readTableStructuralReplacements(readTarget);
433506
433989
  const previousBlockIndex = previous3 ? blockDigestIndex(previous3.blockDigests) : null;
433507
433990
  const insertedBlockHint = previousBlockIndex && [...dirtyStoryBlocks.get(handle.shardId) ?? []].some((blockId) => !previousBlockIndex.has(blockId));
433508
- const structuralSnapshot = previous3 && (wholeStoryDirtyShardIds.has(handle.shardId) || insertedBlockHint) ? readStorySnapshot(readTarget) : null;
433991
+ const structuralSnapshot = previous3 && (wholeStoryDirtyShardIds.has(handle.shardId) || insertedBlockHint || tableReplacements.length === 0 && input.dirty.some((record4) => record4.shardId === handle.shardId && record4.kind === PROJECTION_DIRTY_KIND.storyBlocks)) ? readStorySnapshot(readTarget) : null;
433509
433992
  const overlaidTableIds = structuralSnapshot ? new Set(tableReplacements.map((table) => table.tableNodeId)) : null;
433510
433993
  const restoredTableBoundary = structuralSnapshot && previousBlockIndex ? structuralSnapshot.blocks.some((block) => block.structuralRefs.tableNodeId != null && !previousBlockIndex.has(block.blockId) && !overlaidTableIds.has(block.structuralRefs.tableNodeId)) : false;
433511
433994
  const removedTableBoundary = structuralSnapshot && previous3 ? hasRemovedTableBoundary(previous3, structuralSnapshot.blocks, new Set(tableReplacements.filter((table) => table.deltaKind === "table.rewrite" && table.xml === "").flatMap((table) => table.affectedBlockIds))) : false;
@@ -433527,7 +434010,8 @@ function materializeProjection(input) {
433527
434010
  blocks: controlledSnapshot.blocks.map(({ blockId, leadingXml, trailingXml, splitFromBlockId }) => ({ blockId, leadingXml, trailingXml, splitFromBlockId }))
433528
434011
  });
433529
434012
  }
433530
- if (controlledSnapshot && !controlledTextOnly || restoredTableBoundary || removedTableBoundary) {
434013
+ const changedTableBoundary = structuralSnapshot && previous3 && tableReplacements.length === 0 && hasChangedTableBoundaryXml(previous3, structuralSnapshot.blocks);
434014
+ if (controlledSnapshot && !controlledTextOnly || restoredTableBoundary || removedTableBoundary || changedTableBoundary) {
433531
434015
  const snapshot4 = controlledSnapshot ?? structuralSnapshot ?? readStorySnapshot(readTarget);
433532
434016
  const placements2 = projectedNamespaceContexts(snapshot4, bootstrap, sourceNamespaces);
433533
434017
  const blocks = snapshot4.blocks.map((block) => ({
@@ -434088,6 +434572,20 @@ function projectedNamespaceContexts(snapshot3, bootstrap, source) {
434088
434572
  });
434089
434573
  return contexts;
434090
434574
  }
434575
+ function hasChangedTableBoundaryXml(previous3, blocks) {
434576
+ const byId = new Map(previous3.blockDigests.map((entry) => [entry.blockId, entry]));
434577
+ return blocks.some((block) => {
434578
+ if (!block.structuralRefs.tableNodeId || !block.leadingXml)
434579
+ return false;
434580
+ const entry = byId.get(block.blockId);
434581
+ if (!entry || entry.xmlStart == null)
434582
+ return false;
434583
+ const leading = block.leadingXml;
434584
+ if (entry.xml.startsWith(leading))
434585
+ return false;
434586
+ return entry.xmlStart < leading.length || previous3.xml.slice(entry.xmlStart - leading.length, entry.xmlStart) !== leading;
434587
+ });
434588
+ }
434091
434589
  function hasRemovedTableBoundary(previous3, blocks, overlayDeletedBlockIds) {
434092
434590
  const liveIds = new Set(blocks.map((block) => block.blockId));
434093
434591
  const removed = previous3.blockDigests.filter((block) => !liveIds.has(block.blockId) && !overlayDeletedBlockIds.has(block.blockId));
@@ -435854,8 +436352,8 @@ function renderSyntheticTableCell(input) {
435854
436352
  }).slice(0, 8).toUpperCase();
435855
436353
  const prefix = input.tableXml.slice(input.cellSpan.start, contentStart);
435856
436354
  const inherited = new XmlEmissionContext(prefix, input.inherited).at(prefix.length);
435857
- const { word: word3, word2010, declarations } = paragraphEmissionNames({ inherited, source: inherited }, "");
435858
- return prefix + `<${word3}:p ${word2010}:paraId="${paragraphId4}"${declarations}/>` + input.tableXml.slice(contentEnd, input.cellSpan.end);
436355
+ const { word: word4, word2010, declarations } = paragraphEmissionNames({ inherited, source: inherited }, "");
436356
+ return prefix + `<${word4}:p ${word2010}:paraId="${paragraphId4}"${declarations}/>` + input.tableXml.slice(contentEnd, input.cellSpan.end);
435859
436357
  }
435860
436358
  function directElementSpans(xml, openEnd, closeStart, localName3) {
435861
436359
  const spans = [];
@@ -439212,6 +439710,16 @@ function mirrorFamilyIntoStory(input) {
439212
439710
  }
439213
439711
  return;
439214
439712
  case "storyBlocks":
439713
+ if (input.extension.wholeBodyTextReplacement) {
439714
+ if (input.storyId !== input.extension.wholeBodyTextReplacement.storyId) {
439715
+ throw new Error("whole-body replacement mirror received a different story");
439716
+ }
439717
+ resolveStoryShardScope(input.doc).doc.transact(() => {
439718
+ syncWholeStoryFromSession(input.session, input.storyId, input.doc);
439719
+ getStoryTablesMap(input.doc).clear();
439720
+ }, STORY_SURFACE_BACKEND_ORIGIN);
439721
+ return;
439722
+ }
439215
439723
  if (input.extension.contentControlRewrite) {
439216
439724
  mirrorContentControlRewrite(input);
439217
439725
  return;
@@ -441925,6 +442433,9 @@ function admitPreparedStorySurfaceMutation(prepared, options) {
441925
442433
  return { ok: false, message: `no story shard registered for ${storyId}` };
441926
442434
  }
441927
442435
  }
442436
+ if (extension2.wholeBodyTextReplacement) {
442437
+ return options.session && options.isSessionProjectionCurrent?.() === true && extension2.family === "storyBlocks" && prepared.source.kind === "storySurfaceRewrite" && prepared.source.operationId === "range-ref-whole-body-replace" && storyIds.length === 1 && storyIds[0] === extension2.wholeBodyTextReplacement.storyId && extension2.targetBlockIds.length > 0 ? { ok: true } : { ok: false, message: "Whole-body replacement requires a current owning session and complete story proof." };
442438
+ }
441928
442439
  if (prepared.source.kind === "storySurfaceRewrite" && prepared.source.contentControlRewrite) {
441929
442440
  return options.session && extension2.family === "storyBlocks" && extension2.contentControlRewrite && storyIds.length === 1 ? { ok: true } : { ok: false, message: "Content-control rewrite requires a prepared structural delta and owning session." };
441930
442441
  }
@@ -444489,12 +445000,12 @@ function buildProjectionApplyInputForTesting(record3, previousRecord, projection
444489
445000
  }
444490
445001
  function buildProjectedParts(record3, previousRecord, changedPartUris, projectionRegistry, options) {
444491
445002
  const out = [];
444492
- const encoder3 = new TextEncoder;
445003
+ const encoder4 = new TextEncoder;
444493
445004
  const previousStoriesByPartUri = new Map((previousRecord?.stories ?? []).map((story) => [story.partUri, story]));
444494
445005
  for (const story of record3.stories) {
444495
445006
  const changed = changedPartUris.has(story.partUri);
444496
- const patches = changed && !options.forceStoryBytes ? buildStoryPartBytePatches(previousStoriesByPartUri.get(story.partUri), story, encoder3, options.readLivePartBytes, options.readLiveBlockRange) : null;
444497
- const bytes = changed && !patches ? encodeProjectionXml(encoder3, story.xml) : null;
445007
+ const patches = changed && !options.forceStoryBytes ? buildStoryPartBytePatches(previousStoriesByPartUri.get(story.partUri), story, encoder4, options.readLivePartBytes, options.readLiveBlockRange) : null;
445008
+ const bytes = changed && !patches ? encodeProjectionXml(encoder4, story.xml) : null;
444498
445009
  out.push({
444499
445010
  partUri: story.partUri,
444500
445011
  contentType: storyContentType(story.storyKind),
@@ -444504,7 +445015,7 @@ function buildProjectedParts(record3, previousRecord, changedPartUris, projectio
444504
445015
  });
444505
445016
  }
444506
445017
  for (const relationship of record3.relationships) {
444507
- const bytes = changedPartUris.has(relationship.relsPartUri) ? encodeProjectionXml(encoder3, relationship.xml) : null;
445018
+ const bytes = changedPartUris.has(relationship.relsPartUri) ? encodeProjectionXml(encoder4, relationship.xml) : null;
444508
445019
  out.push({
444509
445020
  partUri: relationship.relsPartUri,
444510
445021
  contentType: "application/vnd.openxmlformats-package.relationships+xml",
@@ -444514,7 +445025,7 @@ function buildProjectedParts(record3, previousRecord, changedPartUris, projectio
444514
445025
  }
444515
445026
  for (const part of record3.parts) {
444516
445027
  if (part.content.kind === "xml") {
444517
- const bytes = changedPartUris.has(part.partUri) ? encodeProjectionXml(encoder3, part.content.xml) : null;
445028
+ const bytes = changedPartUris.has(part.partUri) ? encodeProjectionXml(encoder4, part.content.xml) : null;
444518
445029
  out.push({
444519
445030
  partUri: part.partUri,
444520
445031
  contentType: part.contentType || null,
@@ -444541,7 +445052,7 @@ function storyProjectionSignature(story) {
444541
445052
  ...story.blockDigests.map((block) => `${block.blockId}:${block.digest}:${block.xml.length}`)
444542
445053
  ].join("|");
444543
445054
  }
444544
- function buildStoryPartBytePatches(previous3, next, encoder3, readLivePartBytes, readLiveBlockRange) {
445055
+ function buildStoryPartBytePatches(previous3, next, encoder4, readLivePartBytes, readLiveBlockRange) {
444545
445056
  if (!previous3 || previous3.partUri !== next.partUri || previous3.storyKind !== next.storyKind)
444546
445057
  return null;
444547
445058
  if (previous3.blockDigests.length !== next.blockDigests.length)
@@ -444566,13 +445077,13 @@ function buildStoryPartBytePatches(previous3, next, encoder3, readLivePartBytes,
444566
445077
  if (priorBlock.digest === nextBlock.digest && priorBlock.xml === nextBlock.xml)
444567
445078
  continue;
444568
445079
  const range = readLiveBlockRange ? readLiveBlockRange(previous3.storyId, previous3.partUri, priorBlock.blockId) : priorBlock.byteStart != null && priorBlock.byteEnd != null ? { startByte: priorBlock.byteStart, endByte: priorBlock.byteEnd } : null;
444569
- if (!range || !liveWindowMatches(liveBytes, range.startByte, range.endByte, encoder3.encode(priorBlock.xml))) {
445080
+ if (!range || !liveWindowMatches(liveBytes, range.startByte, range.endByte, encoder4.encode(priorBlock.xml))) {
444570
445081
  return null;
444571
445082
  }
444572
445083
  patches.push({
444573
445084
  startByte: range.startByte,
444574
445085
  endByte: range.endByte,
444575
- bytes: encodeProjectionXml(encoder3, nextBlock.xml)
445086
+ bytes: encodeProjectionXml(encoder4, nextBlock.xml)
444576
445087
  });
444577
445088
  }
444578
445089
  if (previous3.xml.slice(previousEnd) !== next.xml.slice(nextEnd))
@@ -444588,8 +445099,8 @@ function liveWindowMatches(live, startByte, endByte, expected) {
444588
445099
  }
444589
445100
  return true;
444590
445101
  }
444591
- function encodeProjectionXml(encoder3, xml) {
444592
- return measureSDTxPerf("projectionEncodeMs", () => encoder3.encode(xml));
445102
+ function encodeProjectionXml(encoder4, xml) {
445103
+ return measureSDTxPerf("projectionEncodeMs", () => encoder4.encode(xml));
444593
445104
  }
444594
445105
  function projectionPartSignatures(record3) {
444595
445106
  const signatures = new Map;
@@ -444636,16 +445147,16 @@ function storyContentType(storyKind) {
444636
445147
  }
444637
445148
  async function encodeProjectionRecordAsDocx(input) {
444638
445149
  const entries2 = new Map;
444639
- const encoder3 = new TextEncoder;
445150
+ const encoder4 = new TextEncoder;
444640
445151
  for (const story of input.record.stories) {
444641
- entries2.set(zipKey(story.partUri), encodeProjectionXml(encoder3, story.xml));
445152
+ entries2.set(zipKey(story.partUri), encodeProjectionXml(encoder4, story.xml));
444642
445153
  }
444643
445154
  for (const relationship of input.record.relationships) {
444644
- entries2.set(zipKey(relationship.relsPartUri), encodeProjectionXml(encoder3, relationship.xml));
445155
+ entries2.set(zipKey(relationship.relsPartUri), encodeProjectionXml(encoder4, relationship.xml));
444645
445156
  }
444646
445157
  for (const part of input.record.parts) {
444647
445158
  if (part.content.kind === "xml") {
444648
- entries2.set(zipKey(part.partUri), encodeProjectionXml(encoder3, part.content.xml));
445159
+ entries2.set(zipKey(part.partUri), encodeProjectionXml(encoder4, part.content.xml));
444649
445160
  continue;
444650
445161
  }
444651
445162
  const bytes = await resolveProjectedPartBytes(part.partUri, input.projectionRegistry, input.blobAdapter);