@superdoc/mcp 1.6.0-next.6 → 1.6.0-next.8

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 +1863 -1291
  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.6";
31446
+ var SDK_VERSION = "2.19.0-next.8";
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;
@@ -194891,12 +195025,15 @@ function compileParsedOverlapEdit(input, tokens, descendedEditableContainers) {
194891
195025
  if (commented.length > 0) {
194892
195026
  const parent = commented[0].token;
194893
195027
  const following = touched.filter((entry) => entry.token.kind === "plain");
194894
- const collapsedInsertion = commented.length === 1 && wrappers.length === 1 && input.changeMode === "tracked" && input.newText.length > 0 && input.rangeStart === input.rangeEnd && input.rangeStart > parent.visibleStart && input.rangeStart < parent.visibleEnd;
194895
- if (!collapsedInsertion && (commented.length !== 1 || wrappers.length !== 1 || following.length !== 1 || following[0].token.byteStart < parent.byteEnd || input.changeMode !== "tracked" || input.newText.length === 0 || input.rangeStart <= parent.visibleStart || input.rangeStart >= parent.visibleEnd || input.rangeEnd <= parent.visibleEnd || input.rangeEnd > following[0].token.visibleEnd)) {
195028
+ const collapsedInsertion = commented.length === 1 && wrappers.length === 1 && input.changeMode === "tracked" && input.newText.length > 0 && input.rangeStart === input.rangeEnd && input.rangeStart >= parent.visibleStart && input.rangeStart <= parent.visibleEnd;
195029
+ const partialDeletion = commented.length === 1 && wrappers.length === 1 && input.changeMode === "tracked" && input.newText.length === 0 && input.rangeStart >= parent.visibleStart && input.rangeEnd <= parent.visibleEnd && input.rangeStart < input.rangeEnd && input.rangeEnd - input.rangeStart < parent.inner.text.length;
195030
+ if (collapsedInsertion && (input.rangeStart === parent.visibleStart || input.rangeStart === parent.visibleEnd))
195031
+ return insertBesideCommentedInsertion(input, parent);
195032
+ if (!collapsedInsertion && !partialDeletion && (commented.length !== 1 || wrappers.length !== 1 || following.length !== 1 || following[0].token.byteStart < parent.byteEnd || input.changeMode !== "tracked" || input.newText.length === 0 || input.rangeStart <= parent.visibleStart || input.rangeStart >= parent.visibleEnd || input.rangeEnd <= parent.visibleEnd || input.rangeEnd > following[0].token.visibleEnd)) {
194896
195033
  return {
194897
195034
  ok: false,
194898
195035
  reason: "text-range-in-unsupported-tracked-wrapper",
194899
- detail: "overlap compiler: comment-bearing insertion requires bounded tracked typing or spanning replacement."
195036
+ detail: "overlap compiler: comment-bearing insertion requires bounded tracked typing, partial deletion, or spanning replacement."
194900
195037
  };
194901
195038
  }
194902
195039
  }
@@ -195325,14 +195462,19 @@ function tryContinueDirectInsertionInAdjacentPlainRun(input, allTokens, touched)
195325
195462
  }
195326
195463
  return null;
195327
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
+ }
195328
195469
  function tryPureDeleteAcrossTokens(input, allTokens, touched, touchedBreaks = []) {
195329
195470
  if (input.newText.length !== 0 || input.rangeStart >= input.rangeEnd)
195330
195471
  return null;
195331
195472
  const touchedInsertions = touched.filter((entry) => entry.token.kind === "ins");
195332
- 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)) {
195333
195474
  return null;
195334
195475
  }
195335
- 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;
195336
195478
  }
195337
195479
  function tryRangeReplacementAcrossTokens(input, allTokens, touched) {
195338
195480
  if (input.newText.length === 0 || input.rangeStart >= input.rangeEnd)
@@ -195349,7 +195491,7 @@ function tryRangeReplacementAcrossTokens(input, allTokens, touched) {
195349
195491
  if (!firstSelected)
195350
195492
  return null;
195351
195493
  const touchedInsertions = touched.filter((entry) => entry.token.kind === "ins");
195352
- 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)) {
195353
195495
  return null;
195354
195496
  }
195355
195497
  const result = input.changeMode === "tracked" ? authorTrackedPureDelete(input, allTokens, touched) : authorDirectPureDelete(input, allTokens, touched);
@@ -196199,6 +196341,29 @@ function closeFreshInsertionScope(xml, source, destination) {
196199
196341
  return null;
196200
196342
  return closeNamespaceScope(xml.slice(0, wrapper.openEnd) + inner + xml.slice(wrapper.closeStart), source, destination, { referencedOnly: true });
196201
196343
  }
