@ai-matrx/office 0.4.0 → 0.5.3
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 +44 -0
- package/dist/chunk-2UBGQUXW.cjs +37 -0
- package/dist/chunk-2UBGQUXW.cjs.map +1 -0
- package/dist/chunk-BWMAYLW4.cjs +272 -0
- package/dist/chunk-BWMAYLW4.cjs.map +1 -0
- package/dist/chunk-IDEA5UXK.js +272 -0
- package/dist/chunk-IDEA5UXK.js.map +1 -0
- package/dist/chunk-MPKXXZZV.js +37 -0
- package/dist/chunk-MPKXXZZV.js.map +1 -0
- package/dist/chunk-O6FTSXHE.cjs +463 -0
- package/dist/chunk-O6FTSXHE.cjs.map +1 -0
- package/dist/chunk-PI473GES.js +463 -0
- package/dist/chunk-PI473GES.js.map +1 -0
- package/dist/chunk-QZE7HBZB.cjs.map +1 -1
- package/dist/chunk-ZDZCCOUB.cjs.map +1 -1
- package/dist/docs-host.cjs +40 -0
- package/dist/docs-host.cjs.map +1 -0
- package/dist/docs-host.d.cts +28 -0
- package/dist/docs-host.d.ts +28 -0
- package/dist/docs-host.js +19 -0
- package/dist/docs-host.js.map +1 -0
- package/dist/docs-io.cjs +496 -0
- package/dist/docs-io.cjs.map +1 -0
- package/dist/docs-io.d.cts +147 -0
- package/dist/docs-io.d.ts +147 -0
- package/dist/docs-io.js +496 -0
- package/dist/docs-io.js.map +1 -0
- package/dist/docs-tools.cjs +217 -0
- package/dist/docs-tools.cjs.map +1 -0
- package/dist/docs-tools.d.cts +150 -0
- package/dist/docs-tools.d.ts +150 -0
- package/dist/docs-tools.js +217 -0
- package/dist/docs-tools.js.map +1 -0
- package/dist/docs.cjs +657 -0
- package/dist/docs.cjs.map +1 -0
- package/dist/docs.d.cts +582 -0
- package/dist/docs.d.ts +582 -0
- package/dist/docs.js +657 -0
- package/dist/docs.js.map +1 -0
- package/dist/matrxImagePorts-JDFYE4QI.cjs.map +1 -1
- package/dist/sheets-xlsx.cjs.map +1 -1
- package/dist/sheets.cjs.map +1 -1
- package/dist/univer-collab.cjs +3 -0
- package/dist/univer-collab.cjs.map +1 -1
- package/dist/univer-collab.d.cts +7 -0
- package/dist/univer-collab.d.ts +7 -0
- package/dist/univer-collab.js +3 -0
- package/dist/univer-collab.js.map +1 -1
- package/dist/xlsx-to-univer-AQAXU3TC.cjs.map +1 -1
- package/package.json +49 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.3
|
|
4
|
+
|
|
5
|
+
New `./docs/host` entry: the Docs host ports alone (`configureDocsHost`, `getDocsHost`, `DocsHostPorts`, `DocsSupabase`). It imports nothing heavy, so a start-up module can register the host without pulling the document engine (Univer, lodash-es, rxjs, mammoth) into first load. `./docs` still re-exports the same functions; both share one `globalThis` slot.
|
|
6
|
+
|
|
7
|
+
### Consumer action
|
|
8
|
+
|
|
9
|
+
Import `configureDocsHost` from `@ai-matrx/office/docs/host` in the start-up module.
|
|
10
|
+
|
|
11
|
+
## 0.5.2
|
|
12
|
+
|
|
13
|
+
No API change. The docs file-import test runs under jsdom (`jsdom` is now a dev dependency, so the isolated publish run can start its worker).
|
|
14
|
+
|
|
15
|
+
## 0.5.1
|
|
16
|
+
|
|
17
|
+
Fix: two-person Docs co-editing. Each seat mounts its own Univer unit, and a mutation carries the SENDER's unit id; replayed unchanged, the receiver threw "DocumentDataModel not found for unitId" and typed text never arrived in either direction.
|
|
18
|
+
|
|
19
|
+
- `DocumentModel` re-addresses every replay (peer edits and same-browser views) to the receiving view's own unit. `DocumentViewPort` gains optional `unitId()` (falls back to the id of `snapshot()`).
|
|
20
|
+
- A failed apply is never only a console line: `DocumentModelDeps.onApplyFailed(documentId, mutationId, error)` lets the app say so, and the model re-syncs the views from the saved version (unless this tab has unsaved edits).
|
|
21
|
+
- `WorkbookCollabSession` gets the same: optional `unitId()` re-addresses a peer's mutation, and `onApplyFailed(mutationId, error)` reports a refused apply.
|
|
22
|
+
|
|
23
|
+
## 0.5.0
|
|
24
|
+
|
|
25
|
+
W1-G4. The Docs model, service and io move in from matrx-frontend `features/documents`.
|
|
26
|
+
|
|
27
|
+
- New `./docs` entry (pure, SSR-import-safe): the document service (`createDocument`, `getLatestDocumentSnapshot`, `saveDocumentSnapshot`, `copyDocument`, ...), the open-document model (`DocumentModel`, load / one save / realtime / conflict), the `document_body` write contract (`documentBodyWriteHandler`, `planBodyEdit`; the handler type is structural, the package imports no chat), the snapshot sanitizer, symbol sets, `fitZoomRatio` and the documents hub display helpers.
|
|
28
|
+
- New `./docs/io` entry (heavy; load on demand): `markdownToUniverDoc`, `univerDocToMarkdown`, the file import `importDocumentFile` (.docx / .md / .txt / .html) and the open-format downloads (`exportOpenFormat`, `downloadOpenFormat`: EPUB, ODT, RTF).
|
|
29
|
+
- New `./docs/tools` entry: the pure insert plans (building blocks, table of contents, bookmarks) and the Univer edit operations that apply them.
|
|
30
|
+
- New host port `configureDocsHost({ getSupabase, requestRaw })`. An unconfigured port throws naming itself.
|
|
31
|
+
- Depends on `@ai-matrx/{content-ir,rich-content}` (markdown engine) and `@univerjs/docs` (dynamic import in the edit operations).
|
|
32
|
+
|
|
33
|
+
### Consumer action
|
|
34
|
+
|
|
35
|
+
Call `configureDocsHost(...)` once at start-up, in a client module. Replace `@/features/documents/{document-service,document-model/documentModel,doc-symbols,document-body-text,agent-context/documentWriteValidation,utils/*}` imports with `@ai-matrx/office/docs`; `markdown-to-univer-doc`, `univer-doc-to-markdown`, `import-document-file`, `export-open-formats` with `@ai-matrx/office/docs/io`; `doc-tools-core`, `doc-edit-ops` with `@ai-matrx/office/docs/tools`.
|
|
36
|
+
|
|
37
|
+
## 0.3.1
|
|
38
|
+
|
|
39
|
+
SOURCE CHANGED WITH NO RELEASE NOTE. This release shipped source changes that nobody described in an Unreleased entry,
|
|
40
|
+
so they may include breaking API changes. Consumer action is UNKNOWN: read the diff before upgrading.
|
|
41
|
+
Diff: `git diff ed06946f4d 696913bd94 -- apps/shared/office/src`
|
|
42
|
+
|
|
43
|
+
Changed shipped source files (1):
|
|
44
|
+
- `apps/shared/office/src/univer/collab/WorkbookCollabSession.ts`
|
|
45
|
+
|
|
3
46
|
## 0.4.0
|
|
4
47
|
|
|
5
48
|
W1-G2b. The Sheets model and io move in from matrx-frontend `features/workbooks`.
|
|
@@ -46,3 +89,4 @@ First release (W1-G1a). `/core`: editor menu model, ribbon model, Google parity
|
|
|
46
89
|
### Consumer action
|
|
47
90
|
|
|
48
91
|
Call `configureOfficeHosts(map)` at start-up before using `officeHref`. Register Coming-soon rows and the announcer through `@ai-matrx/kit/coming-soon`.
|
|
92
|
+
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/document-page-style.ts
|
|
2
|
+
var TRADITIONAL = 1;
|
|
3
|
+
var PORTRAIT = 0;
|
|
4
|
+
var PX_PER_INCH = 96;
|
|
5
|
+
var DEFAULT_DOCUMENT_PAGE_STYLE = {
|
|
6
|
+
pageSize: { width: 816, height: 1056 },
|
|
7
|
+
documentFlavor: TRADITIONAL,
|
|
8
|
+
pageOrient: PORTRAIT,
|
|
9
|
+
marginTop: PX_PER_INCH,
|
|
10
|
+
marginBottom: PX_PER_INCH,
|
|
11
|
+
marginLeft: PX_PER_INCH,
|
|
12
|
+
marginRight: PX_PER_INCH,
|
|
13
|
+
// Univer applies no paragraph spacing to a paginated page by itself; without this every paragraph
|
|
14
|
+
// runs into the next (Google Docs' own default: 1.15 lines, 10px after).
|
|
15
|
+
defaultParagraphStyle: { spaceAbove: { v: 0 }, spaceBelow: { v: 10 }, lineSpacing: 1.15 }
|
|
16
|
+
};
|
|
17
|
+
function defaultDocumentPageStyle() {
|
|
18
|
+
return {
|
|
19
|
+
...DEFAULT_DOCUMENT_PAGE_STYLE,
|
|
20
|
+
pageSize: { ...DEFAULT_DOCUMENT_PAGE_STYLE.pageSize },
|
|
21
|
+
defaultParagraphStyle: { ...DEFAULT_DOCUMENT_PAGE_STYLE.defaultParagraphStyle }
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function isLegacySqueezedPageStyle(style) {
|
|
25
|
+
const size = _optionalChain([style, 'optionalAccess', _ => _.pageSize]);
|
|
26
|
+
return !!size && size.width === 595 && size.height === 842 && _optionalChain([style, 'optionalAccess', _2 => _2.marginLeft]) === 90 && _optionalChain([style, 'optionalAccess', _3 => _3.marginRight]) === 90 && _optionalChain([style, 'optionalAccess', _4 => _4.marginTop]) === 72 && _optionalChain([style, 'optionalAccess', _5 => _5.marginBottom]) === 72;
|
|
27
|
+
}
|
|
28
|
+
var PAGE_COLORS = ["#ffffff", "#fff8e7", "#f3f3f3", "#e8f0fe", "#e6f4ea", "#fef7e0"];
|
|
29
|
+
var DEFAULT_PAGE_COLOR = PAGE_COLORS[0];
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
exports.PX_PER_INCH = PX_PER_INCH; exports.DEFAULT_DOCUMENT_PAGE_STYLE = DEFAULT_DOCUMENT_PAGE_STYLE; exports.defaultDocumentPageStyle = defaultDocumentPageStyle; exports.isLegacySqueezedPageStyle = isLegacySqueezedPageStyle;
|
|
37
|
+
//# sourceMappingURL=chunk-2UBGQUXW.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/_work/aidream/aidream/apps/shared/office/dist/chunk-2UBGQUXW.cjs","../src/core/document-page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AAW,SAAA,EAAW,SAAS,CAAA;AACrF,IAAM,mBAAA,EAAqB,WAAA,CAAY,CAAC,CAAA;ADlE/C;AACA;AACE;AACA;AACA;AACA;AACF,iOAAC","file":"/home/runner/_work/aidream/aidream/apps/shared/office/dist/chunk-2UBGQUXW.cjs","sourcesContent":[null,"/**\n * The ONE page geometry every Matrx cloud document is laid out with.\n *\n * Univer lays a document out inside `documentStyle.pageSize`. With no pageSize\n * the docs renderer has no page box at all: text never wraps (it runs off the\n * right edge) and the vertical extent is unbounded, so the docs viewport\n * reports nothing to scroll — the wheel is swallowed and the page sits frozen\n * at the top. Every writer of a Univer snapshot MUST stamp this style.\n *\n * Consumers: `DocumentEditor` (new empty doc), `markdown-to-univer-doc`\n * (markdown import), and `sanitizeUniverDocSnapshot` (recovery for snapshots\n * that reached storage without it — notably `origin='agent'` writes).\n */\nimport type { DocumentFlavor, IDocumentData, PageOrientType } from \"@univerjs/core\";\n\n// Univer's enum values, written out: this file is read by tests and the markdown importer, which must not\n// pull Univer's runtime in just for four numbers (guarded by the page-style test).\nconst TRADITIONAL = 1 as DocumentFlavor;\nconst MODERN = 2 as DocumentFlavor;\nconst PORTRAIT = 0 as PageOrientType;\nconst LANDSCAPE = 1 as PageOrientType;\n\ntype DocumentStyle = NonNullable<IDocumentData[\"documentStyle\"]>;\n\n/** Univer lays documents out in 96-dpi CSS pixels: one inch is 96 units. */\nexport const PX_PER_INCH = 96;\n\n/** Paper sizes the Page setup dialog offers, in 96-dpi pixels, portrait (width x height). */\nexport const PAPER_SIZES = {\n Letter: { width: 816, height: 1056, label: \"Letter (8.5 x 11 in)\" },\n Legal: { width: 816, height: 1344, label: \"Legal (8.5 x 14 in)\" },\n Tabloid: { width: 1056, height: 1632, label: \"Tabloid (11 x 17 in)\" },\n Executive: { width: 696, height: 1008, label: \"Executive (7.25 x 10.5 in)\" },\n Statement: { width: 528, height: 816, label: \"Statement (5.5 x 8.5 in)\" },\n A3: { width: 1123, height: 1587, label: \"A3 (11.69 x 16.54 in)\" },\n A4: { width: 794, height: 1124, label: \"A4 (8.27 x 11.69 in)\" },\n A5: { width: 559, height: 794, label: \"A5 (5.83 x 8.27 in)\" },\n} as const;\nexport type PaperSizeName = keyof typeof PAPER_SIZES;\n\n/** A real page, like Google Docs: Letter, one-inch margins (624px of text), paginated. */\nexport const DEFAULT_DOCUMENT_PAGE_STYLE: DocumentStyle = {\n pageSize: { width: 816, height: 1056 },\n documentFlavor: TRADITIONAL,\n pageOrient: PORTRAIT,\n marginTop: PX_PER_INCH,\n marginBottom: PX_PER_INCH,\n marginLeft: PX_PER_INCH,\n marginRight: PX_PER_INCH,\n // Univer applies no paragraph spacing to a paginated page by itself; without this every paragraph\n // runs into the next (Google Docs' own default: 1.15 lines, 10px after).\n defaultParagraphStyle: { spaceAbove: { v: 0 }, spaceBelow: { v: 10 }, lineSpacing: 1.15 },\n};\n\n/** Fresh copy — Univer mutates the style it is handed. */\nexport function defaultDocumentPageStyle(): DocumentStyle {\n return {\n ...DEFAULT_DOCUMENT_PAGE_STYLE,\n pageSize: { ...DEFAULT_DOCUMENT_PAGE_STYLE.pageSize! },\n defaultParagraphStyle: { ...DEFAULT_DOCUMENT_PAGE_STYLE.defaultParagraphStyle! },\n };\n}\n\n/**\n * The squeezed geometry every document was stamped with until 2026-10-15: A4 at 72 dpi (595 x 842)\n * with 90/72 margins, in Univer's pageless flavour, so the text column was ~415px with no paper.\n * Pageless was never offered then, so this exact shape is always the old default, never a choice.\n */\nexport function isLegacySqueezedPageStyle(style: DocumentStyle | undefined): boolean {\n const size = style?.pageSize;\n return (\n !!size &&\n size.width === 595 &&\n size.height === 842 &&\n style?.marginLeft === 90 &&\n style?.marginRight === 90 &&\n style?.marginTop === 72 &&\n style?.marginBottom === 72\n );\n}\n\n/** What the Page setup dialog edits. Margins are in inches, like Google's. */\nexport interface PageSetupValues {\n pageless: boolean;\n orientation: \"portrait\" | \"landscape\";\n paper: PaperSizeName;\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Paper colour, hex. Always a light colour so the black ink stays readable. */\n pageColor: string;\n}\n\nexport const PAGE_COLORS = [\"#ffffff\", \"#fff8e7\", \"#f3f3f3\", \"#e8f0fe\", \"#e6f4ea\", \"#fef7e0\"] as const;\nexport const DEFAULT_PAGE_COLOR = PAGE_COLORS[0];\n/** Key on `documentStyle` carrying the paper colour (Univer paints it from the host's surface theme). */\nexport const PAGE_COLOR_KEY = \"matrxPageColor\";\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\n/** The dialog's values, read from a document's style (missing parts fall back to the default page). */\nexport function pageSetupFromStyle(style: DocumentStyle | undefined): PageSetupValues {\n const landscape = style?.pageOrient === LANDSCAPE;\n const w = style?.pageSize?.width ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.width!;\n const h = style?.pageSize?.height ?? DEFAULT_DOCUMENT_PAGE_STYLE.pageSize!.height!;\n const [pw, ph] = landscape ? [h, w] : [w, h];\n const paper =\n (Object.keys(PAPER_SIZES) as PaperSizeName[]).find(\n (k) => Math.abs(PAPER_SIZES[k].width - pw) <= 1 && Math.abs(PAPER_SIZES[k].height - ph) <= 1,\n ) ?? \"Letter\";\n const inch = (v: number | undefined) => round2((v ?? PX_PER_INCH) / PX_PER_INCH);\n const color = (style as Record<string, unknown> | undefined)?.[PAGE_COLOR_KEY];\n return {\n pageless: style?.documentFlavor === MODERN,\n orientation: landscape ? \"landscape\" : \"portrait\",\n paper,\n marginTop: inch(style?.marginTop),\n marginBottom: inch(style?.marginBottom),\n marginLeft: inch(style?.marginLeft),\n marginRight: inch(style?.marginRight),\n pageColor: typeof color === \"string\" && color ? color : DEFAULT_PAGE_COLOR,\n };\n}\n\n/** Params for Univer's `docs.command.page-setup` (pageSize is the as-printed size: swapped when landscape). */\nexport function pageSetupCommandParams(v: PageSetupValues) {\n const base = PAPER_SIZES[v.paper];\n const landscape = v.orientation === \"landscape\";\n return {\n documentFlavor: v.pageless ? MODERN : TRADITIONAL,\n pageOrient: landscape ? LANDSCAPE : PORTRAIT,\n pageSize: landscape ? { width: base.height, height: base.width } : { width: base.width, height: base.height },\n marginTop: Math.round(v.marginTop * PX_PER_INCH),\n marginBottom: Math.round(v.marginBottom * PX_PER_INCH),\n marginLeft: Math.round(v.marginLeft * PX_PER_INCH),\n marginRight: Math.round(v.marginRight * PX_PER_INCH),\n };\n}\n"]}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunk2UBGQUXWcjs = require('./chunk-2UBGQUXW.cjs');
|
|
5
|
+
|
|
6
|
+
// src/docs/ports.ts
|
|
7
|
+
var SLOT = /* @__PURE__ */ Symbol.for("ai-matrx.office.docs-host");
|
|
8
|
+
var slot = () => {
|
|
9
|
+
const g = globalThis;
|
|
10
|
+
return g[SLOT] ??= {};
|
|
11
|
+
};
|
|
12
|
+
function configureDocsHost(ports) {
|
|
13
|
+
slot().ports = ports;
|
|
14
|
+
}
|
|
15
|
+
function getDocsHost() {
|
|
16
|
+
const ports = slot().ports;
|
|
17
|
+
if (!ports) throw new Error("@ai-matrx/office/docs: configureDocsHost(ports) was not called before the document service ran.");
|
|
18
|
+
return ports;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/docs/document-service.ts
|
|
22
|
+
var _api = require('@ai-matrx/api');
|
|
23
|
+
var _auth = require('@ai-matrx/auth');
|
|
24
|
+
var _db = require('@ai-matrx/data/db');
|
|
25
|
+
var db = () => getDocsHost().getSupabase();
|
|
26
|
+
async function createDocument(args) {
|
|
27
|
+
let organizationId;
|
|
28
|
+
try {
|
|
29
|
+
organizationId = _api.requireOrganizationContext.call(void 0, void 0, args.organizationId);
|
|
30
|
+
} catch (error2) {
|
|
31
|
+
return {
|
|
32
|
+
success: false,
|
|
33
|
+
error: error2 instanceof Error ? error2.message : "Select an organization before creating a document."
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const { data: userData, error: userErr } = await _auth.getClaimsUser.call(void 0, db());
|
|
37
|
+
if (userErr || !_optionalChain([userData, 'optionalAccess', _ => _.user])) {
|
|
38
|
+
return {
|
|
39
|
+
success: false,
|
|
40
|
+
error: _nullishCoalesce(_optionalChain([userErr, 'optionalAccess', _2 => _2.message]), () => ( "not authenticated"))
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const { data, error } = await db().schema("workbench").from("udt_documents").insert({
|
|
44
|
+
document_name: args.name,
|
|
45
|
+
description: _nullishCoalesce(args.description, () => ( null)),
|
|
46
|
+
source: _nullishCoalesce(args.source, () => ( "created")),
|
|
47
|
+
organization_id: organizationId,
|
|
48
|
+
project_id: _nullishCoalesce(args.projectId, () => ( null)),
|
|
49
|
+
task_id: _nullishCoalesce(args.taskId, () => ( null)),
|
|
50
|
+
original_file_id: _nullishCoalesce(args.originalFileId, () => ( null)),
|
|
51
|
+
// CANONICAL columns (workbench_udt_canonical_step1). `visibility` is the
|
|
52
|
+
// source of truth; the legacy `is_public` boolean is derived from it by
|
|
53
|
+
// the workbench._bridge_legacy_owner trigger, so writing both here would
|
|
54
|
+
// be two authorities for one fact. A new document defaults to `internal`
|
|
55
|
+
// — it is org work product, not an individual person's private thing
|
|
56
|
+
// (db-rules §6) — unless the caller explicitly asked for public.
|
|
57
|
+
created_by: userData.user.id,
|
|
58
|
+
visibility: args.isPublic ? "public" : "internal"
|
|
59
|
+
}).select("*").single();
|
|
60
|
+
if (error) return { success: false, error: error.message };
|
|
61
|
+
return { success: true, data };
|
|
62
|
+
}
|
|
63
|
+
async function listAccessibleDocuments() {
|
|
64
|
+
try {
|
|
65
|
+
const rows = await _db.readAllRows.call(void 0,
|
|
66
|
+
({ from, to }) => db().schema("workbench").from("udt_documents").select("*", { count: "exact" }).is("deleted_at", null).order("updated_at", { ascending: false }).order("id", { ascending: true }).range(from, to).returns(),
|
|
67
|
+
{ label: "workbench.udt_documents accessible documents" }
|
|
68
|
+
);
|
|
69
|
+
return { success: true, data: rows };
|
|
70
|
+
} catch (error) {
|
|
71
|
+
return {
|
|
72
|
+
success: false,
|
|
73
|
+
error: error instanceof Error ? error.message : String(error)
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function getDocument(documentId) {
|
|
78
|
+
const { data, error } = await db().schema("workbench").from("udt_documents").select("*").eq("id", documentId).is("deleted_at", null).maybeSingle();
|
|
79
|
+
if (error) return { success: false, error: error.message };
|
|
80
|
+
if (!data) {
|
|
81
|
+
return {
|
|
82
|
+
success: false,
|
|
83
|
+
error: "This document is in the trash or you no longer have access to it. Restore it from Trash, or ask its owner to share it again."
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
return { success: true, data };
|
|
87
|
+
}
|
|
88
|
+
async function renameDocument(documentId, name) {
|
|
89
|
+
const { data, error } = await _db.writeOneRow.call(void 0,
|
|
90
|
+
db().schema("workbench").from("udt_documents").update({ document_name: name, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", documentId).select("*"),
|
|
91
|
+
{ action: "update", noun: "document" }
|
|
92
|
+
);
|
|
93
|
+
if (error) return { success: false, error: error.message };
|
|
94
|
+
return { success: true, data };
|
|
95
|
+
}
|
|
96
|
+
async function moveDocument(documentId, projectId) {
|
|
97
|
+
const { data, error } = await _db.writeOneRow.call(void 0,
|
|
98
|
+
db().schema("workbench").from("udt_documents").update({ project_id: projectId, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", documentId).select("*"),
|
|
99
|
+
{ action: "update", noun: "document" }
|
|
100
|
+
);
|
|
101
|
+
if (error) return { success: false, error: error.message };
|
|
102
|
+
return { success: true, data };
|
|
103
|
+
}
|
|
104
|
+
async function updateDocumentDescription(documentId, description) {
|
|
105
|
+
const { data, error } = await _db.writeOneRow.call(void 0,
|
|
106
|
+
db().schema("workbench").from("udt_documents").update({
|
|
107
|
+
description: description && description.length > 0 ? description : null,
|
|
108
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
109
|
+
}).eq("id", documentId).select("*"),
|
|
110
|
+
{ action: "update", noun: "document" }
|
|
111
|
+
);
|
|
112
|
+
if (error) return { success: false, error: error.message };
|
|
113
|
+
return { success: true, data };
|
|
114
|
+
}
|
|
115
|
+
async function restoreDocument(documentId) {
|
|
116
|
+
const { error } = await _db.tryWriteOne.call(void 0,
|
|
117
|
+
db().schema("workbench").from("udt_documents").update({ deleted_at: null }).eq("id", documentId).select("id"),
|
|
118
|
+
{ action: "restore", noun: "document" }
|
|
119
|
+
);
|
|
120
|
+
if (error) return { success: false, error: error.message };
|
|
121
|
+
return { success: true, data: true };
|
|
122
|
+
}
|
|
123
|
+
async function discardFailedDocument(documentId) {
|
|
124
|
+
const { error } = await _db.tryWriteOne.call(void 0,
|
|
125
|
+
db().schema("workbench").from("udt_documents").update({ deleted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", documentId).select("id"),
|
|
126
|
+
{ action: "archive", noun: "document" }
|
|
127
|
+
);
|
|
128
|
+
if (error) return { success: false, error: error.message };
|
|
129
|
+
return { success: true, data: true };
|
|
130
|
+
}
|
|
131
|
+
async function deleteDocument(documentId) {
|
|
132
|
+
const { error } = await _db.tryWriteOne.call(void 0,
|
|
133
|
+
db().schema("workbench").from("udt_documents").update({ deleted_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", documentId).select("id"),
|
|
134
|
+
{ action: "delete", noun: "document" }
|
|
135
|
+
);
|
|
136
|
+
if (error) return { success: false, error: error.message };
|
|
137
|
+
return { success: true, data: true };
|
|
138
|
+
}
|
|
139
|
+
async function getLatestDocumentSnapshot(documentId) {
|
|
140
|
+
const { data, error } = await db().schema("workbench").from("udt_document_snapshots").select("*").eq("document_id", documentId).order("created_at", { ascending: false }).limit(1).maybeSingle();
|
|
141
|
+
if (error) return { success: false, error: error.message };
|
|
142
|
+
return { success: true, data: _nullishCoalesce(data, () => ( null)) };
|
|
143
|
+
}
|
|
144
|
+
async function saveDocumentSnapshot(args) {
|
|
145
|
+
const { data: userData } = await _auth.getClaimsUser.call(void 0, db());
|
|
146
|
+
const { data, error } = await db().schema("workbench").from("udt_document_snapshots").insert({
|
|
147
|
+
document_id: args.documentId,
|
|
148
|
+
snapshot: args.snapshot,
|
|
149
|
+
label: _nullishCoalesce(args.label, () => ( null)),
|
|
150
|
+
origin: _nullishCoalesce(args.origin, () => ( "autosave")),
|
|
151
|
+
created_by: _nullishCoalesce(_optionalChain([userData, 'optionalAccess', _3 => _3.user, 'optionalAccess', _4 => _4.id]), () => ( null))
|
|
152
|
+
}).select("*").single();
|
|
153
|
+
if (error) return { success: false, error: error.message };
|
|
154
|
+
await db().schema("workbench").from("udt_documents").update({ updated_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", args.documentId);
|
|
155
|
+
return { success: true, data };
|
|
156
|
+
}
|
|
157
|
+
async function copyDocument(documentId, name) {
|
|
158
|
+
const original = await getDocument(documentId);
|
|
159
|
+
if (!original.success) return original;
|
|
160
|
+
const row = original.data;
|
|
161
|
+
if (!row.organization_id) {
|
|
162
|
+
return { success: false, error: "This document has no organization and cannot be copied." };
|
|
163
|
+
}
|
|
164
|
+
const created = await createDocument({
|
|
165
|
+
name: _nullishCoalesce(name, () => ( row.document_name)),
|
|
166
|
+
description: _nullishCoalesce(row.description, () => ( null)),
|
|
167
|
+
organizationId: row.organization_id,
|
|
168
|
+
projectId: _nullishCoalesce(row.project_id, () => ( null)),
|
|
169
|
+
isPublic: row.visibility === "public"
|
|
170
|
+
});
|
|
171
|
+
if (!created.success) return created;
|
|
172
|
+
const latest = await getLatestDocumentSnapshot(documentId);
|
|
173
|
+
if (!latest.success) return latest;
|
|
174
|
+
if (latest.data) {
|
|
175
|
+
const saved = await saveDocumentSnapshot({
|
|
176
|
+
documentId: created.data.id,
|
|
177
|
+
snapshot: latest.data.snapshot,
|
|
178
|
+
label: latest.data.label,
|
|
179
|
+
origin: "autosave"
|
|
180
|
+
});
|
|
181
|
+
if (!saved.success) return saved;
|
|
182
|
+
}
|
|
183
|
+
return created;
|
|
184
|
+
}
|
|
185
|
+
async function listTrashedDocuments() {
|
|
186
|
+
const { data, error } = await db().schema("workbench").from("udt_documents").select("*").not("deleted_at", "is", null).order("deleted_at", { ascending: false });
|
|
187
|
+
if (error) return { success: false, error: error.message };
|
|
188
|
+
return { success: true, data: _nullishCoalesce(data, () => ( [])) };
|
|
189
|
+
}
|
|
190
|
+
async function listDocumentSnapshots(documentId, limit = 50) {
|
|
191
|
+
const { data, error } = await db().schema("workbench").from("udt_document_snapshots").select("id, document_id, label, origin, created_by, created_at").eq("document_id", documentId).order("created_at", { ascending: false }).limit(limit);
|
|
192
|
+
if (error) return { success: false, error: error.message };
|
|
193
|
+
return { success: true, data: _nullishCoalesce(data, () => ( [])) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/docs/sanitize-univer-doc-snapshot.ts
|
|
197
|
+
var _core = require('@univerjs/core');
|
|
198
|
+
var NAMED_STYLE_STRING_TO_NUMBER = Object.fromEntries(
|
|
199
|
+
Object.entries(_core.NamedStyleType).filter(([key, val]) => typeof val === "number" && isNaN(Number(key))).map(([key, val]) => [key, val])
|
|
200
|
+
);
|
|
201
|
+
function sanitizeUniverDocSnapshot(snapshot, docId) {
|
|
202
|
+
restorePageStyle(snapshot, docId);
|
|
203
|
+
const paragraphs = _optionalChain([snapshot, 'optionalAccess', _5 => _5.body, 'optionalAccess', _6 => _6.paragraphs]);
|
|
204
|
+
if (!Array.isArray(paragraphs)) return snapshot;
|
|
205
|
+
let fixed = 0;
|
|
206
|
+
for (const paragraph of paragraphs) {
|
|
207
|
+
const style = _optionalChain([paragraph, 'optionalAccess', _7 => _7.paragraphStyle]);
|
|
208
|
+
const value = _optionalChain([style, 'optionalAccess', _8 => _8.namedStyleType]);
|
|
209
|
+
if (typeof value === "string") {
|
|
210
|
+
const numeric = NAMED_STYLE_STRING_TO_NUMBER[value];
|
|
211
|
+
if (numeric !== void 0) {
|
|
212
|
+
style.namedStyleType = numeric;
|
|
213
|
+
fixed += 1;
|
|
214
|
+
} else {
|
|
215
|
+
delete style.namedStyleType;
|
|
216
|
+
fixed += 1;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (fixed > 0) {
|
|
221
|
+
console.warn(
|
|
222
|
+
`[data-tables] RECOVERY: sanitized ${fixed} string namedStyleType value(s) to numeric NamedStyleType in document snapshot${docId ? ` ${docId}` : ""}. The snapshot was written with the wrong enum encoding (string instead of number) and would have crashed Univer's <ParagraphMenu>. Fix the snapshot writer to emit numeric NamedStyleType values.`
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return snapshot;
|
|
226
|
+
}
|
|
227
|
+
function restorePageStyle(snapshot, docId) {
|
|
228
|
+
if (!snapshot || typeof snapshot !== "object") return;
|
|
229
|
+
const style = snapshot.documentStyle;
|
|
230
|
+
if (_optionalChain([style, 'optionalAccess', _9 => _9.pageSize, 'optionalAccess', _10 => _10.width]) && _chunk2UBGQUXWcjs.isLegacySqueezedPageStyle.call(void 0, style)) {
|
|
231
|
+
const page = _chunk2UBGQUXWcjs.defaultDocumentPageStyle.call(void 0, );
|
|
232
|
+
snapshot.documentStyle = { ...style, ...page, defaultParagraphStyle: _nullishCoalesce(style.defaultParagraphStyle, () => ( page.defaultParagraphStyle)) };
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (_optionalChain([style, 'optionalAccess', _11 => _11.pageSize, 'optionalAccess', _12 => _12.width])) {
|
|
236
|
+
if (!style.documentFlavor) {
|
|
237
|
+
const page = _chunk2UBGQUXWcjs.defaultDocumentPageStyle.call(void 0, );
|
|
238
|
+
Object.assign(style, { documentFlavor: page.documentFlavor });
|
|
239
|
+
if (page.defaultParagraphStyle) style.defaultParagraphStyle ??= page.defaultParagraphStyle;
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
snapshot.documentStyle = {
|
|
244
|
+
..._chunk2UBGQUXWcjs.defaultDocumentPageStyle.call(void 0, ),
|
|
245
|
+
..._nullishCoalesce(snapshot.documentStyle, () => ( {})),
|
|
246
|
+
pageSize: _chunk2UBGQUXWcjs.defaultDocumentPageStyle.call(void 0, ).pageSize
|
|
247
|
+
};
|
|
248
|
+
console.warn(
|
|
249
|
+
`[data-tables] RECOVERY: document snapshot${docId ? ` ${docId}` : ""} had no documentStyle.pageSize \u2014 restored the default Letter page geometry. Without a page box Univer lays the body out unbounded: text does not wrap and the viewport has no scrollable extent, so the document appears frozen. Fix the snapshot writer (agent/markdown converters must stamp DEFAULT_DOCUMENT_PAGE_STYLE).`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
exports.configureDocsHost = configureDocsHost; exports.getDocsHost = getDocsHost; exports.createDocument = createDocument; exports.listAccessibleDocuments = listAccessibleDocuments; exports.getDocument = getDocument; exports.renameDocument = renameDocument; exports.moveDocument = moveDocument; exports.updateDocumentDescription = updateDocumentDescription; exports.restoreDocument = restoreDocument; exports.discardFailedDocument = discardFailedDocument; exports.deleteDocument = deleteDocument; exports.getLatestDocumentSnapshot = getLatestDocumentSnapshot; exports.saveDocumentSnapshot = saveDocumentSnapshot; exports.copyDocument = copyDocument; exports.listTrashedDocuments = listTrashedDocuments; exports.listDocumentSnapshots = listDocumentSnapshots; exports.sanitizeUniverDocSnapshot = sanitizeUniverDocSnapshot;
|
|
272
|
+
//# sourceMappingURL=chunk-BWMAYLW4.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/_work/aidream/aidream/apps/shared/office/dist/chunk-BWMAYLW4.cjs","../src/docs/ports.ts","../src/docs/document-service.ts","../src/docs/sanitize-univer-doc-snapshot.ts"],"names":["error"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACiBA,IAAM,KAAA,kBAAO,MAAA,CAAO,GAAA,CAAI,2BAA2B,CAAA;AAEnD,IAAM,KAAA,EAAO,CAAA,EAAA,GAAY;AACvB,EAAA,MAAM,EAAA,EAAI,UAAA;AACV,EAAA,OAAQ,CAAA,CAAE,IAAI,EAAA,IAAM,CAAC,CAAA;AACvB,CAAA;AAEO,SAAS,iBAAA,CAAkB,KAAA,EAA4B;AAC5D,EAAA,IAAA,CAAK,CAAA,CAAE,MAAA,EAAQ,KAAA;AACjB;AAEO,SAAS,WAAA,CAAA,EAA6B;AAC3C,EAAA,MAAM,MAAA,EAAQ,IAAA,CAAK,CAAA,CAAE,KAAA;AACrB,EAAA,GAAA,CAAI,CAAC,KAAA,EAAO,MAAM,IAAI,KAAA,CAAM,iGAAiG,CAAA;AAC7H,EAAA,OAAO,KAAA;AACT;ADlBA;AACA;AEFA,oCAA2C;AAC3C,sCAA8B;AAC9B,uCAAsD;AAOtD,IAAM,GAAA,EAAK,CAAA,EAAA,GAAM,WAAA,CAAY,CAAA,CAAE,WAAA,CAAY,CAAA;AAoB3C,MAAA,SAAsB,cAAA,CACpB,IAAA,EACqC;AACrC,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI;AACF,IAAA,eAAA,EAAiB,6CAAA,KAA2B,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,CAAA,kCAAA,EAAqC,KAAK,CAAA,8EAAA,EACS,MAAA,EAAQ,CAAA,CAAA,EAAI,KAAK,CAAA,EAAA;AAItE,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAU4E;AAC3B,EAAA;AAKxB,EAAA;AACyC,EAAA;AACxB,IAAA;AACyF,IAAA;AAC/H,IAAA;AACF,EAAA;AAC4B,EAAA;AACC,IAAA;AACa,MAAA;AACsB,MAAA;AACS,MAAA;AACvE,IAAA;AACA,IAAA;AACF,EAAA;AAEyB,EAAA;AACK,IAAA;AACG,IAAA;AACM,IAAA;AACvC,EAAA;AAEQ,EAAA;AAC8D,IAAA;AAMtE,EAAA;AACF;AHiHmJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/_work/aidream/aidream/apps/shared/office/dist/chunk-BWMAYLW4.cjs","sourcesContent":[null,"/**\n * The host ports of the Docs model and io.\n *\n * The package owns the document service, the open-document model and the converters, but two things\n * belong to the app that mounts them: the database client (a package owns no client) and the server\n * request that converts a .docx to .odt / .rtf (the app owns the server URL, auth and error capture).\n * The host states them once at start-up with `configureDocsHost`. State sits on a `globalThis` slot\n * so a dual-bundled copy of the package still sees one host. An unconfigured port THROWS naming\n * itself (nothing fails silently).\n */\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\n\n/** A Supabase client over any schema: the package cannot import the app's generated database types. */\nexport type DocsSupabase = SupabaseClient<any, any, any>;\n\nexport interface DocsHostPorts {\n /** The app's database client (signed in as the person). */\n getSupabase(): DocsSupabase;\n /** An authenticated request to the Matrx server returning the raw `Response` (the open-format converter). */\n requestRaw(path: string, init: { method: \"POST\"; body: FormData }): Promise<Response>;\n}\n\nconst SLOT = Symbol.for(\"ai-matrx.office.docs-host\");\ntype Slot = { ports?: DocsHostPorts };\nconst slot = (): Slot => {\n const g = globalThis as Record<symbol, Slot | undefined>;\n return (g[SLOT] ??= {});\n};\n\nexport function configureDocsHost(ports: DocsHostPorts): void {\n slot().ports = ports;\n}\n\nexport function getDocsHost(): DocsHostPorts {\n const ports = slot().ports;\n if (!ports) throw new Error(\"@ai-matrx/office/docs: configureDocsHost(ports) was not called before the document service ran.\");\n return ports;\n}\n","/**\n * Document service — typed wrappers for `udt_documents` + `udt_document_snapshots`.\n *\n * Cloud document editor backed by Univer's preset-docs-core. Same shape as\n * `workbook-service.ts` — metadata in `udt_documents`, content state in\n * append-only `udt_document_snapshots`. The editor hydrates from the LATEST\n * snapshot and writes a new snapshot per save (debounced on the client —\n * see DocumentEditor).\n *\n * What lives elsewhere:\n * - Sharing / permissions: features/sharing/ + `has_permission(...)` RLS\n * - The open document (one model per id per tab: load, one save, realtime,\n * collab): features/documents/document-model/\n * - Component (a view of that model): features/documents/components/DocumentEditor\n *\n * Mirrors `workbook-service.ts`. If you're changing the shape of one, change\n * the other at the same time — see `features/data-tables/FEATURE.md`.\n */\nimport { requireOrganizationContext } from \"@ai-matrx/api\";\nimport { getClaimsUser } from \"@ai-matrx/auth\";\nimport { readAllRows, tryWriteOne, writeOneRow } from \"@ai-matrx/data/db\";\nimport type { ServiceResult } from \"@ai-matrx/records/core\";\n\nimport type { DocumentRow, DocumentSnapshot, DocumentSnapshotOrigin } from \"../core\";\nimport { getDocsHost } from \"./ports\";\n\n/** The app's database client, read through the host port at call time. */\nconst db = () => getDocsHost().getSupabase();\n// ─── documents ───────────────────────────────────────────────────────────────\n\nexport type CreateDocumentArgs = {\n name: string;\n description?: string | null;\n /** Origin label for the document itself, mirrors `udt_documents.source`. */\n source?: \"created\" | \"imported_docx\" | \"imported_md\" | \"imported_txt\" | \"linked_gdoc\";\n organizationId: string;\n projectId?: string | null;\n taskId?: string | null;\n isPublic?: boolean;\n /**\n * cld_files.id of the source upload (DOCX / MD / TXT blob). Set on the\n * import flow so the lossless original is recoverable; FK is ON DELETE SET\n * NULL, so deleting the file just nulls the link — the document survives.\n */\n originalFileId?: string | null;\n};\n\nexport async function createDocument(\n args: CreateDocumentArgs,\n): Promise<ServiceResult<DocumentRow>> {\n let organizationId: string;\n try {\n organizationId = requireOrganizationContext(undefined, args.organizationId);\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error\n ? error.message\n : \"Select an organization before creating a document.\",\n };\n }\n\n const { data: userData, error: userErr } = await getClaimsUser(db());\n if (userErr || !userData?.user) {\n return {\n success: false,\n error: userErr?.message ?? \"not authenticated\",\n };\n }\n\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .insert({\n document_name: args.name,\n description: args.description ?? null,\n source: args.source ?? \"created\",\n organization_id: organizationId,\n project_id: args.projectId ?? null,\n task_id: args.taskId ?? null,\n original_file_id: args.originalFileId ?? null,\n // CANONICAL columns (workbench_udt_canonical_step1). `visibility` is the\n // source of truth; the legacy `is_public` boolean is derived from it by\n // the workbench._bridge_legacy_owner trigger, so writing both here would\n // be two authorities for one fact. A new document defaults to `internal`\n // — it is org work product, not an individual person's private thing\n // (db-rules §6) — unless the caller explicitly asked for public.\n created_by: userData.user.id,\n visibility: args.isPublic ? \"public\" : \"internal\",\n })\n .select(\"*\")\n .single();\n if (error) return { success: false, error: error.message };\n return { success: true, data: data as DocumentRow };\n}\n\nexport async function listAccessibleDocuments(): Promise<\n ServiceResult<DocumentRow[]>\n> {\n // RLS handles owner / published-to-the-web / shared access. The library and\n // the pickers treat this list as COMPLETE (\"you have no such document\"), so\n // it pages past PostgREST's silent 1000-row cap (D190).\n try {\n const rows = await readAllRows<DocumentRow>(\n ({ from, to }) =>\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .select(\"*\", { count: \"exact\" })\n .is(\"deleted_at\", null)\n .order(\"updated_at\", { ascending: false })\n .order(\"id\", { ascending: true })\n .range(from, to)\n .returns<DocumentRow[]>(),\n { label: \"workbench.udt_documents accessible documents\" },\n );\n return { success: true, data: rows };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport async function getDocument(\n documentId: string,\n): Promise<ServiceResult<DocumentRow>> {\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .select(\"*\")\n .eq(\"id\", documentId)\n .is(\"deleted_at\", null)\n .maybeSingle();\n if (error) return { success: false, error: error.message };\n if (!data) {\n // A trashed or unreachable document is a state the person can act on,\n // never PostgREST's \"Cannot coerce the result to a single JSON object\".\n return {\n success: false,\n error:\n \"This document is in the trash or you no longer have access to it. Restore it from Trash, or ask its owner to share it again.\",\n };\n }\n return { success: true, data: data as DocumentRow };\n}\n\nexport async function renameDocument(\n documentId: string,\n name: string,\n): Promise<ServiceResult<DocumentRow>> {\n const { data, error } = await writeOneRow(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ document_name: name, updated_at: new Date().toISOString() })\n .eq(\"id\", documentId)\n .select(\"*\"),\n { action: \"update\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: data as DocumentRow };\n}\n\n/**\n * Move the document into a project (or out of one with `null`). Sibling of\n * `renameDocument`: the one named setter for `project_id`.\n */\nexport async function moveDocument(\n documentId: string,\n projectId: string | null,\n): Promise<ServiceResult<DocumentRow>> {\n const { data, error } = await writeOneRow(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ project_id: projectId, updated_at: new Date().toISOString() })\n .eq(\"id\", documentId)\n .select(\"*\"),\n { action: \"update\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: data as DocumentRow };\n}\n\n/**\n * Rewrite the document's description. Sibling of `renameDocument` — the two\n * human-authored fields on `udt_documents` each get a named setter so callers\n * never hand-roll a `.from(\"udt_documents\").update(...)`. Pass `null` (or an\n * empty string) to clear it.\n *\n * Added when the documents surface became agent-writable: the\n * `document_description` write target on `/documents/[id]` is its caller, the\n * same way `updateWorkbookDescription` serves `workbook_description`. Keeping\n * the pair symmetric is this file's standing contract with `workbook-service`\n * (see the module header).\n */\nexport async function updateDocumentDescription(\n documentId: string,\n description: string | null,\n): Promise<ServiceResult<DocumentRow>> {\n const { data, error } = await writeOneRow(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({\n description: description && description.length > 0 ? description : null,\n updated_at: new Date().toISOString(),\n })\n .eq(\"id\", documentId)\n .select(\"*\"),\n { action: \"update\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: data as DocumentRow };\n}\n\n/**\n * Soft delete — the document is tombstoned, not destroyed, and its snapshots stay\n * with it. Every read path filters `deleted_at is null`. Pair with\n * restoreDocument for undo. (aidream migration 0458.)\n */\nexport async function restoreDocument(\n documentId: string,\n): Promise<ServiceResult<true>> {\n const { error } = await tryWriteOne(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ deleted_at: null })\n .eq(\"id\", documentId)\n .select(\"id\"),\n { action: \"restore\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: true };\n}\n\n/**\n * Archive (delete means archive: never a hard delete) — only for rolling back a document this very flow just created and\n * failed to populate. Never use for a user-initiated delete: that is\n * deleteDocument, which tombstones and stays recoverable.\n */\nexport async function discardFailedDocument(\n documentId: string,\n): Promise<ServiceResult<true>> {\n const { error } = await tryWriteOne(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ deleted_at: new Date().toISOString() })\n .eq(\"id\", documentId)\n .select(\"id\"),\n { action: \"archive\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: true };\n}\n\nexport async function deleteDocument(\n documentId: string,\n): Promise<ServiceResult<true>> {\n const { error } = await tryWriteOne(\n db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ deleted_at: new Date().toISOString() })\n .eq(\"id\", documentId)\n .select(\"id\"),\n { action: \"delete\", noun: \"document\" },\n );\n if (error) return { success: false, error: error.message };\n return { success: true, data: true };\n}\n\n// ─── snapshots (document content) ────────────────────────────────────────────\n\n/**\n * Latest-snapshot fetch — what an opened document hydrates from. Returns\n * `data: null` (success path) when the document has no snapshots yet (newly\n * created, never saved). Distinguish \"no snapshot\" from \"load error\" by\n * checking `result.data === null`.\n */\nexport async function getLatestDocumentSnapshot(\n documentId: string,\n): Promise<ServiceResult<DocumentSnapshot | null>> {\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_document_snapshots\")\n .select(\"*\")\n .eq(\"document_id\", documentId)\n .order(\"created_at\", { ascending: false })\n .limit(1)\n .maybeSingle();\n if (error) return { success: false, error: error.message };\n return { success: true, data: (data ?? null) as DocumentSnapshot | null };\n}\n\nexport type SaveDocumentSnapshotArgs = {\n documentId: string;\n snapshot: unknown; // opaque to us — Univer IDocumentData decides the shape\n label?: string | null;\n origin?: DocumentSnapshotOrigin;\n};\n\nexport async function saveDocumentSnapshot(\n args: SaveDocumentSnapshotArgs,\n): Promise<ServiceResult<DocumentSnapshot>> {\n const { data: userData } = await getClaimsUser(db());\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_document_snapshots\")\n .insert({\n document_id: args.documentId,\n snapshot: args.snapshot as never,\n label: args.label ?? null,\n origin: args.origin ?? \"autosave\",\n created_by: userData?.user?.id ?? null,\n })\n .select(\"*\")\n .single();\n if (error) return { success: false, error: error.message };\n\n // Touch the parent document's updated_at so list views can sort by recency\n // without scanning snapshots. Best-effort — failure here is harmless.\n // write-lands-exempt: best-effort recency stamp on the parent document; the snapshot insert above is the real write\n await db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .update({ updated_at: new Date().toISOString() })\n .eq(\"id\", args.documentId);\n\n return { success: true, data: data as DocumentSnapshot };\n}\n\n/**\n * An independent copy of a document: its own row, with the latest snapshot copied over, so editing the copy never\n * touches the original. The copy lives in the original's organization and project. Used by a board-template use.\n */\nexport async function copyDocument(\n documentId: string,\n name?: string,\n): Promise<ServiceResult<DocumentRow>> {\n const original = await getDocument(documentId);\n if (!original.success) return original;\n const row = original.data;\n if (!row.organization_id) {\n return { success: false, error: \"This document has no organization and cannot be copied.\" };\n }\n const created = await createDocument({\n name: name ?? row.document_name,\n description: row.description ?? null,\n organizationId: row.organization_id,\n projectId: row.project_id ?? null,\n isPublic: row.visibility === \"public\",\n });\n if (!created.success) return created;\n const latest = await getLatestDocumentSnapshot(documentId);\n if (!latest.success) return latest;\n if (latest.data) {\n const saved = await saveDocumentSnapshot({\n documentId: created.data.id,\n snapshot: latest.data.snapshot,\n label: latest.data.label,\n origin: \"autosave\",\n });\n if (!saved.success) return saved;\n }\n return created;\n}\n\n/** Trash view: the caller's own archived documents (RLS decides what is readable). */\nexport async function listTrashedDocuments(): Promise<\n ServiceResult<DocumentRow[]>\n> {\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_documents\")\n .select(\"*\")\n .not(\"deleted_at\", \"is\", null)\n .order(\"deleted_at\", { ascending: false });\n if (error) return { success: false, error: error.message };\n return { success: true, data: (data ?? []) as DocumentRow[] };\n}\n\nexport async function listDocumentSnapshots(\n documentId: string,\n limit = 50,\n): Promise<ServiceResult<DocumentSnapshot[]>> {\n const { data, error } = await db()\n .schema(\"workbench\")\n .from(\"udt_document_snapshots\")\n // component-created-by-ok: append-only snapshot with NO updated_by column and NO parent-rewrite trigger — created_by is the author the client wrote at insert (the only person field this table has)\n .select(\"id, document_id, label, origin, created_by, created_at\")\n .eq(\"document_id\", documentId)\n .order(\"created_at\", { ascending: false })\n .limit(limit);\n if (error) return { success: false, error: error.message };\n return { success: true, data: (data ?? []) as DocumentSnapshot[] };\n}\n","/**\n * sanitizeUniverDocSnapshot — defensive normalizer for Univer document\n * snapshots loaded from storage.\n *\n * WHY THIS EXISTS (loud recovery layer):\n * Univer's `NamedStyleType` is a NUMERIC enum (`HEADING_1 = 4`, `HEADING_2 = 5`,\n * …). Some snapshots in storage were produced by an external markdown→Univer\n * converter that wrote the *string* name (`\"HEADING_1\"`) into\n * `paragraphStyle.namedStyleType` instead of the numeric value. At render time\n * Univer does `HEADING_ICON_MAP[namedStyleType]` → `undefined` →\n * `icon.key` throws `Cannot read properties of undefined (reading 'key')` inside\n * the `<ParagraphMenu>` component the moment the cursor lands in a heading. That\n * uncaught error tears down Univer's React root, so the document loads and then\n * vanishes. See `features/data-tables/FEATURE.md`.\n *\n * This normalizer converts those string enum values back to numbers BEFORE the\n * snapshot reaches `createUniverDoc`. It is a recovery layer: when it fires it\n * means malformed data slipped past the writer, so it SCREAMS (console.warn)\n * with a count and the document id. The proper long-term fix is to make the\n * writer emit numeric enum values; until then this keeps the editor alive.\n *\n * Returns the SAME object (mutated in place) for ergonomic call sites, plus a\n * `fixed` count via the second return slot is intentionally avoided — callers\n * only need the sanitized snapshot; the warning is the signal.\n */\nimport { NamedStyleType } from \"@univerjs/core\";\nimport type { IDocumentData } from \"@univerjs/core\";\n\nimport {\n defaultDocumentPageStyle,\n isLegacySqueezedPageStyle,\n} from \"../core\";\n\n/**\n * Map of every string name that could appear in a legacy snapshot to its\n * canonical numeric `NamedStyleType`. Built from the enum itself so it stays in\n * lockstep with Univer (numeric enums expose name→value on string keys).\n */\nconst NAMED_STYLE_STRING_TO_NUMBER: Record<string, number> = Object.fromEntries(\n Object.entries(NamedStyleType)\n .filter(([key, val]) => typeof val === \"number\" && isNaN(Number(key)))\n .map(([key, val]) => [key, val as number]),\n);\n\n/**\n * Normalize a Univer document snapshot in place. Currently fixes string-valued\n * `paragraphStyle.namedStyleType` (the confirmed `<ParagraphMenu>` crash). New\n * classes of string-vs-enum corruption should be added here, not patched at the\n * call site.\n *\n * @param snapshot The snapshot about to be passed to `createUniverDoc`.\n * @param docId Document id, for the loud warning only.\n * @returns the same snapshot reference (mutated).\n */\nexport function sanitizeUniverDocSnapshot(\n snapshot: Partial<IDocumentData>,\n docId?: string,\n): Partial<IDocumentData> {\n restorePageStyle(snapshot, docId);\n\n const paragraphs = snapshot?.body?.paragraphs;\n if (!Array.isArray(paragraphs)) return snapshot;\n\n let fixed = 0;\n for (const paragraph of paragraphs) {\n const style = paragraph?.paragraphStyle as\n { namedStyleType?: unknown } | undefined;\n const value = style?.namedStyleType;\n if (typeof value === \"string\") {\n const numeric = NAMED_STYLE_STRING_TO_NUMBER[value];\n if (numeric !== undefined) {\n (style as { namedStyleType?: number }).namedStyleType = numeric;\n fixed += 1;\n } else {\n // Unknown string we can't map — drop it so Univer falls back to\n // NORMAL_TEXT rather than crashing on the lookup.\n delete (style as { namedStyleType?: unknown }).namedStyleType;\n fixed += 1;\n }\n }\n }\n\n if (fixed > 0) {\n console.warn(\n `[data-tables] RECOVERY: sanitized ${fixed} string namedStyleType value(s) ` +\n `to numeric NamedStyleType in document snapshot${docId ? ` ${docId}` : \"\"}. ` +\n `The snapshot was written with the wrong enum encoding (string instead of ` +\n `number) and would have crashed Univer's <ParagraphMenu>. Fix the snapshot ` +\n `writer to emit numeric NamedStyleType values.`,\n );\n }\n\n return snapshot;\n}\n\n/**\n * Second recovery: a snapshot with no `documentStyle.pageSize` has no page box,\n * so Univer lays the body out unbounded — text never wraps and the docs\n * viewport reports no scrollable extent, which reads to the user as \"the\n * document won't scroll\". Snapshots written by agents (`origin='agent'`) and by\n * older converters reach storage with `documentStyle: {}`. Stamp the canonical\n * page geometry back on and SCREAM: the writer is the real bug.\n */\nfunction restorePageStyle(snapshot: Partial<IDocumentData>, docId?: string) {\n if (!snapshot || typeof snapshot !== \"object\") return;\n\n // THE SQUEEZED PAGE (2026-10-15): documents carried A4-at-72dpi geometry in Univer's pageless\n // flavour — a 415px text column with no paper. Move them to a real Letter page, unchanged text.\n // A document with no flavour at all is a paginated page too (Univer would otherwise pick pageless).\n const style = snapshot.documentStyle;\n if (style?.pageSize?.width && isLegacySqueezedPageStyle(style)) {\n const page = defaultDocumentPageStyle();\n snapshot.documentStyle = { ...style, ...page, defaultParagraphStyle: style.defaultParagraphStyle ?? page.defaultParagraphStyle } as typeof style;\n return;\n }\n if (style?.pageSize?.width) {\n if (!style.documentFlavor) {\n const page = defaultDocumentPageStyle();\n Object.assign(style, { documentFlavor: page.documentFlavor });\n if (page.defaultParagraphStyle) style.defaultParagraphStyle ??= page.defaultParagraphStyle;\n }\n return;\n }\n\n snapshot.documentStyle = {\n ...defaultDocumentPageStyle(),\n ...(snapshot.documentStyle ?? {}),\n pageSize: defaultDocumentPageStyle().pageSize,\n } as NonNullable<typeof snapshot.documentStyle>;\n\n console.warn(\n `[data-tables] RECOVERY: document snapshot${docId ? ` ${docId}` : \"\"} had no ` +\n `documentStyle.pageSize — restored the default Letter page geometry. Without a ` +\n `page box Univer lays the body out unbounded: text does not wrap and the ` +\n `viewport has no scrollable extent, so the document appears frozen. Fix the ` +\n `snapshot writer (agent/markdown converters must stamp ` +\n `DEFAULT_DOCUMENT_PAGE_STYLE).`,\n );\n}\n"]}
|