@ai-matrx/office 0.8.59 → 0.8.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,15 @@
1
1
  # Changelog
2
2
 
3
- ## 0.8.59
3
+ ## 0.8.60
4
4
 
5
5
  UNVERIFIED: this release has no Unreleased entry and the source comparison could not be made (the caller supplied no source comparison). Whether source changed is unknown; consumer action is unknown.
6
6
  Check the package's gitHead on npm against this version's gitHead: `git diff <previous gitHead> <this gitHead> -- apps/shared/office/src`.
7
7
 
8
+ ## 0.8.59
9
+
10
+ Automatic changed-only republish (docs/metadata drift since the last published version; verified: `git diff c271beb42b 838e7ca49b -- apps/shared/office/src`
11
+ has no shipped-source changes outside tests, fixtures and docs). No consumer action required.
12
+
8
13
  ## 0.8.58
9
14
 
10
15
  Automatic changed-only republish (docs/metadata drift since the last published version; verified: `git diff 4caaa1a3f9 c271beb42b -- apps/shared/office/src`
@@ -4,6 +4,7 @@
4
4
  var _chunkXAIKXHHJcjs = require('./chunk-XAIKXHHJ.cjs');
5
5
 
6
6
  // src/docs/doc-tools-core.ts
7
+ var _source = require('@ai-matrx/content-ir/source');
7
8
  var BUILDING_BLOCKS = [
8
9
  { id: "meeting-notes", label: "Meeting notes", description: "Date, attendees, agenda, decisions and action items.", markdown: "## Meeting notes\n\nDate: \nAttendees: \n\n### Agenda\n\n1. \n\n### Discussion\n\n### Decisions\n\n### Action items\n\n\u2610 Owner: Task, due date\n" },
9
10
  { id: "project-tracker", label: "Project tracker", description: "Goal, milestones, owners, risks and status.", markdown: "## Project tracker\n\nGoal: \nOwner: \nStatus: On track\n\n### Milestones\n\n\u2610 Milestone, owner, due date\n\n### Risks\n\n### Next steps\n" },
@@ -30,14 +31,13 @@ function markdownFragment(markdown) {
30
31
  function looksLikeMarkdown(text) {
31
32
  if (!text) return false;
32
33
  const lines = text.split(/\r?\n/);
33
- const delimiter = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/;
34
34
  for (let i = 0; i < lines.length; i++) {
35
35
  const line = lines[i];
36
36
  if (/^\s{0,3}#{1,6}\s+\S/.test(line)) return true;
37
37
  if (/^\s*([-*+]|\d+[.)])\s+\S/.test(line)) return true;
38
38
  if (/^\s{0,3}(```|~~~)/.test(line)) return true;
39
39
  if (/^\s*>\s?\S/.test(line)) return true;
40
- if (i > 0 && delimiter.test(line) && lines[i - 1].includes("|")) return true;
40
+ if (_source.tableStartsAt.call(void 0, lines, i)) return true;
41
41
  }
42
42
  return /\*\*[^*\s][^*]*\*\*|\[[^\]\n]+\]\([^)\s]+\)/.test(text);
43
43
  }
@@ -145,4 +145,4 @@ function readDocumentLanguage(documentStyle) {
145
145
 
146
146
 
147
147
  exports.BUILDING_BLOCKS = BUILDING_BLOCKS; exports.markdownFragment = markdownFragment; exports.looksLikeMarkdown = looksLikeMarkdown; exports.blockInsertPlan = blockInsertPlan; exports.BOOKMARK_RANGE_TYPE = BOOKMARK_RANGE_TYPE; exports.BOOKMARK_ANCHOR = BOOKMARK_ANCHOR; exports.collectBookmarks = collectBookmarks; exports.bookmarkBody = bookmarkBody; exports.cleanBookmarkName = cleanBookmarkName; exports.bookmarkFromHash = bookmarkFromHash; exports.bookmarkHash = bookmarkHash; exports.paragraphBorderParams = paragraphBorderParams; exports.rulerGeometry = rulerGeometry; exports.DOCUMENT_LANGUAGE_KEY = DOCUMENT_LANGUAGE_KEY; exports.DOCUMENT_LANGUAGES = DOCUMENT_LANGUAGES; exports.readDocumentLanguage = readDocumentLanguage;
148
- //# sourceMappingURL=chunk-NSU6EVJK.cjs.map
148
+ //# sourceMappingURL=chunk-6TUFBQLH.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/chunk-6TUFBQLH.cjs","../src/docs/doc-tools-core.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AAC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;AACtB,EAAA;AACC,EAAA;AACpB,EAAA;AACD,EAAA;AACA,EAAA;AACC,EAAA;AACe,EAAA;AACjB,EAAA;AACG,EAAA;AACF,EAAA;AACiB,EAAA;AACjB,EAAA;AACD,EAAA;AACE,EAAA;AACjC;AAEqE;AACqB,EAAA;AACvB,EAAA;AACnE;ADvFmE;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/chunk-6TUFBQLH.cjs","sourcesContent":[null,"/**\n * The pure half of the Docs tools: building blocks, bookmarks, paragraph borders, the ruler's\n * geometry and the document language. No Univer import, so each is proven on plain snapshots.\n */\n\nimport { PX_PER_INCH } from \"../core\";\nimport { tableStartsAt } from \"@ai-matrx/content-ir/source\";\nimport { markdownToUniverDoc } from \"./markdown-to-univer-doc\";\n\nexport interface BuildingBlock {\n id: string;\n label: string;\n description: string;\n markdown: string;\n}\n\nexport const BUILDING_BLOCKS: BuildingBlock[] = [\n { id: \"meeting-notes\", label: \"Meeting notes\", description: \"Date, attendees, agenda, decisions and action items.\", markdown: \"## Meeting notes\\n\\nDate: \\nAttendees: \\n\\n### Agenda\\n\\n1. \\n\\n### Discussion\\n\\n### Decisions\\n\\n### Action items\\n\\n☐ Owner: Task, due date\\n\" },\n { id: \"project-tracker\", label: \"Project tracker\", description: \"Goal, milestones, owners, risks and status.\", markdown: \"## Project tracker\\n\\nGoal: \\nOwner: \\nStatus: On track\\n\\n### Milestones\\n\\n☐ Milestone, owner, due date\\n\\n### Risks\\n\\n### Next steps\\n\" },\n { id: \"email-draft\", label: \"Email draft\", description: \"To, subject and a three-part message ready to fill in.\", markdown: \"## Email draft\\n\\nTo: \\nSubject: \\n\\nHi ,\\n\\nI am writing about .\\n\\nThe next step is .\\n\\nThanks,\\n\" },\n { id: \"weekly-status\", label: \"Weekly status\", description: \"Done, next, and blocked, for one week.\", markdown: \"## Weekly status\\n\\nWeek of: \\n\\n### Done this week\\n\\n### Next week\\n\\n### Blocked\\n\" },\n { id: \"decision-log\", label: \"Decision record\", description: \"Context, options, decision and consequences.\", markdown: \"## Decision record\\n\\nDate: \\nDecider: \\n\\n### Context\\n\\n### Options considered\\n\\n### Decision\\n\\n### Consequences\\n\" },\n { id: \"pros-cons\", label: \"Pros and cons\", description: \"A side-by-side weighing of one choice.\", markdown: \"## Pros and cons\\n\\nChoice: \\n\\n### Pros\\n\\n### Cons\\n\\n### Verdict\\n\" },\n];\n\n/** What Univer's paste command takes as `doc`: a body (no document-closing `\\n`) plus the table sources its `tables` name. */\nexport interface MarkdownFragment {\n body: Record<string, unknown> & { dataStream: string };\n tableSource?: Record<string, unknown>;\n drawings?: Record<string, unknown>;\n}\n\n/**\n * Markdown to a fragment Univer can insert at the caret (`doc.command.inner-paste`): headings, lists,\n * bold, links and REAL tables, from THE one writer (`markdownToUniverDoc`). The document-closing `\\n`\n * and its section break are dropped; every other body part (tables, links, runs) is kept.\n */\nexport function markdownFragment(markdown: string): MarkdownFragment {\n const doc = markdownToUniverDoc(markdown) as unknown as {\n body?: Record<string, unknown> & { dataStream: string };\n tableSource?: Record<string, unknown>;\n drawings?: Record<string, unknown>;\n };\n const whole = doc.body ?? { dataStream: \"\" };\n let stream = whole.dataStream;\n if (stream.endsWith(\"\\n\")) stream = stream.slice(0, -1);\n const { sectionBreaks: _sectionBreaks, ...rest } = whole;\n void _sectionBreaks;\n const paragraphs = ((whole.paragraphs as Array<{ startIndex: number }> | undefined) ?? []).filter((p) => p.startIndex < stream.length);\n const textRuns = ((whole.textRuns as Array<{ st: number; ed: number }> | undefined) ?? [])\n .filter((r) => r.st < stream.length)\n .map((r) => ({ ...r, ed: Math.min(r.ed, stream.length) }));\n return {\n body: { ...rest, dataStream: stream, paragraphs, textRuns },\n ...(doc.tableSource ? { tableSource: doc.tableSource } : {}),\n ...(doc.drawings ? { drawings: doc.drawings } : {}),\n };\n}\n\n/**\n * True when text carries markdown STRUCTURE a document should draw: a table, a heading, a list, a\n * fence, a quote, a link, or bold. Plain prose (and a stray `*` or `_`) is false, so ordinary\n * typing and paste stay plain text. Every door that takes agent- or clipboard-supplied text asks\n * this one question, then converts through `markdownFragment`.\n */\nexport function looksLikeMarkdown(text: string): boolean {\n if (!text) return false;\n const lines = text.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (/^\\s{0,3}#{1,6}\\s+\\S/.test(line)) return true;\n if (/^\\s*([-*+]|\\d+[.)])\\s+\\S/.test(line)) return true;\n if (/^\\s{0,3}(```|~~~)/.test(line)) return true;\n if (/^\\s*>\\s?\\S/.test(line)) return true;\n if (tableStartsAt(lines, i)) return true;\n }\n return /\\*\\*[^*\\s][^*]*\\*\\*|\\[[^\\]\\n]+\\]\\([^)\\s]+\\)/.test(text);\n}\n\n/**\n * Where a BLOCK (table of contents, building block) goes for a caret: never inside a paragraph's\n * text, so a heading is never split. Caret at the start of a paragraph (or in an empty one) →\n * insert right there; anywhere else → end the caret's paragraph with a new line and insert at the\n * start of that new paragraph. `dataStream` is Univer's body stream (paragraphs end in `\\r`).\n */\nexport function blockInsertPlan(dataStream: string, caret: number): { at: number; breakAt: number | null } {\n const c = Math.max(0, Math.min(caret, dataStream.length));\n const start = Math.max(dataStream.lastIndexOf(\"\\r\", c - 1), dataStream.lastIndexOf(\"\\n\", c - 1)) + 1;\n let end = dataStream.indexOf(\"\\r\", c);\n if (end < 0) end = dataStream.length;\n // Field marks and anchors are zero-width: a paragraph holding only them is empty.\n const text = dataStream.slice(start, end).replace(/[\\u0000-\\u001f\\u200b]/g, \"\").trim();\n if (c === start || text === \"\") return { at: start, breakAt: null };\n return { at: end + 1, breakAt: end };\n}\n\n/** Univer's CustomRangeType.BOOKMARK. */\nexport const BOOKMARK_RANGE_TYPE = 3;\n/** A bookmark is an invisible anchor: one zero-width character the custom range wraps. */\nexport const BOOKMARK_ANCHOR = \"​\";\n\nexport interface Bookmark {\n id: string;\n name: string;\n offset: number;\n}\n\ninterface BodyWithRanges {\n customRanges?: Array<{ rangeId: string; rangeType: number; startIndex: number; properties?: { name?: unknown } }>;\n}\n\nexport function collectBookmarks(snapshot: unknown): Bookmark[] {\n const body = (snapshot as { body?: BodyWithRanges } | null)?.body;\n const out: Bookmark[] = [];\n for (const r of body?.customRanges ?? []) {\n if (r.rangeType !== BOOKMARK_RANGE_TYPE) continue;\n out.push({ id: r.rangeId, name: typeof r.properties?.name === \"string\" ? r.properties.name : \"\", offset: r.startIndex });\n }\n return out.sort((a, b) => a.offset - b.offset);\n}\n\nexport function bookmarkBody(id: string, name: string) {\n return {\n dataStream: BOOKMARK_ANCHOR,\n customRanges: [{ startIndex: 0, endIndex: 0, rangeId: id, rangeType: BOOKMARK_RANGE_TYPE, properties: { name }, wholeEntity: true }],\n };\n}\n\nexport function cleanBookmarkName(raw: string, existing: readonly Bookmark[]): { ok: true; name: string } | { ok: false; why: string } {\n const name = raw.replace(/\\s+/g, \" \").trim().slice(0, 80);\n if (!name) return { ok: false, why: \"Give the bookmark a name.\" };\n if (existing.some((b) => b.name.toLowerCase() === name.toLowerCase())) return { ok: false, why: `A bookmark named \"${name}\" already exists.` };\n return { ok: true, name };\n}\n\n/** `#bookmark=<name>` in the page address names a bookmark to jump to on open. */\nexport function bookmarkFromHash(hash: string): string | null {\n const m = /^#bookmark=(.+)$/.exec(hash);\n if (!m) return null;\n try {\n return decodeURIComponent(m[1]!);\n } catch {\n return null;\n }\n}\nexport const bookmarkHash = (name: string) => `#bookmark=${encodeURIComponent(name)}`;\n\nexport type BorderSide = \"top\" | \"bottom\" | \"both\" | \"none\";\nexport type BorderDash = \"solid\" | \"dashed\" | \"dotted\";\n/** Univer's DashStyleType values. */\nconst DASH: Record<BorderDash, number> = { solid: 1, dotted: 2, dashed: 3 };\n\nexport interface BorderChoice {\n side: BorderSide;\n color: string;\n width: number;\n dash: BorderDash;\n padding: number;\n}\n\n/** The `paragraph` argument of `doc-paragraph-setting.command` for a choice (Univer draws top and bottom paragraph borders). */\nexport function paragraphBorderParams(c: BorderChoice): Record<string, unknown> {\n const line = { color: { rgb: c.color }, width: c.width, dashStyle: DASH[c.dash], padding: c.padding };\n return {\n borderTop: c.side === \"top\" || c.side === \"both\" ? line : null,\n borderBottom: c.side === \"bottom\" || c.side === \"both\" ? line : null,\n };\n}\n\nexport interface RulerGeometry {\n pageLeft: number;\n pageWidth: number;\n marginLeft: number;\n marginRight: number;\n ticks: Array<{ x: number; kind: \"inch\" | \"half\" | \"eighth\"; label?: string }>;\n}\n\n/** The ruler above the page: inch ticks from the page's left edge (margins shaded), at the current zoom. */\nexport function rulerGeometry(a: { containerWidth: number; zoom: number; pageWidthPx: number; marginLeftPx: number; marginRightPx: number }): RulerGeometry {\n const pageWidth = a.pageWidthPx * a.zoom;\n const pageLeft = Math.max(0, (a.containerWidth - pageWidth) / 2);\n const ticks: RulerGeometry[\"ticks\"] = [];\n const inches = a.pageWidthPx / PX_PER_INCH;\n for (let eighth = 0; eighth <= Math.floor(inches * 8); eighth++) {\n const x = pageLeft + (eighth * PX_PER_INCH * a.zoom) / 8;\n if (eighth % 8 === 0) {\n const marginInches = a.marginLeftPx / PX_PER_INCH;\n ticks.push({ x, kind: \"inch\", ...(eighth / 8 !== marginInches ? { label: String(Math.round(Math.abs(eighth / 8 - marginInches))) } : {}) });\n } else ticks.push({ x, kind: eighth % 4 === 0 ? \"half\" : \"eighth\" });\n }\n return { pageLeft, pageWidth, marginLeft: a.marginLeftPx * a.zoom, marginRight: a.marginRightPx * a.zoom, ticks };\n}\n\n/** The key on the document style that carries the language (the slot the paper color also uses). */\nexport const DOCUMENT_LANGUAGE_KEY = \"matrxLanguage\";\nexport const DOCUMENT_LANGUAGES: Array<{ code: string; label: string }> = [\n { code: \"en-US\", label: \"English (United States)\" },\n { code: \"en-GB\", label: \"English (United Kingdom)\" },\n { code: \"es\", label: \"Spanish\" },\n { code: \"fr\", label: \"French\" },\n { code: \"de\", label: \"German\" },\n { code: \"it\", label: \"Italian\" },\n { code: \"pt-BR\", label: \"Portuguese (Brazil)\" },\n { code: \"nl\", label: \"Dutch\" },\n { code: \"ja\", label: \"Japanese\" },\n { code: \"ko\", label: \"Korean\" },\n { code: \"zh-CN\", label: \"Chinese (Simplified)\" },\n { code: \"ar\", label: \"Arabic\" },\n { code: \"hi\", label: \"Hindi\" },\n { code: \"ru\", label: \"Russian\" },\n];\n\nexport function readDocumentLanguage(documentStyle: unknown): string {\n const v = (documentStyle as Record<string, unknown> | undefined)?.[DOCUMENT_LANGUAGE_KEY];\n return typeof v === \"string\" && DOCUMENT_LANGUAGES.some((l) => l.code === v) ? v : \"en-US\";\n}\n"]}
@@ -4,6 +4,7 @@ import {
4
4
  } from "./chunk-Y24EYKSD.js";
5
5
 
6
6
  // src/docs/doc-tools-core.ts
7
+ import { tableStartsAt } from "@ai-matrx/content-ir/source";
7
8
  var BUILDING_BLOCKS = [
8
9
  { id: "meeting-notes", label: "Meeting notes", description: "Date, attendees, agenda, decisions and action items.", markdown: "## Meeting notes\n\nDate: \nAttendees: \n\n### Agenda\n\n1. \n\n### Discussion\n\n### Decisions\n\n### Action items\n\n\u2610 Owner: Task, due date\n" },
9
10
  { id: "project-tracker", label: "Project tracker", description: "Goal, milestones, owners, risks and status.", markdown: "## Project tracker\n\nGoal: \nOwner: \nStatus: On track\n\n### Milestones\n\n\u2610 Milestone, owner, due date\n\n### Risks\n\n### Next steps\n" },
@@ -30,14 +31,13 @@ function markdownFragment(markdown) {
30
31
  function looksLikeMarkdown(text) {
31
32
  if (!text) return false;
32
33
  const lines = text.split(/\r?\n/);
33
- const delimiter = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/;
34
34
  for (let i = 0; i < lines.length; i++) {
35
35
  const line = lines[i];
36
36
  if (/^\s{0,3}#{1,6}\s+\S/.test(line)) return true;
37
37
  if (/^\s*([-*+]|\d+[.)])\s+\S/.test(line)) return true;
38
38
  if (/^\s{0,3}(```|~~~)/.test(line)) return true;
39
39
  if (/^\s*>\s?\S/.test(line)) return true;
40
- if (i > 0 && delimiter.test(line) && lines[i - 1].includes("|")) return true;
40
+ if (tableStartsAt(lines, i)) return true;
41
41
  }
42
42
  return /\*\*[^*\s][^*]*\*\*|\[[^\]\n]+\]\([^)\s]+\)/.test(text);
43
43
  }
@@ -145,4 +145,4 @@ export {
145
145
  DOCUMENT_LANGUAGES,
146
146
  readDocumentLanguage
147
147
  };
148
- //# sourceMappingURL=chunk-DY5TGHBI.js.map
148
+ //# sourceMappingURL=chunk-JVEJ5XLX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/docs/doc-tools-core.ts"],"sourcesContent":["/**\n * The pure half of the Docs tools: building blocks, bookmarks, paragraph borders, the ruler's\n * geometry and the document language. No Univer import, so each is proven on plain snapshots.\n */\n\nimport { PX_PER_INCH } from \"../core\";\nimport { tableStartsAt } from \"@ai-matrx/content-ir/source\";\nimport { markdownToUniverDoc } from \"./markdown-to-univer-doc\";\n\nexport interface BuildingBlock {\n id: string;\n label: string;\n description: string;\n markdown: string;\n}\n\nexport const BUILDING_BLOCKS: BuildingBlock[] = [\n { id: \"meeting-notes\", label: \"Meeting notes\", description: \"Date, attendees, agenda, decisions and action items.\", markdown: \"## Meeting notes\\n\\nDate: \\nAttendees: \\n\\n### Agenda\\n\\n1. \\n\\n### Discussion\\n\\n### Decisions\\n\\n### Action items\\n\\n☐ Owner: Task, due date\\n\" },\n { id: \"project-tracker\", label: \"Project tracker\", description: \"Goal, milestones, owners, risks and status.\", markdown: \"## Project tracker\\n\\nGoal: \\nOwner: \\nStatus: On track\\n\\n### Milestones\\n\\n☐ Milestone, owner, due date\\n\\n### Risks\\n\\n### Next steps\\n\" },\n { id: \"email-draft\", label: \"Email draft\", description: \"To, subject and a three-part message ready to fill in.\", markdown: \"## Email draft\\n\\nTo: \\nSubject: \\n\\nHi ,\\n\\nI am writing about .\\n\\nThe next step is .\\n\\nThanks,\\n\" },\n { id: \"weekly-status\", label: \"Weekly status\", description: \"Done, next, and blocked, for one week.\", markdown: \"## Weekly status\\n\\nWeek of: \\n\\n### Done this week\\n\\n### Next week\\n\\n### Blocked\\n\" },\n { id: \"decision-log\", label: \"Decision record\", description: \"Context, options, decision and consequences.\", markdown: \"## Decision record\\n\\nDate: \\nDecider: \\n\\n### Context\\n\\n### Options considered\\n\\n### Decision\\n\\n### Consequences\\n\" },\n { id: \"pros-cons\", label: \"Pros and cons\", description: \"A side-by-side weighing of one choice.\", markdown: \"## Pros and cons\\n\\nChoice: \\n\\n### Pros\\n\\n### Cons\\n\\n### Verdict\\n\" },\n];\n\n/** What Univer's paste command takes as `doc`: a body (no document-closing `\\n`) plus the table sources its `tables` name. */\nexport interface MarkdownFragment {\n body: Record<string, unknown> & { dataStream: string };\n tableSource?: Record<string, unknown>;\n drawings?: Record<string, unknown>;\n}\n\n/**\n * Markdown to a fragment Univer can insert at the caret (`doc.command.inner-paste`): headings, lists,\n * bold, links and REAL tables, from THE one writer (`markdownToUniverDoc`). The document-closing `\\n`\n * and its section break are dropped; every other body part (tables, links, runs) is kept.\n */\nexport function markdownFragment(markdown: string): MarkdownFragment {\n const doc = markdownToUniverDoc(markdown) as unknown as {\n body?: Record<string, unknown> & { dataStream: string };\n tableSource?: Record<string, unknown>;\n drawings?: Record<string, unknown>;\n };\n const whole = doc.body ?? { dataStream: \"\" };\n let stream = whole.dataStream;\n if (stream.endsWith(\"\\n\")) stream = stream.slice(0, -1);\n const { sectionBreaks: _sectionBreaks, ...rest } = whole;\n void _sectionBreaks;\n const paragraphs = ((whole.paragraphs as Array<{ startIndex: number }> | undefined) ?? []).filter((p) => p.startIndex < stream.length);\n const textRuns = ((whole.textRuns as Array<{ st: number; ed: number }> | undefined) ?? [])\n .filter((r) => r.st < stream.length)\n .map((r) => ({ ...r, ed: Math.min(r.ed, stream.length) }));\n return {\n body: { ...rest, dataStream: stream, paragraphs, textRuns },\n ...(doc.tableSource ? { tableSource: doc.tableSource } : {}),\n ...(doc.drawings ? { drawings: doc.drawings } : {}),\n };\n}\n\n/**\n * True when text carries markdown STRUCTURE a document should draw: a table, a heading, a list, a\n * fence, a quote, a link, or bold. Plain prose (and a stray `*` or `_`) is false, so ordinary\n * typing and paste stay plain text. Every door that takes agent- or clipboard-supplied text asks\n * this one question, then converts through `markdownFragment`.\n */\nexport function looksLikeMarkdown(text: string): boolean {\n if (!text) return false;\n const lines = text.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (/^\\s{0,3}#{1,6}\\s+\\S/.test(line)) return true;\n if (/^\\s*([-*+]|\\d+[.)])\\s+\\S/.test(line)) return true;\n if (/^\\s{0,3}(```|~~~)/.test(line)) return true;\n if (/^\\s*>\\s?\\S/.test(line)) return true;\n if (tableStartsAt(lines, i)) return true;\n }\n return /\\*\\*[^*\\s][^*]*\\*\\*|\\[[^\\]\\n]+\\]\\([^)\\s]+\\)/.test(text);\n}\n\n/**\n * Where a BLOCK (table of contents, building block) goes for a caret: never inside a paragraph's\n * text, so a heading is never split. Caret at the start of a paragraph (or in an empty one) →\n * insert right there; anywhere else → end the caret's paragraph with a new line and insert at the\n * start of that new paragraph. `dataStream` is Univer's body stream (paragraphs end in `\\r`).\n */\nexport function blockInsertPlan(dataStream: string, caret: number): { at: number; breakAt: number | null } {\n const c = Math.max(0, Math.min(caret, dataStream.length));\n const start = Math.max(dataStream.lastIndexOf(\"\\r\", c - 1), dataStream.lastIndexOf(\"\\n\", c - 1)) + 1;\n let end = dataStream.indexOf(\"\\r\", c);\n if (end < 0) end = dataStream.length;\n // Field marks and anchors are zero-width: a paragraph holding only them is empty.\n const text = dataStream.slice(start, end).replace(/[\\u0000-\\u001f\\u200b]/g, \"\").trim();\n if (c === start || text === \"\") return { at: start, breakAt: null };\n return { at: end + 1, breakAt: end };\n}\n\n/** Univer's CustomRangeType.BOOKMARK. */\nexport const BOOKMARK_RANGE_TYPE = 3;\n/** A bookmark is an invisible anchor: one zero-width character the custom range wraps. */\nexport const BOOKMARK_ANCHOR = \"​\";\n\nexport interface Bookmark {\n id: string;\n name: string;\n offset: number;\n}\n\ninterface BodyWithRanges {\n customRanges?: Array<{ rangeId: string; rangeType: number; startIndex: number; properties?: { name?: unknown } }>;\n}\n\nexport function collectBookmarks(snapshot: unknown): Bookmark[] {\n const body = (snapshot as { body?: BodyWithRanges } | null)?.body;\n const out: Bookmark[] = [];\n for (const r of body?.customRanges ?? []) {\n if (r.rangeType !== BOOKMARK_RANGE_TYPE) continue;\n out.push({ id: r.rangeId, name: typeof r.properties?.name === \"string\" ? r.properties.name : \"\", offset: r.startIndex });\n }\n return out.sort((a, b) => a.offset - b.offset);\n}\n\nexport function bookmarkBody(id: string, name: string) {\n return {\n dataStream: BOOKMARK_ANCHOR,\n customRanges: [{ startIndex: 0, endIndex: 0, rangeId: id, rangeType: BOOKMARK_RANGE_TYPE, properties: { name }, wholeEntity: true }],\n };\n}\n\nexport function cleanBookmarkName(raw: string, existing: readonly Bookmark[]): { ok: true; name: string } | { ok: false; why: string } {\n const name = raw.replace(/\\s+/g, \" \").trim().slice(0, 80);\n if (!name) return { ok: false, why: \"Give the bookmark a name.\" };\n if (existing.some((b) => b.name.toLowerCase() === name.toLowerCase())) return { ok: false, why: `A bookmark named \"${name}\" already exists.` };\n return { ok: true, name };\n}\n\n/** `#bookmark=<name>` in the page address names a bookmark to jump to on open. */\nexport function bookmarkFromHash(hash: string): string | null {\n const m = /^#bookmark=(.+)$/.exec(hash);\n if (!m) return null;\n try {\n return decodeURIComponent(m[1]!);\n } catch {\n return null;\n }\n}\nexport const bookmarkHash = (name: string) => `#bookmark=${encodeURIComponent(name)}`;\n\nexport type BorderSide = \"top\" | \"bottom\" | \"both\" | \"none\";\nexport type BorderDash = \"solid\" | \"dashed\" | \"dotted\";\n/** Univer's DashStyleType values. */\nconst DASH: Record<BorderDash, number> = { solid: 1, dotted: 2, dashed: 3 };\n\nexport interface BorderChoice {\n side: BorderSide;\n color: string;\n width: number;\n dash: BorderDash;\n padding: number;\n}\n\n/** The `paragraph` argument of `doc-paragraph-setting.command` for a choice (Univer draws top and bottom paragraph borders). */\nexport function paragraphBorderParams(c: BorderChoice): Record<string, unknown> {\n const line = { color: { rgb: c.color }, width: c.width, dashStyle: DASH[c.dash], padding: c.padding };\n return {\n borderTop: c.side === \"top\" || c.side === \"both\" ? line : null,\n borderBottom: c.side === \"bottom\" || c.side === \"both\" ? line : null,\n };\n}\n\nexport interface RulerGeometry {\n pageLeft: number;\n pageWidth: number;\n marginLeft: number;\n marginRight: number;\n ticks: Array<{ x: number; kind: \"inch\" | \"half\" | \"eighth\"; label?: string }>;\n}\n\n/** The ruler above the page: inch ticks from the page's left edge (margins shaded), at the current zoom. */\nexport function rulerGeometry(a: { containerWidth: number; zoom: number; pageWidthPx: number; marginLeftPx: number; marginRightPx: number }): RulerGeometry {\n const pageWidth = a.pageWidthPx * a.zoom;\n const pageLeft = Math.max(0, (a.containerWidth - pageWidth) / 2);\n const ticks: RulerGeometry[\"ticks\"] = [];\n const inches = a.pageWidthPx / PX_PER_INCH;\n for (let eighth = 0; eighth <= Math.floor(inches * 8); eighth++) {\n const x = pageLeft + (eighth * PX_PER_INCH * a.zoom) / 8;\n if (eighth % 8 === 0) {\n const marginInches = a.marginLeftPx / PX_PER_INCH;\n ticks.push({ x, kind: \"inch\", ...(eighth / 8 !== marginInches ? { label: String(Math.round(Math.abs(eighth / 8 - marginInches))) } : {}) });\n } else ticks.push({ x, kind: eighth % 4 === 0 ? \"half\" : \"eighth\" });\n }\n return { pageLeft, pageWidth, marginLeft: a.marginLeftPx * a.zoom, marginRight: a.marginRightPx * a.zoom, ticks };\n}\n\n/** The key on the document style that carries the language (the slot the paper color also uses). */\nexport const DOCUMENT_LANGUAGE_KEY = \"matrxLanguage\";\nexport const DOCUMENT_LANGUAGES: Array<{ code: string; label: string }> = [\n { code: \"en-US\", label: \"English (United States)\" },\n { code: \"en-GB\", label: \"English (United Kingdom)\" },\n { code: \"es\", label: \"Spanish\" },\n { code: \"fr\", label: \"French\" },\n { code: \"de\", label: \"German\" },\n { code: \"it\", label: \"Italian\" },\n { code: \"pt-BR\", label: \"Portuguese (Brazil)\" },\n { code: \"nl\", label: \"Dutch\" },\n { code: \"ja\", label: \"Japanese\" },\n { code: \"ko\", label: \"Korean\" },\n { code: \"zh-CN\", label: \"Chinese (Simplified)\" },\n { code: \"ar\", label: \"Arabic\" },\n { code: \"hi\", label: \"Hindi\" },\n { code: \"ru\", label: \"Russian\" },\n];\n\nexport function readDocumentLanguage(documentStyle: unknown): string {\n const v = (documentStyle as Record<string, unknown> | undefined)?.[DOCUMENT_LANGUAGE_KEY];\n return typeof v === \"string\" && DOCUMENT_LANGUAGES.some((l) => l.code === v) ? v : \"en-US\";\n}\n"],"mappings":";;;;;;AAMA,SAAS,qBAAqB;AAUvB,IAAM,kBAAmC;AAAA,EAC9C,EAAE,IAAI,iBAAiB,OAAO,iBAAiB,aAAa,wDAAwD,UAAU,wJAAmJ;AAAA,EACjR,EAAE,IAAI,mBAAmB,OAAO,mBAAmB,aAAa,+CAA+C,UAAU,kJAA6I;AAAA,EACtQ,EAAE,IAAI,eAAe,OAAO,eAAe,aAAa,0DAA0D,UAAU,uGAAuG;AAAA,EACnO,EAAE,IAAI,iBAAiB,OAAO,iBAAiB,aAAa,0CAA0C,UAAU,wFAAwF;AAAA,EACxM,EAAE,IAAI,gBAAgB,OAAO,mBAAmB,aAAa,gDAAgD,UAAU,yHAAyH;AAAA,EAChP,EAAE,IAAI,aAAa,OAAO,iBAAiB,aAAa,0CAA0C,UAAU,wEAAwE;AACtL;AAcO,SAAS,iBAAiB,UAAoC;AACnE,QAAM,MAAM,oBAAoB,QAAQ;AAKxC,QAAM,QAAQ,IAAI,QAAQ,EAAE,YAAY,GAAG;AAC3C,MAAI,SAAS,MAAM;AACnB,MAAI,OAAO,SAAS,IAAI,EAAG,UAAS,OAAO,MAAM,GAAG,EAAE;AACtD,QAAM,EAAE,eAAe,gBAAgB,GAA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AAE,UAAU,WAAW,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,EAAE,gBAAgB,EAAE,MAAM,MAAM;AAClH;AAGO,IAAM,wBAAwB;AAC9B,IAAM,qBAA6D;AAAA,EACxE,EAAE,MAAM,SAAS,OAAO,0BAA0B;AAAA,EAClD,EAAE,MAAM,SAAS,OAAO,2BAA2B;AAAA,EACnD,EAAE,MAAM,MAAM,OAAO,UAAU;AAAA,EAC/B,EAAE,MAAM,MAAM,OAAO,SAAS;AAAA,EAC9B,EAAE,MAAM,MAAM,OAAO,SAAS;AAAA,EAC9B,EAAE,MAAM,MAAM,OAAO,UAAU;AAAA,EAC/B,EAAE,MAAM,SAAS,OAAO,sBAAsB;AAAA,EAC9C,EAAE,MAAM,MAAM,OAAO,QAAQ;AAAA,EAC7B,EAAE,MAAM,MAAM,OAAO,WAAW;AAAA,EAChC,EAAE,MAAM,MAAM,OAAO,SAAS;AAAA,EAC9B,EAAE,MAAM,SAAS,OAAO,uBAAuB;AAAA,EAC/C,EAAE,MAAM,MAAM,OAAO,SAAS;AAAA,EAC9B,EAAE,MAAM,MAAM,OAAO,QAAQ;AAAA,EAC7B,EAAE,MAAM,MAAM,OAAO,UAAU;AACjC;AAEO,SAAS,qBAAqB,eAAgC;AACnE,QAAM,IAAK,gBAAwD,qBAAqB;AACxF,SAAO,OAAO,MAAM,YAAY,mBAAmB,KAAK,CAAC,MAAM,EAAE,SAAS,CAAC,IAAI,IAAI;AACrF;","names":[]}
package/dist/docs-io.cjs CHANGED
@@ -11,6 +11,7 @@ var _chunkXJBJKOUHcjs = require('./chunk-XJBJKOUH.cjs');
11
11
  var _chunkXAIKXHHJcjs = require('./chunk-XAIKXHHJ.cjs');
12
12
 
13
13
  // src/docs/univer-doc-to-markdown.ts
14
+ var _source = require('@ai-matrx/content-ir/source');
14
15
  var TABLE_CELL_SEP = " | ";
15
16
  var TABLE_START = "";
16
17
  var TABLE_ROW_START = "\x1B";
@@ -207,7 +208,7 @@ function univerDocToMarkdown(snapshot, options = {}) {
207
208
  if (atEnd) break;
208
209
  }
209
210
  const kindOf = (line) => /^\s*(?:\u2022|[-*+]|\d+[.)])\s+/.test(line) ? "list" : line.includes(TABLE_CELL_SEP) ? "table" : "text";
210
- const rawRow = (l) => /^\s*\|.*\|\s*$/.test(l);
211
+ const rawRow = _source.isPipeLedRow;
211
212
  const rows = lines.filter((l, i) => {
212
213
  if (l.trim()) return true;
213
214
  let a = i - 1;
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/docs-io.cjs","../src/docs/univer-doc-to-markdown.ts","../src/docs/import-document-file.ts","../src/docs/export-open-formats.ts"],"names":["out"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACgBA,IAAM,eAAA,EAAiB,SAAA;AAGvB,IAAM,YAAA,EAAc,GAAA;AACpB,IAAM,gBAAA,EAAkB,MAAA;AACxB,IAAM,iBAAA,EAAmB,GAAA;AACzB,IAAM,eAAA,EAAiB,GAAA;AACvB,IAAM,cAAA,EAAgB,GAAA;AACtB,IAAM,UAAA,EAAY,GAAA;AAClB,IAAM,WAAA,EAAa,GAAA;AACnB,IAAM,SAAA,EAAW,GAAA;AAUjB,SAAS,aAAA,CAAc,IAAA,EAA4B;AACjD,EAAA,MAAM,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,GAAG,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,EAAA,GAAM,CAAA,CAAE,MAAM,CAAC,CAAA;AACtD,EAAA,MAAM,KAAA,EAAO,CAAC,CAAA,EAAa,CAAA,EAAA,GAAA,kBAAe,CAAA,CAAE,CAAC,CAAA,UAAK,IAAA,CAAA,CAAI,OAAA,CAAQ,gBAAA,EAAkB,IAAI,CAAA;AACpF,EAAA,MAAM,KAAA,EAAO,CAAC,CAAA,EAAa,KAAA,EAAA,GACzB,CAAA,EAAA,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,EAAA;AACnB,EAAA;AAC+B,IAAA;AACZ,IAAA;AACjC,IAAA;AACT,EAAA;AACqD,EAAA;AACO,EAAA;AACJ,EAAA;AACpB,EAAA;AAC7B,EAAA;AACT;AAEkI;AAC/E,EAAA;AACV,IAAA;AACK,MAAA;AACc,MAAA;AACJ,MAAA;AACpD,IAAA;AAC2C,IAAA;AACf,MAAA;AAC0C,MAAA;AACxC,MAAA;AACe,MAAA;AACE,MAAA;AAC/C,IAAA;AACiC,IAAA;AACiC,MAAA;AACzB,MAAA;AAC3B,MAAA;AACI,MAAA;AACL,MAAA;AACmB,MAAA;AACnB,MAAA;AACC,MAAA;AACqC,MAAA;AACnD,IAAA;AACD,EAAA;AACH;AHyf+D;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/docs-io.cjs","sourcesContent":[null,"/**\n * univerDocToMarkdown — the reverse of `markdown-to-univer-doc.ts`.\n *\n * Why it exists: the canvas pane for a cloud document (`udt_document`) offers a\n * `Source` tab, and the rule in `features/canvas/core/canvasSource.ts` is that\n * Source shows THE ITEM'S OWN SOURCE — for a document, its markdown — never the\n * redux envelope. A document's content lives as an opaque Univer\n * `IDocumentData` snapshot in `workbench.udt_document_snapshots`, so something\n * has to read it back out. This is that something, and it is the ONLY one:\n * never re-implement a second snapshot reader.\n *\n * What it reads (the half `markdownToUniverDoc` writes):\n * - `body.dataStream` — the text; `\\r` terminates a paragraph, a trailing\n * `\\n` terminates the section.\n * - `body.paragraphs` — one entry per `\\r` (`startIndex` = the `\\r` offset).\n * - `body.textRuns` — `{ st, ed, ts }` style overlays. `ts.bl` + a heading\n * font size is how `markdownToUniverDoc` encodes\n * `#`..`######`, so the level is recovered from `fs`.\n *\n * Fidelity is deliberately MODEST and honest: headings, bold, italic,\n * strikethrough and inline/monospace code round-trip; everything else comes\n * back as the plain text the user actually sees. A document typed by hand in\n * Univer never had markdown syntax in the first place — printing its text is\n * the truthful answer, not a reconstruction.\n *\n * PURE — no React, no Redux, no IO.\n */\n\nconst TABLE_CELL_SEP = \" | \";\n\n// Univer's DataStreamTreeTokenType control characters (literals: no Univer runtime here).\nconst TABLE_START = \"\\x1A\";\nconst TABLE_ROW_START = \"\\x1B\";\nconst TABLE_CELL_START = \"\\x1C\";\nconst TABLE_CELL_END = \"\\x1D\";\nconst TABLE_ROW_END = \"\\x0E\";\nconst TABLE_END = \"\\x0F\";\nconst LINK_START = \"\\x1F\";\nconst LINK_END = \"\\x1E\";\n\ninterface CustomRangeLike {\n startIndex?: number;\n endIndex?: number;\n rangeType?: number;\n properties?: { url?: unknown };\n}\n\n/** The Univer-native shapes (real tables, hyperlink ranges) written back as markdown. */\nfunction tableMarkdown(rows: string[][]): string[] {\n const width = Math.max(1, ...rows.map((r) => r.length));\n const cell = (r: string[], i: number) => (r[i] ?? \"\").replace(/^\\*\\*(.*)\\*\\*$/, \"$1\");\n const line = (r: string[], plain: boolean) =>\n `| ${Array.from({ length: width }, (_, i) => (plain ? cell(r, i) : (r[i] ?? \"\"))).join(\" | \")} |`;\n const out = [line(rows[0]!, true), `|${\" --- |\".repeat(width)}`];\n for (const r of rows.slice(1)) out.push(line(r, false));\n return out;\n}\n\ninterface TextRunLike {\n st?: number;\n ed?: number;\n ts?: {\n bl?: number;\n it?: number;\n ff?: string;\n fs?: number;\n st?: { s?: number } | number;\n };\n}\n\n/** Inverse of markdown-to-univer-doc's HEADING_FONT_SIZE. */\nexport const HEADING_LEVEL_BY_FONT_SIZE: Record<number, number> = {\n 26: 1,\n 22: 2,\n 18: 3,\n 16: 4,\n 14: 5,\n 13: 6,\n};\n\nfunction asArray<T>(value: unknown): T[] {\n return Array.isArray(value) ? (value as T[]) : [];\n}\n\nconst TRUE_ENOUGH = (v: unknown): boolean => v === 1 || v === true;\n\nfunction isStruck(ts: TextRunLike[\"ts\"]): boolean {\n if (!ts) return false;\n const st = ts.st;\n if (typeof st === \"number\") return TRUE_ENOUGH(st);\n return TRUE_ENOUGH(st?.s);\n}\n\n/** The style that applies to the whole paragraph, if the runs agree on one. */\nfunction paragraphHeadingLevel(runs: TextRunLike[]): number | null {\n for (const run of runs) {\n const fs = run.ts?.fs;\n if (typeof fs === \"number\" && TRUE_ENOUGH(run.ts?.bl)) {\n const level = HEADING_LEVEL_BY_FONT_SIZE[fs];\n if (level) return level;\n }\n }\n return null;\n}\n\nfunction emphasize(text: string, ts: TextRunLike[\"ts\"], inHeading: boolean): string {\n if (!text) return text;\n // Never double-mark: a heading's own runs are bold by construction.\n const leading = text.match(/^\\s*/)?.[0] ?? \"\";\n const trailing = text.match(/\\s*$/)?.[0] ?? \"\";\n let core = text.slice(leading.length, text.length - trailing.length);\n if (!core) return text;\n\n const mono = typeof ts?.ff === \"string\" && /mono/i.test(ts.ff);\n if (mono) core = `\\`${core}\\``;\n else {\n if (TRUE_ENOUGH(ts?.it)) core = `*${core}*`;\n if (TRUE_ENOUGH(ts?.bl) && !inHeading) core = `**${core}**`;\n }\n if (isStruck(ts)) core = `~~${core}~~`;\n return `${leading}${core}${trailing}`;\n}\n\n// An inline picture: one CUSTOM_BLOCK token in the stream, its drawing in `snapshot.drawings`.\nconst CUSTOM_BLOCK = \"\\b\";\n\ninterface DrawingLike {\n source?: unknown;\n title?: unknown;\n description?: unknown;\n docTransform?: { size?: { width?: unknown; height?: unknown } };\n}\n\n/**\n * A picture's markdown source. Our own pictures are `matrx-file:<id>`; the\n * drawn size rides as a `#WxH` fragment so a round trip keeps the shape.\n */\nexport function imageMarkdownSource(drawing: DrawingLike): string | null {\n const source = typeof drawing.source === \"string\" ? drawing.source : \"\";\n if (!source || source.startsWith(\"data:\")) return null;\n const w = Number(drawing.docTransform?.size?.width);\n const h = Number(drawing.docTransform?.size?.height);\n return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 && !source.includes(\"#\")\n ? `${source}#${Math.round(w)}x${Math.round(h)}`\n : source;\n}\n\n/** Every picture in a snapshot, as its markdown source (`matrx-file:<id>#WxH` or a URL). */\nexport function documentImageSources(snapshot: unknown): string[] {\n const drawings = ((snapshot as { drawings?: unknown } | null)?.drawings ?? {}) as Record<string, DrawingLike>;\n const body = (snapshot as { body?: { customBlocks?: unknown } } | null)?.body;\n return asArray<{ blockId?: unknown }>(body?.customBlocks)\n .map((b) => (typeof b.blockId === \"string\" && drawings[b.blockId] ? imageMarkdownSource(drawings[b.blockId]!) : null))\n .filter((s): s is string => !!s);\n}\n\nexport interface DocToMarkdownOptions {\n /**\n * Where a picture's markdown points. Return null to leave it out (the caller\n * names what was left out). Default: the stored source.\n */\n imageUrl?: (source: string) => string | null;\n /**\n * Backslash-escape typed text that a markdown reader would take for HTML (`<b>`, `<A22-klm>`) or an entity\n * (`&amp;`), so every renderer and exporter (PDF, Word, EPUB, HTML, print, the shared view) shows the typed text.\n * Default true. Pass false only for a consumer that treats the text as literal characters, not markdown (the\n * Google push writes the string into a Google Doc as is; an agent reading the passage; a source view).\n */\n escapeMarkup?: boolean;\n}\n\n/**\n * One typed character as markdown that renders back as the same character. Markdown readers (the print engine behind\n * PDF / Word / EPUB / HTML among them) treat `<tag>` as raw HTML and drop it, and read `&amp;` as an entity, so typed\n * text that looks like either is backslash-escaped (`\\<`, `\\&`); a plain `<` or `&` (`A < B`, `a&b`) is left alone.\n * A backslash right before one of those is doubled so it cannot swallow the escape.\n */\nfunction markdownSafeChar(stream: string, at: number): string {\n const c = stream[at]!;\n const next = stream[at + 1] ?? \"\";\n if (c === \"<\" && /[A-Za-z/!?]/.test(next)) return \"\\\\<\";\n if (c === \"&\" && /^#?\\w+;/.test(stream.slice(at + 1, at + 34))) return \"\\\\&\";\n if (c === \"\\\\\" && (next === \"<\" || next === \"&\")) return \"\\\\\\\\\";\n return c;\n}\n\n/**\n * Read a Univer document snapshot back as markdown. Returns `\"\"` for an empty\n * or unreadable snapshot so the caller can say \"no source\" honestly rather than\n * printing an envelope.\n */\nexport function univerDocToMarkdown(snapshot: unknown, options: DocToMarkdownOptions = {}): string {\n if (!snapshot || typeof snapshot !== \"object\") return \"\";\n const body = (snapshot as { body?: unknown }).body;\n if (!body || typeof body !== \"object\") return \"\";\n\n const dataStream = (body as { dataStream?: unknown }).dataStream;\n if (typeof dataStream !== \"string\" || !dataStream) return \"\";\n const escapeMarkup = options.escapeMarkup !== false;\n\n // Pictures: each CUSTOM_BLOCK token is read back as `![alt](source)`.\n const drawings = ((snapshot as { drawings?: unknown }).drawings ?? {}) as Record<string, DrawingLike>;\n const blocks = new Map<number, string>();\n for (const b of asArray<{ startIndex?: unknown; blockId?: unknown }>((body as { customBlocks?: unknown }).customBlocks)) {\n if (typeof b.startIndex !== \"number\" || typeof b.blockId !== \"string\") continue;\n const drawing = drawings[b.blockId];\n const source = drawing ? imageMarkdownSource(drawing) : null;\n if (!source || !drawing) continue;\n const url = options.imageUrl ? options.imageUrl(source) : source;\n if (!url) continue;\n const label = typeof drawing.title === \"string\" && drawing.title ? drawing.title\n : typeof drawing.description === \"string\" && drawing.description ? drawing.description : \"image\";\n blocks.set(b.startIndex, `![${label.replace(/[[\\]]/g, \"\")}](${url})`);\n }\n\n const runs = asArray<TextRunLike>((body as { textRuns?: unknown }).textRuns)\n .filter((r) => typeof r.st === \"number\" && typeof r.ed === \"number\")\n .sort((a, b) => (a.st as number) - (b.st as number));\n\n const links = new Map<number, string>();\n for (const r of asArray<CustomRangeLike>((body as { customRanges?: unknown }).customRanges)) {\n if (r.rangeType === 0 && typeof r.endIndex === \"number\" && typeof r.properties?.url === \"string\") {\n links.set(r.endIndex, r.properties.url);\n }\n }\n // A slice of the stream with its hyperlink tokens read back as `[text](url)`.\n const readSlice = (from: number, to: number): string => {\n let out = \"\";\n for (let k = from; k < to; k++) {\n const c = dataStream[k];\n if (c === LINK_START) out += \"[\";\n else if (c === LINK_END) out += `](${links.get(k) ?? \"\"})`;\n else if (c === CUSTOM_BLOCK) out += blocks.get(k) ?? \"\";\n else out += escapeMarkup ? markdownSafeChar(dataStream, k) : c;\n }\n return out;\n };\n\n const lines: string[] = [];\n let cursor = 0;\n let runIndex = 0;\n let tableRows: string[][] | null = null;\n\n // Paragraph boundaries are the `\\r`s in the stream itself — reading them from\n // the stream (rather than trusting `paragraphs`) keeps a snapshot written by\n // Univer's own editor, which may index differently, readable.\n for (let i = 0; i <= dataStream.length; i++) {\n const ch = dataStream[i];\n const atEnd = i === dataStream.length;\n if (!atEnd) {\n if (ch === TABLE_START) {\n tableRows = [];\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_ROW_START) {\n tableRows.push([]);\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_CELL_START) {\n tableRows[tableRows.length - 1]?.push(\"\");\n cursor = i + 1;\n continue;\n }\n if (tableRows && (ch === TABLE_CELL_END || ch === TABLE_ROW_END)) {\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_END) {\n if (tableRows.length) lines.push(\"\", ...tableMarkdown(tableRows), \"\");\n tableRows = null;\n cursor = i + 1;\n continue;\n }\n }\n if (!atEnd && ch !== \"\\r\" && ch !== \"\\n\") continue;\n\n const start = cursor;\n const end = i;\n cursor = i + 1;\n if (end <= start) {\n if (ch === \"\\r\" && !tableRows) lines.push(\"\");\n if (atEnd) break;\n continue;\n }\n\n // Collect the runs overlapping this paragraph.\n const paragraphRuns: TextRunLike[] = [];\n let scan = runIndex;\n while (scan < runs.length && (runs[scan]!.st as number) < end) {\n if ((runs[scan]!.ed as number) > start) paragraphRuns.push(runs[scan]!);\n scan++;\n }\n while (\n runIndex < runs.length &&\n (runs[runIndex]!.ed as number) <= end\n ) {\n runIndex++;\n }\n\n const heading = paragraphHeadingLevel(paragraphRuns);\n let text = \"\";\n let at = start;\n for (const run of paragraphRuns) {\n const rs = Math.max(run.st as number, start);\n const re = Math.min(run.ed as number, end);\n if (rs > at) text += readSlice(at, rs);\n if (re > rs) {\n text += emphasize(readSlice(rs, re), run.ts, heading != null);\n }\n at = Math.max(at, re);\n }\n if (at < end) text += readSlice(at, end);\n\n if (tableRows) {\n // A table cell: its paragraphs join into the one cell, pipes escaped.\n const row = tableRows[tableRows.length - 1];\n if (row?.length) {\n const part = text.trim().replace(/\\|/g, \"\\\\|\");\n const last = row.length - 1;\n row[last] = row[last] ? `${row[last]} ${part}` : part;\n }\n } else {\n lines.push(heading ? `${\"#\".repeat(heading)} ${text.trim()}` : text);\n }\n if (atEnd) break;\n }\n\n // Univer keeps one paragraph per visual line; markdown wants a blank line\n // between blocks (but not inside a list or a table), and consecutive blank\n // paragraphs collapse. The writer (`markdownToUniverDoc`) flattens a list item\n // to a literal \"• \" / \"1. \" prefix and a table row to cells joined by\n // TABLE_CELL_SEP, so those shapes are read back as the markdown they came from.\n type Kind = \"text\" | \"list\" | \"table\";\n const kindOf = (line: string): Kind =>\n /^\\s*(?:\\u2022|[-*+]|\\d+[.)])\\s+/.test(line) ? \"list\" : line.includes(TABLE_CELL_SEP) ? \"table\" : \"text\";\n // A document typed or pasted as markdown keeps a table as literal `| a | b |` lines, one paragraph each, often\n // with an empty paragraph between rows: those rows are ONE table, so the gaps between them close.\n const rawRow = (l: string) => /^\\s*\\|.*\\|\\s*$/.test(l);\n const rows = lines.filter((l, i) => {\n if (l.trim()) return true;\n let a = i - 1;\n while (a >= 0 && !lines[a]!.trim()) a--;\n let z = i + 1;\n while (z < lines.length && !lines[z]!.trim()) z++;\n return !(a >= 0 && z < lines.length && rawRow(lines[a]!) && rawRow(lines[z]!));\n });\n const out: string[] = [];\n let prev: Kind | null = null;\n let tableRow = 0;\n for (const raw of rows) {\n if (!raw.trim()) {\n if (out.length && out[out.length - 1] !== \"\") out.push(\"\");\n prev = null;\n continue;\n }\n let line = raw.replace(/\\s+$/, \"\");\n if (rawRow(line)) {\n if (prev !== \"table\" && out.length && out[out.length - 1] !== \"\") out.push(\"\");\n out.push(line.trim());\n prev = \"table\";\n continue;\n }\n const kind = kindOf(line);\n if (kind === \"list\") {\n line = line.replace(/^(\\s*)\\u2022\\s+/, \"$1- \").replace(/^(\\s*)\\*\\s+/, \"$1- \");\n // Four spaces per nesting level in the document; two read as nesting in markdown.\n line = line.replace(/^( +)/, (m) => \" \".repeat(Math.floor(m.length / 2)));\n }\n if (kind === \"table\") {\n const cells = line.split(/\\s*\\|\\s*/).map((c) => c.trim());\n const isHeader = prev !== \"table\";\n const shown = cells.map((c) => (isHeader ? c.replace(/^\\*\\*(.*)\\*\\*$/, \"$1\") : c));\n line = `| ${shown.join(\" | \")} |`;\n if (isHeader) tableRow = shown.length;\n out.push(...(prev === \"table\" || prev === null || !out.length || out[out.length - 1] === \"\" ? [] : [\"\"]));\n out.push(line);\n if (isHeader) out.push(`|${\" --- |\".repeat(tableRow)}`);\n prev = \"table\";\n continue;\n }\n const tight = kind === \"list\" && prev === \"list\";\n if (out.length && out[out.length - 1] !== \"\" && !tight) out.push(\"\");\n out.push(line);\n prev = kind;\n }\n return out.join(\"\\n\").trim();\n}\n","/**\n * A file from the person's computer -> a new document (Word .docx, Markdown,\n * plain text, HTML). Everything lands as markdown first and goes through THE\n * one writer (`markdownToUniverDoc`), so headings, bold, italic, links and\n * lists keep their shape. Parse first: a file we cannot read never leaves an\n * empty document behind.\n */\n\"use client\";\n\nimport { readZip } from \"@ai-matrx/alchemy/operate/zip\";\n\nimport { createDocument, saveDocumentSnapshot, deleteDocument } from \"./document-service\";\nimport { deriveDocumentName, markdownToUniverDoc } from \"./markdown-to-univer-doc\";\nimport { sanitizeUniverDocSnapshot } from \"./sanitize-univer-doc-snapshot\";\n\nexport const DOCUMENT_UPLOAD_ACCEPT = \".docx,.md,.markdown,.txt,.html,.htm\";\n\ntype Source = \"imported_docx\" | \"imported_md\" | \"imported_txt\";\n\nexport function documentFileKind(name: string): \"docx\" | \"md\" | \"txt\" | \"html\" | null {\n const ext = name.toLowerCase().split(\".\").pop() ?? \"\";\n if (ext === \"docx\") return \"docx\";\n if (ext === \"md\" || ext === \"markdown\") return \"md\";\n if (ext === \"txt\") return \"txt\";\n if (ext === \"html\" || ext === \"htm\") return \"html\";\n return null;\n}\n\nconst W = \"http://schemas.openxmlformats.org/wordprocessingml/2006/main\";\nconst R = \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\";\n\n/** Rows of cell text -> ONE markdown table block (header, delimiter, body rows together). */\nfunction markdownTable(rows: string[][]): string {\n const width = Math.max(...rows.map((r) => r.length));\n const line = (r: string[]) => `| ${Array.from({ length: width }, (_, i) => r[i] ?? \"\").join(\" | \")} |`;\n return [line(rows[0]!), `|${\" --- |\".repeat(width)}`, ...rows.slice(1).map(line)].join(\"\\n\");\n}\n\n/**\n * The parts of a .docx beside `word/document.xml` that its body points into. Each is optional: without\n * `rels` a link keeps only its words and a picture is skipped; without `numbering` every list is bulleted.\n */\nexport interface DocxParts {\n /** `word/_rels/document.xml.rels` — link addresses and picture files by relationship id. */\n rels?: string | null;\n /** `word/numbering.xml` — which lists are numbered. */\n numbering?: string | null;\n}\n\n/** Relationship id -> target. An internal target is written as its path inside the archive (`word/media/image1.png`). */\nexport function docxRelationships(rels: string | null | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!rels) return out;\n const doc = new DOMParser().parseFromString(rels, \"application/xml\");\n for (const el of Array.from(doc.getElementsByTagName(\"*\"))) {\n if (el.localName !== \"Relationship\") continue;\n const id = el.getAttribute(\"Id\");\n const target = el.getAttribute(\"Target\");\n if (!id || !target) continue;\n const external = el.getAttribute(\"TargetMode\") === \"External\" || /^[a-z][a-z0-9+.-]*:/i.test(target);\n out.set(id, external ? target : target.startsWith(\"/\") ? target.slice(1) : `word/${target}`.replace(/\\/\\.\\//g, \"/\"));\n }\n return out;\n}\n\n/** numId -> (level -> numFmt), from numbering.xml. */\nfunction docxNumbering(xml: string | null | undefined): (numId: string, level: number) => string | null {\n if (!xml) return () => null;\n const doc = new DOMParser().parseFromString(xml, \"application/xml\");\n const val = (el: Element | undefined, name: string) => el?.getAttributeNS(W, name) ?? el?.getAttribute(`w:${name}`) ?? null;\n const abstract = new Map<string, Map<number, string>>();\n for (const a of Array.from(doc.getElementsByTagNameNS(W, \"abstractNum\"))) {\n const levels = new Map<number, string>();\n for (const lvl of Array.from(a.getElementsByTagNameNS(W, \"lvl\"))) {\n const fmt = val(lvl.getElementsByTagNameNS(W, \"numFmt\")[0], \"val\");\n if (fmt) levels.set(Number(val(lvl, \"ilvl\") ?? 0), fmt);\n }\n abstract.set(val(a, \"abstractNumId\") ?? \"\", levels);\n }\n const nums = new Map<string, string>();\n for (const n of Array.from(doc.getElementsByTagNameNS(W, \"num\"))) {\n const ref = val(n.getElementsByTagNameNS(W, \"abstractNumId\")[0], \"val\");\n if (ref != null) nums.set(val(n, \"numId\") ?? \"\", ref);\n }\n return (numId, level) => abstract.get(nums.get(numId) ?? \"\")?.get(level) ?? null;\n}\n\n/**\n * Word's document.xml -> markdown: headings, bold/italic/strike runs, links (with `parts.rels`), pictures as\n * `![alt](word/media/…)` (with `parts.rels`; the caller resolves the path to a stored file), bulleted and\n * numbered list paragraphs (numbered with `parts.numbering`), tables as rows.\n */\nexport function docxXmlToMarkdown(xml: string, parts: DocxParts = {}): string {\n const doc = new DOMParser().parseFromString(xml, \"application/xml\");\n const body = doc.getElementsByTagNameNS(W, \"body\")[0];\n if (!body) throw new Error(\"This Word file has no document body.\");\n const rels = docxRelationships(parts.rels);\n const listFormat = docxNumbering(parts.numbering);\n const attr = (el: Element | undefined, name: string) => el?.getAttributeNS(W, name) ?? el?.getAttribute(`w:${name}`) ?? null;\n const first = (el: Element, name: string) => el.getElementsByTagNameNS(W, name)[0] as Element | undefined;\n const on = (props: Element | undefined, name: string) => {\n const el = props ? first(props, name) : undefined;\n return !!el && attr(el, \"val\") !== \"0\" && attr(el, \"val\") !== \"false\";\n };\n const picture = (r: Element): string => {\n const all = Array.from(r.getElementsByTagName(\"*\"));\n const blip = all.find((e) => e.localName === \"blip\");\n const id = blip?.getAttributeNS(R, \"embed\") || blip?.getAttribute(\"r:embed\") || blip?.getAttributeNS(R, \"link\") || blip?.getAttribute(\"r:link\");\n const target = id ? rels.get(id) : undefined;\n if (!target) return \"\";\n const named = all.find((e) => e.localName === \"docPr\");\n const alt = (named?.getAttribute(\"descr\") || named?.getAttribute(\"title\") || \"\").replace(/[[\\]]/g, \"\");\n return `![${alt}](${target.replace(/ /g, \"%20\")})`;\n };\n const run = (r: Element): string => {\n const t = Array.from(r.childNodes)\n .map((n) => {\n const el = n as Element;\n if (el.localName === \"t\") return el.textContent ?? \"\";\n if (el.localName === \"tab\") return \"\\t\";\n if (el.localName === \"br\") return \" \\n\";\n return \"\";\n })\n .join(\"\");\n const pic = Array.from(r.childNodes).some((n) => (n as Element).localName === \"drawing\" || (n as Element).localName === \"pict\") ? picture(r) : \"\";\n if (!t) return pic;\n const rPr = first(r, \"rPr\");\n const bold = on(rPr, \"b\");\n const italic = on(rPr, \"i\");\n const strike = on(rPr, \"strike\");\n const lead = t.match(/^\\s*/)?.[0] ?? \"\";\n const trail = t.match(/\\s*$/)?.[0] ?? \"\";\n const core = t.trim();\n if (!core) return t + pic;\n let marked = core;\n if (bold) marked = `**${marked}**`;\n if (italic) marked = `*${marked}*`;\n if (strike) marked = `~~${marked}~~`;\n return `${lead}${marked}${trail}${pic}`;\n };\n const inline = (parent: Element): string => {\n let text = \"\";\n for (const node of Array.from(parent.childNodes)) {\n const el = node as Element;\n if (el.nodeType !== 1) continue;\n if (el.localName === \"r\") text += run(el);\n else if (el.localName === \"hyperlink\") {\n const words = inline(el);\n const id = el.getAttributeNS(R, \"id\") || el.getAttribute(\"r:id\");\n const href = id ? rels.get(id) : undefined;\n const anchor = el.getAttributeNS(W, \"anchor\") || el.getAttribute(\"w:anchor\");\n text += words.trim() && (href || anchor) ? `[${words.trim()}](${href ?? `#${anchor}`})` : words;\n } else if (el.localName === \"ins\" || el.localName === \"smartTag\" || el.localName === \"sdt\" || el.localName === \"sdtContent\" || el.localName === \"fldSimple\") text += inline(el);\n }\n return text;\n };\n const paragraph = (p: Element): string => {\n const text = inline(p);\n const pPr = first(p, \"pPr\");\n const style = attr(pPr ? first(pPr, \"pStyle\") : undefined, \"val\") ?? \"\";\n const heading = style.match(/^(?:Heading|heading)\\s?(\\d)$/)?.[1] ?? (style === \"Title\" ? \"1\" : null);\n if (heading && text.trim()) return `${\"#\".repeat(Math.min(6, Number(heading)))} ${text.replace(/\\*+/g, \"\").trim()}`;\n const numPr = pPr ? first(pPr, \"numPr\") : undefined;\n if (numPr && text.trim()) {\n const level = Number(attr(first(numPr, \"ilvl\"), \"val\") ?? 0);\n const fmt = listFormat(attr(first(numPr, \"numId\"), \"val\") ?? \"\", level);\n const marker = fmt && fmt !== \"bullet\" && fmt !== \"none\" ? \"1.\" : \"-\";\n return `${\" \".repeat(level)}${marker} ${text.trim()}`;\n }\n return text;\n };\n const out: string[] = [];\n for (const child of Array.from(body.children)) {\n if (child.localName === \"p\") {\n // A figure caption under a picture (\"Figure 1: Team photo\") repeats the picture's description.\n const pPr = first(child, \"pPr\");\n const style = attr(pPr ? first(pPr, \"pStyle\") : undefined, \"val\") ?? \"\";\n if (/^caption$/i.test(style) && /^!\\[[^\\]]*\\]\\([^)]*\\)$/.test(out[out.length - 1] ?? \"\")) continue;\n out.push(paragraph(child));\n } else if (child.localName === \"tbl\") {\n const rows = Array.from(child.getElementsByTagNameNS(W, \"tr\")).map((tr) =>\n Array.from(tr.getElementsByTagNameNS(W, \"tc\")).map((tc) =>\n Array.from(tc.getElementsByTagNameNS(W, \"p\")).map(paragraph).join(\" \").replace(/\\|/g, \"\\\\|\").trim(),\n ),\n );\n // A header row drawn bold is a header row, not bold words.\n const head = rows[0];\n if (head && head.every((c) => !c || /^\\*\\*[^*]+\\*\\*$/.test(c))) rows[0] = head.map((c) => c.replace(/^\\*\\*|\\*\\*$/g, \"\"));\n if (rows.length) out.push(markdownTable(rows));\n }\n }\n // A list run stays tight; everything else is its own block.\n return out\n .reduce<string[]>((acc, line, i) => {\n const isList = (l: string | undefined) => /^\\s*(-|\\d+\\.) /.test(l ?? \"\");\n if (i > 0 && !(isList(out[i - 1]) && isList(line))) acc.push(\"\");\n acc.push(line);\n return acc;\n }, [])\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/** HTML -> markdown for the blocks a document keeps (headings, paragraphs, lists, emphasis, links). */\nexport function htmlToDocumentMarkdown(html: string): string {\n const doc = new DOMParser().parseFromString(html, \"text/html\");\n const inline = (node: Node): string => {\n if (node.nodeType === 3) return (node.textContent ?? \"\").replace(/\\s+/g, \" \");\n if (node.nodeType !== 1) return \"\";\n const el = node as Element;\n const inner = Array.from(el.childNodes).map(inline).join(\"\");\n switch (el.tagName.toLowerCase()) {\n case \"strong\":\n case \"b\":\n return inner.trim() ? `**${inner.trim()}**` : \"\";\n case \"em\":\n case \"i\":\n return inner.trim() ? `*${inner.trim()}*` : \"\";\n case \"a\": {\n const href = el.getAttribute(\"href\");\n return href && /^https?:|^mailto:/i.test(href) ? `[${inner.trim()}](${href})` : inner;\n }\n case \"br\":\n return \" \\n\";\n case \"code\":\n return `\\`${inner}\\``;\n default:\n return inner;\n }\n };\n const out: string[] = [];\n const block = (el: Element, depth = 0): void => {\n const tag = el.tagName.toLowerCase();\n const h = tag.match(/^h([1-6])$/);\n if (h) {\n out.push(`${\"#\".repeat(Number(h[1]))} ${inline(el).trim()}`);\n return;\n }\n if (tag === \"p\" || tag === \"blockquote\") {\n out.push(inline(el).trim());\n return;\n }\n if (tag === \"table\") {\n const rows = Array.from(el.querySelectorAll(\"tr\")).map((tr) =>\n Array.from(tr.children)\n .filter((c) => /^(td|th)$/i.test(c.tagName))\n .map((c) => inline(c).replace(/\\|/g, \"\\\\|\").replace(/\\s+/g, \" \").trim()),\n );\n if (rows.length) out.push(markdownTable(rows));\n return;\n }\n if (tag === \"pre\") {\n out.push(\"```\", el.textContent ?? \"\", \"```\");\n return;\n }\n if (tag === \"ul\" || tag === \"ol\") {\n Array.from(el.children).forEach((li, n) => {\n if (li.tagName.toLowerCase() !== \"li\") return;\n const own = Array.from(li.childNodes).filter((c) => !(c.nodeType === 1 && /^(ul|ol)$/i.test((c as Element).tagName)));\n out.push(`${\" \".repeat(depth)}${tag === \"ol\" ? `${n + 1}.` : \"-\"} ${own.map(inline).join(\"\").trim()}`);\n Array.from(li.children)\n .filter((c) => /^(ul|ol)$/i.test(c.tagName))\n .forEach((c) => block(c, depth + 1));\n });\n return;\n }\n if (tag === \"script\" || tag === \"style\" || tag === \"head\") return;\n const kids = Array.from(el.children);\n if (kids.length === 0) {\n const t = inline(el).trim();\n if (t) out.push(t);\n return;\n }\n kids.forEach((k) => block(k, depth));\n };\n block(doc.body);\n return out\n .map((l) => l.replace(/\\s+$/, \"\"))\n .reduce<string[]>((acc, line, i) => {\n const list = (s: string | undefined) => /^\\s*(-|\\d+\\.) /.test(s ?? \"\");\n if (i > 0 && !(list(out[i - 1]) && list(line))) acc.push(\"\");\n acc.push(line);\n return acc;\n }, [])\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport async function documentFileToMarkdown(file: File): Promise<{ markdown: string; source: Source }> {\n const kind = documentFileKind(file.name);\n if (kind === \"docx\") {\n const zip = await readZip(file);\n const entry = zip.get(\"word/document.xml\");\n if (!entry) throw new Error(\"This is not a Word document (.docx).\");\n const xml = await entry.text();\n const rels = (await zip.get(\"word/_rels/document.xml.rels\")?.text()) ?? null;\n const numbering = (await zip.get(\"word/numbering.xml\")?.text()) ?? null;\n // A picture stored inside the file has no address a Docs document can draw, so it stays out here (as\n // before); a Spaces import reads `docxXmlToMarkdown` itself and stores each picture as a file.\n const markdown = docxXmlToMarkdown(xml, { rels, numbering }).replace(/!\\[[^\\]]*\\]\\(word\\/[^)]*\\)/g, \"\");\n return { markdown, source: \"imported_docx\" };\n }\n const text = await file.text();\n if (kind === \"md\") return { markdown: text, source: \"imported_md\" };\n if (kind === \"html\") return { markdown: htmlToDocumentMarkdown(text), source: \"imported_md\" };\n if (kind === \"txt\") {\n // Plain text: each line is its own paragraph; nothing in it is read as markdown.\n const escaped = text\n .replace(/\\r\\n?/g, \"\\n\")\n .split(\"\\n\")\n .map((l) => l.replace(/([\\\\`*_[\\]#>|~])/g, \"\\\\$1\"))\n .join(\"\\n\\n\");\n return { markdown: escaped, source: \"imported_txt\" };\n }\n throw new Error(\"Upload a Word (.docx), Markdown, text or HTML file.\");\n}\n\n/** Create a document from an uploaded file; returns its id. */\nexport async function importDocumentFile(file: File, organizationId: string): Promise<{ id: string; name: string }> {\n const { markdown, source } = await documentFileToMarkdown(file);\n const name = file.name.replace(/\\.[^.]+$/, \"\").trim() || deriveDocumentName(markdown);\n const created = await createDocument({ name, source, organizationId, description: `Imported from ${file.name}` });\n if (!created.success) throw new Error(`Could not create the document: ${created.error}`);\n const id = created.data.id;\n const snapshot = sanitizeUniverDocSnapshot(markdownToUniverDoc(markdown, name), id);\n const saved = await saveDocumentSnapshot({ documentId: id, snapshot, origin: \"imported\", label: `Imported from ${file.name}` });\n if (!saved.success) {\n await deleteDocument(id);\n throw new Error(`Could not save the imported content: ${saved.error}`);\n }\n return { id, name };\n}\n","/**\n * File → Download → EPUB / OpenDocument (.odt) / Rich Text (.rtf).\n * EPUB the print package's EPUB engine, straight from the live text.\n * ODT/RTF the same engine writes the .docx, then aidream's LibreOffice route\n * (`POST /office/convert-document`) converts it. Nothing is stored.\n * Engine, converter and saver are injected so the forcing test runs the real logic.\n */\n\nimport { getDocsHost } from \"./ports\";\n\nexport type OpenFormat = \"epub\" | \"odt\" | \"rtf\";\n\nexport const OPEN_FORMATS: Record<OpenFormat, { label: string; extension: string; mime: string }> = {\n epub: { label: \"EPUB\", extension: \"epub\", mime: \"application/epub+zip\" },\n odt: { label: \"OpenDocument\", extension: \"odt\", mime: \"application/vnd.oasis.opendocument.text\" },\n rtf: { label: \"Rich Text\", extension: \"rtf\", mime: \"application/rtf\" },\n};\n\nexport interface OpenFormatDeps {\n engine: (markdown: string, format: \"docx\" | \"epub\", fileName: string) => Promise<{ bytes: Uint8Array; fileName: string }>;\n convert: (docx: Uint8Array, fileName: string, target: \"odt\" | \"rtf\") => Promise<Uint8Array>;\n save: (fileName: string, bytes: Uint8Array, mime: string) => void;\n}\n\nfunction baseName(title: string | null | undefined): string {\n const base = (title ?? \"\").replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]+/g, \" \").replace(/\\s+/g, \" \").trim().slice(0, 120);\n return base || \"document\";\n}\n\nexport async function exportOpenFormat(markdown: string, format: OpenFormat, title: string | null | undefined, deps: OpenFormatDeps): Promise<string> {\n const name = baseName(title);\n const spec = OPEN_FORMATS[format];\n const fileName = `${name}.${spec.extension}`;\n if (format === \"epub\") {\n const out = await deps.engine(markdown, \"epub\", name);\n deps.save(fileName, out.bytes, spec.mime);\n return fileName;\n }\n const docx = await deps.engine(markdown, \"docx\", name);\n const bytes = await deps.convert(docx.bytes, docx.fileName, format);\n if (!bytes.byteLength) throw new Error(`The ${spec.label} converter returned an empty file.`);\n deps.save(fileName, bytes, spec.mime);\n return fileName;\n}\n\nexport async function downloadOpenFormat(markdown: string, format: OpenFormat, title: string | null | undefined): Promise<string> {\n return exportOpenFormat(markdown, format, title, {\n engine: async (md, fmt, fileName) => {\n const { exportDocument } = await import(\"@ai-matrx/print/document\");\n const exp = await exportDocument(md, fmt, { fileName });\n return { bytes: exp.bytes, fileName: exp.fileName };\n },\n convert: async (docx, fileName, target) => {\n const form = new FormData();\n form.append(\"file\", new Blob([docx as BlobPart]), fileName.endsWith(\".docx\") ? fileName : `${fileName}.docx`);\n form.append(\"target\", target);\n const res = await getDocsHost().requestRaw(\"/office/convert-document\", { method: \"POST\", body: form });\n return new Uint8Array(await res.arrayBuffer());\n },\n save: (fileName, bytes, mime) => {\n const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: mime }));\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = fileName;\n link.rel = \"noopener\";\n document.body.appendChild(link);\n link.click();\n link.remove();\n setTimeout(() => URL.revokeObjectURL(url), 30_000);\n },\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/docs-io.cjs","../src/docs/univer-doc-to-markdown.ts","../src/docs/import-document-file.ts","../src/docs/export-open-formats.ts"],"names":["out"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACgBA,qDAA6B;AAE7B,IAAM,eAAA,EAAiB,SAAA;AAGvB,IAAM,YAAA,EAAc,GAAA;AACpB,IAAM,gBAAA,EAAkB,MAAA;AACxB,IAAM,iBAAA,EAAmB,GAAA;AACzB,IAAM,eAAA,EAAiB,GAAA;AACvB,IAAM,cAAA,EAAgB,GAAA;AACtB,IAAM,UAAA,EAAY,GAAA;AAClB,IAAM,WAAA,EAAa,GAAA;AACnB,IAAM,SAAA,EAAW,GAAA;AAUjB,SAAS,aAAA,CAAc,IAAA,EAA4B;AACjD,EAAA,MAAM,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,GAAG,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,EAAA,GAAM,CAAA,CAAE,MAAM,CAAC,CAAA;AACtD,EAAA,MAAM,KAAA,EAAO,CAAC,CAAA,EAAa,CAAA,EAAA,GAAA,kBAAe,CAAA,CAAE,CAAC,CAAA,UAAK,IAAA,CAAA,CAAI,OAAA,CAAQ,gBAAA,EAAkB,IAAI,CAAA;AACpF,EAAA,MAAM,KAAA,EAAO,CAAC,CAAA,EAAa,KAAA,EAAA,GACzB,CAAA,EAAA,EAAK,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,MAAM,CAAA,EAAG,CAAC,CAAA,EAAG,CAAA,EAAA,GAAO,MAAA,EAAQ,IAAA,CAAK,CAAA,EAAG,CAAC,EAAA,mBAAK,CAAA,CAAE,CAAC,CAAA,UAAK,IAAI,CAAA,CAAE,IAAA,CAAK,KAAK,CAAC,CAAA,EAAA,CAAA;AAC/F,EAAA,MAAM,IAAA,EAAM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AAC/C,IAAA;AACiC,IAAA;AACiC,MAAA;AACzB,MAAA;AAC3B,MAAA;AACI,MAAA;AACL,MAAA;AACmB,MAAA;AACnB,MAAA;AACC,MAAA;AACqC,MAAA;AACnD,IAAA;AACD,EAAA;AACH;AH0f+D;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/docs-io.cjs","sourcesContent":[null,"/**\n * univerDocToMarkdown — the reverse of `markdown-to-univer-doc.ts`.\n *\n * Why it exists: the canvas pane for a cloud document (`udt_document`) offers a\n * `Source` tab, and the rule in `features/canvas/core/canvasSource.ts` is that\n * Source shows THE ITEM'S OWN SOURCE — for a document, its markdown — never the\n * redux envelope. A document's content lives as an opaque Univer\n * `IDocumentData` snapshot in `workbench.udt_document_snapshots`, so something\n * has to read it back out. This is that something, and it is the ONLY one:\n * never re-implement a second snapshot reader.\n *\n * What it reads (the half `markdownToUniverDoc` writes):\n * - `body.dataStream` — the text; `\\r` terminates a paragraph, a trailing\n * `\\n` terminates the section.\n * - `body.paragraphs` — one entry per `\\r` (`startIndex` = the `\\r` offset).\n * - `body.textRuns` — `{ st, ed, ts }` style overlays. `ts.bl` + a heading\n * font size is how `markdownToUniverDoc` encodes\n * `#`..`######`, so the level is recovered from `fs`.\n *\n * Fidelity is deliberately MODEST and honest: headings, bold, italic,\n * strikethrough and inline/monospace code round-trip; everything else comes\n * back as the plain text the user actually sees. A document typed by hand in\n * Univer never had markdown syntax in the first place — printing its text is\n * the truthful answer, not a reconstruction.\n *\n * PURE — no React, no Redux, no IO.\n */\n\nimport { isPipeLedRow } from \"@ai-matrx/content-ir/source\";\n\nconst TABLE_CELL_SEP = \" | \";\n\n// Univer's DataStreamTreeTokenType control characters (literals: no Univer runtime here).\nconst TABLE_START = \"\\x1A\";\nconst TABLE_ROW_START = \"\\x1B\";\nconst TABLE_CELL_START = \"\\x1C\";\nconst TABLE_CELL_END = \"\\x1D\";\nconst TABLE_ROW_END = \"\\x0E\";\nconst TABLE_END = \"\\x0F\";\nconst LINK_START = \"\\x1F\";\nconst LINK_END = \"\\x1E\";\n\ninterface CustomRangeLike {\n startIndex?: number;\n endIndex?: number;\n rangeType?: number;\n properties?: { url?: unknown };\n}\n\n/** The Univer-native shapes (real tables, hyperlink ranges) written back as markdown. */\nfunction tableMarkdown(rows: string[][]): string[] {\n const width = Math.max(1, ...rows.map((r) => r.length));\n const cell = (r: string[], i: number) => (r[i] ?? \"\").replace(/^\\*\\*(.*)\\*\\*$/, \"$1\");\n const line = (r: string[], plain: boolean) =>\n `| ${Array.from({ length: width }, (_, i) => (plain ? cell(r, i) : (r[i] ?? \"\"))).join(\" | \")} |`;\n const out = [line(rows[0]!, true), `|${\" --- |\".repeat(width)}`];\n for (const r of rows.slice(1)) out.push(line(r, false));\n return out;\n}\n\ninterface TextRunLike {\n st?: number;\n ed?: number;\n ts?: {\n bl?: number;\n it?: number;\n ff?: string;\n fs?: number;\n st?: { s?: number } | number;\n };\n}\n\n/** Inverse of markdown-to-univer-doc's HEADING_FONT_SIZE. */\nexport const HEADING_LEVEL_BY_FONT_SIZE: Record<number, number> = {\n 26: 1,\n 22: 2,\n 18: 3,\n 16: 4,\n 14: 5,\n 13: 6,\n};\n\nfunction asArray<T>(value: unknown): T[] {\n return Array.isArray(value) ? (value as T[]) : [];\n}\n\nconst TRUE_ENOUGH = (v: unknown): boolean => v === 1 || v === true;\n\nfunction isStruck(ts: TextRunLike[\"ts\"]): boolean {\n if (!ts) return false;\n const st = ts.st;\n if (typeof st === \"number\") return TRUE_ENOUGH(st);\n return TRUE_ENOUGH(st?.s);\n}\n\n/** The style that applies to the whole paragraph, if the runs agree on one. */\nfunction paragraphHeadingLevel(runs: TextRunLike[]): number | null {\n for (const run of runs) {\n const fs = run.ts?.fs;\n if (typeof fs === \"number\" && TRUE_ENOUGH(run.ts?.bl)) {\n const level = HEADING_LEVEL_BY_FONT_SIZE[fs];\n if (level) return level;\n }\n }\n return null;\n}\n\nfunction emphasize(text: string, ts: TextRunLike[\"ts\"], inHeading: boolean): string {\n if (!text) return text;\n // Never double-mark: a heading's own runs are bold by construction.\n const leading = text.match(/^\\s*/)?.[0] ?? \"\";\n const trailing = text.match(/\\s*$/)?.[0] ?? \"\";\n let core = text.slice(leading.length, text.length - trailing.length);\n if (!core) return text;\n\n const mono = typeof ts?.ff === \"string\" && /mono/i.test(ts.ff);\n if (mono) core = `\\`${core}\\``;\n else {\n if (TRUE_ENOUGH(ts?.it)) core = `*${core}*`;\n if (TRUE_ENOUGH(ts?.bl) && !inHeading) core = `**${core}**`;\n }\n if (isStruck(ts)) core = `~~${core}~~`;\n return `${leading}${core}${trailing}`;\n}\n\n// An inline picture: one CUSTOM_BLOCK token in the stream, its drawing in `snapshot.drawings`.\nconst CUSTOM_BLOCK = \"\\b\";\n\ninterface DrawingLike {\n source?: unknown;\n title?: unknown;\n description?: unknown;\n docTransform?: { size?: { width?: unknown; height?: unknown } };\n}\n\n/**\n * A picture's markdown source. Our own pictures are `matrx-file:<id>`; the\n * drawn size rides as a `#WxH` fragment so a round trip keeps the shape.\n */\nexport function imageMarkdownSource(drawing: DrawingLike): string | null {\n const source = typeof drawing.source === \"string\" ? drawing.source : \"\";\n if (!source || source.startsWith(\"data:\")) return null;\n const w = Number(drawing.docTransform?.size?.width);\n const h = Number(drawing.docTransform?.size?.height);\n return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 && !source.includes(\"#\")\n ? `${source}#${Math.round(w)}x${Math.round(h)}`\n : source;\n}\n\n/** Every picture in a snapshot, as its markdown source (`matrx-file:<id>#WxH` or a URL). */\nexport function documentImageSources(snapshot: unknown): string[] {\n const drawings = ((snapshot as { drawings?: unknown } | null)?.drawings ?? {}) as Record<string, DrawingLike>;\n const body = (snapshot as { body?: { customBlocks?: unknown } } | null)?.body;\n return asArray<{ blockId?: unknown }>(body?.customBlocks)\n .map((b) => (typeof b.blockId === \"string\" && drawings[b.blockId] ? imageMarkdownSource(drawings[b.blockId]!) : null))\n .filter((s): s is string => !!s);\n}\n\nexport interface DocToMarkdownOptions {\n /**\n * Where a picture's markdown points. Return null to leave it out (the caller\n * names what was left out). Default: the stored source.\n */\n imageUrl?: (source: string) => string | null;\n /**\n * Backslash-escape typed text that a markdown reader would take for HTML (`<b>`, `<A22-klm>`) or an entity\n * (`&amp;`), so every renderer and exporter (PDF, Word, EPUB, HTML, print, the shared view) shows the typed text.\n * Default true. Pass false only for a consumer that treats the text as literal characters, not markdown (the\n * Google push writes the string into a Google Doc as is; an agent reading the passage; a source view).\n */\n escapeMarkup?: boolean;\n}\n\n/**\n * One typed character as markdown that renders back as the same character. Markdown readers (the print engine behind\n * PDF / Word / EPUB / HTML among them) treat `<tag>` as raw HTML and drop it, and read `&amp;` as an entity, so typed\n * text that looks like either is backslash-escaped (`\\<`, `\\&`); a plain `<` or `&` (`A < B`, `a&b`) is left alone.\n * A backslash right before one of those is doubled so it cannot swallow the escape.\n */\nfunction markdownSafeChar(stream: string, at: number): string {\n const c = stream[at]!;\n const next = stream[at + 1] ?? \"\";\n if (c === \"<\" && /[A-Za-z/!?]/.test(next)) return \"\\\\<\";\n if (c === \"&\" && /^#?\\w+;/.test(stream.slice(at + 1, at + 34))) return \"\\\\&\";\n if (c === \"\\\\\" && (next === \"<\" || next === \"&\")) return \"\\\\\\\\\";\n return c;\n}\n\n/**\n * Read a Univer document snapshot back as markdown. Returns `\"\"` for an empty\n * or unreadable snapshot so the caller can say \"no source\" honestly rather than\n * printing an envelope.\n */\nexport function univerDocToMarkdown(snapshot: unknown, options: DocToMarkdownOptions = {}): string {\n if (!snapshot || typeof snapshot !== \"object\") return \"\";\n const body = (snapshot as { body?: unknown }).body;\n if (!body || typeof body !== \"object\") return \"\";\n\n const dataStream = (body as { dataStream?: unknown }).dataStream;\n if (typeof dataStream !== \"string\" || !dataStream) return \"\";\n const escapeMarkup = options.escapeMarkup !== false;\n\n // Pictures: each CUSTOM_BLOCK token is read back as `![alt](source)`.\n const drawings = ((snapshot as { drawings?: unknown }).drawings ?? {}) as Record<string, DrawingLike>;\n const blocks = new Map<number, string>();\n for (const b of asArray<{ startIndex?: unknown; blockId?: unknown }>((body as { customBlocks?: unknown }).customBlocks)) {\n if (typeof b.startIndex !== \"number\" || typeof b.blockId !== \"string\") continue;\n const drawing = drawings[b.blockId];\n const source = drawing ? imageMarkdownSource(drawing) : null;\n if (!source || !drawing) continue;\n const url = options.imageUrl ? options.imageUrl(source) : source;\n if (!url) continue;\n const label = typeof drawing.title === \"string\" && drawing.title ? drawing.title\n : typeof drawing.description === \"string\" && drawing.description ? drawing.description : \"image\";\n blocks.set(b.startIndex, `![${label.replace(/[[\\]]/g, \"\")}](${url})`);\n }\n\n const runs = asArray<TextRunLike>((body as { textRuns?: unknown }).textRuns)\n .filter((r) => typeof r.st === \"number\" && typeof r.ed === \"number\")\n .sort((a, b) => (a.st as number) - (b.st as number));\n\n const links = new Map<number, string>();\n for (const r of asArray<CustomRangeLike>((body as { customRanges?: unknown }).customRanges)) {\n if (r.rangeType === 0 && typeof r.endIndex === \"number\" && typeof r.properties?.url === \"string\") {\n links.set(r.endIndex, r.properties.url);\n }\n }\n // A slice of the stream with its hyperlink tokens read back as `[text](url)`.\n const readSlice = (from: number, to: number): string => {\n let out = \"\";\n for (let k = from; k < to; k++) {\n const c = dataStream[k];\n if (c === LINK_START) out += \"[\";\n else if (c === LINK_END) out += `](${links.get(k) ?? \"\"})`;\n else if (c === CUSTOM_BLOCK) out += blocks.get(k) ?? \"\";\n else out += escapeMarkup ? markdownSafeChar(dataStream, k) : c;\n }\n return out;\n };\n\n const lines: string[] = [];\n let cursor = 0;\n let runIndex = 0;\n let tableRows: string[][] | null = null;\n\n // Paragraph boundaries are the `\\r`s in the stream itself — reading them from\n // the stream (rather than trusting `paragraphs`) keeps a snapshot written by\n // Univer's own editor, which may index differently, readable.\n for (let i = 0; i <= dataStream.length; i++) {\n const ch = dataStream[i];\n const atEnd = i === dataStream.length;\n if (!atEnd) {\n if (ch === TABLE_START) {\n tableRows = [];\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_ROW_START) {\n tableRows.push([]);\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_CELL_START) {\n tableRows[tableRows.length - 1]?.push(\"\");\n cursor = i + 1;\n continue;\n }\n if (tableRows && (ch === TABLE_CELL_END || ch === TABLE_ROW_END)) {\n cursor = i + 1;\n continue;\n }\n if (tableRows && ch === TABLE_END) {\n if (tableRows.length) lines.push(\"\", ...tableMarkdown(tableRows), \"\");\n tableRows = null;\n cursor = i + 1;\n continue;\n }\n }\n if (!atEnd && ch !== \"\\r\" && ch !== \"\\n\") continue;\n\n const start = cursor;\n const end = i;\n cursor = i + 1;\n if (end <= start) {\n if (ch === \"\\r\" && !tableRows) lines.push(\"\");\n if (atEnd) break;\n continue;\n }\n\n // Collect the runs overlapping this paragraph.\n const paragraphRuns: TextRunLike[] = [];\n let scan = runIndex;\n while (scan < runs.length && (runs[scan]!.st as number) < end) {\n if ((runs[scan]!.ed as number) > start) paragraphRuns.push(runs[scan]!);\n scan++;\n }\n while (\n runIndex < runs.length &&\n (runs[runIndex]!.ed as number) <= end\n ) {\n runIndex++;\n }\n\n const heading = paragraphHeadingLevel(paragraphRuns);\n let text = \"\";\n let at = start;\n for (const run of paragraphRuns) {\n const rs = Math.max(run.st as number, start);\n const re = Math.min(run.ed as number, end);\n if (rs > at) text += readSlice(at, rs);\n if (re > rs) {\n text += emphasize(readSlice(rs, re), run.ts, heading != null);\n }\n at = Math.max(at, re);\n }\n if (at < end) text += readSlice(at, end);\n\n if (tableRows) {\n // A table cell: its paragraphs join into the one cell, pipes escaped.\n const row = tableRows[tableRows.length - 1];\n if (row?.length) {\n const part = text.trim().replace(/\\|/g, \"\\\\|\");\n const last = row.length - 1;\n row[last] = row[last] ? `${row[last]} ${part}` : part;\n }\n } else {\n lines.push(heading ? `${\"#\".repeat(heading)} ${text.trim()}` : text);\n }\n if (atEnd) break;\n }\n\n // Univer keeps one paragraph per visual line; markdown wants a blank line\n // between blocks (but not inside a list or a table), and consecutive blank\n // paragraphs collapse. The writer (`markdownToUniverDoc`) flattens a list item\n // to a literal \"• \" / \"1. \" prefix and a table row to cells joined by\n // TABLE_CELL_SEP, so those shapes are read back as the markdown they came from.\n type Kind = \"text\" | \"list\" | \"table\";\n const kindOf = (line: string): Kind =>\n /^\\s*(?:\\u2022|[-*+]|\\d+[.)])\\s+/.test(line) ? \"list\" : line.includes(TABLE_CELL_SEP) ? \"table\" : \"text\";\n // A document typed or pasted as markdown keeps a table as literal `| a | b |` lines, one paragraph each, often\n // with an empty paragraph between rows: those rows are ONE table, so the gaps between them close.\n const rawRow = isPipeLedRow;\n const rows = lines.filter((l, i) => {\n if (l.trim()) return true;\n let a = i - 1;\n while (a >= 0 && !lines[a]!.trim()) a--;\n let z = i + 1;\n while (z < lines.length && !lines[z]!.trim()) z++;\n return !(a >= 0 && z < lines.length && rawRow(lines[a]!) && rawRow(lines[z]!));\n });\n const out: string[] = [];\n let prev: Kind | null = null;\n let tableRow = 0;\n for (const raw of rows) {\n if (!raw.trim()) {\n if (out.length && out[out.length - 1] !== \"\") out.push(\"\");\n prev = null;\n continue;\n }\n let line = raw.replace(/\\s+$/, \"\");\n if (rawRow(line)) {\n if (prev !== \"table\" && out.length && out[out.length - 1] !== \"\") out.push(\"\");\n out.push(line.trim());\n prev = \"table\";\n continue;\n }\n const kind = kindOf(line);\n if (kind === \"list\") {\n line = line.replace(/^(\\s*)\\u2022\\s+/, \"$1- \").replace(/^(\\s*)\\*\\s+/, \"$1- \");\n // Four spaces per nesting level in the document; two read as nesting in markdown.\n line = line.replace(/^( +)/, (m) => \" \".repeat(Math.floor(m.length / 2)));\n }\n if (kind === \"table\") {\n const cells = line.split(/\\s*\\|\\s*/).map((c) => c.trim());\n const isHeader = prev !== \"table\";\n const shown = cells.map((c) => (isHeader ? c.replace(/^\\*\\*(.*)\\*\\*$/, \"$1\") : c));\n line = `| ${shown.join(\" | \")} |`;\n if (isHeader) tableRow = shown.length;\n out.push(...(prev === \"table\" || prev === null || !out.length || out[out.length - 1] === \"\" ? [] : [\"\"]));\n out.push(line);\n if (isHeader) out.push(`|${\" --- |\".repeat(tableRow)}`);\n prev = \"table\";\n continue;\n }\n const tight = kind === \"list\" && prev === \"list\";\n if (out.length && out[out.length - 1] !== \"\" && !tight) out.push(\"\");\n out.push(line);\n prev = kind;\n }\n return out.join(\"\\n\").trim();\n}\n","/**\n * A file from the person's computer -> a new document (Word .docx, Markdown,\n * plain text, HTML). Everything lands as markdown first and goes through THE\n * one writer (`markdownToUniverDoc`), so headings, bold, italic, links and\n * lists keep their shape. Parse first: a file we cannot read never leaves an\n * empty document behind.\n */\n\"use client\";\n\nimport { readZip } from \"@ai-matrx/alchemy/operate/zip\";\n\nimport { createDocument, saveDocumentSnapshot, deleteDocument } from \"./document-service\";\nimport { deriveDocumentName, markdownToUniverDoc } from \"./markdown-to-univer-doc\";\nimport { sanitizeUniverDocSnapshot } from \"./sanitize-univer-doc-snapshot\";\n\nexport const DOCUMENT_UPLOAD_ACCEPT = \".docx,.md,.markdown,.txt,.html,.htm\";\n\ntype Source = \"imported_docx\" | \"imported_md\" | \"imported_txt\";\n\nexport function documentFileKind(name: string): \"docx\" | \"md\" | \"txt\" | \"html\" | null {\n const ext = name.toLowerCase().split(\".\").pop() ?? \"\";\n if (ext === \"docx\") return \"docx\";\n if (ext === \"md\" || ext === \"markdown\") return \"md\";\n if (ext === \"txt\") return \"txt\";\n if (ext === \"html\" || ext === \"htm\") return \"html\";\n return null;\n}\n\nconst W = \"http://schemas.openxmlformats.org/wordprocessingml/2006/main\";\nconst R = \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\";\n\n/** Rows of cell text -> ONE markdown table block (header, delimiter, body rows together). */\nfunction markdownTable(rows: string[][]): string {\n const width = Math.max(...rows.map((r) => r.length));\n const line = (r: string[]) => `| ${Array.from({ length: width }, (_, i) => r[i] ?? \"\").join(\" | \")} |`;\n return [line(rows[0]!), `|${\" --- |\".repeat(width)}`, ...rows.slice(1).map(line)].join(\"\\n\");\n}\n\n/**\n * The parts of a .docx beside `word/document.xml` that its body points into. Each is optional: without\n * `rels` a link keeps only its words and a picture is skipped; without `numbering` every list is bulleted.\n */\nexport interface DocxParts {\n /** `word/_rels/document.xml.rels` — link addresses and picture files by relationship id. */\n rels?: string | null;\n /** `word/numbering.xml` — which lists are numbered. */\n numbering?: string | null;\n}\n\n/** Relationship id -> target. An internal target is written as its path inside the archive (`word/media/image1.png`). */\nexport function docxRelationships(rels: string | null | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!rels) return out;\n const doc = new DOMParser().parseFromString(rels, \"application/xml\");\n for (const el of Array.from(doc.getElementsByTagName(\"*\"))) {\n if (el.localName !== \"Relationship\") continue;\n const id = el.getAttribute(\"Id\");\n const target = el.getAttribute(\"Target\");\n if (!id || !target) continue;\n const external = el.getAttribute(\"TargetMode\") === \"External\" || /^[a-z][a-z0-9+.-]*:/i.test(target);\n out.set(id, external ? target : target.startsWith(\"/\") ? target.slice(1) : `word/${target}`.replace(/\\/\\.\\//g, \"/\"));\n }\n return out;\n}\n\n/** numId -> (level -> numFmt), from numbering.xml. */\nfunction docxNumbering(xml: string | null | undefined): (numId: string, level: number) => string | null {\n if (!xml) return () => null;\n const doc = new DOMParser().parseFromString(xml, \"application/xml\");\n const val = (el: Element | undefined, name: string) => el?.getAttributeNS(W, name) ?? el?.getAttribute(`w:${name}`) ?? null;\n const abstract = new Map<string, Map<number, string>>();\n for (const a of Array.from(doc.getElementsByTagNameNS(W, \"abstractNum\"))) {\n const levels = new Map<number, string>();\n for (const lvl of Array.from(a.getElementsByTagNameNS(W, \"lvl\"))) {\n const fmt = val(lvl.getElementsByTagNameNS(W, \"numFmt\")[0], \"val\");\n if (fmt) levels.set(Number(val(lvl, \"ilvl\") ?? 0), fmt);\n }\n abstract.set(val(a, \"abstractNumId\") ?? \"\", levels);\n }\n const nums = new Map<string, string>();\n for (const n of Array.from(doc.getElementsByTagNameNS(W, \"num\"))) {\n const ref = val(n.getElementsByTagNameNS(W, \"abstractNumId\")[0], \"val\");\n if (ref != null) nums.set(val(n, \"numId\") ?? \"\", ref);\n }\n return (numId, level) => abstract.get(nums.get(numId) ?? \"\")?.get(level) ?? null;\n}\n\n/**\n * Word's document.xml -> markdown: headings, bold/italic/strike runs, links (with `parts.rels`), pictures as\n * `![alt](word/media/…)` (with `parts.rels`; the caller resolves the path to a stored file), bulleted and\n * numbered list paragraphs (numbered with `parts.numbering`), tables as rows.\n */\nexport function docxXmlToMarkdown(xml: string, parts: DocxParts = {}): string {\n const doc = new DOMParser().parseFromString(xml, \"application/xml\");\n const body = doc.getElementsByTagNameNS(W, \"body\")[0];\n if (!body) throw new Error(\"This Word file has no document body.\");\n const rels = docxRelationships(parts.rels);\n const listFormat = docxNumbering(parts.numbering);\n const attr = (el: Element | undefined, name: string) => el?.getAttributeNS(W, name) ?? el?.getAttribute(`w:${name}`) ?? null;\n const first = (el: Element, name: string) => el.getElementsByTagNameNS(W, name)[0] as Element | undefined;\n const on = (props: Element | undefined, name: string) => {\n const el = props ? first(props, name) : undefined;\n return !!el && attr(el, \"val\") !== \"0\" && attr(el, \"val\") !== \"false\";\n };\n const picture = (r: Element): string => {\n const all = Array.from(r.getElementsByTagName(\"*\"));\n const blip = all.find((e) => e.localName === \"blip\");\n const id = blip?.getAttributeNS(R, \"embed\") || blip?.getAttribute(\"r:embed\") || blip?.getAttributeNS(R, \"link\") || blip?.getAttribute(\"r:link\");\n const target = id ? rels.get(id) : undefined;\n if (!target) return \"\";\n const named = all.find((e) => e.localName === \"docPr\");\n const alt = (named?.getAttribute(\"descr\") || named?.getAttribute(\"title\") || \"\").replace(/[[\\]]/g, \"\");\n return `![${alt}](${target.replace(/ /g, \"%20\")})`;\n };\n const run = (r: Element): string => {\n const t = Array.from(r.childNodes)\n .map((n) => {\n const el = n as Element;\n if (el.localName === \"t\") return el.textContent ?? \"\";\n if (el.localName === \"tab\") return \"\\t\";\n if (el.localName === \"br\") return \" \\n\";\n return \"\";\n })\n .join(\"\");\n const pic = Array.from(r.childNodes).some((n) => (n as Element).localName === \"drawing\" || (n as Element).localName === \"pict\") ? picture(r) : \"\";\n if (!t) return pic;\n const rPr = first(r, \"rPr\");\n const bold = on(rPr, \"b\");\n const italic = on(rPr, \"i\");\n const strike = on(rPr, \"strike\");\n const lead = t.match(/^\\s*/)?.[0] ?? \"\";\n const trail = t.match(/\\s*$/)?.[0] ?? \"\";\n const core = t.trim();\n if (!core) return t + pic;\n let marked = core;\n if (bold) marked = `**${marked}**`;\n if (italic) marked = `*${marked}*`;\n if (strike) marked = `~~${marked}~~`;\n return `${lead}${marked}${trail}${pic}`;\n };\n const inline = (parent: Element): string => {\n let text = \"\";\n for (const node of Array.from(parent.childNodes)) {\n const el = node as Element;\n if (el.nodeType !== 1) continue;\n if (el.localName === \"r\") text += run(el);\n else if (el.localName === \"hyperlink\") {\n const words = inline(el);\n const id = el.getAttributeNS(R, \"id\") || el.getAttribute(\"r:id\");\n const href = id ? rels.get(id) : undefined;\n const anchor = el.getAttributeNS(W, \"anchor\") || el.getAttribute(\"w:anchor\");\n text += words.trim() && (href || anchor) ? `[${words.trim()}](${href ?? `#${anchor}`})` : words;\n } else if (el.localName === \"ins\" || el.localName === \"smartTag\" || el.localName === \"sdt\" || el.localName === \"sdtContent\" || el.localName === \"fldSimple\") text += inline(el);\n }\n return text;\n };\n const paragraph = (p: Element): string => {\n const text = inline(p);\n const pPr = first(p, \"pPr\");\n const style = attr(pPr ? first(pPr, \"pStyle\") : undefined, \"val\") ?? \"\";\n const heading = style.match(/^(?:Heading|heading)\\s?(\\d)$/)?.[1] ?? (style === \"Title\" ? \"1\" : null);\n if (heading && text.trim()) return `${\"#\".repeat(Math.min(6, Number(heading)))} ${text.replace(/\\*+/g, \"\").trim()}`;\n const numPr = pPr ? first(pPr, \"numPr\") : undefined;\n if (numPr && text.trim()) {\n const level = Number(attr(first(numPr, \"ilvl\"), \"val\") ?? 0);\n const fmt = listFormat(attr(first(numPr, \"numId\"), \"val\") ?? \"\", level);\n const marker = fmt && fmt !== \"bullet\" && fmt !== \"none\" ? \"1.\" : \"-\";\n return `${\" \".repeat(level)}${marker} ${text.trim()}`;\n }\n return text;\n };\n const out: string[] = [];\n for (const child of Array.from(body.children)) {\n if (child.localName === \"p\") {\n // A figure caption under a picture (\"Figure 1: Team photo\") repeats the picture's description.\n const pPr = first(child, \"pPr\");\n const style = attr(pPr ? first(pPr, \"pStyle\") : undefined, \"val\") ?? \"\";\n if (/^caption$/i.test(style) && /^!\\[[^\\]]*\\]\\([^)]*\\)$/.test(out[out.length - 1] ?? \"\")) continue;\n out.push(paragraph(child));\n } else if (child.localName === \"tbl\") {\n const rows = Array.from(child.getElementsByTagNameNS(W, \"tr\")).map((tr) =>\n Array.from(tr.getElementsByTagNameNS(W, \"tc\")).map((tc) =>\n Array.from(tc.getElementsByTagNameNS(W, \"p\")).map(paragraph).join(\" \").replace(/\\|/g, \"\\\\|\").trim(),\n ),\n );\n // A header row drawn bold is a header row, not bold words.\n const head = rows[0];\n if (head && head.every((c) => !c || /^\\*\\*[^*]+\\*\\*$/.test(c))) rows[0] = head.map((c) => c.replace(/^\\*\\*|\\*\\*$/g, \"\"));\n if (rows.length) out.push(markdownTable(rows));\n }\n }\n // A list run stays tight; everything else is its own block.\n return out\n .reduce<string[]>((acc, line, i) => {\n const isList = (l: string | undefined) => /^\\s*(-|\\d+\\.) /.test(l ?? \"\");\n if (i > 0 && !(isList(out[i - 1]) && isList(line))) acc.push(\"\");\n acc.push(line);\n return acc;\n }, [])\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/** HTML -> markdown for the blocks a document keeps (headings, paragraphs, lists, emphasis, links). */\nexport function htmlToDocumentMarkdown(html: string): string {\n const doc = new DOMParser().parseFromString(html, \"text/html\");\n const inline = (node: Node): string => {\n if (node.nodeType === 3) return (node.textContent ?? \"\").replace(/\\s+/g, \" \");\n if (node.nodeType !== 1) return \"\";\n const el = node as Element;\n const inner = Array.from(el.childNodes).map(inline).join(\"\");\n switch (el.tagName.toLowerCase()) {\n case \"strong\":\n case \"b\":\n return inner.trim() ? `**${inner.trim()}**` : \"\";\n case \"em\":\n case \"i\":\n return inner.trim() ? `*${inner.trim()}*` : \"\";\n case \"a\": {\n const href = el.getAttribute(\"href\");\n return href && /^https?:|^mailto:/i.test(href) ? `[${inner.trim()}](${href})` : inner;\n }\n case \"br\":\n return \" \\n\";\n case \"code\":\n return `\\`${inner}\\``;\n default:\n return inner;\n }\n };\n const out: string[] = [];\n const block = (el: Element, depth = 0): void => {\n const tag = el.tagName.toLowerCase();\n const h = tag.match(/^h([1-6])$/);\n if (h) {\n out.push(`${\"#\".repeat(Number(h[1]))} ${inline(el).trim()}`);\n return;\n }\n if (tag === \"p\" || tag === \"blockquote\") {\n out.push(inline(el).trim());\n return;\n }\n if (tag === \"table\") {\n const rows = Array.from(el.querySelectorAll(\"tr\")).map((tr) =>\n Array.from(tr.children)\n .filter((c) => /^(td|th)$/i.test(c.tagName))\n .map((c) => inline(c).replace(/\\|/g, \"\\\\|\").replace(/\\s+/g, \" \").trim()),\n );\n if (rows.length) out.push(markdownTable(rows));\n return;\n }\n if (tag === \"pre\") {\n out.push(\"```\", el.textContent ?? \"\", \"```\");\n return;\n }\n if (tag === \"ul\" || tag === \"ol\") {\n Array.from(el.children).forEach((li, n) => {\n if (li.tagName.toLowerCase() !== \"li\") return;\n const own = Array.from(li.childNodes).filter((c) => !(c.nodeType === 1 && /^(ul|ol)$/i.test((c as Element).tagName)));\n out.push(`${\" \".repeat(depth)}${tag === \"ol\" ? `${n + 1}.` : \"-\"} ${own.map(inline).join(\"\").trim()}`);\n Array.from(li.children)\n .filter((c) => /^(ul|ol)$/i.test(c.tagName))\n .forEach((c) => block(c, depth + 1));\n });\n return;\n }\n if (tag === \"script\" || tag === \"style\" || tag === \"head\") return;\n const kids = Array.from(el.children);\n if (kids.length === 0) {\n const t = inline(el).trim();\n if (t) out.push(t);\n return;\n }\n kids.forEach((k) => block(k, depth));\n };\n block(doc.body);\n return out\n .map((l) => l.replace(/\\s+$/, \"\"))\n .reduce<string[]>((acc, line, i) => {\n const list = (s: string | undefined) => /^\\s*(-|\\d+\\.) /.test(s ?? \"\");\n if (i > 0 && !(list(out[i - 1]) && list(line))) acc.push(\"\");\n acc.push(line);\n return acc;\n }, [])\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport async function documentFileToMarkdown(file: File): Promise<{ markdown: string; source: Source }> {\n const kind = documentFileKind(file.name);\n if (kind === \"docx\") {\n const zip = await readZip(file);\n const entry = zip.get(\"word/document.xml\");\n if (!entry) throw new Error(\"This is not a Word document (.docx).\");\n const xml = await entry.text();\n const rels = (await zip.get(\"word/_rels/document.xml.rels\")?.text()) ?? null;\n const numbering = (await zip.get(\"word/numbering.xml\")?.text()) ?? null;\n // A picture stored inside the file has no address a Docs document can draw, so it stays out here (as\n // before); a Spaces import reads `docxXmlToMarkdown` itself and stores each picture as a file.\n const markdown = docxXmlToMarkdown(xml, { rels, numbering }).replace(/!\\[[^\\]]*\\]\\(word\\/[^)]*\\)/g, \"\");\n return { markdown, source: \"imported_docx\" };\n }\n const text = await file.text();\n if (kind === \"md\") return { markdown: text, source: \"imported_md\" };\n if (kind === \"html\") return { markdown: htmlToDocumentMarkdown(text), source: \"imported_md\" };\n if (kind === \"txt\") {\n // Plain text: each line is its own paragraph; nothing in it is read as markdown.\n const escaped = text\n .replace(/\\r\\n?/g, \"\\n\")\n .split(\"\\n\")\n .map((l) => l.replace(/([\\\\`*_[\\]#>|~])/g, \"\\\\$1\"))\n .join(\"\\n\\n\");\n return { markdown: escaped, source: \"imported_txt\" };\n }\n throw new Error(\"Upload a Word (.docx), Markdown, text or HTML file.\");\n}\n\n/** Create a document from an uploaded file; returns its id. */\nexport async function importDocumentFile(file: File, organizationId: string): Promise<{ id: string; name: string }> {\n const { markdown, source } = await documentFileToMarkdown(file);\n const name = file.name.replace(/\\.[^.]+$/, \"\").trim() || deriveDocumentName(markdown);\n const created = await createDocument({ name, source, organizationId, description: `Imported from ${file.name}` });\n if (!created.success) throw new Error(`Could not create the document: ${created.error}`);\n const id = created.data.id;\n const snapshot = sanitizeUniverDocSnapshot(markdownToUniverDoc(markdown, name), id);\n const saved = await saveDocumentSnapshot({ documentId: id, snapshot, origin: \"imported\", label: `Imported from ${file.name}` });\n if (!saved.success) {\n await deleteDocument(id);\n throw new Error(`Could not save the imported content: ${saved.error}`);\n }\n return { id, name };\n}\n","/**\n * File → Download → EPUB / OpenDocument (.odt) / Rich Text (.rtf).\n * EPUB the print package's EPUB engine, straight from the live text.\n * ODT/RTF the same engine writes the .docx, then aidream's LibreOffice route\n * (`POST /office/convert-document`) converts it. Nothing is stored.\n * Engine, converter and saver are injected so the forcing test runs the real logic.\n */\n\nimport { getDocsHost } from \"./ports\";\n\nexport type OpenFormat = \"epub\" | \"odt\" | \"rtf\";\n\nexport const OPEN_FORMATS: Record<OpenFormat, { label: string; extension: string; mime: string }> = {\n epub: { label: \"EPUB\", extension: \"epub\", mime: \"application/epub+zip\" },\n odt: { label: \"OpenDocument\", extension: \"odt\", mime: \"application/vnd.oasis.opendocument.text\" },\n rtf: { label: \"Rich Text\", extension: \"rtf\", mime: \"application/rtf\" },\n};\n\nexport interface OpenFormatDeps {\n engine: (markdown: string, format: \"docx\" | \"epub\", fileName: string) => Promise<{ bytes: Uint8Array; fileName: string }>;\n convert: (docx: Uint8Array, fileName: string, target: \"odt\" | \"rtf\") => Promise<Uint8Array>;\n save: (fileName: string, bytes: Uint8Array, mime: string) => void;\n}\n\nfunction baseName(title: string | null | undefined): string {\n const base = (title ?? \"\").replace(/[\\\\/:*?\"<>|\\u0000-\\u001f]+/g, \" \").replace(/\\s+/g, \" \").trim().slice(0, 120);\n return base || \"document\";\n}\n\nexport async function exportOpenFormat(markdown: string, format: OpenFormat, title: string | null | undefined, deps: OpenFormatDeps): Promise<string> {\n const name = baseName(title);\n const spec = OPEN_FORMATS[format];\n const fileName = `${name}.${spec.extension}`;\n if (format === \"epub\") {\n const out = await deps.engine(markdown, \"epub\", name);\n deps.save(fileName, out.bytes, spec.mime);\n return fileName;\n }\n const docx = await deps.engine(markdown, \"docx\", name);\n const bytes = await deps.convert(docx.bytes, docx.fileName, format);\n if (!bytes.byteLength) throw new Error(`The ${spec.label} converter returned an empty file.`);\n deps.save(fileName, bytes, spec.mime);\n return fileName;\n}\n\nexport async function downloadOpenFormat(markdown: string, format: OpenFormat, title: string | null | undefined): Promise<string> {\n return exportOpenFormat(markdown, format, title, {\n engine: async (md, fmt, fileName) => {\n const { exportDocument } = await import(\"@ai-matrx/print/document\");\n const exp = await exportDocument(md, fmt, { fileName });\n return { bytes: exp.bytes, fileName: exp.fileName };\n },\n convert: async (docx, fileName, target) => {\n const form = new FormData();\n form.append(\"file\", new Blob([docx as BlobPart]), fileName.endsWith(\".docx\") ? fileName : `${fileName}.docx`);\n form.append(\"target\", target);\n const res = await getDocsHost().requestRaw(\"/office/convert-document\", { method: \"POST\", body: form });\n return new Uint8Array(await res.arrayBuffer());\n },\n save: (fileName, bytes, mime) => {\n const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: mime }));\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = fileName;\n link.rel = \"noopener\";\n document.body.appendChild(link);\n link.click();\n link.remove();\n setTimeout(() => URL.revokeObjectURL(url), 30_000);\n },\n });\n}\n"]}
package/dist/docs-io.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from "./chunk-Y24EYKSD.js";
12
12
 
13
13
  // src/docs/univer-doc-to-markdown.ts
14
+ import { isPipeLedRow } from "@ai-matrx/content-ir/source";
14
15
  var TABLE_CELL_SEP = " | ";
15
16
  var TABLE_START = "";
16
17
  var TABLE_ROW_START = "\x1B";
@@ -207,7 +208,7 @@ function univerDocToMarkdown(snapshot, options = {}) {
207
208
  if (atEnd) break;
208
209
  }
209
210
  const kindOf = (line) => /^\s*(?:\u2022|[-*+]|\d+[.)])\s+/.test(line) ? "list" : line.includes(TABLE_CELL_SEP) ? "table" : "text";
210
- const rawRow = (l) => /^\s*\|.*\|\s*$/.test(l);
211
+ const rawRow = isPipeLedRow;
211
212
  const rows = lines.filter((l, i) => {
212
213
  if (l.trim()) return true;
213
214
  let a = i - 1;