196344
+ function insertBesideCommentedInsertion(input, parent) {
196345
+ const before = input.rangeStart === parent.visibleStart;
196346
+ const offset = before ? 0 : parent.inner.text.length;
196347
+ const meta3 = runMetaAtInsertionPoint(parent, offset);
196348
+ const fresh = buildInsWrapperXml({
196349
+ nsPrefix: parent.nsPrefix,
196350
+ wId: String(resolveNextWId(input)),
196351
+ author: { name: input.currentAuthor.name, initials: input.currentAuthor.initials ?? null, email: input.currentAuthor.email ?? null },
196352
+ date: input.txTimestamp,
196353
+ rsidR: input.insRsid,
196354
+ inner: { ...meta3, rPr: rPrAtInsertionPoint(parent, offset), text: input.newText }
196355
+ });
196356
+ const closed = closeFreshInsertionScope(fresh, Object.fromEntries(parent.namespaceBindings), input.namespaceBindings ?? {});
196357
+ if (closed == null)
196358
+ return { ok: false, reason: "text-range-in-unsupported-tracked-wrapper" };
196359
+ const boundary = before ? parent.byteStart : parent.byteEnd;
196360
+ return {
196361
+ ok: true,
196362
+ xml: input.paragraphXml.slice(0, boundary) + closed + input.paragraphXml.slice(boundary),
196363
+ emittedRsids: [input.insRsid],
196364
+ requiresCollaborationSessionSync: true
196365
+ };
196366
+ }
196202
196367
  function splitInsertionAroundChildChange(input, allTokens, parent) {
196203
196368
  const nestedDeletions = parent.nestedDeletions ?? [];
196204
196369
  const rawLocalStart = input.rangeStart - parent.visibleStart;
@@ -196252,7 +196417,7 @@ function splitInsertionAroundChildChange(input, allTokens, parent) {
196252
196417
  const hasTailFragment = tailText.length > 0 || tailOwnedNested.length > 0;
196253
196418
  const emitsTrailingParentFragment = hasTailFragment || removedText.length > 0 && input.newText.length > 0;
196254
196419
  const tailParentWId = input.changeMode === "tracked" && input.newText.length > 0 && hasHeadFragment && emitsTrailingParentFragment ? allocateFreshWId() : parent.wId;
196255
- const liftComment = parent.commentedBoundary && input.rangeStart === input.rangeEnd && input.changeMode === "tracked" && input.newText.length > 0 && parent._classification !== "same-user";
196420
+ const liftComment = parent.commentedBoundary && input.changeMode === "tracked" && (input.rangeStart === input.rangeEnd && input.newText.length > 0 || removedText.length > 0 && input.newText.length === 0) && parent._classification !== "same-user";
196256
196421
  const headInsXml = hasHeadFragment ? buildInsWrapperXml({
196257
196422
  openTag: parent.openTag,
196258
196423
  namespaceBindings: parent.namespaceBindings,
@@ -198172,6 +198337,9 @@ function allocateDistinctBatchRsids(state, txId, count) {
198172
198337
  return allocated;
198173
198338
  }
198174
198339
  function runEditTextCommit(input) {
198340
+ if (input.validateOnly && input.op.edits) {
198341
+ input = { ...input, state: createTextEditValidationState(input.state) };
198342
+ }
198175
198343
  const { state, txId, op } = input;
198176
198344
  if (op.edits) {
198177
198345
  return op.changeMode === "tracked" ? runTrackedEditTextBatchCommit(input, op.edits) : runDirectEditTextBatchCommit(input, op.edits);
@@ -198515,6 +198683,8 @@ function runDirectEditTextBatchCommit(input, edits) {
198515
198683
  actorAttribution: { actorType: input.options.actorTag ?? "code" }
198516
198684
  }
198517
198685
  };
198686
+ if (input.validateOnly)
198687
+ return { txId, status: "committed" };
198518
198688
  return commitPreparedMutation(state, prepared, { pushHistory: input.pushHistory });
198519
198689
  }
198520
198690
  function rewritePlainTrackedTextBatch(paragraphBytes, edits, stampByEdit, stamping) {
@@ -198652,6 +198822,13 @@ function runTrackedEditTextBatchCommit(input, edits) {
198652
198822
  byBlock.set(edit.on.startBlockId, entries);
198653
198823
  }
198654
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
+ };
198655
198832
  const plannedRsids = allocateDistinctBatchRsids(state, txId, ordered.length);
198656
198833
  const stampByEdit = new Map(ordered.map((edit, ordinal) => [edit, {
198657
198834
  rsid: edit.rsid ?? plannedRsids[ordinal],
@@ -198775,7 +198952,7 @@ function runTrackedEditTextBatchCommit(input, edits) {
198775
198952
  wId: stamp.wId,
198776
198953
  author: stamping.author,
198777
198954
  date: stamping.date
198778
- });
198955
+ }, undefined, undefined, planAdditionalWId);
198779
198956
  if (!overlap.ok)
198780
198957
  return rejected2(txId, overlap.reason);
198781
198958
  afterBytes = overlap.bytes;
@@ -198907,7 +199084,7 @@ function runTrackedEditTextBatchCommit(input, edits) {
198907
199084
  baseRevisions: forwardPatchGroup.baseRevisions,
198908
199085
  reservations: {
198909
199086
  conflictRule: "first-choice-strict",
198910
- revisionWIds: plannedWIds
199087
+ revisionWIds: [...plannedWIds, ...additionalWIds]
198911
199088
  },
198912
199089
  localApplyBundle: forwardPatchGroup,
198913
199090
  semanticDelta: {
@@ -198958,6 +199135,8 @@ function runTrackedEditTextBatchCommit(input, edits) {
198958
199135
  actorAttribution: { actorType: input.options.actorTag ?? "code" }
198959
199136
  }
198960
199137
  };
199138
+ if (input.validateOnly)
199139
+ return { txId, status: "committed" };
198961
199140
  return commitPreparedMutation(state, prepared, { pushHistory: input.pushHistory });
198962
199141
  }
198963
199142
  function resolveTextEditPartView(state, op) {
@@ -200764,7 +200943,7 @@ function tryOverlapRewriteDirect(input, bytes, window2, byteBase, inheritedNames
200764
200943
  requiresCollaborationSessionSync: compiled.requiresCollaborationSessionSync
200765
200944
  };
200766
200945
  }
200767
- function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inlineContext, inheritedNamespaceBindings) {
200946
+ function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inlineContext, inheritedNamespaceBindings, planAdditionalWId) {
200768
200947
  const op = input.op;
200769
200948
  let paragraphXml = inlineContext?.paragraphXml ?? TD42.decode(bytes.subarray(window2.byteStart, window2.byteEnd));
200770
200949
  const namespaceBindings = inheritedNamespaceBindings ?? textTargetNamespaceBindings(input, window2, byteBase);
@@ -200785,7 +200964,7 @@ function tryOverlapRewriteTracked(input, bytes, window2, byteBase, stamp, inline
200785
200964
  rsid: stamp.rsid,
200786
200965
  insRsid: stamp.insRsid,
200787
200966
  nextWId: stamp.wId,
200788
- reserveWId: () => reserveRevisionWIdBlock(input.state, 1),
200967
+ reserveWId: planAdditionalWId ?? (() => reserveRevisionWIdBlock(input.state, 1)),
200789
200968
  revisionOccurrenceAt: createRevisionOccurrenceResolver(input, bytes, window2, byteBase, paragraphXml)
200790
200969
  });
200791
200970
  let compiled = compile(true);
@@ -203707,6 +203886,7 @@ function collectPerPartRevisions(state, partUris) {
203707
203886
  }
203708
203887
  var TD42, TE16, TRACKED_WRAPPER_OPEN_RE, INLINE_CONTROL_PLACEHOLDER = "";
203709
203888
  var init_compile_edit_text = __esm(() => {
203889
+ init_text_edit_validation_state();
203710
203890
  init_rewrite_groups();
203711
203891
  init_comparison_hunk_groups();
203712
203892
  init_word_text_payload();
@@ -212527,6 +212707,28 @@ function collectStandaloneCommentWIds(state) {
212527
212707
  return out;
212528
212708
  }
212529
212709
  function preserveAdjacentEndBoundaryWIdsForDroppedRange(input) {
212710
+ if (input.decision === "reject" && input.fragment.kind === "ins") {
212711
+ const markerIndex = input.markerIndex ?? buildCommentMarkerIndex(input.partXml);
212712
+ const preserved2 = new Set(input.defaultWIds);
212713
+ for (const wId of input.defaultWIds) {
212714
+ const markers = markerIndex.allByWId.get(wId) ?? [];
212715
+ if (markers.length !== 3)
212716
+ continue;
212717
+ const start = markers.find((marker) => marker.kind === "commentRangeStart");
212718
+ const end = markers.find((marker) => marker.kind === "commentRangeEnd");
212719
+ const reference = markers.find((marker) => marker.kind === "commentReference");
212720
+ if (!start || !end || !reference || start.byteEnd > input.droppedRange.startInXml || end.byteStart < input.droppedRange.endInXml || reference.byteStart < end.byteEnd) {
212721
+ continue;
212722
+ }
212723
+ const before = input.partXml.slice(start.byteEnd, input.droppedRange.startInXml);
212724
+ const after = input.partXml.slice(input.droppedRange.endInXml, end.byteStart);
212725
+ const opening = /^\s*<([\w.-]+):ins\b(?:[^"'<>]|"[^"]*"|'[^']*')*>\s*$/.exec(before);
212726
+ const closing = /^\s*<\/([\w.-]+):ins\s*>\s*$/.exec(after);
212727
+ if (opening && closing && opening[1] === closing[1])
212728
+ preserved2.delete(wId);
212729
+ }
212730
+ return preserved2;
212731
+ }
212530
212732
  if (input.decision !== "accept" || input.fragment.kind !== "del" || isSessionCreatedTextFragment(input.fragment, input.sessionCreatedTrackedChangeRsids, input.sessionCreatedTrackedChangeWIds)) {
212531
212733
  return input.defaultWIds;
212532
212734
  }
@@ -223137,8 +223339,13 @@ function runStorySurfaceRewriteCommit(input) {
223137
223339
  }
223138
223340
  const headerFooterUpdate = prepareHeaderFooterUpdate(input.state, op, effectivePerPart);
223139
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
+ }
223140
223346
  const storySurface = {
223141
223347
  family,
223348
+ ...wholeBodyTextReplacement ? { wholeBodyTextReplacement } : {},
223142
223349
  ...contentControlRewrite ? { contentControlRewrite } : {},
223143
223350
  storyLocal: op.storyLocal,
223144
223351
  ...op.changeMode ? { changeMode: op.changeMode } : {},
@@ -223179,6 +223386,7 @@ function runStorySurfaceRewriteCommit(input) {
223179
223386
  },
223180
223387
  replayInputs: {
223181
223388
  source: op,
223389
+ ...wholeBodyTextReplacement ? { wholeBodyTextReplacement } : {},
223182
223390
  inverseDescriptor: createPreparedInverseDescriptor(op, storyPartOwnership)
223183
223391
  },
223184
223392
  backendExtensions: {
@@ -223625,6 +223833,7 @@ var init_compile_story_surface_rewrite = __esm(() => {
223625
223833
  init_session_hyperlink_metadata();
223626
223834
  init_sectpr_parser();
223627
223835
  init_content_control_rewrite();
223836
+ init_whole_body_text_replacement();
223628
223837
  init_header_footer_update();
223629
223838
  init_compile_paste_notes();
223630
223839
  init_commit_prepared_mutation();
@@ -244419,28 +244628,7 @@ function preflightDirectTextEdit(input) {
244419
244628
  const validationView = createDirectTextEditValidationView(input);
244420
244629
  if (!validationView.ok)
244421
244630
  return validationView.reason;
244422
- const validationState = {
244423
- ...input.state,
244424
- packageBytes: validationView.packageBytes,
244425
- partRegistries: new Map(input.state.partRegistries),
244426
- idReservations: {
244427
- ...input.state.idReservations,
244428
- revisionWIds: {
244429
- ...input.state.idReservations.revisionWIds,
244430
- issued: new Set(input.state.idReservations.revisionWIds.issued)
244431
- },
244432
- comments: {
244433
- wIds: new Set(input.state.idReservations.comments.wIds),
244434
- repairedSourceWIds: new Map(input.state.idReservations.comments.repairedSourceWIds),
244435
- paraIds: new Set(input.state.idReservations.comments.paraIds),
244436
- durableIds: new Set(input.state.idReservations.comments.durableIds)
244437
- }
244438
- }
244439
- };
244440
- isolateLazyIndexTelemetry(validationState);
244441
- isolateTableCatalogCache(validationState);
244442
- isolatePartWmlScanCache(validationState);
244443
- isolateTrackedChangePartScanCache(validationState);
244631
+ const validationState = createTextEditValidationState(input.state, validationView.packageBytes);
244444
244632
  if (validationView.omittedByteRangeCount > 0) {
244445
244633
  invalidateTrackedChangeCatalogIfTouched(validationState, [input.on.partUri]);
244446
244634
  }
@@ -244463,6 +244651,28 @@ function preflightDirectTextEdit(input) {
244463
244651
  });
244464
244652
  return receipt2.status === "rejected" ? receipt2.rejectedReason ?? "internal-error" : null;
244465
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
+ }
244466
244676
  function createDirectTextEditValidationView(input) {
244467
244677
  const packageBytes = input.state.packageBytes.detached();
244468
244678
  const ranges = input.validationByteRangesToOmit ?? [];
@@ -248088,10 +248298,8 @@ function emptyHeaderFooterSkeleton(kind) {
248088
248298
  }
248089
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;
248090
248300
  var init_tx_context = __esm(() => {
248091
- init_part_wml_scan_cache();
248301
+ init_text_edit_validation_state();
248092
248302
  init_part_payload();
248093
- init_lazy_indexes();
248094
- init_table_catalog();
248095
248303
  init_catalog3();
248096
248304
  init_sd_document_state();
248097
248305
  init_paragraph_index();
@@ -251730,11 +251938,10 @@ async function streamingSavePackageToSink(entries, sink) {
251730
251938
  largestOutputChunkBytes: metrics.largestOutputChunkBytes
251731
251939
  };
251732
251940
  }
251733
- var STREAM_PUSH_CHUNK, STREAMING_SAVE_ZIP_ENTRY_MTIME;
251941
+ var STREAM_PUSH_CHUNK, STREAMING_SAVE_ZIP_ENTRY_MTIME = "1980-01-01T00:00:00";
251734
251942
  var init_large_streaming_save = __esm(() => {
251735
251943
  init_esm2();
251736
251944
  STREAM_PUSH_CHUNK = 64 * 1024;
251737
- STREAMING_SAVE_ZIP_ENTRY_MTIME = new Date(1980, 0, 1, 0, 0, 0);
251738
251945
  });
251739
251946
 
251740
251947
  // ../../../v2/editor-core/dist/document/transactions/comment-export-normalization.js
@@ -253379,11 +253586,14 @@ function listSDDocumentSessionInternalPartRelationships(session, ownerPartUri) {
253379
253586
  const parsed = parseRelationshipsXml(xml, {
253380
253587
  ownerPartUri: normalizedOwner,
253381
253588
  relsUri,
253382
- resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode)
253589
+ resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode, internal.state.parts)
253383
253590
  });
253384
253591
  return parsed.relationships;
253385
253592
  }
253386
253593
  function listSDDocumentSessionInternalCapturePartRelationships(session, ownerPartUri) {
253594
+ const internal = INTERNALS.get(session);
253595
+ if (!internal)
253596
+ throw new Error("internal: unknown SDDocumentSession instance");
253387
253597
  const normalizedOwner = normalizePartUri(ownerPartUri);
253388
253598
  const relsUri = relsUriFor(normalizedOwner);
253389
253599
  const bytes = getSDDocumentSessionInternalCapturePartBytes(session, relsUri);
@@ -253392,7 +253602,7 @@ function listSDDocumentSessionInternalCapturePartRelationships(session, ownerPar
253392
253602
  const parsed = parseRelationshipsXml(RELS_DECODER.decode(bytes), {
253393
253603
  ownerPartUri: normalizedOwner,
253394
253604
  relsUri,
253395
- resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode)
253605
+ resolveTarget: (target, mode) => resolveTargetUri(normalizedOwner, target, mode, internal.state.parts)
253396
253606
  });
253397
253607
  return parsed.relationships;
253398
253608
  }
@@ -254683,6 +254893,12 @@ function preflightSDDocumentSessionInternalDirectTextEdit(session, input) {
254683
254893
  ...input.validationByteRangesToOmit ? { validationByteRangesToOmit: input.validationByteRangesToOmit } : {}
254684
254894
  });
254685
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
+ }
254686
254902
  function validateSDDocumentSessionInternalImageMove(session, input) {
254687
254903
  const internal = INTERNALS.get(session);
254688
254904
  if (!internal)
@@ -255196,6 +255412,9 @@ function applyHistoryEntryThroughBackend(state, entry, direction) {
255196
255412
  if (!patchGroup)
255197
255413
  return { status: "rejected", rejectedReason: "patch-precondition-failed" };
255198
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
+ }
255199
255418
  const exactRender = prepareExactHistoryRenderInput(state, prepared, entry, direction);
255200
255419
  const result = getMutationExecutionBackend(state).apply(prepared);
255201
255420
  if (result.status !== "committed" || !result.applyResult) {
@@ -255417,6 +255636,7 @@ function prepareHistoryReplayMutation(state, entry, direction, patchGroup) {
255417
255636
  const controlOwner = storyPartOwnership[0];
255418
255637
  const controlBytes = controlOwner && state.packageBytes.get(controlOwner.partUri);
255419
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;
255420
255640
  const contentControlRewrite = patchGroup.source.kind === "storySurfaceRewrite" && patchGroup.source.contentControlRewrite && controlBytes && controlPatch ? prepareContentControlRewrite(controlBytes, controlPatch) : null;
255421
255641
  const declaredStoryTargetBlockIds = patchGroup.source.kind === "storySurfaceRewrite" || patchGroup.source.kind === "storyFormatMutation" ? [...new Set(patchGroup.source.targetBlockIds)] : [];
255422
255642
  const compareParagraphInsertions = entry.preparedReplayInputs?.compareParagraphInsertions ?? [];
@@ -255475,7 +255695,8 @@ function prepareHistoryReplayMutation(state, entry, direction, patchGroup) {
255475
255695
  backendExtensions: {
255476
255696
  ...patchGroup.storiesTouched.length > 0 ? {
255477
255697
  storySurface: {
255478
- 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 } : {},
255479
255700
  ...contentControlRewrite ? { contentControlRewrite } : {},
255480
255701
  ...patchGroup.source.kind === "storySurfaceRewrite" ? { headerFooterUpdate: prepareHeaderFooterUpdate(state, patchGroup.source, patchGroup.perPart, direction) ?? undefined } : {},
255481
255702
  storyLocal: !touchesPackageSidecar,
@@ -257453,11 +257674,12 @@ async function waitForQueuedPreScan(controller, cancel) {
257453
257674
  }
257454
257675
  return outcome.value;
257455
257676
  }
257456
- var SAVE_XML_DECODER, SAVE_XML_ENCODER, PACKAGE_BINDING_TEXT_ENCODER, WORD_XML_PART_RE, REVIEW_SOURCE_COPY_CHUNK_BYTES, INTERNALS, LIVE_MAIN_STORY_SCAN_MEMO, RELS_DECODER, DEFAULT_SAVE_COMPRESSION_LEVEL = 6, SAVE_ZIP_ENTRY_MTIME, EMPTY_PART_URI_SET, ALREADY_COMPRESSED_PART_RE, RAW_FONT_PART_RE, RSID_ATTR_FOR_FINGERPRINT_RE, SIMPLE_TRACKED_CHANGE_WRAPPER_OPEN_RE, WRAPPER_ID_ATTR_FOR_FINGERPRINT_RE, SDSourceBackedSaveUnsupportedError, REMOTE_PROJECTION_GENERATIONS, COLLABORATION_ATTACHMENTS, FIELD_STABLE_ID_ALLOCATORS;
257677
+ var SAVE_XML_DECODER, SAVE_XML_ENCODER, PACKAGE_BINDING_TEXT_ENCODER, WORD_XML_PART_RE, REVIEW_SOURCE_COPY_CHUNK_BYTES, INTERNALS, LIVE_MAIN_STORY_SCAN_MEMO, RELS_DECODER, DEFAULT_SAVE_COMPRESSION_LEVEL = 6, SAVE_ZIP_ENTRY_MTIME = "1980-01-01T00:00:00", EMPTY_PART_URI_SET, ALREADY_COMPRESSED_PART_RE, RAW_FONT_PART_RE, RSID_ATTR_FOR_FINGERPRINT_RE, SIMPLE_TRACKED_CHANGE_WRAPPER_OPEN_RE, WRAPPER_ID_ATTR_FOR_FINGERPRINT_RE, SDSourceBackedSaveUnsupportedError, REMOTE_PROJECTION_GENERATIONS, COLLABORATION_ATTACHMENTS, FIELD_STABLE_ID_ALLOCATORS;
257457
257678
  var init_sd_document_session = __esm(() => {
257458
257679
  init_textbox_atom_replacement();
257459
257680
  init_paragraph_signal_index();
257460
257681
  init_content_control_rewrite();
257682
+ init_whole_body_text_replacement();
257461
257683
  init_header_footer_update();
257462
257684
  init_session_hyperlink_metadata();
257463
257685
  init_history_text_replay();
@@ -257526,7 +257748,6 @@ var init_sd_document_session = __esm(() => {
257526
257748
  INTERNALS = new WeakMap;
257527
257749
  LIVE_MAIN_STORY_SCAN_MEMO = new WeakMap;
257528
257750
  RELS_DECODER = new TextDecoder("utf-8", { fatal: false });
257529
- SAVE_ZIP_ENTRY_MTIME = new Date(1980, 0, 1, 0, 0, 0);
257530
257751
  EMPTY_PART_URI_SET = new Set;
257531
257752
  ALREADY_COMPRESSED_PART_RE = /\.(png|jpe?g|gif|webp|bmp|ico|tiff?|emf|wmf|mp3|mp4|m4a|mov|avi|wmv|ogg|zip|gz|woff2?|eot)$/i;
257532
257753
  RAW_FONT_PART_RE = /\.(ttf|otf|odttf)$/i;
@@ -258758,6 +258979,63 @@ var init_textbox_registry_session = __esm(() => {
258758
258979
  init_sd_document_session();
258759
258980
  });
258760
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
+
258761
259039
  // ../../../v2/editor-core/dist/document/sd-document-session-internal.js
258762
259040
  var init_sd_document_session_internal = __esm(() => {
258763
259041
  init_core_properties();
@@ -258837,6 +259115,7 @@ var init_sd_document_session_internal = __esm(() => {
258837
259115
  init_bibliography_style();
258838
259116
  init_bibliography_review_resources();
258839
259117
  init_compile_compare_apply();
259118
+ init_selection_text_replacement_preflight();
258840
259119
  });
258841
259120
 
258842
259121
  // ../../../v2/document-api-v2-adapter/dist/address/story-identity.js
@@ -286308,8 +286587,13 @@ function toCssFontFamily(fontName, options = {}) {
286308
286587
  if (!fontName || typeof fontName !== "string")
286309
286588
  return fontName;
286310
286589
  let trimmed = fontName.trim();
286311
- if (!trimmed || trimmed.includes(","))
286590
+ if (!trimmed)
286312
286591
  return trimmed;
286592
+ const explicitParts = normalizeParts(trimmed);
286593
+ if (explicitParts.length > 1) {
286594
+ const serialized = explicitParts.map(serializeFamily);
286595
+ return serialized.every((part, i2) => part === explicitParts[i2]) ? trimmed : serialized.join(", ");
286596
+ }
286313
286597
  if (trimmed.toLowerCase() === INHERITED_FONT_FAMILY)
286314
286598
  return;
286315
286599
  if (trimmed.includes(";")) {
@@ -286320,15 +286604,16 @@ function toCssFontFamily(fontName, options = {}) {
286320
286604
  const fixedPitch = typeof pitch === "string" && pitch.trim().toLowerCase() === "fixed";
286321
286605
  const fallbackValue = fallback ?? (fixedPitch ? "monospace" : undefined) ?? (family !== "auto" && Object.hasOwn(FONT_FAMILY_FALLBACKS, family) ? mapWordFamilyFallback(family) : undefined) ?? inferGenericFallbackFromFontName(trimmed);
286322
286606
  const fallbackParts = normalizeParts(fallbackValue);
286607
+ const primaryParts = normalizeParts(trimmed);
286323
286608
  if (fallbackParts.length === 0) {
286324
- return trimmed;
286609
+ return primaryParts.map(serializeFamily).join(", ");
286325
286610
  }
286326
286611
  const normalizedName = trimmed.toLowerCase();
286327
286612
  const includesName = fallbackParts.some((part) => part.toLowerCase() === normalizedName);
286328
286613
  if (includesName) {
286329
- return fallbackParts.join(", ");
286614
+ return fallbackParts.map(serializeFamily).join(", ");
286330
286615
  }
286331
- return [trimmed, ...fallbackParts].join(", ");
286616
+ return [...primaryParts, ...fallbackParts].map(serializeFamily).join(", ");
286332
286617
  }
286333
286618
  var FONT_FAMILY_FALLBACKS, DEFAULT_GENERIC_FALLBACK = "sans-serif", INHERITED_FONT_FAMILY = "inherit", SERIF_LIKE_FONTS, normalizeFontNameForLookup = (fontName) => {
286334
286619
  if (!fontName || typeof fontName !== "string")
@@ -286339,7 +286624,7 @@ var FONT_FAMILY_FALLBACKS, DEFAULT_GENERIC_FALLBACK = "sans-serif", INHERITED_FO
286339
286624
  if (MONOSPACE_FONTS.has(name))
286340
286625
  return "monospace";
286341
286626
  return SERIF_LIKE_FONTS.has(name) ? "serif" : DEFAULT_GENERIC_FALLBACK;
286342
- }, normalizeParts = (value) => (value || "").split(",").map((part) => part.trim()).filter(Boolean), splitOutsideQuotes = (str, delimiter) => {
286627
+ }, normalizeParts = (value) => splitOutsideQuotes(value || "", ","), splitOutsideQuotes = (str, delimiter) => {
286343
286628
  if (!str.includes('"') && !str.includes("'")) {
286344
286629
  return str.split(delimiter).map((p) => p.trim()).filter(Boolean);
286345
286630
  }
@@ -286374,6 +286659,14 @@ var FONT_FAMILY_FALLBACKS, DEFAULT_GENERIC_FALLBACK = "sans-serif", INHERITED_FO
286374
286659
  if (current.trim())
286375
286660
  parts.push(current.trim());
286376
286661
  return parts;
286662
+ }, CSS_IDENTIFIER, serializeFamily = (family) => {
286663
+ const first = family[0];
286664
+ if ((first === '"' || first === "'") && family.endsWith(first))
286665
+ return family;
286666
+ if (family.split(/\s+/).every((part) => CSS_IDENTIFIER.test(part)))
286667
+ return family;
286668
+ const escaped = family.replace(/["\\\x00-\x1f\x7f]/g, (char) => char === '"' || char === "\\" ? `\\${char}` : `\\${char.codePointAt(0).toString(16)} `);
286669
+ return `"${escaped}"`;
286377
286670
  }, CSS_GENERIC_FAMILIES;
286378
286671
  var init_font_utils = __esm(() => {
286379
286672
  FONT_FAMILY_FALLBACKS = Object.freeze({
@@ -286414,6 +286707,7 @@ var init_font_utils = __esm(() => {
286414
286707
  "dejavu sans mono",
286415
286708
  "source code pro"
286416
286709
  ]);
286710
+ CSS_IDENTIFIER = /^(?:--|-?(?:[a-zA-Z_]|[^\x00-\x7f]))(?:[a-zA-Z0-9_-]|[^\x00-\x7f])*$/;
286417
286711
  CSS_GENERIC_FAMILIES = new Set([
286418
286712
  "serif",
286419
286713
  "sans-serif",
@@ -330948,9 +331242,60 @@ var init_tracked_body_replacement = __esm(() => {
330948
331242
  function rewriteWholeBodySelectionText(bytes, index2, text4) {
330949
331243
  const first = index2.entries[0];
330950
331244
  const last = index2.entries[index2.entries.length - 1];
330951
- 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)))) {
330952
331276
  return { ok: false, reason: "unsupported-context" };
330953
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];
330954
331299
  const firstXml = decoder6.decode(bytes.subarray(first.byteStart, first.byteEnd));
330955
331300
  const lastXml = decoder6.decode(bytes.subarray(last.byteStart, last.byteEnd));
330956
331301
  let splitExistingRevision = false;
@@ -330995,10 +331340,68 @@ function rewriteWholeBodySelectionText(bytes, index2, text4) {
330995
331340
  xml: decoder6.decode(bytes.subarray(0, first.byteStart)) + rewritten.xml + decoder6.decode(bytes.subarray(last.byteEnd))
330996
331341
  };
330997
331342
  }
330998
- 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";
330999
331401
  var init_whole_body_selection_text = __esm(() => {
331000
331402
  init_sd_document_session_internal();
331001
331403
  decoder6 = new TextDecoder;
331404
+ encoder2 = new TextEncoder;
331002
331405
  });
331003
331406
 
331004
331407
  // ../../../v2/document-api-v2-adapter/dist/selection-mutation/cross-cell-delete.js
@@ -331869,6 +332272,13 @@ class V2SelectionMutationAdapter {
331869
332272
  resolution: edits[0].resolution
331870
332273
  };
331871
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
+ }
331872
332282
  begun.tx.editTextRanges({
331873
332283
  changeMode: options?.changeMode ?? "direct",
331874
332284
  edits: kernelEdits
@@ -332051,30 +332461,21 @@ class V2SelectionMutationAdapter {
332051
332461
  if ("error" in wholeStory) {
332052
332462
  return failureWithoutResolution(wholeStory.error, wholeStory.message);
332053
332463
  }
332054
- if (request.text.length > 0 && wholeStory.crossParagraph) {
332464
+ if (request.text.length > 0) {
332055
332465
  if (!isDirectTextPayload(request.text)) {
332056
332466
  return failureWithoutResolution("INVALID_PAYLOAD", "replacement text contains unsupported control characters for direct text replace.");
332057
332467
  }
332058
- const plan = resolveCrossParagraphSelectionPlan({
332059
- target: wholeStory.normalizedTarget,
332060
- index: index2,
332061
- readPartBytes: (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri),
332062
- buildOffsetMap: buildOffsetMapForCoordinateSpace3,
332063
- ...offsetSpace ? { offsetSpace } : {}
332064
- });
332065
- if ("error" in plan)
332066
- return failureWithoutResolution(plan.error, plan.message);
332067
- const preflight = preflightSelectionRangeCollapse({ context: this.context, index: index2, changeMode: "tracked" }, plan);
332068
- if (preflight)
332069
- return failureWithoutResolution(preflight.failure.code, preflight.failure.message);
332070
- return this.executeWholeBodyTextReplace({
332071
- ...wholeStory.normalizedTarget,
332072
- start: { kind: "text", blockId: plan.startBlockId, offset: plan.startOffset },
332073
- end: { kind: "text", blockId: plan.endBlockId, offset: plan.endOffset }
332074
- }, storyLocator, request.text, options, plan);
332075
- }
332076
- if (request.text.length > 0) {
332077
- 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);
332078
332479
  }
332079
332480
  const effectiveStory2 = effectiveResolutionStory(story, storyLocator);
332080
332481
  const selectedText2 = wholeStory.crossParagraph ? readResolvedMultiParagraphText(index2, this.context.session, wholeStory.resolved) : readResolvedSelectionText(index2, this.context.session, wholeStory.resolved);
@@ -332107,6 +332508,17 @@ class V2SelectionMutationAdapter {
332107
332508
  });
332108
332509
  }
332109
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
+ }
332110
332522
  if (target.start.kind === "text" && target.end.kind === "text" && target.start.blockId !== target.end.blockId && (request.text === "" || (options?.changeMode ?? "direct") === "direct")) {
332111
332523
  const readPartBytes3 = (partUri) => getSDDocumentSessionInternalPartBytes(this.context.session, partUri);
332112
332524
  if (request.text === "" && (options?.changeMode ?? "direct") === "direct" && selectionCrossesTableCells(index2, readPartBytes3, target)) {
@@ -332394,6 +332806,90 @@ class V2SelectionMutationAdapter {
332394
332806
  buildInsertedTextEffectMs
332395
332807
  });
332396
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
+ }
332397
332893
  executeCrossParagraphReplace(input) {
332398
332894
  const { target, index: index2, story, storyLocator, text: text4, startedAt, storyResolveMs, offsetSpace, options, atomicFieldDelete } = input;
332399
332895
  if (target.coordinateSpace === "tracked") {
@@ -333428,10 +333924,10 @@ class V2SelectionMutationAdapter {
333428
333924
  return failureWithoutResolution(mapRejectionReason(rewritten.reason), rewritten.reason);
333429
333925
  nextXml = rewritten.xml;
333430
333926
  } else {
333431
- nextXml = rewriteBodyToSingleTextParagraph(sourceXml, first.blockId, replacementText);
333432
- }
333433
- if (nextXml == null) {
333434
- 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;
333435
333931
  }
333436
333932
  const changeMode = options?.changeMode ?? "direct";
333437
333933
  let replacementParagraphId = first.blockId;
@@ -333482,7 +333978,10 @@ class V2SelectionMutationAdapter {
333482
333978
  },
333483
333979
  storySurface: {
333484
333980
  family: "storyBlocks",
333485
- targetBlockIds: [first.blockId],
333981
+ targetBlockIds: [
333982
+ ...index2.entries.map((entry) => entry.blockId),
333983
+ ...createdRefs.flatMap((ref5) => ref5.kind === "block" ? [ref5.nodeId] : [])
333984
+ ],
333486
333985
  changeMode
333487
333986
  }
333488
333987
  });
@@ -333494,12 +333993,12 @@ class V2SelectionMutationAdapter {
333494
333993
  };
333495
333994
  }
333496
333995
  const storyRef = { kind: "story", storyType: "body" };
333497
- const effects2 = buildInsertedTextEffect({
333996
+ const effects2 = buildCreatedTextEffect({
333498
333997
  blockId: replacementParagraphId,
333499
- baseOffset: 0,
333998
+ start: 0,
333999
+ paintedStart: 0,
333500
334000
  text: replacementText,
333501
- story: storyRef,
333502
- changeMode
334001
+ story: storyRef
333503
334002
  });
333504
334003
  const inserted = projectTrackedStructuralEntityIds(this.context, createdRefs.flatMap((ref5) => ref5.kind === "trackedChange" ? [ref5.entityId] : [])).map((entityId) => ({ kind: "entity", entityType: "trackedChange", entityId }));
333505
334004
  return {
@@ -333691,8 +334190,20 @@ function buildInsertedTextEffect(input) {
333691
334190
  }
333692
334191
  start = proof.startOffset;
333693
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;
333694
334205
  const end = start + input.text.length;
333695
- const paintedStart = input.paintedBaseOffset ?? input.baseOffset;
334206
+ const paintedStart = input.paintedStart;
333696
334207
  const paintedEnd = paintedStart + input.text.length;
333697
334208
  const storyPart = input.story ? { story: input.story } : {};
333698
334209
  const target = {
@@ -366694,7 +367205,7 @@ function isStructurallyBlankStoryParagraph(input) {
366694
367205
  function positiveNoteCaptures(bytes, family) {
366695
367206
  const xml = new TextDecoder().decode(bytes);
366696
367207
  const bomLength = bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? 3 : 0;
366697
- const encoder2 = new TextEncoder;
367208
+ const encoder3 = new TextEncoder;
366698
367209
  const local = family === "footnotes" ? "footnote" : "endnote";
366699
367210
  const parsed = collectXmlElementRanges(xml);
366700
367211
  if (parsed.errors.length > 0)
@@ -366709,13 +367220,13 @@ function positiveNoteCaptures(bytes, family) {
366709
367220
  if (!id || !Number.isSafeInteger(Number(id)) || Number(id) <= 0)
366710
367221
  continue;
366711
367222
  const noteXml = xml.slice(range.start, range.end);
366712
- const byteStart = bomLength + encoder2.encode(xml.slice(0, range.start)).length;
367223
+ const byteStart = bomLength + encoder3.encode(xml.slice(0, range.start)).length;
366713
367224
  result.push({
366714
367225
  noteId: id,
366715
367226
  noteXml,
366716
367227
  rootOpenTag,
366717
367228
  byteStart,
366718
- byteEnd: byteStart + encoder2.encode(noteXml).length
367229
+ byteEnd: byteStart + encoder3.encode(noteXml).length
366719
367230
  });
366720
367231
  }
366721
367232
  return result;
@@ -400678,167 +401189,167 @@ class StringEncoder {
400678
401189
  this.lensE.write(string7.length);
400679
401190
  }
400680
401191
  toUint8Array() {
400681
- const encoder2 = new Encoder;
401192
+ const encoder3 = new Encoder;
400682
401193
  this.sarr.push(this.s);
400683
401194
  this.s = "";
400684
- writeVarString(encoder2, this.sarr.join(""));
400685
- writeUint8Array(encoder2, this.lensE.toUint8Array());
400686
- return toUint8Array(encoder2);
401195
+ writeVarString(encoder3, this.sarr.join(""));
401196
+ writeUint8Array(encoder3, this.lensE.toUint8Array());
401197
+ return toUint8Array(encoder3);
400687
401198
  }
400688
401199
  }
400689
- var createEncoder = () => new Encoder, length = (encoder2) => {
400690
- let len = encoder2.cpos;
400691
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
400692
- 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;
400693
401204
  }
400694
401205
  return len;
400695
- }, toUint8Array = (encoder2) => {
400696
- const uint8arr = new Uint8Array(length(encoder2));
401206
+ }, toUint8Array = (encoder3) => {
401207
+ const uint8arr = new Uint8Array(length(encoder3));
400697
401208
  let curPos = 0;
400698
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
400699
- const d = encoder2.bufs[i2];
401209
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
401210
+ const d = encoder3.bufs[i2];
400700
401211
  uint8arr.set(d, curPos);
400701
401212
  curPos += d.length;
400702
401213
  }
400703
- uint8arr.set(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos), curPos);
401214
+ uint8arr.set(new Uint8Array(encoder3.cbuf.buffer, 0, encoder3.cpos), curPos);
400704
401215
  return uint8arr;
400705
- }, verifyLen = (encoder2, len) => {
400706
- const bufferLen = encoder2.cbuf.length;
400707
- if (bufferLen - encoder2.cpos < len) {
400708
- encoder2.bufs.push(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos));
400709
- encoder2.cbuf = new Uint8Array(max2(bufferLen, len) * 2);
400710
- encoder2.cpos = 0;
400711
- }
400712
- }, write = (encoder2, num) => {
400713
- const bufferLen = encoder2.cbuf.length;
400714
- if (encoder2.cpos === bufferLen) {
400715
- encoder2.bufs.push(encoder2.cbuf);
400716
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
400717
- encoder2.cpos = 0;
400718
- }
400719
- encoder2.cbuf[encoder2.cpos++] = num;
400720
- }, 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) => {
400721
401232
  while (num > BITS7) {
400722
- write(encoder2, BIT8 | BITS7 & num);
401233
+ write(encoder3, BIT8 | BITS7 & num);
400723
401234
  num = floor(num / 128);
400724
401235
  }
400725
- write(encoder2, BITS7 & num);
400726
- }, writeVarInt = (encoder2, num) => {
401236
+ write(encoder3, BITS7 & num);
401237
+ }, writeVarInt = (encoder3, num) => {
400727
401238
  const isNegative = isNegativeZero(num);
400728
401239
  if (isNegative) {
400729
401240
  num = -num;
400730
401241
  }
400731
- write(encoder2, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
401242
+ write(encoder3, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
400732
401243
  num = floor(num / 64);
400733
401244
  while (num > 0) {
400734
- write(encoder2, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
401245
+ write(encoder3, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
400735
401246
  num = floor(num / 128);
400736
401247
  }
400737
- }, _strBuffer, _maxStrBSize, _writeVarStringNative = (encoder2, str) => {
401248
+ }, _strBuffer, _maxStrBSize, _writeVarStringNative = (encoder3, str) => {
400738
401249
  if (str.length < _maxStrBSize) {
400739
401250
  const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
400740
- writeVarUint(encoder2, written);
401251
+ writeVarUint(encoder3, written);
400741
401252
  for (let i2 = 0;i2 < written; i2++) {
400742
- write(encoder2, _strBuffer[i2]);
401253
+ write(encoder3, _strBuffer[i2]);
400743
401254
  }
400744
401255
  } else {
400745
- writeVarUint8Array(encoder2, encodeUtf8(str));
401256
+ writeVarUint8Array(encoder3, encodeUtf8(str));
400746
401257
  }
400747
- }, _writeVarStringPolyfill = (encoder2, str) => {
401258
+ }, _writeVarStringPolyfill = (encoder3, str) => {
400748
401259
  const encodedString = unescape(encodeURIComponent(str));
400749
401260
  const len = encodedString.length;
400750
- writeVarUint(encoder2, len);
401261
+ writeVarUint(encoder3, len);
400751
401262
  for (let i2 = 0;i2 < len; i2++) {
400752
- write(encoder2, encodedString.codePointAt(i2));
401263
+ write(encoder3, encodedString.codePointAt(i2));
400753
401264
  }
400754
- }, writeVarString, writeUint8Array = (encoder2, uint8Array) => {
400755
- const bufferLen = encoder2.cbuf.length;
400756
- const cpos = encoder2.cpos;
401265
+ }, writeVarString, writeUint8Array = (encoder3, uint8Array) => {
401266
+ const bufferLen = encoder3.cbuf.length;
401267
+ const cpos = encoder3.cpos;
400757
401268
  const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
400758
401269
  const rightCopyLen = uint8Array.length - leftCopyLen;
400759
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
400760
- encoder2.cpos += leftCopyLen;
401270
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
401271
+ encoder3.cpos += leftCopyLen;
400761
401272
  if (rightCopyLen > 0) {
400762
- encoder2.bufs.push(encoder2.cbuf);
400763
- encoder2.cbuf = new Uint8Array(max2(bufferLen * 2, rightCopyLen));
400764
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
400765
- encoder2.cpos = rightCopyLen;
400766
- }
400767
- }, writeVarUint8Array = (encoder2, uint8Array) => {
400768
- writeVarUint(encoder2, uint8Array.byteLength);
400769
- writeUint8Array(encoder2, uint8Array);
400770
- }, writeOnDataView = (encoder2, len) => {
400771
- verifyLen(encoder2, len);
400772
- const dview = new DataView(encoder2.cbuf.buffer, encoder2.cpos, len);
400773
- 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;
400774
401285
  return dview;
400775
- }, 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) => {
400776
401287
  floatTestBed.setFloat32(0, num);
400777
401288
  return floatTestBed.getFloat32(0) === num;
400778
- }, writeAny = (encoder2, data) => {
401289
+ }, writeAny = (encoder3, data) => {
400779
401290
  switch (typeof data) {
400780
401291
  case "string":
400781
- write(encoder2, 119);
400782
- writeVarString(encoder2, data);
401292
+ write(encoder3, 119);
401293
+ writeVarString(encoder3, data);
400783
401294
  break;
400784
401295
  case "number":
400785
401296
  if (isInteger2(data) && abs(data) <= BITS31) {
400786
- write(encoder2, 125);
400787
- writeVarInt(encoder2, data);
401297
+ write(encoder3, 125);
401298
+ writeVarInt(encoder3, data);
400788
401299
  } else if (isFloat32(data)) {
400789
- write(encoder2, 124);
400790
- writeFloat32(encoder2, data);
401300
+ write(encoder3, 124);
401301
+ writeFloat32(encoder3, data);
400791
401302
  } else {
400792
- write(encoder2, 123);
400793
- writeFloat64(encoder2, data);
401303
+ write(encoder3, 123);
401304
+ writeFloat64(encoder3, data);
400794
401305
  }
400795
401306
  break;
400796
401307
  case "bigint":
400797
- write(encoder2, 122);
400798
- writeBigInt64(encoder2, data);
401308
+ write(encoder3, 122);
401309
+ writeBigInt64(encoder3, data);
400799
401310
  break;
400800
401311
  case "object":
400801
401312
  if (data === null) {
400802
- write(encoder2, 126);
401313
+ write(encoder3, 126);
400803
401314
  } else if (isArray(data)) {
400804
- write(encoder2, 117);
400805
- writeVarUint(encoder2, data.length);
401315
+ write(encoder3, 117);
401316
+ writeVarUint(encoder3, data.length);
400806
401317
  for (let i2 = 0;i2 < data.length; i2++) {
400807
- writeAny(encoder2, data[i2]);
401318
+ writeAny(encoder3, data[i2]);
400808
401319
  }
400809
401320
  } else if (data instanceof Uint8Array) {
400810
- write(encoder2, 116);
400811
- writeVarUint8Array(encoder2, data);
401321
+ write(encoder3, 116);
401322
+ writeVarUint8Array(encoder3, data);
400812
401323
  } else {
400813
- write(encoder2, 118);
401324
+ write(encoder3, 118);
400814
401325
  const keys = Object.keys(data);
400815
- writeVarUint(encoder2, keys.length);
401326
+ writeVarUint(encoder3, keys.length);
400816
401327
  for (let i2 = 0;i2 < keys.length; i2++) {
400817
401328
  const key2 = keys[i2];
400818
- writeVarString(encoder2, key2);
400819
- writeAny(encoder2, data[key2]);
401329
+ writeVarString(encoder3, key2);
401330
+ writeAny(encoder3, data[key2]);
400820
401331
  }
400821
401332
  }
400822
401333
  break;
400823
401334
  case "boolean":
400824
- write(encoder2, data ? 120 : 121);
401335
+ write(encoder3, data ? 120 : 121);
400825
401336
  break;
400826
401337
  default:
400827
- write(encoder2, 127);
401338
+ write(encoder3, 127);
400828
401339
  }
400829
- }, RleEncoder, flushUintOptRleEncoder = (encoder2) => {
400830
- if (encoder2.count > 0) {
400831
- writeVarInt(encoder2.encoder, encoder2.count === 1 ? encoder2.s : -encoder2.s);
400832
- if (encoder2.count > 1) {
400833
- 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);
400834
401345
  }
400835
401346
  }
400836
- }, flushIntDiffOptRleEncoder = (encoder2) => {
400837
- if (encoder2.count > 0) {
400838
- const encodedDiff = encoder2.diff * 2 + (encoder2.count === 1 ? 0 : 1);
400839
- writeVarInt(encoder2.encoder, encodedDiff);
400840
- if (encoder2.count > 1) {
400841
- 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);
400842
401353
  }
400843
401354
  }
400844
401355
  };
@@ -401617,11 +402128,11 @@ class PermanentUserData {
401617
402128
  user.get("ids").push([clientid2]);
401618
402129
  }
401619
402130
  });
401620
- const encoder2 = new DSEncoderV1;
402131
+ const encoder3 = new DSEncoderV1;
401621
402132
  const ds = this.dss.get(userDescription);
401622
402133
  if (ds) {
401623
- writeDeleteSet(encoder2, ds);
401624
- user.get("ds").push([encoder2.toUint8Array()]);
402134
+ writeDeleteSet(encoder3, ds);
402135
+ user.get("ds").push([encoder3.toUint8Array()]);
401625
402136
  }
401626
402137
  }
401627
402138
  }, 0);
@@ -401631,9 +402142,9 @@ class PermanentUserData {
401631
402142
  const yds = user.get("ds");
401632
402143
  const ds = transaction.deleteSet;
401633
402144
  if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {
401634
- const encoder2 = new DSEncoderV1;
401635
- writeDeleteSet(encoder2, ds);
401636
- yds.push([encoder2.toUint8Array()]);
402145
+ const encoder3 = new DSEncoderV1;
402146
+ writeDeleteSet(encoder3, ds);
402147
+ yds.push([encoder3.toUint8Array()]);
401637
402148
  }
401638
402149
  });
401639
402150
  });
@@ -401752,11 +402263,11 @@ class LazyStructReader {
401752
402263
  }
401753
402264
 
401754
402265
  class LazyStructWriter {
401755
- constructor(encoder2) {
402266
+ constructor(encoder3) {
401756
402267
  this.currClient = 0;
401757
402268
  this.startClock = 0;
401758
402269
  this.written = 0;
401759
- this.encoder = encoder2;
402270
+ this.encoder = encoder3;
401760
402271
  this.clientStructs = [];
401761
402272
  }
401762
402273
  }
@@ -401993,7 +402504,7 @@ class AbstractStruct {
401993
402504
  mergeWith(right) {
401994
402505
  return false;
401995
402506
  }
401996
- write(encoder2, offset, encodingRef) {
402507
+ write(encoder3, offset, encodingRef) {
401997
402508
  throw methodUnimplemented();
401998
402509
  }
401999
402510
  integrate(transaction, offset) {
@@ -402026,8 +402537,8 @@ class ContentBinary {
402026
402537
  integrate(transaction, item) {}
402027
402538
  delete(transaction) {}
402028
402539
  gc(store) {}
402029
- write(encoder2, offset) {
402030
- encoder2.writeBuf(this.content);
402540
+ write(encoder3, offset) {
402541
+ encoder3.writeBuf(this.content);
402031
402542
  }
402032
402543
  getRef() {
402033
402544
  return 3;
@@ -402065,8 +402576,8 @@ class ContentDeleted {
402065
402576
  }
402066
402577
  delete(transaction) {}
402067
402578
  gc(store) {}
402068
- write(encoder2, offset) {
402069
- encoder2.writeLen(this.len - offset);
402579
+ write(encoder3, offset) {
402580
+ encoder3.writeLen(this.len - offset);
402070
402581
  }
402071
402582
  getRef() {
402072
402583
  return 1;
@@ -402124,9 +402635,9 @@ class ContentDoc {
402124
402635
  }
402125
402636
  }
402126
402637
  gc(store) {}
402127
- write(encoder2, offset) {
402128
- encoder2.writeString(this.doc.guid);
402129
- encoder2.writeAny(this.opts);
402638
+ write(encoder3, offset) {
402639
+ encoder3.writeString(this.doc.guid);
402640
+ encoder3.writeAny(this.opts);
402130
402641
  }
402131
402642
  getRef() {
402132
402643
  return 9;
@@ -402158,8 +402669,8 @@ class ContentEmbed {
402158
402669
  integrate(transaction, item) {}
402159
402670
  delete(transaction) {}
402160
402671
  gc(store) {}
402161
- write(encoder2, offset) {
402162
- encoder2.writeJSON(this.embed);
402672
+ write(encoder3, offset) {
402673
+ encoder3.writeJSON(this.embed);
402163
402674
  }
402164
402675
  getRef() {
402165
402676
  return 5;
@@ -402196,9 +402707,9 @@ class ContentFormat {
402196
402707
  }
402197
402708
  delete(transaction) {}
402198
402709
  gc(store) {}
402199
- write(encoder2, offset) {
402200
- encoder2.writeKey(this.key);
402201
- encoder2.writeJSON(this.value);
402710
+ write(encoder3, offset) {
402711
+ encoder3.writeKey(this.key);
402712
+ encoder3.writeJSON(this.value);
402202
402713
  }
402203
402714
  getRef() {
402204
402715
  return 6;
@@ -402233,12 +402744,12 @@ class ContentJSON {
402233
402744
  integrate(transaction, item) {}
402234
402745
  delete(transaction) {}
402235
402746
  gc(store) {}
402236
- write(encoder2, offset) {
402747
+ write(encoder3, offset) {
402237
402748
  const len = this.arr.length;
402238
- encoder2.writeLen(len - offset);
402749
+ encoder3.writeLen(len - offset);
402239
402750
  for (let i2 = offset;i2 < len; i2++) {
402240
402751
  const c = this.arr[i2];
402241
- encoder2.writeString(c === undefined ? "undefined" : JSON.stringify(c));
402752
+ encoder3.writeString(c === undefined ? "undefined" : JSON.stringify(c));
402242
402753
  }
402243
402754
  }
402244
402755
  getRef() {
@@ -402275,12 +402786,12 @@ class ContentAny {
402275
402786
  integrate(transaction, item) {}
402276
402787
  delete(transaction) {}
402277
402788
  gc(store) {}
402278
- write(encoder2, offset) {
402789
+ write(encoder3, offset) {
402279
402790
  const len = this.arr.length;
402280
- encoder2.writeLen(len - offset);
402791
+ encoder3.writeLen(len - offset);
402281
402792
  for (let i2 = offset;i2 < len; i2++) {
402282
402793
  const c = this.arr[i2];
402283
- encoder2.writeAny(c);
402794
+ encoder3.writeAny(c);
402284
402795
  }
402285
402796
  }
402286
402797
  getRef() {
@@ -402321,8 +402832,8 @@ class ContentString {
402321
402832
  integrate(transaction, item) {}
402322
402833
  delete(transaction) {}
402323
402834
  gc(store) {}
402324
- write(encoder2, offset) {
402325
- 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));
402326
402837
  }
402327
402838
  getRef() {
402328
402839
  return 4;
@@ -402388,8 +402899,8 @@ class ContentType {
402388
402899
  });
402389
402900
  this.type._map = new Map;
402390
402901
  }
402391
- write(encoder2, offset) {
402392
- this.type._write(encoder2);
402902
+ write(encoder3, offset) {
402903
+ this.type._write(encoder3);
402393
402904
  }
402394
402905
  getRef() {
402395
402906
  return 7;
@@ -402481,17 +402992,17 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402481
402992
  }
402482
402993
  });
402483
402994
  return ds;
402484
- }, writeDeleteSet = (encoder2, ds) => {
402485
- writeVarUint(encoder2.restEncoder, ds.clients.size);
402995
+ }, writeDeleteSet = (encoder3, ds) => {
402996
+ writeVarUint(encoder3.restEncoder, ds.clients.size);
402486
402997
  from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => {
402487
- encoder2.resetDsCurVal();
402488
- writeVarUint(encoder2.restEncoder, client);
402998
+ encoder3.resetDsCurVal();
402999
+ writeVarUint(encoder3.restEncoder, client);
402489
403000
  const len = dsitems.length;
402490
- writeVarUint(encoder2.restEncoder, len);
403001
+ writeVarUint(encoder3.restEncoder, len);
402491
403002
  for (let i2 = 0;i2 < len; i2++) {
402492
403003
  const item = dsitems[i2];
402493
- encoder2.writeDsClock(item.clock);
402494
- encoder2.writeDsLen(item.len);
403004
+ encoder3.writeDsClock(item.clock);
403005
+ encoder3.writeDsLen(item.len);
402495
403006
  }
402496
403007
  });
402497
403008
  }, readDeleteSet = (decoder9) => {
@@ -402556,18 +403067,18 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402556
403067
  return ds.toUint8Array();
402557
403068
  }
402558
403069
  return null;
402559
- }, generateNewClientId, Doc2, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, writeStructs = (encoder2, structs, client, clock) => {
403070
+ }, generateNewClientId, Doc2, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, writeStructs = (encoder3, structs, client, clock) => {
402560
403071
  clock = max2(clock, structs[0].id.clock);
402561
403072
  const startNewStructs = findIndexSS(structs, clock);
402562
- writeVarUint(encoder2.restEncoder, structs.length - startNewStructs);
402563
- encoder2.writeClient(client);
402564
- writeVarUint(encoder2.restEncoder, clock);
403073
+ writeVarUint(encoder3.restEncoder, structs.length - startNewStructs);
403074
+ encoder3.writeClient(client);
403075
+ writeVarUint(encoder3.restEncoder, clock);
402565
403076
  const firstStruct = structs[startNewStructs];
402566
- firstStruct.write(encoder2, clock - firstStruct.id.clock);
403077
+ firstStruct.write(encoder3, clock - firstStruct.id.clock);
402567
403078
  for (let i2 = startNewStructs + 1;i2 < structs.length; i2++) {
402568
- structs[i2].write(encoder2, 0);
403079
+ structs[i2].write(encoder3, 0);
402569
403080
  }
402570
- }, writeClientsStructs = (encoder2, store, _sm) => {
403081
+ }, writeClientsStructs = (encoder3, store, _sm) => {
402571
403082
  const sm = new Map;
402572
403083
  _sm.forEach((clock, client) => {
402573
403084
  if (getState(store, client) > clock) {
@@ -402579,9 +403090,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402579
403090
  sm.set(client, 0);
402580
403091
  }
402581
403092
  });
402582
- writeVarUint(encoder2.restEncoder, sm.size);
403093
+ writeVarUint(encoder3.restEncoder, sm.size);
402583
403094
  from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
402584
- writeStructs(encoder2, store.clients.get(client), client, clock);
403095
+ writeStructs(encoder3, store.clients.get(client), client, clock);
402585
403096
  });
402586
403097
  }, readClientsStructRefs = (decoder9, doc2) => {
402587
403098
  const clientRefs = create();
@@ -402709,13 +403220,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402709
403220
  }
402710
403221
  }
402711
403222
  if (restStructs.clients.size > 0) {
402712
- const encoder2 = new UpdateEncoderV2;
402713
- writeClientsStructs(encoder2, restStructs, new Map);
402714
- writeVarUint(encoder2.restEncoder, 0);
402715
- 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() };
402716
403227
  }
402717
403228
  return null;
402718
- }, 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) => {
402719
403230
  transaction.local = false;
402720
403231
  let retry = false;
402721
403232
  const doc2 = transaction.doc;
@@ -402763,13 +403274,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402763
403274
  }, transactionOrigin, false), applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
402764
403275
  const decoder9 = createDecoder(update);
402765
403276
  readUpdateV2(decoder9, ydoc, transactionOrigin, new YDecoder(decoder9));
402766
- }, applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1), writeStateAsUpdate = (encoder2, doc2, targetStateVector = new Map) => {
402767
- writeClientsStructs(encoder2, doc2.store, targetStateVector);
402768
- writeDeleteSet(encoder2, createDeleteSetFromStructStore(doc2.store));
402769
- }, 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) => {
402770
403281
  const targetStateVector = decodeStateVector(encodedTargetStateVector);
402771
- writeStateAsUpdate(encoder2, doc2, targetStateVector);
402772
- const updates = [encoder2.toUint8Array()];
403282
+ writeStateAsUpdate(encoder3, doc2, targetStateVector);
403283
+ const updates = [encoder3.toUint8Array()];
402773
403284
  if (doc2.store.pendingDs) {
402774
403285
  updates.push(doc2.store.pendingDs);
402775
403286
  }
@@ -402777,9 +403288,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402777
403288
  updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector));
402778
403289
  }
402779
403290
  if (updates.length > 1) {
402780
- if (encoder2.constructor === UpdateEncoderV1) {
403291
+ if (encoder3.constructor === UpdateEncoderV1) {
402781
403292
  return mergeUpdates(updates.map((update, i2) => i2 === 0 ? update : convertUpdateFormatV2ToV1(update)));
402782
- } else if (encoder2.constructor === UpdateEncoderV2) {
403293
+ } else if (encoder3.constructor === UpdateEncoderV2) {
402783
403294
  return mergeUpdatesV2(updates);
402784
403295
  }
402785
403296
  }
@@ -402793,20 +403304,20 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402793
403304
  ss.set(client, clock);
402794
403305
  }
402795
403306
  return ss;
402796
- }, decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))), writeStateVector = (encoder2, sv) => {
402797
- writeVarUint(encoder2.restEncoder, sv.size);
403307
+ }, decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))), writeStateVector = (encoder3, sv) => {
403308
+ writeVarUint(encoder3.restEncoder, sv.size);
402798
403309
  from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
402799
- writeVarUint(encoder2.restEncoder, client);
402800
- writeVarUint(encoder2.restEncoder, clock);
403310
+ writeVarUint(encoder3.restEncoder, client);
403311
+ writeVarUint(encoder3.restEncoder, clock);
402801
403312
  });
402802
- return encoder2;
402803
- }, 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) => {
402804
403315
  if (doc2 instanceof Map) {
402805
- writeStateVector(encoder2, doc2);
403316
+ writeStateVector(encoder3, doc2);
402806
403317
  } else {
402807
- writeDocumentStateVector(encoder2, doc2);
403318
+ writeDocumentStateVector(encoder3, doc2);
402808
403319
  }
402809
- return encoder2.toUint8Array();
403320
+ return encoder3.toUint8Array();
402810
403321
  }, encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1), createEventHandler = () => new EventHandler, addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f), removeEventHandlerListener = (eventHandler, f) => {
402811
403322
  const l = eventHandler.l;
402812
403323
  const len = l.length;
@@ -402814,9 +403325,9 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402814
403325
  if (len === eventHandler.l.length) {
402815
403326
  console.error("[yjs] Tried to remove event handler that doesn't exist.");
402816
403327
  }
402817
- }, 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) => {
402818
- writeVarUint(encoder2, id2.client);
402819
- 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);
402820
403331
  }, readID = (decoder9) => createID(readVarUint(decoder9), readVarUint(decoder9)), findRootTypeKey = (type) => {
402821
403332
  for (const [key2, value2] of type.doc.share.entries()) {
402822
403333
  if (value2 === type) {
@@ -402862,26 +403373,26 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402862
403373
  t = t.right;
402863
403374
  }
402864
403375
  return createRelativePosition(type, null, assoc);
402865
- }, writeRelativePosition = (encoder2, rpos) => {
403376
+ }, writeRelativePosition = (encoder3, rpos) => {
402866
403377
  const { type, tname, item, assoc } = rpos;
402867
403378
  if (item !== null) {
402868
- writeVarUint(encoder2, 0);
402869
- writeID(encoder2, item);
403379
+ writeVarUint(encoder3, 0);
403380
+ writeID(encoder3, item);
402870
403381
  } else if (tname !== null) {
402871
- writeUint8(encoder2, 1);
402872
- writeVarString(encoder2, tname);
403382
+ writeUint8(encoder3, 1);
403383
+ writeVarString(encoder3, tname);
402873
403384
  } else if (type !== null) {
402874
- writeUint8(encoder2, 2);
402875
- writeID(encoder2, type);
403385
+ writeUint8(encoder3, 2);
403386
+ writeID(encoder3, type);
402876
403387
  } else {
402877
403388
  throw unexpectedCase();
402878
403389
  }
402879
- writeVarInt(encoder2, assoc);
402880
- return encoder2;
403390
+ writeVarInt(encoder3, assoc);
403391
+ return encoder3;
402881
403392
  }, encodeRelativePosition = (rpos) => {
402882
- const encoder2 = createEncoder();
402883
- writeRelativePosition(encoder2, rpos);
402884
- return toUint8Array(encoder2);
403393
+ const encoder3 = createEncoder();
403394
+ writeRelativePosition(encoder3, rpos);
403395
+ return toUint8Array(encoder3);
402885
403396
  }, readRelativePosition = (decoder9) => {
402886
403397
  let type = null;
402887
403398
  let tname = null;
@@ -402957,10 +403468,10 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
402957
403468
  }
402958
403469
  }
402959
403470
  return createAbsolutePosition(type, index2, rpos.assoc);
402960
- }, encodeSnapshotV2 = (snapshot2, encoder2 = new DSEncoderV2) => {
402961
- writeDeleteSet(encoder2, snapshot2.ds);
402962
- writeStateVector(encoder2, snapshot2.sv);
402963
- return encoder2.toUint8Array();
403471
+ }, encodeSnapshotV2 = (snapshot2, encoder3 = new DSEncoderV2) => {
403472
+ writeDeleteSet(encoder3, snapshot2.ds);
403473
+ writeStateVector(encoder3, snapshot2.sv);
403474
+ return encoder3.toUint8Array();
402964
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) => {
402965
403476
  const meta3 = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
402966
403477
  const store = transaction.doc.store;
@@ -403061,13 +403572,13 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403061
403572
  }
403062
403573
  f(struct);
403063
403574
  } while (index2 < structs.length && structs[index2].id.clock < clockEnd);
403064
- }, writeUpdateMessageFromTransaction = (encoder2, transaction) => {
403575
+ }, writeUpdateMessageFromTransaction = (encoder3, transaction) => {
403065
403576
  if (transaction.deleteSet.clients.size === 0 && !any3(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
403066
403577
  return false;
403067
403578
  }
403068
403579
  sortAndMergeDeleteSet(transaction.deleteSet);
403069
- writeStructsFromTransaction(encoder2, transaction);
403070
- writeDeleteSet(encoder2, transaction.deleteSet);
403580
+ writeStructsFromTransaction(encoder3, transaction);
403581
+ writeDeleteSet(encoder3, transaction.deleteSet);
403071
403582
  return true;
403072
403583
  }, addChangedTypeToTransaction = (transaction, type, parentSub) => {
403073
403584
  const item = type._item;
@@ -403195,17 +403706,17 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403195
403706
  }
403196
403707
  doc2.emit("afterTransactionCleanup", [transaction, doc2]);
403197
403708
  if (doc2._observers.has("update")) {
403198
- const encoder2 = new UpdateEncoderV1;
403199
- const hasContent2 = writeUpdateMessageFromTransaction(encoder2, transaction);
403709
+ const encoder3 = new UpdateEncoderV1;
403710
+ const hasContent2 = writeUpdateMessageFromTransaction(encoder3, transaction);
403200
403711
  if (hasContent2) {
403201
- doc2.emit("update", [encoder2.toUint8Array(), transaction.origin, doc2, transaction]);
403712
+ doc2.emit("update", [encoder3.toUint8Array(), transaction.origin, doc2, transaction]);
403202
403713
  }
403203
403714
  }
403204
403715
  if (doc2._observers.has("updateV2")) {
403205
- const encoder2 = new UpdateEncoderV2;
403206
- const hasContent2 = writeUpdateMessageFromTransaction(encoder2, transaction);
403716
+ const encoder3 = new UpdateEncoderV2;
403717
+ const hasContent2 = writeUpdateMessageFromTransaction(encoder3, transaction);
403207
403718
  if (hasContent2) {
403208
- doc2.emit("updateV2", [encoder2.toUint8Array(), transaction.origin, doc2, transaction]);
403719
+ doc2.emit("updateV2", [encoder3.toUint8Array(), transaction.origin, doc2, transaction]);
403209
403720
  }
403210
403721
  }
403211
403722
  const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
@@ -403416,8 +403927,8 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403416
403927
  return updateEncoder.toUint8Array();
403417
403928
  }, diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
403418
403929
  const state = decodeStateVector(sv);
403419
- const encoder2 = new YEncoder;
403420
- const lazyStructWriter = new LazyStructWriter(encoder2);
403930
+ const encoder3 = new YEncoder;
403931
+ const lazyStructWriter = new LazyStructWriter(encoder3);
403421
403932
  const decoder9 = new YDecoder(createDecoder(update));
403422
403933
  const reader = new LazyStructReader(decoder9, false);
403423
403934
  while (reader.curr) {
@@ -403443,8 +403954,8 @@ var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes,
403443
403954
  }
403444
403955
  finishLazyStructWriting(lazyStructWriter);
403445
403956
  const ds = readDeleteSet(decoder9);
403446
- writeDeleteSet(encoder2, ds);
403447
- return encoder2.toUint8Array();
403957
+ writeDeleteSet(encoder3, ds);
403958
+ return encoder3.toUint8Array();
403448
403959
  }, flushLazyStructWriter = (lazyWriter) => {
403449
403960
  if (lazyWriter.written > 0) {
403450
403961
  lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
@@ -404640,19 +405151,19 @@ var init_yjs = __esm(() => {
404640
405151
  this.lenEncoder = new UintOptRleEncoder;
404641
405152
  }
404642
405153
  toUint8Array() {
404643
- const encoder2 = createEncoder();
404644
- writeVarUint(encoder2, 0);
404645
- writeVarUint8Array(encoder2, this.keyClockEncoder.toUint8Array());
404646
- writeVarUint8Array(encoder2, this.clientEncoder.toUint8Array());
404647
- writeVarUint8Array(encoder2, this.leftClockEncoder.toUint8Array());
404648
- writeVarUint8Array(encoder2, this.rightClockEncoder.toUint8Array());
404649
- writeVarUint8Array(encoder2, toUint8Array(this.infoEncoder));
404650
- writeVarUint8Array(encoder2, this.stringEncoder.toUint8Array());
404651
- writeVarUint8Array(encoder2, toUint8Array(this.parentInfoEncoder));
404652
- writeVarUint8Array(encoder2, this.typeRefEncoder.toUint8Array());
404653
- writeVarUint8Array(encoder2, this.lenEncoder.toUint8Array());
404654
- writeUint8Array(encoder2, toUint8Array(this.restEncoder));
404655
- 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);
404656
405167
  }
404657
405168
  writeLeftID(id2) {
404658
405169
  this.clientEncoder.write(id2.client);
@@ -404929,8 +405440,8 @@ var init_yjs = __esm(() => {
404929
405440
  [Symbol.iterator]() {
404930
405441
  return typeListCreateIterator(this);
404931
405442
  }
404932
- _write(encoder2) {
404933
- encoder2.writeTypeRef(YArrayRefID);
405443
+ _write(encoder3) {
405444
+ encoder3.writeTypeRef(YArrayRefID);
404934
405445
  }
404935
405446
  };
404936
405447
  YMapEvent = class YMapEvent extends YEvent {
@@ -405039,8 +405550,8 @@ var init_yjs = __esm(() => {
405039
405550
  this._prelimContent.clear();
405040
405551
  }
405041
405552
  }
405042
- _write(encoder2) {
405043
- encoder2.writeTypeRef(YMapRefID);
405553
+ _write(encoder3) {
405554
+ encoder3.writeTypeRef(YMapRefID);
405044
405555
  }
405045
405556
  };
405046
405557
  YTextEvent = class YTextEvent extends YEvent {
@@ -405487,8 +405998,8 @@ var init_yjs = __esm(() => {
405487
405998
  getAttributes() {
405488
405999
  return typeMapGetAll(this);
405489
406000
  }
405490
- _write(encoder2) {
405491
- encoder2.writeTypeRef(YTextRefID);
406001
+ _write(encoder3) {
406002
+ encoder3.writeTypeRef(YTextRefID);
405492
406003
  }
405493
406004
  };
405494
406005
  YXmlTreeWalker = class YXmlTreeWalker {
@@ -405646,8 +406157,8 @@ var init_yjs = __esm(() => {
405646
406157
  forEach(f) {
405647
406158
  typeListForEach(this, f);
405648
406159
  }
405649
- _write(encoder2) {
405650
- encoder2.writeTypeRef(YXmlFragmentRefID);
406160
+ _write(encoder3) {
406161
+ encoder3.writeTypeRef(YXmlFragmentRefID);
405651
406162
  }
405652
406163
  };
405653
406164
  YXmlElement = class YXmlElement extends YXmlFragment {
@@ -405744,9 +406255,9 @@ var init_yjs = __esm(() => {
405744
406255
  }
405745
406256
  return dom;
405746
406257
  }
405747
- _write(encoder2) {
405748
- encoder2.writeTypeRef(YXmlElementRefID);
405749
- encoder2.writeKey(this.nodeName);
406258
+ _write(encoder3) {
406259
+ encoder3.writeTypeRef(YXmlElementRefID);
406260
+ encoder3.writeKey(this.nodeName);
405750
406261
  }
405751
406262
  };
405752
406263
  YXmlEvent = class YXmlEvent extends YEvent {
@@ -405792,9 +406303,9 @@ var init_yjs = __esm(() => {
405792
406303
  }
405793
406304
  return dom;
405794
406305
  }
405795
- _write(encoder2) {
405796
- encoder2.writeTypeRef(YXmlHookRefID);
405797
- encoder2.writeKey(this.hookName);
406306
+ _write(encoder3) {
406307
+ encoder3.writeTypeRef(YXmlHookRefID);
406308
+ encoder3.writeKey(this.hookName);
405798
406309
  }
405799
406310
  };
405800
406311
  YXmlText = class YXmlText extends YText {
@@ -405853,8 +406364,8 @@ var init_yjs = __esm(() => {
405853
406364
  toJSON() {
405854
406365
  return this.toString();
405855
406366
  }
405856
- _write(encoder2) {
405857
- encoder2.writeTypeRef(YXmlTextRefID);
406367
+ _write(encoder3) {
406368
+ encoder3.writeTypeRef(YXmlTextRefID);
405858
406369
  }
405859
406370
  };
405860
406371
  GC = class GC extends AbstractStruct {
@@ -405876,9 +406387,9 @@ var init_yjs = __esm(() => {
405876
406387
  }
405877
406388
  addStruct(transaction.doc.store, this);
405878
406389
  }
405879
- write(encoder2, offset) {
405880
- encoder2.writeInfo(structGCRefNumber);
405881
- encoder2.writeLen(this.length - offset);
406390
+ write(encoder3, offset) {
406391
+ encoder3.writeInfo(structGCRefNumber);
406392
+ encoder3.writeLen(this.length - offset);
405882
406393
  }
405883
406394
  getMissing(transaction, store) {
405884
406395
  return null;
@@ -406124,17 +406635,17 @@ var init_yjs = __esm(() => {
406124
406635
  this.content = new ContentDeleted(this.length);
406125
406636
  }
406126
406637
  }
406127
- write(encoder2, offset) {
406638
+ write(encoder3, offset) {
406128
406639
  const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
406129
406640
  const rightOrigin = this.rightOrigin;
406130
406641
  const parentSub = this.parentSub;
406131
406642
  const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | (rightOrigin === null ? 0 : BIT7) | (parentSub === null ? 0 : BIT6);
406132
- encoder2.writeInfo(info);
406643
+ encoder3.writeInfo(info);
406133
406644
  if (origin !== null) {
406134
- encoder2.writeLeftID(origin);
406645
+ encoder3.writeLeftID(origin);
406135
406646
  }
406136
406647
  if (rightOrigin !== null) {
406137
- encoder2.writeRightID(rightOrigin);
406648
+ encoder3.writeRightID(rightOrigin);
406138
406649
  }
406139
406650
  if (origin === null && rightOrigin === null) {
406140
406651
  const parent = this.parent;
@@ -406142,26 +406653,26 @@ var init_yjs = __esm(() => {
406142
406653
  const parentItem = parent._item;
406143
406654
  if (parentItem === null) {
406144
406655
  const ykey = findRootTypeKey(parent);
406145
- encoder2.writeParentInfo(true);
406146
- encoder2.writeString(ykey);
406656
+ encoder3.writeParentInfo(true);
406657
+ encoder3.writeString(ykey);
406147
406658
  } else {
406148
- encoder2.writeParentInfo(false);
406149
- encoder2.writeLeftID(parentItem.id);
406659
+ encoder3.writeParentInfo(false);
406660
+ encoder3.writeLeftID(parentItem.id);
406150
406661
  }
406151
406662
  } else if (parent.constructor === String) {
406152
- encoder2.writeParentInfo(true);
406153
- encoder2.writeString(parent);
406663
+ encoder3.writeParentInfo(true);
406664
+ encoder3.writeString(parent);
406154
406665
  } else if (parent.constructor === ID) {
406155
- encoder2.writeParentInfo(false);
406156
- encoder2.writeLeftID(parent);
406666
+ encoder3.writeParentInfo(false);
406667
+ encoder3.writeLeftID(parent);
406157
406668
  } else {
406158
406669
  unexpectedCase();
406159
406670
  }
406160
406671
  if (parentSub !== null) {
406161
- encoder2.writeString(parentSub);
406672
+ encoder3.writeString(parentSub);
406162
406673
  }
406163
406674
  }
406164
- this.content.write(encoder2, offset);
406675
+ this.content.write(encoder3, offset);
406165
406676
  }
406166
406677
  };
406167
406678
  contentRefs = [
@@ -406196,9 +406707,9 @@ var init_yjs = __esm(() => {
406196
406707
  integrate(transaction, offset) {
406197
406708
  unexpectedCase();
406198
406709
  }
406199
- write(encoder2, offset) {
406200
- encoder2.writeInfo(structSkipRefNumber);
406201
- writeVarUint(encoder2.restEncoder, this.length - offset);
406710
+ write(encoder3, offset) {
406711
+ encoder3.writeInfo(structSkipRefNumber);
406712
+ writeVarUint(encoder3.restEncoder, this.length - offset);
406202
406713
  }
406203
406714
  getMissing(transaction, store) {
406204
406715
  return null;
@@ -406258,14 +406769,14 @@ var init_broadcastchannel = __esm(() => {
406258
406769
  });
406259
406770
 
406260
406771
  // ../../../v2/node_modules/.pnpm/y-protocols@1.0.7_yjs@13.6.31/node_modules/y-protocols/sync.js
406261
- var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writeSyncStep1 = (encoder2, doc2) => {
406262
- writeVarUint(encoder2, messageYjsSyncStep1);
406772
+ var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writeSyncStep1 = (encoder3, doc2) => {
406773
+ writeVarUint(encoder3, messageYjsSyncStep1);
406263
406774
  const sv = encodeStateVector(doc2);
406264
- writeVarUint8Array(encoder2, sv);
406265
- }, writeSyncStep2 = (encoder2, doc2, encodedStateVector) => {
406266
- writeVarUint(encoder2, messageYjsSyncStep2);
406267
- writeVarUint8Array(encoder2, encodeStateAsUpdate(doc2, encodedStateVector));
406268
- }, 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) => {
406269
406780
  try {
406270
406781
  applyUpdate(doc2, readVarUint8Array(decoder9), transactionOrigin);
406271
406782
  } catch (error48) {
@@ -406273,14 +406784,14 @@ var messageYjsSyncStep1 = 0, messageYjsSyncStep2 = 1, messageYjsUpdate = 2, writ
406273
406784
  errorHandler(error48);
406274
406785
  console.error("Caught error while handling a Yjs update", error48);
406275
406786
  }
406276
- }, writeUpdate = (encoder2, update) => {
406277
- writeVarUint(encoder2, messageYjsUpdate);
406278
- writeVarUint8Array(encoder2, update);
406279
- }, 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) => {
406280
406791
  const messageType = readVarUint(decoder9);
406281
406792
  switch (messageType) {
406282
406793
  case messageYjsSyncStep1:
406283
- readSyncStep1(decoder9, encoder2, doc2);
406794
+ readSyncStep1(decoder9, encoder3, doc2);
406284
406795
  break;
406285
406796
  case messageYjsSyncStep2:
406286
406797
  readSyncStep2(decoder9, doc2, transactionOrigin, errorHandler);
@@ -406334,17 +406845,17 @@ var outdatedTimeout = 30000, Awareness, removeAwarenessStates = (awareness, clie
406334
406845
  }
406335
406846
  }, encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
406336
406847
  const len = clients.length;
406337
- const encoder2 = createEncoder();
406338
- writeVarUint(encoder2, len);
406848
+ const encoder3 = createEncoder();
406849
+ writeVarUint(encoder3, len);
406339
406850
  for (let i2 = 0;i2 < len; i2++) {
406340
406851
  const clientID = clients[i2];
406341
406852
  const state = states.get(clientID) || null;
406342
406853
  const clock = awareness.meta.get(clientID).clock;
406343
- writeVarUint(encoder2, clientID);
406344
- writeVarUint(encoder2, clock);
406345
- writeVarString(encoder2, JSON.stringify(state));
406854
+ writeVarUint(encoder3, clientID);
406855
+ writeVarUint(encoder3, clock);
406856
+ writeVarString(encoder3, JSON.stringify(state));
406346
406857
  }
406347
- return toUint8Array(encoder2);
406858
+ return toUint8Array(encoder3);
406348
406859
  }, applyAwarenessUpdate = (awareness, update, origin) => {
406349
406860
  const decoder9 = createDecoder(update);
406350
406861
  const timestamp = getUnixTime();
@@ -406504,15 +407015,15 @@ var init_url = __esm(() => {
406504
407015
  var messageSync = 0, messageQueryAwareness = 3, messageAwareness = 1, messageAuth = 2, messageHandlers, messageReconnectTimeout = 30000, permissionDeniedHandler = (provider, reason) => console.warn(`Permission denied to access ${provider.url}.
406505
407016
  ${reason}`), readMessage = (provider, buf, emitSynced) => {
406506
407017
  const decoder9 = createDecoder(buf);
406507
- const encoder2 = createEncoder();
407018
+ const encoder3 = createEncoder();
406508
407019
  const messageType = readVarUint(decoder9);
406509
407020
  const messageHandler = provider.messageHandlers[messageType];
406510
407021
  if (messageHandler) {
406511
- messageHandler(encoder2, decoder9, provider, emitSynced, messageType);
407022
+ messageHandler(encoder3, decoder9, provider, emitSynced, messageType);
406512
407023
  } else {
406513
407024
  console.error("Unable to compute message");
406514
407025
  }
406515
- return encoder2;
407026
+ return encoder3;
406516
407027
  }, closeWebsocketConnection = (provider, ws, event) => {
406517
407028
  if (ws === provider.ws) {
406518
407029
  provider.emit("connection-close", [event, provider]);
@@ -406541,9 +407052,9 @@ ${reason}`), readMessage = (provider, buf, emitSynced) => {
406541
407052
  provider.synced = false;
406542
407053
  websocket.onmessage = (event) => {
406543
407054
  provider.wsLastMessageReceived = getUnixTime();
406544
- const encoder2 = readMessage(provider, new Uint8Array(event.data), true);
406545
- if (length(encoder2) > 1) {
406546
- websocket.send(toUint8Array(encoder2));
407055
+ const encoder3 = readMessage(provider, new Uint8Array(event.data), true);
407056
+ if (length(encoder3) > 1) {
407057
+ websocket.send(toUint8Array(encoder3));
406547
407058
  }
406548
407059
  };
406549
407060
  websocket.onerror = (event) => {
@@ -406560,10 +407071,10 @@ ${reason}`), readMessage = (provider, buf, emitSynced) => {
406560
407071
  provider.emit("status", [{
406561
407072
  status: "connected"
406562
407073
  }]);
406563
- const encoder2 = createEncoder();
406564
- writeVarUint(encoder2, messageSync);
406565
- writeSyncStep1(encoder2, provider.doc);
406566
- websocket.send(toUint8Array(encoder2));
407074
+ const encoder3 = createEncoder();
407075
+ writeVarUint(encoder3, messageSync);
407076
+ writeSyncStep1(encoder3, provider.doc);
407077
+ websocket.send(toUint8Array(encoder3));
406567
407078
  if (provider.awareness.getLocalState() !== null) {
406568
407079
  const encoderAwarenessState = createEncoder();
406569
407080
  writeVarUint(encoderAwarenessState, messageAwareness);
@@ -406599,16 +407110,16 @@ var init_y_websocket = __esm(() => {
406599
407110
  init_url();
406600
407111
  init_environment();
406601
407112
  messageHandlers = [];
406602
- messageHandlers[messageSync] = (encoder2, decoder9, provider, emitSynced, _messageType) => {
406603
- writeVarUint(encoder2, messageSync);
406604
- 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);
406605
407116
  if (emitSynced && syncMessageType === messageYjsSyncStep2 && !provider.synced) {
406606
407117
  provider.synced = true;
406607
407118
  }
406608
407119
  };
406609
- messageHandlers[messageQueryAwareness] = (encoder2, _decoder, provider, _emitSynced, _messageType) => {
406610
- writeVarUint(encoder2, messageAwareness);
406611
- 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())));
406612
407123
  };
406613
407124
  messageHandlers[messageAwareness] = (_encoder, decoder9, provider, _emitSynced, _messageType) => {
406614
407125
  applyAwarenessUpdate(provider.awareness, readVarUint8Array(decoder9), provider);
@@ -406654,36 +407165,36 @@ var init_y_websocket = __esm(() => {
406654
407165
  if (resyncInterval > 0) {
406655
407166
  this._resyncInterval = setInterval(() => {
406656
407167
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
406657
- const encoder2 = createEncoder();
406658
- writeVarUint(encoder2, messageSync);
406659
- writeSyncStep1(encoder2, doc2);
406660
- this.ws.send(toUint8Array(encoder2));
407168
+ const encoder3 = createEncoder();
407169
+ writeVarUint(encoder3, messageSync);
407170
+ writeSyncStep1(encoder3, doc2);
407171
+ this.ws.send(toUint8Array(encoder3));
406661
407172
  }
406662
407173
  }, resyncInterval);
406663
407174
  }
406664
407175
  this._bcSubscriber = (data, origin) => {
406665
407176
  if (origin !== this) {
406666
- const encoder2 = readMessage(this, new Uint8Array(data), false);
406667
- if (length(encoder2) > 1) {
406668
- 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);
406669
407180
  }
406670
407181
  }
406671
407182
  };
406672
407183
  this._updateHandler = (update, origin) => {
406673
407184
  if (origin !== this) {
406674
- const encoder2 = createEncoder();
406675
- writeVarUint(encoder2, messageSync);
406676
- writeUpdate(encoder2, update);
406677
- broadcastMessage(this, toUint8Array(encoder2));
407185
+ const encoder3 = createEncoder();
407186
+ writeVarUint(encoder3, messageSync);
407187
+ writeUpdate(encoder3, update);
407188
+ broadcastMessage(this, toUint8Array(encoder3));
406678
407189
  }
406679
407190
  };
406680
407191
  this.doc.on("update", this._updateHandler);
406681
407192
  this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {
406682
407193
  const changedClients = added.concat(updated).concat(removed);
406683
- const encoder2 = createEncoder();
406684
- writeVarUint(encoder2, messageAwareness);
406685
- writeVarUint8Array(encoder2, encodeAwarenessUpdate(awareness, changedClients));
406686
- broadcastMessage(this, toUint8Array(encoder2));
407194
+ const encoder3 = createEncoder();
407195
+ writeVarUint(encoder3, messageAwareness);
407196
+ writeVarUint8Array(encoder3, encodeAwarenessUpdate(awareness, changedClients));
407197
+ broadcastMessage(this, toUint8Array(encoder3));
406687
407198
  };
406688
407199
  this._exitHandler = () => {
406689
407200
  removeAwarenessStates(this.awareness, [doc2.clientID], "app closed");
@@ -406755,12 +407266,12 @@ var init_y_websocket = __esm(() => {
406755
407266
  publish(this.bcChannel, toUint8Array(encoderAwarenessState), this);
406756
407267
  }
406757
407268
  disconnectBc() {
406758
- const encoder2 = createEncoder();
406759
- writeVarUint(encoder2, messageAwareness);
406760
- writeVarUint8Array(encoder2, encodeAwarenessUpdate(this.awareness, [
407269
+ const encoder3 = createEncoder();
407270
+ writeVarUint(encoder3, messageAwareness);
407271
+ writeVarUint8Array(encoder3, encodeAwarenessUpdate(this.awareness, [
406761
407272
  this.doc.clientID
406762
407273
  ], new Map));
406763
- broadcastMessage(this, toUint8Array(encoder2));
407274
+ broadcastMessage(this, toUint8Array(encoder3));
406764
407275
  if (this.bcconnected) {
406765
407276
  unsubscribe(this.bcChannel, this._bcSubscriber);
406766
407277
  this.bcconnected = false;
@@ -407302,53 +407813,53 @@ var floor2, min2 = (a, b) => a < b ? a : b, max3 = (a, b) => a > b ? a : b, BIT8
407302
407813
  buf[i2] = encodedString.codePointAt(i2);
407303
407814
  }
407304
407815
  return buf;
407305
- }, utf8TextEncoder2, _encodeUtf8Native2 = (str) => utf8TextEncoder2.encode(str), encodeUtf82, utf8TextDecoder2, write2 = (encoder2, num) => {
407306
- const bufferLen = encoder2.cbuf.length;
407307
- if (encoder2.cpos === bufferLen) {
407308
- encoder2.bufs.push(encoder2.cbuf);
407309
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
407310
- encoder2.cpos = 0;
407311
- }
407312
- encoder2.cbuf[encoder2.cpos++] = num;
407313
- }, 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) => {
407314
407825
  while (num > BITS72) {
407315
- write2(encoder2, BIT82 | BITS72 & num);
407826
+ write2(encoder3, BIT82 | BITS72 & num);
407316
407827
  num = floor2(num / 128);
407317
407828
  }
407318
- write2(encoder2, BITS72 & num);
407319
- }, _strBuffer2, _maxStrBSize2, _writeVarStringNative2 = (encoder2, str) => {
407829
+ write2(encoder3, BITS72 & num);
407830
+ }, _strBuffer2, _maxStrBSize2, _writeVarStringNative2 = (encoder3, str) => {
407320
407831
  if (str.length < _maxStrBSize2) {
407321
407832
  const written = utf8TextEncoder2.encodeInto(str, _strBuffer2).written || 0;
407322
- writeVarUint2(encoder2, written);
407833
+ writeVarUint2(encoder3, written);
407323
407834
  for (let i2 = 0;i2 < written; i2++) {
407324
- write2(encoder2, _strBuffer2[i2]);
407835
+ write2(encoder3, _strBuffer2[i2]);
407325
407836
  }
407326
407837
  } else {
407327
- writeVarUint8Array2(encoder2, encodeUtf82(str));
407838
+ writeVarUint8Array2(encoder3, encodeUtf82(str));
407328
407839
  }
407329
- }, _writeVarStringPolyfill2 = (encoder2, str) => {
407840
+ }, _writeVarStringPolyfill2 = (encoder3, str) => {
407330
407841
  const encodedString = unescape(encodeURIComponent(str));
407331
407842
  const len = encodedString.length;
407332
- writeVarUint2(encoder2, len);
407843
+ writeVarUint2(encoder3, len);
407333
407844
  for (let i2 = 0;i2 < len; i2++) {
407334
- write2(encoder2, encodedString.codePointAt(i2));
407845
+ write2(encoder3, encodedString.codePointAt(i2));
407335
407846
  }
407336
- }, writeVarString2, writeUint8Array2 = (encoder2, uint8Array) => {
407337
- const bufferLen = encoder2.cbuf.length;
407338
- const cpos = encoder2.cpos;
407847
+ }, writeVarString2, writeUint8Array2 = (encoder3, uint8Array) => {
407848
+ const bufferLen = encoder3.cbuf.length;
407849
+ const cpos = encoder3.cpos;
407339
407850
  const leftCopyLen = min2(bufferLen - cpos, uint8Array.length);
407340
407851
  const rightCopyLen = uint8Array.length - leftCopyLen;
407341
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
407342
- encoder2.cpos += leftCopyLen;
407852
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
407853
+ encoder3.cpos += leftCopyLen;
407343
407854
  if (rightCopyLen > 0) {
407344
- encoder2.bufs.push(encoder2.cbuf);
407345
- encoder2.cbuf = new Uint8Array(max3(bufferLen * 2, rightCopyLen));
407346
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
407347
- encoder2.cpos = rightCopyLen;
407348
- }
407349
- }, writeVarUint8Array2 = (encoder2, uint8Array) => {
407350
- writeVarUint2(encoder2, uint8Array.byteLength);
407351
- 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);
407352
407863
  }, create6 = (s) => new Error(s), errorUnexpectedEndOfArray2, errorIntegerOutOfRange2, readUint8Array2 = (decoder9, len) => {
407353
407864
  const view = new Uint8Array(decoder9.arr.buffer, decoder9.pos + decoder9.arr.byteOffset, len);
407354
407865
  decoder9.pos += len;
@@ -407390,9 +407901,9 @@ var floor2, min2 = (a, b) => a < b ? a : b, max3 = (a, b) => a > b ? a : b, BIT8
407390
407901
  }
407391
407902
  return decodeURIComponent(escape(encodedString));
407392
407903
  }
407393
- }, _readVarStringNative2 = (decoder9) => utf8TextDecoder2.decode(readVarUint8Array2(decoder9)), readVarString2, AuthMessageType, writeAuthentication = (encoder2, auth) => {
407394
- writeVarUint2(encoder2, AuthMessageType.Token);
407395
- writeVarString2(encoder2, auth);
407904
+ }, _readVarStringNative2 = (decoder9) => utf8TextDecoder2.decode(readVarUint8Array2(decoder9)), readVarString2, AuthMessageType, writeAuthentication = (encoder3, auth) => {
407905
+ writeVarUint2(encoder3, AuthMessageType.Token);
407906
+ writeVarString2(encoder3, auth);
407396
407907
  }, readAuthMessage2 = (decoder9, permissionDeniedHandler2, authenticatedHandler) => {
407397
407908
  switch (readVarUint2(decoder9)) {
407398
407909
  case AuthMessageType.PermissionDenied: {
@@ -407967,69 +408478,69 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
407967
408478
  }
407968
408479
  }
407969
408480
  return params2;
407970
- }, 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) => {
407971
- let len = encoder2.cpos;
407972
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
407973
- 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;
407974
408485
  }
407975
408486
  return len;
407976
- }, toUint8Array2 = (encoder2) => {
407977
- const uint8arr = new Uint8Array(length2(encoder2));
408487
+ }, toUint8Array2 = (encoder3) => {
408488
+ const uint8arr = new Uint8Array(length2(encoder3));
407978
408489
  let curPos = 0;
407979
- for (let i2 = 0;i2 < encoder2.bufs.length; i2++) {
407980
- const d = encoder2.bufs[i2];
408490
+ for (let i2 = 0;i2 < encoder3.bufs.length; i2++) {
408491
+ const d = encoder3.bufs[i2];
407981
408492
  uint8arr.set(d, curPos);
407982
408493
  curPos += d.length;
407983
408494
  }
407984
- uint8arr.set(new Uint8Array(encoder2.cbuf.buffer, 0, encoder2.cpos), curPos);
408495
+ uint8arr.set(new Uint8Array(encoder3.cbuf.buffer, 0, encoder3.cpos), curPos);
407985
408496
  return uint8arr;
407986
- }, write3 = (encoder2, num) => {
407987
- const bufferLen = encoder2.cbuf.length;
407988
- if (encoder2.cpos === bufferLen) {
407989
- encoder2.bufs.push(encoder2.cbuf);
407990
- encoder2.cbuf = new Uint8Array(bufferLen * 2);
407991
- encoder2.cpos = 0;
407992
- }
407993
- encoder2.cbuf[encoder2.cpos++] = num;
407994
- }, 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) => {
407995
408506
  while (num > BITS73) {
407996
- write3(encoder2, BIT83 | BITS73 & num);
408507
+ write3(encoder3, BIT83 | BITS73 & num);
407997
408508
  num = floor3(num / 128);
407998
408509
  }
407999
- write3(encoder2, BITS73 & num);
408000
- }, _strBuffer3, _maxStrBSize3, _writeVarStringNative3 = (encoder2, str) => {
408510
+ write3(encoder3, BITS73 & num);
408511
+ }, _strBuffer3, _maxStrBSize3, _writeVarStringNative3 = (encoder3, str) => {
408001
408512
  if (str.length < _maxStrBSize3) {
408002
408513
  const written = utf8TextEncoder3.encodeInto(str, _strBuffer3).written || 0;
408003
- writeVarUint3(encoder2, written);
408514
+ writeVarUint3(encoder3, written);
408004
408515
  for (let i2 = 0;i2 < written; i2++) {
408005
- write3(encoder2, _strBuffer3[i2]);
408516
+ write3(encoder3, _strBuffer3[i2]);
408006
408517
  }
408007
408518
  } else {
408008
- writeVarUint8Array3(encoder2, encodeUtf83(str));
408519
+ writeVarUint8Array3(encoder3, encodeUtf83(str));
408009
408520
  }
408010
- }, _writeVarStringPolyfill3 = (encoder2, str) => {
408521
+ }, _writeVarStringPolyfill3 = (encoder3, str) => {
408011
408522
  const encodedString = unescape(encodeURIComponent(str));
408012
408523
  const len = encodedString.length;
408013
- writeVarUint3(encoder2, len);
408524
+ writeVarUint3(encoder3, len);
408014
408525
  for (let i2 = 0;i2 < len; i2++) {
408015
- write3(encoder2, encodedString.codePointAt(i2));
408526
+ write3(encoder3, encodedString.codePointAt(i2));
408016
408527
  }
408017
- }, writeVarString3, writeUint8Array3 = (encoder2, uint8Array) => {
408018
- const bufferLen = encoder2.cbuf.length;
408019
- const cpos = encoder2.cpos;
408528
+ }, writeVarString3, writeUint8Array3 = (encoder3, uint8Array) => {
408529
+ const bufferLen = encoder3.cbuf.length;
408530
+ const cpos = encoder3.cpos;
408020
408531
  const leftCopyLen = min3(bufferLen - cpos, uint8Array.length);
408021
408532
  const rightCopyLen = uint8Array.length - leftCopyLen;
408022
- encoder2.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
408023
- encoder2.cpos += leftCopyLen;
408533
+ encoder3.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
408534
+ encoder3.cpos += leftCopyLen;
408024
408535
  if (rightCopyLen > 0) {
408025
- encoder2.bufs.push(encoder2.cbuf);
408026
- encoder2.cbuf = new Uint8Array(max4(bufferLen * 2, rightCopyLen));
408027
- encoder2.cbuf.set(uint8Array.subarray(leftCopyLen));
408028
- encoder2.cpos = rightCopyLen;
408029
- }
408030
- }, writeVarUint8Array3 = (encoder2, uint8Array) => {
408031
- writeVarUint3(encoder2, uint8Array.byteLength);
408032
- 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);
408033
408544
  }, create7 = (s) => new Error(s), errorUnexpectedEndOfArray3, errorIntegerOutOfRange3, createDecoder2 = (uint8Array) => new Decoder2(uint8Array), readUint8Array3 = (decoder9, len) => {
408034
408545
  const view = new Uint8Array(decoder9.arr.buffer, decoder9.pos + decoder9.arr.byteOffset, len);
408035
408546
  decoder9.pos += len;
@@ -408172,17 +408683,17 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
408172
408683
  }
408173
408684
  }, encodeAwarenessUpdate2 = (awareness, clients, states = awareness.states) => {
408174
408685
  const len = clients.length;
408175
- const encoder2 = createEncoder2();
408176
- writeVarUint3(encoder2, len);
408686
+ const encoder3 = createEncoder2();
408687
+ writeVarUint3(encoder3, len);
408177
408688
  for (let i2 = 0;i2 < len; i2++) {
408178
408689
  const clientID = clients[i2];
408179
408690
  const state = states.get(clientID) || null;
408180
408691
  const clock = awareness.meta.get(clientID).clock;
408181
- writeVarUint3(encoder2, clientID);
408182
- writeVarUint3(encoder2, clock);
408183
- writeVarString3(encoder2, JSON.stringify(state));
408692
+ writeVarUint3(encoder3, clientID);
408693
+ writeVarUint3(encoder3, clock);
408694
+ writeVarString3(encoder3, JSON.stringify(state));
408184
408695
  }
408185
- return toUint8Array2(encoder2);
408696
+ return toUint8Array2(encoder3);
408186
408697
  }, applyAwarenessUpdate2 = (awareness, update, origin) => {
408187
408698
  const decoder9 = createDecoder2(update);
408188
408699
  const timestamp = getUnixTime2();
@@ -408238,27 +408749,27 @@ var import_attempt, create$2 = () => new Map, setIfUndefined2 = (map4, key2, cre
408238
408749
  removed
408239
408750
  }, origin]);
408240
408751
  }
408241
- }, encodeQueryParams2 = (params3) => map4(params3, (val, key2) => `${encodeURIComponent(key2)}=${encodeURIComponent(val)}`).join("&"), MessageType, WebSocketStatus, HocuspocusProviderWebsocket, messageYjsSyncStep12 = 0, messageYjsSyncStep22 = 1, messageYjsUpdate2 = 2, writeSyncStep12 = (encoder2, doc2) => {
408242
- 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);
408243
408754
  const sv = encodeStateVector(doc2);
408244
- writeVarUint8Array3(encoder2, sv);
408245
- }, writeSyncStep22 = (encoder2, doc2, encodedStateVector) => {
408246
- writeVarUint3(encoder2, messageYjsSyncStep22);
408247
- writeVarUint8Array3(encoder2, encodeStateAsUpdate(doc2, encodedStateVector));
408248
- }, 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) => {
408249
408760
  try {
408250
408761
  applyUpdate(doc2, readVarUint8Array3(decoder9), transactionOrigin);
408251
408762
  } catch (error48) {
408252
408763
  console.error("Caught error while handling a Yjs update", error48);
408253
408764
  }
408254
- }, writeUpdate2 = (encoder2, update) => {
408255
- writeVarUint3(encoder2, messageYjsUpdate2);
408256
- writeVarUint8Array3(encoder2, update);
408257
- }, 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) => {
408258
408769
  const messageType = readVarUint3(decoder9);
408259
408770
  switch (messageType) {
408260
408771
  case messageYjsSyncStep12:
408261
- readSyncStep12(decoder9, encoder2, doc2);
408772
+ readSyncStep12(decoder9, encoder3, doc2);
408262
408773
  break;
408263
408774
  case messageYjsSyncStep22:
408264
408775
  readSyncStep22(decoder9, doc2, transactionOrigin);
@@ -409271,7 +409782,7 @@ function createHocuspocusSingleDocAdapter(config2) {
409271
409782
  hooks: {
409272
409783
  attach({ ydoc, providerRoomName, onSynced, onDegraded, onReconnecting, onFailed, onStateless }) {
409273
409784
  let hasSynced = false;
409274
- const provider = new HocuspocusProvider({
409785
+ const provider = new V2HocuspocusProvider({
409275
409786
  url: config2.url,
409276
409787
  name: providerRoomName,
409277
409788
  document: ydoc,
@@ -409280,11 +409791,17 @@ function createHocuspocusSingleDocAdapter(config2) {
409280
409791
  preserveConnection: false,
409281
409792
  broadcast: config2.broadcast ?? true,
409282
409793
  quiet: true,
409283
- onSynced() {
409794
+ onSynced({ state }) {
409795
+ if (!state) {
409796
+ if (hasSynced)
409797
+ onDegraded();
409798
+ return;
409799
+ }
409284
409800
  hasSynced = true;
409285
409801
  onSynced();
409286
409802
  },
409287
409803
  onAuthenticationFailed() {
409804
+ provider.disconnect();
409288
409805
  onFailed({
409289
409806
  providerFamily: "hocuspocus",
409290
409807
  reason: "authentication_failed"
@@ -409301,6 +409818,7 @@ function createHocuspocusSingleDocAdapter(config2) {
409301
409818
  onClose(data) {
409302
409819
  const code2 = data.event?.code;
409303
409820
  if (code2 === 4401 || code2 === 4403) {
409821
+ provider.disconnect();
409304
409822
  onFailed({ providerFamily: "hocuspocus", code: code2 });
409305
409823
  return;
409306
409824
  }
@@ -409340,11 +409858,37 @@ function createHocuspocusSingleDocAdapter(config2) {
409340
409858
  }
409341
409859
  });
409342
409860
  }
409861
+ var V2HocuspocusProvider;
409343
409862
  var init_hocuspocus_single_doc = __esm(() => {
409344
409863
  init_hocuspocus_provider_esm();
409864
+ init_decoding();
409345
409865
  init_capability_matrix();
409346
409866
  init_diagnostics2();
409347
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
+ };
409348
409892
  });
409349
409893
 
409350
409894
  // ../../../v2/node_modules/.pnpm/@liveblocks+core@3.15.5_@types+json-schema@7.0.15/node_modules/@liveblocks/core/dist/index.js
@@ -418652,8 +419196,8 @@ function clean(...arrays) {
418652
419196
  function createView(arr) {
418653
419197
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
418654
419198
  }
418655
- function rotr(word3, shift) {
418656
- return word3 << 32 - shift | word3 >>> shift;
419199
+ function rotr(word4, shift) {
419200
+ return word4 << 32 - shift | word4 >>> shift;
418657
419201
  }
418658
419202
  function utf8ToBytes(str) {
418659
419203
  if (typeof str !== "string")
@@ -422475,8 +423019,8 @@ function parseParagraphXml(xml, inheritedNamespaceBindings = {}, trackedWrapperI
422475
423019
  if (trackedWrapperIdentityState) {
422476
423020
  advanceTrackedWrapperIdentityState(pPrSpan.xml, paragraphNamespaceBindings, trackedWrapperIdentityState);
422477
423021
  }
422478
- const directChildren3 = readDirectPPrChildren(pPrSpan.xml);
422479
- for (const [prop, child] of directChildren3) {
423022
+ const directChildren4 = readDirectPPrChildren(pPrSpan.xml);
423023
+ for (const [prop, child] of directChildren4) {
422480
423024
  if (prop === "pStyle" || prop === "numPr")
422481
423025
  continue;
422482
423026
  pPr[prop] = child;
@@ -429482,7 +430026,7 @@ function canonicalize2(value2) {
429482
430026
  }
429483
430027
  function reservationDigest(bundle) {
429484
430028
  const canonical = canonicalJson2(bundle);
429485
- return sha256Hex2(encoder2.encode(canonical));
430029
+ return sha256Hex2(encoder3.encode(canonical));
429486
430030
  }
429487
430031
  function shardReservationDigest(bundle, shardId) {
429488
430032
  const slice = {};
@@ -429511,10 +430055,10 @@ function shardReservationDigest(bundle, shardId) {
429511
430055
  }
429512
430056
  return reservationDigest({ shardId, slice });
429513
430057
  }
429514
- var encoder2;
430058
+ var encoder3;
429515
430059
  var init_digest2 = __esm(() => {
429516
430060
  init_hash();
429517
- encoder2 = new TextEncoder;
430061
+ encoder3 = new TextEncoder;
429518
430062
  });
429519
430063
 
429520
430064
  // ../../../v2/collaboration-v2/dist/journal/schema.js
@@ -433297,10 +433841,10 @@ function paragraphEmissionNames(context, preservedXml) {
433297
433841
  bindings[prefix] = namespace;
433298
433842
  return prefix;
433299
433843
  };
433300
- const word3 = choose("w", WORD_NAMESPACE7);
433844
+ const word4 = choose("w", WORD_NAMESPACE7);
433301
433845
  const word2010 = choose("w14", WORD_2010_NAMESPACE3);
433302
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("");
433303
- return { word: word3, word2010, declarations };
433847
+ return { word: word4, word2010, declarations };
433304
433848
  }
433305
433849
  var WORD_NAMESPACE7 = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", WORD_2010_NAMESPACE3 = "http://schemas.microsoft.com/office/word/2010/wordml", CANONICAL_NAMESPACES;
433306
433850
  var init_xml_emission_context = __esm(() => {
@@ -433444,7 +433988,7 @@ function materializeProjection(input) {
433444
433988
  const tableReplacements = readTableStructuralReplacements(readTarget);
433445
433989
  const previousBlockIndex = previous3 ? blockDigestIndex(previous3.blockDigests) : null;
433446
433990
  const insertedBlockHint = previousBlockIndex && [...dirtyStoryBlocks.get(handle.shardId) ?? []].some((blockId) => !previousBlockIndex.has(blockId));
433447
- 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;
433448
433992
  const overlaidTableIds = structuralSnapshot ? new Set(tableReplacements.map((table) => table.tableNodeId)) : null;
433449
433993
  const restoredTableBoundary = structuralSnapshot && previousBlockIndex ? structuralSnapshot.blocks.some((block) => block.structuralRefs.tableNodeId != null && !previousBlockIndex.has(block.blockId) && !overlaidTableIds.has(block.structuralRefs.tableNodeId)) : false;
433450
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;
@@ -433466,7 +434010,8 @@ function materializeProjection(input) {
433466
434010
  blocks: controlledSnapshot.blocks.map(({ blockId, leadingXml, trailingXml, splitFromBlockId }) => ({ blockId, leadingXml, trailingXml, splitFromBlockId }))
433467
434011
  });
433468
434012
  }
433469
- if (controlledSnapshot && !controlledTextOnly || restoredTableBoundary || removedTableBoundary) {
434013
+ const changedTableBoundary = structuralSnapshot && previous3 && tableReplacements.length === 0 && hasChangedTableBoundaryXml(previous3, structuralSnapshot.blocks);
434014
+ if (controlledSnapshot && !controlledTextOnly || restoredTableBoundary || removedTableBoundary || changedTableBoundary) {
433470
434015
  const snapshot4 = controlledSnapshot ?? structuralSnapshot ?? readStorySnapshot(readTarget);
433471
434016
  const placements2 = projectedNamespaceContexts(snapshot4, bootstrap, sourceNamespaces);
433472
434017
  const blocks = snapshot4.blocks.map((block) => ({
@@ -434027,6 +434572,20 @@ function projectedNamespaceContexts(snapshot3, bootstrap, source) {
434027
434572
  });
434028
434573
  return contexts;
434029
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
+ }
434030
434589
  function hasRemovedTableBoundary(previous3, blocks, overlayDeletedBlockIds) {
434031
434590
  const liveIds = new Set(blocks.map((block) => block.blockId));
434032
434591
  const removed = previous3.blockDigests.filter((block) => !liveIds.has(block.blockId) && !overlayDeletedBlockIds.has(block.blockId));
@@ -435793,8 +436352,8 @@ function renderSyntheticTableCell(input) {
435793
436352
  }).slice(0, 8).toUpperCase();
435794
436353
  const prefix = input.tableXml.slice(input.cellSpan.start, contentStart);
435795
436354
  const inherited = new XmlEmissionContext(prefix, input.inherited).at(prefix.length);
435796
- const { word: word3, word2010, declarations } = paragraphEmissionNames({ inherited, source: inherited }, "");
435797
- 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);
435798
436357
  }
435799
436358
  function directElementSpans(xml, openEnd, closeStart, localName3) {
435800
436359
  const spans = [];
@@ -439151,6 +439710,16 @@ function mirrorFamilyIntoStory(input) {
439151
439710
  }
439152
439711
  return;
439153
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
+ }
439154
439723
  if (input.extension.contentControlRewrite) {
439155
439724
  mirrorContentControlRewrite(input);
439156
439725
  return;
@@ -441864,6 +442433,9 @@ function admitPreparedStorySurfaceMutation(prepared, options) {
441864
442433
  return { ok: false, message: `no story shard registered for ${storyId}` };
441865
442434
  }
441866
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
+ }
441867
442439
  if (prepared.source.kind === "storySurfaceRewrite" && prepared.source.contentControlRewrite) {
441868
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." };
441869
442441
  }
@@ -444428,12 +445000,12 @@ function buildProjectionApplyInputForTesting(record3, previousRecord, projection
444428
445000
  }
444429
445001
  function buildProjectedParts(record3, previousRecord, changedPartUris, projectionRegistry, options) {
444430
445002
  const out = [];
444431
- const encoder3 = new TextEncoder;
445003
+ const encoder4 = new TextEncoder;
444432
445004
  const previousStoriesByPartUri = new Map((previousRecord?.stories ?? []).map((story) => [story.partUri, story]));
444433
445005
  for (const story of record3.stories) {
444434
445006
  const changed = changedPartUris.has(story.partUri);
444435
- const patches = changed && !options.forceStoryBytes ? buildStoryPartBytePatches(previousStoriesByPartUri.get(story.partUri), story, encoder3, options.readLivePartBytes, options.readLiveBlockRange) : null;
444436
- 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;
444437
445009
  out.push({
444438
445010
  partUri: story.partUri,
444439
445011
  contentType: storyContentType(story.storyKind),
@@ -444443,7 +445015,7 @@ function buildProjectedParts(record3, previousRecord, changedPartUris, projectio
444443
445015
  });
444444
445016
  }
444445
445017
  for (const relationship of record3.relationships) {
444446
- const bytes = changedPartUris.has(relationship.relsPartUri) ? encodeProjectionXml(encoder3, relationship.xml) : null;
445018
+ const bytes = changedPartUris.has(relationship.relsPartUri) ? encodeProjectionXml(encoder4, relationship.xml) : null;
444447
445019
  out.push({
444448
445020
  partUri: relationship.relsPartUri,
444449
445021
  contentType: "application/vnd.openxmlformats-package.relationships+xml",
@@ -444453,7 +445025,7 @@ function buildProjectedParts(record3, previousRecord, changedPartUris, projectio
444453
445025
  }
444454
445026
  for (const part of record3.parts) {
444455
445027
  if (part.content.kind === "xml") {
444456
- 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;
444457
445029
  out.push({
444458
445030
  partUri: part.partUri,
444459
445031
  contentType: part.contentType || null,
@@ -444480,7 +445052,7 @@ function storyProjectionSignature(story) {
444480
445052
  ...story.blockDigests.map((block) => `${block.blockId}:${block.digest}:${block.xml.length}`)
444481
445053
  ].join("|");
444482
445054
  }
444483
- function buildStoryPartBytePatches(previous3, next, encoder3, readLivePartBytes, readLiveBlockRange) {
445055
+ function buildStoryPartBytePatches(previous3, next, encoder4, readLivePartBytes, readLiveBlockRange) {
444484
445056
  if (!previous3 || previous3.partUri !== next.partUri || previous3.storyKind !== next.storyKind)
444485
445057
  return null;
444486
445058
  if (previous3.blockDigests.length !== next.blockDigests.length)
@@ -444505,13 +445077,13 @@ function buildStoryPartBytePatches(previous3, next, encoder3, readLivePartBytes,
444505
445077
  if (priorBlock.digest === nextBlock.digest && priorBlock.xml === nextBlock.xml)
444506
445078
  continue;
444507
445079
  const range = readLiveBlockRange ? readLiveBlockRange(previous3.storyId, previous3.partUri, priorBlock.blockId) : priorBlock.byteStart != null && priorBlock.byteEnd != null ? { startByte: priorBlock.byteStart, endByte: priorBlock.byteEnd } : null;
444508
- 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))) {
444509
445081
  return null;
444510
445082
  }
444511
445083
  patches.push({
444512
445084
  startByte: range.startByte,
444513
445085
  endByte: range.endByte,
444514
- bytes: encodeProjectionXml(encoder3, nextBlock.xml)
445086
+ bytes: encodeProjectionXml(encoder4, nextBlock.xml)
444515
445087
  });
444516
445088
  }
444517
445089
  if (previous3.xml.slice(previousEnd) !== next.xml.slice(nextEnd))
@@ -444527,8 +445099,8 @@ function liveWindowMatches(live, startByte, endByte, expected) {
444527
445099
  }
444528
445100
  return true;
444529
445101
  }
444530
- function encodeProjectionXml(encoder3, xml) {
444531
- return measureSDTxPerf("projectionEncodeMs", () => encoder3.encode(xml));
445102
+ function encodeProjectionXml(encoder4, xml) {
445103
+ return measureSDTxPerf("projectionEncodeMs", () => encoder4.encode(xml));
444532
445104
  }
444533
445105
  function projectionPartSignatures(record3) {
444534
445106
  const signatures = new Map;
@@ -444575,16 +445147,16 @@ function storyContentType(storyKind) {
444575
445147
  }
444576
445148
  async function encodeProjectionRecordAsDocx(input) {
444577
445149
  const entries2 = new Map;
444578
- const encoder3 = new TextEncoder;
445150
+ const encoder4 = new TextEncoder;
444579
445151
  for (const story of input.record.stories) {
444580
- entries2.set(zipKey(story.partUri), encodeProjectionXml(encoder3, story.xml));
445152
+ entries2.set(zipKey(story.partUri), encodeProjectionXml(encoder4, story.xml));
444581
445153
  }
444582
445154
  for (const relationship of input.record.relationships) {
444583
- entries2.set(zipKey(relationship.relsPartUri), encodeProjectionXml(encoder3, relationship.xml));
445155
+ entries2.set(zipKey(relationship.relsPartUri), encodeProjectionXml(encoder4, relationship.xml));
444584
445156
  }
444585
445157
  for (const part of input.record.parts) {
444586
445158
  if (part.content.kind === "xml") {
444587
- entries2.set(zipKey(part.partUri), encodeProjectionXml(encoder3, part.content.xml));
445159
+ entries2.set(zipKey(part.partUri), encodeProjectionXml(encoder4, part.content.xml));
444588
445160
  continue;
444589
445161
  }
444590
445162
  const bytes = await resolveProjectedPartBytes(part.partUri, input.projectionRegistry, input.blobAdapter);