@superdoc/mcp 1.9.0-next.5 → 1.9.0-next.7

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 +562 -76
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -31620,7 +31620,7 @@ var init_host = __esm(() => {
31620
31620
  });
31621
31621
 
31622
31622
  // ../../packages/sdk/langs/node/src/runtime/sdk-version.generated.ts
31623
- var SDK_VERSION = "2.22.0-next.5";
31623
+ var SDK_VERSION = "2.22.0-next.7";
31624
31624
 
31625
31625
  // ../../packages/sdk/langs/node/src/runtime/embedded-platform.ts
31626
31626
  import { accessSync, chmodSync, constants, existsSync, statSync } from "node:fs";
@@ -127497,7 +127497,7 @@ function contextKey(value) {
127497
127497
  }
127498
127498
  function memoCanonicalXmlAnalysis(input, compute) {
127499
127499
  const frame = activeFrame;
127500
- if (!frame || frame.cold || frame.retained?.released || input.xml.length > MAX_WINDOW_CHARACTERS)
127500
+ if (!frame || frame.cold || frame.retained?.released || input.xml.length > MAX_WINDOW_CHARACTERS || input.kind === "paragraph-inline" && input.xml.length > MAX_INLINE_WINDOW_CHARACTERS)
127501
127501
  return compute(input.namespaceBindings);
127502
127502
  const namespaceKey = issuedNamespaceKeys.get(input.namespaceBindings);
127503
127503
  if (namespaceKey === undefined)
@@ -127658,7 +127658,7 @@ function memoRetainedAnalysis(cache, key, xml, compute) {
127658
127658
  cache.outputUnits += resources.units;
127659
127659
  return detached;
127660
127660
  }
127661
- var activeFrame = null, MAX_WINDOW_CHARACTERS, MAX_RETAINED_CHARACTERS, MAX_ENTRIES = 32, MAX_RETAINED_OUTPUT_UNITS = 262144, MAX_RETAINED_OUTPUT_BYTES, issuedNamespaceKeys, retainedAnalyses, releasedOwners, CANONICAL_XML_EMPTY_NAMESPACE_BINDINGS;
127661
+ var activeFrame = null, MAX_WINDOW_CHARACTERS, MAX_INLINE_WINDOW_CHARACTERS = 512, MAX_RETAINED_CHARACTERS, MAX_ENTRIES = 32, MAX_RETAINED_OUTPUT_UNITS = 262144, MAX_RETAINED_OUTPUT_BYTES, issuedNamespaceKeys, retainedAnalyses, releasedOwners, CANONICAL_XML_EMPTY_NAMESPACE_BINDINGS;
127662
127662
  var init_canonical_xml_analysis_frame = __esm(() => {
127663
127663
  MAX_WINDOW_CHARACTERS = 512 * 1024;
127664
127664
  MAX_RETAINED_CHARACTERS = 2 * 1024 * 1024;
@@ -165526,6 +165526,7 @@ function createParagraphSemanticOwnershipCollector(xml) {
165526
165526
  paragraphOwner = { start: event.start, ancestors: [...stack], hasSemanticRange: false, ownership: Object.freeze({
165527
165527
  containerKind: parent.local === "body" ? "body" : "cell",
165528
165528
  containerId: parent.containerId,
165529
+ containerPath: Object.freeze(stack.filter((frame) => frame.plain && (frame.local === "body" || frame.local === "tc")).map((frame) => frame.containerId)),
165529
165530
  namespaceBindings: createCanonicalXmlNamespaceBindings(Object.entries(event.namespaceBindings)),
165530
165531
  parentNamespaceBindings: parent.namespaceBindings
165531
165532
  }) };
@@ -166048,6 +166049,17 @@ function relatedLogicalIds(entry) {
166048
166049
  ...entry.subsumption?.role === "parent" ? entry.subsumption.ownedChildIds : []
166049
166050
  ];
166050
166051
  }
166052
+ function paragraphEndsCertifiedContainer(state, review, paragraph) {
166053
+ const ownership = readResidentParagraphOwnership(state, paragraph.blockId);
166054
+ if (!ownership)
166055
+ return false;
166056
+ const end = Math.min(payloadLength(review.payload), paragraph.byteEnd + 256);
166057
+ const bytes = readResidentPartRangeFromStateSync(state, review.partUri, paragraph.byteEnd, end);
166058
+ if (!bytes)
166059
+ return false;
166060
+ const close = /^[ \t\r\n]*<\/(?:([A-Za-z_][\w.-]*):)?(body|tc)[ \t\r\n]*>/.exec(decoder4.decode(bytes));
166061
+ return close?.[2] === (ownership.containerKind === "cell" ? "tc" : "body") && ownership.parentNamespaceBindings[close[1] ?? ""] === NS_W;
166062
+ }
166051
166063
  function readResidentReviewComponent(state, mode, sourceIds, includeCoordinates = true) {
166052
166064
  const review = reviews.get(state);
166053
166065
  if (!review || review.payload !== state.packageBytes.getPayload(review.partUri) || sourceIds.size === 0)
@@ -166074,6 +166086,7 @@ function readResidentReviewComponent(state, mode, sourceIds, includeCoordinates
166074
166086
  if (!ownership || ownership.parentNamespaceBindings.w !== NS_W)
166075
166087
  return null;
166076
166088
  const hasParagraphBridge = (owner2) => (owner2.xml.match(/<w:pPr\b[\s\S]*?<\/w:pPr>/g) ?? []).some((xml) => /<w:pPrChange\b|<w:rPr\b[\s\S]*?<w:(?:ins|del)\b/.test(xml));
166089
+ const topologyBoundaryOwners = new Set;
166077
166090
  const neighbor = (ordinal, delta) => {
166078
166091
  const paragraph2 = index.entries[ordinal], adjacent = index.entries[ordinal + delta];
166079
166092
  if (!paragraph2 || !adjacent)
@@ -166081,13 +166094,17 @@ function readResidentReviewComponent(state, mode, sourceIds, includeCoordinates
166081
166094
  const adjacentOwnership = readResidentParagraphOwnership(state, adjacent.blockId);
166082
166095
  if (!adjacentOwnership) {
166083
166096
  const current2 = review.owners.get(paragraph2.blockId), other = review.owners.get(adjacent.blockId);
166084
- if (current2 && other && !/<(?:[\w.-]+:)?pPr\b/.test(current2.xml) && !/<(?:[\w.-]+:)?(?:ins|del|moveFrom|moveTo|pPrChange|rPrChange)\b/.test(other.xml))
166097
+ if (current2 && other && !/<(?:[\w.-]+:)?pPr\b/.test(current2.xml) && !/<(?:[\w.-]+:)?(?:ins|del|moveFrom|moveTo|pPrChange|rPrChange)\b/.test(other.xml)) {
166098
+ topologyBoundaryOwners.add(paragraph2.blockId);
166085
166099
  return ordinal;
166100
+ }
166086
166101
  return null;
166087
166102
  }
166088
166103
  if (adjacentOwnership.containerId === ownership.containerId)
166089
166104
  return ordinal + delta;
166090
166105
  const current = review.owners.get(paragraph2.blockId);
166106
+ if (adjacentOwnership.containerPath.includes(ownership.containerId))
166107
+ topologyBoundaryOwners.add(paragraph2.blockId);
166091
166108
  return current && hasParagraphBridge(current) ? null : ordinal;
166092
166109
  };
166093
166110
  const previous = neighbor(first, -1), next = neighbor(last, 1);
@@ -166153,13 +166170,13 @@ function readResidentReviewComponent(state, mode, sourceIds, includeCoordinates
166153
166170
  return null;
166154
166171
  const wrapped = prefix + xml + suffix;
166155
166172
  const prefixBytes = new TextEncoder().encode(prefix).length;
166156
- const firstChar = owners[0].charStart + review.charDeltas.at(owners[0].ordinal);
166173
+ const firstChar2 = owners[0].charStart + review.charDeltas.at(owners[0].ordinal);
166157
166174
  const firstTracked = owners[0].trackedStart + review.trackedDeltas.at(owners[0].ordinal);
166158
166175
  const analyses = [];
166159
166176
  let complete = true;
166160
166177
  for (const owner2 of owners) {
166161
166178
  const paragraph2 = index.entries[owner2.ordinal];
166162
- const charStart = prefix.length + owner2.charStart + review.charDeltas.at(owner2.ordinal) - firstChar;
166179
+ const charStart = prefix.length + owner2.charStart + review.charDeltas.at(owner2.ordinal) - firstChar2;
166163
166180
  if (wrapped.slice(charStart, charStart + owner2.xml.length) !== owner2.xml)
166164
166181
  return null;
166165
166182
  let physical = owner2.physical;
@@ -166214,6 +166231,20 @@ function readResidentReviewComponent(state, mode, sourceIds, includeCoordinates
166214
166231
  lookupContext: createStructuralLookupContext()
166215
166232
  };
166216
166233
  }
166234
+ const firstChar = owners[0].charStart + review.charDeltas.at(owners[0].ordinal);
166235
+ for (const owner2 of owners) {
166236
+ if (!topologyBoundaryOwners.has(owner2.blockId))
166237
+ continue;
166238
+ const charStart = prefix.length + owner2.charStart + review.charDeltas.at(owner2.ordinal) - firstChar;
166239
+ for (const fragments2 of component.raw.byRsid.values())
166240
+ for (const fragment3 of fragments2) {
166241
+ if (fragment3.kind === "ins" && fragment3.byteStart >= charStart && fragment3.byteEnd <= charStart + owner2.xml.length && isEmptyTableSplitParagraph(owner2.xml, fragment3.byteStart - charStart, fragment3.byteEnd - charStart) && !paragraphEndsCertifiedContainer(state, review, index.entries[owner2.ordinal])) {
166242
+ if (component !== cached2)
166243
+ component.lookupContext.dispose();
166244
+ return null;
166245
+ }
166246
+ }
166247
+ }
166217
166248
  const modeCached = component.logicalByMode.get(mode);
166218
166249
  const dependencies = componentDependencies(state, component.dependencyIds);
166219
166250
  let logical = modeCached && componentDependenciesMatch(modeCached.dependencies, dependencies) ? modeCached.logical : null;
@@ -166906,6 +166937,7 @@ var init_resident_review = __esm(() => {
166906
166937
  init_resident_paragraphs();
166907
166938
  init_comment_anchor_index();
166908
166939
  init_sd_document_state();
166940
+ init_part_payload();
166909
166941
  init_paragraph_index();
166910
166942
  init_wml_paragraph_spans();
166911
166943
  init_paragraph_inline_model();
@@ -166916,6 +166948,7 @@ var init_resident_review = __esm(() => {
166916
166948
  init_source_inventory();
166917
166949
  init_export_projection();
166918
166950
  init_resident_paragraph_ownership();
166951
+ init_table_split_paragraph();
166919
166952
  init_effective_list_reference();
166920
166953
  init_canonical_xml_analysis_frame();
166921
166954
  reviews = new WeakMap;
@@ -173793,6 +173826,54 @@ function refreshTextboxExecutionBackendCapabilities(state, geometryMutationBacke
173793
173826
  };
173794
173827
  }
173795
173828
  }
173829
+ function captureSourceSignalPackage(state) {
173830
+ const parts = new Map(state.partOrder.flatMap((id) => {
173831
+ const descriptor = state.parts.get(id)?.descriptor;
173832
+ return descriptor ? [[id, {
173833
+ uri: descriptor.partUri,
173834
+ contentType: descriptor.contentType,
173835
+ kind: descriptor.kind,
173836
+ uncompressedSize: descriptor.size.uncompressedBytes ?? 0
173837
+ }]] : [];
173838
+ }));
173839
+ const payloads = state.packageBytes.detached();
173840
+ const source = state.lazyPackagePayloadSource;
173841
+ const sourceParts = new Set([...state.parts].flatMap(([uri, { descriptor }]) => state.sourcePartRevisions.get(uri) === descriptor.revision ? [uri] : []));
173842
+ const fencedMain = state.mainStorySourceRangeReader?.partUri;
173843
+ const read = (name) => {
173844
+ const uri = normalizePartUri(name);
173845
+ if (!parts.has(uri) || uri === fencedMain)
173846
+ return;
173847
+ const retained = payloads.get(uri);
173848
+ if (retained)
173849
+ return retained;
173850
+ const bytes = sourceParts.has(uri) ? source?.readPayload(uri) : undefined;
173851
+ if (bytes)
173852
+ payloads.set(uri, bytes);
173853
+ return bytes ?? undefined;
173854
+ };
173855
+ const mainDocumentPartUri = state.mainStoryId ? state.stories.get(state.mainStoryId)?.descriptor.ownerPartUri ?? null : null;
173856
+ const relsParts = new Map;
173857
+ const mainRelsUri = mainDocumentPartUri ? relsUriFor(mainDocumentPartUri) : null;
173858
+ const mainRelsBytes = mainRelsUri ? read(mainRelsUri) : undefined;
173859
+ const mainDocumentRelationships = mainDocumentPartUri && mainRelsUri && mainRelsBytes ? parseRelationshipsXml(new TextDecoder().decode(mainRelsBytes), {
173860
+ ownerPartUri: mainDocumentPartUri,
173861
+ relsUri: mainRelsUri,
173862
+ resolveTarget: (target, mode) => resolveTargetUri(mainDocumentPartUri, target, mode, parts)
173863
+ }) : null;
173864
+ if (mainDocumentRelationships && mainRelsUri)
173865
+ relsParts.set(mainRelsUri, mainDocumentRelationships);
173866
+ return {
173867
+ parts,
173868
+ mainDocumentPartUri,
173869
+ mainDocumentRelationships,
173870
+ relsParts,
173871
+ zip: { payloads: { get: read, has: (name) => {
173872
+ const uri = normalizePartUri(name);
173873
+ return parts.has(uri) && uri !== fencedMain && payloads.has(uri);
173874
+ } } }
173875
+ };
173876
+ }
173796
173877
  function ensurePackagePartBytes(state, partUri) {
173797
173878
  const normalizedPartUri = partUri.startsWith("/") ? partUri : `/${partUri}`;
173798
173879
  const cached2 = state.packageBytes.get(normalizedPartUri);
@@ -182415,7 +182496,14 @@ function compileParsedOverlapEdit(input, tokens, descendedEditableContainers) {
182415
182496
  }
182416
182497
  const paragraphContainsMoveWrapper = tokens.some((token) => token.kind === "unsupported" && token.foreignTrackedWrapper !== true && (token.trackedKind === "moveFrom" || token.trackedKind === "moveTo"));
182417
182498
  const trackedPlainCaret = (input.coordinateSpace ?? "visible") === "tracked" && tokenOwningCollapsedCaret(input, tokens)?.kind === "plain";
182418
- const deletedControlBoundary = input.collapsedInlineAffinity != null && tokens.some((token) => token.kind === "unsupported" && token.deletedInlineControl === true && token.visibleStart === input.rangeStart && token.visibleEnd === input.rangeStart);
182499
+ const deletedControlBoundary = tokens.some((token) => {
182500
+ if (token.kind !== "unsupported" || token.deletedInlineControl !== true)
182501
+ return false;
182502
+ if ((input.coordinateSpace ?? "visible") !== "tracked") {
182503
+ return input.collapsedInlineAffinity != null && token.visibleStart === input.rangeStart && token.visibleEnd === input.rangeStart;
182504
+ }
182505
+ return token.visibleStart === input.rangeStart && input.collapsedInlineAffinity !== "downstream" || token.visibleEnd === input.rangeStart && input.collapsedInlineAffinity !== "upstream";
182506
+ });
182419
182507
  if ((paragraphContainsMoveWrapper || trackedPlainCaret || deletedControlBoundary) && input.rangeStart === input.rangeEnd && input.newText.length > 0) {
182420
182508
  const defersExplicitUpstreamMoveBoundary = input.changeMode === "direct" && input.collapsedInlineAffinity === "upstream" && !tokens.some((token) => token.kind === "plain" && token.visibleEnd === input.rangeStart) && tokens.some((token) => token.kind === "unsupported" && token.foreignTrackedWrapper !== true && token.trackedKind === "moveFrom" && token.visibleStart === input.rangeStart && token.visibleEnd === input.rangeStart);
182421
182509
  if (defersExplicitUpstreamMoveBoundary) {
@@ -193158,6 +193246,92 @@ var init_closed_history_group = __esm(() => {
193158
193246
  preparedGroups = new WeakMap;
193159
193247
  });
193160
193248
 
193249
+ // ../../../v2/editor-core/dist/document/transactions/tracked-annotation-reconstruction.js
193250
+ function hasTrackedRemap(refs) {
193251
+ return refs.some((remap) => remap.from.kind === "trackedChange" || remap.to.kind === "trackedChange");
193252
+ }
193253
+ function decisionKey(prepared) {
193254
+ return JSON.stringify({
193255
+ txId: prepared.txId,
193256
+ source: prepared.source,
193257
+ base: prepared.baseRevisions,
193258
+ created: prepared.semanticDelta.createdRefs,
193259
+ updated: prepared.semanticDelta.updatedRefs,
193260
+ invalidated: prepared.semanticDelta.invalidatedRefs,
193261
+ remapped: prepared.semanticDelta.remappedRefs
193262
+ });
193263
+ }
193264
+ function captureTrackedDecisionAnnotationReconstruction(state, prepared) {
193265
+ if (prepared.source.kind !== "trackedChangeDecide" || prepared.source !== prepared.localApplyBundle.source || !hasTrackedRemap(prepared.semanticDelta.remappedRefs))
193266
+ return;
193267
+ preparedDecisions.set(prepared, {
193268
+ state,
193269
+ documentEpoch: state.documentRef.documentId,
193270
+ packageRevision: state.packageRevision,
193271
+ commitSequence: state.renderCommitSequence,
193272
+ source: prepared.source,
193273
+ bundle: prepared.localApplyBundle,
193274
+ key: decisionKey(prepared)
193275
+ });
193276
+ }
193277
+ function sourceKey(commit) {
193278
+ return JSON.stringify({
193279
+ documentEpoch: commit.documentEpoch,
193280
+ commitSequence: commit.commitSequence,
193281
+ coveredCommitSequenceStart: commit.coveredCommitSequenceStart,
193282
+ txId: commit.txId,
193283
+ package: commit.revisions.package,
193284
+ historyReplay: commit.historyReplay,
193285
+ created: commit.facts.createdRefs,
193286
+ updated: commit.facts.updatedRefs,
193287
+ invalidated: commit.facts.invalidatedRefs,
193288
+ remapped: commit.facts.remappedRefs
193289
+ });
193290
+ }
193291
+ function requiresCanonicalAnnotations(commit) {
193292
+ return commit.classification.kind === "broad" && !commit.remote && commit.trackedAnnotations == null && commit.trackedAnnotationHistory == null && commit.trackedAnnotationHistoryGroup == null && commit.trackedAnnotationSteps == null && commit.trackedAnnotationRemovals == null && commit.sourceProjectionEffect == null && commit.sourceProjectionSteps == null && (hasTrackedRemap(commit.facts.remappedRefs) || commit.historyReplay === true && commit.facts.createdRefs.some((ref3) => ref3.kind === "trackedChange"));
193293
+ }
193294
+ function issue2(state, commit) {
193295
+ const token = Object.freeze({});
193296
+ issued2.set(token, { state, key: sourceKey(commit) });
193297
+ return token;
193298
+ }
193299
+ function sealTrackedDecisionAnnotationReconstruction(state, prepared, entry, result, commit) {
193300
+ const captured = preparedDecisions.get(prepared);
193301
+ preparedDecisions.delete(prepared);
193302
+ if (!captured || captured.state !== state || captured.documentEpoch !== state.documentRef.documentId || captured.source !== prepared.source || captured.bundle !== prepared.localApplyBundle || captured.key !== decisionKey(prepared) || commit.historyReplay || captured.commitSequence + 1 !== result.commitSequence || captured.packageRevision !== result.previousPackageRevision || state.history.entries.get(entry.txId) !== entry || entry.txId !== prepared.txId || commit.txId !== prepared.txId || entry.forwardPatchGroup !== result.forwardPatchGroup || entry.inversePatchGroup !== result.inversePatchGroup || result.forwardPatchGroup?.source !== captured.source || result.status !== "committed" || result.documentEpoch !== captured.documentEpoch || result.documentEpoch !== commit.documentEpoch || result.commitSequence !== state.renderCommitSequence || result.commitSequence !== commit.commitSequence || result.previousPackageRevision !== commit.revisions.package.previous || result.packageRevision !== state.packageRevision || result.packageRevision !== commit.revisions.package.next || JSON.stringify({
193303
+ created: commit.facts.createdRefs,
193304
+ updated: commit.facts.updatedRefs,
193305
+ invalidated: commit.facts.invalidatedRefs,
193306
+ remapped: commit.facts.remappedRefs
193307
+ }) !== JSON.stringify({
193308
+ created: prepared.semanticDelta.createdRefs,
193309
+ updated: prepared.semanticDelta.updatedRefs,
193310
+ invalidated: prepared.semanticDelta.invalidatedRefs,
193311
+ remapped: prepared.semanticDelta.remappedRefs
193312
+ }) || !requiresCanonicalAnnotations(commit))
193313
+ return null;
193314
+ return issue2(state, commit);
193315
+ }
193316
+ function issueTrackedAnnotationReconstruction(state, entry, result, commit) {
193317
+ if (state.history.entries.get(entry.txId) !== entry || entry.forwardPatchGroup.source.kind !== "trackedChangeDecide" || result.status !== "committed" || result.documentEpoch !== state.documentRef.documentId || result.commitSequence !== state.renderCommitSequence || result.documentEpoch !== commit.documentEpoch || result.commitSequence !== commit.commitSequence || result.previousPackageRevision !== commit.revisions.package.previous || result.packageRevision !== state.packageRevision || result.packageRevision !== commit.revisions.package.next || commit.historyReplay !== true || !requiresCanonicalAnnotations(commit))
193318
+ return null;
193319
+ return issue2(state, commit);
193320
+ }
193321
+ function isIssuedTrackedAnnotationReconstruction(value) {
193322
+ return Object.isFrozen(value) && issued2.has(value);
193323
+ }
193324
+ function readIssuedTrackedAnnotationReconstruction(commit) {
193325
+ const token = commit.trackedAnnotationReconstruction;
193326
+ const binding = token && issued2.get(token);
193327
+ return !!binding && Object.isFrozen(token) && binding.key === sourceKey(commit) && commit.documentEpoch === binding.state.documentRef.documentId && commit.commitSequence <= binding.state.renderCommitSequence && requiresCanonicalAnnotations(commit);
193328
+ }
193329
+ var issued2, preparedDecisions;
193330
+ var init_tracked_annotation_reconstruction = __esm(() => {
193331
+ issued2 = new WeakMap;
193332
+ preparedDecisions = new WeakMap;
193333
+ });
193334
+
193161
193335
  // ../../../v2/editor-core/dist/document/transactions/render-commit-annotation-effect.js
193162
193336
  function proveAnnotationSourceEffect(input) {
193163
193337
  const { before, after, commentId, operation, beforeNamespaces, afterNamespaces } = input;
@@ -193264,7 +193438,7 @@ var init_comment_tracked_change_metadata = __esm(() => {
193264
193438
 
193265
193439
  // ../../../v2/editor-core/dist/document/transactions/tracked-decision-comment-metadata.js
193266
193440
  function readIssuedTrackedDecisionCommentMetadata(state, prepared) {
193267
- const group = prepared.localApplyBundle, proof = issued2.get(group.perPart);
193441
+ const group = prepared.localApplyBundle, proof = issued3.get(group.perPart);
193268
193442
  if (!proof || proof.state !== state || prepared.source.kind !== "trackedChangeDecide" || prepared.baseRevisions.package !== proof.packageRevision || prepared.baseRevisions.perPart[COMMENTS_PART_URI] !== proof.commentsRevision)
193269
193443
  return null;
193270
193444
  const parts = Object.keys(group.perPart), bodyPartUri = parts.find((uri) => uri !== COMMENTS_PART_URI);
@@ -193381,7 +193555,7 @@ function applyRetiredTrackedChangeCommentMetadataCleanup(args) {
193381
193555
  });
193382
193556
  const commentsRevision = args.state.parts.get(COMMENTS_PART_URI)?.descriptor.revision;
193383
193557
  if (!pendingPatch && commentsRevision && updatedRefs.length)
193384
- issued2.set(args.perPart, {
193558
+ issued3.set(args.perPart, {
193385
193559
  state: args.state,
193386
193560
  packageRevision: args.state.packageRevision,
193387
193561
  commentsRevision,
@@ -193391,14 +193565,14 @@ function applyRetiredTrackedChangeCommentMetadataCleanup(args) {
193391
193565
  });
193392
193566
  return updatedRefs;
193393
193567
  }
193394
- var TD34, TE13, issued2;
193568
+ var TD34, TE13, issued3;
193395
193569
  var init_tracked_decision_comment_metadata = __esm(() => {
193396
193570
  init_comments_catalog();
193397
193571
  init_comment_tracked_change_metadata();
193398
193572
  init_patch_substrate();
193399
193573
  TD34 = new TextDecoder;
193400
193574
  TE13 = new TextEncoder;
193401
- issued2 = new WeakMap;
193575
+ issued3 = new WeakMap;
193402
193576
  });
193403
193577
 
193404
193578
  // ../../../v2/editor-core/dist/document/transactions/tracked-decision-comment-cascade.js
@@ -193412,7 +193586,7 @@ function fingerprint2(group, updatedRefs, invalidatedRefs) {
193412
193586
  ], (_key, value) => value instanceof Uint8Array ? { byteLength: value.length } : value);
193413
193587
  }
193414
193588
  function readIssuedTrackedDecisionCommentCascade(state, prepared) {
193415
- const group = prepared.localApplyBundle, proof = issued3.get(group.perPart);
193589
+ const group = prepared.localApplyBundle, proof = issued4.get(group.perPart);
193416
193590
  if (!proof || proof.state !== state || prepared.source.kind !== "trackedChangeDecide" || prepared.baseRevisions.package !== proof.packageRevision || proof.patches.some(({ partUri, index, patch, bytes }) => {
193417
193591
  const entry = group.perPart[partUri];
193418
193592
  return entry?.kind !== "modify" || entry.patches[index] !== patch || patch.bytes.length !== bytes.length || !bytes.every((byte, index2) => patch.bytes[index2] === byte);
@@ -193565,7 +193739,7 @@ function prepareBoundedTrackedDecisionCommentCascade(input) {
193565
193739
  patchMaps: group.patchMaps,
193566
193740
  retiredSourceIds: input.retiredSourceIds
193567
193741
  }).filter((ref3) => ref3.kind !== "comment" || !removed.has(ref3.commentId));
193568
- issued3.set(group.perPart, {
193742
+ issued4.set(group.perPart, {
193569
193743
  state,
193570
193744
  packageRevision: group.baseRevisions.package,
193571
193745
  bodyPartUri: paragraph.partUri,
@@ -193579,7 +193753,7 @@ function prepareBoundedTrackedDecisionCommentCascade(input) {
193579
193753
  }
193580
193754
  };
193581
193755
  }
193582
- var TD35, TE14, issued3;
193756
+ var TD35, TE14, issued4;
193583
193757
  var init_tracked_decision_comment_cascade = __esm(() => {
193584
193758
  init_resident_review();
193585
193759
  init_body_comment_anchors();
@@ -193589,7 +193763,7 @@ var init_tracked_decision_comment_cascade = __esm(() => {
193589
193763
  init_patch_substrate();
193590
193764
  TD35 = new TextDecoder;
193591
193765
  TE14 = new TextEncoder;
193592
- issued3 = new WeakMap;
193766
+ issued4 = new WeakMap;
193593
193767
  });
193594
193768
 
193595
193769
  // ../../../v2/editor-core/dist/document/transactions/render-commit-inline-effect.js
@@ -194395,6 +194569,16 @@ function issueStructuralTrackedCarrierPartition(state, input) {
194395
194569
  const ownership = readResidentParagraphOwnership(state, paragraph.blockId);
194396
194570
  if (!ownership || paragraph.storyId !== state.mainStoryId || input.resultParagraphs.length !== 2 || input.beforeXml.length > 512 * 1024 || input.afterXml.length > 512 * 1024)
194397
194571
  return null;
194572
+ const local = buildTrackedChangeCatalogFromPartXml({
194573
+ scanScope: "bounded-source-window",
194574
+ xml: input.beforeXml,
194575
+ partUri: paragraph.partUri,
194576
+ storyId: paragraph.storyId,
194577
+ namespaceBindings: ownership.namespaceBindings
194578
+ });
194579
+ const sourceKeys2 = [...local.byRsid.keys()];
194580
+ if (!sourceKeys2.length)
194581
+ return null;
194398
194582
  const inlineMaps = new Map;
194399
194583
  const readInline = (xml) => {
194400
194584
  let value = inlineMaps.get(xml);
@@ -194423,16 +194607,6 @@ function issueStructuralTrackedCarrierPartition(state, input) {
194423
194607
  const renderedPayloads = renderedParagraphs.map((xml) => inlinePayload(xml, ownership.namespaceBindings, readInline, lineage, input.authoredMarkWordId));
194424
194608
  if (!before || resultPayloads.some((payload) => !payload) || JSON.stringify(compactPayload(before)) !== JSON.stringify(compactPayload(resultPayloads.flatMap((payload) => payload))) || renderedPayloads.some((payload) => !payload) || JSON.stringify(compactPayload(renderedPayloads.flatMap((payload) => payload))) !== JSON.stringify(compactPayload(before)) || !proveClosedCommentAnchorPreservation(input.beforeXml, input.afterXml, ownership.namespaceBindings))
194425
194609
  return null;
194426
- const local = buildTrackedChangeCatalogFromPartXml({
194427
- scanScope: "bounded-source-window",
194428
- xml: input.beforeXml,
194429
- partUri: paragraph.partUri,
194430
- storyId: paragraph.storyId,
194431
- namespaceBindings: ownership.namespaceBindings
194432
- });
194433
- const sourceKeys2 = [...local.byRsid.keys()];
194434
- if (!sourceKeys2.length)
194435
- return null;
194436
194610
  for (const mode of ["paired", "independent"]) {
194437
194611
  const view = readResidentReviewCatalog(state, mode, sourceKeys2, true);
194438
194612
  if (!view || !componentFits(view, paragraph.byteStart, paragraph.byteEnd, paragraph.partUri, paragraph.storyId))
@@ -194447,7 +194621,7 @@ function issueStructuralTrackedCarrierPartition(state, input) {
194447
194621
  });
194448
194622
  const afterSourceKeys = [...new Set([...sourceKeys2, ...afterCatalog.byRsid.keys()])];
194449
194623
  const proof = Object.freeze({ kind: "structural-tracked-carrier-partition" });
194450
- issued4.set(proof, {
194624
+ issued5.set(proof, {
194451
194625
  state,
194452
194626
  txId: input.txId,
194453
194627
  storyId: paragraph.storyId,
@@ -194464,7 +194638,7 @@ function issueStructuralTrackedCarrierPartition(state, input) {
194464
194638
  }
194465
194639
  function proveStructuralTrackedCarrierPartition(state, prepared, originXml, resultXml) {
194466
194640
  const proof = prepared.backendExtensions.storySurface?.structuralTrackedCarrierPartition;
194467
- const record3 = proof && issued4.get(proof);
194641
+ const record3 = proof && issued5.get(proof);
194468
194642
  const source = prepared.source;
194469
194643
  if (!record3 || record3.state !== state || record3.txId !== prepared.txId || source.kind !== "paragraphSplit" || source.target.storyId !== record3.storyId || source.target.paraId !== record3.blockId || originXml.length !== 1 || originXml[0] !== record3.beforeXml || resultXml.length !== 2 || resultXml.join("") !== record3.afterXml)
194470
194644
  return false;
@@ -194626,7 +194800,7 @@ function compactPayload(payload) {
194626
194800
  }
194627
194801
  return result;
194628
194802
  }
194629
- var issued4;
194803
+ var issued5;
194630
194804
  var init_structural_tracked_carrier_partition = __esm(() => {
194631
194805
  init_paragraph_inline_model();
194632
194806
  init_resident_paragraph_ownership();
@@ -194635,7 +194809,7 @@ var init_structural_tracked_carrier_partition = __esm(() => {
194635
194809
  init_comment_range_invariance();
194636
194810
  init_xml_sax();
194637
194811
  init_paragraph_mark_markers();
194638
- issued4 = new WeakMap;
194812
+ issued5 = new WeakMap;
194639
194813
  });
194640
194814
 
194641
194815
  // ../../../v2/editor-core/dist/document/transactions/tracked-annotation-history.js
@@ -194985,7 +195159,7 @@ function cloneEnvelopeValue(value) {
194985
195159
  return value.map((entry) => cloneEnvelopeValue(entry));
194986
195160
  if (value == null || typeof value !== "object")
194987
195161
  return value;
194988
- if (isIssuedTrackedAnnotationHistoryOwner(value) || isIssuedTrackedAnnotationHistoryCapsule(value) || isIssuedTrackedAnnotationHistoryGroupCapsule(value))
195162
+ if (isIssuedTrackedAnnotationHistoryOwner(value) || isIssuedTrackedAnnotationHistoryCapsule(value) || isIssuedTrackedAnnotationHistoryGroupCapsule(value) || isIssuedTrackedAnnotationReconstruction(value))
194989
195163
  return value;
194990
195164
  const clone2 = {};
194991
195165
  for (const [key3, entry] of Object.entries(value)) {
@@ -197396,6 +197570,8 @@ function collapseSDRenderCommitEnvelopes(commits) {
197396
197570
  const last = commits[commits.length - 1];
197397
197571
  if (commits.some((commit) => commit.documentEpoch !== last.documentEpoch))
197398
197572
  return null;
197573
+ if (commits.some((commit) => commit.trackedAnnotationReconstruction != null && !readIssuedTrackedAnnotationReconstruction(commit) || commit.trackedAnnotationSteps?.some((step2) => step2.trackedAnnotationReconstruction != null) && (commit.classification.kind !== "broad" || commit.sourceProjectionEffect != null || commit.sourceProjectionSteps != null)))
197574
+ return null;
197399
197575
  const reviewReplicaCommits = collapseReviewReplicaCommitsForAggregate(commits, first, last);
197400
197576
  const localHistory = collapseNarrowTextHistoryCommits(commits) ?? collapseSecondaryTextHistoryCommits(commits);
197401
197577
  const trackedAnnotations = collapseTrackedAnnotationsForAggregate(commits);
@@ -197489,7 +197665,8 @@ function collapseTrackedAnnotationSteps(commits) {
197489
197665
  ...commit.trackedAnnotationRemovals != null ? { trackedAnnotationRemovals: commit.trackedAnnotationRemovals } : {},
197490
197666
  ...commit.trackedAnnotationHistory ? { trackedAnnotationHistory: commit.trackedAnnotationHistory } : {},
197491
197667
  ...commit.trackedAnnotationHistoryGroup ? { trackedAnnotationHistoryGroup: commit.trackedAnnotationHistoryGroup } : {},
197492
- ...commit.trackedAnnotationHistoryGroup ? { updatedRefs: commit.facts.updatedRefs } : {},
197668
+ ...commit.trackedAnnotationReconstruction ? { trackedAnnotationReconstruction: commit.trackedAnnotationReconstruction } : {},
197669
+ ...commit.trackedAnnotationHistoryGroup || commit.trackedAnnotationReconstruction ? { updatedRefs: commit.facts.updatedRefs } : {},
197493
197670
  ...commit.classification.kind === "broad" && commit.classification.reason === "tracked-annotation-unproved" && trackedAnnotations == null ? { unproved: true } : {}
197494
197671
  });
197495
197672
  }
@@ -199593,7 +199770,7 @@ function locateExactResidentBodyChild(state, storyId, partUri, byteStart, byteEn
199593
199770
  const matches = [];
199594
199771
  for (const chunk of chunks) {
199595
199772
  const revision = state.stories.get(storyId)?.descriptor.revision;
199596
- const issued5 = revision && readIssuedSourceChunkBodyChild({
199773
+ const issued6 = revision && readIssuedSourceChunkBodyChild({
199597
199774
  chunk: captureSourceChunkReadSnapshot(chunk).descriptor,
199598
199775
  storyId,
199599
199776
  storyRevision: revision,
@@ -199601,8 +199778,8 @@ function locateExactResidentBodyChild(state, storyId, partUri, byteStart, byteEn
199601
199778
  byteStart,
199602
199779
  byteEnd
199603
199780
  });
199604
- if (issued5) {
199605
- matches.push(issued5);
199781
+ if (issued6) {
199782
+ matches.push(issued6);
199606
199783
  continue;
199607
199784
  }
199608
199785
  const cached2 = cache?.get(chunk);
@@ -199941,6 +200118,7 @@ var init_render_commit_envelope = __esm(() => {
199941
200118
  init_resident_paragraph_ownership();
199942
200119
  init_structural_tracked_carrier_partition();
199943
200120
  init_tracked_annotation_history();
200121
+ init_tracked_annotation_reconstruction();
199944
200122
  init_paragraph_mark_markers();
199945
200123
  init_body_boundary_scan();
199946
200124
  init_comment_range_invariance();
@@ -200089,8 +200267,12 @@ function commitPreparedMutationInFrame(state, prepared, options) {
200089
200267
  historyEntry.renderReplay = renderCommit;
200090
200268
  if (historyEntry && backend.kind === "local")
200091
200269
  sealClosedHistoryGroupEntry(state, historyEntry);
200092
- if (historyEntry)
200270
+ if (historyEntry) {
200093
200271
  options.pushHistory(historyEntry);
200272
+ const authority = sealTrackedDecisionAnnotationReconstruction(state, prepared, historyEntry, applyResult, renderCommit);
200273
+ if (authority)
200274
+ renderCommit.trackedAnnotationReconstruction = authority;
200275
+ }
200094
200276
  if (historyEntry?.renderReplay)
200095
200277
  rememberResidentParagraphSplit(state, renderCommit);
200096
200278
  attachSDRenderCommitEnvelope(receipt2, renderCommit);
@@ -200102,6 +200284,7 @@ var init_commit_prepared_mutation = __esm(() => {
200102
200284
  init_execution_backend();
200103
200285
  init_history_text_replay();
200104
200286
  init_closed_history_group();
200287
+ init_tracked_annotation_reconstruction();
200105
200288
  init_render_commit_envelope();
200106
200289
  });
200107
200290
 
@@ -202682,7 +202865,7 @@ function commitTracked(input, view) {
202682
202865
  overlapEmittedRsids = [op.rsid];
202683
202866
  overlapTrackedTextAnnotations = spanningDeleteWIds.map((segmentWId) => ({
202684
202867
  changeId: op.rsid,
202685
- wId: String(segmentWId),
202868
+ wId: String(segmentWId + 1),
202686
202869
  kind: "delete",
202687
202870
  author: {
202688
202871
  name: stamping.author.name,
@@ -235976,14 +236159,18 @@ function captureRenderSourceSnapshot(state, snapshotId, currentSections) {
235976
236159
  const mainCoverage = mainStoryId ? coverage.get(mainStoryId) : null;
235977
236160
  const mainStory = mainStoryId ? storiesById.get(mainStoryId) : null;
235978
236161
  const signalSnapshot = state.sourceSignals.snapshot;
235979
- const sections = structuredClone(currentSections ?? (signalSnapshot?.packageRevision === binding.packageRevision && mainSignals?.storyRevision === mainStory?.revision && mainSignals?.completeness.sections === "complete" && mainCoverage?.facts.status === "source-complete" && signalSnapshot.sourceCoverageRevision === mainCoverage.facts.sourceCoverageRevision ? {
236162
+ const sectionCandidate = currentSections ?? (signalSnapshot?.packageRevision === binding.packageRevision && mainSignals?.storyRevision === mainStory?.revision && mainSignals?.completeness.sections === "complete" && mainCoverage?.facts.status === "source-complete" && signalSnapshot.sourceCoverageRevision === mainCoverage.facts.sourceCoverageRevision ? {
235980
236163
  packageRevision: binding.packageRevision,
235981
236164
  sourceCoverageRevision: signalSnapshot.sourceCoverageRevision,
235982
236165
  signalsRevision: signalSnapshot.signalsRevision,
235983
236166
  storyId: mainSignals.storyId,
235984
236167
  storyRevision: mainSignals.storyRevision,
235985
236168
  sections: mainSignals.sections
235986
- } : null));
236169
+ } : null);
236170
+ const sections = sectionCandidate && mainStory && mainCoverage && sectionCandidate.packageRevision === binding.packageRevision && sectionCandidate.storyId === mainStory.storyId && sectionCandidate.storyRevision === mainStory.revision && sectionCandidate.sourceCoverageRevision === mainCoverage.facts.sourceCoverageRevision && sectionCandidate.sections.every((section) => {
236171
+ const anchor = section.sourceAnchor;
236172
+ return anchor.stability === "byte-span" && section.storyId === mainStory.storyId && section.storyRevision === mainStory.revision && anchor.storyId === mainStory.storyId && anchor.storyRevision === mainStory.revision && anchor.partId === mainStory.ownerPartUri && anchor.partRevision === partsById.get(anchor.partId)?.revision;
236173
+ }) ? structuredClone(sectionCandidate) : null;
235987
236174
  const lazyReads = new Map;
235988
236175
  const lifetime = new AbortController;
235989
236176
  let pendingSections = null;
@@ -238231,7 +238418,7 @@ function applyDecisionToFragment(input) {
238231
238418
  return { ok: false, reason: "invalid-input" };
238232
238419
  const inner = xml.slice(wrapper.openEnd, wrapper.closeStart);
238233
238420
  const visible = visibleTextLengthInWrapper(inner, fragment3.kind);
238234
- switch (decisionKey(decision, fragment3.kind)) {
238421
+ switch (decisionKey2(decision, fragment3.kind)) {
238235
238422
  case "accept-ins":
238236
238423
  return {
238237
238424
  ok: true,
@@ -238294,7 +238481,7 @@ function applyDecisionToFragment(input) {
238294
238481
  return { ok: false, reason: "unsupported-context" };
238295
238482
  }
238296
238483
  }
238297
- function decisionKey(decision, kind) {
238484
+ function decisionKey2(decision, kind) {
238298
238485
  return `${decision}-${kind}`;
238299
238486
  }
238300
238487
  function visibleTextLengthInWrapper(inner, _kind) {
@@ -238379,7 +238566,7 @@ function applyPartialDecisionToFragment(input) {
238379
238566
  postChunk = `${postOpen}${post}${wrapperClose}`;
238380
238567
  emittedPost = true;
238381
238568
  }
238382
- switch (decisionKey(decision, fragment3.kind)) {
238569
+ switch (decisionKey2(decision, fragment3.kind)) {
238383
238570
  case "accept-ins":
238384
238571
  selChunk = sel;
238385
238572
  visibleTextDelta = 0;
@@ -244399,6 +244586,8 @@ function runTrackedChangeDecideCommitWithLookupContext(lookupContext, input, xml
244399
244586
  actorAttribution: { actorType: input.options.actorTag ?? "code" }
244400
244587
  }
244401
244588
  };
244589
+ if (restoredInsertion)
244590
+ captureTrackedDecisionAnnotationReconstruction(state, prepared);
244402
244591
  const receipt2 = commitPreparedMutation(state, prepared, { pushHistory: input.pushHistory });
244403
244592
  if (receipt2.status === "committed") {
244404
244593
  for (const [rsid, lineage] of pendingSplitLineage) {
@@ -247471,6 +247660,7 @@ var init_compile_tracked_change_decide = __esm(() => {
247471
247660
  init_revision_wid_allocator();
247472
247661
  init_semantic_style_dependencies();
247473
247662
  init_commit_prepared_mutation();
247663
+ init_tracked_annotation_reconstruction();
247474
247664
  init_review_comment_dependencies();
247475
247665
  init_review_resource_dependencies();
247476
247666
  init_compile_tracked_change_decide_local();
@@ -254087,7 +254277,7 @@ function compareTrackedStampPair(input, includeParagraphProperties = false) {
254087
254277
  function makeCompareHunkStampSource(primary, input) {
254088
254278
  const usedPairs = [];
254089
254279
  const reservedRsids = new Set([primary.del.rsid]);
254090
- let issued5 = false;
254280
+ let issued6 = false;
254091
254281
  let pendingRsids = [];
254092
254282
  let batchOrdinal = 0;
254093
254283
  const nextRsid = () => {
@@ -254104,8 +254294,8 @@ function makeCompareHunkStampSource(primary, input) {
254104
254294
  }
254105
254295
  };
254106
254296
  const next = () => {
254107
- if (!issued5) {
254108
- issued5 = true;
254297
+ if (!issued6) {
254298
+ issued6 = true;
254109
254299
  usedPairs.push(primary);
254110
254300
  return primary;
254111
254301
  }
@@ -272875,11 +273065,22 @@ function attachHistoryRenderCommit(state, entry, direction, result, exactRender,
272875
273065
  ensureSDRenderCommitVersion(state, result);
272876
273066
  const renderCommit = replayCommit ?? (exactRender ? buildSDRenderCommitEnvelope(state, exactRender.prepared, result, exactRender.origin, { dirtyBlock: exactRender.dirtyBlock, historyReplay: true }) : buildSDBroadRenderCommitEnvelope(state, `${entry.txId}:${direction}`, result, "history-replay"));
272877
273067
  if (renderCommit) {
272878
- attachSDRenderCommitEnvelope(result, {
273068
+ const reconstructAnnotations = entry.forwardPatchGroup.source.kind === "trackedChangeDecide" && !renderCommit.trackedAnnotationHistory && !renderCommit.trackedAnnotationHistoryGroup && renderCommit.trackedAnnotations == null && (renderCommit.facts.createdRefs.some((ref3) => ref3.kind === "trackedChange") || renderCommit.facts.remappedRefs.some((remap) => remap.from.kind === "trackedChange" || remap.to.kind === "trackedChange"));
273069
+ const replay = {
272879
273070
  ...renderCommit,
272880
- ...sourceProjectionEffect ? { sourceProjectionEffect } : {},
273071
+ ...reconstructAnnotations ? {
273072
+ classification: renderCommit.classification.kind === "broad" && renderCommit.classification.reason !== "history-replay" ? renderCommit.classification : { kind: "broad", reason: "tracked-annotation-unproved" },
273073
+ sourceProjectionEffect: undefined,
273074
+ sourceProjectionSteps: undefined
273075
+ } : sourceProjectionEffect ? { sourceProjectionEffect } : {},
272881
273076
  historyReplay: true
272882
- });
273077
+ };
273078
+ if (reconstructAnnotations) {
273079
+ const authority = issueTrackedAnnotationReconstruction(state, entry, result, replay);
273080
+ if (authority)
273081
+ replay.trackedAnnotationReconstruction = authority;
273082
+ }
273083
+ attachSDRenderCommitEnvelope(result, replay);
272883
273084
  }
272884
273085
  return result;
272885
273086
  }
@@ -274164,7 +274365,7 @@ async function openSDDocumentSession(options) {
274164
274365
  function buildReadyPartial() {
274165
274366
  const signalsRevision = state.revisions.signalsRevision();
274166
274367
  const snapshot2 = buildReadySignals({
274167
- pkg: openResult.packageOpen.pkg,
274368
+ pkg: captureSourceSignalPackage(state),
274168
274369
  scan: openResult.bodyBoundaryScan,
274169
274370
  buffer: mainDocumentBuffer(openResult) ?? new Uint8Array(0),
274170
274371
  mainStoryId,
@@ -274532,7 +274733,7 @@ async function openSDDocumentSession(options) {
274532
274733
  chunkBytesProvider: fencedChunkBytesProvider,
274533
274734
  scan: signalsScan,
274534
274735
  spine: liveSourceSpine,
274535
- pkg: openResult.packageOpen.pkg,
274736
+ pkg: captureSourceSignalPackage(state),
274536
274737
  mainStoryId,
274537
274738
  mainOwnerPartId: mainPartId,
274538
274739
  sourceCoverageRevision: revisionGuard.sourceCoverageRevision,
@@ -274752,7 +274953,7 @@ async function openSDDocumentSession(options) {
274752
274953
  findings: preScanned.sectFindings,
274753
274954
  scan: bodyBoundaryScan,
274754
274955
  totalBodyChildren: sourceCompleteResult.spine.bodyChildCount,
274755
- pkg: openResult.packageOpen.pkg,
274956
+ pkg: captureSourceSignalPackage(state),
274756
274957
  mainStoryId,
274757
274958
  mainOwnerPartId: mainPartId,
274758
274959
  storyRevision: guard.storyRevision,
@@ -275303,6 +275504,7 @@ var init_sd_document_session = __esm(() => {
275303
275504
  init_sd_document_state();
275304
275505
  init_adopted_fenced_source_completion();
275305
275506
  init_render_commit_envelope();
275507
+ init_tracked_annotation_reconstruction();
275306
275508
  init_semantic_style_dependencies();
275307
275509
  init_revision_wid_scan();
275308
275510
  init_document_background();
@@ -318308,7 +318510,7 @@ function buildVisibleSelectionTarget(story, start, end) {
318308
318510
  ...distinctFootnotes(start.story ?? story, end.story ?? story) ? {} : { story }
318309
318511
  };
318310
318512
  }
318311
- function buildSelectionTarget(session, story, start, end, entries2) {
318513
+ function buildSelectionTarget(session, story, start, end, entries2, collapsed = false) {
318312
318514
  const hasTrackedEndpoint = start.trackedOffset != null || end.trackedOffset != null;
318313
318515
  if (!hasTrackedEndpoint)
318314
318516
  return buildVisibleSelectionTarget(story, start, end);
@@ -318325,6 +318527,9 @@ function buildSelectionTarget(session, story, start, end, entries2) {
318325
318527
  if (resolvedStart == null || resolvedEnd == null) {
318326
318528
  return null;
318327
318529
  }
318530
+ if (collapsed && startEntry === endEntry && start.offset === end.offset && resolvedStart === resolvedEnd && projectsOnlyDeletedControls(startMap, resolvedStart, start.offset)) {
318531
+ return buildVisibleSelectionTarget(story, start, end);
318532
+ }
318328
318533
  const [orderedStart, orderedEnd] = start.blockId === end.blockId && resolvedEnd < resolvedStart ? [resolvedEnd, resolvedStart] : [resolvedStart, resolvedEnd];
318329
318534
  return {
318330
318535
  kind: "selection",
@@ -318334,6 +318539,24 @@ function buildSelectionTarget(session, story, start, end, entries2) {
318334
318539
  coordinateSpace: "tracked"
318335
318540
  };
318336
318541
  }
318542
+ function projectsOnlyDeletedControls(map3, trackedOffset, visibleOffset) {
318543
+ let tracked = 0, visible = 0, deletedControl = false;
318544
+ for (const leaf of map3.leaves()) {
318545
+ if (leaf.trackedStart >= trackedOffset)
318546
+ break;
318547
+ const width = Math.min(leaf.trackedEnd, trackedOffset) - leaf.trackedStart;
318548
+ if (width <= 0)
318549
+ continue;
318550
+ if (leaf.trackedEnd - leaf.trackedStart === leaf.visibleEnd - leaf.visibleStart) {
318551
+ visible += width;
318552
+ } else if (leaf.kind === "control" && leaf.deleted && (leaf.control === "tab" || leaf.control === "br" || leaf.control === "cr") && leaf.trackedEnd <= trackedOffset && leaf.visibleStart === leaf.visibleEnd) {
318553
+ deletedControl = true;
318554
+ } else
318555
+ return false;
318556
+ tracked += width;
318557
+ }
318558
+ return deletedControl && tracked === trackedOffset && visible === visibleOffset;
318559
+ }
318337
318560
  function readParagraphInlineMap(session, entry) {
318338
318561
  const bytes = getSDDocumentSessionInternalPartRange(session, entry.partUri, entry.byteStart, entry.byteEnd);
318339
318562
  if (!bytes)
@@ -318400,9 +318623,25 @@ function resolveTableCellSelectionEntries(session, story, anchorBlockId, focusBl
318400
318623
  if (!index || !anchorEntry || index.duplicateParaIds.has(anchorBlockId) || index.duplicateParaIds.has(focusBlockId))
318401
318624
  return null;
318402
318625
  const catalog = readTableCatalogForSession(session, anchorEntry.storyId);
318403
- const anchor = catalog?.byParagraphId.get(anchorBlockId);
318404
- const focus = catalog?.byParagraphId.get(focusBlockId);
318405
- if (!anchor || !focus || anchor.table !== focus.table || anchor.cell === focus.cell)
318626
+ const owner = (blockId) => {
318627
+ const entry = index.byParaId(blockId), enclosing = catalog?.byParagraphId.get(blockId);
318628
+ if (!entry || !enclosing)
318629
+ return null;
318630
+ const table = tableForParagraph({ session }, anchorEntry.storyId, enclosing.table, entry);
318631
+ if (table === enclosing.table)
318632
+ return enclosing;
318633
+ for (const row of table.rows)
318634
+ for (const cell of row.cells) {
318635
+ if (entry.byteStart < cell.bodyByteStart || entry.byteEnd > cell.bodyByteEnd)
318636
+ continue;
318637
+ const paragraph2 = cell.paragraphs.find((candidate2) => candidate2.paragraphId === blockId && candidate2.byteStart === entry.byteStart && candidate2.byteEnd === entry.byteEnd);
318638
+ if (paragraph2)
318639
+ return { table, row, cell, paragraph: paragraph2 };
318640
+ }
318641
+ return null;
318642
+ };
318643
+ const anchor = owner(anchorBlockId), focus = owner(focusBlockId);
318644
+ if (!anchor || !focus || anchor.table.tableNodeId !== focus.table.tableNodeId || anchor.table.tableByteStart !== focus.table.tableByteStart || anchor.table.tableByteEnd !== focus.table.tableByteEnd || anchor.cell.cellNodeId === focus.cell.cellNodeId)
318406
318645
  return null;
318407
318646
  for (const endpoint of [anchor, focus]) {
318408
318647
  if (endpoint.paragraph.isDirectCellChild)
@@ -318512,7 +318751,7 @@ function resolveBrowserLiveSelectionForSession(session, input, options = {}) {
318512
318751
  const resolved = resolveEntries(session, input);
318513
318752
  if (!resolved)
318514
318753
  return null;
318515
- const selectionTarget = buildSelectionTarget(session, input.story, resolved.start, resolved.end, resolved.entries);
318754
+ const selectionTarget = buildSelectionTarget(session, input.story, resolved.start, resolved.end, resolved.entries, input.collapsed === true);
318516
318755
  if (!selectionTarget)
318517
318756
  return null;
318518
318757
  const contiguous = resolved.entries.every((entry, i2) => i2 === 0 || entry.ordinal === resolved.entries[i2 - 1].ordinal + 1);
@@ -318541,7 +318780,7 @@ function resolveBrowserLiveSelectionForSession(session, input, options = {}) {
318541
318780
  }
318542
318781
  function resolveBrowserSelectionReviewIdsForSession(session, input, options = {}) {
318543
318782
  const resolved = resolveEntries(session, input);
318544
- if (!resolved || !buildSelectionTarget(session, input.story, resolved.start, resolved.end, resolved.entries))
318783
+ if (!resolved || !buildSelectionTarget(session, input.story, resolved.start, resolved.end, resolved.entries, input.collapsed === true))
318545
318784
  return null;
318546
318785
  return readActiveReviewIds(session, resolved.entries, resolved.target.segments, options);
318547
318786
  }
@@ -318942,6 +319181,7 @@ var TEXT_DECODER7, ACTIVE_MARK_ORDER;
318942
319181
  var init_live_selection = __esm(() => {
318943
319182
  init_sd_document_session_internal();
318944
319183
  init_sd_document_session_internal();
319184
+ init_xml3();
318945
319185
  init_footnote_range();
318946
319186
  TEXT_DECODER7 = new TextDecoder;
318947
319187
  ACTIVE_MARK_ORDER = ["bold", "italic", "underline", "strikethrough"];
@@ -376707,6 +376947,15 @@ class V2TrackedChangesAdapter {
376707
376947
  const residentViews = new Map;
376708
376948
  let fullView;
376709
376949
  const storyFilter = story ? resolveStoryFilter(story, this.context.session) : undefined;
376950
+ const structuralScope = source?.structuralOwner ? resolveReviewSnapshotStructuralScope(this.context, source, storyFilter) : undefined;
376951
+ if (source?.structuralOwner && !structuralScope)
376952
+ return {
376953
+ requestedIds: [...new Set(requestedIds)],
376954
+ canonicalIds: [],
376955
+ items: [],
376956
+ unresolvedTrackedChangeIds: [...new Set(requestedIds)]
376957
+ };
376958
+ const sourceFilter = source && { ...source, structuralScope: structuralScope ?? undefined };
376710
376959
  const resolveSession = createTrackedChangeFragmentResolveSession();
376711
376960
  const seenInput = new Set;
376712
376961
  const seenCanonical = new Set;
@@ -376725,7 +376974,7 @@ class V2TrackedChangesAdapter {
376725
376974
  if (resident) {
376726
376975
  view = resident;
376727
376976
  for (const requested of requestedIds) {
376728
- if (resolveReviewSnapshotTrackedChangeId(resident, requested, storyFilter, source))
376977
+ if (resolveReviewSnapshotTrackedChangeId(resident, requested, storyFilter, sourceFilter))
376729
376978
  residentViews.set(requested, resident);
376730
376979
  }
376731
376980
  } else
@@ -376733,7 +376982,7 @@ class V2TrackedChangesAdapter {
376733
376982
  }
376734
376983
  const { logical } = view;
376735
376984
  const localEntry = getLocalTrackedTextEntry(this.context, id);
376736
- const entry = localEntry && (!storyFilter || logicalEntryMatchesStoryFilter(localEntry, storyFilter)) && reviewSnapshotEntryMatchesSource(localEntry, source) ? localEntry : resolveReviewSnapshotTrackedChangeId(view, id, storyFilter, source);
376985
+ const entry = localEntry && (!storyFilter || logicalEntryMatchesStoryFilter(localEntry, storyFilter)) && reviewSnapshotEntryMatchesSource(localEntry, sourceFilter, id) ? localEntry : resolveReviewSnapshotTrackedChangeId(view, id, storyFilter, sourceFilter);
376737
376986
  if (!entry) {
376738
376987
  unresolvedTrackedChangeIds.push(id);
376739
376988
  continue;
@@ -376744,6 +376993,13 @@ class V2TrackedChangesAdapter {
376744
376993
  seenCanonical.add(entry.id);
376745
376994
  items.push(buildDiscoveryItem2(entry, this.context, logical, undefined, resolveSession));
376746
376995
  }
376996
+ if (source?.structuralOwner && !reviewSnapshotSourceIsCurrent(this.context, source.structuralOwner))
376997
+ return {
376998
+ requestedIds: orderedRequestedIds,
376999
+ canonicalIds: [],
377000
+ items: [],
377001
+ unresolvedTrackedChangeIds: orderedRequestedIds
377002
+ };
376747
377003
  return { requestedIds: orderedRequestedIds, canonicalIds, items, unresolvedTrackedChangeIds };
376748
377004
  }
376749
377005
  moveFragmentWordIds(requestedIds) {
@@ -379455,6 +379711,26 @@ function addReviewGroupChildRefs(args) {
379455
379711
  function projectFormattingDeltaSummary(entry) {
379456
379712
  if (entry.type !== "formatting")
379457
379713
  return null;
379714
+ const delta = entry.formattingDelta;
379715
+ if (entry.subtype === "run-formatting" && delta) {
379716
+ const value2 = (input) => {
379717
+ if (input === undefined)
379718
+ return "∅";
379719
+ if (input === true)
379720
+ return "on";
379721
+ if (input === false || input === null)
379722
+ return "off";
379723
+ return typeof input === "object" ? JSON.stringify(input) : String(input);
379724
+ };
379725
+ const keys = new Set([...Object.keys(delta.beforeProperties), ...Object.keys(delta.afterProperties)]);
379726
+ const differences = [];
379727
+ for (const key3 of keys) {
379728
+ const before = delta.beforeProperties[key3], after = delta.afterProperties[key3];
379729
+ if (JSON.stringify(before) !== JSON.stringify(after))
379730
+ differences.push(`${key3}: ${value2(before)} → ${value2(after)}`);
379731
+ }
379732
+ return differences.length ? `run formatting revision: ${differences.join(", ")}` : "run formatting revision";
379733
+ }
379458
379734
  return entry.excerpt || null;
379459
379735
  }
379460
379736
  function projectSourceIds(entry) {
@@ -379606,7 +379882,7 @@ function logicalEntriesForSourceAlias(logical, alias) {
379606
379882
  function resolveReviewSnapshotTrackedChangeId(view, requestedId, storyFilter, source) {
379607
379883
  const matches = new Map;
379608
379884
  const add = (entry) => {
379609
- if (!reviewSnapshotEntryMatchesSource(entry, source))
379885
+ if (!reviewSnapshotEntryMatchesSource(entry, source, requestedId))
379610
379886
  return;
379611
379887
  const canonical = resolveReviewSnapshotOwner(view.logical, entry);
379612
379888
  if (!canonical)
@@ -379639,16 +379915,51 @@ function resolveReviewSnapshotOwner(logical, entry) {
379639
379915
  let current = entry;
379640
379916
  while (!seen.has(current.id)) {
379641
379917
  seen.add(current.id);
379642
- const parent = resolveSubsumedLogicalChange(logical, current);
379918
+ const reviewParentId = reviewGroupDisplayParentId(current);
379919
+ const parent = reviewParentId ? logical.byId.get(reviewParentId) : resolveSubsumedLogicalChange(logical, current);
379920
+ if (!parent)
379921
+ return null;
379643
379922
  if (parent.id === current.id)
379644
- return current;
379923
+ return isVisibleLogicalTrackedChange(current) ? current : null;
379924
+ if (parent.storyId !== current.storyId || parent.partUri !== current.partUri)
379925
+ return null;
379926
+ if (reviewParentId && (parent.reviewGroup?.role !== "parent" || parent.reviewGroup.kind !== current.reviewGroup?.kind || !parent.reviewGroup.ownedChildIds.includes(current.id)))
379927
+ return null;
379645
379928
  current = parent;
379646
379929
  }
379647
379930
  return null;
379648
379931
  }
379649
- function reviewSnapshotEntryMatchesSource(entry, source) {
379932
+ function reviewSnapshotEntryMatchesSource(entry, source, requestedId) {
379650
379933
  if (source?.partUri && entry.partUri !== source.partUri)
379651
379934
  return false;
379935
+ if (source?.structuralScope) {
379936
+ const scope = source.structuralScope;
379937
+ const aliases = requestedId ? reviewSnapshotRequestedIdAliases(requestedId) : [];
379938
+ const structural = entry.structuralFragments.some((fragment4) => {
379939
+ if (fragment4.partUri !== scope.partUri || fragment4.storyId !== scope.storyId || requestedId !== entry.id && ![fragment4.wId, fragment4.entityKey, fragment4.rsid, fragment4.enclosingParagraphRsid].some((alias) => alias != null && aliases.includes(alias)))
379940
+ return false;
379941
+ if (source.structuralOwner?.author != null && fragment4.author.name !== source.structuralOwner.author || source.structuralOwner?.date != null && fragment4.date !== source.structuralOwner.date)
379942
+ return false;
379943
+ if (!fragment4.structuralKind.startsWith(`${scope.kind}-`))
379944
+ return false;
379945
+ if (source.kind === "insert" && !fragment4.structuralKind.endsWith("-insertion") || source.kind === "delete" && !fragment4.structuralKind.endsWith("-deletion") || source.kind === "format" && /-(?:insertion|deletion)$/.test(fragment4.structuralKind))
379946
+ return false;
379947
+ const { sourceByteStart: start, sourceByteEnd: end } = fragment4;
379948
+ if (start == null || end == null || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end <= start)
379949
+ return false;
379950
+ return start >= scope.start && end <= scope.propertiesEnd || start <= scope.start && end >= scope.end;
379951
+ });
379952
+ const properties2 = scope.kind === "cell" && source.kind !== "insert" && source.kind !== "delete" && entry.formattingFragments.some((fragment4) => {
379953
+ if (fragment4.subtype !== "cell" || fragment4.partUri !== scope.partUri || fragment4.storyId !== scope.storyId || requestedId !== entry.id && ![fragment4.wId, fragment4.entityKey].some((alias) => alias != null && aliases.includes(alias)))
379954
+ return false;
379955
+ if (source.structuralOwner?.author != null && fragment4.author.name !== source.structuralOwner.author || source.structuralOwner?.date != null && fragment4.date !== source.structuralOwner.date)
379956
+ return false;
379957
+ const { sourceByteStart: start, sourceByteEnd: end } = fragment4;
379958
+ return start != null && end != null && Number.isSafeInteger(start) && Number.isSafeInteger(end) && start >= scope.start && end > start && end <= scope.propertiesEnd;
379959
+ });
379960
+ if (entry.storyId !== scope.storyId || entry.partUri !== scope.partUri || !structural && !properties2)
379961
+ return false;
379962
+ }
379652
379963
  if (!source?.kind)
379653
379964
  return true;
379654
379965
  if (source.kind === "format")
@@ -379656,6 +379967,31 @@ function reviewSnapshotEntryMatchesSource(entry, source) {
379656
379967
  const insertion = source.kind === "insert";
379657
379968
  return entry.fragments.some((fragment4) => insertion ? fragment4.kind === "ins" || fragment4.kind === "moveTo" : fragment4.kind === "del" || fragment4.kind === "moveFrom") || entry.structuralFragments.some((fragment4) => fragment4.structuralKind.endsWith(insertion ? "-insertion" : "-deletion"));
379658
379969
  }
379970
+ function reviewSnapshotSourceIsCurrent(context, owner) {
379971
+ const current = getSDDocumentSessionInternalSourceCommit(context.session);
379972
+ return current.documentEpoch === owner.documentEpoch && current.commitSequence === owner.commitSequence && String(getSDDocumentSessionInternalPackageRevision(context.session)) === owner.packageRevision;
379973
+ }
379974
+ function resolveReviewSnapshotStructuralScope(context, source, story) {
379975
+ const owner = source.structuralOwner;
379976
+ if (!owner || !source.partUri || !reviewSnapshotSourceIsCurrent(context, owner) || !owner.tableNodeId || !Number.isSafeInteger(owner.commitSequence) || owner.commitSequence < 0 || !Number.isSafeInteger(owner.rowIndex) || owner.rowIndex < 0 || owner.cellIndex != null && (!Number.isSafeInteger(owner.cellIndex) || owner.cellIndex < 0))
379977
+ return null;
379978
+ const matches = listSDDocumentSessionInternalStories(context.session).flatMap((candidate2) => {
379979
+ const { storyId, partUri: partUri2 } = candidate2;
379980
+ if (partUri2 !== source.partUri || story?.kind === "body-only" && !isBodyStoryId2(storyId) || story?.kind === "specific" && !story.storyIds?.has(storyId))
379981
+ return [];
379982
+ const catalog = readTableCatalogForSession(context.session, storyId);
379983
+ return (catalog?.tables ?? []).filter((table2) => table2.tableNodeId === owner.tableNodeId).map((table2) => ({ table: table2, partUri: partUri2 }));
379984
+ });
379985
+ if (matches.length !== 1)
379986
+ return null;
379987
+ const { table, partUri } = matches[0];
379988
+ const row = table.rows[owner.rowIndex];
379989
+ const cell = owner.cellIndex != null ? row?.cells[owner.cellIndex] : undefined;
379990
+ if (!row || owner.cellIndex != null && !cell)
379991
+ return null;
379992
+ const common = { storyId: table.storyId, partUri };
379993
+ return cell ? { ...common, kind: "cell", start: cell.cellByteStart, end: cell.cellByteEnd, propertiesEnd: cell.bodyByteStart } : { ...common, kind: "row", start: row.rowByteStart, end: row.rowByteEnd, propertiesEnd: row.cells[0]?.cellByteStart ?? row.rowBodyByteEnd };
379994
+ }
379659
379995
  function resolveWordSourceTrackedChangeId(view, requestedId) {
379660
379996
  const matches = new Map;
379661
379997
  for (const alias of reviewSnapshotRequestedIdAliases(requestedId)) {
@@ -462708,6 +463044,33 @@ function emissionContext(owner, xml) {
462708
463044
  return cached2.context;
462709
463045
  }
462710
463046
  function materializeProjection(input) {
463047
+ return materializeProjectionInternal(input);
463048
+ }
463049
+ function materializeDeletedTableSourceProjection(input) {
463050
+ const manifest = readRoomManifest(input.rootDoc);
463051
+ if (!manifest.snapshot || manifest.diagnostics.length)
463052
+ throw new Error("deleted-table source requires its valid room manifest");
463053
+ for (const handle of input.shardRegistry.listStories()) {
463054
+ if (handle.rootDoc !== input.rootDoc || input.rootDoc.getMap("content").get(handle.shardId) !== handle.scope || handle.bootstrap?.sourcePackageSha256 !== manifest.snapshot.meta.createdFrom.sha256Zip) {
463055
+ throw new Error("deleted-table source does not belong to this room and original package");
463056
+ }
463057
+ }
463058
+ const recovery = { count: 0 };
463059
+ const output = materializeProjectionInternal({ ...input, previousRecord: null }, recovery);
463060
+ if (recovery.count === 0)
463061
+ throw new Error("no recoverable deleted-table source");
463062
+ for (const story of output.record.stories) {
463063
+ const parsed = collectXmlElementRanges(story.xml);
463064
+ const handle = input.shardRegistry.listStories().find((handle2) => snapshotStoryShard(shardReadTarget(handle2)).meta.storyId === story.storyId);
463065
+ const live = handle ? snapshotStoryShard(shardReadTarget(handle)).blocks.map((block) => block.blockId) : [];
463066
+ const ids = parsed.ranges.filter((range) => range.tag.namespaceUri === WORD_NAMESPACE10 && range.tag.localName === "p").map((range) => range.tag.attributes.find((attribute3) => attribute3.namespaceUri === "http://schemas.microsoft.com/office/word/2010/wordml" && attribute3.localName === "paraId")?.value);
463067
+ if (parsed.errors.length || ids.length !== live.length || ids.some((id2, index2) => id2 !== live[index2])) {
463068
+ throw new Error("deleted-table source does not preserve the complete current paragraph order");
463069
+ }
463070
+ }
463071
+ return output;
463072
+ }
463073
+ function materializeProjectionInternal(input, recovery) {
462711
463074
  const readStorySnapshot = input.readStorySnapshot ?? snapshotStoryShard;
462712
463075
  const previousById = new Map;
462713
463076
  const previousByPartUri = new Map;
@@ -462836,7 +463199,11 @@ function materializeProjection(input) {
462836
463199
  continue;
462837
463200
  }
462838
463201
  const sourceXmlByteAligned = isByteAlignedSourceXml(bootstrap);
462839
- const tableReplacements = readTableStructuralReplacements(readTarget);
463202
+ let tableReplacements = readTableStructuralReplacements(readTarget);
463203
+ if (recovery && tableReplacements.some((table) => table.tableNodeId !== table.entryKey)) {
463204
+ tableReplacements = recoverDeletedTableReplacements(handle, bootstrap, tableReplacements);
463205
+ recovery.count += 1;
463206
+ }
462840
463207
  const previousBlockIndex = previous3 ? blockDigestIndex(previous3.blockDigests) : null;
462841
463208
  const insertedBlockHint = previousBlockIndex && [...dirtyStoryBlocks.get(handle.shardId) ?? []].some((blockId) => !previousBlockIndex.has(blockId));
462842
463209
  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;
@@ -464110,6 +464477,73 @@ function remapTableStructuralOverlaysAfterStoryXmlPatch(input) {
464110
464477
  };
464111
464478
  });
464112
464479
  }
464480
+ function recoverDeletedTableReplacements(handle, bootstrap, replacements) {
464481
+ const source = bootstrap?.sourceXml;
464482
+ if (!source)
464483
+ throw new Error("deleted-table source requires its original package");
464484
+ const parsed = collectXmlElementRanges(source);
464485
+ if (parsed.errors.length)
464486
+ throw new Error("deleted-table source has invalid original XML");
464487
+ const target = shardReadTarget(handle);
464488
+ const snapshot3 = snapshotStoryShard(target);
464489
+ const live = new Set(snapshot3.blocks.map((block) => block.blockId));
464490
+ const tables2 = getStoryTablesMap(target);
464491
+ if (tables2.size !== replacements.length || live.size !== snapshot3.blocks.length) {
464492
+ throw new Error("deleted-table source has ambiguous owners");
464493
+ }
464494
+ const allowedKeys = new Set([
464495
+ "tableNodeId",
464496
+ "storyId",
464497
+ "partUri",
464498
+ "lastPreparedTxId",
464499
+ "lastDeltaKind",
464500
+ "xml",
464501
+ "sourceXmlStart",
464502
+ "sourceXmlEnd",
464503
+ "sourceByteStart",
464504
+ "sourceByteEnd",
464505
+ "affectedRows",
464506
+ "affectedCells",
464507
+ "affectedBlocks",
464508
+ "tableBlocks",
464509
+ "nonTableAffectedBlocks"
464510
+ ]);
464511
+ const entries4 = replacements.map((table) => {
464512
+ const raw = tables2.get(table.entryKey);
464513
+ const span = findUniqueTableSpanFromTableNodeId(source, table.entryKey);
464514
+ if (!isYMap(raw) || !span || [...raw.keys()].some((key3) => !allowedKeys.has(key3)) || raw.get("storyId") !== snapshot3.meta.storyId || raw.get("partUri") !== snapshot3.meta.sourcePartUri || table.deltaKind !== "table.rewrite" || table.xml !== "" || !table.lastPreparedTxId || table.tableBlockIds.length || table.nonTableAffectedBlockIds.length) {
464515
+ throw new Error("deleted-table source has an unsupported tombstone");
464516
+ }
464517
+ for (const key3 of ["affectedRows", "affectedCells", "affectedBlocks", "tableBlocks", "nonTableAffectedBlocks"]) {
464518
+ const membership = raw.get(key3);
464519
+ if (!(membership instanceof YArray))
464520
+ throw new Error("deleted-table source has malformed membership");
464521
+ const values2 = membership.toArray();
464522
+ if (values2.some((value2) => typeof value2 !== "string" || value2.length === 0) || new Set(values2).size !== values2.length) {
464523
+ throw new Error("deleted-table source has malformed membership");
464524
+ }
464525
+ }
464526
+ const paragraphs2 = parsed.ranges.filter((range) => range.tag.namespaceUri === WORD_NAMESPACE10 && range.tag.localName === "p" && range.start > span.start && range.end < span.end);
464527
+ const ids = paragraphs2.map((paragraph4) => paragraph4.tag.attributes.find((attribute3) => attribute3.namespaceUri === "http://schemas.microsoft.com/office/word/2010/wordml" && attribute3.localName === "paraId")?.value);
464528
+ const affected = new Set(table.affectedBlockIds);
464529
+ if (!ids.length || ids.some((id2) => !id2 || !affected.has(id2) || live.has(id2)) || new Set(ids).size !== ids.length || affected.size !== ids.length || affected.size !== table.affectedBlockIds.length || snapshot3.blocks.some((block) => block.structuralRefs.tableNodeId === table.entryKey)) {
464530
+ throw new Error("deleted-table source does not prove complete removed membership");
464531
+ }
464532
+ return { table, raw, span };
464533
+ }).sort((a, b) => a.span.start - b.span.start);
464534
+ let removedBytes = 0;
464535
+ let previousEnd = 0;
464536
+ return entries4.map(({ table, raw, span }) => {
464537
+ const start = UTF8_ENCODER3.encode(source.slice(0, span.start)).length - removedBytes;
464538
+ const length3 = UTF8_ENCODER3.encode(source.slice(span.start, span.end)).length;
464539
+ if (span.start < previousEnd || raw.get("sourceByteStart") !== start || raw.get("sourceByteEnd") !== start + length3) {
464540
+ throw new Error("deleted-table source byte ownership does not match its serial deletions");
464541
+ }
464542
+ previousEnd = span.end;
464543
+ removedBytes += length3;
464544
+ return { ...table, tableNodeId: table.entryKey, sourceXmlStart: span.start, sourceXmlEnd: span.end };
464545
+ });
464546
+ }
464113
464547
  function removeRedundantSplitSeparators(projection, redundantBlockIds) {
464114
464548
  const entries4 = [...projection.blockDigests];
464115
464549
  const changedIndices = [];
@@ -465578,7 +466012,7 @@ function readTableSplitChildren(table) {
465578
466012
  function readTableStructuralReplacements(target) {
465579
466013
  const out = [];
465580
466014
  let liveBlockIds;
465581
- getStoryTablesMap(target).forEach((value2) => {
466015
+ getStoryTablesMap(target).forEach((value2, entryKey2) => {
465582
466016
  if (!isYMap(value2))
465583
466017
  return;
465584
466018
  const tableNodeId = value2.get("tableNodeId");
@@ -465628,6 +466062,7 @@ function readTableStructuralReplacements(target) {
465628
466062
  return;
465629
466063
  }
465630
466064
  out.push({
466065
+ entryKey: entryKey2,
465631
466066
  tableNodeId,
465632
466067
  lastPreparedTxId,
465633
466068
  sourceXmlStart: start,
@@ -466867,6 +467302,7 @@ var init_materialize = __esm(() => {
466867
467302
  init_content_control_groups();
466868
467303
  init_scope3();
466869
467304
  init_safety();
467305
+ init_read2();
466870
467306
  init_canonical();
466871
467307
  init_package_xml();
466872
467308
  init_reorder_story_owners();
@@ -467172,6 +467608,7 @@ var init_freshness = __esm(() => {
467172
467608
  "selection.extractOoxml",
467173
467609
  "search",
467174
467610
  "blocks.list",
467611
+ "render.source",
467175
467612
  "lists.getState",
467176
467613
  "tables.list",
467177
467614
  "tables.get",
@@ -467468,6 +467905,24 @@ function createCollabV2ProjectionRuntime(options) {
467468
467905
  diagnostics = [];
467469
467906
  return snapshot3();
467470
467907
  }
467908
+ function recoverDeletedTableSource() {
467909
+ ensureNotDisposed();
467910
+ const token = captureProjectionSnapshot({
467911
+ rootDoc: options.rootDoc,
467912
+ shardRegistry: options.shardRegistry,
467913
+ journalAcceptsMinor: options.journalAcceptsMinor,
467914
+ blobCompletenessProbe: options.blobCompletenessProbe
467915
+ });
467916
+ if (token.journalCompleteness !== "ok" || options.shardRegistry.requiredShardIds().some((id2) => !options.shardRegistry.get(id2))) {
467917
+ throw new Error("deleted-table source requires complete current collaboration owners");
467918
+ }
467919
+ return materializeDeletedTableSourceProjection({
467920
+ snapshotToken: token,
467921
+ rootDoc: options.rootDoc,
467922
+ shardRegistry: options.shardRegistry,
467923
+ dirty: pendingDirty
467924
+ }).record;
467925
+ }
467471
467926
  async function runBarrier(request) {
467472
467927
  ensureNotDisposed();
467473
467928
  const capturedToken = captureProjectionSnapshot({
@@ -467673,6 +468128,7 @@ function createCollabV2ProjectionRuntime(options) {
467673
468128
  addDirty(dirtyScopesFromPackageBatch(batch2));
467674
468129
  },
467675
468130
  refresh,
468131
+ recoverDeletedTableSource,
467676
468132
  runBarrier,
467677
468133
  markCollabMutation() {
467678
468134
  hasCollabMutation = true;
@@ -470476,12 +470932,7 @@ function trackedStoryTextRequiresMergedCarrierSync(validation) {
470476
470932
  const authorsText = validation.trackedInsert != null || validation.trackedInsertContinuation === true || (validation.trackedRefinement?.metadata.insertedText.length ?? 0) > 0;
470477
470933
  if (!authorsText && validation.trackedRefinement?.usesMergedCarrier !== true)
470478
470934
  return false;
470479
- const ordered = listOrderedBlocks(validation.target.scope);
470480
- const index2 = ordered.findIndex((entry) => entry.blockId === validation.target.blockId);
470481
- const head = ordered[index2]?.block;
470482
- if (!head || head.get(BLOCK_KEY.mergedIntoBlockId))
470483
- return false;
470484
- return ordered[index2 + 1]?.block.get(BLOCK_KEY.mergedIntoBlockId) === validation.target.blockId;
470935
+ return readLogicalBlockChain(validation.target.scope, validation.target.blockId).length > 1;
470485
470936
  }
470486
470937
  function createStorySurfaceExecutionBackend(options) {
470487
470938
  const delegate = options.delegate;
@@ -471945,12 +472396,26 @@ function tryMirrorStoryText(prepared, extension2, options, admitted) {
471945
472396
  const trackedInsert = validation.trackedInsert;
471946
472397
  if (!trackedInsert) {
471947
472398
  if (validation.trackedInsertContinuation) {
472399
+ const span = validation.trackedInsertContinuationSpan;
472400
+ if (!span)
472401
+ throw new Error("tracked continuation is missing its owning insertion");
472402
+ const start = getBlockAtoms(target.block).toArray().find((atom) => atom.get(ATOM_KEY.id) === span.startAtomId);
472403
+ if (!start)
472404
+ throw new Error("tracked continuation lost its owning insertion");
472405
+ const offset = validation.trackedInsertOffset ?? source.on.startOffset;
471948
472406
  insertTextAtResolvedTarget({
471949
472407
  target,
471950
- offset: validation.trackedInsertOffset ?? source.on.startOffset,
472408
+ offset,
471951
472409
  text: source.newText,
471952
472410
  origin: STORY_SURFACE_BACKEND_ORIGIN
471953
472411
  });
472412
+ if (offset === span.startOffset) {
472413
+ start.set(ATOM_KEY.visibleOffset, offset);
472414
+ getBlockAnchors(target.block).forEach((anchor) => {
472415
+ if (anchor.get(ANCHOR_KEY.id) === span.startAtomId)
472416
+ anchor.set(ANCHOR_KEY.visibleOffset, offset);
472417
+ });
472418
+ }
471954
472419
  return;
471955
472420
  }
471956
472421
  throw new Error("tracked storyText mirror missing typed insert metadata");
@@ -472250,7 +472715,7 @@ function validateDirectStoryText(prepared, extension2, options) {
472250
472715
  return { ok: false, failureReason: atomFailureReason };
472251
472716
  }
472252
472717
  }
472253
- return {
472718
+ const validation = {
472254
472719
  ok: true,
472255
472720
  source,
472256
472721
  doc: doc2,
@@ -472264,6 +472729,19 @@ function validateDirectStoryText(prepared, extension2, options) {
472264
472729
  ...validatedTrackedRefinement ? { trackedRefinement: validatedTrackedRefinement } : {},
472265
472730
  ...trackedEdit?.ok ? { trackedEdit: trackedEdit.trackedEdit } : {}
472266
472731
  };
472732
+ if (trackedInsertContinuation && !trackedStoryTextRequiresMergedCarrierSync(validation)) {
472733
+ const updated = prepared.semanticDelta.updatedRefs.filter((ref5) => ref5.kind === "trackedChange");
472734
+ if (updated.length !== 1 || String(updated[0].storyId) !== sourceStoryId) {
472735
+ return { ok: false, failureReason: "tracked continuation requires one updated insertion identity" };
472736
+ }
472737
+ const offset = trackedInsertOffset ?? source.on.startOffset;
472738
+ const spans = collectLiveTrackedTextSpansInBlock(hydratedBlock, updated[0].entityId, "ins").filter((span) => span.startOffset <= offset && offset <= span.endOffset);
472739
+ if (spans.length !== 1) {
472740
+ return { ok: false, failureReason: "tracked continuation could not resolve its owning insertion" };
472741
+ }
472742
+ return { ...validation, trackedInsertContinuationSpan: spans[0] };
472743
+ }
472744
+ return validation;
472267
472745
  }
472268
472746
  function storyIdsRequiringShards(prepared, extension2, resolveStoryShard) {
472269
472747
  if (extension2.family === "storyText" && prepared.source.kind === "editText") {
@@ -474015,7 +474493,14 @@ function createCollabV2SessionProjectionController(options) {
474015
474493
  return { ok: true };
474016
474494
  return remoteProjectionPending ? refreshCleanRecord() : synchronizeSessionFromRuntime();
474017
474495
  }
474018
- return refreshCleanRecord();
474496
+ const result = refreshCleanRecord();
474497
+ if (result.ok || operationId !== "render.source")
474498
+ return result;
474499
+ try {
474500
+ return synchronizeSessionFromRuntime({ sourceRecord: runtime.recoverDeletedTableSource() });
474501
+ } catch {
474502
+ return result;
474503
+ }
474019
474504
  }
474020
474505
  function ingestRoomAuthoritativeInitialDirty() {
474021
474506
  for (const handle of options.projectionRegistry.listStories()) {
@@ -474040,10 +474525,10 @@ function createCollabV2SessionProjectionController(options) {
474040
474525
  };
474041
474526
  }
474042
474527
  const state = runtime.state;
474043
- if (state.freshness !== "clean") {
474528
+ if (!input.sourceRecord && state.freshness !== "clean") {
474044
474529
  return projectionStateFailure(state.blockingReason);
474045
474530
  }
474046
- const record3 = runtime.lastCleanRecord();
474531
+ const record3 = input.sourceRecord ?? runtime.lastCleanRecord();
474047
474532
  if (!record3) {
474048
474533
  return {
474049
474534
  ok: false,
@@ -480252,6 +480737,7 @@ async function buildCanonicalShardGraph(input) {
480252
480737
  shardId: storyShardId2(input.runtime.rootId, story.storyKind, story.partUri),
480253
480738
  bytes: readCompletePartBytes(input.session, sourceOpen, story.partUri)
480254
480739
  }));
480740
+ const sourcePackageSha256 = sha256Hex2(input.sourceBuffer);
480255
480741
  for (const { story, shardId, bytes } of stories) {
480256
480742
  let unit;
480257
480743
  if (maySeedStoryShardsFromLocalSource && bytes) {
@@ -480283,7 +480769,7 @@ async function buildCanonicalShardGraph(input) {
480283
480769
  doc: rootDoc,
480284
480770
  rootDoc,
480285
480771
  scope: unit.scope,
480286
- ...storyBootstrap ? { bootstrap: storyBootstrap } : {}
480772
+ ...storyBootstrap ? { bootstrap: { ...storyBootstrap, sourcePackageSha256 } } : {}
480287
480773
  };
480288
480774
  storyHandles.set(shardId, handle);
480289
480775
  storyHandlesByStoryId.set(story.storyId, handle);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superdoc/mcp",
3
- "version": "1.9.0-next.5",
3
+ "version": "1.9.0-next.7",
4
4
  "description": "Model Context Protocol server for SuperDoc, giving an AI agent tools to read and edit .docx files.",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0",
@@ -24,13 +24,13 @@
24
24
  ],
25
25
  "dependencies": {
26
26
  "@modelcontextprotocol/sdk": "^1.26.0",
27
- "@superdoc/sdk": "2.22.0-next.5",
27
+ "@superdoc/sdk": "2.22.0-next.7",
28
28
  "debug": "^4.4.3",
29
29
  "zod": "^4.3.6"
30
30
  },
31
31
  "devDependencies": {
32
- "superdoc": "2.25.0-next.5",
33
- "@superdoc/docx-engine": "0.24.0-next.5",
32
+ "superdoc": "2.25.0-next.7",
33
+ "@superdoc/docx-engine": "0.24.0-next.7",
34
34
  "@superdoc/document-api": "0.1.0-alpha.0",
35
35
  "@types/bun": "^1.3.8",
36
36
  "@types/node": "22.19.2",