@yudaocode/univer-docs 1.6.215 → 1.6.217

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -65,6 +65,7 @@ __export(src_exports, {
65
65
  DocIoService: () => DocIoService,
66
66
  DocIoTargetError: () => DocIoTargetError,
67
67
  DocSdtService: () => DocSdtService,
68
+ DocTemplateProtocolError: () => DocTemplateProtocolError,
68
69
  DocxImportError: () => DocxImportError,
69
70
  EvaluateDocCascadeRulesCommand: () => EvaluateDocCascadeRulesCommand,
70
71
  EvaluateDocTableFormulasCommand: () => EvaluateDocTableFormulasCommand,
@@ -76,6 +77,7 @@ __export(src_exports, {
76
77
  IDocExtensionRegistryService: () => IDocExtensionRegistryService,
77
78
  IDocIoService: () => IDocIoService,
78
79
  IDocSdtService: () => IDocSdtService,
80
+ INLINE_VALUE_TOKEN_RE: () => INLINE_VALUE_TOKEN_RE,
79
81
  InsertDocAreaCommand: () => InsertDocAreaCommand,
80
82
  InsertDocBibliographyCommand: () => InsertDocBibliographyCommand,
81
83
  InsertDocBookmarkCommand: () => InsertDocBookmarkCommand,
@@ -222,6 +224,7 @@ __export(src_exports, {
222
224
  computeToggledMultiOptionValue: () => computeToggledMultiOptionValue,
223
225
  convertDocTableToText: () => convertDocTableToText,
224
226
  convertTextToDocTableInSnapshot: () => convertTextToDocTableInSnapshot,
227
+ createDocAbortError: () => createDocAbortError,
225
228
  decodeImageDataUrlForPdf: () => decodeImageDataUrlForPdf,
226
229
  deleteColumnGroupFromSnapshot: () => deleteColumnGroupFromSnapshot,
227
230
  deleteDocArea: () => deleteDocAreaFromSnapshot,
@@ -263,7 +266,10 @@ __export(src_exports, {
263
266
  extractAnchorTypography: () => extractAnchorTypography,
264
267
  extractDocCatalog: () => extractDocCatalog,
265
268
  extractDocCatalogTree: () => extractDocCatalogTree,
269
+ extractDocFieldInstruction: () => extractDocFieldInstruction,
266
270
  extractDocFormValues: () => extractDocFormValues,
271
+ extractDocInlinePlaceholders: () => extractDocInlinePlaceholders,
272
+ extractNativeTextSpansFromPdfBytes: () => extractNativeTextSpansFromPdfBytes,
267
273
  fillDatasetIntoDocSnapshot: () => fillDatasetIntoDocSnapshot,
268
274
  findAndReplaceDocTextInSnapshot: () => findAndReplaceDocTextInSnapshot,
269
275
  findMergedMasterInTableRows: () => findMergedMasterInTableRows,
@@ -355,6 +361,7 @@ __export(src_exports, {
355
361
  insertSyntaxCodeBlockIntoSnapshot: () => insertSyntaxCodeBlockIntoSnapshot,
356
362
  insertTableOfContentsIntoSnapshot: () => insertTableOfContentsIntoSnapshot,
357
363
  inspectDocxExportCapabilities: () => inspectDocxExportCapabilities,
364
+ isDynamicPageFieldInstruction: () => isDynamicPageFieldInstruction,
358
365
  isEditBlockedByTitleLock: () => isEditBlockedByTitleLock,
359
366
  isOffsetInLockedTableCell: () => isOffsetInLockedTableCell,
360
367
  isOffsetLockedByGroupSdt: () => isOffsetLockedByGroupSdt,
@@ -385,6 +392,7 @@ __export(src_exports, {
385
392
  normalizeSdtListItems: () => normalizeSdtListItems,
386
393
  numberToChineseUpperMoney: () => numberToChineseUpperMoney,
387
394
  parseDateRangePair: () => parseDateRangePair,
395
+ parseDocBindingKey: () => parseDocBindingKey,
388
396
  parseDocxBytesToDocData: () => parseDocxBytesToDocData,
389
397
  parseDocxBytesWithReport: () => parseDocxBytesWithReport,
390
398
  parseFieldInstrString: () => parseFieldInstrString,
@@ -478,6 +486,7 @@ __export(src_exports, {
478
486
  splitDocTableCellInSnapshot: () => splitDocTableCellInSnapshot,
479
487
  stripDocEditorChromeForView: () => stripDocEditorChromeForView,
480
488
  stripSdtAffixes: () => stripSdtAffixes,
489
+ summarizeDocTemplate: () => summarizeDocTemplate,
481
490
  syncDocDrawingsToUniverServices: () => syncDocDrawingsToUniverServices,
482
491
  syncSnapshotAuxFields: () => syncSnapshotAuxFields,
483
492
  toControlSpecSnapshot: () => toControlSpecSnapshot,
@@ -515,6 +524,15 @@ var import_core13 = require("@univerjs/core");
515
524
  // src/types/doc-sdt.ts
516
525
  var YUDAO_DOCS_TEMPLATE_RESOURCE = "YUDAO_DOCS_TEMPLATE_RESOURCE";
517
526
  var DOC_DRAWING_PLUGIN_RESOURCE = "DOC_DRAWING_PLUGIN";
527
+ var DocTemplateProtocolError = class extends Error {
528
+ constructor(code, message, details) {
529
+ super(message);
530
+ this.name = "DocTemplateProtocolError";
531
+ this.code = code;
532
+ this.tableId = details?.tableId;
533
+ this.rowIndex = details?.rowIndex;
534
+ }
535
+ };
518
536
 
519
537
  // src/utils/doc-medical-and-blocks.ts
520
538
  var import_core = require("@univerjs/core");
@@ -8532,9 +8550,9 @@ function paginateSingleDocToPdfPages(rawSnapshot, options, imageNamePrefix = "Im
8532
8550
  );
8533
8551
  ops.push("Q");
8534
8552
  };
8535
- const renderTokensRowAt = (ops, tokens, startX, baselineY) => {
8553
+ const renderTokensRowAt = (ops, tokens, startX, baselineY, explicitPageIndex) => {
8536
8554
  let tokX = startX;
8537
- const curPageIndex = pageStreams.length - 1;
8555
+ const curPageIndex = explicitPageIndex ?? pageStreams.length - 1;
8538
8556
  for (const tok of tokens) {
8539
8557
  if (tok.bookmarkNames?.length) {
8540
8558
  for (const bmName of tok.bookmarkNames) {
@@ -8550,7 +8568,7 @@ function paginateSingleDocToPdfPages(rawSnapshot, options, imageNamePrefix = "Im
8550
8568
  continue;
8551
8569
  }
8552
8570
  }
8553
- if (tok.noteRefEntry && tok.noteRefEntry.noteType === "footnote") {
8571
+ if (explicitPageIndex === void 0 && tok.noteRefEntry && tok.noteRefEntry.noteType === "footnote") {
8554
8572
  if (!emittedFootnoteIds.has(tok.noteRefEntry.id)) {
8555
8573
  emittedFootnoteIds.add(tok.noteRefEntry.id);
8556
8574
  currentPageFootnotes.push(tok.noteRefEntry);
@@ -9618,7 +9636,285 @@ function paginateSingleDocToPdfPages(rawSnapshot, options, imageNamePrefix = "Im
9618
9636
  }
9619
9637
  return String(num);
9620
9638
  };
9639
+ const toRomanPageNumber = (num, upper) => {
9640
+ if (num <= 0 || num >= 4e3) return String(num);
9641
+ const pairs = [
9642
+ [1e3, "M"],
9643
+ [900, "CM"],
9644
+ [500, "D"],
9645
+ [400, "CD"],
9646
+ [100, "C"],
9647
+ [90, "XC"],
9648
+ [50, "L"],
9649
+ [40, "XL"],
9650
+ [10, "X"],
9651
+ [9, "IX"],
9652
+ [5, "V"],
9653
+ [4, "IV"],
9654
+ [1, "I"]
9655
+ ];
9656
+ let rem = Math.floor(num);
9657
+ let out = "";
9658
+ for (const [val, sym] of pairs) {
9659
+ while (rem >= val) {
9660
+ out += sym;
9661
+ rem -= val;
9662
+ }
9663
+ }
9664
+ return upper ? out : out.toLowerCase();
9665
+ };
9621
9666
  const fmtPgToken = (num) => pageNumberType === "chinese" ? toChinesePageNumber(num) : String(num);
9667
+ const formatDynamicFieldPageNumber = (num, rawInstr) => {
9668
+ if (/\\?\*\s*ROMAN\b/.test(rawInstr)) return toRomanPageNumber(num, true);
9669
+ if (/\\?\*\s*roman\b/.test(rawInstr)) return toRomanPageNumber(num, false);
9670
+ if (/\\?\*\s*CHINESENUM/i.test(rawInstr)) return toChinesePageNumber(num);
9671
+ if (/\\?\*\s*ARABIC\b/i.test(rawInstr)) return String(num);
9672
+ return fmtPgToken(num);
9673
+ };
9674
+ const docStyle = snapshot.documentStyle ?? {};
9675
+ const useFirstPageHf = docStyle.useFirstPageHeaderFooter === import_core6.BooleanNumber.TRUE;
9676
+ const useEvenOddHf = docStyle.evenAndOddHeaders === import_core6.BooleanNumber.TRUE;
9677
+ const resolvePageHeaderBody = (pageIndex) => {
9678
+ const hdrs = snapshot.headers;
9679
+ if (!hdrs) return void 0;
9680
+ if (pageIndex === 0 && useFirstPageHf) {
9681
+ const firstId = docStyle.firstPageHeaderId;
9682
+ return (firstId ? hdrs[firstId]?.body : void 0) ?? hdrs.firstPageHeader?.body;
9683
+ }
9684
+ if (useEvenOddHf && (pageIndex + 1) % 2 === 0) {
9685
+ const evenId = docStyle.evenPageHeaderId;
9686
+ const evenBody = (evenId ? hdrs[evenId]?.body : void 0) ?? hdrs.evenPageHeader?.body;
9687
+ if (evenBody) return evenBody;
9688
+ }
9689
+ const defId = docStyle.defaultHeaderId;
9690
+ if (defId && hdrs[defId]?.body) return hdrs[defId].body;
9691
+ if (hdrs.defaultHeader?.body) return hdrs.defaultHeader.body;
9692
+ const fallbackKey = Object.keys(hdrs).find(
9693
+ (k) => k !== "firstPageHeader" && k !== "evenPageHeader"
9694
+ );
9695
+ return fallbackKey ? hdrs[fallbackKey]?.body : Object.values(hdrs)[0]?.body;
9696
+ };
9697
+ const resolvePageFooterBody = (pageIndex) => {
9698
+ const ftrs = snapshot.footers;
9699
+ if (!ftrs) return void 0;
9700
+ if (pageIndex === 0 && useFirstPageHf) {
9701
+ const firstId = docStyle.firstPageFooterId;
9702
+ return (firstId ? ftrs[firstId]?.body : void 0) ?? ftrs.firstPageFooter?.body;
9703
+ }
9704
+ if (useEvenOddHf && (pageIndex + 1) % 2 === 0) {
9705
+ const evenId = docStyle.evenPageFooterId;
9706
+ const evenBody = (evenId ? ftrs[evenId]?.body : void 0) ?? ftrs.evenPageFooter?.body;
9707
+ if (evenBody) return evenBody;
9708
+ }
9709
+ const defId = docStyle.defaultFooterId;
9710
+ if (defId && ftrs[defId]?.body) return ftrs[defId].body;
9711
+ if (ftrs.defaultFooter?.body) return ftrs.defaultFooter.body;
9712
+ const fallbackKey = Object.keys(ftrs).find(
9713
+ (k) => k !== "firstPageFooter" && k !== "evenPageFooter"
9714
+ );
9715
+ return fallbackKey ? ftrs[fallbackKey]?.body : Object.values(ftrs)[0]?.body;
9716
+ };
9717
+ const materializeHeaderFooterPageFields = (rawStoryBody, logicalPageNo, totalPageCount) => {
9718
+ let nextBody = import_core6.Tools.deepClone(rawStoryBody);
9719
+ const dynamicRanges = [...nextBody.customRanges ?? []].map((r) => ({ range: r, instr: extractDocFieldInstruction(r) })).filter((item) => {
9720
+ if (!item.instr) return false;
9721
+ const firstTok = (item.instr.trim().replace(/^\\+/, "").split(/[\s\\]+/)[0] || "").toUpperCase();
9722
+ return firstTok === "PAGE" || firstTok === "NUMPAGES" || firstTok === "SECTIONPAGES";
9723
+ }).sort((a, b) => b.range.startIndex - a.range.startIndex);
9724
+ for (const { range, instr } of dynamicRanges) {
9725
+ const firstTok = (instr.trim().replace(/^\\+/, "").split(/[\s\\]+/)[0] || "").toUpperCase();
9726
+ const evaluated = firstTok === "PAGE" ? formatDynamicFieldPageNumber(logicalPageNo, instr) : formatDynamicFieldPageNumber(totalPageCount, instr);
9727
+ const existingTs = findBodyRunStyle(nextBody, range.startIndex);
9728
+ const isEditorFieldHighlight = existingTs?.bg?.rgb?.toLowerCase() === "#f3f5ff" && existingTs?.cl?.rgb?.toLowerCase() === "#2c53f1" && !range.properties?.field?.preserveStyle;
9729
+ const cleanStyle = isEditorFieldHighlight ? {
9730
+ ...existingTs,
9731
+ cl: void 0,
9732
+ bg: void 0
9733
+ } : existingTs;
9734
+ nextBody = spliceDocumentBodySpan(nextBody, range.startIndex, range.endIndex, evaluated, {
9735
+ targetRangeId: range.rangeId,
9736
+ updatedRangeProperties: range.properties,
9737
+ ...cleanStyle ? { textStyle: cleanStyle } : {}
9738
+ });
9739
+ }
9740
+ return nextBody;
9741
+ };
9742
+ const renderStorySegmentIntoMarginOps = (targetOps, rawStoryBody, role, pageIndex, pgW, pgH, logicalPageNo, totalPageCount) => {
9743
+ const resolvedStory = materializeHeaderFooterPageFields(
9744
+ rawStoryBody,
9745
+ logicalPageNo,
9746
+ totalPageCount
9747
+ );
9748
+ const storyStream = resolvedStory.dataStream || "";
9749
+ const hasVisibleText = storyStream.replace(/[\r\n\u0000-\u001F]/g, "").trim().length > 0;
9750
+ const hasInlineBlocks = (resolvedStory.customBlocks ?? []).length > 0;
9751
+ if (!hasVisibleText && !hasInlineBlocks) return false;
9752
+ const availW = Math.max(120, pgW - marginLeft - marginRight);
9753
+ const hfCtx = {
9754
+ ...spanCtxBase,
9755
+ dynamicFieldSpans: [],
9756
+ bookmarks: [],
9757
+ comments: [],
9758
+ includeComments: false
9759
+ };
9760
+ const collectedRows = [];
9761
+ const storyTables = [...resolvedStory.tables ?? []].sort(
9762
+ (a, b) => a.startIndex - b.startIndex
9763
+ );
9764
+ const isOffsetInStoryTable = (offset) => storyTables.some((t) => offset >= t.startIndex && offset < t.endIndex);
9765
+ const storyParas = [...resolvedStory.paragraphs ?? []].sort(
9766
+ (a, b) => a.startIndex - b.startIndex
9767
+ );
9768
+ const storyItems = [];
9769
+ for (const tbl of storyTables) {
9770
+ storyItems.push({ kind: "table", pos: tbl.startIndex, tbl });
9771
+ }
9772
+ for (let pi = 0; pi < storyParas.length; pi++) {
9773
+ const para = storyParas[pi];
9774
+ const pEnd = para.startIndex;
9775
+ if (isOffsetInStoryTable(pEnd)) continue;
9776
+ let pStart = pi === 0 ? 0 : storyParas[pi - 1].startIndex + 1;
9777
+ for (const tbl of storyTables) {
9778
+ if (tbl.endIndex > pStart && tbl.endIndex <= pEnd) {
9779
+ pStart = tbl.endIndex;
9780
+ }
9781
+ }
9782
+ if (pEnd < pStart) continue;
9783
+ storyItems.push({ kind: "para", pos: pStart, pStart, pEnd, para });
9784
+ }
9785
+ storyItems.sort((a, b) => a.pos - b.pos);
9786
+ const normalizeHfSegments = (segs) => segs.filter((it) => "text" in it).map((s) => {
9787
+ const isDefaultDark = Math.abs(s.color.r - 0.06) < 0.01 && Math.abs(s.color.g - 0.09) < 0.01 && Math.abs(s.color.b - 0.16) < 0.01;
9788
+ return isDefaultDark ? { ...s, color: { r: 0.35, g: 0.41, b: 0.49 } } : s;
9789
+ });
9790
+ for (const item of storyItems) {
9791
+ if (item.kind === "table") {
9792
+ const parsedRows = parseTableRowsInStream(
9793
+ storyStream,
9794
+ item.tbl.startIndex,
9795
+ item.tbl.endIndex
9796
+ );
9797
+ const tblDef = snapshot.tableSource?.[item.tbl.tableId];
9798
+ for (const rSpan of parsedRows) {
9799
+ if (rSpan.cells.length === 0) continue;
9800
+ const rawColWidths = rSpan.cells.map(
9801
+ (_, ci) => Math.max(24, Number(tblDef?.tableColumns?.[ci]?.size?.width?.v ?? availW / rSpan.cells.length))
9802
+ );
9803
+ const sumW = rawColWidths.reduce((a, b) => a + b, 0) || 1;
9804
+ let curCellX = marginLeft;
9805
+ const rowCells = [];
9806
+ let maxLh = 12;
9807
+ let maxFs = 9;
9808
+ rSpan.cells.forEach((cell, ci) => {
9809
+ const cw = rawColWidths[ci] / sumW * availW;
9810
+ const cellParas = storyParas.filter(
9811
+ (cp) => cp.startIndex >= cell.contentStart && cp.startIndex < cell.cellEndInclusive
9812
+ );
9813
+ const hAlign = cellParas[0]?.paragraphStyle?.horizontalAlign;
9814
+ const cellAlign = hAlign === 2 ? "center" : hAlign === 3 ? "right" : "left";
9815
+ const segs = normalizeHfSegments(
9816
+ buildStyledSegmentsForSpan(resolvedStory, cell.contentStart, cell.textEndExclusive, 9, hfCtx)
9817
+ );
9818
+ const wrapped = wrapSegmentsToLines(segs, Math.max(24, cw - 4), cellAlign, autoHyphenation);
9819
+ const firstLine = wrapped[0];
9820
+ maxLh = Math.max(maxLh, Math.min(20, firstLine.lineHeightPt * 0.78));
9821
+ maxFs = Math.max(maxFs, firstLine.maxFontSize);
9822
+ rowCells.push({ line: firstLine, xBase: curCellX, width: cw });
9823
+ curCellX += cw;
9824
+ });
9825
+ collectedRows.push({
9826
+ kind: "columns",
9827
+ cells: rowCells,
9828
+ lineHeightPt: maxLh,
9829
+ maxFontSize: maxFs
9830
+ });
9831
+ }
9832
+ } else {
9833
+ const rawSlice = storyStream.slice(item.pStart, item.pEnd);
9834
+ if (rawSlice.replace(/[\r\n\u0000-\u001F]/g, "").trim().length === 0 && !rawSlice.includes(import_core6.DataStreamTreeTokenType.CUSTOM_BLOCK)) {
9835
+ continue;
9836
+ }
9837
+ const hAlign = item.para?.paragraphStyle?.horizontalAlign;
9838
+ const align = hAlign === 2 ? "center" : hAlign === 3 ? "right" : "left";
9839
+ if (rawSlice.includes(" ")) {
9840
+ const tabRanges = [];
9841
+ let segSt = item.pStart;
9842
+ for (let pos = item.pStart; pos < item.pEnd; pos++) {
9843
+ if (storyStream[pos] === " ") {
9844
+ tabRanges.push({ start: segSt, end: pos });
9845
+ segSt = pos + 1;
9846
+ }
9847
+ }
9848
+ tabRanges.push({ start: segSt, end: item.pEnd });
9849
+ const zoneCount = tabRanges.length;
9850
+ const zoneCells = [];
9851
+ let maxFs = 9;
9852
+ tabRanges.forEach((rg, zIdx) => {
9853
+ const zAlign = zoneCount === 2 ? zIdx === 0 ? "left" : "right" : zIdx === 0 ? "left" : zIdx === zoneCount - 1 ? "right" : "center";
9854
+ const segs = normalizeHfSegments(
9855
+ buildStyledSegmentsForSpan(resolvedStory, rg.start, rg.end, 9, hfCtx)
9856
+ );
9857
+ const ln = wrapSegmentsToLines(segs, availW, zAlign, autoHyphenation)[0];
9858
+ maxFs = Math.max(maxFs, ln.maxFontSize);
9859
+ zoneCells.push({ line: ln, xBase: marginLeft, width: availW });
9860
+ });
9861
+ collectedRows.push({
9862
+ kind: "columns",
9863
+ cells: zoneCells,
9864
+ lineHeightPt: Math.max(12, Math.round(maxFs * 1.35)),
9865
+ maxFontSize: maxFs
9866
+ });
9867
+ } else {
9868
+ const segs = normalizeHfSegments(
9869
+ buildStyledSegmentsForSpan(resolvedStory, item.pStart, item.pEnd, 9, hfCtx)
9870
+ );
9871
+ const wrappedLines = wrapSegmentsToLines(segs, availW, align, autoHyphenation);
9872
+ for (const ln of wrappedLines) {
9873
+ if (ln.tokens.length === 0) continue;
9874
+ collectedRows.push({
9875
+ kind: "single",
9876
+ line: ln,
9877
+ xBase: marginLeft,
9878
+ width: availW
9879
+ });
9880
+ }
9881
+ }
9882
+ }
9883
+ }
9884
+ if (collectedRows.length === 0) return false;
9885
+ targetOps.push("q");
9886
+ targetOps.push(`% DocStory:${role}:page=${pageIndex + 1}`);
9887
+ const marginDist = role === "header" ? Math.max(16, Math.min(42, Number(docStyle.marginHeader ?? 24) || 24)) : Math.max(18, Math.min(40, Number(docStyle.marginFooter ?? 24) || 24));
9888
+ let rowY = role === "header" ? pgH - marginDist - 9 : marginDist + (collectedRows.length - 1) * 12;
9889
+ for (const row of collectedRows) {
9890
+ if (row.kind === "single") {
9891
+ const ln = row.line;
9892
+ let lx = row.xBase;
9893
+ if (ln.align === "center") {
9894
+ lx = row.xBase + Math.max(0, (row.width - ln.totalWidthPt) / 2);
9895
+ } else if (ln.align === "right") {
9896
+ lx = row.xBase + Math.max(0, row.width - ln.totalWidthPt);
9897
+ }
9898
+ renderTokensRowAt(targetOps, ln.tokens, lx, rowY, pageIndex);
9899
+ rowY -= Math.max(12, Math.min(18, ln.lineHeightPt * 0.78));
9900
+ } else {
9901
+ for (const cell of row.cells) {
9902
+ const ln = cell.line;
9903
+ if (ln.tokens.length === 0) continue;
9904
+ let lx = cell.xBase;
9905
+ if (ln.align === "center") {
9906
+ lx = cell.xBase + Math.max(0, (cell.width - ln.totalWidthPt) / 2);
9907
+ } else if (ln.align === "right") {
9908
+ lx = cell.xBase + Math.max(0, cell.width - ln.totalWidthPt);
9909
+ }
9910
+ renderTokensRowAt(targetOps, ln.tokens, lx, rowY, pageIndex);
9911
+ }
9912
+ rowY -= row.lineHeightPt;
9913
+ }
9914
+ }
9915
+ targetOps.push("Q");
9916
+ return true;
9917
+ };
9622
9918
  const totalPages = pageStreams.length;
9623
9919
  const effectiveTotalNumbered = Math.max(1, totalPages - (fromPageNo - 1) + (startPageNo - 1));
9624
9920
  for (let pageIdx = 0; pageIdx < totalPages; pageIdx++) {
@@ -9812,17 +10108,48 @@ function paginateSingleDocToPdfPages(rawSnapshot, options, imageNamePrefix = "Im
9812
10108
  }
9813
10109
  postOps.push("Q");
9814
10110
  }
9815
- const shouldShowFooter = (fieldsOnly ? options?.showPageFooter === true : !pagelessMode && options?.showPageFooter !== false) && pageIdx + 1 >= fromPageNo;
10111
+ let renderedExplicitDocFooter = false;
10112
+ if (!fieldsOnly && !pagelessMode) {
10113
+ const pageHdrBody = resolvePageHeaderBody(pageIdx);
10114
+ if (pageHdrBody) {
10115
+ renderStorySegmentIntoMarginOps(
10116
+ postOps,
10117
+ pageHdrBody,
10118
+ "header",
10119
+ pageIdx,
10120
+ pgW,
10121
+ pgH,
10122
+ logicalPageNo,
10123
+ totalPages
10124
+ );
10125
+ }
10126
+ const pageFtrBody = resolvePageFooterBody(pageIdx);
10127
+ if (pageFtrBody) {
10128
+ renderedExplicitDocFooter = renderStorySegmentIntoMarginOps(
10129
+ postOps,
10130
+ pageFtrBody,
10131
+ "footer",
10132
+ pageIdx,
10133
+ pgW,
10134
+ pgH,
10135
+ logicalPageNo,
10136
+ totalPages
10137
+ );
10138
+ }
10139
+ }
10140
+ const hasExplicitOptionPageFormat = Boolean(options?.pageNumberFormat);
10141
+ const shouldShowFooter = (!renderedExplicitDocFooter || hasExplicitOptionPageFormat) && (fieldsOnly ? options?.showPageFooter === true : !pagelessMode && options?.showPageFooter !== false) && pageIdx + 1 >= fromPageNo;
9816
10142
  if (shouldShowFooter) {
9817
10143
  const fmtTemplate = pageNumberFormat || "Page {pageNo} / {pageCount}";
9818
10144
  const footerLabel = fmtTemplate.replace(/\{pageNo\}/g, fmtPgToken(logicalPageNo)).replace(/\{pageCount\}/g, fmtPgToken(effectiveTotalNumbered));
9819
10145
  const fw = measureTextWidthPt(footerLabel, 9);
9820
10146
  const fx = pageNumberAlign === "left" ? marginLeft : pageNumberAlign === "right" ? pgW - marginRight - fw : (pgW - fw) / 2;
10147
+ const syntheticFooterY = renderedExplicitDocFooter ? 12 : 26;
9821
10148
  emitPdfMixedTextOps(
9822
10149
  postOps,
9823
10150
  footerLabel,
9824
10151
  fx,
9825
- 26,
10152
+ syntheticFooterY,
9826
10153
  9,
9827
10154
  false,
9828
10155
  { r: 0.45, g: 0.51, b: 0.59 }
@@ -10051,6 +10378,85 @@ function exportBatchDocPdfBytes(templateSnapshot, records, options) {
10051
10378
  `${templateSnapshot.title || "Batch Mail-Merge"} (${effectiveRecords.length})`
10052
10379
  );
10053
10380
  }
10381
+ function unescapePdfAsciiLiteral(raw) {
10382
+ let out = "";
10383
+ for (let i = 0; i < raw.length; i++) {
10384
+ if (raw[i] === "\\" && i + 1 < raw.length) {
10385
+ const next = raw[++i];
10386
+ if (next === "n") out += "\n";
10387
+ else if (next === "r") out += "\r";
10388
+ else if (next === "t") out += " ";
10389
+ else out += next;
10390
+ } else {
10391
+ out += raw[i];
10392
+ }
10393
+ }
10394
+ return out;
10395
+ }
10396
+ function decodePdfHexUtf16Be(hexRaw) {
10397
+ const clean = hexRaw.replace(/\s+/g, "");
10398
+ const start = clean.toUpperCase().startsWith("FEFF") ? 4 : 0;
10399
+ let out = "";
10400
+ for (let i = start; i + 3 < clean.length; i += 4) {
10401
+ const code = parseInt(clean.slice(i, i + 4), 16);
10402
+ if (!Number.isNaN(code)) {
10403
+ out += String.fromCharCode(code);
10404
+ }
10405
+ }
10406
+ return out;
10407
+ }
10408
+ function extractNativeTextSpansFromPdfBytes(pdfBytes) {
10409
+ const rawPdf = new TextDecoder("latin1").decode(pdfBytes);
10410
+ const objects = /* @__PURE__ */ new Map();
10411
+ const objRe = /(\d+)\s+0\s+obj\r?\n([\s\S]*?)\r?\nendobj/g;
10412
+ let om;
10413
+ while ((om = objRe.exec(rawPdf)) !== null) {
10414
+ objects.set(Number(om[1]), om[2]);
10415
+ }
10416
+ let pageObjIds = [];
10417
+ for (const bodyStr of objects.values()) {
10418
+ if (/\/Type\s*\/Pages\b/.test(bodyStr)) {
10419
+ const kidsMatch = bodyStr.match(/\/Kids\s*\[([^\]]*)\]/);
10420
+ if (kidsMatch) {
10421
+ pageObjIds = Array.from(kidsMatch[1].matchAll(/(\d+)\s+0\s+R/g)).map(
10422
+ (m) => Number(m[1])
10423
+ );
10424
+ break;
10425
+ }
10426
+ }
10427
+ }
10428
+ if (pageObjIds.length === 0) {
10429
+ for (const [id, bodyStr] of objects.entries()) {
10430
+ if (/\/Type\s*\/Page\b/.test(bodyStr)) {
10431
+ pageObjIds.push(id);
10432
+ }
10433
+ }
10434
+ pageObjIds.sort((a, b) => a - b);
10435
+ }
10436
+ return pageObjIds.map((pageObjId, pageIndex) => {
10437
+ const pageDict = objects.get(pageObjId) || "";
10438
+ const contentsId = Number(pageDict.match(/\/Contents\s+(\d+)\s+0\s+R/)?.[1] ?? 0);
10439
+ const streamObj = objects.get(contentsId) || "";
10440
+ const streamMatch = streamObj.match(/stream\r?\n([\s\S]*?)\r?\nendstream/);
10441
+ const streamBody = streamMatch ? streamMatch[1] : "";
10442
+ const spans = [];
10443
+ const tjRe = /\(((?:\\.|[^\\)])*)\)\s*Tj|<([0-9A-Fa-f\s]+)>\s*Tj/g;
10444
+ let tm;
10445
+ while ((tm = tjRe.exec(streamBody)) !== null) {
10446
+ if (tm[1] !== void 0) {
10447
+ spans.push(unescapePdfAsciiLiteral(tm[1]));
10448
+ } else if (tm[2] !== void 0) {
10449
+ spans.push(decodePdfHexUtf16Be(tm[2]));
10450
+ }
10451
+ }
10452
+ return {
10453
+ pageIndex,
10454
+ pageNumber: pageIndex + 1,
10455
+ spans,
10456
+ text: spans.join("")
10457
+ };
10458
+ });
10459
+ }
10054
10460
 
10055
10461
  // src/exporter/docx-exporter.ts
10056
10462
  var import_core7 = require("@univerjs/core");
@@ -10792,7 +11198,7 @@ function serializeSpanToRunsAndSdtXml(body, spanStart, spanEndExclusive, exportC
10792
11198
  (r) => r.rangeType === import_core7.CustomRangeType.HYPERLINK && r.startIndex >= spanStart && r.endIndex < spanEndExclusive && !exportCtx?.excludeRangeIds?.has(r.rangeId)
10793
11199
  );
10794
11200
  const docFieldRanges = (body.customRanges ?? []).filter(
10795
- (r) => r.properties?.yudaoBlockKind === "docField" && r.startIndex >= spanStart && r.endIndex < spanEndExclusive
11201
+ (r) => (r.properties?.yudaoBlockKind === "docField" || typeof r.properties?.fieldInstr === "string") && r.startIndex >= spanStart && r.endIndex < spanEndExclusive
10796
11202
  );
10797
11203
  const noteRanges = (body.customRanges ?? []).filter(
10798
11204
  (r) => (r.rangeType === import_core7.CustomRangeType.FOOTNOTE || r.rangeType === import_core7.CustomRangeType.ENDNOTE) && r.startIndex >= spanStart && r.endIndex < spanEndExclusive
@@ -10885,11 +11291,14 @@ function serializeSpanToRunsAndSdtXml(body, spanStart, spanEndExclusive, exportC
10885
11291
  }
10886
11292
  const fieldAtCursor = docFieldRanges.find((r) => r.startIndex === cursor);
10887
11293
  if (fieldAtCursor) {
10888
- const fldObj = fieldAtCursor.properties?.field;
10889
- const instrText = String(fldObj?.instrText || fldObj?.fieldType || "PAGE").trim();
11294
+ const fProps = fieldAtCursor.properties ?? {};
11295
+ const fldObj = fProps.field;
11296
+ const instrText = String(
11297
+ fProps.fieldInstr || fldObj?.instrText || fldObj?.fieldType || "PAGE"
11298
+ ).trim();
10890
11299
  const fldValText = stream.slice(fieldAtCursor.startIndex, fieldAtCursor.endIndex + 1).replace(/[\r\n\u0000-\u001F]/g, "");
10891
11300
  const fldStyle = findStyleAtBody(body, fieldAtCursor.startIndex);
10892
- if (fldObj?.sourceKind === "complex") {
11301
+ if (fldObj?.sourceKind === "complex" || fProps.fieldSimple === false) {
10893
11302
  const rPr = buildRunPrXml(fldStyle);
10894
11303
  const valRuns = buildRunXmlWithBreaks(fldValText, fldStyle);
10895
11304
  innerXml.push(
@@ -17702,6 +18111,8 @@ function insertDocFieldIntoSnapshot(sourceSnapshot, fieldType, instructionArgs,
17702
18111
  endIndex: entry.endIndex,
17703
18112
  properties: {
17704
18113
  yudaoBlockKind: "docField",
18114
+ fieldInstr: entry.instrText,
18115
+ fieldSimple: true,
17705
18116
  field: import_core8.Tools.deepClone(entry)
17706
18117
  }
17707
18118
  });
@@ -17757,11 +18168,26 @@ function listDocFields(snapshot) {
17757
18168
  items.push({
17758
18169
  ...import_core8.Tools.deepClone(f),
17759
18170
  id: r.rangeId,
18171
+ instrText: String(props.fieldInstr || f.instrText || f.fieldType),
17760
18172
  value: liveVal || f.value,
17761
18173
  ...segmentId ? { segmentId } : {},
17762
18174
  startIndex: r.startIndex,
17763
18175
  endIndex: r.endIndex
17764
18176
  });
18177
+ } else if (typeof props?.fieldInstr === "string" && props.fieldInstr.trim()) {
18178
+ const parsedInstr = parseFieldInstrString(props.fieldInstr);
18179
+ const liveVal = stream.slice(r.startIndex, r.endIndex + 1).replace(/[\r\n\u0000-\u001F]/g, "");
18180
+ items.push({
18181
+ id: r.rangeId,
18182
+ fieldType: parsedInstr.fieldType,
18183
+ ...parsedInstr.instructionArgs ? { instructionArgs: parsedInstr.instructionArgs } : {},
18184
+ instrText: props.fieldInstr.trim(),
18185
+ value: liveVal || "1",
18186
+ sourceKind: props.fieldSimple === false ? "complex" : "simple",
18187
+ ...segmentId ? { segmentId } : {},
18188
+ startIndex: r.startIndex,
18189
+ endIndex: r.endIndex
18190
+ });
17765
18191
  }
17766
18192
  }
17767
18193
  items.sort((a, b) => (a.startIndex ?? 0) - (b.startIndex ?? 0));
@@ -17787,7 +18213,7 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
17787
18213
  const liveBody = resolveSegmentBodyInSnapshot(snapshot, fld.segmentId);
17788
18214
  if (!liveBody) continue;
17789
18215
  const range = (liveBody.customRanges ?? []).find(
17790
- (r) => r.rangeId === fld.id && r.properties?.yudaoBlockKind === "docField"
18216
+ (r) => r.rangeId === fld.id && (r.properties?.yudaoBlockKind === "docField" || typeof r.properties?.fieldInstr === "string")
17791
18217
  );
17792
18218
  if (!range) continue;
17793
18219
  const nextVal = evaluateSingleFieldValue(
@@ -17814,6 +18240,8 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
17814
18240
  targetRangeId: fld.id,
17815
18241
  updatedRangeProperties: {
17816
18242
  yudaoBlockKind: "docField",
18243
+ fieldInstr: updatedEntry.instrText,
18244
+ ...updatedEntry.sourceKind ? { fieldSimple: updatedEntry.sourceKind === "simple" } : {},
17817
18245
  field: import_core8.Tools.deepClone(updatedEntry)
17818
18246
  },
17819
18247
  textStyle: fld.preserveStyle ? void 0 : { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
@@ -17836,7 +18264,7 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
17836
18264
  const liveBody = resolveSegmentBodyInSnapshot(snapshot, fld.segmentId);
17837
18265
  if (!liveBody) continue;
17838
18266
  const range = (liveBody.customRanges ?? []).find(
17839
- (r) => r.rangeId === fld.id && r.properties?.yudaoBlockKind === "docField"
18267
+ (r) => r.rangeId === fld.id && (r.properties?.yudaoBlockKind === "docField" || typeof r.properties?.fieldInstr === "string")
17840
18268
  );
17841
18269
  if (!range) continue;
17842
18270
  const nextVal = evaluateSingleFieldValue(
@@ -17863,6 +18291,8 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
17863
18291
  targetRangeId: fld.id,
17864
18292
  updatedRangeProperties: {
17865
18293
  yudaoBlockKind: "docField",
18294
+ fieldInstr: updatedEntry.instrText,
18295
+ ...updatedEntry.sourceKind ? { fieldSimple: updatedEntry.sourceKind === "simple" } : {},
17866
18296
  field: import_core8.Tools.deepClone(updatedEntry)
17867
18297
  },
17868
18298
  textStyle: fld.preserveStyle ? void 0 : { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
@@ -23466,19 +23896,88 @@ var PATH_PART = "[\\p{L}\\p{N}_.\\[\\]-]+";
23466
23896
  var EXPLICIT_LIST_TOKEN_RE = new RegExp(`(?:\\$|#)\\{#(${IDENT_PART})\\.(${PATH_PART})\\}`, "gu");
23467
23897
  var EXPLICIT_NESTED_LIST_TOKEN_RE = new RegExp(`(?:\\$|#)\\{#(${PATH_PART})\\}`, "gu");
23468
23898
  var ANY_CELL_TOKEN_RE = new RegExp(`(?:\\$|#)\\{(#?)(${PATH_PART})\\}`, "gu");
23469
- var INLINE_VALUE_TOKEN_RE = new RegExp(`(?:\\$|#)\\{(${PATH_PART})\\}`, "gu");
23899
+ var INLINE_VALUE_TOKEN_RE = new RegExp(`(?:\\$|#)\\{(#?${PATH_PART})\\}`, "gu");
23900
+ function parseDocBindingKey(rawKey) {
23901
+ const trimmed = typeof rawKey === "string" ? rawKey.trim() : "";
23902
+ let inner = trimmed;
23903
+ const wrappedMatch = inner.match(/^(?:\$|#)\{([\s\S]*)\}$/);
23904
+ if (wrappedMatch) {
23905
+ inner = wrappedMatch[1].trim();
23906
+ }
23907
+ inner = inner.replace(/^#/, "").trim();
23908
+ const dotIdx = inner.indexOf(".");
23909
+ if (dotIdx > 0 && dotIdx < inner.length - 1) {
23910
+ const datasetCode = inner.slice(0, dotIdx).replace(/\[\d+\]$/, "").trim();
23911
+ const fieldPath = inner.slice(dotIdx + 1).trim();
23912
+ return {
23913
+ rawKey: trimmed,
23914
+ ...datasetCode ? { datasetCode } : {},
23915
+ fieldPath
23916
+ };
23917
+ }
23918
+ return {
23919
+ rawKey: trimmed,
23920
+ fieldPath: inner
23921
+ };
23922
+ }
23923
+ function extractDocInlinePlaceholders(text, syntax = "both") {
23924
+ if (typeof text !== "string" || text.length === 0) return [];
23925
+ const sigilGroup = syntax === "dollar" ? "(\\$)" : syntax === "hash" ? "(#)" : "(\\$|#)";
23926
+ const re = new RegExp(`${sigilGroup}\\{(#?${PATH_PART})\\}`, "gu");
23927
+ const matches = [];
23928
+ let m;
23929
+ while ((m = re.exec(text)) !== null) {
23930
+ const sigil = m[1] === "#" ? "hash" : "dollar";
23931
+ const rawKey = m[2];
23932
+ const parsed = parseDocBindingKey(rawKey);
23933
+ matches.push({
23934
+ token: m[0],
23935
+ rawKey,
23936
+ syntax: sigil,
23937
+ index: m.index,
23938
+ ...parsed.datasetCode ? { datasetCode: parsed.datasetCode } : {},
23939
+ fieldPath: parsed.fieldPath
23940
+ });
23941
+ }
23942
+ return matches;
23943
+ }
23944
+ function extractDocFieldInstruction(range) {
23945
+ const props = range?.properties ?? void 0;
23946
+ if (!props) return void 0;
23947
+ if (typeof props.fieldInstr === "string" && props.fieldInstr.trim().length > 0) {
23948
+ return props.fieldInstr.trim();
23949
+ }
23950
+ if (props.yudaoBlockKind === "docField" || props.field != null) {
23951
+ const fallback = props.instrText ?? props.field?.instrText ?? props.field?.fieldType;
23952
+ if (typeof fallback === "string" && fallback.trim().length > 0) {
23953
+ return fallback.trim();
23954
+ }
23955
+ }
23956
+ return void 0;
23957
+ }
23958
+ function isDynamicPageFieldInstruction(instr) {
23959
+ if (!instr || typeof instr !== "string") return false;
23960
+ const firstToken = (instr.trim().replace(/^\\+/, "").split(/[\s\\]+/)[0] || "").toUpperCase();
23961
+ return firstToken === "PAGE" || firstToken === "NUMPAGES" || firstToken === "SECTIONPAGES" || firstToken === "PAGEREF";
23962
+ }
23470
23963
  function resolvePathValue(source, path) {
23471
23964
  if (!source || !path) return void 0;
23472
- if (Object.prototype.hasOwnProperty.call(source, path)) {
23473
- return source[path];
23965
+ if (!path.includes(".") && !path.includes("[")) {
23966
+ return Object.prototype.hasOwnProperty.call(source, path) ? source[path] : void 0;
23474
23967
  }
23475
23968
  const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
23476
23969
  let cur = source;
23477
23970
  for (const key of parts) {
23478
- if (cur == null || typeof cur !== "object") return void 0;
23971
+ if (cur == null || typeof cur !== "object") {
23972
+ cur = void 0;
23973
+ break;
23974
+ }
23479
23975
  cur = cur[key];
23480
23976
  }
23481
- return cur;
23977
+ if (cur !== void 0) {
23978
+ return cur;
23979
+ }
23980
+ return Object.prototype.hasOwnProperty.call(source, path) ? source[path] : void 0;
23482
23981
  }
23483
23982
  function readDocTemplateMetadataFromSnapshot(snapshot) {
23484
23983
  const entry = (snapshot?.resources ?? []).find((r) => r.name === YUDAO_DOCS_TEMPLATE_RESOURCE);
@@ -25253,8 +25752,9 @@ function replaceRowCellTokens(rawCellText, listKey, itemObj, rowSeqIndex, rootDa
25253
25752
  if (rootVal !== void 0 && rootVal !== null && typeof rootVal !== "object") {
25254
25753
  return String(rootVal);
25255
25754
  }
25755
+ return "";
25256
25756
  }
25257
- return full;
25757
+ return "";
25258
25758
  });
25259
25759
  }
25260
25760
  function renderLoopCellContent(body, cell, cellSdts, detectedListKey, itemObj, rowSeqIndex, rootData, hasExplicitListKey) {
@@ -25362,6 +25862,43 @@ function renderLoopCellContent(body, cell, cellSdts, detectedListKey, itemObj, r
25362
25862
  }
25363
25863
  return out;
25364
25864
  }
25865
+ function assertRowLoopStructureSupported(body, tableId, tableIndex, rowSpan, rowIndex, tblSource) {
25866
+ const rowSlice = body.dataStream.slice(rowSpan.rowStart, rowSpan.rowEndInclusive + 1);
25867
+ const hasNestedStreamToken = rowSlice.includes(import_core13.DataStreamTreeTokenType.TABLE_START) || rowSlice.includes(import_core13.DataStreamTreeTokenType.TABLE_END);
25868
+ const hasNestedTableRange = (body.tables ?? []).some(
25869
+ (otherTbl, otherIdx) => otherIdx !== tableIndex && otherTbl.startIndex >= rowSpan.rowStart && otherTbl.startIndex <= rowSpan.rowEndInclusive
25870
+ );
25871
+ if (hasNestedStreamToken || hasNestedTableRange) {
25872
+ throw new DocTemplateProtocolError(
25873
+ "UNSUPPORTED_ROW_LOOP_STRUCTURE",
25874
+ `Detail loop row ${rowIndex} in table "${tableId}" contains a nested table, which is unsupported by single-level tableRowLoops.`,
25875
+ { tableId, rowIndex }
25876
+ );
25877
+ }
25878
+ const rowCells = tblSource?.tableRows?.[rowIndex]?.tableCells ?? [];
25879
+ const hasDirectVerticalMerge = rowCells.some((cell) => {
25880
+ if (!cell) return false;
25881
+ const anyCell = cell;
25882
+ return typeof cell.rowSpan === "number" && (cell.rowSpan > 1 || cell.rowSpan === 0) || anyCell.vMerge !== void 0;
25883
+ });
25884
+ let coveredByUpperVerticalMerge = false;
25885
+ if (!hasDirectVerticalMerge && tblSource?.tableRows) {
25886
+ for (let prevR = 0; prevR < rowIndex && prevR < tblSource.tableRows.length; prevR++) {
25887
+ const prevCells = tblSource.tableRows[prevR]?.tableCells ?? [];
25888
+ if (prevCells.some((c) => typeof c?.rowSpan === "number" && c.rowSpan > rowIndex - prevR)) {
25889
+ coveredByUpperVerticalMerge = true;
25890
+ break;
25891
+ }
25892
+ }
25893
+ }
25894
+ if (hasDirectVerticalMerge || coveredByUpperVerticalMerge) {
25895
+ throw new DocTemplateProtocolError(
25896
+ "UNSUPPORTED_ROW_LOOP_STRUCTURE",
25897
+ `Detail loop row ${rowIndex} in table "${tableId}" participates in a vertical cell merge (vMerge / rowSpan), which is unsupported by single-level tableRowLoops.`,
25898
+ { tableId, rowIndex }
25899
+ );
25900
+ }
25901
+ }
25365
25902
  function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
25366
25903
  const body = nextSnapshot.body;
25367
25904
  if (!body?.tables?.length) return;
@@ -25378,7 +25915,8 @@ function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
25378
25915
  if (parsedRows.length === 0) continue;
25379
25916
  const tblSource = nextSnapshot.tableSource?.[tblRef.tableId];
25380
25917
  let remainingRowCount = parsedRows.length;
25381
- for (let rIdx = parsedRows.length - 1; rIdx >= 0; rIdx--) {
25918
+ const detectedRowLoops = /* @__PURE__ */ new Map();
25919
+ for (let rIdx = 0; rIdx < parsedRows.length; rIdx++) {
25382
25920
  const rowSpan = parsedRows[rIdx];
25383
25921
  const loopKey = `${tblRef.tableId}:${rIdx}`;
25384
25922
  const explicitCfg = loopMap[loopKey];
@@ -25434,35 +25972,54 @@ function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
25434
25972
  }
25435
25973
  }
25436
25974
  }
25975
+ if (explicitCfg || detectedListKey) {
25976
+ assertRowLoopStructureSupported(body, tblRef.tableId, tIdx, rowSpan, rIdx, tblSource);
25977
+ }
25437
25978
  if (!detectedListKey) continue;
25438
- consumedLoopKeys.add(loopKey);
25439
- const rawItems = resolvePathValue(data, detectedListKey) ?? data?.[detectedListKey];
25440
- const items = Array.isArray(rawItems) ? rawItems : [];
25441
- const emptyStrategy = explicitCfg?.emptyStrategy ?? "keep-blank";
25442
- const repeatHeader = explicitCfg?.repeatHeaderRow ?? true;
25443
- if (explicitCfg?.repeatHeaderRow === false) {
25444
- if (tblSource?.tableRows) {
25445
- const upper = Math.max(1, rIdx);
25446
- for (let h = 0; h < upper && h < tblSource.tableRows.length; h++) {
25447
- tblSource.tableRows[h] = {
25448
- ...tblSource.tableRows[h],
25449
- repeatHeaderRow: import_core13.BooleanNumber.FALSE
25450
- };
25451
- }
25452
- }
25453
- if (snapMeta.tableRepeatHeaders && tblRef.tableId in snapMeta.tableRepeatHeaders) {
25454
- delete snapMeta.tableRepeatHeaders[tblRef.tableId];
25455
- metaChanged = true;
25456
- }
25457
- } else if (repeatHeader && rIdx > 0 && tblSource?.tableRows) {
25458
- for (let h = 0; h < rIdx && h < tblSource.tableRows.length; h++) {
25979
+ detectedRowLoops.set(rIdx, {
25980
+ loopKey,
25981
+ explicitCfg,
25982
+ hasExplicitListKey,
25983
+ detectedListKey,
25984
+ rowCellSdts
25985
+ });
25986
+ }
25987
+ if (detectedRowLoops.size === 0) continue;
25988
+ const firstLoopRowIdx = Math.min(...detectedRowLoops.keys());
25989
+ const firstLoopMeta = detectedRowLoops.get(firstLoopRowIdx);
25990
+ const firstRepeatHeader = firstLoopMeta.explicitCfg?.repeatHeaderRow ?? true;
25991
+ if (firstLoopMeta.explicitCfg?.repeatHeaderRow === false) {
25992
+ if (tblSource?.tableRows) {
25993
+ const upper = Math.max(1, firstLoopRowIdx);
25994
+ for (let h = 0; h < upper && h < tblSource.tableRows.length; h++) {
25459
25995
  tblSource.tableRows[h] = {
25460
25996
  ...tblSource.tableRows[h],
25461
- ...h === 0 ? { isFirstRow: import_core13.BooleanNumber.TRUE } : {},
25462
- repeatHeaderRow: import_core13.BooleanNumber.TRUE
25997
+ repeatHeaderRow: import_core13.BooleanNumber.FALSE
25463
25998
  };
25464
25999
  }
25465
26000
  }
26001
+ if (snapMeta.tableRepeatHeaders && tblRef.tableId in snapMeta.tableRepeatHeaders) {
26002
+ delete snapMeta.tableRepeatHeaders[tblRef.tableId];
26003
+ metaChanged = true;
26004
+ }
26005
+ } else if (firstRepeatHeader && firstLoopRowIdx > 0 && tblSource?.tableRows) {
26006
+ for (let h = 0; h < firstLoopRowIdx && h < tblSource.tableRows.length; h++) {
26007
+ tblSource.tableRows[h] = {
26008
+ ...tblSource.tableRows[h],
26009
+ ...h === 0 ? { isFirstRow: import_core13.BooleanNumber.TRUE } : {},
26010
+ repeatHeaderRow: import_core13.BooleanNumber.TRUE
26011
+ };
26012
+ }
26013
+ }
26014
+ for (let rIdx = parsedRows.length - 1; rIdx >= 0; rIdx--) {
26015
+ const detectedEntry = detectedRowLoops.get(rIdx);
26016
+ if (!detectedEntry) continue;
26017
+ const rowSpan = parsedRows[rIdx];
26018
+ const { loopKey, explicitCfg, hasExplicitListKey, detectedListKey, rowCellSdts } = detectedEntry;
26019
+ consumedLoopKeys.add(loopKey);
26020
+ const rawItems = resolvePathValue(data, detectedListKey) ?? data?.[detectedListKey];
26021
+ const items = Array.isArray(rawItems) ? rawItems : [];
26022
+ const emptyStrategy = explicitCfg?.emptyStrategy ?? "keep-blank";
25466
26023
  if (items.length === 0 && emptyStrategy === "remove" && remainingRowCount > 1) {
25467
26024
  remainingRowCount--;
25468
26025
  const removeStart = rowSpan.rowStart;
@@ -26047,20 +26604,29 @@ function fillDatasetIntoDocSnapshot(snapshot, data, options) {
26047
26604
  }
26048
26605
  const dynamicBodySpans = [];
26049
26606
  const replaceInlineTokensInBody = (targetBody, trackSpans = false) => {
26050
- INLINE_VALUE_TOKEN_RE.lastIndex = 0;
26607
+ const protectedRepeatingRanges = (targetBody.customRanges ?? []).filter(
26608
+ (r) => r.rangeType === import_core13.CustomRangeType.SDT && (r.properties?.yudaoKind === "repeatingSection" || r.properties?.kind === "repeatingSection")
26609
+ );
26610
+ const tokenRe = new RegExp(INLINE_VALUE_TOKEN_RE.source, INLINE_VALUE_TOKEN_RE.flags);
26051
26611
  let match;
26052
26612
  const replacements = [];
26053
- while ((match = INLINE_VALUE_TOKEN_RE.exec(targetBody.dataStream)) !== null) {
26613
+ while ((match = tokenRe.exec(targetBody.dataStream)) !== null) {
26054
26614
  const expr = match[1];
26055
26615
  if (expr.startsWith("#")) continue;
26056
- const val = resolvePathValue(data, expr);
26057
- if (val !== void 0 && val !== null && typeof val !== "object") {
26058
- replacements.push({
26059
- start: match.index,
26060
- endInclusive: match.index + match[0].length - 1,
26061
- text: String(val)
26062
- });
26616
+ const matchStart = match.index;
26617
+ const matchEndInclusive = match.index + match[0].length - 1;
26618
+ if (protectedRepeatingRanges.some(
26619
+ (r) => matchStart >= r.startIndex && matchEndInclusive <= r.endIndex
26620
+ )) {
26621
+ continue;
26063
26622
  }
26623
+ const val = resolvePathValue(data, expr);
26624
+ const resolvedText = val !== void 0 && val !== null && typeof val !== "object" ? String(val) : "";
26625
+ replacements.push({
26626
+ start: matchStart,
26627
+ endInclusive: matchEndInclusive,
26628
+ text: resolvedText
26629
+ });
26064
26630
  }
26065
26631
  let updated = targetBody;
26066
26632
  for (let i = replacements.length - 1; i >= 0; i--) {
@@ -26219,6 +26785,8 @@ function buildStructuredDocData(params) {
26219
26785
  endIndex: ed - 1,
26220
26786
  properties: {
26221
26787
  yudaoBlockKind: "docField",
26788
+ fieldInstr: entry.instrText,
26789
+ ...seg.docField.sourceKind ? { fieldSimple: seg.docField.sourceKind === "simple" } : {},
26222
26790
  field: import_core13.Tools.deepClone(entry)
26223
26791
  }
26224
26792
  });
@@ -28005,6 +28573,89 @@ function diffDocSnapshots(beforeSnapshot, afterSnapshot) {
28005
28573
  removedLength
28006
28574
  };
28007
28575
  }
28576
+ function summarizeDocTemplate(snapshot) {
28577
+ const bindings = [];
28578
+ const datasetCodeSet = /* @__PURE__ */ new Set();
28579
+ let sdtCount = 0;
28580
+ let placeholderCount = 0;
28581
+ let hasDynamicPageFields = false;
28582
+ const scanStory = (storyBody, scope, segmentId) => {
28583
+ if (!storyBody) return;
28584
+ const customRanges = storyBody.customRanges ?? [];
28585
+ for (const r of customRanges) {
28586
+ const fldInstr = extractDocFieldInstruction(r);
28587
+ if (fldInstr && isDynamicPageFieldInstruction(fldInstr)) {
28588
+ hasDynamicPageFields = true;
28589
+ }
28590
+ if (r.rangeType !== import_core13.CustomRangeType.SDT) continue;
28591
+ const resolved = parseSdtRangeToResolved(storyBody, r, segmentId);
28592
+ if (!resolved) continue;
28593
+ sdtCount++;
28594
+ if (resolved.kind === "group" && !resolved.bindingPath) continue;
28595
+ const rawKey = (resolved.bindingPath || resolved.tag || "").trim();
28596
+ if (!rawKey) continue;
28597
+ const parsed = parseDocBindingKey(rawKey);
28598
+ if (parsed.datasetCode) {
28599
+ datasetCodeSet.add(parsed.datasetCode);
28600
+ }
28601
+ bindings.push({
28602
+ source: "sdt",
28603
+ scope,
28604
+ ...segmentId ? { segmentId } : {},
28605
+ rawKey: parsed.rawKey,
28606
+ ...parsed.datasetCode ? { datasetCode: parsed.datasetCode } : {},
28607
+ fieldPath: parsed.fieldPath,
28608
+ controlId: resolved.id,
28609
+ controlType: resolved.kind
28610
+ });
28611
+ }
28612
+ const placeholders = extractDocInlinePlaceholders(storyBody.dataStream ?? "", "both");
28613
+ for (const ph of placeholders) {
28614
+ placeholderCount++;
28615
+ if (ph.datasetCode) {
28616
+ datasetCodeSet.add(ph.datasetCode);
28617
+ }
28618
+ bindings.push({
28619
+ source: "placeholder",
28620
+ scope,
28621
+ ...segmentId ? { segmentId } : {},
28622
+ rawKey: ph.rawKey,
28623
+ ...ph.datasetCode ? { datasetCode: ph.datasetCode } : {},
28624
+ fieldPath: ph.fieldPath
28625
+ });
28626
+ }
28627
+ };
28628
+ scanStory(snapshot?.body, "body");
28629
+ for (const [segId, hdr] of Object.entries(snapshot?.headers ?? {})) {
28630
+ scanStory(hdr?.body, "header", segId);
28631
+ }
28632
+ for (const [segId, ftr] of Object.entries(snapshot?.footers ?? {})) {
28633
+ scanStory(ftr?.body, "footer", segId);
28634
+ }
28635
+ const meta = readDocTemplateMetadataFromSnapshot(snapshot);
28636
+ const tableRowLoops = Object.values(meta.tableRowLoops ?? {}).map(
28637
+ (cfg) => import_core13.Tools.deepClone(cfg)
28638
+ );
28639
+ for (const loop of tableRowLoops) {
28640
+ if (loop.listKey?.trim()) {
28641
+ const parsedLoop = parseDocBindingKey(loop.listKey);
28642
+ const code = parsedLoop.datasetCode || parsedLoop.fieldPath;
28643
+ if (code) datasetCodeSet.add(code);
28644
+ }
28645
+ }
28646
+ const metadataKeys = Object.keys(meta).filter(
28647
+ (k) => meta[k] !== void 0
28648
+ );
28649
+ return {
28650
+ datasetCodes: Array.from(datasetCodeSet),
28651
+ bindings,
28652
+ tableRowLoops,
28653
+ metadataKeys,
28654
+ sdtCount,
28655
+ placeholderCount,
28656
+ hasDynamicPageFields
28657
+ };
28658
+ }
28008
28659
 
28009
28660
  // src/services/doc-sdt.service.ts
28010
28661
  var IDocSdtService = (0, import_core14.createIdentifier)("yudao.univer-docs.sdt.service");
@@ -31751,37 +32402,109 @@ var FillDocDatasetCommand = {
31751
32402
  );
31752
32403
  }
31753
32404
  };
32405
+ function isValidReplacementDocSnapshot(snapshot) {
32406
+ if (!snapshot || typeof snapshot !== "object") return false;
32407
+ const candidate = snapshot;
32408
+ const body = candidate.body;
32409
+ if (!body || typeof body !== "object") return false;
32410
+ if (typeof body.dataStream !== "string" || body.dataStream.length < 2) return false;
32411
+ if (!body.dataStream.endsWith("\r\n")) return false;
32412
+ if (body.paragraphs !== void 0 && !Array.isArray(body.paragraphs)) return false;
32413
+ if (body.sectionBreaks !== void 0 && !Array.isArray(body.sectionBreaks)) return false;
32414
+ if (body.tables !== void 0 && !Array.isArray(body.tables)) return false;
32415
+ if (body.customRanges !== void 0 && !Array.isArray(body.customRanges)) return false;
32416
+ if (body.textRuns !== void 0 && !Array.isArray(body.textRuns)) return false;
32417
+ return true;
32418
+ }
32419
+ function restoreDocUnitStateOnFailure(accessor, docModel, unitId, prevSnapClone, prevMetaClone) {
32420
+ const commandService = accessor.get(import_core20.ICommandService);
32421
+ const sdtService = accessor.get(IDocSdtService);
32422
+ try {
32423
+ const curBody = docModel.getSnapshot().body;
32424
+ if (curBody && prevSnapClone.body && !import_core20.Tools.diffValue(curBody, prevSnapClone.body)) {
32425
+ const revertActions = buildBodyReplaceEditOp(curBody, import_core20.Tools.deepClone(prevSnapClone.body));
32426
+ if (revertActions) {
32427
+ const liveRef = docModel.getSnapshot();
32428
+ const wasDisabled = Boolean(liveRef.disabled);
32429
+ if (wasDisabled) liveRef.disabled = false;
32430
+ try {
32431
+ commandService.syncExecuteCommand(import_docs4.RichTextEditingMutation.id, {
32432
+ unitId,
32433
+ actions: revertActions,
32434
+ noHistory: true,
32435
+ noNeedSetTextRange: true
32436
+ });
32437
+ } finally {
32438
+ if (wasDisabled) liveRef.disabled = true;
32439
+ }
32440
+ }
32441
+ }
32442
+ } catch {
32443
+ }
32444
+ try {
32445
+ syncDocDrawingsToUniverServices(accessor, unitId, import_core20.Tools.deepClone(prevSnapClone));
32446
+ } catch {
32447
+ }
32448
+ sdtService.setTemplateMetadata(unitId, import_core20.Tools.deepClone(prevMetaClone));
32449
+ const liveSnap = docModel.getSnapshot();
32450
+ const exactPrev = import_core20.Tools.deepClone(prevSnapClone);
32451
+ for (const key of Object.keys(liveSnap)) {
32452
+ if (!(key in exactPrev)) {
32453
+ delete liveSnap[key];
32454
+ }
32455
+ }
32456
+ Object.assign(liveSnap, exactPrev);
32457
+ reinitializeDocHeaderFooterModels(docModel);
32458
+ }
31754
32459
  var ReplaceDocUnitSnapshotCommand = {
31755
32460
  id: "yudao-docs.command.replace-snapshot",
31756
32461
  type: import_core20.CommandType.COMMAND,
31757
32462
  handler: (accessor, params) => {
31758
- if (!params?.snapshot?.body) return false;
32463
+ if (!isValidReplacementDocSnapshot(params?.snapshot)) return false;
31759
32464
  const docModel = getTargetDocModel(accessor, params.unitId);
31760
32465
  if (!docModel) return false;
31761
32466
  const unitId = docModel.getUnitId();
31762
- const normalizedSnap = import_core20.Tools.deepClone(params.snapshot);
31763
- if (!normalizedSnap.id) {
31764
- normalizedSnap.id = unitId;
31765
- }
31766
- normalizeDocDrawingsAndPluginResource(normalizedSnap);
31767
- const prevSnap = docModel.getSnapshot();
31768
- const auxChanged = normalizedSnap.headers !== void 0 && !import_core20.Tools.diffValue(prevSnap.headers ?? {}, normalizedSnap.headers ?? {}) || normalizedSnap.footers !== void 0 && !import_core20.Tools.diffValue(prevSnap.footers ?? {}, normalizedSnap.footers ?? {}) || normalizedSnap.drawings !== void 0 && !import_core20.Tools.diffValue(prevSnap.drawings ?? {}, normalizedSnap.drawings ?? {}) || normalizedSnap.drawingsOrder !== void 0 && !import_core20.Tools.diffValue(prevSnap.drawingsOrder ?? [], normalizedSnap.drawingsOrder ?? []) || normalizedSnap.documentStyle !== void 0 && !import_core20.Tools.diffValue(prevSnap.documentStyle ?? {}, normalizedSnap.documentStyle ?? {}) || normalizedSnap.styles !== void 0 && !import_core20.Tools.diffValue(prevSnap.styles ?? {}, normalizedSnap.styles ?? {}) || normalizedSnap.tableSource !== void 0 && !import_core20.Tools.diffValue(prevSnap.tableSource ?? {}, normalizedSnap.tableSource ?? {});
31769
- syncSnapshotAuxFields(docModel, normalizedSnap);
31770
- reinitializeDocHeaderFooterModels(docModel);
31771
- syncDocDrawingsToUniverServices(accessor, unitId, normalizedSnap);
31772
- const snapMeta = readDocTemplateMetadataFromSnapshot(normalizedSnap);
31773
32467
  const sdtService = accessor.get(IDocSdtService);
31774
- sdtService.setTemplateMetadata(unitId, snapMeta);
31775
- sdtService.bumpRevision(unitId);
31776
- return executeBodyUpdateViaRichTextMutation(
31777
- accessor,
31778
- docModel,
31779
- normalizedSnap.body,
31780
- 0,
31781
- true,
31782
- Boolean(params.allowInViewMode),
31783
- auxChanged
31784
- );
32468
+ const allowInViewMode = Boolean(params.allowInViewMode);
32469
+ if (!allowInViewMode && sdtService.getDocMode(unitId) === "view") {
32470
+ return false;
32471
+ }
32472
+ const prevSnapClone = import_core20.Tools.deepClone(docModel.getSnapshot());
32473
+ const prevMetaClone = import_core20.Tools.deepClone(sdtService.getTemplateMetadata(unitId));
32474
+ try {
32475
+ const normalizedSnap = import_core20.Tools.deepClone(params.snapshot);
32476
+ if (!normalizedSnap.id) {
32477
+ normalizedSnap.id = unitId;
32478
+ }
32479
+ normalizeDocDrawingsAndPluginResource(normalizedSnap);
32480
+ if (!isValidReplacementDocSnapshot(normalizedSnap)) {
32481
+ return false;
32482
+ }
32483
+ const auxChanged = normalizedSnap.headers !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.headers ?? {}, normalizedSnap.headers ?? {}) || normalizedSnap.footers !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.footers ?? {}, normalizedSnap.footers ?? {}) || normalizedSnap.drawings !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.drawings ?? {}, normalizedSnap.drawings ?? {}) || normalizedSnap.drawingsOrder !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.drawingsOrder ?? [], normalizedSnap.drawingsOrder ?? []) || normalizedSnap.documentStyle !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.documentStyle ?? {}, normalizedSnap.documentStyle ?? {}) || normalizedSnap.styles !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.styles ?? {}, normalizedSnap.styles ?? {}) || normalizedSnap.tableSource !== void 0 && !import_core20.Tools.diffValue(prevSnapClone.tableSource ?? {}, normalizedSnap.tableSource ?? {});
32484
+ syncSnapshotAuxFields(docModel, normalizedSnap);
32485
+ reinitializeDocHeaderFooterModels(docModel);
32486
+ syncDocDrawingsToUniverServices(accessor, unitId, normalizedSnap);
32487
+ const snapMeta = readDocTemplateMetadataFromSnapshot(normalizedSnap);
32488
+ sdtService.setTemplateMetadata(unitId, snapMeta);
32489
+ const ok = executeBodyUpdateViaRichTextMutation(
32490
+ accessor,
32491
+ docModel,
32492
+ normalizedSnap.body,
32493
+ 0,
32494
+ true,
32495
+ allowInViewMode,
32496
+ auxChanged
32497
+ );
32498
+ if (!ok) {
32499
+ restoreDocUnitStateOnFailure(accessor, docModel, unitId, prevSnapClone, prevMetaClone);
32500
+ return false;
32501
+ }
32502
+ sdtService.bumpRevision(unitId);
32503
+ return true;
32504
+ } catch {
32505
+ restoreDocUnitStateOnFailure(accessor, docModel, unitId, prevSnapClone, prevMetaClone);
32506
+ return false;
32507
+ }
31785
32508
  }
31786
32509
  };
31787
32510
  var SetDocModeCommand = {
@@ -33640,6 +34363,47 @@ var DocIoTargetError = class extends Error {
33640
34363
  }
33641
34364
  };
33642
34365
  var IDocIoService = (0, import_core24.createIdentifier)("yudao.univer-docs.io.service");
34366
+ function createDocAbortError(signal) {
34367
+ const reason = signal?.reason;
34368
+ if (reason instanceof Error && reason.name === "AbortError") {
34369
+ return reason;
34370
+ }
34371
+ if (typeof DOMException !== "undefined") {
34372
+ return new DOMException("The operation was aborted.", "AbortError");
34373
+ }
34374
+ const err = new Error("The operation was aborted.");
34375
+ err.name = "AbortError";
34376
+ return err;
34377
+ }
34378
+ function throwIfDocIoAborted(signal) {
34379
+ if (signal?.aborted) {
34380
+ throw createDocAbortError(signal);
34381
+ }
34382
+ }
34383
+ async function runWithAbortSignal(executor, signal) {
34384
+ throwIfDocIoAborted(signal);
34385
+ if (!signal) {
34386
+ return executor();
34387
+ }
34388
+ let onAbort;
34389
+ const abortPromise = new Promise((_, reject) => {
34390
+ onAbort = () => reject(createDocAbortError(signal));
34391
+ if (signal.aborted) {
34392
+ onAbort();
34393
+ return;
34394
+ }
34395
+ signal.addEventListener("abort", onAbort, { once: true });
34396
+ });
34397
+ try {
34398
+ const result = await Promise.race([executor(), abortPromise]);
34399
+ throwIfDocIoAborted(signal);
34400
+ return result;
34401
+ } finally {
34402
+ if (onAbort) {
34403
+ signal.removeEventListener("abort", onAbort);
34404
+ }
34405
+ }
34406
+ }
33643
34407
  async function normalizeToUint8Array(raw) {
33644
34408
  if (raw instanceof Uint8Array) return raw;
33645
34409
  if (raw instanceof ArrayBuffer) return new Uint8Array(raw);
@@ -33713,8 +34477,9 @@ function unwrapAdapterImportResult(rawResult) {
33713
34477
  return { documentData: doc, warnings };
33714
34478
  }
33715
34479
  var DocIoService = class extends import_core24.Disposable {
33716
- constructor() {
34480
+ constructor(_univerInstanceService) {
33717
34481
  super();
34482
+ this._univerInstanceService = _univerInstanceService;
33718
34483
  this._adapter$ = new import_rxjs4.BehaviorSubject({ name: "frontend-default" });
33719
34484
  this._saved$ = new import_rxjs4.Subject();
33720
34485
  this._nextHookId = 1;
@@ -33835,8 +34600,11 @@ var DocIoService = class extends import_core24.Disposable {
33835
34600
  return hasHook ? "server" : "browser";
33836
34601
  }
33837
34602
  async importDocWithReport(file, options) {
34603
+ const signal = options?.signal;
34604
+ throwIfDocIoAborted(signal);
33838
34605
  let browserWarnings = [];
33839
34606
  const defaultImport = async (f) => {
34607
+ throwIfDocIoAborted(signal);
33840
34608
  const lower = f.name.toLowerCase();
33841
34609
  const fmtKey2 = inferFormatFromFileName(f.name);
33842
34610
  const caps = this.getIoCapabilities();
@@ -33846,15 +34614,19 @@ var DocIoService = class extends import_core24.Disposable {
33846
34614
  const baseTitle = f.name.replace(/\.[^.]+$/, "") || "\u672A\u547D\u540D\u6587\u6863";
33847
34615
  if (lower.endsWith(".docx")) {
33848
34616
  const ab = await f.arrayBuffer();
34617
+ throwIfDocIoAborted(signal);
33849
34618
  const report = await parseDocxBytesWithReport(new Uint8Array(ab), baseTitle);
34619
+ throwIfDocIoAborted(signal);
33850
34620
  browserWarnings = report.warnings;
33851
34621
  return report.documentData;
33852
34622
  }
33853
34623
  if (lower.endsWith(".rtf") || lower.endsWith(".odt") || lower.endsWith(".doc") || lower.endsWith(".xml")) {
33854
34624
  const ab = await f.arrayBuffer();
34625
+ throwIfDocIoAborted(signal);
33855
34626
  return importLegacyDocBytes(new Uint8Array(ab), baseTitle);
33856
34627
  }
33857
34628
  const text = await f.text();
34629
+ throwIfDocIoAborted(signal);
33858
34630
  if (lower.endsWith(".json")) {
33859
34631
  return JSON.parse(text);
33860
34632
  }
@@ -33880,10 +34652,14 @@ var DocIoService = class extends import_core24.Disposable {
33880
34652
  );
33881
34653
  }
33882
34654
  try {
33883
- const rawOutcome = await adapter.importDoc(file, {
33884
- unitId: options?.unitId,
33885
- defaultImport
33886
- });
34655
+ const rawOutcome = await runWithAbortSignal(
34656
+ () => adapter.importDoc(file, {
34657
+ unitId: options?.unitId,
34658
+ signal,
34659
+ defaultImport
34660
+ }),
34661
+ signal
34662
+ );
33887
34663
  const unwrapped = unwrapAdapterImportResult(rawOutcome);
33888
34664
  return {
33889
34665
  snapshot: unwrapped.documentData,
@@ -33893,6 +34669,9 @@ var DocIoService = class extends import_core24.Disposable {
33893
34669
  fileName: file.name
33894
34670
  };
33895
34671
  } catch (err) {
34672
+ if (err?.name === "AbortError") {
34673
+ throw err;
34674
+ }
33896
34675
  if (err && typeof err === "object" && !err.suggestedFallback) {
33897
34676
  err.suggestedFallback = "browser";
33898
34677
  }
@@ -33900,7 +34679,7 @@ var DocIoService = class extends import_core24.Disposable {
33900
34679
  }
33901
34680
  }
33902
34681
  try {
33903
- const documentData = await defaultImport(file);
34682
+ const documentData = await runWithAbortSignal(() => defaultImport(file), signal);
33904
34683
  return {
33905
34684
  snapshot: documentData,
33906
34685
  documentData,
@@ -33909,6 +34688,9 @@ var DocIoService = class extends import_core24.Disposable {
33909
34688
  fileName: file.name
33910
34689
  };
33911
34690
  } catch (err) {
34691
+ if (err?.name === "AbortError") {
34692
+ throw err;
34693
+ }
33912
34694
  if (err && typeof err === "object") {
33913
34695
  err.suggestedFallback = "server";
33914
34696
  }
@@ -33916,12 +34698,19 @@ var DocIoService = class extends import_core24.Disposable {
33916
34698
  }
33917
34699
  }
33918
34700
  async importDoc(file, unitId, options) {
33919
- const res = await this.importDocWithReport(file, { unitId, target: options?.target });
34701
+ const res = await this.importDocWithReport(file, {
34702
+ unitId,
34703
+ target: options?.target,
34704
+ signal: options?.signal
34705
+ });
33920
34706
  return res.documentData;
33921
34707
  }
33922
34708
  async exportDoc(params) {
34709
+ const signal = params.signal;
34710
+ throwIfDocIoAborted(signal);
33923
34711
  const format = params.format ?? "docx";
33924
34712
  const defaultExport = async () => {
34713
+ throwIfDocIoAborted(signal);
33925
34714
  const caps = this.getIoCapabilities();
33926
34715
  if (format in caps.formats.export && !caps.formats.export[format].browser) {
33927
34716
  throw new Error(`\u5F53\u524D\u6D4F\u89C8\u5668\u672C\u5730\u5F15\u64CE\u672A\u542F\u7528 .${format} \u683C\u5F0F\u5BFC\u51FA`);
@@ -34008,16 +34797,25 @@ var DocIoService = class extends import_core24.Disposable {
34008
34797
  );
34009
34798
  }
34010
34799
  try {
34011
- const raw = await adapter.exportDoc({
34012
- unitId: params.unitId,
34013
- snapshot: params.snapshot,
34014
- format,
34015
- data: params.data,
34016
- pdfOptions: params.pdfOptions,
34017
- defaultExport
34018
- });
34019
- return normalizeToUint8Array(raw);
34800
+ const raw = await runWithAbortSignal(
34801
+ () => adapter.exportDoc({
34802
+ unitId: params.unitId,
34803
+ snapshot: params.snapshot,
34804
+ format,
34805
+ data: params.data,
34806
+ pdfOptions: params.pdfOptions,
34807
+ signal,
34808
+ defaultExport
34809
+ }),
34810
+ signal
34811
+ );
34812
+ const bytes = await normalizeToUint8Array(raw);
34813
+ throwIfDocIoAborted(signal);
34814
+ return bytes;
34020
34815
  } catch (err) {
34816
+ if (err?.name === "AbortError") {
34817
+ throw err;
34818
+ }
34021
34819
  if (err && typeof err === "object" && !err.suggestedFallback) {
34022
34820
  err.suggestedFallback = "browser";
34023
34821
  }
@@ -34025,14 +34823,49 @@ var DocIoService = class extends import_core24.Disposable {
34025
34823
  }
34026
34824
  }
34027
34825
  try {
34028
- return await defaultExport();
34826
+ return await runWithAbortSignal(() => defaultExport(), signal);
34029
34827
  } catch (err) {
34828
+ if (err?.name === "AbortError") {
34829
+ throw err;
34830
+ }
34030
34831
  if (err && typeof err === "object") {
34031
34832
  err.suggestedFallback = "server";
34032
34833
  }
34033
34834
  throw err;
34034
34835
  }
34035
34836
  }
34837
+ async exportDocFromUnit(unitIdOrParams, options) {
34838
+ const normalized = typeof unitIdOrParams === "string" || unitIdOrParams === void 0 ? { ...options ?? {}, ...unitIdOrParams !== void 0 ? { unitId: unitIdOrParams } : {} } : unitIdOrParams;
34839
+ throwIfDocIoAborted(normalized.signal);
34840
+ let resolvedSnapshot = normalized.snapshot;
34841
+ let resolvedUnitId = normalized.unitId || "";
34842
+ if (!resolvedSnapshot && this._univerInstanceService) {
34843
+ const docModel = normalized.unitId ? this._univerInstanceService.getUnit(
34844
+ normalized.unitId,
34845
+ import_core24.UniverInstanceType.UNIVER_DOC
34846
+ ) : this._univerInstanceService.getCurrentUnitOfType(
34847
+ import_core24.UniverInstanceType.UNIVER_DOC
34848
+ );
34849
+ if (docModel) {
34850
+ resolvedUnitId = docModel.getUnitId();
34851
+ resolvedSnapshot = docModel.getSnapshot();
34852
+ }
34853
+ }
34854
+ if (!resolvedSnapshot) {
34855
+ throw new Error(
34856
+ `\u65E0\u6CD5\u5BFC\u51FA\u6587\u6863\uFF1A\u672A\u627E\u5230\u6587\u6863\u5B9E\u4F8B${resolvedUnitId ? ` (${resolvedUnitId})` : ""}`
34857
+ );
34858
+ }
34859
+ return this.exportDoc({
34860
+ unitId: resolvedUnitId || resolvedSnapshot.id || "doc",
34861
+ snapshot: resolvedSnapshot,
34862
+ format: normalized.format,
34863
+ data: normalized.data,
34864
+ pdfOptions: normalized.pdfOptions,
34865
+ target: normalized.target,
34866
+ signal: normalized.signal
34867
+ });
34868
+ }
34036
34869
  async saveToHost(context) {
34037
34870
  let canceled = false;
34038
34871
  const beforeEv = {
@@ -34071,6 +34904,9 @@ var DocIoService = class extends import_core24.Disposable {
34071
34904
  return true;
34072
34905
  }
34073
34906
  };
34907
+ DocIoService = __decorateClass([
34908
+ __decorateParam(0, (0, import_core24.Optional)(import_core24.IUniverInstanceService))
34909
+ ], DocIoService);
34074
34910
 
34075
34911
  // src/plugin.ts
34076
34912
  var VIEW_MODE_BLOCKED_PREFIXES = [
@@ -34340,6 +35176,7 @@ UniverDocsExtPlugin = __decorateClass([
34340
35176
  DocIoService,
34341
35177
  DocIoTargetError,
34342
35178
  DocSdtService,
35179
+ DocTemplateProtocolError,
34343
35180
  DocxImportError,
34344
35181
  EvaluateDocCascadeRulesCommand,
34345
35182
  EvaluateDocTableFormulasCommand,
@@ -34351,6 +35188,7 @@ UniverDocsExtPlugin = __decorateClass([
34351
35188
  IDocExtensionRegistryService,
34352
35189
  IDocIoService,
34353
35190
  IDocSdtService,
35191
+ INLINE_VALUE_TOKEN_RE,
34354
35192
  InsertDocAreaCommand,
34355
35193
  InsertDocBibliographyCommand,
34356
35194
  InsertDocBookmarkCommand,
@@ -34497,6 +35335,7 @@ UniverDocsExtPlugin = __decorateClass([
34497
35335
  computeToggledMultiOptionValue,
34498
35336
  convertDocTableToText,
34499
35337
  convertTextToDocTableInSnapshot,
35338
+ createDocAbortError,
34500
35339
  decodeImageDataUrlForPdf,
34501
35340
  deleteColumnGroupFromSnapshot,
34502
35341
  deleteDocArea,
@@ -34538,7 +35377,10 @@ UniverDocsExtPlugin = __decorateClass([
34538
35377
  extractAnchorTypography,
34539
35378
  extractDocCatalog,
34540
35379
  extractDocCatalogTree,
35380
+ extractDocFieldInstruction,
34541
35381
  extractDocFormValues,
35382
+ extractDocInlinePlaceholders,
35383
+ extractNativeTextSpansFromPdfBytes,
34542
35384
  fillDatasetIntoDocSnapshot,
34543
35385
  findAndReplaceDocTextInSnapshot,
34544
35386
  findMergedMasterInTableRows,
@@ -34630,6 +35472,7 @@ UniverDocsExtPlugin = __decorateClass([
34630
35472
  insertSyntaxCodeBlockIntoSnapshot,
34631
35473
  insertTableOfContentsIntoSnapshot,
34632
35474
  inspectDocxExportCapabilities,
35475
+ isDynamicPageFieldInstruction,
34633
35476
  isEditBlockedByTitleLock,
34634
35477
  isOffsetInLockedTableCell,
34635
35478
  isOffsetLockedByGroupSdt,
@@ -34660,6 +35503,7 @@ UniverDocsExtPlugin = __decorateClass([
34660
35503
  normalizeSdtListItems,
34661
35504
  numberToChineseUpperMoney,
34662
35505
  parseDateRangePair,
35506
+ parseDocBindingKey,
34663
35507
  parseDocxBytesToDocData,
34664
35508
  parseDocxBytesWithReport,
34665
35509
  parseFieldInstrString,
@@ -34753,6 +35597,7 @@ UniverDocsExtPlugin = __decorateClass([
34753
35597
  splitDocTableCellInSnapshot,
34754
35598
  stripDocEditorChromeForView,
34755
35599
  stripSdtAffixes,
35600
+ summarizeDocTemplate,
34756
35601
  syncDocDrawingsToUniverServices,
34757
35602
  syncSnapshotAuxFields,
34758
35603
  toControlSpecSnapshot,