@ai-matrx/office 0.5.2 → 0.6.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","../src/sheets/univer-to-xlsx.ts","../src/sheets/import-workbook-file.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,oDAA0B;AAG1B,kDAA6B;AAC7B,yDAA+C;AAoCxC,SAAS,4BAAA,CAA6B,QAAA,EAAkC;AAC7E,EAAA,MAAM,WAAA,mBAAa,QAAA,CAAS,UAAA,UAAc,MAAA,CAAO,IAAA,kBAAK,QAAA,CAAS,MAAA,UAAU,CAAC,GAAC,GAAA;AAC3E,EAAA,MAAM,OAAA,EAAiC,CAAC,CAAA;AACxC,EAAA,IAAA,CAAA,MAAW,QAAA,GAAW,UAAA,EAAY;AAChC,IAAA,MAAM,MAAA,kBAAQ,QAAA,mBAAS,MAAA,4BAAA,CAAS,OAAO,GAAA;AACvC,IAAA,GAAA,CAAI,CAAC,KAAA,EAAO,QAAA;AACZ,IAAA,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,KAAA,EAAA,kBAAQ,KAAA,CAAM,IAAA,UAAQ,SAAA,CAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,EAAA,GAAK,QAAQ,CAAC,CAAA;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,OAAO,CAAA;AAClB;AAGA,MAAA,SAAsB,yBAAA,CACpB,QAAA,EACA,QAAA,EAAmD,CAAC,CAAA,EAC/B;AACrB,EAAA,OAAA,CAAQ,MAAM,mBAAA,CAAoB,QAAA,EAAU,OAAO,CAAA,CAAA,CAAG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ACC,IAAA;AACE,IAAA;AACC,IAAA;AACF,IAAA;AACC,MAAA;AACG,MAAA;AACC,MAAA;AACR,MAAA;AACA,MAAA;AACO,MAAA;AACuB,MAAA;AAC3B,MAAA;AACE,QAAA;AACA,QAAA;AACJ,QAAA;AACI,MAAA;AACD,QAAA;AACV,MAAA;AACY,MAAA;AACH,MAAA;AACI,MAAA;AACC,MAAA;AACH,MAAA;AACb,IAAA;AACF,EAAA;AACF;AAES;AACD,EAAA;AACU,EAAA;AACE,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACN,IAAA;AACM,IAAA;AACjB,EAAA;AACa,EAAA;AACK,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACA,IAAA;AACjB,EAAA;AACgB,EAAA;AACV,IAAA;AACY,MAAA;AACR,IAAA;AAER,IAAA;AACF,EAAA;AACe,EAAA;AACA,EAAA;AACC,IAAA;AAChB,EAAA;AACF;AAEkB;AACR,EAAA;AACQ,EAAA;AACC,IAAA;AACJ,MAAA;AACG,QAAA;AACC,QAAA;AACb,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACI,EAAA;AACI,IAAA;AACM,IAAA;AACL,MAAA;AACZ,MAAA;AACY,MAAA;AACA,MAAA;AACZ,MAAA;AACa,MAAA;AACA,MAAA;AACf,IAAA;AACsB,IAAA;AACT,IAAA;AACA,MAAA;AACL,MAAA;AACI,MAAA;AACG,MAAA;AACJ,IAAA;AACC,MAAA;AACE,MAAA;AACF,IAAA;AACL,MAAA;AACA,QAAA;AACH,QAAA;AACU,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACC,MAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACF,IAAA;AACO,MAAA;AACZ,IAAA;AACc,IAAA;AACjB,EAAA;AACF;AAEmB;AAEF;AACI,EAAA;AACC,EAAA;AACT,EAAA;AACE,EAAA;AACK,EAAA;AACA,EAAA;AACF,EAAA;AACL,EAAA;AACC,EAAA;AACL,EAAA;AACT;AAES;AACI,EAAA;AACO,IAAA;AACJ,IAAA;AACA,IAAA;AACE,IAAA;AACE,IAAA;AACH,IAAA;AACU,IAAA;AACb,IAAA;AACM,MAAA;AACD,MAAA;AACN,QAAA;AACC,UAAA;AACM,YAAA;AACV,UAAA;AACA,UAAA;AACG,QAAA;AACM,UAAA;AACT,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACJ,MAAA;AACS,IAAA;AACI,MAAA;AACP,MAAA;AACE,QAAA;AACI,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACH,MAAA;AACE,QAAA;AACI,QAAA;AACD,QAAA;AACA,QAAA;AACX,MAAA;AACF,IAAA;AACU,IAAA;AACI,MAAA;AACZ,MAAA;AACF,IAAA;AACG,IAAA;AACL,EAAA;AACF;AAES;AACK,EAAA;AACF,EAAA;AACM,EAAA;AACD,IAAA;AACE,IAAA;AACjB,EAAA;AACa,EAAA;AACC,IAAA;AACd,EAAA;AACF;AAEoB;AACD,EAAA;AACnB;AAEoB;AACD,EAAA;AACH,IAAA;AACG,MAAA;AACA,MAAA;AACf,IAAA;AACF,EAAA;AACqB,EAAA;AACL,EAAA;AACA,EAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACA,IAAA;AACH,IAAA;AACK,MAAA;AAChB,IAAA;AACc,IAAA;AAChB,EAAA;AACiB,EAAA;AACC,IAAA;AACV,IAAA;AACO,IAAA;AACf,EAAA;AACkB,EAAA;AACpB;AAEe;AAOC,EAAA;AACE,EAAA;AACR,IAAA;AACS,IAAA;AACJ,IAAA;AACoB,IAAA;AACS,IAAA;AACxB,IAAA;AACH,IAAA;AACC,MAAA;AACJ,MAAA;AACC,IAAA;AACL,MAAA;AACU,QAAA;AACA,QAAA;AACN,MAAA;AACE,QAAA;AACV,MAAA;AACF,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ClB,EAAA;AAEa,EAAA;AACf;AFwYoB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","sourcesContent":[null,"/**\n * univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.\n *\n * Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx\n * format can hold from what Univer holds: values, formulas, merged ranges,\n * cell styles and number formats, column widths, row heights, frozen panes,\n * data validation, conditional formatting, the header-row filter range,\n * notes, comment threads (as notes), cell links, and pictures.\n *\n * What it cannot carry is NAMED in the returned report and shown to the person\n * at export time — never dropped silently.\n *\n * Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,\n * conditional formatting, notes, links and images; the registered\n * `xlsx-workbook` format writes values only). It is loaded on demand, so\n * the editor bundle does not pay for it until someone exports or imports.\n */\n\nimport { buildFile } from \"@ai-matrx/alchemy/operate\";\nimport type { WorkbookCellJson, WorkbookJson } from \"@ai-matrx/alchemy/operate/read\";\nimport type { ICellData, IWorkbookData, IWorksheetData } from \"@univerjs/core\";\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { loadExcelJs, type ExcelJSTypes } from \"@ai-matrx/print/xlsx-styled\";\nimport {\n H_ALIGN_OUT,\n RESOURCE,\n V_ALIGN_OUT,\n borderToExcel,\n colPxToChars,\n colorToArgb,\n readResource,\n rangeToA1,\n rowPxToPt,\n type RangeLike,\n type UniverResource,\n} from \"./xlsx-shared\";\n\nexport type ExportXlsxOptions = {\n /** File name without extension. Defaults to \"workbook\". */\n filename?: string;\n /** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */\n resolveImage?: ExportImagePort;\n};\n\nexport type ExportImagePort = (\n source: string,\n) => Promise<{ bytes: Uint8Array; extension: \"png\" | \"jpeg\" | \"gif\" } | null>;\n\n/** What an export could not carry, in words for the person. Empty when nothing was lost. */\nexport type XlsxExportReport = { dropped: string[] };\n\ntype Snapshot = Partial<IWorkbookData>;\ntype Style = Record<string, unknown>;\ntype Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- Univer resource payloads are untyped JSON\n\n// ─── the thin WorkbookJson path (values + merges), kept for other callers ───\n\n/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */\nexport function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson {\n const sheetOrder = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n const sheets: WorkbookJson[\"sheets\"] = [];\n for (const sheetId of sheetOrder) {\n const sheet = snapshot.sheets?.[sheetId];\n if (!sheet) continue;\n sheets.push(sheetToJson(sheet, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n }\n return { sheets };\n}\n\n/** Full-fidelity bytes. Does NOT trigger a download. */\nexport async function univerSnapshotToXlsxBytes(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<Uint8Array> {\n return (await buildXlsxFromUniver(snapshot, options)).bytes;\n}\n\n/** Convert + trigger a browser download; returns what could not be carried. */\nexport async function downloadUniverAsXlsx(\n snapshot: Snapshot,\n options: ExportXlsxOptions = {},\n): Promise<XlsxExportReport> {\n if (typeof document === \"undefined\") return { dropped: [] };\n const filename = `${(options.filename ?? \"workbook\").replace(/\\.xlsx$/i, \"\")}.xlsx`;\n const { bytes, report } = await buildXlsxFromUniver(snapshot, options);\n const blob = new Blob([bytes as BlobPart], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n });\n downloadFile(filename, blob, blob.type);\n return report;\n}\n\n// ─── the full-fidelity writer ──────────────────────────────────────────────\n\nexport async function buildXlsxFromUniver(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<{ bytes: Uint8Array; report: XlsxExportReport }> {\n const ExcelJS = await loadExcelJs();\n const wb = new ExcelJS.Workbook();\n const dropped = new Set<string>();\n const resources = (snapshot.resources ?? []) as UniverResource[];\n const styles = (snapshot.styles ?? {}) as Record<string, Style>;\n\n const validation = readResource<Json>(resources, RESOURCE.validation) ?? {};\n const conditional = readResource<Json>(resources, RESOURCE.conditional) ?? {};\n const filters = readResource<Json>(resources, RESOURCE.filter) ?? {};\n const notes = readResource<Json>(resources, RESOURCE.note) ?? {};\n const comments = readResource<Json>(resources, RESOURCE.comments) ?? {};\n const drawings = readResource<Json>(resources, RESOURCE.drawing) ?? {};\n const tables = readResource<Json>(resources, RESOURCE.table) ?? {};\n\n const order = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n for (const sheetId of order) {\n const sheet = snapshot.sheets?.[sheetId] as Partial<IWorksheetData> | undefined;\n if (!sheet) continue;\n const ws = wb.addWorksheet(uniqueName(wb, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n writeCells(ws, sheet, styles);\n writeLayout(ws, sheet);\n const tab = colorToArgb(typeof sheet.tabColor === \"string\" ? sheet.tabColor : undefined);\n if (tab) ws.properties.tabColor = { argb: tab };\n writeValidation(ws, validation[sheetId], dropped);\n writeConditional(ws, conditional[sheetId], dropped);\n writeFilter(ws, filters[sheetId], dropped);\n writeNotes(ws, notes[sheetId], comments[sheetId], dropped);\n await writeImages(wb, ws, drawings[sheetId], options.resolveImage, dropped);\n if (tables[sheetId] && Object.keys(tables[sheetId]).length) {\n dropped.add(\"Tables are exported as plain ranges (their data and styling are kept)\");\n }\n }\n\n const buffer = await wb.xlsx.writeBuffer();\n return { bytes: new Uint8Array(buffer as ArrayBuffer), report: { dropped: [...dropped] } };\n}\n\nfunction uniqueName(wb: ExcelJSTypes.Workbook, name: string): string {\n let candidate = name;\n let n = 2;\n while (wb.getWorksheet(candidate)) candidate = `${name.slice(0, 28)} ${n++}`;\n return candidate;\n}\n\nfunction styleOf(cell: ICellData, styles: Record<string, Style>): Style | undefined {\n const s = cell.s;\n if (!s) return undefined;\n return typeof s === \"string\" ? styles[s] : (s as Style);\n}\n\nfunction applyStyle(target: ExcelJSTypes.Cell, st: Style | undefined): void {\n if (!st) return;\n const font: Partial<ExcelJSTypes.Font> = {};\n if (st.ff) font.name = String(st.ff);\n if (typeof st.fs === \"number\") font.size = st.fs;\n if (st.bl === 1) font.bold = true;\n if (st.it === 1) font.italic = true;\n if ((st.ul as Json | undefined)?.s === 1) font.underline = true;\n if ((st.st as Json | undefined)?.s === 1) font.strike = true;\n const fg = colorToArgb((st.cl as Json | undefined)?.rgb);\n if (fg) font.color = { argb: fg };\n if (Object.keys(font).length) target.font = font;\n const bg = colorToArgb((st.bg as Json | undefined)?.rgb);\n if (bg) target.fill = { type: \"pattern\", pattern: \"solid\", fgColor: { argb: bg } };\n const alignment: Partial<ExcelJSTypes.Alignment> = {};\n if (typeof st.ht === \"number\" && H_ALIGN_OUT[st.ht]) alignment.horizontal = H_ALIGN_OUT[st.ht] as ExcelJSTypes.Alignment[\"horizontal\"];\n if (typeof st.vt === \"number\" && V_ALIGN_OUT[st.vt]) alignment.vertical = V_ALIGN_OUT[st.vt] as ExcelJSTypes.Alignment[\"vertical\"];\n if (st.tb === 3) alignment.wrapText = true;\n if (Object.keys(alignment).length) target.alignment = alignment;\n const bd = st.bd as Json | undefined;\n if (bd) {\n const border: Partial<ExcelJSTypes.Borders> = {};\n for (const [key, side] of [[\"t\", \"top\"], [\"b\", \"bottom\"], [\"l\", \"left\"], [\"r\", \"right\"]] as const) {\n const b = bd[key] as Json | undefined;\n const style = borderToExcel(b?.s);\n if (style) {\n (border as Json)[side] = { style, color: { argb: colorToArgb(b?.cl?.rgb) ?? \"FF000000\" } };\n }\n }\n if (Object.keys(border).length) target.border = border;\n }\n const pattern = (st.n as Json | undefined)?.pattern;\n if (typeof pattern === \"string\" && pattern && pattern !== \"General\") target.numFmt = pattern;\n}\n\nfunction plainText(p: Json | undefined): string {\n return String(p?.body?.dataStream ?? \"\").replace(/\\r\\n$/, \"\").replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction linkOf(p: Json | undefined): string | undefined {\n const ranges = p?.body?.customRanges as Json[] | undefined;\n return ranges?.find((r) => r.rangeType === 0 && r.properties?.url)?.properties?.url;\n}\n\nfunction writeCells(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>, styles: Record<string, Style>): void {\n const cellData = sheet.cellData ?? {};\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n const row = cellData[r];\n if (!row || !Number.isFinite(r)) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n const cell = row[c] as ICellData | undefined;\n if (!cell || !Number.isFinite(c)) continue;\n const target = ws.getCell(r + 1, c + 1);\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n const rich = cell.p as Json | undefined;\n let value: ExcelJSTypes.CellValue = null;\n if (cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n if (cell.t === 3) value = Boolean(cell.v);\n else if (cell.t === 2 || typeof cell.v === \"number\") value = Number(cell.v);\n else value = String(cell.v);\n } else if (rich) {\n value = plainText(rich);\n }\n const url = linkOf(rich);\n if (url) value = { text: String(value ?? url), hyperlink: url };\n if (formula) value = { formula, result: (value as number | string | boolean | undefined) ?? undefined } as ExcelJSTypes.CellFormulaValue;\n if (value !== null && value !== \"\") target.value = value;\n applyStyle(target, styleOf(cell, styles));\n }\n }\n}\n\nfunction writeLayout(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>): void {\n const defaultCol = sheet.defaultColumnWidth;\n const columns = sheet.columnData ?? {};\n for (const key of Object.keys(columns)) {\n const c = Number(key);\n const col = columns[c];\n if (!col) continue;\n const target = ws.getColumn(c + 1);\n if (typeof col.w === \"number\") target.width = colPxToChars(col.w);\n else if (defaultCol) target.width = colPxToChars(defaultCol);\n if (col.hd === 1) target.hidden = true;\n }\n const rows = sheet.rowData ?? {};\n for (const key of Object.keys(rows)) {\n const r = Number(key);\n const row = rows[r];\n if (!row) continue;\n const target = ws.getRow(r + 1);\n if (typeof row.h === \"number\") target.height = rowPxToPt(row.h);\n if (row.hd === 1) target.hidden = true;\n }\n for (const m of sheet.mergeData ?? []) {\n try {\n ws.mergeCells(m.startRow + 1, m.startColumn + 1, m.endRow + 1, m.endColumn + 1);\n } catch {\n /* an overlapping merge in a damaged snapshot: keep the first */\n }\n }\n const freeze = sheet.freeze;\n if (freeze && (freeze.xSplit > 0 || freeze.ySplit > 0)) {\n ws.views = [{ state: \"frozen\", xSplit: freeze.xSplit, ySplit: freeze.ySplit }];\n }\n}\n\nconst eachCell = (ranges: RangeLike[], fn: (row: number, col: number) => void, cap = 100_000): boolean => {\n let n = 0;\n for (const r of ranges) {\n for (let row = r.startRow; row <= r.endRow; row++) {\n for (let col = r.startColumn; col <= r.endColumn; col++) {\n if (++n > cap) return false;\n fn(row, col);\n }\n }\n }\n return true;\n};\n\nfunction writeValidation(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const rule of rules ?? []) {\n const type = String(rule.type);\n const base: Json = {\n allowBlank: rule.allowBlank !== false,\n showErrorMessage: rule.showErrorMessage !== false,\n errorTitle: rule.errorTitle,\n error: rule.error,\n showInputMessage: Boolean(rule.showInputMessage),\n promptTitle: rule.promptTitle,\n prompt: rule.prompt,\n };\n let dv: Json | null = null;\n if (type === \"list\" || type === \"listMultiple\") {\n const f1 = String(rule.formula1 ?? \"\");\n const isRange = /^=?'?[^,\"]*!?\\$?[A-Z]+\\$?\\d+(:\\$?[A-Z]+\\$?\\d+)?$/i.test(f1) && !f1.includes(\",\");\n dv = { ...base, type: \"list\", formulae: [isRange ? f1.replace(/^=/, \"\") : `\"${f1.replace(/\"/g, \"\")}\"`] };\n if (type === \"listMultiple\") dropped.add(\"Multi-select dropdowns become single-select\");\n } else if (type === \"checkbox\") {\n dv = { ...base, type: \"list\", formulae: ['\"TRUE,FALSE\"'] };\n dropped.add(\"Checkboxes become TRUE/FALSE dropdowns\");\n } else if ([\"whole\", \"decimal\", \"date\", \"time\", \"textLength\"].includes(type)) {\n dv = {\n ...base,\n type,\n operator: rule.operator ?? \"between\",\n formulae: [rule.formula1, rule.formula2].filter((f) => f !== undefined && f !== \"\"),\n };\n } else if (type === \"custom\") {\n dv = { ...base, type: \"custom\", formulae: [String(rule.formula1 ?? \"\").replace(/^=/, \"\")] };\n }\n if (!dv) continue;\n if (!dv.errorTitle) delete dv.errorTitle;\n const complete = eachCell((rule.ranges ?? []) as RangeLike[], (r, c) => {\n ws.getCell(r + 1, c + 1).dataValidation = dv as ExcelJSTypes.DataValidation;\n });\n if (!complete) dropped.add(\"Data validation on very large ranges was cut off\");\n }\n}\n\nconst NUMBER_OPS = new Set([\"greaterThan\", \"greaterThanOrEqual\", \"lessThan\", \"lessThanOrEqual\", \"equal\", \"notEqual\", \"between\", \"notBetween\"]);\n\nfunction cfStyle(style: Json | undefined): Json {\n const out: Json = {};\n const font: Json = {};\n const fg = colorToArgb(style?.cl?.rgb);\n if (fg) font.color = { argb: fg };\n if (style?.bl === 1) font.bold = true;\n if (style?.it === 1) font.italic = true;\n if (Object.keys(font).length) out.font = font;\n const bg = colorToArgb(style?.bg?.rgb);\n if (bg) out.fill = { type: \"pattern\", pattern: \"solid\", bgColor: { argb: bg } };\n return out;\n}\n\nfunction writeConditional(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const entry of rules ?? []) {\n const ranges = (entry.ranges ?? []) as RangeLike[];\n if (!ranges.length) continue;\n const ref = ranges.map(rangeToA1).join(\" \");\n const first = ranges[0]!;\n const topLeft = rangeToA1({ ...first, endRow: first.startRow, endColumn: first.startColumn });\n const rule = entry.rule as Json;\n let out: Json | null = null;\n if (rule?.type === \"highlightCell\") {\n const style = cfStyle(rule.style);\n switch (rule.subType) {\n case \"number\":\n if (NUMBER_OPS.has(rule.operator)) {\n out = { type: \"cellIs\", operator: rule.operator, formulae: Array.isArray(rule.value) ? rule.value : [rule.value], style };\n }\n break;\n case \"text\":\n if (rule.operator === \"containsText\") out = { type: \"containsText\", operator: \"containsText\", text: String(rule.value ?? \"\"), style };\n break;\n case \"duplicateValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})>1`], style };\n break;\n case \"uniqueValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})=1`], style };\n break;\n case \"formula\":\n out = { type: \"expression\", formulae: [String(rule.value ?? \"\").replace(/^=/, \"\")], style };\n break;\n }\n } else if (rule?.type === \"colorScale\" && Array.isArray(rule.config)) {\n const cfg = [...rule.config].sort((a: Json, b: Json) => a.index - b.index);\n out = {\n type: \"colorScale\",\n cfvo: cfg.map((c: Json) => ({ type: c.value?.type ?? \"min\", ...(c.value?.value !== undefined ? { value: c.value.value } : {}) })),\n color: cfg.map((c: Json) => ({ argb: colorToArgb(c.color) ?? \"FFFFFFFF\" })),\n };\n } else if (rule?.type === \"dataBar\") {\n out = {\n type: \"dataBar\",\n gradient: rule.config?.isGradient !== false,\n cfvo: [{ type: rule.config?.min?.type ?? \"min\" }, { type: rule.config?.max?.type ?? \"max\" }],\n color: { argb: colorToArgb(rule.config?.positiveColor) ?? \"FF638EC6\" },\n };\n }\n if (!out) {\n dropped.add(\"Some conditional formats (icon sets, top/bottom, average, date rules) are not written\");\n continue;\n }\n ws.addConditionalFormatting({ ref, rules: [{ ...out, priority: 1 }] } as ExcelJSTypes.ConditionalFormattingOptions);\n }\n}\n\nfunction writeFilter(ws: ExcelJSTypes.Worksheet, filter: Json | undefined, dropped: Set<string>): void {\n const ref = filter?.ref as RangeLike | undefined;\n if (!ref) return;\n ws.autoFilter = {\n from: { row: ref.startRow + 1, column: ref.startColumn + 1 },\n to: { row: ref.endRow + 1, column: ref.endColumn + 1 },\n };\n if ((filter?.filterColumns as unknown[] | undefined)?.length) {\n dropped.add(\"Which filter choices were applied is not saved (the filter arrows are)\");\n }\n}\n\nfunction threadText(c: Json): string {\n return String(c?.text?.dataStream ?? \"\").replace(/\\r\\n?$/, \"\").replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction writeNotes(ws: ExcelJSTypes.Worksheet, sheetNotes: Json | undefined, sheetComments: Json | Json[] | undefined, dropped: Set<string>): void {\n for (const [row, cols] of Object.entries(sheetNotes ?? {})) {\n for (const [col, note] of Object.entries(cols as Json)) {\n const text = String((note as Json).note ?? \"\");\n if (text) ws.getCell(Number(row) + 1, Number(col) + 1).note = text;\n }\n }\n const list: Json[] = Array.isArray(sheetComments) ? sheetComments : sheetComments ? Object.values(sheetComments).flat() : [];\n const threads = new Map<string, string[]>();\n for (const c of list) {\n if (!c?.ref) continue;\n const lines = threads.get(c.ref) ?? [];\n const who = c.authorName ?? c.personId ?? \"\";\n lines.push(`${who ? who + \": \" : \"\"}${threadText(c)}`);\n for (const child of (c.children ?? []) as Json[]) {\n lines.push(`${child.authorName ?? child.personId ?? \"\"}: ${threadText(child)}`);\n }\n threads.set(c.ref, lines);\n }\n for (const [ref, lines] of threads) {\n const cell = ws.getCell(ref);\n const existing = typeof cell.note === \"string\" ? cell.note : \"\";\n cell.note = [existing, ...lines].filter(Boolean).join(\"\\n\");\n }\n if (threads.size) dropped.add(\"Comment threads are written as cell notes (replies and resolved state are flattened)\");\n}\n\nasync function writeImages(\n wb: ExcelJSTypes.Workbook,\n ws: ExcelJSTypes.Worksheet,\n sheetDrawings: Json | undefined,\n resolve: ExportImagePort | undefined,\n dropped: Set<string>,\n): Promise<void> {\n const data = (sheetDrawings?.data ?? {}) as Record<string, Json>;\n for (const d of Object.values(data)) {\n if (d.drawingType !== 0 || !d.source) continue;\n const from = d.sheetTransform?.from;\n if (!from) continue;\n let bytes: Uint8Array | null = null;\n let extension: \"png\" | \"jpeg\" | \"gif\" = \"png\";\n const dataUrl = /^data:image\\/(png|jpeg|jpg|gif);base64,(.+)$/i.exec(String(d.source));\n if (dataUrl) {\n extension = dataUrl[1]!.toLowerCase() === \"gif\" ? \"gif\" : dataUrl[1]!.toLowerCase() === \"png\" ? \"png\" : \"jpeg\";\n bytes = Uint8Array.from(atob(dataUrl[2]!), (ch) => ch.charCodeAt(0));\n } else if (resolve) {\n try {\n const got = await resolve(String(d.source));\n if (got) ({ bytes, extension } = got);\n } catch {\n bytes = null;\n }\n }\n if (!bytes) {\n dropped.add(\"Some pictures could not be read and were left out\");\n continue;\n }\n const id = wb.addImage({ buffer: bytes as unknown as NonNullable<Parameters<typeof wb.addImage>[0][\"buffer\"]>, extension });\n ws.addImage(id, {\n tl: { col: from.column + (from.columnOffset ?? 0) / 64, row: from.row + (from.rowOffset ?? 0) / 20 },\n ext: { width: d.transform?.width ?? 200, height: d.transform?.height ?? 150 },\n });\n }\n}\n\n// ─── internals of the thin path ────────────────────────────────────────────\n\nfunction sheetToJson(sheet: Partial<IWorksheetData>, name: string): WorkbookJson[\"sheets\"][number] {\n const cellData = sheet.cellData ?? {};\n const rows: (WorkbookCellJson | null)[][] = [];\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n if (!Number.isFinite(r)) continue;\n const row = cellData[r];\n if (!row) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n if (!Number.isFinite(c)) continue;\n const cell = row[c];\n if (!cell) continue;\n const out = toWorkbookCell(cell);\n if (!out) continue;\n while (rows.length <= r) rows.push([]);\n const line = rows[r]!;\n while (line.length < c) line.push(null);\n line[c] = out;\n }\n }\n const merges = (sheet.mergeData ?? []).map((m) => ({\n s: { r: m.startRow, c: m.startColumn },\n e: { r: m.endRow, c: m.endColumn },\n }));\n return { name, rows, ...(merges.length ? { merges } : {}) };\n}\n\nfunction toWorkbookCell(cell: ICellData): WorkbookCellJson | null {\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n let out: WorkbookCellJson;\n switch (cell.t) {\n case 2:\n out = { t: \"n\", v: typeof cell.v === \"number\" ? cell.v : Number(cell.v ?? 0) };\n break;\n case 3:\n out = { t: \"b\", v: Boolean(cell.v) };\n break;\n default:\n out = {\n t: \"s\",\n v:\n cell.v === null || cell.v === undefined\n ? \"\"\n : typeof cell.v === \"object\"\n ? JSON.stringify(cell.v)\n : String(cell.v),\n };\n }\n if ((out.v === \"\" || out.v === null || out.v === undefined) && !formula) return null;\n return formula ? { ...out, f: formula } : out;\n}\n\n// Kept so existing callers of the registered-format path keep compiling.\nexport async function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array> {\n const built = await buildFile(\n { kind: \"registered\", format: \"workbook\", value: univerSnapshotToWorkbookJson(snapshot) },\n \"xlsx-workbook\",\n );\n return built.bytes;\n}\n","/**\n * Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's\n * File → Import both run it. The file is parsed before anything is created (a malformed file leaves\n * no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls\n * the new row back.\n */\n\nimport { isServiceFailure } from \"@ai-matrx/records/core\";\n\nimport { getSheetsHost } from \"./ports\";\nimport {\n createWorkbook,\n discardFailedWorkbook,\n saveSnapshot,\n} from \"./workbook-service\";\n\n/**\n * Pre-flight import file check. We deliberately do NOT use the `accept`\n * attribute on the picker (it greys out everything in Drive / Google\n * Sheets pickers on iOS and many Android pickers), so we validate after\n * pick. Returns null when the file is accepted, or a short user-facing\n * reason string when it isn't.\n */\nexport function unsupportedFileReason(file: File): string | null {\n const name = file.name.toLowerCase();\n // Native, parseable formats.\n if (\n name.endsWith(\".xlsx\") ||\n name.endsWith(\".xls\") ||\n name.endsWith(\".csv\")\n ) {\n return null;\n }\n if (name.endsWith(\".tsv\") || name.endsWith(\".txt\")) return null; // SheetJS parses these too\n\n // Drive's \"Google Sheets\" shortcut is a tiny JSON pointer file that browsers cannot resolve into\n // the sheet; the Google Sheets import reads the real file through Google's own picker.\n if (name.endsWith(\".gsheet\")) {\n return \"A Google Sheets shortcut can't be uploaded. Use Import from Google Sheets.\";\n }\n // Anything else.\n return `\"${file.name}\" isn't a spreadsheet file. Supported: .xlsx, .xls, .csv. For a Google Sheet, use Import from Google Sheets.`;\n}\n\nexport async function importWorkbookFile(\n file: File,\n organizationId: string | null,\n): Promise<{ id: string; name: string; notCarried: string[] }> {\n const capturedOrganizationId = await getSheetsHost().ensureOrgId(organizationId);\n // Parse first — if the file is malformed, we surface the error\n // BEFORE creating an empty workbook the user would have to delete.\n const { xlsxToUniverWorkbook } =\n await import(\"./xlsx-to-univer\");\n const droppedOnImport: string[] = [];\n const { uploadImportedImage } = await import(\"../univer/matrxImagePorts\");\n const snapshot = await xlsxToUniverWorkbook(file, {\n uploadImage: uploadImportedImage,\n onDropped: (what) => droppedOnImport.push(what),\n });\n\n // Stash the lossless original in cld_files so users can download or\n // re-import the source later. Failure here is non-fatal — the workbook\n // import path is the primary deliverable, the original-file link is\n // a recoverability nicety (FK is ON DELETE SET NULL, so we'd nil out\n // the link if the file went away anyway). Log + continue on failure.\n let originalFileId: string | undefined;\n try {\n const uploaded = await getSheetsHost().uploadOriginalFile(file, { folderPath: \"Workbooks/Imports\" });\n originalFileId = uploaded.fileId;\n } catch (uploadErr) {\n console.warn(\n \"Workbook import: stashing original failed; continuing without link.\",\n uploadErr,\n );\n }\n\n const cleanName = file.name.replace(/\\.[^.]+$/, \"\") || \"Imported workbook\";\n const created = await createWorkbook({\n name: cleanName,\n description: `Imported from ${file.name}`,\n source: file.name.toLowerCase().endsWith(\".csv\")\n ? \"imported_csv\"\n : \"imported_xlsx\",\n organizationId: capturedOrganizationId,\n ...(originalFileId ? { originalFileId } : {}),\n });\n if (isServiceFailure(created)) throw new Error(created.error);\n\n const saved = await saveSnapshot({\n workbookId: created.data.id,\n snapshot,\n origin: \"imported\",\n label: file.name,\n });\n if (isServiceFailure(saved)) {\n // Roll back the workbook so we don't leave an empty husk on import\n // failure. Best-effort, and a HARD delete on purpose: this row was\n // created seconds ago by this same flow and never reached the user, so\n // tombstoning it would leave invisible litter instead of cleaning up.\n await discardFailedWorkbook(created.data.id);\n throw new Error(saved.error);\n }\n\n return { id: created.data.id, name: cleanName, notCarried: droppedOnImport };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/_work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","../src/sheets/univer-to-xlsx.ts","../src/sheets/import-workbook-file.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,oDAA0B;AAG1B,kDAA6B;AAC7B,yDAA+C;AAoCxC,SAAS,4BAAA,CAA6B,QAAA,EAAkC;AAC7E,EAAA,MAAM,WAAA,mBAAa,QAAA,CAAS,UAAA,UAAc,MAAA,CAAO,IAAA,kBAAK,QAAA,CAAS,MAAA,UAAU,CAAC,GAAC,GAAA;AAC3E,EAAA,MAAM,OAAA,EAAiC,CAAC,CAAA;AACxC,EAAA,IAAA,CAAA,MAAW,QAAA,GAAW,UAAA,EAAY;AAChC,IAAA,MAAM,MAAA,kBAAQ,QAAA,mBAAS,MAAA,4BAAA,CAAS,OAAO,GAAA;AACvC,IAAA,GAAA,CAAI,CAAC,KAAA,EAAO,QAAA;AACZ,IAAA,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,KAAA,EAAA,kBAAQ,KAAA,CAAM,IAAA,UAAQ,SAAA,CAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,EAAA,GAAK,QAAQ,CAAC,CAAA;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,OAAO,CAAA;AAClB;AAGA,MAAA,SAAsB,yBAAA,CACpB,QAAA,EACA,QAAA,EAAmD,CAAC,CAAA,EAC/B;AACrB,EAAA,OAAA,CAAQ,MAAM,mBAAA,CAAoB,QAAA,EAAU,OAAO,CAAA,CAAA,CAAG,KAAA;AACxD;AAGA,MAAA,SAAsB,oBAAA,CACpB,QAAA,EACA,QAAA,EAA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C,MAAA;AACR,MAAA;AACA,MAAA;AACO,MAAA;AACuB,MAAA;AAC3B,MAAA;AACE,QAAA;AACA,QAAA;AACJ,QAAA;AACI,MAAA;AACD,QAAA;AACV,MAAA;AACY,MAAA;AACH,MAAA;AACI,MAAA;AACC,MAAA;AACH,MAAA;AACb,IAAA;AACF,EAAA;AACF;AAES;AACD,EAAA;AACU,EAAA;AACE,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACN,IAAA;AACM,IAAA;AACjB,EAAA;AACa,EAAA;AACK,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACA,IAAA;AACjB,EAAA;AACgB,EAAA;AACV,IAAA;AACY,MAAA;AACR,IAAA;AAER,IAAA;AACF,EAAA;AACe,EAAA;AACA,EAAA;AACC,IAAA;AAChB,EAAA;AACF;AAEkB;AACR,EAAA;AACQ,EAAA;AACC,IAAA;AACJ,MAAA;AACG,QAAA;AACC,QAAA;AACb,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACI,EAAA;AACI,IAAA;AACM,IAAA;AACL,MAAA;AACZ,MAAA;AACY,MAAA;AACA,MAAA;AACZ,MAAA;AACa,MAAA;AACA,MAAA;AACf,IAAA;AACsB,IAAA;AACT,IAAA;AACA,MAAA;AACL,MAAA;AACI,MAAA;AACG,MAAA;AACJ,IAAA;AACC,MAAA;AACE,MAAA;AACF,IAAA;AACL,MAAA;AACA,QAAA;AACH,QAAA;AACU,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACC,MAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACF,IAAA;AACO,MAAA;AACZ,IAAA;AACc,IAAA;AACjB,EAAA;AACF;AAEmB;AAEF;AACI,EAAA;AACC,EAAA;AACT,EAAA;AACE,EAAA;AACK,EAAA;AACA,EAAA;AACF,EAAA;AACL,EAAA;AACC,EAAA;AACL,EAAA;AACT;AAES;AACI,EAAA;AACO,IAAA;AACJ,IAAA;AACA,IAAA;AACE,IAAA;AACE,IAAA;AACH,IAAA;AACU,IAAA;AACb,IAAA;AACM,MAAA;AACD,MAAA;AACN,QAAA;AACC,UAAA;AACM,YAAA;AACV,UAAA;AACA,UAAA;AACG,QAAA;AACM,UAAA;AACT,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACJ,MAAA;AACS,IAAA;AACI,MAAA;AACP,MAAA;AACE,QAAA;AACI,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACH,MAAA;AACE,QAAA;AACI,QAAA;AACD,QAAA;AACA,QAAA;AACX,MAAA;AACF,IAAA;AACU,IAAA;AACI,MAAA;AACZ,MAAA;AACF,IAAA;AACG,IAAA;AACL,EAAA;AACF;AAES;AACK,EAAA;AACF,EAAA;AACM,EAAA;AACD,IAAA;AACE,IAAA;AACjB,EAAA;AACa,EAAA;AACC,IAAA;AACd,EAAA;AACF;AAEoB;AACD,EAAA;AACnB;AAEoB;AACD,EAAA;AACH,IAAA;AACG,MAAA;AACA,MAAA;AACf,IAAA;AACF,EAAA;AACqB,EAAA;AACL,EAAA;AACA,EAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACA,IAAA;AACH,IAAA;AACK,MAAA;AAChB,IAAA;AACc,IAAA;AAChB,EAAA;AACiB,EAAA;AACC,IAAA;AACV,IAAA;AACO,IAAA;AACf,EAAA;AACkB,EAAA;AACpB;AAEe;AAOC,EAAA;AACE,EAAA;AACR,IAAA;AACS,IAAA;AACJ,IAAA;AACoB,IAAA;AACS,IAAA;AACxB,IAAA;AACH,IAAA;AACC,MAAA;AACJ,MAAA;AACC,IAAA;AACL,MAAA;AACU,QAAA;AACA,QAAA;AACN,MAAA;AACE,QAAA;AACV,MAAA;AACF,IAAA;AACY,IAAA;AACE,MAAA;AACZ,MAAA;AACF,IAAA;AACc,IAAA;AACE,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A;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/_work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","sourcesContent":[null,"/**\n * univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.\n *\n * Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx\n * format can hold from what Univer holds: values, formulas, merged ranges,\n * cell styles and number formats, column widths, row heights, frozen panes,\n * data validation, conditional formatting, the header-row filter range,\n * notes, comment threads (as notes), cell links, and pictures.\n *\n * What it cannot carry is NAMED in the returned report and shown to the person\n * at export time — never dropped silently.\n *\n * Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,\n * conditional formatting, notes, links and images; the registered\n * `xlsx-workbook` format writes values only). It is loaded on demand, so\n * the editor bundle does not pay for it until someone exports or imports.\n */\n\nimport { buildFile } from \"@ai-matrx/alchemy/operate\";\nimport type { WorkbookCellJson, WorkbookJson } from \"@ai-matrx/alchemy/operate/read\";\nimport type { ICellData, IWorkbookData, IWorksheetData } from \"@univerjs/core\";\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { loadExcelJs, type ExcelJSTypes } from \"@ai-matrx/print/xlsx-styled\";\nimport {\n H_ALIGN_OUT,\n RESOURCE,\n V_ALIGN_OUT,\n borderToExcel,\n colPxToChars,\n colorToArgb,\n readResource,\n rangeToA1,\n rowPxToPt,\n type RangeLike,\n type UniverResource,\n} from \"./xlsx-shared\";\n\nexport type ExportXlsxOptions = {\n /** File name without extension. Defaults to \"workbook\". */\n filename?: string;\n /** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */\n resolveImage?: ExportImagePort;\n};\n\nexport type ExportImagePort = (\n source: string,\n) => Promise<{ bytes: Uint8Array; extension: \"png\" | \"jpeg\" | \"gif\" } | null>;\n\n/** What an export could not carry, in words for the person. Empty when nothing was lost. */\nexport type XlsxExportReport = { dropped: string[] };\n\ntype Snapshot = Partial<IWorkbookData>;\ntype Style = Record<string, unknown>;\ntype Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- Univer resource payloads are untyped JSON\n\n// ─── the thin WorkbookJson path (values + merges), kept for other callers ───\n\n/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */\nexport function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson {\n const sheetOrder = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n const sheets: WorkbookJson[\"sheets\"] = [];\n for (const sheetId of sheetOrder) {\n const sheet = snapshot.sheets?.[sheetId];\n if (!sheet) continue;\n sheets.push(sheetToJson(sheet, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n }\n return { sheets };\n}\n\n/** Full-fidelity bytes. Does NOT trigger a download. */\nexport async function univerSnapshotToXlsxBytes(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<Uint8Array> {\n return (await buildXlsxFromUniver(snapshot, options)).bytes;\n}\n\n/** Convert + trigger a browser download; returns what could not be carried. */\nexport async function downloadUniverAsXlsx(\n snapshot: Snapshot,\n options: ExportXlsxOptions = {},\n): Promise<XlsxExportReport> {\n if (typeof document === \"undefined\") return { dropped: [] };\n const filename = `${(options.filename ?? \"workbook\").replace(/\\.xlsx$/i, \"\")}.xlsx`;\n const { bytes, report } = await buildXlsxFromUniver(snapshot, options);\n const blob = new Blob([bytes as BlobPart], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n });\n downloadFile(filename, blob, blob.type);\n return report;\n}\n\n// ─── the full-fidelity writer ──────────────────────────────────────────────\n\nexport async function buildXlsxFromUniver(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<{ bytes: Uint8Array; report: XlsxExportReport }> {\n const ExcelJS = await loadExcelJs();\n const wb = new ExcelJS.Workbook();\n const dropped = new Set<string>();\n const resources = (snapshot.resources ?? []) as UniverResource[];\n const styles = (snapshot.styles ?? {}) as Record<string, Style>;\n\n const validation = readResource<Json>(resources, RESOURCE.validation) ?? {};\n const conditional = readResource<Json>(resources, RESOURCE.conditional) ?? {};\n const filters = readResource<Json>(resources, RESOURCE.filter) ?? {};\n const notes = readResource<Json>(resources, RESOURCE.note) ?? {};\n const comments = readResource<Json>(resources, RESOURCE.comments) ?? {};\n const drawings = readResource<Json>(resources, RESOURCE.drawing) ?? {};\n const tables = readResource<Json>(resources, RESOURCE.table) ?? {};\n\n const order = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n for (const sheetId of order) {\n const sheet = snapshot.sheets?.[sheetId] as Partial<IWorksheetData> | undefined;\n if (!sheet) continue;\n const ws = wb.addWorksheet(uniqueName(wb, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n writeCells(ws, sheet, styles);\n writeLayout(ws, sheet);\n const tab = colorToArgb(typeof sheet.tabColor === \"string\" ? sheet.tabColor : undefined);\n if (tab) ws.properties.tabColor = { argb: tab };\n writeValidation(ws, validation[sheetId], dropped);\n writeConditional(ws, conditional[sheetId], dropped);\n writeFilter(ws, filters[sheetId], dropped);\n writeNotes(ws, notes[sheetId], comments[sheetId], dropped);\n await writeImages(wb, ws, drawings[sheetId], options.resolveImage, dropped);\n if (tables[sheetId] && Object.keys(tables[sheetId]).length) {\n dropped.add(\"Tables are exported as plain ranges (their data and styling are kept)\");\n }\n }\n\n const buffer = await wb.xlsx.writeBuffer();\n return { bytes: new Uint8Array(buffer as ArrayBuffer), report: { dropped: [...dropped] } };\n}\n\nfunction uniqueName(wb: ExcelJSTypes.Workbook, name: string): string {\n let candidate = name;\n let n = 2;\n while (wb.getWorksheet(candidate)) candidate = `${name.slice(0, 28)} ${n++}`;\n return candidate;\n}\n\nfunction styleOf(cell: ICellData, styles: Record<string, Style>): Style | undefined {\n const s = cell.s;\n if (!s) return undefined;\n return typeof s === \"string\" ? styles[s] : (s as Style);\n}\n\nfunction applyStyle(target: ExcelJSTypes.Cell, st: Style | undefined): void {\n if (!st) return;\n const font: Partial<ExcelJSTypes.Font> = {};\n if (st.ff) font.name = String(st.ff);\n if (typeof st.fs === \"number\") font.size = st.fs;\n if (st.bl === 1) font.bold = true;\n if (st.it === 1) font.italic = true;\n if ((st.ul as Json | undefined)?.s === 1) font.underline = true;\n if ((st.st as Json | undefined)?.s === 1) font.strike = true;\n const fg = colorToArgb((st.cl as Json | undefined)?.rgb);\n if (fg) font.color = { argb: fg };\n if (Object.keys(font).length) target.font = font;\n const bg = colorToArgb((st.bg as Json | undefined)?.rgb);\n if (bg) target.fill = { type: \"pattern\", pattern: \"solid\", fgColor: { argb: bg } };\n const alignment: Partial<ExcelJSTypes.Alignment> = {};\n if (typeof st.ht === \"number\" && H_ALIGN_OUT[st.ht]) alignment.horizontal = H_ALIGN_OUT[st.ht] as ExcelJSTypes.Alignment[\"horizontal\"];\n if (typeof st.vt === \"number\" && V_ALIGN_OUT[st.vt]) alignment.vertical = V_ALIGN_OUT[st.vt] as ExcelJSTypes.Alignment[\"vertical\"];\n if (st.tb === 3) alignment.wrapText = true;\n if (Object.keys(alignment).length) target.alignment = alignment;\n const bd = st.bd as Json | undefined;\n if (bd) {\n const border: Partial<ExcelJSTypes.Borders> = {};\n for (const [key, side] of [[\"t\", \"top\"], [\"b\", \"bottom\"], [\"l\", \"left\"], [\"r\", \"right\"]] as const) {\n const b = bd[key] as Json | undefined;\n const style = borderToExcel(b?.s);\n if (style) {\n (border as Json)[side] = { style, color: { argb: colorToArgb(b?.cl?.rgb) ?? \"FF000000\" } };\n }\n }\n if (Object.keys(border).length) target.border = border;\n }\n const pattern = (st.n as Json | undefined)?.pattern;\n if (typeof pattern === \"string\" && pattern && pattern !== \"General\") target.numFmt = pattern;\n}\n\nfunction plainText(p: Json | undefined): string {\n return String(p?.body?.dataStream ?? \"\").replace(/\\r\\n$/, \"\").replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction linkOf(p: Json | undefined): string | undefined {\n const ranges = p?.body?.customRanges as Json[] | undefined;\n return ranges?.find((r) => r.rangeType === 0 && r.properties?.url)?.properties?.url;\n}\n\nfunction writeCells(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>, styles: Record<string, Style>): void {\n const cellData = sheet.cellData ?? {};\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n const row = cellData[r];\n if (!row || !Number.isFinite(r)) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n const cell = row[c] as ICellData | undefined;\n if (!cell || !Number.isFinite(c)) continue;\n const target = ws.getCell(r + 1, c + 1);\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n const rich = cell.p as Json | undefined;\n let value: ExcelJSTypes.CellValue = null;\n if (cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n if (cell.t === 3) value = Boolean(cell.v);\n else if (cell.t === 2 || typeof cell.v === \"number\") value = Number(cell.v);\n else value = String(cell.v);\n } else if (rich) {\n value = plainText(rich);\n }\n const url = linkOf(rich);\n if (url) value = { text: String(value ?? url), hyperlink: url };\n if (formula) value = { formula, result: (value as number | string | boolean | undefined) ?? undefined } as ExcelJSTypes.CellFormulaValue;\n if (value !== null && value !== \"\") target.value = value;\n applyStyle(target, styleOf(cell, styles));\n }\n }\n}\n\nfunction writeLayout(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>): void {\n const defaultCol = sheet.defaultColumnWidth;\n const columns = sheet.columnData ?? {};\n for (const key of Object.keys(columns)) {\n const c = Number(key);\n const col = columns[c];\n if (!col) continue;\n const target = ws.getColumn(c + 1);\n if (typeof col.w === \"number\") target.width = colPxToChars(col.w);\n else if (defaultCol) target.width = colPxToChars(defaultCol);\n if (col.hd === 1) target.hidden = true;\n }\n const rows = sheet.rowData ?? {};\n for (const key of Object.keys(rows)) {\n const r = Number(key);\n const row = rows[r];\n if (!row) continue;\n const target = ws.getRow(r + 1);\n if (typeof row.h === \"number\") target.height = rowPxToPt(row.h);\n if (row.hd === 1) target.hidden = true;\n }\n for (const m of sheet.mergeData ?? []) {\n try {\n ws.mergeCells(m.startRow + 1, m.startColumn + 1, m.endRow + 1, m.endColumn + 1);\n } catch {\n /* an overlapping merge in a damaged snapshot: keep the first */\n }\n }\n const freeze = sheet.freeze;\n if (freeze && (freeze.xSplit > 0 || freeze.ySplit > 0)) {\n ws.views = [{ state: \"frozen\", xSplit: freeze.xSplit, ySplit: freeze.ySplit }];\n }\n}\n\nconst eachCell = (ranges: RangeLike[], fn: (row: number, col: number) => void, cap = 100_000): boolean => {\n let n = 0;\n for (const r of ranges) {\n for (let row = r.startRow; row <= r.endRow; row++) {\n for (let col = r.startColumn; col <= r.endColumn; col++) {\n if (++n > cap) return false;\n fn(row, col);\n }\n }\n }\n return true;\n};\n\nfunction writeValidation(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const rule of rules ?? []) {\n const type = String(rule.type);\n const base: Json = {\n allowBlank: rule.allowBlank !== false,\n showErrorMessage: rule.showErrorMessage !== false,\n errorTitle: rule.errorTitle,\n error: rule.error,\n showInputMessage: Boolean(rule.showInputMessage),\n promptTitle: rule.promptTitle,\n prompt: rule.prompt,\n };\n let dv: Json | null = null;\n if (type === \"list\" || type === \"listMultiple\") {\n const f1 = String(rule.formula1 ?? \"\");\n const isRange = /^=?'?[^,\"]*!?\\$?[A-Z]+\\$?\\d+(:\\$?[A-Z]+\\$?\\d+)?$/i.test(f1) && !f1.includes(\",\");\n dv = { ...base, type: \"list\", formulae: [isRange ? f1.replace(/^=/, \"\") : `\"${f1.replace(/\"/g, \"\")}\"`] };\n if (type === \"listMultiple\") dropped.add(\"Multi-select dropdowns become single-select\");\n } else if (type === \"checkbox\") {\n dv = { ...base, type: \"list\", formulae: ['\"TRUE,FALSE\"'] };\n dropped.add(\"Checkboxes become TRUE/FALSE dropdowns\");\n } else if ([\"whole\", \"decimal\", \"date\", \"time\", \"textLength\"].includes(type)) {\n dv = {\n ...base,\n type,\n operator: rule.operator ?? \"between\",\n formulae: [rule.formula1, rule.formula2].filter((f) => f !== undefined && f !== \"\"),\n };\n } else if (type === \"custom\") {\n dv = { ...base, type: \"custom\", formulae: [String(rule.formula1 ?? \"\").replace(/^=/, \"\")] };\n }\n if (!dv) continue;\n if (!dv.errorTitle) delete dv.errorTitle;\n const complete = eachCell((rule.ranges ?? []) as RangeLike[], (r, c) => {\n ws.getCell(r + 1, c + 1).dataValidation = dv as ExcelJSTypes.DataValidation;\n });\n if (!complete) dropped.add(\"Data validation on very large ranges was cut off\");\n }\n}\n\nconst NUMBER_OPS = new Set([\"greaterThan\", \"greaterThanOrEqual\", \"lessThan\", \"lessThanOrEqual\", \"equal\", \"notEqual\", \"between\", \"notBetween\"]);\n\nfunction cfStyle(style: Json | undefined): Json {\n const out: Json = {};\n const font: Json = {};\n const fg = colorToArgb(style?.cl?.rgb);\n if (fg) font.color = { argb: fg };\n if (style?.bl === 1) font.bold = true;\n if (style?.it === 1) font.italic = true;\n if (Object.keys(font).length) out.font = font;\n const bg = colorToArgb(style?.bg?.rgb);\n if (bg) out.fill = { type: \"pattern\", pattern: \"solid\", bgColor: { argb: bg } };\n return out;\n}\n\nfunction writeConditional(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const entry of rules ?? []) {\n const ranges = (entry.ranges ?? []) as RangeLike[];\n if (!ranges.length) continue;\n const ref = ranges.map(rangeToA1).join(\" \");\n const first = ranges[0]!;\n const topLeft = rangeToA1({ ...first, endRow: first.startRow, endColumn: first.startColumn });\n const rule = entry.rule as Json;\n let out: Json | null = null;\n if (rule?.type === \"highlightCell\") {\n const style = cfStyle(rule.style);\n switch (rule.subType) {\n case \"number\":\n if (NUMBER_OPS.has(rule.operator)) {\n out = { type: \"cellIs\", operator: rule.operator, formulae: Array.isArray(rule.value) ? rule.value : [rule.value], style };\n }\n break;\n case \"text\":\n if (rule.operator === \"containsText\") out = { type: \"containsText\", operator: \"containsText\", text: String(rule.value ?? \"\"), style };\n break;\n case \"duplicateValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})>1`], style };\n break;\n case \"uniqueValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})=1`], style };\n break;\n case \"formula\":\n out = { type: \"expression\", formulae: [String(rule.value ?? \"\").replace(/^=/, \"\")], style };\n break;\n }\n } else if (rule?.type === \"colorScale\" && Array.isArray(rule.config)) {\n const cfg = [...rule.config].sort((a: Json, b: Json) => a.index - b.index);\n out = {\n type: \"colorScale\",\n cfvo: cfg.map((c: Json) => ({ type: c.value?.type ?? \"min\", ...(c.value?.value !== undefined ? { value: c.value.value } : {}) })),\n color: cfg.map((c: Json) => ({ argb: colorToArgb(c.color) ?? \"FFFFFFFF\" })),\n };\n } else if (rule?.type === \"dataBar\") {\n out = {\n type: \"dataBar\",\n gradient: rule.config?.isGradient !== false,\n cfvo: [{ type: rule.config?.min?.type ?? \"min\" }, { type: rule.config?.max?.type ?? \"max\" }],\n color: { argb: colorToArgb(rule.config?.positiveColor) ?? \"FF638EC6\" },\n };\n }\n if (!out) {\n dropped.add(\"Some conditional formats (icon sets, top/bottom, average, date rules) are not written\");\n continue;\n }\n ws.addConditionalFormatting({ ref, rules: [{ ...out, priority: 1 }] } as ExcelJSTypes.ConditionalFormattingOptions);\n }\n}\n\nfunction writeFilter(ws: ExcelJSTypes.Worksheet, filter: Json | undefined, dropped: Set<string>): void {\n const ref = filter?.ref as RangeLike | undefined;\n if (!ref) return;\n ws.autoFilter = {\n from: { row: ref.startRow + 1, column: ref.startColumn + 1 },\n to: { row: ref.endRow + 1, column: ref.endColumn + 1 },\n };\n if ((filter?.filterColumns as unknown[] | undefined)?.length) {\n dropped.add(\"Which filter choices were applied is not saved (the filter arrows are)\");\n }\n}\n\nfunction threadText(c: Json): string {\n return String(c?.text?.dataStream ?? \"\").replace(/\\r\\n?$/, \"\").replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction writeNotes(ws: ExcelJSTypes.Worksheet, sheetNotes: Json | undefined, sheetComments: Json | Json[] | undefined, dropped: Set<string>): void {\n for (const [row, cols] of Object.entries(sheetNotes ?? {})) {\n for (const [col, note] of Object.entries(cols as Json)) {\n const text = String((note as Json).note ?? \"\");\n if (text) ws.getCell(Number(row) + 1, Number(col) + 1).note = text;\n }\n }\n const list: Json[] = Array.isArray(sheetComments) ? sheetComments : sheetComments ? Object.values(sheetComments).flat() : [];\n const threads = new Map<string, string[]>();\n for (const c of list) {\n if (!c?.ref) continue;\n const lines = threads.get(c.ref) ?? [];\n const who = c.authorName ?? c.personId ?? \"\";\n lines.push(`${who ? who + \": \" : \"\"}${threadText(c)}`);\n for (const child of (c.children ?? []) as Json[]) {\n lines.push(`${child.authorName ?? child.personId ?? \"\"}: ${threadText(child)}`);\n }\n threads.set(c.ref, lines);\n }\n for (const [ref, lines] of threads) {\n const cell = ws.getCell(ref);\n const existing = typeof cell.note === \"string\" ? cell.note : \"\";\n cell.note = [existing, ...lines].filter(Boolean).join(\"\\n\");\n }\n if (threads.size) dropped.add(\"Comment threads are written as cell notes (replies and resolved state are flattened)\");\n}\n\nasync function writeImages(\n wb: ExcelJSTypes.Workbook,\n ws: ExcelJSTypes.Worksheet,\n sheetDrawings: Json | undefined,\n resolve: ExportImagePort | undefined,\n dropped: Set<string>,\n): Promise<void> {\n const data = (sheetDrawings?.data ?? {}) as Record<string, Json>;\n for (const d of Object.values(data)) {\n if (d.drawingType !== 0 || !d.source) continue;\n const from = d.sheetTransform?.from;\n if (!from) continue;\n let bytes: Uint8Array | null = null;\n let extension: \"png\" | \"jpeg\" | \"gif\" = \"png\";\n const dataUrl = /^data:image\\/(png|jpeg|jpg|gif);base64,(.+)$/i.exec(String(d.source));\n if (dataUrl) {\n extension = dataUrl[1]!.toLowerCase() === \"gif\" ? \"gif\" : dataUrl[1]!.toLowerCase() === \"png\" ? \"png\" : \"jpeg\";\n bytes = Uint8Array.from(atob(dataUrl[2]!), (ch) => ch.charCodeAt(0));\n } else if (resolve) {\n try {\n const got = await resolve(String(d.source));\n if (got) ({ bytes, extension } = got);\n } catch {\n bytes = null;\n }\n }\n if (!bytes) {\n dropped.add(\"Some pictures could not be read and were left out\");\n continue;\n }\n const id = wb.addImage({ buffer: bytes as unknown as NonNullable<Parameters<typeof wb.addImage>[0][\"buffer\"]>, extension });\n ws.addImage(id, {\n tl: { col: from.column + (from.columnOffset ?? 0) / 64, row: from.row + (from.rowOffset ?? 0) / 20 },\n ext: { width: d.transform?.width ?? 200, height: d.transform?.height ?? 150 },\n });\n }\n}\n\n// ─── internals of the thin path ────────────────────────────────────────────\n\nfunction sheetToJson(sheet: Partial<IWorksheetData>, name: string): WorkbookJson[\"sheets\"][number] {\n const cellData = sheet.cellData ?? {};\n const rows: (WorkbookCellJson | null)[][] = [];\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n if (!Number.isFinite(r)) continue;\n const row = cellData[r];\n if (!row) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n if (!Number.isFinite(c)) continue;\n const cell = row[c];\n if (!cell) continue;\n const out = toWorkbookCell(cell);\n if (!out) continue;\n while (rows.length <= r) rows.push([]);\n const line = rows[r]!;\n while (line.length < c) line.push(null);\n line[c] = out;\n }\n }\n const merges = (sheet.mergeData ?? []).map((m) => ({\n s: { r: m.startRow, c: m.startColumn },\n e: { r: m.endRow, c: m.endColumn },\n }));\n return { name, rows, ...(merges.length ? { merges } : {}) };\n}\n\nfunction toWorkbookCell(cell: ICellData): WorkbookCellJson | null {\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n let out: WorkbookCellJson;\n switch (cell.t) {\n case 2:\n out = { t: \"n\", v: typeof cell.v === \"number\" ? cell.v : Number(cell.v ?? 0) };\n break;\n case 3:\n out = { t: \"b\", v: Boolean(cell.v) };\n break;\n default:\n out = {\n t: \"s\",\n v:\n cell.v === null || cell.v === undefined\n ? \"\"\n : typeof cell.v === \"object\"\n ? JSON.stringify(cell.v)\n : String(cell.v),\n };\n }\n if ((out.v === \"\" || out.v === null || out.v === undefined) && !formula) return null;\n return formula ? { ...out, f: formula } : out;\n}\n\n// Kept so existing callers of the registered-format path keep compiling.\nexport async function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array> {\n const built = await buildFile(\n { kind: \"registered\", format: \"workbook\", value: univerSnapshotToWorkbookJson(snapshot) },\n \"xlsx-workbook\",\n );\n return built.bytes;\n}\n","/**\n * Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's\n * File → Import both run it. The file is parsed before anything is created (a malformed file leaves\n * no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls\n * the new row back.\n */\n\nimport { isServiceFailure } from \"@ai-matrx/records/core\";\n\nimport { getSheetsHost } from \"./ports\";\nimport {\n createWorkbook,\n discardFailedWorkbook,\n saveSnapshot,\n} from \"./workbook-service\";\n\n/**\n * Pre-flight import file check. We deliberately do NOT use the `accept`\n * attribute on the picker (it greys out everything in Drive / Google\n * Sheets pickers on iOS and many Android pickers), so we validate after\n * pick. Returns null when the file is accepted, or a short user-facing\n * reason string when it isn't.\n */\nexport function unsupportedFileReason(file: File): string | null {\n const name = file.name.toLowerCase();\n // Native, parseable formats.\n if (\n name.endsWith(\".xlsx\") ||\n name.endsWith(\".xls\") ||\n name.endsWith(\".csv\")\n ) {\n return null;\n }\n if (name.endsWith(\".tsv\") || name.endsWith(\".txt\")) return null; // SheetJS parses these too\n\n // Drive's \"Google Sheets\" shortcut is a tiny JSON pointer file that browsers cannot resolve into\n // the sheet; the Google Sheets import reads the real file through Google's own picker.\n if (name.endsWith(\".gsheet\")) {\n return \"A Google Sheets shortcut can't be uploaded. Use Import from Google Sheets.\";\n }\n // Anything else.\n return `\"${file.name}\" isn't a spreadsheet file. Supported: .xlsx, .xls, .csv. For a Google Sheet, use Import from Google Sheets.`;\n}\n\nexport async function importWorkbookFile(\n file: File,\n organizationId: string | null,\n): Promise<{ id: string; name: string; notCarried: string[] }> {\n const capturedOrganizationId = await getSheetsHost().ensureOrgId(organizationId);\n // Parse first — if the file is malformed, we surface the error\n // BEFORE creating an empty workbook the user would have to delete.\n const { xlsxToUniverWorkbook } =\n await import(\"./xlsx-to-univer\");\n const droppedOnImport: string[] = [];\n const { uploadImportedImage } = await import(\"../univer/matrxImagePorts\");\n const snapshot = await xlsxToUniverWorkbook(file, {\n uploadImage: uploadImportedImage,\n onDropped: (what) => droppedOnImport.push(what),\n });\n\n // Stash the lossless original in cld_files so users can download or\n // re-import the source later. Failure here is non-fatal — the workbook\n // import path is the primary deliverable, the original-file link is\n // a recoverability nicety (FK is ON DELETE SET NULL, so we'd nil out\n // the link if the file went away anyway). Log + continue on failure.\n let originalFileId: string | undefined;\n try {\n const uploaded = await getSheetsHost().uploadOriginalFile(file, { folderPath: \"Workbooks/Imports\" });\n originalFileId = uploaded.fileId;\n } catch (uploadErr) {\n console.warn(\n \"Workbook import: stashing original failed; continuing without link.\",\n uploadErr,\n );\n }\n\n const cleanName = file.name.replace(/\\.[^.]+$/, \"\") || \"Imported workbook\";\n const created = await createWorkbook({\n name: cleanName,\n description: `Imported from ${file.name}`,\n source: file.name.toLowerCase().endsWith(\".csv\")\n ? \"imported_csv\"\n : \"imported_xlsx\",\n organizationId: capturedOrganizationId,\n ...(originalFileId ? { originalFileId } : {}),\n });\n if (isServiceFailure(created)) throw new Error(created.error);\n\n const saved = await saveSnapshot({\n workbookId: created.data.id,\n snapshot,\n origin: \"imported\",\n label: file.name,\n });\n if (isServiceFailure(saved)) {\n // Roll back the workbook so we don't leave an empty husk on import\n // failure. Best-effort, and a HARD delete on purpose: this row was\n // created seconds ago by this same flow and never reached the user, so\n // tombstoning it would leave invisible litter instead of cleaning up.\n await discardFailedWorkbook(created.data.id);\n throw new Error(saved.error);\n }\n\n return { id: created.data.id, name: cleanName, notCarried: droppedOnImport };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets.cjs","../src/sheets/univer-snapshot-rows.ts","../src/sheets/snapshot-preview-svg.ts","../src/sheets/snapshot-grid.ts","../src/core/document-page-style.ts","../src/sheets/sheet-page-setup.ts","../src/sheets/sheet-page-setup-service.ts","../src/sheets/sheet-print-pages.ts","../src/sheets/sheet-output.ts","../src/sheets/workbook-scope-source.ts"],"names":["current"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACiCO,SAAS,cAAA,CAAe,QAAA,EAA6B;AAC1D,EAAA,GAAA,CAAI,OAAO,SAAA,IAAa,SAAA,GAAY,SAAA,IAAa,IAAA,EAAM,OAAO,CAAC,CAAA;AAC/D,EAAA,MAAM,MAAA,EAAQ,QAAA;AACd,EAAA,MAAM,OAAA,mBAAS,KAAA,CAAM,MAAA,UAAU,CAAC,GAAA;AAChC,EAAA,MAAM,QAAA,EAAA,kBAAW,KAAA,CAAM,UAAA,UAAc,CAAC,GAAA,CAAA,CAAG,MAAA,CAAO,CAAC,EAAA,EAAA,GAAO,MAAA,CAAO,EAAE,CAAC,CAAA;AAClE,EAAA,OAAO,OAAA,CAAQ,OAAA,EAAS,QAAA,EAAU,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AACtD;AAKA,SAAS,SAAA,CAAU,IAAA,EAAoC,MAAA,EAA+B;AACpF,EAAA,MAAM,EAAA,kBAAI,IAAA,6BAAM,GAAA;AAChB,EAAA,MAAM,MAAA,EAAQ,OAAO,EAAA,IAAM,SAAA,kBAAW,MAAA,4BAAA,CAAS,CAAC,IAAA,EAAI,EAAA,GAAK,OAAO,EAAA,IAAM,SAAA,EAAY,EAAA,EAAqC,IAAA;AACvH,EAAA,MAAM,QAAA,kBAAU,KAAA,6BAAO,CAAA,6BAAG,SAAA;AAC1B,EAAA,OAAO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a,EAAA;AACU,EAAA;AACK,EAAA;AACf,EAAA;AAAyG;AAAA;AAGlH;AAAA,sBAAA;AAE4B,EAAA;AACR,EAAA;AACjB,EAAA;AACT;AAEgC;AACE,EAAA;AAClC;AAW0B;AACT,EAAA;AACW,IAAA;AACL,IAAA;AACpB,EAAA;AACyB,EAAA;AAC5B;AAG8C;AACf,EAAA;AACZ,EAAA;AACc,EAAA;AACR,EAAA;AACD,EAAA;AACS,EAAA;AACZ,EAAA;AACD,EAAA;AACC,EAAA;AACJ,IAAA;AACN,IAAA;AACT,EAAA;AACU,EAAA;AACK,EAAA;AACJ,EAAA;AACU,EAAA;AACX,EAAA;AACA,EAAA;AACH,EAAA;AACT;AAGoC;AACJ,EAAA;AACC,EAAA;AACmB,EAAA;AAErC,EAAA;AACW,EAAA;AACQ,EAAA;AAClC;AAMyC;AACV,EAAA;AACZ,EAAA;AACO,EAAA;AACf,IAAA;AACA,IAAA;AACR,EAAA;AACqB,EAAA;AACJ,EAAA;AACG,EAAA;AACJ,EAAA;AACa,EAAA;AAC1B,EAAA;AACa,IAAA;AACa,IAAA;AACN,MAAA;AACA,MAAA;AACtB,IAAA;AACwC,IAAA;AACX,IAAA;AACV,MAAA;AACX,MAAA;AACmB,MAAA;AAC1B,IAAA;AAC6B,IAAA;AAC9B,EAAA;AACY,IAAA;AACd,EAAA;AACO,EAAA;AACT;AR0rBkC;AACA;AS9yBC;AAGnB;AAGJ,EAAA;AACG,EAAA;AACmB,IAAA;AAChC,EAAA;AACF;AAQE;AAEwB,EAAA;AACJ,EAAA;AACtB;AToyBkC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets.cjs","sourcesContent":[null,"/**\n * features/workbooks/univer-snapshot-rows.ts\n *\n * Snapshot → rows: read a Univer `IWorkbookData` snapshot back out as a plain\n * string grid. The missing half of the workbook round trip — `export-targets`\n * pushes rows INTO a workbook; this reads the (possibly user-edited) values\n * back OUT so features can offer \"edit in the workbook, then import your\n * changes\". Values only (formulas come back as their cached value); first\n * sheet by `sheetOrder` unless a sheet id is named. A number shown through a date format reads as\n * its ISO date (a spreadsheet keeps dates as day serials). Reusable — do not fork a per-feature\n * snapshot walker. Callers: the workbook's \"Make this sheet a table\" (features/workbooks/table-link).\n */\n\ninterface CellShape {\n v?: unknown;\n s?: unknown;\n}\n\ninterface SheetShape {\n name?: string;\n /** Frozen panes: `xSplit` columns and `ySplit` rows are pinned. */\n freeze?: { xSplit?: number; ySplit?: number } | null;\n /** Univer marks a hidden column/row `hd: 1` (a table link's Record ID column is one). */\n columnData?: Record<string, { hd?: number } | null | undefined>;\n rowData?: Record<string, { hd?: number } | null | undefined>;\n cellData?: Record<string, Record<string, CellShape | null | undefined>>;\n}\n\ninterface SnapshotShape {\n sheetOrder?: string[];\n sheets?: Record<string, SheetShape>;\n styles?: Record<string, { n?: { pattern?: string } | null } | null>;\n}\n\nexport interface SnapshotRows {\n sheetName: string;\n /** Dense rectangular grid, trailing empty rows/columns trimmed. */\n rows: string[][];\n /** Rows pinned at the top of the sheet (Freeze rows), counted in `rows`. */\n frozenRows: number;\n /** Columns pinned at the left of the sheet (Freeze columns), counted in each row. */\n frozenCols: number;\n}\n\n/** A zero-based, inclusive cell range (a selection). */\nexport interface CellRange {\n startRow: number;\n endRow: number;\n startColumn: number;\n endColumn: number;\n}\n\n/** Sheet ids in tab order. */\nexport function univerSheetIds(snapshot: unknown): string[] {\n if (typeof snapshot !== \"object\" || snapshot === null) return [];\n const shape = snapshot as SnapshotShape;\n const sheets = shape.sheets ?? {};\n const ordered = (shape.sheetOrder ?? []).filter((id) => sheets[id]);\n return ordered.length ? ordered : Object.keys(sheets);\n}\n\ntype Styles = SnapshotShape[\"styles\"];\n\n/** The number-format pattern a cell is shown through, if any. */\nfunction patternOf(cell: CellShape | null | undefined, styles: Styles): string | null {\n const s = cell?.s;\n const style = typeof s === \"string\" ? styles?.[s] : s && typeof s === \"object\" ? (s as { n?: { pattern?: string } }) : null;\n const pattern = style?.n?.pattern;\n return typeof pattern === \"string\" ? pattern : null;\n}\n\nconst DAY_MS = 86_400_000;\nconst SERIAL_EPOCH_MS = Date.UTC(1899, 11, 30);\n\nfunction cellText(cell: CellShape | null | undefined, styles?: Styles): string {\n const value = cell?.v;\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"number\") {\n const pattern = patternOf(cell, styles)?.replace(/\"[^\"]*\"/g, \"\").toLowerCase() ?? \"\";\n if (/[dy]/.test(pattern)) {\n const iso = new Date(Math.round(SERIAL_EPOCH_MS + value * DAY_MS)).toISOString();\n return /h/.test(pattern) ? `${iso.slice(0, 10)} ${iso.slice(11, 16)}` : iso.slice(0, 10);\n }\n }\n return String(value);\n}\n\n/**\n * Extract the first worksheet of a Univer workbook snapshot as a string grid.\n * Returns null when the value is not snapshot-shaped or has no sheets.\n * `skipHidden` leaves out hidden columns and rows: every read-only view (a share page, an agent's\n * read) passes it, so the table link's hidden Record ID column never reaches a reader.\n */\nexport function univerSnapshotToRows(snapshot: unknown, options: { sheetId?: string; skipHidden?: boolean; range?: CellRange } = {}): SnapshotRows | null {\n if (typeof snapshot !== \"object\" || snapshot === null) return null;\n const shape = snapshot as SnapshotShape;\n const sheets = shape.sheets ?? {};\n const styles = shape.styles;\n const firstId = options.sheetId\n ? sheets[options.sheetId]\n ? options.sheetId\n : undefined\n : (shape.sheetOrder?.find((id) => sheets[id]) ?? Object.keys(sheets)[0]);\n if (!firstId) return null;\n const sheet = sheets[firstId];\n const cellData = sheet?.cellData ?? {};\n\n let maxRow = -1;\n let maxCol = -1;\n for (const [rowKey, row] of Object.entries(cellData)) {\n const rowIndex = Number(rowKey);\n if (!Number.isInteger(rowIndex) || !row) continue;\n for (const [colKey, cell] of Object.entries(row)) {\n const colIndex = Number(colKey);\n if (!Number.isInteger(colIndex)) continue;\n if (cellText(cell) === \"\") continue;\n if (rowIndex > maxRow) maxRow = rowIndex;\n if (colIndex > maxCol) maxCol = colIndex;\n }\n }\n const range = options.range;\n if (range) {\n // A selection prints exactly the cells chosen, empty ones included.\n maxRow = range.endRow;\n maxCol = range.endColumn;\n }\n if (maxRow < 0 || maxCol < 0) {\n return { sheetName: sheet?.name ?? \"Sheet1\", rows: [], frozenRows: 0, frozenCols: 0 };\n }\n const firstRow = range?.startRow ?? 0;\n const firstCol = range?.startColumn ?? 0;\n\n const hiddenCol = (c: number) => options.skipHidden === true && sheet?.columnData?.[String(c)]?.hd === 1;\n const hiddenRow = (r: number) => options.skipHidden === true && sheet?.rowData?.[String(r)]?.hd === 1;\n const rows: string[][] = [];\n const ySplit = Math.max(0, sheet?.freeze?.ySplit ?? 0);\n const xSplit = Math.max(0, sheet?.freeze?.xSplit ?? 0);\n let frozenRows = 0;\n let frozenCols = 0;\n for (let r = firstRow; r <= maxRow; r += 1) {\n if (hiddenRow(r)) continue;\n if (r < ySplit) frozenRows += 1;\n const row: string[] = [];\n const source = cellData[String(r)] ?? {};\n let colsFrozenHere = 0;\n for (let c = firstCol; c <= maxCol; c += 1) {\n if (hiddenCol(c)) continue;\n if (c < xSplit) colsFrozenHere += 1;\n row.push(cellText(source[String(c)], styles));\n }\n frozenCols = colsFrozenHere;\n rows.push(row);\n }\n return { sheetName: sheet?.name ?? \"Sheet1\", rows, frozenRows, frozenCols };\n}\n","/**\n * snapshot → SVG: a faithful miniature of a Univer workbook's first sheet or a\n * Univer document's first page — the gallery tile Google draws. Pure (no DOM,\n * no Univer runtime), so it runs in the browser (thumbnail capture), in tests\n * and in node. Reads only what a snapshot stores: cell values + styles +\n * column widths + merges + conditional formats + checkboxes for sheets; the\n * dataStream + text runs + paragraph styles + tables for documents.\n */\n\nexport const THUMB_WIDTH = 320;\nexport const THUMB_HEIGHT = 414;\n\ntype Rgb = { rgb?: string | null } | null | undefined;\ntype CellStyle = {\n bg?: Rgb;\n cl?: Rgb;\n bl?: number;\n it?: number;\n fs?: number;\n ht?: number;\n n?: { pattern?: string } | null;\n bd?: Record<string, unknown> | null;\n};\ntype Cell = { v?: unknown; s?: string | CellStyle | null; t?: number; f?: string };\ntype Sheet = {\n id?: string;\n name?: string;\n cellData?: Record<string, Record<string, Cell>>;\n columnData?: Record<string, { w?: number; hd?: number }>;\n rowData?: Record<string, { h?: number; hd?: number }>;\n defaultColumnWidth?: number;\n defaultRowHeight?: number;\n mergeData?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n showGridlines?: number;\n freeze?: { ySplit?: number; xSplit?: number };\n};\nexport type Workbook = {\n sheetOrder?: string[];\n sheets?: Record<string, Sheet>;\n styles?: Record<string, CellStyle | null>;\n resources?: Array<{ name?: string; data?: string }>;\n};\n\nconst esc = (s: string) =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\nfunction color(c: Rgb, fallback: string): string {\n const v = c?.rgb;\n return typeof v === \"string\" && v.length > 0 ? v : fallback;\n}\n\n// ─── number formats ──────────────────────────────────────────────────────────\n\nconst EXCEL_EPOCH = Date.UTC(1899, 11, 30);\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\nexport function formatCellValue(v: unknown, pattern?: string | null): string {\n if (v === null || v === undefined) return \"\";\n if (typeof v === \"boolean\") return v ? \"TRUE\" : \"FALSE\";\n if (typeof v !== \"number\" || !pattern || pattern === \"General\") return String(v);\n const p = pattern.toLowerCase();\n if (/[dy]/.test(p) && !p.includes(\"$\")) {\n const d = new Date(EXCEL_EPOCH + Math.round(v) * 86400000);\n const mm = d.getUTCMonth();\n const dd = d.getUTCDate();\n const yy = d.getUTCFullYear();\n if (p.includes(\"mmm\")) return `${MONTHS[mm]} ${dd}${p.includes(\"y\") ? `, ${yy}` : \"\"}`;\n return p.includes(\"y\") ? `${mm + 1}/${dd}/${yy}` : `${mm + 1}/${dd}`;\n }\n const decimals = (pattern.split(\".\")[1]?.match(/0/g) ?? []).length;\n if (p.includes(\"%\")) return `${(v * 100).toFixed(decimals)}%`;\n const grouped = Math.abs(v).toLocaleString(\"en-US\", {\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals,\n useGrouping: pattern.includes(\",\"),\n });\n const sign = v < 0 ? \"-\" : \"\";\n return p.includes(\"$\") ? `${sign}$${grouped}` : `${sign}${grouped}`;\n}\n\n// ─── conditional formatting (the rules a preview can evaluate) ───────────────\n\nexport type CfRule = {\n rule?: {\n type?: string;\n subType?: string;\n operator?: string;\n value?: unknown;\n style?: CellStyle;\n };\n ranges?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n};\n\nexport function parseResource<T>(wb: Workbook, name: string): T | null {\n const res = wb.resources?.find((r) => r.name === name);\n if (!res?.data) return null;\n try {\n return JSON.parse(res.data) as T;\n } catch {\n return null;\n }\n}\n\nexport function cfMatch(rule: NonNullable<CfRule[\"rule\"]>, v: unknown): boolean {\n if (rule.type !== \"highlightCell\") return false;\n if (rule.subType === \"number\" && typeof v === \"number\") {\n const x = rule.value;\n const [a = 0, b = 0] = Array.isArray(x) ? (x as number[]) : [Number(x), Number(x)];\n switch (rule.operator) {\n case \"greaterThan\": return v > a;\n case \"greaterThanOrEqual\": return v >= a;\n case \"lessThan\": return v < a;\n case \"lessThanOrEqual\": return v <= a;\n case \"equal\": return v === a;\n case \"notEqual\": return v !== a;\n case \"between\": return v >= a && v <= b;\n default: return false;\n }\n }\n if (rule.subType === \"text\" && v !== undefined && v !== null) {\n const s = String(v).toLowerCase();\n const want = String(rule.value ?? \"\").toLowerCase();\n switch (rule.operator) {\n case \"containsText\": return s.includes(want);\n case \"equal\": return s === want;\n case \"beginsWith\": return s.startsWith(want);\n default: return false;\n }\n }\n return false;\n}\n\n// ─── workbook ────────────────────────────────────────────────────────────────\n\nexport function workbookPreviewSvg(snapshot: unknown): string {\n const wb = (snapshot ?? {}) as Workbook;\n const firstId = wb.sheetOrder?.[0] ?? Object.keys(wb.sheets ?? {})[0];\n const sheet: Sheet = (firstId && wb.sheets?.[firstId]) || {};\n const sheetId = sheet.id ?? firstId ?? \"\";\n const styles = wb.styles ?? {};\n const cfAll = parseResource<Record<string, CfRule[]>>(wb, \"SHEET_CONDITIONAL_FORMATTING_PLUGIN\");\n const cf = (cfAll?.[sheetId] ?? []).filter((r) => r.rule && r.ranges);\n const dvAll = parseResource<Record<string, Array<{ type?: string; ranges?: CfRule[\"ranges\"] }>>>(\n wb,\n \"SHEET_DATA_VALIDATION_PLUGIN\",\n );\n const checkboxRanges = (dvAll?.[sheetId] ?? []).filter((d) => d.type === \"checkbox\").flatMap((d) => d.ranges ?? []);\n const inRanges = (rs: CfRule[\"ranges\"], r: number, c: number) =>\n (rs ?? []).some((x) => r >= x.startRow && r <= x.endRow && c >= x.startColumn && c <= x.endColumn);\n\n const dcw = sheet.defaultColumnWidth ?? 88;\n const drh = sheet.defaultRowHeight ?? 24;\n const colW = (c: number) => (sheet.columnData?.[c]?.hd ? 0 : sheet.columnData?.[c]?.w ?? dcw);\n const rowH = (r: number) => (sheet.rowData?.[r]?.hd ? 0 : sheet.rowData?.[r]?.h ?? drh);\n\n // Show the used width (at least ~5 default columns), scaled to the tile.\n let maxCol = 0;\n for (const row of Object.values(sheet.cellData ?? {})) {\n for (const c of Object.keys(row ?? {})) maxCol = Math.max(maxCol, Number(c));\n }\n let used = 0;\n for (let c = 0; c <= maxCol; c++) used += colW(c);\n // Google's tiles show the top-left of the sheet at a readable size, not the whole width.\n const span = Math.min(Math.max(used + 12, dcw * 5), 640);\n const scale = THUMB_WIDTH / span;\n\n const out: string[] = [];\n out.push(`<rect width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" fill=\"#ffffff\"/>`);\n const gridOn = sheet.showGridlines !== 0;\n const merges = sheet.mergeData ?? [];\n const covered = new Set<string>();\n for (const m of merges) {\n for (let r = m.startRow; r <= m.endRow; r++)\n for (let c = m.startColumn; c <= m.endColumn; c++)\n if (r !== m.startRow || c !== m.startColumn) covered.add(`${r}:${c}`);\n }\n const texts: string[] = [];\n let y = 0;\n for (let r = 0; y * scale < THUMB_HEIGHT && r < 400; r++) {\n const h = rowH(r);\n let x = 0;\n for (let c = 0; x * scale < THUMB_WIDTH && c < 60; c++) {\n const w = colW(c);\n if (w === 0 || h === 0 || covered.has(`${r}:${c}`)) {\n x += w;\n continue;\n }\n const m = merges.find((mm) => mm.startRow === r && mm.startColumn === c);\n let cw = w;\n let ch = h;\n if (m) {\n cw = 0;\n for (let k = m.startColumn; k <= m.endColumn; k++) cw += colW(k);\n ch = 0;\n for (let k = m.startRow; k <= m.endRow; k++) ch += rowH(k);\n }\n const cell = sheet.cellData?.[r]?.[c];\n const base: CellStyle =\n (typeof cell?.s === \"string\" ? styles[cell.s] : (cell?.s as CellStyle | null)) ?? {};\n let st: CellStyle = base;\n for (const rule of cf) {\n if (inRanges(rule.ranges, r, c) && rule.rule && cfMatch(rule.rule, cell?.v)) {\n st = { ...st, ...rule.rule.style };\n break;\n }\n }\n const X = x * scale;\n const Y = y * scale;\n const W = cw * scale;\n const H = ch * scale;\n const bg = st.bg?.rgb;\n if (bg) out.push(`<rect x=\"${X.toFixed(1)}\" y=\"${Y.toFixed(1)}\" width=\"${W.toFixed(1)}\" height=\"${H.toFixed(1)}\" fill=\"${esc(bg)}\"/>`);\n if (gridOn) out.push(`<rect x=\"${X.toFixed(1)}\" y=\"${Y.toFixed(1)}\" width=\"${W.toFixed(1)}\" height=\"${H.toFixed(1)}\" fill=\"none\" stroke=\"#e2e3e3\" stroke-width=\"0.5\"/>`);\n const fs = Math.max((st.fs ?? 10) * 1.333 * scale, 3);\n const midY = Y + H / 2 + fs * 0.35;\n if (inRanges(checkboxRanges, r, c) && r > 0 && (cell?.v === true || cell?.v === false || cell?.v === 1 || cell?.v === 0 || cell?.v === \"TRUE\" || cell?.v === \"FALSE\")) {\n const box = Math.min(H * 0.55, 9);\n const bx = X + W / 2 - box / 2;\n const by = Y + H / 2 - box / 2;\n const on = cell?.v === true || cell?.v === 1 || cell?.v === \"TRUE\";\n out.push(`<rect x=\"${bx.toFixed(1)}\" y=\"${by.toFixed(1)}\" width=\"${box.toFixed(1)}\" height=\"${box.toFixed(1)}\" rx=\"1\" fill=\"${on ? \"#1a73e8\" : \"#ffffff\"}\" stroke=\"${on ? \"#1a73e8\" : \"#5f6368\"}\" stroke-width=\"0.7\"/>`);\n if (on) out.push(`<path d=\"M${(bx + box * 0.2).toFixed(1)} ${(by + box * 0.5).toFixed(1)} l${(box * 0.25).toFixed(1)} ${(box * 0.25).toFixed(1)} l${(box * 0.4).toFixed(1)} ${(-box * 0.45).toFixed(1)}\" stroke=\"#fff\" stroke-width=\"0.9\" fill=\"none\"/>`);\n } else if (cell && cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n const text = formatCellValue(cell.v, st.n?.pattern);\n const numeric = typeof cell.v === \"number\";\n const ht = st.ht ?? (numeric ? 3 : 1);\n const anchor = ht === 2 ? \"middle\" : ht === 3 ? \"end\" : \"start\";\n const tx = ht === 2 ? X + W / 2 : ht === 3 ? X + W - 2 * scale * 2 : X + 3 * scale;\n const maxChars = Math.max(Math.floor((m ? W : W * (ht === 1 && !numeric ? 3 : 1)) / (fs * 0.55)), 1);\n const shown = text.length > maxChars ? text.slice(0, maxChars) : text;\n texts.push(\n `<text x=\"${tx.toFixed(1)}\" y=\"${midY.toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" text-anchor=\"${anchor}\" fill=\"${esc(color(st.cl, \"#202124\"))}\"${st.bl ? ' font-weight=\"700\"' : \"\"}${st.it ? ' font-style=\"italic\"' : \"\"}>${esc(shown)}</text>`,\n );\n }\n x += w;\n }\n y += h;\n }\n return wrapSvg([...out, ...texts].join(\"\"));\n}\n\n// ─── document ────────────────────────────────────────────────────────────────\n\ntype TextStyle = { fs?: number; bl?: number; it?: number; cl?: Rgb; ff?: string; bg?: Rgb };\ntype DocData = {\n body?: {\n dataStream?: string;\n paragraphs?: Array<{ startIndex: number; paragraphStyle?: { horizontalAlign?: number; spaceAbove?: { v?: number }; spaceBelow?: { v?: number } } }>;\n textRuns?: Array<{ st: number; ed: number; ts?: TextStyle }>;\n tables?: Array<{ startIndex: number; endIndex: number; tableId: string }>;\n };\n documentStyle?: {\n pageSize?: { width?: number; height?: number };\n marginTop?: number;\n marginLeft?: number;\n marginRight?: number;\n };\n};\n\nconst CONTROL = /[\\x1A\\x1B\\x1C\\x1D\\x0E\\x0F\\x1F\\x1E\\b]/g;\n\nexport function documentPreviewSvg(snapshot: unknown): string {\n const doc = (snapshot ?? {}) as DocData;\n const stream = doc.body?.dataStream ?? \"\";\n const pageW = doc.documentStyle?.pageSize?.width ?? 595;\n const scale = THUMB_WIDTH / pageW;\n const ml = (doc.documentStyle?.marginLeft ?? 72) * scale;\n const mr = (doc.documentStyle?.marginRight ?? 72) * scale;\n const mt = (doc.documentStyle?.marginTop ?? 72) * scale;\n const contentW = THUMB_WIDTH - ml - mr;\n const runs = [...(doc.body?.textRuns ?? [])].sort((a, b) => a.st - b.st);\n const tables = doc.body?.tables ?? [];\n const styleAt = (i: number): TextStyle => runs.find((r) => i >= r.st && i < r.ed)?.ts ?? {};\n /** The style most of a paragraph's characters carry (a bold lead-in does not make the line bold). */\n const dominantStyle = (from: number, to: number): TextStyle => {\n const counts = new Map<string, { n: number; ts: TextStyle }>();\n for (let i = from; i < to; i++) {\n if (/\\s/.test(stream[i] ?? \"\")) continue;\n const ts = styleAt(i);\n const k = JSON.stringify(ts);\n const e = counts.get(k) ?? { n: 0, ts };\n e.n++;\n counts.set(k, e);\n }\n let best: { n: number; ts: TextStyle } | null = null;\n for (const e of counts.values()) if (!best || e.n > best.n) best = e;\n return best?.ts ?? {};\n };\n const out: string[] = [`<rect width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" fill=\"#ffffff\"/>`];\n\n let y = mt;\n let start = 0;\n const paragraphs = doc.body?.paragraphs ?? [];\n for (let p = 0; p < paragraphs.length && y < THUMB_HEIGHT; p++) {\n const para = paragraphs[p];\n if (!para) break;\n const end = para.startIndex;\n const table = tables.find((t) => start >= t.startIndex && start < t.endIndex);\n if (table) {\n // Draw the whole table once: rows split on the row token, cells on the cell token.\n const raw = stream.slice(table.startIndex, table.endIndex);\n const rows = raw.split(\"\\x1B\").slice(1).map((row) =>\n row.split(\"\\x1C\").slice(1).map((cell) => cell.replace(/[\\r\\n]/g, \" \").replace(CONTROL, \"\").trim()),\n );\n const cols = Math.max(1, ...rows.map((r) => r.length));\n const cw = contentW / cols;\n // Bold header row when the first cell's text is bold.\n const headerBold = styleAt(table.startIndex + 4).bl === 1;\n for (let r = 0; r < rows.length && y < THUMB_HEIGHT; r++) {\n const rh = 16 * scale * 1.2 + 6 * scale;\n for (let c = 0; c < cols; c++) {\n const cx = ml + c * cw;\n out.push(`<rect x=\"${cx.toFixed(1)}\" y=\"${y.toFixed(1)}\" width=\"${cw.toFixed(1)}\" height=\"${rh.toFixed(1)}\" fill=\"${r === 0 && headerBold ? \"#f1f3f4\" : \"none\"}\" stroke=\"#9aa0a6\" stroke-width=\"0.4\"/>`);\n const fs = 11 * 1.333 * scale;\n const maxChars = Math.max(Math.floor((cw - 6 * scale) / (fs * 0.5)), 1);\n const t = rows[r]?.[c] ?? \"\";\n out.push(`<text x=\"${(cx + 4 * scale).toFixed(1)}\" y=\"${(y + rh / 2 + fs * 0.35).toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" fill=\"#202124\"${r === 0 && headerBold ? ' font-weight=\"700\"' : \"\"}>${esc(t.slice(0, maxChars))}</text>`);\n }\n y += rh;\n }\n // Skip every paragraph inside the table.\n while (p + 1 < paragraphs.length && (paragraphs[p + 1]?.startIndex ?? Infinity) < table.endIndex) p++;\n start = table.endIndex;\n y += 6 * scale;\n continue;\n }\n const text = stream.slice(start, end).replace(CONTROL, \"\");\n const st = dominantStyle(start, end);\n const ps = para.paragraphStyle ?? {};\n const fsPt = st.fs ?? 11;\n const fs = fsPt * 1.333 * scale;\n const lineH = fs * 1.3;\n y += (ps.spaceAbove?.v ?? (fsPt > 13 ? 8 : 0)) * scale;\n const align = ps.horizontalAlign ?? 1;\n const anchor = align === 2 ? \"middle\" : align === 3 ? \"end\" : \"start\";\n const tx = align === 2 ? ml + contentW / 2 : align === 3 ? ml + contentW : ml;\n // Paragraph shading (a filled band) when the run carries a highlight.\n if (!text.trim()) {\n y += lineH * 0.8;\n } else {\n const maxChars = Math.max(Math.floor(contentW / (fs * (st.bl ? 0.56 : 0.5))), 4);\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let line = \"\";\n for (const w of words) {\n if ((line + \" \" + w).trim().length > maxChars && line) {\n lines.push(line);\n line = w;\n } else line = (line + \" \" + w).trim();\n }\n if (line) lines.push(line);\n for (const l of lines) {\n if (y > THUMB_HEIGHT) break;\n y += lineH;\n if (st.bg?.rgb) out.push(`<rect x=\"${ml.toFixed(1)}\" y=\"${(y - fs).toFixed(1)}\" width=\"${contentW.toFixed(1)}\" height=\"${lineH.toFixed(1)}\" fill=\"${esc(st.bg.rgb)}\"/>`);\n out.push(`<text x=\"${tx.toFixed(1)}\" y=\"${y.toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" text-anchor=\"${anchor}\" fill=\"${esc(color(st.cl, \"#202124\"))}\"${st.bl ? ' font-weight=\"700\"' : \"\"}${st.it ? ' font-style=\"italic\"' : \"\"}${st.ff && /serif|georgia|times|garamond/i.test(st.ff) && !/sans/i.test(st.ff) ? ' font-family=\"Georgia, serif\"' : \"\"}>${esc(l)}</text>`);\n }\n }\n y += (ps.spaceBelow?.v ?? 4) * scale;\n start = end + 1;\n }\n return wrapSvg(out.join(\"\"));\n}\n\nfunction wrapSvg(body: string): string {\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" viewBox=\"0 0 ${THUMB_WIDTH} ${THUMB_HEIGHT}\" font-family=\"Arial, Helvetica, sans-serif\">${body}</svg>`;\n}\n\nexport function snapshotPreviewSvg(kind: \"workbook\" | \"document\", snapshot: unknown): string {\n return kind === \"workbook\" ? workbookPreviewSvg(snapshot) : documentPreviewSvg(snapshot);\n}\n","/**\n * features/workbooks/snapshot-grid.ts\n *\n * Snapshot → a formatted, read-only grid model: what a spreadsheet VIEW needs and the plain-string\n * `univer-snapshot-rows` does not carry — number/currency/date formats applied, checkbox cells\n * (data-validation ranges of type checkbox), alignment, bold/italic, fill and text colour, column\n * widths, merges, frozen rows/columns, hidden rows/columns and sheets. Pure (no DOM, no Univer\n * runtime): the signed-out share page draws it. The number formatter is the thumbnail's\n * (`formatCellValue`) so a tile, a share link and the editor read the same.\n */\n\nimport {\n cfMatch,\n formatCellValue,\n parseResource,\n type CfRule,\n type Workbook,\n} from \"./snapshot-preview-svg\";\n\ntype Rgb = { rgb?: string | null } | null | undefined;\ninterface Style {\n bg?: Rgb;\n cl?: Rgb;\n bl?: number;\n it?: number;\n fs?: number;\n ht?: number;\n tb?: number;\n n?: { pattern?: string } | null;\n}\ninterface Cell {\n v?: unknown;\n s?: string | Style | null;\n}\ninterface Sheet {\n id?: string;\n name?: string;\n hidden?: number;\n cellData?: Record<string, Record<string, Cell | null | undefined>>;\n columnData?: Record<string, { w?: number; hd?: number } | null | undefined>;\n rowData?: Record<string, { h?: number; hd?: number } | null | undefined>;\n defaultColumnWidth?: number;\n defaultRowHeight?: number;\n mergeData?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n showGridlines?: number;\n freeze?: { xSplit?: number; ySplit?: number };\n}\n\nexport interface GridCell {\n text: string;\n /** A checkbox cell (a data-validation checkbox range): `checked` says its state. */\n checkbox?: { checked: boolean } | undefined;\n align: \"left\" | \"center\" | \"right\";\n bold: boolean;\n italic: boolean;\n /** Font size in px (the snapshot stores points). */\n fontPx: number;\n bg?: string | undefined;\n color?: string | undefined;\n wrap: boolean;\n rowSpan: number;\n colSpan: number;\n /** Covered by a merge that starts elsewhere: draw nothing. */\n covered: boolean;\n}\n\nexport interface GridSheet {\n id: string;\n name: string;\n /** Visible column indexes (hidden columns left out) with their pixel widths. */\n columns: Array<{ index: number; width: number }>;\n rows: Array<{ index: number; height: number; cells: GridCell[] }>;\n /** How many leading VISIBLE rows / columns stay put while scrolling. */\n frozenRows: number;\n frozenColumns: number;\n gridlines: boolean;\n /** Rows beyond the cap were left out. */\n truncatedFrom: number | null;\n}\n\nexport const GRID_MAX_ROWS = 500;\nexport const GRID_MAX_COLUMNS = 60;\n\nconst PT_TO_PX = 1.333;\nconst isCheckboxValue = (v: unknown) => v === true || v === false || v === 1 || v === 0 || v === \"TRUE\" || v === \"FALSE\";\nconst isOn = (v: unknown) => v === true || v === 1 || v === \"TRUE\";\n\nfunction hasValue(cell: Cell | null | undefined): boolean {\n const v = cell?.v;\n return v !== undefined && v !== null && v !== \"\";\n}\n\n/** Every visible sheet that has something in it, in tab order. Empty and hidden sheets are left out. */\nexport function snapshotToGridSheets(snapshot: unknown): GridSheet[] {\n if (typeof snapshot !== \"object\" || snapshot === null) return [];\n const wb = snapshot as Workbook;\n const sheets = wb.sheets ?? {};\n const order = (wb.sheetOrder ?? []).filter((id) => sheets[id]);\n const ids = order.length > 0 ? order : Object.keys(sheets);\n const out: GridSheet[] = [];\n for (const id of ids) {\n const grid = sheetToGrid(wb, id, sheets[id] as Sheet);\n if (grid) out.push(grid);\n }\n return out;\n}\n\nfunction sheetToGrid(wb: Workbook, id: string, sheet: Sheet): GridSheet | null {\n if (sheet.hidden === 1) return null;\n const cellData = sheet.cellData ?? {};\n let maxRow = -1;\n let maxCol = -1;\n for (const [rk, row] of Object.entries(cellData)) {\n const r = Number(rk);\n if (!Number.isInteger(r) || !row) continue;\n for (const [ck, cell] of Object.entries(row)) {\n const c = Number(ck);\n if (!Number.isInteger(c) || !hasValue(cell)) continue;\n if (r > maxRow) maxRow = r;\n if (c > maxCol) maxCol = c;\n }\n }\n if (maxRow < 0 || maxCol < 0) return null;\n\n const styles = wb.styles ?? {};\n const sheetId = sheet.id ?? id;\n const cfAll = parseResource<Record<string, CfRule[]>>(wb, \"SHEET_CONDITIONAL_FORMATTING_PLUGIN\");\n const cf = (cfAll?.[sheetId] ?? []).filter((r) => r.rule && r.ranges);\n const dvAll = parseResource<Record<string, Array<{ type?: string; ranges?: CfRule[\"ranges\"] }>>>(\n wb,\n \"SHEET_DATA_VALIDATION_PLUGIN\",\n );\n const checkboxRanges = (dvAll?.[sheetId] ?? []).filter((d) => d.type === \"checkbox\").flatMap((d) => d.ranges ?? []);\n const inRanges = (rs: CfRule[\"ranges\"], r: number, c: number) =>\n (rs ?? []).some((x) => r >= x.startRow && r <= x.endRow && c >= x.startColumn && c <= x.endColumn);\n\n const dcw = sheet.defaultColumnWidth ?? 88;\n const drh = sheet.defaultRowHeight ?? 24;\n const lastCol = Math.min(maxCol, GRID_MAX_COLUMNS - 1);\n const columns: GridSheet[\"columns\"] = [];\n for (let c = 0; c <= lastCol; c += 1) {\n const col = sheet.columnData?.[String(c)];\n if (col?.hd === 1) continue;\n columns.push({ index: c, width: col?.w ?? dcw });\n }\n\n const merges = sheet.mergeData ?? [];\n const covered = new Set<string>();\n for (const m of merges) {\n for (let r = m.startRow; r <= m.endRow; r += 1)\n for (let c = m.startColumn; c <= m.endColumn; c += 1) if (r !== m.startRow || c !== m.startColumn) covered.add(`${r}:${c}`);\n }\n\n const rows: GridSheet[\"rows\"] = [];\n const lastRow = Math.min(maxRow, GRID_MAX_ROWS - 1);\n for (let r = 0; r <= lastRow; r += 1) {\n const rd = sheet.rowData?.[String(r)];\n if (rd?.hd === 1) continue;\n const source = cellData[String(r)] ?? {};\n const cells: GridCell[] = columns.map(({ index: c }) => {\n const cell = source[String(c)] ?? undefined;\n const base: Style = (typeof cell?.s === \"string\" ? (styles[cell.s] as Style | null | undefined) : (cell?.s as Style | null | undefined)) ?? {};\n let st: Style = base;\n for (const rule of cf) {\n if (inRanges(rule.ranges, r, c) && rule.rule && cfMatch(rule.rule, cell?.v)) {\n st = { ...st, ...(rule.rule.style as Style | undefined) };\n break;\n }\n }\n const m = merges.find((mm) => mm.startRow === r && mm.startColumn === c);\n const v = cell?.v;\n const box = hasValue(cell) && inRanges(checkboxRanges, r, c) && isCheckboxValue(v);\n const numeric = typeof v === \"number\";\n const ht = st.ht ?? 0;\n return {\n text: box ? \"\" : hasValue(cell) ? formatCellValue(v, st.n?.pattern) : \"\",\n checkbox: box ? { checked: isOn(v) } : undefined,\n align: box || ht === 2 ? \"center\" : ht === 3 || (ht === 0 && numeric) ? \"right\" : \"left\",\n bold: st.bl === 1,\n italic: st.it === 1,\n fontPx: Math.round((st.fs ?? 10) * PT_TO_PX),\n bg: st.bg?.rgb ?? undefined,\n color: st.cl?.rgb ?? undefined,\n wrap: st.tb === 3,\n rowSpan: m ? m.endRow - m.startRow + 1 : 1,\n colSpan: m ? m.endColumn - m.startColumn + 1 : 1,\n covered: covered.has(`${r}:${c}`),\n };\n });\n rows.push({ index: r, height: rd?.h ?? drh, cells });\n }\n\n const ySplit = sheet.freeze?.ySplit ?? 0;\n const xSplit = sheet.freeze?.xSplit ?? 0;\n return {\n id: sheetId,\n name: sheet.name ?? \"Sheet1\",\n columns,\n rows,\n frozenRows: Math.min(rows.filter((r) => r.index < ySplit).length, rows.length),\n frozenColumns: Math.min(columns.filter((c) => c.index < xSplit).length, columns.length),\n gridlines: sheet.showGridlines !== 0,\n truncatedFrom: maxRow > lastRow ? maxRow + 1 : null,\n };\n}\n","/**\n * The ONE page geometry every Matrx cloud document is laid out with.\n *\n * Univer lays a document out inside `documentStyle.pageSize`. With no pageSize\n * the docs renderer has no page box at all: text never wraps (it runs off the\n * right edge) and the vertical extent is unbounded, so the docs viewport\n * reports nothing to scroll — the wheel is swallowed and the page sits frozen\n * at the top. Every writer of a Univer snapshot MUST stamp this style.\n *\n * Consumers: `DocumentEditor` (new empty doc), `markdown-to-univer-doc`\n * (markdown import), and `sanitizeUniverDocSnapshot` (recovery for snapshots\n * that reached storage without it — notably `origin='agent'` writes).\n */\nimport type { DocumentFlavor, IDocumentData, PageOrientType } from \"@univerjs/core\";\n\n// Univer's enum values, written out: this file is read by tests and the markdown importer, which must not\n// pull Univer's runtime in just for four numbers (guarded by the page-style test).\nconst TRADITIONAL = 1 as DocumentFlavor;\nconst MODERN = 2 as DocumentFlavor;\nconst PORTRAIT = 0 as PageOrientType;\nconst LANDSCAPE = 1 as PageOrientType;\n\ntype DocumentStyle = NonNullable<IDocumentData[\"documentStyle\"]>;\n\n/** Univer lays documents out in 96-dpi CSS pixels: one inch is 96 units. */\nexport const PX_PER_INCH = 96;\n\n/** Paper sizes the Page setup dialog offers, in 96-dpi pixels, portrait (width x height). */\nexport const PAPER_SIZES = {\n Letter: { width: 816, height: 1056, label: \"Letter (8.5 x 11 in)\" },\n Legal: { width: 816, height: 1344, label: \"Legal (8.5 x 14 in)\" },\n Tabloid: { width: 1056, height: 1632, label: \"Tabloid (11 x 17 in)\" },\n Executive: { width: 696, height: 1008, label: \"Executive (7.25 x 10.5 in)\" },\n Statement: { width: 528, height: 816, label: \"Statement (5.5 x 8.5 in)\" },\n A3: { width: 1123, height: 1587, label: \"A3 (11.69 x 16.54 in)\" },\n A4: { width: 794, height: 1124, label: \"A4 (8.27 x 11.69 in)\" },\n A5: { width: 559, height: 794, label: \"A5 (5.83 x 8.27 in)\" },\n} as const;\nexport type PaperSizeName = keyof typeof PAPER_SIZES;\n\n/** A real page, like Google Docs: Letter, one-inch margins (624px of text), paginated. */\nexport const DEFAULT_DOCUMENT_PAGE_STYLE: DocumentStyle = {\n pageSize: { width: 816, height: 1056 },\n documentFlavor: TRADITIONAL,\n pageOrient: PORTRAIT,\n marginTop: PX_PER_INCH,\n marginBottom: PX_PER_INCH,\n marginLeft: PX_PER_INCH,\n marginRight: PX_PER_INCH,\n // Univer applies no paragraph spacing to a paginated page by itself; without this every paragraph\n // runs into the next (Google Docs' own default: 1.15 lines, 10px after).\n defaultParagraphStyle: { spaceAbove: { v: 0 }, spaceBelow: { v: 10 }, lineSpacing: 1.15 },\n};\n\n/** Fresh copy — Univer mutates the style it is handed. */\nexport function defaultDocumentPageStyle(): DocumentStyle {\n return {\n ...DEFAULT_DOCUMENT_PAGE_STYLE,\n pageSize: { ...DEFAULT_DOCUMENT_PAGE_STYLE.pageSize! },\n defaultParagraphStyle: { ...DEFAULT_DOCUMENT_PAGE_STYLE.defaultParagraphStyle! },\n };\n}\n\n/**\n * The squeezed geometry every document was stamped with until 2026-10-15: A4 at 72 dpi (595 x 842)\n * with 90/72 margins, in Univer's pageless flavour, so the text column was ~415px with no paper.\n * Pageless was never offered then, so this exact shape is always the old default, never a choice.\n */\nexport function isLegacySqueezedPageStyle(style: DocumentStyle | undefined): boolean {\n const size = style?.pageSize;\n return (\n !!size &&\n size.width === 595 &&\n size.height === 842 &&\n style?.marginLeft === 90 &&\n style?.marginRight === 90 &&\n style?.marginTop === 72 &&\n style?.marginBottom === 72\n );\n}\n\n/** What the Page setup dialog edits. Margins are in inches, like Google's. */\nexport interface PageSetupValues {\n pageless: boolean;\n orientation: \"portrait\" | \"landscape\";\n paper: PaperSizeName;\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Paper colour, hex. Always a light colour so the black ink stays readable. */\n pageColor: string;\n}\n\nexport const PAGE_COLORS = [\"#ffffff\", \"#fff8e7\", \"#f3f3f3\", \"#e8f0fe\", \"#e6f4ea\", \"#fef7e0\"] as const;\nexport const DEFAULT_PAGE_COLOR = PAGE_COLORS[0];\n/** Key on `documentStyle` carrying the paper colour (Univer paints it from the host's surface theme). */\nexport const PAGE_COLOR_KEY = \"matrxPageColor\";\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\n/** The dialog's values, read from a document's style (missing parts fall back to the default page). */\nexport function pageSetupFromStyle(style: DocumentStyle | undefined): PageSetupValues {\n const landscape = style?.pageOrient === LANDSCAPE;\n const w = style?.pageSize?.width ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.width!;\n const h = style?.pageSize?.height ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.height!;\n const [pw, ph] = landscape ? [h, w] : [w, h];\n const paper =\n (Object.keys(PAPER_SIZES) as PaperSizeName[]).find(\n (k) => Math.abs(PAPER_SIZES[k].width - pw) <= 1 && Math.abs(PAPER_SIZES[k].height - ph) <= 1,\n ) ?? \"Letter\";\n const inch = (v: number | undefined) => round2((v ?? PX_PER_INCH) / PX_PER_INCH);\n const color = (style as Record<string, unknown> | undefined)?.[PAGE_COLOR_KEY];\n return {\n pageless: style?.documentFlavor === MODERN,\n orientation: landscape ? \"landscape\" : \"portrait\",\n paper,\n marginTop: inch(style?.marginTop),\n marginBottom: inch(style?.marginBottom),\n marginLeft: inch(style?.marginLeft),\n marginRight: inch(style?.marginRight),\n pageColor: typeof color === \"string\" && color ? color : DEFAULT_PAGE_COLOR,\n };\n}\n\n/** Params for Univer's `docs.command.page-setup` (pageSize is the as-printed size: swapped when landscape). */\nexport function pageSetupCommandParams(v: PageSetupValues) {\n const base = PAPER_SIZES[v.paper];\n const landscape = v.orientation === \"landscape\";\n return {\n documentFlavor: v.pageless ? MODERN : TRADITIONAL,\n pageOrient: landscape ? LANDSCAPE : PORTRAIT,\n pageSize: landscape ? { width: base.height, height: base.width } : { width: base.width, height: base.height },\n marginTop: Math.round(v.marginTop * PX_PER_INCH),\n marginBottom: Math.round(v.marginBottom * PX_PER_INCH),\n marginLeft: Math.round(v.marginLeft * PX_PER_INCH),\n marginRight: Math.round(v.marginRight * PX_PER_INCH),\n };\n}\n","/**\n * A workbook's print settings — Google Sheets' File → Page setup / Print, as pure data and pure\n * pagination (no React, no IO). They live on the workbook (`udt_workbooks.metadata.page_setup`),\n * so Print, Download as PDF and the Page setup dialog all read the same values.\n *\n * Geometry is in 96-dpi CSS pixels, like the rest of the document stack (`PX_PER_INCH`).\n */\n\nimport { PAPER_SIZES, PX_PER_INCH, type PaperSizeName } from \"../core\";\n\nexport const SHEET_SCALES = [\"normal\", \"width\", \"height\", \"page\"] as const;\nexport type SheetScale = (typeof SHEET_SCALES)[number];\nexport const SHEET_MARGIN_PRESETS = [\"normal\", \"narrow\", \"wide\", \"custom\"] as const;\nexport type SheetMarginPreset = (typeof SHEET_MARGIN_PRESETS)[number];\nexport const SHEET_PRINT_SCOPES = [\"sheet\", \"workbook\", \"selection\"] as const;\nexport type SheetPrintScope = (typeof SHEET_PRINT_SCOPES)[number];\nexport type SheetPageOrder = \"down-over\" | \"over-down\";\nexport type SheetAlignH = \"left\" | \"center\" | \"right\";\nexport type SheetAlignV = \"top\" | \"middle\" | \"bottom\";\n\nexport interface SheetPageSetup {\n paper: PaperSizeName;\n orientation: \"portrait\" | \"landscape\";\n scale: SheetScale;\n margins: SheetMarginPreset;\n /** Inches; read only when `margins` is \"custom\". */\n customMargins: { top: number; bottom: number; left: number; right: number };\n scope: SheetPrintScope;\n gridlines: boolean;\n repeatFrozenRows: boolean;\n repeatFrozenColumns: boolean;\n pageOrder: SheetPageOrder;\n alignH: SheetAlignH;\n alignV: SheetAlignV;\n}\n\n/** Google Sheets' defaults: Letter, portrait, 100%, normal margins, current sheet, gridlines on. */\nexport const DEFAULT_SHEET_PAGE_SETUP: SheetPageSetup = {\n paper: \"Letter\",\n orientation: \"portrait\",\n scale: \"normal\",\n margins: \"normal\",\n customMargins: { top: 0.75, bottom: 0.75, left: 0.7, right: 0.7 },\n scope: \"sheet\",\n gridlines: true,\n repeatFrozenRows: false,\n repeatFrozenColumns: false,\n pageOrder: \"down-over\",\n alignH: \"left\",\n alignV: \"top\",\n};\n\n/** Google's three preset margins, in inches. */\nexport const MARGIN_PRESET_INCHES: Record<Exclude<SheetMarginPreset, \"custom\">, { top: number; bottom: number; left: number; right: number }> = {\n normal: { top: 0.75, bottom: 0.75, left: 0.7, right: 0.7 },\n narrow: { top: 0.25, bottom: 0.25, left: 0.25, right: 0.25 },\n wide: { top: 1, bottom: 1, left: 1, right: 1 },\n};\n\nconst isPaper = (v: unknown): v is PaperSizeName => typeof v === \"string\" && v in PAPER_SIZES;\nconst oneOf = <T extends string>(list: readonly T[], v: unknown, fallback: T): T => (typeof v === \"string\" && (list as readonly string[]).includes(v) ? (v as T) : fallback);\nconst inches = (v: unknown, fallback: number) => (typeof v === \"number\" && Number.isFinite(v) && v >= 0 && v <= 5 ? v : fallback);\n\n/** Any stored value → a complete, valid setup. Unknown or broken parts fall back to the default. */\nexport function normalizeSheetPageSetup(raw: unknown): SheetPageSetup {\n const r = (raw && typeof raw === \"object\" ? raw : {}) as Record<string, unknown>;\n const m = (r.customMargins && typeof r.customMargins === \"object\" ? r.customMargins : {}) as Record<string, unknown>;\n const d = DEFAULT_SHEET_PAGE_SETUP;\n return {\n paper: isPaper(r.paper) ? r.paper : d.paper,\n orientation: r.orientation === \"landscape\" ? \"landscape\" : \"portrait\",\n scale: oneOf(SHEET_SCALES, r.scale, d.scale),\n margins: oneOf(SHEET_MARGIN_PRESETS, r.margins, d.margins),\n customMargins: {\n top: inches(m.top, d.customMargins.top),\n bottom: inches(m.bottom, d.customMargins.bottom),\n left: inches(m.left, d.customMargins.left),\n right: inches(m.right, d.customMargins.right),\n },\n scope: oneOf(SHEET_PRINT_SCOPES, r.scope, d.scope),\n gridlines: typeof r.gridlines === \"boolean\" ? r.gridlines : d.gridlines,\n repeatFrozenRows: r.repeatFrozenRows === true,\n repeatFrozenColumns: r.repeatFrozenColumns === true,\n pageOrder: r.pageOrder === \"over-down\" ? \"over-down\" : \"down-over\",\n alignH: oneOf([\"left\", \"center\", \"right\"] as const, r.alignH, d.alignH),\n alignV: oneOf([\"top\", \"middle\", \"bottom\"] as const, r.alignV, d.alignV),\n };\n}\n\n/** The setup stored on a workbook's metadata (`metadata.page_setup`), complete and valid. */\nexport function pageSetupFromMetadata(metadata: unknown): SheetPageSetup {\n return normalizeSheetPageSetup((metadata as { page_setup?: unknown } | null)?.page_setup);\n}\n\nexport interface PrintGeometry {\n /** Paper as printed (orientation applied), px. */\n paperWidth: number;\n paperHeight: number;\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** The printable box inside the margins, px. */\n areaWidth: number;\n areaHeight: number;\n}\n\nexport function printGeometry(setup: SheetPageSetup): PrintGeometry {\n const base = PAPER_SIZES[setup.paper];\n const landscape = setup.orientation === \"landscape\";\n const paperWidth = landscape ? base.height : base.width;\n const paperHeight = landscape ? base.width : base.height;\n const m = setup.margins === \"custom\" ? setup.customMargins : MARGIN_PRESET_INCHES[setup.margins];\n const px = (n: number) => Math.round(n * PX_PER_INCH);\n const geometry = {\n paperWidth,\n paperHeight,\n marginTop: px(m.top),\n marginBottom: px(m.bottom),\n marginLeft: px(m.left),\n marginRight: px(m.right),\n };\n return {\n ...geometry,\n areaWidth: Math.max(48, paperWidth - geometry.marginLeft - geometry.marginRight),\n areaHeight: Math.max(48, paperHeight - geometry.marginTop - geometry.marginBottom),\n };\n}\n\nexport const PRINT_ROW_HEIGHT = 22;\nconst MIN_COL = 48;\nconst MAX_COL = 320;\nconst CHAR_PX = 7;\n\n/** Column widths (px) fitted to the text the column holds. */\nexport function printColumnWidths(rows: readonly (readonly string[])[]): number[] {\n const width = rows.reduce((n, r) => Math.max(n, r.length), 0);\n const out: number[] = [];\n for (let c = 0; c < width; c += 1) {\n let longest = 0;\n for (const r of rows) longest = Math.max(longest, (r[c] ?? \"\").length);\n out.push(Math.min(MAX_COL, Math.max(MIN_COL, longest * CHAR_PX + 16)));\n }\n return out;\n}\n\nexport interface PrintPage {\n /** Grid row indexes drawn on this page, in order (repeated frozen rows first). */\n rows: number[];\n /** Grid column indexes drawn on this page, in order (repeated frozen columns first). */\n cols: number[];\n}\n\nexport interface PrintPlan {\n scale: number;\n geometry: PrintGeometry;\n colWidths: number[];\n pages: PrintPage[];\n}\n\n/** Splits `count` items into bands that fit `capacity(px)`, repeating `frozen` leading items on every band after the first. */\nfunction bands(sizes: readonly number[], capacityPx: number, frozen: number, repeat: boolean): number[][] {\n const total = sizes.length;\n if (total === 0) return [];\n const result: number[][] = [];\n const lead = repeat ? Math.min(frozen, total) : 0;\n const leadPx = sizes.slice(0, lead).reduce((a, b) => a + b, 0);\n let at = 0;\n while (at < total) {\n const first = result.length === 0;\n const carry = !first && lead > 0 ? Array.from({ length: lead }, (_, i) => i) : [];\n let used = first ? 0 : leadPx;\n const band = [...carry];\n // A repeated header never leaves a page with no room for a body item.\n if (!first && leadPx >= capacityPx) used = 0;\n let added = 0;\n while (at < total) {\n const size = sizes[at]!;\n if (used + size > capacityPx && added > 0) break;\n band.push(at);\n used += size;\n added += 1;\n at += 1;\n }\n result.push(band);\n }\n return result;\n}\n\n/** The pages one grid prints on under `setup`: scale, repeated frozen panes, and page order. */\nexport function planSheetPrint(\n rows: readonly (readonly string[])[],\n setup: SheetPageSetup,\n frozen: { rows: number; cols: number } = { rows: 0, cols: 0 },\n): PrintPlan {\n const geometry = printGeometry(setup);\n const colWidths = printColumnWidths(rows);\n const totalW = colWidths.reduce((a, b) => a + b, 0) || 1;\n const totalH = rows.length * PRINT_ROW_HEIGHT || 1;\n const fitW = geometry.areaWidth / totalW;\n const fitH = geometry.areaHeight / totalH;\n const scale =\n setup.scale === \"width\" ? Math.min(1, fitW) : setup.scale === \"height\" ? Math.min(1, fitH) : setup.scale === \"page\" ? Math.min(1, fitW, fitH) : 1;\n const rowBands = bands(\n rows.map(() => PRINT_ROW_HEIGHT),\n geometry.areaHeight / scale,\n frozen.rows,\n setup.repeatFrozenRows,\n );\n const colBands = bands(colWidths, geometry.areaWidth / scale, frozen.cols, setup.repeatFrozenColumns);\n const pages: PrintPage[] = [];\n if (setup.pageOrder === \"down-over\") {\n for (const cols of colBands) for (const r of rowBands) pages.push({ rows: r, cols });\n } else {\n for (const r of rowBands) for (const cols of colBands) pages.push({ rows: r, cols });\n }\n return { scale, geometry, colWidths, pages };\n}\n","/**\n * A workbook's print settings, read and written on the workbook itself:\n * `udt_workbooks.metadata.page_setup` (merged with `mergeJsonColumn`, like the table links beside it).\n */\nimport { mergeJsonColumn } from \"@ai-matrx/data/db\";\n\nimport { getSheetsHost } from \"./ports\";\nimport { normalizeSheetPageSetup, pageSetupFromMetadata, type SheetPageSetup } from \"./sheet-page-setup\";\n\nconst db = () => getSheetsHost().getSupabase();\n\ntype WorkbookMetaRow = { id: string; version: number; metadata: unknown };\n\nexport type PageSetupResult = { ok: true; data: SheetPageSetup } | { ok: false; error: string };\n\nexport async function readSheetPageSetup(workbookId: string): Promise<PageSetupResult> {\n const { data, error } = await db().schema(\"workbench\").from(\"udt_workbooks\").select(\"metadata\").eq(\"id\", workbookId).maybeSingle();\n if (error) return { ok: false, error: error.message };\n return { ok: true, data: pageSetupFromMetadata(data?.metadata) };\n}\n\nexport async function writeSheetPageSetup(workbookId: string, setup: SheetPageSetup): Promise<PageSetupResult> {\n const clean = normalizeSheetPageSetup(setup);\n const result = await mergeJsonColumn<WorkbookMetaRow>({\n fetchCurrent: () => db().schema(\"workbench\").from(\"udt_workbooks\").select(\"id, version, metadata\").eq(\"id\", workbookId).maybeSingle(),\n readColumn: (row) => row.metadata,\n merge: (current) => ({ ...current, page_setup: clean }),\n applyUpdate: ({ value, expectedVersion, nextVersion }) =>\n db()\n .schema(\"workbench\")\n .from(\"udt_workbooks\")\n .update({ metadata: value as never, version: nextVersion })\n .eq(\"id\", workbookId)\n .eq(\"version\", expectedVersion)\n .select(\"id, version, metadata\")\n .maybeSingle(),\n });\n if (result.status === \"saved\") return { ok: true, data: pageSetupFromMetadata(result.row.metadata) };\n if (result.status === \"not_found\") return { ok: false, error: \"This workbook could not be found\" };\n if (result.status === \"conflict\") return { ok: false, error: \"The workbook changed while saving; try again\" };\n const reason: unknown = result.error;\n return { ok: false, error: reason instanceof Error ? reason.message : typeof reason === \"string\" ? reason : \"Something went wrong\" };\n}\n","/**\n * The pages a workbook prints on: the snapshot's cells → paper-sized HTML pages that follow the\n * workbook's print settings (`sheet-page-setup.ts`). Print and Download as PDF both draw these\n * same pages, so what the browser prints is what the PDF holds.\n */\n\nimport { PX_PER_INCH } from \"../core\";\nimport {\n PRINT_ROW_HEIGHT,\n planSheetPrint,\n type PrintGeometry,\n type SheetPageSetup,\n} from \"./sheet-page-setup\";\nimport { univerSheetIds, univerSnapshotToRows, type CellRange } from \"./univer-snapshot-rows\";\n\nexport interface PrintSheet {\n name: string;\n rows: string[][];\n frozenRows: number;\n frozenCols: number;\n}\n\n/** The sheets the setup's \"what to print\" asks for (empty sheets left out). */\nexport function collectPrintSheets(\n snapshot: unknown,\n setup: SheetPageSetup,\n options: { sheetId?: string; selection?: CellRange | null },\n): PrintSheet[] {\n const read = (sheetId: string | undefined, range?: CellRange): PrintSheet | null => {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(sheetId ? { sheetId } : {}), ...(range ? { range } : {}) });\n if (!grid || grid.rows.length === 0) return null;\n return { name: grid.sheetName, rows: grid.rows, frozenRows: grid.frozenRows, frozenCols: grid.frozenCols };\n };\n if (setup.scope === \"workbook\") {\n return univerSheetIds(snapshot)\n .map((id) => read(id))\n .filter((s): s is PrintSheet => s !== null);\n }\n if (setup.scope === \"selection\") {\n const sel = options.selection;\n if (!sel || (sel.startRow === sel.endRow && sel.startColumn === sel.endColumn)) return [];\n const one = read(options.sheetId, sel);\n return one ? [one] : [];\n }\n const one = read(options.sheetId);\n return one ? [one] : [];\n}\n\nconst esc = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\nconst JUSTIFY = { left: \"flex-start\", center: \"center\", right: \"flex-end\" } as const;\nconst ALIGN = { top: \"flex-start\", middle: \"center\", bottom: \"flex-end\" } as const;\n\nfunction pageHtml(\n sheet: PrintSheet,\n page: { rows: number[]; cols: number[] },\n scale: number,\n colWidths: number[],\n g: PrintGeometry,\n setup: SheetPageSetup,\n numbering: { sheet: string; at: number; of: number },\n): string {\n const widths = page.cols.map((c) => colWidths[c] ?? 0);\n const tableW = widths.reduce((a, b) => a + b, 0);\n const tableH = page.rows.length * PRINT_ROW_HEIGHT;\n const border = setup.gridlines ? \"1px solid #b7b7b7\" : \"none\";\n const body = page.rows\n .map(\n (r) =>\n `<tr style=\"height:${PRINT_ROW_HEIGHT}px\">${page.cols\n .map((c) => `<td style=\"border:${border}\">${esc(sheet.rows[r]?.[c] ?? \"\")}</td>`)\n .join(\"\")}</tr>`,\n )\n .join(\"\");\n const cols = widths.map((w) => `<col style=\"width:${w}px\">`).join(\"\");\n return `<section data-print-page data-sheet=\"${esc(numbering.sheet)}\" data-page-number=\"${numbering.at}\" data-page-count=\"${numbering.of}\" data-page-rows=\"${page.rows.length}\" data-page-cols=\"${page.cols.length}\" style=\"width:${g.paperWidth}px;height:${g.paperHeight}px;box-sizing:border-box;padding:${g.marginTop}px ${g.marginRight}px ${g.marginBottom}px ${g.marginLeft}px;background:#fff;overflow:hidden;break-after:page;page-break-after:always\">\n<div style=\"width:${g.areaWidth}px;height:${g.areaHeight}px;display:flex;justify-content:${JUSTIFY[setup.alignH]};align-items:${ALIGN[setup.alignV]};overflow:hidden\">\n<div data-print-content style=\"width:${tableW * scale}px;height:${tableH * scale}px;flex:none;overflow:hidden\">\n<table style=\"width:${tableW}px;table-layout:fixed;border-collapse:collapse;transform:scale(${scale});transform-origin:0 0;font:12px/${PRINT_ROW_HEIGHT - 2}px system-ui,sans-serif;color:#111\"><colgroup>${cols}</colgroup><tbody>${body}</tbody></table>\n</div></div></section>`;\n}\n\nexport interface PrintDocument {\n /** Every page, in print order. */\n pagesHtml: string[];\n pageWidth: number;\n pageHeight: number;\n /** `@page` size in inches, for the browser's print engine. */\n pageSizeInches: { width: number; height: number };\n}\n\n/** All the printed pages of the chosen sheets under the setup (empty when there is nothing to print). */\nexport function buildPrintDocument(sheets: readonly PrintSheet[], setup: SheetPageSetup): PrintDocument | null {\n const out: string[] = [];\n let geometry: PrintGeometry | null = null;\n for (const sheet of sheets) {\n const plan = planSheetPrint(sheet.rows, setup, { rows: sheet.frozenRows, cols: sheet.frozenCols });\n geometry = plan.geometry;\n plan.pages.forEach((page, i) => {\n out.push(pageHtml(sheet, page, plan.scale, plan.colWidths, plan.geometry, setup, { sheet: sheet.name, at: i + 1, of: plan.pages.length }));\n });\n }\n if (!geometry || out.length === 0) return null;\n return {\n pagesHtml: out,\n pageWidth: geometry.paperWidth,\n pageHeight: geometry.paperHeight,\n pageSizeInches: { width: geometry.paperWidth / PX_PER_INCH, height: geometry.paperHeight / PX_PER_INCH },\n };\n}\n\n/** The whole printable web page: `@page` set to the paper, one section per page. */\nexport function printDocumentHtml(doc: PrintDocument, title: string): string {\n const { width, height } = doc.pageSizeInches;\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(title)}</title>\n<style>@page{size:${width.toFixed(3)}in ${height.toFixed(3)}in;margin:0}html,body{margin:0;padding:0;background:#fff}td{padding:0 6px;overflow:hidden;white-space:nowrap;text-overflow:clip;vertical-align:middle}section:last-child{break-after:auto;page-break-after:auto}</style></head>\n<body data-print-paper=\"${width.toFixed(3)}x${height.toFixed(3)}in\">${doc.pagesHtml.join(\"\\n\")}</body></html>`;\n}\n","/**\n * Outputs of a workbook: CSV/TSV/HTML downloads of the current sheet, and Print / PDF of what its page setup asks for.\n * Both read the same string grid the rest of the workbook code reads\n * (`univerSnapshotToRows`) — one source of what \"the sheet\" contains.\n */\n\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { toDelimitedText } from \"@ai-matrx/alchemy/operate/read\";\nimport { PX_PER_INCH } from \"../core\";\nimport type { SheetPageSetup } from \"./sheet-page-setup\";\nimport { buildPrintDocument, collectPrintSheets, printDocumentHtml } from \"./sheet-print-pages\";\nimport { univerSnapshotToRows, type CellRange } from \"./univer-snapshot-rows\";\n\nexport function rowsToCsv(rows: readonly (readonly string[])[]): string {\n const [header, ...body] = rows;\n if (!header) return \"\";\n return toDelimitedText(header, body, { spreadsheetSafe: false });\n}\n\nexport function downloadSheetAsCsv(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const name = `${options.filename.replace(/\\.csv$/i, \"\")}.csv`;\n // BOM so Excel reads UTF-8.\n const blob = new Blob([\"\", rowsToCsv(grid.rows)], { type: \"text/csv;charset=utf-8\" });\n downloadFile(name, blob, blob.type);\n return true;\n}\n\n/** Tab-separated values of the current sheet (Google's .tsv download). */\nexport function downloadSheetAsTsv(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const [header, ...body] = grid.rows;\n const text = toDelimitedText(header!, body, { format: \"tsv\", spreadsheetSafe: false });\n const blob = new Blob([\"\\uFEFF\", text], { type: \"text/tab-separated-values;charset=utf-8\" });\n downloadFile(`${options.filename.replace(/\\.tsv$/i, \"\")}.tsv`, blob, blob.type);\n return true;\n}\n\n/** The current sheet as a standalone web page (Google's .html download). */\nexport function downloadSheetAsHtml(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const body = grid.rows.map((r) => `<tr>${r.map((c) => `<td>${esc(c)}</td>`).join(\"\")}</tr>`).join(\"\\n\");\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(options.filename)} — ${esc(grid.sheetName)}</title>\n<style>body{font:13px system-ui,sans-serif;margin:16px}table{border-collapse:collapse}td{border:1px solid #c0c0c0;padding:2px 6px;vertical-align:top}</style></head>\n<body><table>\n${body}\n</table></body></html>`;\n const blob = new Blob([html], { type: \"text/html;charset=utf-8\" });\n downloadFile(`${options.filename.replace(/\\.html?$/i, \"\")}.html`, blob, blob.type);\n return true;\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\n/** What a print or PDF needs besides the snapshot: the workbook's page setup and the live selection. */\nexport interface SheetPrintOptions {\n sheetId?: string;\n title: string;\n setup: SheetPageSetup;\n /** The cells selected right now (used when the setup prints \"selected cells\"). */\n selection?: CellRange | null;\n}\n\nfunction printDocumentFor(snapshot: unknown, options: SheetPrintOptions) {\n const sheets = collectPrintSheets(snapshot, options.setup, {\n ...(options.sheetId ? { sheetId: options.sheetId } : {}),\n selection: options.selection ?? null,\n });\n return buildPrintDocument(sheets, options.setup);\n}\n\n/** Opens the browser print sheet for what the workbook's page setup asks to print (choose \"Save as PDF\" there). */\nexport function printSheet(snapshot: unknown, options: SheetPrintOptions): boolean {\n const doc = printDocumentFor(snapshot, options);\n if (!doc) return false;\n const html = printDocumentHtml(doc, options.title);\n const frame = document.createElement(\"iframe\");\n frame.style.cssText = \"position:fixed;right:0;bottom:0;width:0;height:0;border:0\";\n document.body.appendChild(frame);\n const fdoc = frame.contentDocument;\n const win = frame.contentWindow;\n if (!fdoc || !win) {\n frame.remove();\n return false;\n }\n fdoc.open();\n fdoc.write(html);\n fdoc.close();\n win.addEventListener(\"afterprint\", () => frame.remove());\n win.focus();\n win.print();\n return true;\n}\n\n/** The sheet's grid as a markdown table (first row is the header row). */\nexport function rowsToMarkdownTable(rows: readonly (readonly string[])[]): string {\n if (rows.length === 0) return \"\";\n const width = Math.max(...rows.map((r) => r.length));\n const cell = (v: string | undefined) => (v ?? \"\").replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n const line = (r: readonly string[]) =>\n `| ${Array.from({ length: width }, (_, i) => cell(r[i])).join(\" | \")} |`;\n const [head, ...rest] = rows;\n return [line(head!), `| ${Array.from({ length: width }, () => \"---\").join(\" | \")} |`, ...rest.map(line)].join(\"\\n\");\n}\n\n/**\n * Real PDF download of what the workbook's page setup prints: the same pages Print draws, each one\n * captured and laid on a PDF page of the chosen paper size and orientation. Returns false when empty.\n */\nexport async function downloadSheetAsPdf(snapshot: unknown, options: SheetPrintOptions): Promise<boolean> {\n const doc = printDocumentFor(snapshot, options);\n if (!doc) return false;\n const [{ renderElement, pagesToPdf }, { downloadFile: save }] = await Promise.all([\n import(\"@ai-matrx/alchemy/operate/capture\"),\n import(\"@ai-matrx/kit/download\"),\n ]);\n const host = document.createElement(\"div\");\n host.setAttribute(\"aria-hidden\", \"true\");\n host.style.cssText = \"position:fixed;left:-20000px;top:0\";\n host.innerHTML = `<style>td{padding:0 6px;overflow:hidden;white-space:nowrap;vertical-align:middle}</style>${doc.pagesHtml.join(\"\")}`;\n document.body.appendChild(host);\n try {\n const pages = [];\n for (const el of Array.from(host.querySelectorAll<HTMLElement>(\"[data-print-page]\"))) {\n const image = await renderElement(el, { pixelRatio: 2, backgroundColor: \"#ffffff\", cacheBust: true });\n pages.push({ image, imageType: \"JPEG\" as const, quality: 0.92, placement: \"fill\" as const });\n }\n const mm = (px: number) => Math.round(((px / PX_PER_INCH) * 25.4) * 100) / 100;\n const pdf = await pagesToPdf(pages, {\n orientation: doc.pageWidth > doc.pageHeight ? \"landscape\" : \"portrait\",\n unit: \"mm\",\n format: [mm(Math.min(doc.pageWidth, doc.pageHeight)), mm(Math.max(doc.pageWidth, doc.pageHeight))],\n });\n save(`${options.title.replace(/[\\\\/:*?\"<>|]+/g, \" \").trim() || \"workbook\"}.pdf`, pdf, \"application/pdf\");\n } finally {\n host.remove();\n }\n return true;\n}\n","// features/workbooks/workbook-scope-source.ts\n//\n// Live bridge from the mounted `WorkbookEditor` to the `matrx-user/workbooks`\n// surface emitter on `/workbooks/[id]`.\n//\n// Why a module slot rather than props: the page owns the workbook row and\n// mounts `<SurfaceRuntimeProvider>`, but the sheets / snapshot / save status\n// live inside the editor (Univer refs + local state), one level DOWN. Pushing\n// them up as state would re-render the editor on every keystroke; a\n// registered getter is read once, at Run time, when the user actually\n// launches an agent.\n//\n// Exactly one editor is mounted at a time (one workbook per route), so a\n// single slot keyed by workbookId is enough. The getter returns null when the\n// editor has not booted — callers omit the values, they never fake them.\n\nexport interface WorkbookLiveScope {\n sheets: Array<{ id: string; name: string; index: number }>;\n activeSheetId: string | null;\n activeSheetName: string | null;\n snapshot: Record<string, unknown> | null;\n bootState: \"booting\" | \"ready\" | \"load_error\";\n loadError: string | null;\n saveStatus: string;\n collab: {\n enabled: boolean;\n is_host: boolean;\n self_uid: string;\n remote_peers: number;\n };\n}\n\ninterface Registration {\n workbookId: string;\n read: () => WorkbookLiveScope | null;\n}\n\nlet current: Registration | null = null;\n\n/** Called by `WorkbookEditor` while mounted. Returns an unregister. */\nexport function registerWorkbookScopeSource(\n registration: Registration,\n): () => void {\n current = registration;\n return () => {\n if (current === registration) current = null;\n };\n}\n\n/**\n * Read the live editor state for `workbookId`. Returns null when no editor is\n * mounted, when a different workbook is mounted, or when Univer has not\n * booted yet — never a fabricated shape.\n */\nexport function readWorkbookScopeSource(\n workbookId: string,\n): WorkbookLiveScope | null {\n if (!current || current.workbookId !== workbookId) return null;\n return current.read();\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/_work/aidream/aidream/apps/shared/office/dist/sheets.cjs","../src/sheets/univer-snapshot-rows.ts","../src/sheets/snapshot-preview-svg.ts","../src/sheets/snapshot-grid.ts","../src/core/document-page-style.ts","../src/sheets/sheet-page-setup.ts","../src/sheets/sheet-page-setup-service.ts","../src/sheets/sheet-print-pages.ts","../src/sheets/sheet-output.ts","../src/sheets/workbook-scope-source.ts"],"names":["current"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6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;AACU,EAAA;AACX,EAAA;AACA,EAAA;AACH,EAAA;AACT;AAGoC;AACJ,EAAA;AACC,EAAA;AACmB,EAAA;AAErC,EAAA;AACW,EAAA;AACQ,EAAA;AAClC;AAMyC;AACV,EAAA;AACZ,EAAA;AACO,EAAA;AACf,IAAA;AACA,IAAA;AACR,EAAA;AACqB,EAAA;AACJ,EAAA;AACG,EAAA;AACJ,EAAA;AACa,EAAA;AAC1B,EAAA;AACa,IAAA;AACa,IAAA;AACN,MAAA;AACA,MAAA;AACtB,IAAA;AACwC,IAAA;AACX,IAAA;AACV,MAAA;AACX,MAAA;AACmB,MAAA;AAC1B,IAAA;AAC6B,IAAA;AAC9B,EAAA;AACY,IAAA;AACd,EAAA;AACO,EAAA;AACT;AR0rBkC;AACA;AS9yBC;AAGnB;AAGJ,EAAA;AACG,EAAA;AACmB,IAAA;AAChC,EAAA;AACF;AAQE;AAEwB,EAAA;AACJ,EAAA;AACtB;AToyBkC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/_work/aidream/aidream/apps/shared/office/dist/sheets.cjs","sourcesContent":[null,"/**\n * features/workbooks/univer-snapshot-rows.ts\n *\n * Snapshot → rows: read a Univer `IWorkbookData` snapshot back out as a plain\n * string grid. The missing half of the workbook round trip — `export-targets`\n * pushes rows INTO a workbook; this reads the (possibly user-edited) values\n * back OUT so features can offer \"edit in the workbook, then import your\n * changes\". Values only (formulas come back as their cached value); first\n * sheet by `sheetOrder` unless a sheet id is named. A number shown through a date format reads as\n * its ISO date (a spreadsheet keeps dates as day serials). Reusable — do not fork a per-feature\n * snapshot walker. Callers: the workbook's \"Make this sheet a table\" (features/workbooks/table-link).\n */\n\ninterface CellShape {\n v?: unknown;\n s?: unknown;\n}\n\ninterface SheetShape {\n name?: string;\n /** Frozen panes: `xSplit` columns and `ySplit` rows are pinned. */\n freeze?: { xSplit?: number; ySplit?: number } | null;\n /** Univer marks a hidden column/row `hd: 1` (a table link's Record ID column is one). */\n columnData?: Record<string, { hd?: number } | null | undefined>;\n rowData?: Record<string, { hd?: number } | null | undefined>;\n cellData?: Record<string, Record<string, CellShape | null | undefined>>;\n}\n\ninterface SnapshotShape {\n sheetOrder?: string[];\n sheets?: Record<string, SheetShape>;\n styles?: Record<string, { n?: { pattern?: string } | null } | null>;\n}\n\nexport interface SnapshotRows {\n sheetName: string;\n /** Dense rectangular grid, trailing empty rows/columns trimmed. */\n rows: string[][];\n /** Rows pinned at the top of the sheet (Freeze rows), counted in `rows`. */\n frozenRows: number;\n /** Columns pinned at the left of the sheet (Freeze columns), counted in each row. */\n frozenCols: number;\n}\n\n/** A zero-based, inclusive cell range (a selection). */\nexport interface CellRange {\n startRow: number;\n endRow: number;\n startColumn: number;\n endColumn: number;\n}\n\n/** Sheet ids in tab order. */\nexport function univerSheetIds(snapshot: unknown): string[] {\n if (typeof snapshot !== \"object\" || snapshot === null) return [];\n const shape = snapshot as SnapshotShape;\n const sheets = shape.sheets ?? {};\n const ordered = (shape.sheetOrder ?? []).filter((id) => sheets[id]);\n return ordered.length ? ordered : Object.keys(sheets);\n}\n\ntype Styles = SnapshotShape[\"styles\"];\n\n/** The number-format pattern a cell is shown through, if any. */\nfunction patternOf(cell: CellShape | null | undefined, styles: Styles): string | null {\n const s = cell?.s;\n const style = typeof s === \"string\" ? styles?.[s] : s && typeof s === \"object\" ? (s as { n?: { pattern?: string } }) : null;\n const pattern = style?.n?.pattern;\n return typeof pattern === \"string\" ? pattern : null;\n}\n\nconst DAY_MS = 86_400_000;\nconst SERIAL_EPOCH_MS = Date.UTC(1899, 11, 30);\n\nfunction cellText(cell: CellShape | null | undefined, styles?: Styles): string {\n const value = cell?.v;\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"number\") {\n const pattern = patternOf(cell, styles)?.replace(/\"[^\"]*\"/g, \"\").toLowerCase() ?? \"\";\n if (/[dy]/.test(pattern)) {\n const iso = new Date(Math.round(SERIAL_EPOCH_MS + value * DAY_MS)).toISOString();\n return /h/.test(pattern) ? `${iso.slice(0, 10)} ${iso.slice(11, 16)}` : iso.slice(0, 10);\n }\n }\n return String(value);\n}\n\n/**\n * Extract the first worksheet of a Univer workbook snapshot as a string grid.\n * Returns null when the value is not snapshot-shaped or has no sheets.\n * `skipHidden` leaves out hidden columns and rows: every read-only view (a share page, an agent's\n * read) passes it, so the table link's hidden Record ID column never reaches a reader.\n */\nexport function univerSnapshotToRows(snapshot: unknown, options: { sheetId?: string; skipHidden?: boolean; range?: CellRange } = {}): SnapshotRows | null {\n if (typeof snapshot !== \"object\" || snapshot === null) return null;\n const shape = snapshot as SnapshotShape;\n const sheets = shape.sheets ?? {};\n const styles = shape.styles;\n const firstId = options.sheetId\n ? sheets[options.sheetId]\n ? options.sheetId\n : undefined\n : (shape.sheetOrder?.find((id) => sheets[id]) ?? Object.keys(sheets)[0]);\n if (!firstId) return null;\n const sheet = sheets[firstId];\n const cellData = sheet?.cellData ?? {};\n\n let maxRow = -1;\n let maxCol = -1;\n for (const [rowKey, row] of Object.entries(cellData)) {\n const rowIndex = Number(rowKey);\n if (!Number.isInteger(rowIndex) || !row) continue;\n for (const [colKey, cell] of Object.entries(row)) {\n const colIndex = Number(colKey);\n if (!Number.isInteger(colIndex)) continue;\n if (cellText(cell) === \"\") continue;\n if (rowIndex > maxRow) maxRow = rowIndex;\n if (colIndex > maxCol) maxCol = colIndex;\n }\n }\n const range = options.range;\n if (range) {\n // A selection prints exactly the cells chosen, empty ones included.\n maxRow = range.endRow;\n maxCol = range.endColumn;\n }\n if (maxRow < 0 || maxCol < 0) {\n return { sheetName: sheet?.name ?? \"Sheet1\", rows: [], frozenRows: 0, frozenCols: 0 };\n }\n const firstRow = range?.startRow ?? 0;\n const firstCol = range?.startColumn ?? 0;\n\n const hiddenCol = (c: number) => options.skipHidden === true && sheet?.columnData?.[String(c)]?.hd === 1;\n const hiddenRow = (r: number) => options.skipHidden === true && sheet?.rowData?.[String(r)]?.hd === 1;\n const rows: string[][] = [];\n const ySplit = Math.max(0, sheet?.freeze?.ySplit ?? 0);\n const xSplit = Math.max(0, sheet?.freeze?.xSplit ?? 0);\n let frozenRows = 0;\n let frozenCols = 0;\n for (let r = firstRow; r <= maxRow; r += 1) {\n if (hiddenRow(r)) continue;\n if (r < ySplit) frozenRows += 1;\n const row: string[] = [];\n const source = cellData[String(r)] ?? {};\n let colsFrozenHere = 0;\n for (let c = firstCol; c <= maxCol; c += 1) {\n if (hiddenCol(c)) continue;\n if (c < xSplit) colsFrozenHere += 1;\n row.push(cellText(source[String(c)], styles));\n }\n frozenCols = colsFrozenHere;\n rows.push(row);\n }\n return { sheetName: sheet?.name ?? \"Sheet1\", rows, frozenRows, frozenCols };\n}\n","/**\n * snapshot → SVG: a faithful miniature of a Univer workbook's first sheet or a\n * Univer document's first page — the gallery tile Google draws. Pure (no DOM,\n * no Univer runtime), so it runs in the browser (thumbnail capture), in tests\n * and in node. Reads only what a snapshot stores: cell values + styles +\n * column widths + merges + conditional formats + checkboxes for sheets; the\n * dataStream + text runs + paragraph styles + tables for documents.\n */\n\nexport const THUMB_WIDTH = 320;\nexport const THUMB_HEIGHT = 414;\n\ntype Rgb = { rgb?: string | null } | null | undefined;\ntype CellStyle = {\n bg?: Rgb;\n cl?: Rgb;\n bl?: number;\n it?: number;\n fs?: number;\n ht?: number;\n n?: { pattern?: string } | null;\n bd?: Record<string, unknown> | null;\n};\ntype Cell = { v?: unknown; s?: string | CellStyle | null; t?: number; f?: string };\ntype Sheet = {\n id?: string;\n name?: string;\n cellData?: Record<string, Record<string, Cell>>;\n columnData?: Record<string, { w?: number; hd?: number }>;\n rowData?: Record<string, { h?: number; hd?: number }>;\n defaultColumnWidth?: number;\n defaultRowHeight?: number;\n mergeData?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n showGridlines?: number;\n freeze?: { ySplit?: number; xSplit?: number };\n};\nexport type Workbook = {\n sheetOrder?: string[];\n sheets?: Record<string, Sheet>;\n styles?: Record<string, CellStyle | null>;\n resources?: Array<{ name?: string; data?: string }>;\n};\n\nconst esc = (s: string) =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\nfunction color(c: Rgb, fallback: string): string {\n const v = c?.rgb;\n return typeof v === \"string\" && v.length > 0 ? v : fallback;\n}\n\n// ─── number formats ──────────────────────────────────────────────────────────\n\nconst EXCEL_EPOCH = Date.UTC(1899, 11, 30);\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\nexport function formatCellValue(v: unknown, pattern?: string | null): string {\n if (v === null || v === undefined) return \"\";\n if (typeof v === \"boolean\") return v ? \"TRUE\" : \"FALSE\";\n if (typeof v !== \"number\" || !pattern || pattern === \"General\") return String(v);\n const p = pattern.toLowerCase();\n if (/[dy]/.test(p) && !p.includes(\"$\")) {\n const d = new Date(EXCEL_EPOCH + Math.round(v) * 86400000);\n const mm = d.getUTCMonth();\n const dd = d.getUTCDate();\n const yy = d.getUTCFullYear();\n if (p.includes(\"mmm\")) return `${MONTHS[mm]} ${dd}${p.includes(\"y\") ? `, ${yy}` : \"\"}`;\n return p.includes(\"y\") ? `${mm + 1}/${dd}/${yy}` : `${mm + 1}/${dd}`;\n }\n const decimals = (pattern.split(\".\")[1]?.match(/0/g) ?? []).length;\n if (p.includes(\"%\")) return `${(v * 100).toFixed(decimals)}%`;\n const grouped = Math.abs(v).toLocaleString(\"en-US\", {\n minimumFractionDigits: decimals,\n maximumFractionDigits: decimals,\n useGrouping: pattern.includes(\",\"),\n });\n const sign = v < 0 ? \"-\" : \"\";\n return p.includes(\"$\") ? `${sign}$${grouped}` : `${sign}${grouped}`;\n}\n\n// ─── conditional formatting (the rules a preview can evaluate) ───────────────\n\nexport type CfRule = {\n rule?: {\n type?: string;\n subType?: string;\n operator?: string;\n value?: unknown;\n style?: CellStyle;\n };\n ranges?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n};\n\nexport function parseResource<T>(wb: Workbook, name: string): T | null {\n const res = wb.resources?.find((r) => r.name === name);\n if (!res?.data) return null;\n try {\n return JSON.parse(res.data) as T;\n } catch {\n return null;\n }\n}\n\nexport function cfMatch(rule: NonNullable<CfRule[\"rule\"]>, v: unknown): boolean {\n if (rule.type !== \"highlightCell\") return false;\n if (rule.subType === \"number\" && typeof v === \"number\") {\n const x = rule.value;\n const [a = 0, b = 0] = Array.isArray(x) ? (x as number[]) : [Number(x), Number(x)];\n switch (rule.operator) {\n case \"greaterThan\": return v > a;\n case \"greaterThanOrEqual\": return v >= a;\n case \"lessThan\": return v < a;\n case \"lessThanOrEqual\": return v <= a;\n case \"equal\": return v === a;\n case \"notEqual\": return v !== a;\n case \"between\": return v >= a && v <= b;\n default: return false;\n }\n }\n if (rule.subType === \"text\" && v !== undefined && v !== null) {\n const s = String(v).toLowerCase();\n const want = String(rule.value ?? \"\").toLowerCase();\n switch (rule.operator) {\n case \"containsText\": return s.includes(want);\n case \"equal\": return s === want;\n case \"beginsWith\": return s.startsWith(want);\n default: return false;\n }\n }\n return false;\n}\n\n// ─── workbook ────────────────────────────────────────────────────────────────\n\nexport function workbookPreviewSvg(snapshot: unknown): string {\n const wb = (snapshot ?? {}) as Workbook;\n const firstId = wb.sheetOrder?.[0] ?? Object.keys(wb.sheets ?? {})[0];\n const sheet: Sheet = (firstId && wb.sheets?.[firstId]) || {};\n const sheetId = sheet.id ?? firstId ?? \"\";\n const styles = wb.styles ?? {};\n const cfAll = parseResource<Record<string, CfRule[]>>(wb, \"SHEET_CONDITIONAL_FORMATTING_PLUGIN\");\n const cf = (cfAll?.[sheetId] ?? []).filter((r) => r.rule && r.ranges);\n const dvAll = parseResource<Record<string, Array<{ type?: string; ranges?: CfRule[\"ranges\"] }>>>(\n wb,\n \"SHEET_DATA_VALIDATION_PLUGIN\",\n );\n const checkboxRanges = (dvAll?.[sheetId] ?? []).filter((d) => d.type === \"checkbox\").flatMap((d) => d.ranges ?? []);\n const inRanges = (rs: CfRule[\"ranges\"], r: number, c: number) =>\n (rs ?? []).some((x) => r >= x.startRow && r <= x.endRow && c >= x.startColumn && c <= x.endColumn);\n\n const dcw = sheet.defaultColumnWidth ?? 88;\n const drh = sheet.defaultRowHeight ?? 24;\n const colW = (c: number) => (sheet.columnData?.[c]?.hd ? 0 : sheet.columnData?.[c]?.w ?? dcw);\n const rowH = (r: number) => (sheet.rowData?.[r]?.hd ? 0 : sheet.rowData?.[r]?.h ?? drh);\n\n // Show the used width (at least ~5 default columns), scaled to the tile.\n let maxCol = 0;\n for (const row of Object.values(sheet.cellData ?? {})) {\n for (const c of Object.keys(row ?? {})) maxCol = Math.max(maxCol, Number(c));\n }\n let used = 0;\n for (let c = 0; c <= maxCol; c++) used += colW(c);\n // Google's tiles show the top-left of the sheet at a readable size, not the whole width.\n const span = Math.min(Math.max(used + 12, dcw * 5), 640);\n const scale = THUMB_WIDTH / span;\n\n const out: string[] = [];\n out.push(`<rect width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" fill=\"#ffffff\"/>`);\n const gridOn = sheet.showGridlines !== 0;\n const merges = sheet.mergeData ?? [];\n const covered = new Set<string>();\n for (const m of merges) {\n for (let r = m.startRow; r <= m.endRow; r++)\n for (let c = m.startColumn; c <= m.endColumn; c++)\n if (r !== m.startRow || c !== m.startColumn) covered.add(`${r}:${c}`);\n }\n const texts: string[] = [];\n let y = 0;\n for (let r = 0; y * scale < THUMB_HEIGHT && r < 400; r++) {\n const h = rowH(r);\n let x = 0;\n for (let c = 0; x * scale < THUMB_WIDTH && c < 60; c++) {\n const w = colW(c);\n if (w === 0 || h === 0 || covered.has(`${r}:${c}`)) {\n x += w;\n continue;\n }\n const m = merges.find((mm) => mm.startRow === r && mm.startColumn === c);\n let cw = w;\n let ch = h;\n if (m) {\n cw = 0;\n for (let k = m.startColumn; k <= m.endColumn; k++) cw += colW(k);\n ch = 0;\n for (let k = m.startRow; k <= m.endRow; k++) ch += rowH(k);\n }\n const cell = sheet.cellData?.[r]?.[c];\n const base: CellStyle =\n (typeof cell?.s === \"string\" ? styles[cell.s] : (cell?.s as CellStyle | null)) ?? {};\n let st: CellStyle = base;\n for (const rule of cf) {\n if (inRanges(rule.ranges, r, c) && rule.rule && cfMatch(rule.rule, cell?.v)) {\n st = { ...st, ...rule.rule.style };\n break;\n }\n }\n const X = x * scale;\n const Y = y * scale;\n const W = cw * scale;\n const H = ch * scale;\n const bg = st.bg?.rgb;\n if (bg) out.push(`<rect x=\"${X.toFixed(1)}\" y=\"${Y.toFixed(1)}\" width=\"${W.toFixed(1)}\" height=\"${H.toFixed(1)}\" fill=\"${esc(bg)}\"/>`);\n if (gridOn) out.push(`<rect x=\"${X.toFixed(1)}\" y=\"${Y.toFixed(1)}\" width=\"${W.toFixed(1)}\" height=\"${H.toFixed(1)}\" fill=\"none\" stroke=\"#e2e3e3\" stroke-width=\"0.5\"/>`);\n const fs = Math.max((st.fs ?? 10) * 1.333 * scale, 3);\n const midY = Y + H / 2 + fs * 0.35;\n if (inRanges(checkboxRanges, r, c) && r > 0 && (cell?.v === true || cell?.v === false || cell?.v === 1 || cell?.v === 0 || cell?.v === \"TRUE\" || cell?.v === \"FALSE\")) {\n const box = Math.min(H * 0.55, 9);\n const bx = X + W / 2 - box / 2;\n const by = Y + H / 2 - box / 2;\n const on = cell?.v === true || cell?.v === 1 || cell?.v === \"TRUE\";\n out.push(`<rect x=\"${bx.toFixed(1)}\" y=\"${by.toFixed(1)}\" width=\"${box.toFixed(1)}\" height=\"${box.toFixed(1)}\" rx=\"1\" fill=\"${on ? \"#1a73e8\" : \"#ffffff\"}\" stroke=\"${on ? \"#1a73e8\" : \"#5f6368\"}\" stroke-width=\"0.7\"/>`);\n if (on) out.push(`<path d=\"M${(bx + box * 0.2).toFixed(1)} ${(by + box * 0.5).toFixed(1)} l${(box * 0.25).toFixed(1)} ${(box * 0.25).toFixed(1)} l${(box * 0.4).toFixed(1)} ${(-box * 0.45).toFixed(1)}\" stroke=\"#fff\" stroke-width=\"0.9\" fill=\"none\"/>`);\n } else if (cell && cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n const text = formatCellValue(cell.v, st.n?.pattern);\n const numeric = typeof cell.v === \"number\";\n const ht = st.ht ?? (numeric ? 3 : 1);\n const anchor = ht === 2 ? \"middle\" : ht === 3 ? \"end\" : \"start\";\n const tx = ht === 2 ? X + W / 2 : ht === 3 ? X + W - 2 * scale * 2 : X + 3 * scale;\n const maxChars = Math.max(Math.floor((m ? W : W * (ht === 1 && !numeric ? 3 : 1)) / (fs * 0.55)), 1);\n const shown = text.length > maxChars ? text.slice(0, maxChars) : text;\n texts.push(\n `<text x=\"${tx.toFixed(1)}\" y=\"${midY.toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" text-anchor=\"${anchor}\" fill=\"${esc(color(st.cl, \"#202124\"))}\"${st.bl ? ' font-weight=\"700\"' : \"\"}${st.it ? ' font-style=\"italic\"' : \"\"}>${esc(shown)}</text>`,\n );\n }\n x += w;\n }\n y += h;\n }\n return wrapSvg([...out, ...texts].join(\"\"));\n}\n\n// ─── document ────────────────────────────────────────────────────────────────\n\ntype TextStyle = { fs?: number; bl?: number; it?: number; cl?: Rgb; ff?: string; bg?: Rgb };\ntype DocData = {\n body?: {\n dataStream?: string;\n paragraphs?: Array<{ startIndex: number; paragraphStyle?: { horizontalAlign?: number; spaceAbove?: { v?: number }; spaceBelow?: { v?: number } } }>;\n textRuns?: Array<{ st: number; ed: number; ts?: TextStyle }>;\n tables?: Array<{ startIndex: number; endIndex: number; tableId: string }>;\n };\n documentStyle?: {\n pageSize?: { width?: number; height?: number };\n marginTop?: number;\n marginLeft?: number;\n marginRight?: number;\n };\n};\n\nconst CONTROL = /[\\x1A\\x1B\\x1C\\x1D\\x0E\\x0F\\x1F\\x1E\\b]/g;\n\nexport function documentPreviewSvg(snapshot: unknown): string {\n const doc = (snapshot ?? {}) as DocData;\n const stream = doc.body?.dataStream ?? \"\";\n const pageW = doc.documentStyle?.pageSize?.width ?? 595;\n const scale = THUMB_WIDTH / pageW;\n const ml = (doc.documentStyle?.marginLeft ?? 72) * scale;\n const mr = (doc.documentStyle?.marginRight ?? 72) * scale;\n const mt = (doc.documentStyle?.marginTop ?? 72) * scale;\n const contentW = THUMB_WIDTH - ml - mr;\n const runs = [...(doc.body?.textRuns ?? [])].sort((a, b) => a.st - b.st);\n const tables = doc.body?.tables ?? [];\n const styleAt = (i: number): TextStyle => runs.find((r) => i >= r.st && i < r.ed)?.ts ?? {};\n /** The style most of a paragraph's characters carry (a bold lead-in does not make the line bold). */\n const dominantStyle = (from: number, to: number): TextStyle => {\n const counts = new Map<string, { n: number; ts: TextStyle }>();\n for (let i = from; i < to; i++) {\n if (/\\s/.test(stream[i] ?? \"\")) continue;\n const ts = styleAt(i);\n const k = JSON.stringify(ts);\n const e = counts.get(k) ?? { n: 0, ts };\n e.n++;\n counts.set(k, e);\n }\n let best: { n: number; ts: TextStyle } | null = null;\n for (const e of counts.values()) if (!best || e.n > best.n) best = e;\n return best?.ts ?? {};\n };\n const out: string[] = [`<rect width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" fill=\"#ffffff\"/>`];\n\n let y = mt;\n let start = 0;\n const paragraphs = doc.body?.paragraphs ?? [];\n for (let p = 0; p < paragraphs.length && y < THUMB_HEIGHT; p++) {\n const para = paragraphs[p];\n if (!para) break;\n const end = para.startIndex;\n const table = tables.find((t) => start >= t.startIndex && start < t.endIndex);\n if (table) {\n // Draw the whole table once: rows split on the row token, cells on the cell token.\n const raw = stream.slice(table.startIndex, table.endIndex);\n const rows = raw.split(\"\\x1B\").slice(1).map((row) =>\n row.split(\"\\x1C\").slice(1).map((cell) => cell.replace(/[\\r\\n]/g, \" \").replace(CONTROL, \"\").trim()),\n );\n const cols = Math.max(1, ...rows.map((r) => r.length));\n const cw = contentW / cols;\n // Bold header row when the first cell's text is bold.\n const headerBold = styleAt(table.startIndex + 4).bl === 1;\n for (let r = 0; r < rows.length && y < THUMB_HEIGHT; r++) {\n const rh = 16 * scale * 1.2 + 6 * scale;\n for (let c = 0; c < cols; c++) {\n const cx = ml + c * cw;\n out.push(`<rect x=\"${cx.toFixed(1)}\" y=\"${y.toFixed(1)}\" width=\"${cw.toFixed(1)}\" height=\"${rh.toFixed(1)}\" fill=\"${r === 0 && headerBold ? \"#f1f3f4\" : \"none\"}\" stroke=\"#9aa0a6\" stroke-width=\"0.4\"/>`);\n const fs = 11 * 1.333 * scale;\n const maxChars = Math.max(Math.floor((cw - 6 * scale) / (fs * 0.5)), 1);\n const t = rows[r]?.[c] ?? \"\";\n out.push(`<text x=\"${(cx + 4 * scale).toFixed(1)}\" y=\"${(y + rh / 2 + fs * 0.35).toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" fill=\"#202124\"${r === 0 && headerBold ? ' font-weight=\"700\"' : \"\"}>${esc(t.slice(0, maxChars))}</text>`);\n }\n y += rh;\n }\n // Skip every paragraph inside the table.\n while (p + 1 < paragraphs.length && (paragraphs[p + 1]?.startIndex ?? Infinity) < table.endIndex) p++;\n start = table.endIndex;\n y += 6 * scale;\n continue;\n }\n const text = stream.slice(start, end).replace(CONTROL, \"\");\n const st = dominantStyle(start, end);\n const ps = para.paragraphStyle ?? {};\n const fsPt = st.fs ?? 11;\n const fs = fsPt * 1.333 * scale;\n const lineH = fs * 1.3;\n y += (ps.spaceAbove?.v ?? (fsPt > 13 ? 8 : 0)) * scale;\n const align = ps.horizontalAlign ?? 1;\n const anchor = align === 2 ? \"middle\" : align === 3 ? \"end\" : \"start\";\n const tx = align === 2 ? ml + contentW / 2 : align === 3 ? ml + contentW : ml;\n // Paragraph shading (a filled band) when the run carries a highlight.\n if (!text.trim()) {\n y += lineH * 0.8;\n } else {\n const maxChars = Math.max(Math.floor(contentW / (fs * (st.bl ? 0.56 : 0.5))), 4);\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let line = \"\";\n for (const w of words) {\n if ((line + \" \" + w).trim().length > maxChars && line) {\n lines.push(line);\n line = w;\n } else line = (line + \" \" + w).trim();\n }\n if (line) lines.push(line);\n for (const l of lines) {\n if (y > THUMB_HEIGHT) break;\n y += lineH;\n if (st.bg?.rgb) out.push(`<rect x=\"${ml.toFixed(1)}\" y=\"${(y - fs).toFixed(1)}\" width=\"${contentW.toFixed(1)}\" height=\"${lineH.toFixed(1)}\" fill=\"${esc(st.bg.rgb)}\"/>`);\n out.push(`<text x=\"${tx.toFixed(1)}\" y=\"${y.toFixed(1)}\" font-size=\"${fs.toFixed(1)}\" text-anchor=\"${anchor}\" fill=\"${esc(color(st.cl, \"#202124\"))}\"${st.bl ? ' font-weight=\"700\"' : \"\"}${st.it ? ' font-style=\"italic\"' : \"\"}${st.ff && /serif|georgia|times|garamond/i.test(st.ff) && !/sans/i.test(st.ff) ? ' font-family=\"Georgia, serif\"' : \"\"}>${esc(l)}</text>`);\n }\n }\n y += (ps.spaceBelow?.v ?? 4) * scale;\n start = end + 1;\n }\n return wrapSvg(out.join(\"\"));\n}\n\nfunction wrapSvg(body: string): string {\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${THUMB_WIDTH}\" height=\"${THUMB_HEIGHT}\" viewBox=\"0 0 ${THUMB_WIDTH} ${THUMB_HEIGHT}\" font-family=\"Arial, Helvetica, sans-serif\">${body}</svg>`;\n}\n\nexport function snapshotPreviewSvg(kind: \"workbook\" | \"document\", snapshot: unknown): string {\n return kind === \"workbook\" ? workbookPreviewSvg(snapshot) : documentPreviewSvg(snapshot);\n}\n","/**\n * features/workbooks/snapshot-grid.ts\n *\n * Snapshot → a formatted, read-only grid model: what a spreadsheet VIEW needs and the plain-string\n * `univer-snapshot-rows` does not carry — number/currency/date formats applied, checkbox cells\n * (data-validation ranges of type checkbox), alignment, bold/italic, fill and text colour, column\n * widths, merges, frozen rows/columns, hidden rows/columns and sheets. Pure (no DOM, no Univer\n * runtime): the signed-out share page draws it. The number formatter is the thumbnail's\n * (`formatCellValue`) so a tile, a share link and the editor read the same.\n */\n\nimport {\n cfMatch,\n formatCellValue,\n parseResource,\n type CfRule,\n type Workbook,\n} from \"./snapshot-preview-svg\";\n\ntype Rgb = { rgb?: string | null } | null | undefined;\ninterface Style {\n bg?: Rgb;\n cl?: Rgb;\n bl?: number;\n it?: number;\n fs?: number;\n ht?: number;\n tb?: number;\n n?: { pattern?: string } | null;\n}\ninterface Cell {\n v?: unknown;\n s?: string | Style | null;\n}\ninterface Sheet {\n id?: string;\n name?: string;\n hidden?: number;\n cellData?: Record<string, Record<string, Cell | null | undefined>>;\n columnData?: Record<string, { w?: number; hd?: number } | null | undefined>;\n rowData?: Record<string, { h?: number; hd?: number } | null | undefined>;\n defaultColumnWidth?: number;\n defaultRowHeight?: number;\n mergeData?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;\n showGridlines?: number;\n freeze?: { xSplit?: number; ySplit?: number };\n}\n\nexport interface GridCell {\n text: string;\n /** A checkbox cell (a data-validation checkbox range): `checked` says its state. */\n checkbox?: { checked: boolean } | undefined;\n align: \"left\" | \"center\" | \"right\";\n bold: boolean;\n italic: boolean;\n /** Font size in px (the snapshot stores points). */\n fontPx: number;\n bg?: string | undefined;\n color?: string | undefined;\n wrap: boolean;\n rowSpan: number;\n colSpan: number;\n /** Covered by a merge that starts elsewhere: draw nothing. */\n covered: boolean;\n}\n\nexport interface GridSheet {\n id: string;\n name: string;\n /** Visible column indexes (hidden columns left out) with their pixel widths. */\n columns: Array<{ index: number; width: number }>;\n rows: Array<{ index: number; height: number; cells: GridCell[] }>;\n /** How many leading VISIBLE rows / columns stay put while scrolling. */\n frozenRows: number;\n frozenColumns: number;\n gridlines: boolean;\n /** Rows beyond the cap were left out. */\n truncatedFrom: number | null;\n}\n\nexport const GRID_MAX_ROWS = 500;\nexport const GRID_MAX_COLUMNS = 60;\n\nconst PT_TO_PX = 1.333;\nconst isCheckboxValue = (v: unknown) => v === true || v === false || v === 1 || v === 0 || v === \"TRUE\" || v === \"FALSE\";\nconst isOn = (v: unknown) => v === true || v === 1 || v === \"TRUE\";\n\nfunction hasValue(cell: Cell | null | undefined): boolean {\n const v = cell?.v;\n return v !== undefined && v !== null && v !== \"\";\n}\n\n/** Every visible sheet that has something in it, in tab order. Empty and hidden sheets are left out. */\nexport function snapshotToGridSheets(snapshot: unknown): GridSheet[] {\n if (typeof snapshot !== \"object\" || snapshot === null) return [];\n const wb = snapshot as Workbook;\n const sheets = wb.sheets ?? {};\n const order = (wb.sheetOrder ?? []).filter((id) => sheets[id]);\n const ids = order.length > 0 ? order : Object.keys(sheets);\n const out: GridSheet[] = [];\n for (const id of ids) {\n const grid = sheetToGrid(wb, id, sheets[id] as Sheet);\n if (grid) out.push(grid);\n }\n return out;\n}\n\nfunction sheetToGrid(wb: Workbook, id: string, sheet: Sheet): GridSheet | null {\n if (sheet.hidden === 1) return null;\n const cellData = sheet.cellData ?? {};\n let maxRow = -1;\n let maxCol = -1;\n for (const [rk, row] of Object.entries(cellData)) {\n const r = Number(rk);\n if (!Number.isInteger(r) || !row) continue;\n for (const [ck, cell] of Object.entries(row)) {\n const c = Number(ck);\n if (!Number.isInteger(c) || !hasValue(cell)) continue;\n if (r > maxRow) maxRow = r;\n if (c > maxCol) maxCol = c;\n }\n }\n if (maxRow < 0 || maxCol < 0) return null;\n\n const styles = wb.styles ?? {};\n const sheetId = sheet.id ?? id;\n const cfAll = parseResource<Record<string, CfRule[]>>(wb, \"SHEET_CONDITIONAL_FORMATTING_PLUGIN\");\n const cf = (cfAll?.[sheetId] ?? []).filter((r) => r.rule && r.ranges);\n const dvAll = parseResource<Record<string, Array<{ type?: string; ranges?: CfRule[\"ranges\"] }>>>(\n wb,\n \"SHEET_DATA_VALIDATION_PLUGIN\",\n );\n const checkboxRanges = (dvAll?.[sheetId] ?? []).filter((d) => d.type === \"checkbox\").flatMap((d) => d.ranges ?? []);\n const inRanges = (rs: CfRule[\"ranges\"], r: number, c: number) =>\n (rs ?? []).some((x) => r >= x.startRow && r <= x.endRow && c >= x.startColumn && c <= x.endColumn);\n\n const dcw = sheet.defaultColumnWidth ?? 88;\n const drh = sheet.defaultRowHeight ?? 24;\n const lastCol = Math.min(maxCol, GRID_MAX_COLUMNS - 1);\n const columns: GridSheet[\"columns\"] = [];\n for (let c = 0; c <= lastCol; c += 1) {\n const col = sheet.columnData?.[String(c)];\n if (col?.hd === 1) continue;\n columns.push({ index: c, width: col?.w ?? dcw });\n }\n\n const merges = sheet.mergeData ?? [];\n const covered = new Set<string>();\n for (const m of merges) {\n for (let r = m.startRow; r <= m.endRow; r += 1)\n for (let c = m.startColumn; c <= m.endColumn; c += 1) if (r !== m.startRow || c !== m.startColumn) covered.add(`${r}:${c}`);\n }\n\n const rows: GridSheet[\"rows\"] = [];\n const lastRow = Math.min(maxRow, GRID_MAX_ROWS - 1);\n for (let r = 0; r <= lastRow; r += 1) {\n const rd = sheet.rowData?.[String(r)];\n if (rd?.hd === 1) continue;\n const source = cellData[String(r)] ?? {};\n const cells: GridCell[] = columns.map(({ index: c }) => {\n const cell = source[String(c)] ?? undefined;\n const base: Style = (typeof cell?.s === \"string\" ? (styles[cell.s] as Style | null | undefined) : (cell?.s as Style | null | undefined)) ?? {};\n let st: Style = base;\n for (const rule of cf) {\n if (inRanges(rule.ranges, r, c) && rule.rule && cfMatch(rule.rule, cell?.v)) {\n st = { ...st, ...(rule.rule.style as Style | undefined) };\n break;\n }\n }\n const m = merges.find((mm) => mm.startRow === r && mm.startColumn === c);\n const v = cell?.v;\n const box = hasValue(cell) && inRanges(checkboxRanges, r, c) && isCheckboxValue(v);\n const numeric = typeof v === \"number\";\n const ht = st.ht ?? 0;\n return {\n text: box ? \"\" : hasValue(cell) ? formatCellValue(v, st.n?.pattern) : \"\",\n checkbox: box ? { checked: isOn(v) } : undefined,\n align: box || ht === 2 ? \"center\" : ht === 3 || (ht === 0 && numeric) ? \"right\" : \"left\",\n bold: st.bl === 1,\n italic: st.it === 1,\n fontPx: Math.round((st.fs ?? 10) * PT_TO_PX),\n bg: st.bg?.rgb ?? undefined,\n color: st.cl?.rgb ?? undefined,\n wrap: st.tb === 3,\n rowSpan: m ? m.endRow - m.startRow + 1 : 1,\n colSpan: m ? m.endColumn - m.startColumn + 1 : 1,\n covered: covered.has(`${r}:${c}`),\n };\n });\n rows.push({ index: r, height: rd?.h ?? drh, cells });\n }\n\n const ySplit = sheet.freeze?.ySplit ?? 0;\n const xSplit = sheet.freeze?.xSplit ?? 0;\n return {\n id: sheetId,\n name: sheet.name ?? \"Sheet1\",\n columns,\n rows,\n frozenRows: Math.min(rows.filter((r) => r.index < ySplit).length, rows.length),\n frozenColumns: Math.min(columns.filter((c) => c.index < xSplit).length, columns.length),\n gridlines: sheet.showGridlines !== 0,\n truncatedFrom: maxRow > lastRow ? maxRow + 1 : null,\n };\n}\n","/**\n * The ONE page geometry every Matrx cloud document is laid out with.\n *\n * Univer lays a document out inside `documentStyle.pageSize`. With no pageSize\n * the docs renderer has no page box at all: text never wraps (it runs off the\n * right edge) and the vertical extent is unbounded, so the docs viewport\n * reports nothing to scroll — the wheel is swallowed and the page sits frozen\n * at the top. Every writer of a Univer snapshot MUST stamp this style.\n *\n * Consumers: `DocumentEditor` (new empty doc), `markdown-to-univer-doc`\n * (markdown import), and `sanitizeUniverDocSnapshot` (recovery for snapshots\n * that reached storage without it — notably `origin='agent'` writes).\n */\nimport type { DocumentFlavor, IDocumentData, PageOrientType } from \"@univerjs/core\";\n\n// Univer's enum values, written out: this file is read by tests and the markdown importer, which must not\n// pull Univer's runtime in just for four numbers (guarded by the page-style test).\nconst TRADITIONAL = 1 as DocumentFlavor;\nconst MODERN = 2 as DocumentFlavor;\nconst PORTRAIT = 0 as PageOrientType;\nconst LANDSCAPE = 1 as PageOrientType;\n\ntype DocumentStyle = NonNullable<IDocumentData[\"documentStyle\"]>;\n\n/** Univer lays documents out in 96-dpi CSS pixels: one inch is 96 units. */\nexport const PX_PER_INCH = 96;\n\n/** Paper sizes the Page setup dialog offers, in 96-dpi pixels, portrait (width x height). */\nexport const PAPER_SIZES = {\n Letter: { width: 816, height: 1056, label: \"Letter (8.5 x 11 in)\" },\n Legal: { width: 816, height: 1344, label: \"Legal (8.5 x 14 in)\" },\n Tabloid: { width: 1056, height: 1632, label: \"Tabloid (11 x 17 in)\" },\n Executive: { width: 696, height: 1008, label: \"Executive (7.25 x 10.5 in)\" },\n Statement: { width: 528, height: 816, label: \"Statement (5.5 x 8.5 in)\" },\n A3: { width: 1123, height: 1587, label: \"A3 (11.69 x 16.54 in)\" },\n A4: { width: 794, height: 1124, label: \"A4 (8.27 x 11.69 in)\" },\n A5: { width: 559, height: 794, label: \"A5 (5.83 x 8.27 in)\" },\n} as const;\nexport type PaperSizeName = keyof typeof PAPER_SIZES;\n\n/** A real page, like Google Docs: Letter, one-inch margins (624px of text), paginated. */\nexport const DEFAULT_DOCUMENT_PAGE_STYLE: DocumentStyle = {\n pageSize: { width: 816, height: 1056 },\n documentFlavor: TRADITIONAL,\n pageOrient: PORTRAIT,\n marginTop: PX_PER_INCH,\n marginBottom: PX_PER_INCH,\n marginLeft: PX_PER_INCH,\n marginRight: PX_PER_INCH,\n // Univer applies no paragraph spacing to a paginated page by itself; without this every paragraph\n // runs into the next (Google Docs' own default: 1.15 lines, 10px after).\n defaultParagraphStyle: { spaceAbove: { v: 0 }, spaceBelow: { v: 10 }, lineSpacing: 1.15 },\n};\n\n/** Fresh copy — Univer mutates the style it is handed. */\nexport function defaultDocumentPageStyle(): DocumentStyle {\n return {\n ...DEFAULT_DOCUMENT_PAGE_STYLE,\n pageSize: { ...DEFAULT_DOCUMENT_PAGE_STYLE.pageSize! },\n defaultParagraphStyle: { ...DEFAULT_DOCUMENT_PAGE_STYLE.defaultParagraphStyle! },\n };\n}\n\n/**\n * The squeezed geometry every document was stamped with until 2026-10-15: A4 at 72 dpi (595 x 842)\n * with 90/72 margins, in Univer's pageless flavour, so the text column was ~415px with no paper.\n * Pageless was never offered then, so this exact shape is always the old default, never a choice.\n */\nexport function isLegacySqueezedPageStyle(style: DocumentStyle | undefined): boolean {\n const size = style?.pageSize;\n return (\n !!size &&\n size.width === 595 &&\n size.height === 842 &&\n style?.marginLeft === 90 &&\n style?.marginRight === 90 &&\n style?.marginTop === 72 &&\n style?.marginBottom === 72\n );\n}\n\n/** What the Page setup dialog edits. Margins are in inches, like Google's. */\nexport interface PageSetupValues {\n pageless: boolean;\n orientation: \"portrait\" | \"landscape\";\n paper: PaperSizeName;\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Paper colour, hex. Always a light colour so the black ink stays readable. */\n pageColor: string;\n}\n\nexport const PAGE_COLORS = [\"#ffffff\", \"#fff8e7\", \"#f3f3f3\", \"#e8f0fe\", \"#e6f4ea\", \"#fef7e0\"] as const;\nexport const DEFAULT_PAGE_COLOR = PAGE_COLORS[0];\n/** Key on `documentStyle` carrying the paper colour (Univer paints it from the host's surface theme). */\nexport const PAGE_COLOR_KEY = \"matrxPageColor\";\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\n/** The dialog's values, read from a document's style (missing parts fall back to the default page). */\nexport function pageSetupFromStyle(style: DocumentStyle | undefined): PageSetupValues {\n const landscape = style?.pageOrient === LANDSCAPE;\n const w = style?.pageSize?.width ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.width!;\n const h = style?.pageSize?.height ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.height!;\n const [pw, ph] = landscape ? [h, w] : [w, h];\n const paper =\n (Object.keys(PAPER_SIZES) as PaperSizeName[]).find(\n (k) => Math.abs(PAPER_SIZES[k].width - pw) <= 1 && Math.abs(PAPER_SIZES[k].height - ph) <= 1,\n ) ?? \"Letter\";\n const inch = (v: number | undefined) => round2((v ?? PX_PER_INCH) / PX_PER_INCH);\n const color = (style as Record<string, unknown> | undefined)?.[PAGE_COLOR_KEY];\n return {\n pageless: style?.documentFlavor === MODERN,\n orientation: landscape ? \"landscape\" : \"portrait\",\n paper,\n marginTop: inch(style?.marginTop),\n marginBottom: inch(style?.marginBottom),\n marginLeft: inch(style?.marginLeft),\n marginRight: inch(style?.marginRight),\n pageColor: typeof color === \"string\" && color ? color : DEFAULT_PAGE_COLOR,\n };\n}\n\n/** Params for Univer's `docs.command.page-setup` (pageSize is the as-printed size: swapped when landscape). */\nexport function pageSetupCommandParams(v: PageSetupValues) {\n const base = PAPER_SIZES[v.paper];\n const landscape = v.orientation === \"landscape\";\n return {\n documentFlavor: v.pageless ? MODERN : TRADITIONAL,\n pageOrient: landscape ? LANDSCAPE : PORTRAIT,\n pageSize: landscape ? { width: base.height, height: base.width } : { width: base.width, height: base.height },\n marginTop: Math.round(v.marginTop * PX_PER_INCH),\n marginBottom: Math.round(v.marginBottom * PX_PER_INCH),\n marginLeft: Math.round(v.marginLeft * PX_PER_INCH),\n marginRight: Math.round(v.marginRight * PX_PER_INCH),\n };\n}\n","/**\n * A workbook's print settings — Google Sheets' File → Page setup / Print, as pure data and pure\n * pagination (no React, no IO). They live on the workbook (`udt_workbooks.metadata.page_setup`),\n * so Print, Download as PDF and the Page setup dialog all read the same values.\n *\n * Geometry is in 96-dpi CSS pixels, like the rest of the document stack (`PX_PER_INCH`).\n */\n\nimport { PAPER_SIZES, PX_PER_INCH, type PaperSizeName } from \"../core\";\n\nexport const SHEET_SCALES = [\"normal\", \"width\", \"height\", \"page\"] as const;\nexport type SheetScale = (typeof SHEET_SCALES)[number];\nexport const SHEET_MARGIN_PRESETS = [\"normal\", \"narrow\", \"wide\", \"custom\"] as const;\nexport type SheetMarginPreset = (typeof SHEET_MARGIN_PRESETS)[number];\nexport const SHEET_PRINT_SCOPES = [\"sheet\", \"workbook\", \"selection\"] as const;\nexport type SheetPrintScope = (typeof SHEET_PRINT_SCOPES)[number];\nexport type SheetPageOrder = \"down-over\" | \"over-down\";\nexport type SheetAlignH = \"left\" | \"center\" | \"right\";\nexport type SheetAlignV = \"top\" | \"middle\" | \"bottom\";\n\nexport interface SheetPageSetup {\n paper: PaperSizeName;\n orientation: \"portrait\" | \"landscape\";\n scale: SheetScale;\n margins: SheetMarginPreset;\n /** Inches; read only when `margins` is \"custom\". */\n customMargins: { top: number; bottom: number; left: number; right: number };\n scope: SheetPrintScope;\n gridlines: boolean;\n repeatFrozenRows: boolean;\n repeatFrozenColumns: boolean;\n pageOrder: SheetPageOrder;\n alignH: SheetAlignH;\n alignV: SheetAlignV;\n}\n\n/** Google Sheets' defaults: Letter, portrait, 100%, normal margins, current sheet, gridlines on. */\nexport const DEFAULT_SHEET_PAGE_SETUP: SheetPageSetup = {\n paper: \"Letter\",\n orientation: \"portrait\",\n scale: \"normal\",\n margins: \"normal\",\n customMargins: { top: 0.75, bottom: 0.75, left: 0.7, right: 0.7 },\n scope: \"sheet\",\n gridlines: true,\n repeatFrozenRows: false,\n repeatFrozenColumns: false,\n pageOrder: \"down-over\",\n alignH: \"left\",\n alignV: \"top\",\n};\n\n/** Google's three preset margins, in inches. */\nexport const MARGIN_PRESET_INCHES: Record<Exclude<SheetMarginPreset, \"custom\">, { top: number; bottom: number; left: number; right: number }> = {\n normal: { top: 0.75, bottom: 0.75, left: 0.7, right: 0.7 },\n narrow: { top: 0.25, bottom: 0.25, left: 0.25, right: 0.25 },\n wide: { top: 1, bottom: 1, left: 1, right: 1 },\n};\n\nconst isPaper = (v: unknown): v is PaperSizeName => typeof v === \"string\" && v in PAPER_SIZES;\nconst oneOf = <T extends string>(list: readonly T[], v: unknown, fallback: T): T => (typeof v === \"string\" && (list as readonly string[]).includes(v) ? (v as T) : fallback);\nconst inches = (v: unknown, fallback: number) => (typeof v === \"number\" && Number.isFinite(v) && v >= 0 && v <= 5 ? v : fallback);\n\n/** Any stored value → a complete, valid setup. Unknown or broken parts fall back to the default. */\nexport function normalizeSheetPageSetup(raw: unknown): SheetPageSetup {\n const r = (raw && typeof raw === \"object\" ? raw : {}) as Record<string, unknown>;\n const m = (r.customMargins && typeof r.customMargins === \"object\" ? r.customMargins : {}) as Record<string, unknown>;\n const d = DEFAULT_SHEET_PAGE_SETUP;\n return {\n paper: isPaper(r.paper) ? r.paper : d.paper,\n orientation: r.orientation === \"landscape\" ? \"landscape\" : \"portrait\",\n scale: oneOf(SHEET_SCALES, r.scale, d.scale),\n margins: oneOf(SHEET_MARGIN_PRESETS, r.margins, d.margins),\n customMargins: {\n top: inches(m.top, d.customMargins.top),\n bottom: inches(m.bottom, d.customMargins.bottom),\n left: inches(m.left, d.customMargins.left),\n right: inches(m.right, d.customMargins.right),\n },\n scope: oneOf(SHEET_PRINT_SCOPES, r.scope, d.scope),\n gridlines: typeof r.gridlines === \"boolean\" ? r.gridlines : d.gridlines,\n repeatFrozenRows: r.repeatFrozenRows === true,\n repeatFrozenColumns: r.repeatFrozenColumns === true,\n pageOrder: r.pageOrder === \"over-down\" ? \"over-down\" : \"down-over\",\n alignH: oneOf([\"left\", \"center\", \"right\"] as const, r.alignH, d.alignH),\n alignV: oneOf([\"top\", \"middle\", \"bottom\"] as const, r.alignV, d.alignV),\n };\n}\n\n/** The setup stored on a workbook's metadata (`metadata.page_setup`), complete and valid. */\nexport function pageSetupFromMetadata(metadata: unknown): SheetPageSetup {\n return normalizeSheetPageSetup((metadata as { page_setup?: unknown } | null)?.page_setup);\n}\n\nexport interface PrintGeometry {\n /** Paper as printed (orientation applied), px. */\n paperWidth: number;\n paperHeight: number;\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** The printable box inside the margins, px. */\n areaWidth: number;\n areaHeight: number;\n}\n\nexport function printGeometry(setup: SheetPageSetup): PrintGeometry {\n const base = PAPER_SIZES[setup.paper];\n const landscape = setup.orientation === \"landscape\";\n const paperWidth = landscape ? base.height : base.width;\n const paperHeight = landscape ? base.width : base.height;\n const m = setup.margins === \"custom\" ? setup.customMargins : MARGIN_PRESET_INCHES[setup.margins];\n const px = (n: number) => Math.round(n * PX_PER_INCH);\n const geometry = {\n paperWidth,\n paperHeight,\n marginTop: px(m.top),\n marginBottom: px(m.bottom),\n marginLeft: px(m.left),\n marginRight: px(m.right),\n };\n return {\n ...geometry,\n areaWidth: Math.max(48, paperWidth - geometry.marginLeft - geometry.marginRight),\n areaHeight: Math.max(48, paperHeight - geometry.marginTop - geometry.marginBottom),\n };\n}\n\nexport const PRINT_ROW_HEIGHT = 22;\nconst MIN_COL = 48;\nconst MAX_COL = 320;\nconst CHAR_PX = 7;\n\n/** Column widths (px) fitted to the text the column holds. */\nexport function printColumnWidths(rows: readonly (readonly string[])[]): number[] {\n const width = rows.reduce((n, r) => Math.max(n, r.length), 0);\n const out: number[] = [];\n for (let c = 0; c < width; c += 1) {\n let longest = 0;\n for (const r of rows) longest = Math.max(longest, (r[c] ?? \"\").length);\n out.push(Math.min(MAX_COL, Math.max(MIN_COL, longest * CHAR_PX + 16)));\n }\n return out;\n}\n\nexport interface PrintPage {\n /** Grid row indexes drawn on this page, in order (repeated frozen rows first). */\n rows: number[];\n /** Grid column indexes drawn on this page, in order (repeated frozen columns first). */\n cols: number[];\n}\n\nexport interface PrintPlan {\n scale: number;\n geometry: PrintGeometry;\n colWidths: number[];\n pages: PrintPage[];\n}\n\n/** Splits `count` items into bands that fit `capacity(px)`, repeating `frozen` leading items on every band after the first. */\nfunction bands(sizes: readonly number[], capacityPx: number, frozen: number, repeat: boolean): number[][] {\n const total = sizes.length;\n if (total === 0) return [];\n const result: number[][] = [];\n const lead = repeat ? Math.min(frozen, total) : 0;\n const leadPx = sizes.slice(0, lead).reduce((a, b) => a + b, 0);\n let at = 0;\n while (at < total) {\n const first = result.length === 0;\n const carry = !first && lead > 0 ? Array.from({ length: lead }, (_, i) => i) : [];\n let used = first ? 0 : leadPx;\n const band = [...carry];\n // A repeated header never leaves a page with no room for a body item.\n if (!first && leadPx >= capacityPx) used = 0;\n let added = 0;\n while (at < total) {\n const size = sizes[at]!;\n if (used + size > capacityPx && added > 0) break;\n band.push(at);\n used += size;\n added += 1;\n at += 1;\n }\n result.push(band);\n }\n return result;\n}\n\n/** The pages one grid prints on under `setup`: scale, repeated frozen panes, and page order. */\nexport function planSheetPrint(\n rows: readonly (readonly string[])[],\n setup: SheetPageSetup,\n frozen: { rows: number; cols: number } = { rows: 0, cols: 0 },\n): PrintPlan {\n const geometry = printGeometry(setup);\n const colWidths = printColumnWidths(rows);\n const totalW = colWidths.reduce((a, b) => a + b, 0) || 1;\n const totalH = rows.length * PRINT_ROW_HEIGHT || 1;\n const fitW = geometry.areaWidth / totalW;\n const fitH = geometry.areaHeight / totalH;\n const scale =\n setup.scale === \"width\" ? Math.min(1, fitW) : setup.scale === \"height\" ? Math.min(1, fitH) : setup.scale === \"page\" ? Math.min(1, fitW, fitH) : 1;\n const rowBands = bands(\n rows.map(() => PRINT_ROW_HEIGHT),\n geometry.areaHeight / scale,\n frozen.rows,\n setup.repeatFrozenRows,\n );\n const colBands = bands(colWidths, geometry.areaWidth / scale, frozen.cols, setup.repeatFrozenColumns);\n const pages: PrintPage[] = [];\n if (setup.pageOrder === \"down-over\") {\n for (const cols of colBands) for (const r of rowBands) pages.push({ rows: r, cols });\n } else {\n for (const r of rowBands) for (const cols of colBands) pages.push({ rows: r, cols });\n }\n return { scale, geometry, colWidths, pages };\n}\n","/**\n * A workbook's print settings, read and written on the workbook itself:\n * `udt_workbooks.metadata.page_setup` (merged with `mergeJsonColumn`, like the table links beside it).\n */\nimport { mergeJsonColumn } from \"@ai-matrx/data/db\";\n\nimport { getSheetsHost } from \"./ports\";\nimport { normalizeSheetPageSetup, pageSetupFromMetadata, type SheetPageSetup } from \"./sheet-page-setup\";\n\nconst db = () => getSheetsHost().getSupabase();\n\ntype WorkbookMetaRow = { id: string; version: number; metadata: unknown };\n\nexport type PageSetupResult = { ok: true; data: SheetPageSetup } | { ok: false; error: string };\n\nexport async function readSheetPageSetup(workbookId: string): Promise<PageSetupResult> {\n const { data, error } = await db().schema(\"workbench\").from(\"udt_workbooks\").select(\"metadata\").eq(\"id\", workbookId).maybeSingle();\n if (error) return { ok: false, error: error.message };\n return { ok: true, data: pageSetupFromMetadata(data?.metadata) };\n}\n\nexport async function writeSheetPageSetup(workbookId: string, setup: SheetPageSetup): Promise<PageSetupResult> {\n const clean = normalizeSheetPageSetup(setup);\n const result = await mergeJsonColumn<WorkbookMetaRow>({\n fetchCurrent: () => db().schema(\"workbench\").from(\"udt_workbooks\").select(\"id, version, metadata\").eq(\"id\", workbookId).maybeSingle(),\n readColumn: (row) => row.metadata,\n merge: (current) => ({ ...current, page_setup: clean }),\n applyUpdate: ({ value, expectedVersion, nextVersion }) =>\n db()\n .schema(\"workbench\")\n .from(\"udt_workbooks\")\n .update({ metadata: value as never, version: nextVersion })\n .eq(\"id\", workbookId)\n .eq(\"version\", expectedVersion)\n .select(\"id, version, metadata\")\n .maybeSingle(),\n });\n if (result.status === \"saved\") return { ok: true, data: pageSetupFromMetadata(result.row.metadata) };\n if (result.status === \"not_found\") return { ok: false, error: \"This workbook could not be found\" };\n if (result.status === \"conflict\") return { ok: false, error: \"The workbook changed while saving; try again\" };\n const reason: unknown = result.error;\n return { ok: false, error: reason instanceof Error ? reason.message : typeof reason === \"string\" ? reason : \"Something went wrong\" };\n}\n","/**\n * The pages a workbook prints on: the snapshot's cells → paper-sized HTML pages that follow the\n * workbook's print settings (`sheet-page-setup.ts`). Print and Download as PDF both draw these\n * same pages, so what the browser prints is what the PDF holds.\n */\n\nimport { PX_PER_INCH } from \"../core\";\nimport {\n PRINT_ROW_HEIGHT,\n planSheetPrint,\n type PrintGeometry,\n type SheetPageSetup,\n} from \"./sheet-page-setup\";\nimport { univerSheetIds, univerSnapshotToRows, type CellRange } from \"./univer-snapshot-rows\";\n\nexport interface PrintSheet {\n name: string;\n rows: string[][];\n frozenRows: number;\n frozenCols: number;\n}\n\n/** The sheets the setup's \"what to print\" asks for (empty sheets left out). */\nexport function collectPrintSheets(\n snapshot: unknown,\n setup: SheetPageSetup,\n options: { sheetId?: string; selection?: CellRange | null },\n): PrintSheet[] {\n const read = (sheetId: string | undefined, range?: CellRange): PrintSheet | null => {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(sheetId ? { sheetId } : {}), ...(range ? { range } : {}) });\n if (!grid || grid.rows.length === 0) return null;\n return { name: grid.sheetName, rows: grid.rows, frozenRows: grid.frozenRows, frozenCols: grid.frozenCols };\n };\n if (setup.scope === \"workbook\") {\n return univerSheetIds(snapshot)\n .map((id) => read(id))\n .filter((s): s is PrintSheet => s !== null);\n }\n if (setup.scope === \"selection\") {\n const sel = options.selection;\n if (!sel || (sel.startRow === sel.endRow && sel.startColumn === sel.endColumn)) return [];\n const one = read(options.sheetId, sel);\n return one ? [one] : [];\n }\n const one = read(options.sheetId);\n return one ? [one] : [];\n}\n\nconst esc = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\nconst JUSTIFY = { left: \"flex-start\", center: \"center\", right: \"flex-end\" } as const;\nconst ALIGN = { top: \"flex-start\", middle: \"center\", bottom: \"flex-end\" } as const;\n\nfunction pageHtml(\n sheet: PrintSheet,\n page: { rows: number[]; cols: number[] },\n scale: number,\n colWidths: number[],\n g: PrintGeometry,\n setup: SheetPageSetup,\n numbering: { sheet: string; at: number; of: number },\n): string {\n const widths = page.cols.map((c) => colWidths[c] ?? 0);\n const tableW = widths.reduce((a, b) => a + b, 0);\n const tableH = page.rows.length * PRINT_ROW_HEIGHT;\n const border = setup.gridlines ? \"1px solid #b7b7b7\" : \"none\";\n const body = page.rows\n .map(\n (r) =>\n `<tr style=\"height:${PRINT_ROW_HEIGHT}px\">${page.cols\n .map((c) => `<td style=\"border:${border}\">${esc(sheet.rows[r]?.[c] ?? \"\")}</td>`)\n .join(\"\")}</tr>`,\n )\n .join(\"\");\n const cols = widths.map((w) => `<col style=\"width:${w}px\">`).join(\"\");\n return `<section data-print-page data-sheet=\"${esc(numbering.sheet)}\" data-page-number=\"${numbering.at}\" data-page-count=\"${numbering.of}\" data-page-rows=\"${page.rows.length}\" data-page-cols=\"${page.cols.length}\" style=\"width:${g.paperWidth}px;height:${g.paperHeight}px;box-sizing:border-box;padding:${g.marginTop}px ${g.marginRight}px ${g.marginBottom}px ${g.marginLeft}px;background:#fff;overflow:hidden;break-after:page;page-break-after:always\">\n<div style=\"width:${g.areaWidth}px;height:${g.areaHeight}px;display:flex;justify-content:${JUSTIFY[setup.alignH]};align-items:${ALIGN[setup.alignV]};overflow:hidden\">\n<div data-print-content style=\"width:${tableW * scale}px;height:${tableH * scale}px;flex:none;overflow:hidden\">\n<table style=\"width:${tableW}px;table-layout:fixed;border-collapse:collapse;transform:scale(${scale});transform-origin:0 0;font:12px/${PRINT_ROW_HEIGHT - 2}px system-ui,sans-serif;color:#111\"><colgroup>${cols}</colgroup><tbody>${body}</tbody></table>\n</div></div></section>`;\n}\n\nexport interface PrintDocument {\n /** Every page, in print order. */\n pagesHtml: string[];\n pageWidth: number;\n pageHeight: number;\n /** `@page` size in inches, for the browser's print engine. */\n pageSizeInches: { width: number; height: number };\n}\n\n/** All the printed pages of the chosen sheets under the setup (empty when there is nothing to print). */\nexport function buildPrintDocument(sheets: readonly PrintSheet[], setup: SheetPageSetup): PrintDocument | null {\n const out: string[] = [];\n let geometry: PrintGeometry | null = null;\n for (const sheet of sheets) {\n const plan = planSheetPrint(sheet.rows, setup, { rows: sheet.frozenRows, cols: sheet.frozenCols });\n geometry = plan.geometry;\n plan.pages.forEach((page, i) => {\n out.push(pageHtml(sheet, page, plan.scale, plan.colWidths, plan.geometry, setup, { sheet: sheet.name, at: i + 1, of: plan.pages.length }));\n });\n }\n if (!geometry || out.length === 0) return null;\n return {\n pagesHtml: out,\n pageWidth: geometry.paperWidth,\n pageHeight: geometry.paperHeight,\n pageSizeInches: { width: geometry.paperWidth / PX_PER_INCH, height: geometry.paperHeight / PX_PER_INCH },\n };\n}\n\n/** The whole printable web page: `@page` set to the paper, one section per page. */\nexport function printDocumentHtml(doc: PrintDocument, title: string): string {\n const { width, height } = doc.pageSizeInches;\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(title)}</title>\n<style>@page{size:${width.toFixed(3)}in ${height.toFixed(3)}in;margin:0}html,body{margin:0;padding:0;background:#fff}td{padding:0 6px;overflow:hidden;white-space:nowrap;text-overflow:clip;vertical-align:middle}section:last-child{break-after:auto;page-break-after:auto}</style></head>\n<body data-print-paper=\"${width.toFixed(3)}x${height.toFixed(3)}in\">${doc.pagesHtml.join(\"\\n\")}</body></html>`;\n}\n","/**\n * Outputs of a workbook: CSV/TSV/HTML downloads of the current sheet, and Print / PDF of what its page setup asks for.\n * Both read the same string grid the rest of the workbook code reads\n * (`univerSnapshotToRows`) — one source of what \"the sheet\" contains.\n */\n\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { toDelimitedText } from \"@ai-matrx/alchemy/operate/read\";\nimport { PX_PER_INCH } from \"../core\";\nimport type { SheetPageSetup } from \"./sheet-page-setup\";\nimport { buildPrintDocument, collectPrintSheets, printDocumentHtml } from \"./sheet-print-pages\";\nimport { univerSnapshotToRows, type CellRange } from \"./univer-snapshot-rows\";\n\nexport function rowsToCsv(rows: readonly (readonly string[])[]): string {\n const [header, ...body] = rows;\n if (!header) return \"\";\n return toDelimitedText(header, body, { spreadsheetSafe: false });\n}\n\nexport function downloadSheetAsCsv(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const name = `${options.filename.replace(/\\.csv$/i, \"\")}.csv`;\n // BOM so Excel reads UTF-8.\n const blob = new Blob([\"\", rowsToCsv(grid.rows)], { type: \"text/csv;charset=utf-8\" });\n downloadFile(name, blob, blob.type);\n return true;\n}\n\n/** Tab-separated values of the current sheet (Google's .tsv download). */\nexport function downloadSheetAsTsv(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const [header, ...body] = grid.rows;\n const text = toDelimitedText(header!, body, { format: \"tsv\", spreadsheetSafe: false });\n const blob = new Blob([\"\\uFEFF\", text], { type: \"text/tab-separated-values;charset=utf-8\" });\n downloadFile(`${options.filename.replace(/\\.tsv$/i, \"\")}.tsv`, blob, blob.type);\n return true;\n}\n\n/** The current sheet as a standalone web page (Google's .html download). */\nexport function downloadSheetAsHtml(\n snapshot: unknown,\n options: { sheetId?: string; filename: string },\n): boolean {\n const grid = univerSnapshotToRows(snapshot, { skipHidden: true, ...(options.sheetId ? { sheetId: options.sheetId } : {}) });\n if (!grid || grid.rows.length === 0) return false;\n const body = grid.rows.map((r) => `<tr>${r.map((c) => `<td>${esc(c)}</td>`).join(\"\")}</tr>`).join(\"\\n\");\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(options.filename)} — ${esc(grid.sheetName)}</title>\n<style>body{font:13px system-ui,sans-serif;margin:16px}table{border-collapse:collapse}td{border:1px solid #c0c0c0;padding:2px 6px;vertical-align:top}</style></head>\n<body><table>\n${body}\n</table></body></html>`;\n const blob = new Blob([html], { type: \"text/html;charset=utf-8\" });\n downloadFile(`${options.filename.replace(/\\.html?$/i, \"\")}.html`, blob, blob.type);\n return true;\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\n/** What a print or PDF needs besides the snapshot: the workbook's page setup and the live selection. */\nexport interface SheetPrintOptions {\n sheetId?: string;\n title: string;\n setup: SheetPageSetup;\n /** The cells selected right now (used when the setup prints \"selected cells\"). */\n selection?: CellRange | null;\n}\n\nfunction printDocumentFor(snapshot: unknown, options: SheetPrintOptions) {\n const sheets = collectPrintSheets(snapshot, options.setup, {\n ...(options.sheetId ? { sheetId: options.sheetId } : {}),\n selection: options.selection ?? null,\n });\n return buildPrintDocument(sheets, options.setup);\n}\n\n/** Opens the browser print sheet for what the workbook's page setup asks to print (choose \"Save as PDF\" there). */\nexport function printSheet(snapshot: unknown, options: SheetPrintOptions): boolean {\n const doc = printDocumentFor(snapshot, options);\n if (!doc) return false;\n const html = printDocumentHtml(doc, options.title);\n const frame = document.createElement(\"iframe\");\n frame.style.cssText = \"position:fixed;right:0;bottom:0;width:0;height:0;border:0\";\n document.body.appendChild(frame);\n const fdoc = frame.contentDocument;\n const win = frame.contentWindow;\n if (!fdoc || !win) {\n frame.remove();\n return false;\n }\n fdoc.open();\n fdoc.write(html);\n fdoc.close();\n win.addEventListener(\"afterprint\", () => frame.remove());\n win.focus();\n win.print();\n return true;\n}\n\n/** The sheet's grid as a markdown table (first row is the header row). */\nexport function rowsToMarkdownTable(rows: readonly (readonly string[])[]): string {\n if (rows.length === 0) return \"\";\n const width = Math.max(...rows.map((r) => r.length));\n const cell = (v: string | undefined) => (v ?? \"\").replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n const line = (r: readonly string[]) =>\n `| ${Array.from({ length: width }, (_, i) => cell(r[i])).join(\" | \")} |`;\n const [head, ...rest] = rows;\n return [line(head!), `| ${Array.from({ length: width }, () => \"---\").join(\" | \")} |`, ...rest.map(line)].join(\"\\n\");\n}\n\n/**\n * Real PDF download of what the workbook's page setup prints: the same pages Print draws, each one\n * captured and laid on a PDF page of the chosen paper size and orientation. Returns false when empty.\n */\nexport async function downloadSheetAsPdf(snapshot: unknown, options: SheetPrintOptions): Promise<boolean> {\n const doc = printDocumentFor(snapshot, options);\n if (!doc) return false;\n const [{ renderElement, pagesToPdf }, { downloadFile: save }] = await Promise.all([\n import(\"@ai-matrx/alchemy/operate/capture\"),\n import(\"@ai-matrx/kit/download\"),\n ]);\n const host = document.createElement(\"div\");\n host.setAttribute(\"aria-hidden\", \"true\");\n host.style.cssText = \"position:fixed;left:-20000px;top:0\";\n host.innerHTML = `<style>td{padding:0 6px;overflow:hidden;white-space:nowrap;vertical-align:middle}</style>${doc.pagesHtml.join(\"\")}`;\n document.body.appendChild(host);\n try {\n const pages = [];\n for (const el of Array.from(host.querySelectorAll<HTMLElement>(\"[data-print-page]\"))) {\n const image = await renderElement(el, { pixelRatio: 2, backgroundColor: \"#ffffff\", cacheBust: true });\n pages.push({ image, imageType: \"JPEG\" as const, quality: 0.92, placement: \"fill\" as const });\n }\n const mm = (px: number) => Math.round(((px / PX_PER_INCH) * 25.4) * 100) / 100;\n const pdf = await pagesToPdf(pages, {\n orientation: doc.pageWidth > doc.pageHeight ? \"landscape\" : \"portrait\",\n unit: \"mm\",\n format: [mm(Math.min(doc.pageWidth, doc.pageHeight)), mm(Math.max(doc.pageWidth, doc.pageHeight))],\n });\n save(`${options.title.replace(/[\\\\/:*?\"<>|]+/g, \" \").trim() || \"workbook\"}.pdf`, pdf, \"application/pdf\");\n } finally {\n host.remove();\n }\n return true;\n}\n","// features/workbooks/workbook-scope-source.ts\n//\n// Live bridge from the mounted `WorkbookEditor` to the `matrx-user/workbooks`\n// surface emitter on `/workbooks/[id]`.\n//\n// Why a module slot rather than props: the page owns the workbook row and\n// mounts `<SurfaceRuntimeProvider>`, but the sheets / snapshot / save status\n// live inside the editor (Univer refs + local state), one level DOWN. Pushing\n// them up as state would re-render the editor on every keystroke; a\n// registered getter is read once, at Run time, when the user actually\n// launches an agent.\n//\n// Exactly one editor is mounted at a time (one workbook per route), so a\n// single slot keyed by workbookId is enough. The getter returns null when the\n// editor has not booted — callers omit the values, they never fake them.\n\nexport interface WorkbookLiveScope {\n sheets: Array<{ id: string; name: string; index: number }>;\n activeSheetId: string | null;\n activeSheetName: string | null;\n snapshot: Record<string, unknown> | null;\n bootState: \"booting\" | \"ready\" | \"load_error\";\n loadError: string | null;\n saveStatus: string;\n collab: {\n enabled: boolean;\n is_host: boolean;\n self_uid: string;\n remote_peers: number;\n };\n}\n\ninterface Registration {\n workbookId: string;\n read: () => WorkbookLiveScope | null;\n}\n\nlet current: Registration | null = null;\n\n/** Called by `WorkbookEditor` while mounted. Returns an unregister. */\nexport function registerWorkbookScopeSource(\n registration: Registration,\n): () => void {\n current = registration;\n return () => {\n if (current === registration) current = null;\n };\n}\n\n/**\n * Read the live editor state for `workbookId`. Returns null when no editor is\n * mounted, when a different workbook is mounted, or when Univer has not\n * booted yet — never a fabricated shape.\n */\nexport function readWorkbookScopeSource(\n workbookId: string,\n): WorkbookLiveScope | null {\n if (!current || current.workbookId !== workbookId) return null;\n return current.read();\n}\n"]}