@univerjs-pro/exchange-node 1.3.1 → 1.5.2

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.
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: !0 });
10
+ }, __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from == "object" || typeof from == "function")
12
+ for (let key of __getOwnPropNames(from))
13
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
22
+ mod
23
+ )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
24
+
25
+ // src/mermaid.ts
26
+ var mermaid_exports = {};
27
+ __export(mermaid_exports, {
28
+ compileMermaid: () => compileMermaid
29
+ });
30
+ module.exports = __toCommonJS(mermaid_exports);
31
+ var import_node_buffer = require("node:buffer"), import_node_path2 = require("node:path"), import_node_crypto = require("node:crypto"), import_boards = require("@univerjs-pro/boards"), import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core");
32
+
33
+ // src/binding.ts
34
+ var import_node_module = require("node:module"), import_node_process = __toESM(require("node:process"), 1), import_node_path = require("node:path"), import_node_fs = require("node:fs");
35
+
36
+ // src/types.ts
37
+ var ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode3) => (ExchangeErrorCode3.INVALID_ARGUMENT = "INVALID_ARGUMENT", ExchangeErrorCode3.UNSUPPORTED_FORMAT = "UNSUPPORTED_FORMAT", ExchangeErrorCode3.INVALID_FILE = "INVALID_FILE", ExchangeErrorCode3.INCOMPLETE_SNAPSHOT = "INCOMPLETE_SNAPSHOT", ExchangeErrorCode3.IO_ERROR = "IO_ERROR", ExchangeErrorCode3.NATIVE_LOAD_FAILED = "NATIVE_LOAD_FAILED", ExchangeErrorCode3.CONVERSION_FAILED = "CONVERSION_FAILED", ExchangeErrorCode3.LICENSE_EXPORT_QUOTA_EXCEEDED = "LICENSE_EXPORT_QUOTA_EXCEEDED", ExchangeErrorCode3.LICENSE_INVALID = "LICENSE_INVALID", ExchangeErrorCode3.LICENSE_POLICY_INVALID = "LICENSE_POLICY_INVALID", ExchangeErrorCode3.LICENSE_NOT_YET_EFFECTIVE = "LICENSE_NOT_YET_EFFECTIVE", ExchangeErrorCode3.LICENSE_UNIT_TYPE_REJECTED = "LICENSE_UNIT_TYPE_REJECTED", ExchangeErrorCode3.LICENSE_VERSION_NOT_ALLOWED = "LICENSE_VERSION_NOT_ALLOWED", ExchangeErrorCode3.LICENSE_CONCURRENCY_TIMEOUT = "LICENSE_CONCURRENCY_TIMEOUT", ExchangeErrorCode3.LICENSE_USAGE_STATE_INVALID = "LICENSE_USAGE_STATE_INVALID", ExchangeErrorCode3.LICENSE_USAGE_STORAGE_ERROR = "LICENSE_USAGE_STORAGE_ERROR", ExchangeErrorCode3))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
38
+ constructor(code, message, options) {
39
+ super(message, options);
40
+ this.code = code;
41
+ }
42
+ code;
43
+ name = "ExchangeError";
44
+ };
45
+
46
+ // src/binding.ts
47
+ var nativeBinding = null, nativeBindingSource = null, nodeRequire = (0, import_node_module.createRequire)(__filename);
48
+ function errorMessage(error) {
49
+ return error instanceof Error ? error.message : String(error);
50
+ }
51
+ function validateBinding(binding) {
52
+ try {
53
+ if (!binding || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1 || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.exchangeExportSnapshot != "function" || typeof binding.exchangeApplyImportFileReferences != "function" || typeof binding.exchangeExportRequirements != "function")
54
+ throw new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
55
+ return binding;
56
+ } catch (error) {
57
+ throw error instanceof ExchangeError ? error : new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
58
+ }
59
+ }
60
+ async function loadNativeBinding() {
61
+ if (nativeBinding)
62
+ return nativeBinding;
63
+ let errors = [], runtimeDirectory = import_node_process.default.env.UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE;
64
+ if (runtimeDirectory !== void 0)
65
+ try {
66
+ if (!(0, import_node_path.isAbsolute)(runtimeDirectory))
67
+ throw new Error("Expected an absolute runtime directory path.");
68
+ if (!(0, import_node_fs.statSync)(runtimeDirectory).isDirectory())
69
+ throw new Error("Expected a runtime directory.");
70
+ let nativeLibraryPath = (0, import_node_path.join)(runtimeDirectory, "univer-exchange-node.node"), loaded = { exports: {} };
71
+ return import_node_process.default.dlopen(loaded, nativeLibraryPath), nativeBinding = validateBinding(loaded.exports), nativeBindingSource = "UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE", nativeBinding;
72
+ } catch (error) {
73
+ throw new ExchangeError(
74
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
75
+ `Failed to load native exchange binding from UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE: ${errorMessage(error)}`,
76
+ { cause: error }
77
+ );
78
+ }
79
+ try {
80
+ return nativeBinding = validateBinding(nodeRequire("@univerjs-pro/exchange-node-binding")), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
81
+ } catch (error) {
82
+ errors.push(`@univerjs-pro/exchange-node-binding: ${errorMessage(error)}`);
83
+ }
84
+ throw new ExchangeError(
85
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
86
+ [
87
+ "Failed to load native exchange binding.",
88
+ `platform=${import_node_process.default.platform}`,
89
+ `arch=${import_node_process.default.arch}`,
90
+ "expected npm package=@univerjs-pro/exchange-node-binding",
91
+ "attempted paths:",
92
+ ...errors.map((item) => `- ${item}`)
93
+ ].join(`
94
+ `)
95
+ );
96
+ }
97
+ async function loadBoardBinding() {
98
+ let binding = await loadNativeBinding();
99
+ if (typeof binding.__internalExchangeBoardProtocolVersion != "function" || binding.__internalExchangeBoardProtocolVersion() !== 1 || typeof binding.exchangeCompileMermaid != "function")
100
+ throw new ExchangeError(
101
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
102
+ "Board/Mermaid requires a native exchange binding with Board protocol 1. Upgrade @univerjs-pro/exchange-node-binding."
103
+ );
104
+ return binding;
105
+ }
106
+
107
+ // src/errors.ts
108
+ function structuredExchangeError(error, ErrorClass = ExchangeError) {
109
+ return error instanceof ErrorClass ? error : error !== null && typeof error == "object" && "code" in error && "message" in error && typeof error.code == "string" && typeof error.message == "string" && Object.values(ExchangeErrorCode).includes(error.code) ? new ErrorClass(error.code, error.message, {
110
+ cause: error
111
+ }) : new ErrorClass("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Invalid native exchange error protocol.");
112
+ }
113
+
114
+ // src/snapshot-collector.ts
115
+ var import_protocol = require("@univerjs/protocol");
116
+ function createSnapshotCollector() {
117
+ let sheetBlocks = /* @__PURE__ */ new Map();
118
+ return {
119
+ // The public Pro conversion functions accept the host-wide service
120
+ // contract even though these conversion paths use its two write methods.
121
+ service: {
122
+ async saveSheetBlock(_context, { block }) {
123
+ return block ? (sheetBlocks.set(block.id, block), {
124
+ blockID: block.id,
125
+ error: { code: import_protocol.ErrorCode.OK, message: "" }
126
+ }) : {
127
+ blockID: "",
128
+ error: { code: import_protocol.ErrorCode.UNDEFINED, message: "block is required" }
129
+ };
130
+ },
131
+ async saveSnapshot() {
132
+ return { error: { code: import_protocol.ErrorCode.OK, message: "" } };
133
+ }
134
+ },
135
+ get sheetBlocks() {
136
+ return [...sheetBlocks.values()];
137
+ }
138
+ };
139
+ }
140
+
141
+ // src/mermaid.ts
142
+ var import_runtime = __toESM(require("../shared/runtime.cjs"), 1), import_index = require("./index.cjs");
143
+ function invalid(message) {
144
+ return new import_index.ExchangeError(import_index.ExchangeErrorCode.INVALID_ARGUMENT, message);
145
+ }
146
+ function bytes(value, name) {
147
+ if (typeof value == "string") return import_node_buffer.Buffer.from(value, "utf8");
148
+ if (import_node_buffer.Buffer.isBuffer(value)) return value;
149
+ throw invalid(`${name} must be a string or Buffer.`);
150
+ }
151
+ async function compileMermaid(source, options = {}) {
152
+ return compile(source, options);
153
+ }
154
+ async function compile(source, options = {}) {
155
+ if (options === null || typeof options != "object" || Array.isArray(options) || Reflect.ownKeys(options).some((key) => key !== "resourceManifest")) throw invalid("Invalid Mermaid compile options.");
156
+ let input = bytes(source, "source"), manifest = options.resourceManifest === void 0 ? void 0 : bytes(options.resourceManifest, "resourceManifest");
157
+ try {
158
+ let binding = await loadBoardBinding(), draft = JSON.parse(await binding.exchangeCompileMermaid(input, manifest));
159
+ if (draft.version !== 2 || draft.sourceType !== "mermaid" || !Array.isArray(draft.elements))
160
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED, "Incompatible native Mermaid draft protocol.");
161
+ return draft;
162
+ } catch (error) {
163
+ throw structuredExchangeError(error);
164
+ }
165
+ }
166
+ function alignment(value, values) {
167
+ if (value === void 0) return;
168
+ let result = typeof value == "string" ? values[value] : void 0;
169
+ if (result === void 0)
170
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED, `Unsupported Mermaid alignment: ${value}`);
171
+ return result;
172
+ }
173
+ function toEditorDraft(draft) {
174
+ let elements = draft.elements.map((element) => {
175
+ if (element.type !== "text" || !element.textStyle) return element;
176
+ let style = element.textStyle;
177
+ return { ...element, textStyle: {
178
+ ...style,
179
+ horizontalAlign: alignment(style.horizontalAlign, {
180
+ left: import_core.HorizontalAlign.LEFT,
181
+ center: import_core.HorizontalAlign.CENTER,
182
+ right: import_core.HorizontalAlign.RIGHT,
183
+ justified: import_core.HorizontalAlign.JUSTIFIED,
184
+ justify: import_core.HorizontalAlign.JUSTIFIED
185
+ }),
186
+ verticalAlign: alignment(style.verticalAlign, {
187
+ top: import_core.VerticalAlign.TOP,
188
+ center: import_core.VerticalAlign.MIDDLE,
189
+ middle: import_core.VerticalAlign.MIDDLE,
190
+ bottom: import_core.VerticalAlign.BOTTOM
191
+ })
192
+ } };
193
+ });
194
+ return { ...draft, elements };
195
+ }
196
+ var adapter = import_runtime.default.getMermaid() ?? {
197
+ async import(input, options) {
198
+ if (options.unitId !== void 0 && (typeof options.unitId != "string" || options.unitId.trim().length === 0))
199
+ throw invalid("unitId must be a non-empty string when provided.");
200
+ let draft = await compile(input, options.mermaid), editorDraft = toEditorDraft(draft), materialized = (0, import_boards.materializeBoardImportDraft)({
201
+ draft: editorDraft,
202
+ position: { left: 0, top: 0 },
203
+ createId: () => (0, import_node_crypto.randomUUID)()
204
+ }), elements = materialized.elements.map(import_boards.normalizeBoardConnectorElementContent), pageId = (0, import_node_crypto.randomUUID)(), name = (0, import_node_path2.basename)(options.fileName, (0, import_node_path2.extname)(options.fileName));
205
+ return {
206
+ value: {
207
+ id: options.unitId ?? (0, import_node_crypto.randomUUID)(),
208
+ name,
209
+ appVersion: "1.0.0",
210
+ defaultPageSize: { width: Math.max(1, materialized.bounds.width), height: Math.max(1, materialized.bounds.height) },
211
+ activePageId: pageId,
212
+ pageOrder: [pageId],
213
+ pages: { [pageId]: {
214
+ id: pageId,
215
+ pageType: import_boards.BoardPageType.Page,
216
+ name: draft.title || name,
217
+ elementOrder: elements.map((element) => element.id),
218
+ elements: Object.fromEntries(elements.map((element) => [element.id, element]))
219
+ } },
220
+ // A new Unit owns its resource namespace. Preserve resource payloads and the
221
+ // matching chart/table IDs; materializeBoardImportDraft only returns elements.
222
+ resources: (draft.resources ?? []).map(({ name: name2, data }) => ({ name: name2, data }))
223
+ },
224
+ diagnostics: (draft.diagnostics ?? []).map(({ code, message, ...details }) => ({ code, message, details }))
225
+ };
226
+ },
227
+ async toSnapshot(board) {
228
+ let { snapshot } = await (0, import_collaboration.transformBoardDataToSnapshot)(board.resources, board, board.id, board.rev ?? 0, createSnapshotCollector().service);
229
+ return { snapshot, sheetBlocks: [] };
230
+ }
231
+ };
232
+ import_runtime.default.registerMermaid(adapter);
233
+ // Annotate the CommonJS export names for ESM import in node:
234
+ 0 && (module.exports = {
235
+ compileMermaid
236
+ });
package/lib/cjs/pdf.cjs CHANGED
@@ -22,7 +22,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  // src/pdf.ts
23
23
  var pdf_exports = {};
24
24
  module.exports = __toCommonJS(pdf_exports);
25
- var import_collaboration = require("@univerjs-pro/collaboration"), import_pdfs = require("@univerjs-pro/pdfs"), import_node_buffer = require("node:buffer"), import_node_module = require("node:module");
25
+ var import_collaboration = require("@univerjs-pro/collaboration"), import_pdfs = require("@univerjs-pro/pdfs"), import_core = require("@univerjs/core"), import_node_buffer = require("node:buffer"), import_node_crypto2 = require("node:crypto"), import_node_module = require("node:module"), import_node_path = require("node:path"), import_node_fs = require("node:fs"), import_node_process = __toESM(require("node:process"), 1);
26
26
 
27
27
  // src/snapshot-collector.ts
28
28
  var import_protocol = require("@univerjs/protocol");
@@ -51,8 +51,8 @@ function createSnapshotCollector() {
51
51
  };
52
52
  }
53
53
 
54
- // src/pdf.ts
55
- var import_runtime = __toESM(require("../shared/runtime.cjs"), 1), import_index = require("./index.cjs");
54
+ // src/file-storage.ts
55
+ var import_node_crypto = require("node:crypto");
56
56
 
57
57
  // src/types.ts
58
58
  var ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode3) => (ExchangeErrorCode3.INVALID_ARGUMENT = "INVALID_ARGUMENT", ExchangeErrorCode3.UNSUPPORTED_FORMAT = "UNSUPPORTED_FORMAT", ExchangeErrorCode3.INVALID_FILE = "INVALID_FILE", ExchangeErrorCode3.INCOMPLETE_SNAPSHOT = "INCOMPLETE_SNAPSHOT", ExchangeErrorCode3.IO_ERROR = "IO_ERROR", ExchangeErrorCode3.NATIVE_LOAD_FAILED = "NATIVE_LOAD_FAILED", ExchangeErrorCode3.CONVERSION_FAILED = "CONVERSION_FAILED", ExchangeErrorCode3.LICENSE_EXPORT_QUOTA_EXCEEDED = "LICENSE_EXPORT_QUOTA_EXCEEDED", ExchangeErrorCode3.LICENSE_INVALID = "LICENSE_INVALID", ExchangeErrorCode3.LICENSE_POLICY_INVALID = "LICENSE_POLICY_INVALID", ExchangeErrorCode3.LICENSE_NOT_YET_EFFECTIVE = "LICENSE_NOT_YET_EFFECTIVE", ExchangeErrorCode3.LICENSE_UNIT_TYPE_REJECTED = "LICENSE_UNIT_TYPE_REJECTED", ExchangeErrorCode3.LICENSE_VERSION_NOT_ALLOWED = "LICENSE_VERSION_NOT_ALLOWED", ExchangeErrorCode3.LICENSE_CONCURRENCY_TIMEOUT = "LICENSE_CONCURRENCY_TIMEOUT", ExchangeErrorCode3.LICENSE_USAGE_STATE_INVALID = "LICENSE_USAGE_STATE_INVALID", ExchangeErrorCode3.LICENSE_USAGE_STORAGE_ERROR = "LICENSE_USAGE_STORAGE_ERROR", ExchangeErrorCode3))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
@@ -64,6 +64,31 @@ var ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode3) => (ExchangeErrorC
64
64
  name = "ExchangeError";
65
65
  };
66
66
 
67
+ // src/file-storage.ts
68
+ async function storeFileReferences(inputs, files, ErrorClass = ExchangeError) {
69
+ let groups = /* @__PURE__ */ new Map();
70
+ for (let { id, ...file } of inputs) {
71
+ let hash = (0, import_node_crypto.createHash)("sha256").update(file.bytes).digest("hex"), group = groups.get(hash) ?? { file, ids: [] };
72
+ group.ids.push(id), groups.set(hash, group);
73
+ }
74
+ let references = /* @__PURE__ */ new Map();
75
+ for (let { file, ids } of groups.values()) {
76
+ let decision = await files.store(file);
77
+ if (decision?.mode !== "inline") {
78
+ if (decision?.mode !== "reference" || typeof decision.source != "string" || !decision.source.trim())
79
+ throw new ErrorClass(
80
+ "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
81
+ 'files.store must return { mode: "inline" } or { mode: "reference", source }'
82
+ );
83
+ for (let id of ids) references.set(id, decision.source);
84
+ }
85
+ }
86
+ return references;
87
+ }
88
+
89
+ // src/pdf.ts
90
+ var import_runtime = __toESM(require("../shared/runtime.cjs"), 1), import_index = require("./index.cjs");
91
+
67
92
  // src/errors.ts
68
93
  function structuredExchangeError(error, ErrorClass = ExchangeError) {
69
94
  return error instanceof ErrorClass ? error : error !== null && typeof error == "object" && "code" in error && "message" in error && typeof error.code == "string" && typeof error.message == "string" && Object.values(ExchangeErrorCode).includes(error.code) ? new ErrorClass(error.code, error.message, {
@@ -76,14 +101,23 @@ var require2 = (0, import_node_module.createRequire)(__filename), bindingPromise
76
101
  function loadBinding() {
77
102
  return bindingPromise ??= Promise.resolve().then(() => {
78
103
  try {
79
- let binding = require2("@univerjs-pro/exchange-pdf-node-binding");
104
+ let runtimeDirectory = import_node_process.default.env.UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE, binding;
105
+ if (runtimeDirectory !== void 0) {
106
+ if (!(0, import_node_path.isAbsolute)(runtimeDirectory))
107
+ throw new Error("UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE must be an absolute runtime directory path.");
108
+ if (!(0, import_node_fs.statSync)(runtimeDirectory).isDirectory())
109
+ throw new Error("UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE must name a directory.");
110
+ let nativeLibraryPath = (0, import_node_path.join)(runtimeDirectory, "exchange-pdf.node"), loaded = { exports: {} };
111
+ import_node_process.default.dlopen(loaded, nativeLibraryPath), binding = loaded.exports;
112
+ } else
113
+ binding = require2("@univerjs-pro/exchange-pdf-node-binding");
80
114
  if (typeof binding.convert != "function" || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1)
81
115
  throw new TypeError("PDF binding does not implement the required configuration protocol");
82
116
  return binding;
83
117
  } catch (error) {
84
118
  throw new import_index.ExchangeError(
85
119
  import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED,
86
- "Unable to load @univerjs-pro/exchange-pdf-node-binding",
120
+ import_node_process.default.env.UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE !== void 0 ? "Unable to load PDF binding from UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE" : "Unable to load @univerjs-pro/exchange-pdf-node-binding",
87
121
  { cause: error }
88
122
  );
89
123
  }
@@ -116,9 +150,13 @@ function prepareInput(action) {
116
150
  try {
117
151
  return action();
118
152
  } catch (error) {
119
- throw error instanceof import_index.ExchangeError ? error : new import_index.ExchangeError(import_index.ExchangeErrorCode.INVALID_ARGUMENT, "Invalid PDF conversion arguments: pdfUnitOrOptions.", {
120
- cause: error
121
- });
153
+ throw error instanceof import_index.ExchangeError ? error : new import_index.ExchangeError(
154
+ import_index.ExchangeErrorCode.INVALID_ARGUMENT,
155
+ "Invalid PDF conversion arguments: pdfUnitOrOptions.",
156
+ {
157
+ cause: error
158
+ }
159
+ );
122
160
  }
123
161
  }
124
162
  function encodeInput(value) {
@@ -134,6 +172,168 @@ function completeUnit(input) {
134
172
  );
135
173
  return prepareInput(() => (0, import_pdfs.normalizePdfUnitData)(input));
136
174
  }
175
+ function imageManifest(unit) {
176
+ return unit.metadata?.exchangeNodePdf?.decodeManifest ?? {};
177
+ }
178
+ function invalidResource(message) {
179
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.INVALID_ARGUMENT, message);
180
+ }
181
+ async function storePdfFiles(unit, files) {
182
+ let streams = unit.document.assets.streams, targetsByStream = /* @__PURE__ */ new Map(), attachmentsByStream = /* @__PURE__ */ new Map(), addTarget = (streamId, targetId) => {
183
+ if (!streamId) return;
184
+ let targets = targetsByStream.get(streamId);
185
+ targets || targetsByStream.set(streamId, targets = /* @__PURE__ */ new Set()), targets.add(targetId);
186
+ };
187
+ for (let asset of Object.values(unit.document.assets.images)) addTarget(asset.decodedAssetId, asset.id);
188
+ let manifest = imageManifest(unit);
189
+ for (let [id, resource] of Object.entries({ ...manifest.fontFaces, ...manifest.imageAssets, ...manifest.pageRasters }))
190
+ addTarget(resource.streamAssetId, id);
191
+ for (let asset of Object.values(unit.document.assets.attachments)) {
192
+ let streamId = asset.metadata?.streamAssetId;
193
+ if (typeof streamId != "string" || !streamId) continue;
194
+ let attachments = attachmentsByStream.get(streamId) ?? [];
195
+ attachments.push(asset), attachmentsByStream.set(streamId, attachments), addTarget(streamId, asset.id);
196
+ }
197
+ let inputs = Object.entries(streams).flatMap(([id, stream]) => {
198
+ if (stream.storage !== "inline-base64" || typeof stream.value != "string") return [];
199
+ let attachment = attachmentsByStream.get(id)?.[0], bytes = import_node_buffer.Buffer.from(stream.value, "base64");
200
+ return [
201
+ {
202
+ id,
203
+ name: attachment?.fileName ?? (id === unit.sourceDocumentRef?.assetId ? unit.name : id),
204
+ mimeType: attachment?.mimeType || stream.mimeType || "application/octet-stream",
205
+ size: bytes.length,
206
+ bytes
207
+ }
208
+ ];
209
+ }), references = await storeFileReferences(inputs, files, import_index.ExchangeError), bindings = unit.resourceBindings ??= {};
210
+ for (let [id, source] of references) {
211
+ let stream = streams[id], bytes = import_node_buffer.Buffer.from(stream.value, "base64"), binding = {
212
+ kind: "universer-resource",
213
+ source,
214
+ imageSourceType: import_core.ImageSourceType.UUID,
215
+ mimeType: stream.mimeType,
216
+ byteLength: bytes.length,
217
+ checksum: (0, import_node_crypto2.createHash)("sha256").update(bytes).digest("hex")
218
+ };
219
+ Object.defineProperty(bindings, id, {
220
+ value: binding,
221
+ enumerable: !0,
222
+ configurable: !0,
223
+ writable: !0
224
+ }), stream.storage = "external-file", stream.uri = source, stream.checksum = binding.checksum, delete stream.value;
225
+ for (let targetId of targetsByStream.get(id) ?? [])
226
+ Object.defineProperty(bindings, targetId, {
227
+ value: binding,
228
+ enumerable: !0,
229
+ configurable: !0,
230
+ writable: !0
231
+ });
232
+ for (let attachment of attachmentsByStream.get(id) ?? [])
233
+ attachment.byteLength = bytes.length, attachment.checksum = binding.checksum;
234
+ if (unit.sourceDocumentRef?.assetId === id) {
235
+ unit.sourceDocumentRef.assetId = source;
236
+ for (let entry of Object.values(unit.document.sources ?? {}))
237
+ entry.assetId === id && (entry.assetId = source);
238
+ unit.document.source?.assetId === id && (unit.document.source.assetId = source), source !== id && Object.hasOwn(streams, source) && streams[source].checksum !== binding.checksum && invalidResource("files.store source conflicts with an existing PDF asset identifier"), Object.defineProperty(streams, source, {
239
+ value: { ...stream, id: source },
240
+ enumerable: !0,
241
+ configurable: !0,
242
+ writable: !0
243
+ }), Object.defineProperty(bindings, source, {
244
+ value: binding,
245
+ enumerable: !0,
246
+ configurable: !0,
247
+ writable: !0
248
+ });
249
+ }
250
+ }
251
+ }
252
+ function hasExternalFiles(unit) {
253
+ return Object.values(unit.resourceBindings ?? {}).some((b) => b.kind === "universer-resource") || Object.values(unit.editState.managedResources).some(
254
+ (r) => r.imageSourceType === import_core.ImageSourceType.UUID || r.imageSourceType === import_core.ImageSourceType.URL
255
+ );
256
+ }
257
+ async function loadPdfFiles(unit, options, loaded) {
258
+ if (!options.files || !hasExternalFiles(unit)) return unit;
259
+ let copy = structuredClone(unit), hydrated = /* @__PURE__ */ new Set();
260
+ for (; ; ) {
261
+ let result = await convertPdf(
262
+ 3,
263
+ encodeInput({
264
+ strictResources: options.strictResources ?? !0
265
+ }).toString("utf8"),
266
+ encodeInput(copy)
267
+ );
268
+ parseDiagnostics(result.metadata);
269
+ let requirements = JSON.parse(result.payload.toString("utf8"));
270
+ if (!Array.isArray(requirements?.files))
271
+ throw new import_index.ExchangeError(
272
+ import_index.ExchangeErrorCode.CONVERSION_FAILED,
273
+ "PDF binding returned invalid file requirements; reinstall the matching PDF binding and SDK."
274
+ );
275
+ if (requirements.files.length === 0) return copy;
276
+ for (let file of requirements.files)
277
+ if (!file || typeof file.assetId != "string" || !file.assetId || typeof file.source != "string" || !file.source || !["UUID", "URL"].includes(file.sourceType) || file.optional !== void 0 && typeof file.optional != "boolean" || file.optional === !0 && file.managed === !0 || !file.managed && (typeof file.streamAssetId != "string" || !file.streamAssetId))
278
+ throw new import_index.ExchangeError(
279
+ import_index.ExchangeErrorCode.CONVERSION_FAILED,
280
+ "PDF binding returned an invalid file requirement"
281
+ );
282
+ for (let file of requirements.files) {
283
+ let target = JSON.stringify([file.managed, file.assetId, file.streamAssetId]);
284
+ if (hydrated.has(target))
285
+ throw new import_index.ExchangeError(
286
+ import_index.ExchangeErrorCode.CONVERSION_FAILED,
287
+ "PDF binding still requires a resolved file"
288
+ );
289
+ hydrated.add(target);
290
+ let key = JSON.stringify([unit.id, file.sourceType, file.source]), bytes = loaded.get(key);
291
+ if (!bytes) {
292
+ let content;
293
+ try {
294
+ content = await options.files.load({
295
+ unitId: unit.id,
296
+ sourceType: file.sourceType,
297
+ source: file.source
298
+ });
299
+ } catch (error) {
300
+ if (!file.optional) throw error;
301
+ delete copy.resourceBindings?.[file.assetId];
302
+ continue;
303
+ }
304
+ content?.bytes instanceof Uint8Array || invalidResource("files.load must return { bytes: Uint8Array }"), bytes = import_node_buffer.Buffer.from(content.bytes), loaded.set(key, bytes);
305
+ }
306
+ if (file.managed) {
307
+ let resource = copy.editState.managedResources[file.assetId];
308
+ if (!resource)
309
+ throw new import_index.ExchangeError(
310
+ import_index.ExchangeErrorCode.CONVERSION_FAILED,
311
+ "PDF binding requested an unknown managed resource"
312
+ );
313
+ resource.source = bytes.toString("base64"), resource.imageSourceType = import_core.ImageSourceType.BASE64;
314
+ } else {
315
+ let id = file.streamAssetId, previous = copy.document.assets.streams[id], durable = copy.resourceBindings?.[id] ?? copy.resourceBindings?.[file.assetId];
316
+ if (previous?.byteLength !== void 0 && previous.byteLength !== bytes.length || durable?.kind === "universer-resource" && durable.checksum && (0, import_node_crypto2.createHash)("sha256").update(bytes).digest("hex") !== durable.checksum)
317
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.CONVERSION_FAILED, `PDF file integrity mismatch: ${id}`);
318
+ Object.defineProperty(copy.document.assets.streams, id, {
319
+ enumerable: !0,
320
+ configurable: !0,
321
+ writable: !0,
322
+ value: {
323
+ ...previous,
324
+ id,
325
+ type: import_pdfs.PdfAssetType.STREAM,
326
+ storage: "inline-base64",
327
+ value: bytes.toString("base64"),
328
+ byteLength: bytes.length
329
+ }
330
+ });
331
+ let asset = copy.document.assets.images[file.assetId];
332
+ asset && (asset.decodedAssetId = id);
333
+ }
334
+ }
335
+ }
336
+ }
137
337
  var adapter = {
138
338
  async configure(snapshot) {
139
339
  let configuration = encodeInput(snapshot), binding = await loadBinding();
@@ -153,26 +353,42 @@ var adapter = {
153
353
  try {
154
354
  return JSON.parse(result);
155
355
  } catch (error) {
156
- throw new import_index.ExchangeError(import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED, "PDF binding returned invalid quota metadata", {
157
- cause: error
158
- });
356
+ throw new import_index.ExchangeError(
357
+ import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED,
358
+ "PDF binding returned invalid quota metadata",
359
+ {
360
+ cause: error
361
+ }
362
+ );
159
363
  }
160
364
  },
161
365
  async import(input, options) {
162
- let result = await convertPdf(1, encodeInput(options).toString("utf8"), input);
163
- return {
164
- value: completeUnit(JSON.parse(result.payload.toString("utf8"))),
366
+ let result = await convertPdf(
367
+ 1,
368
+ encodeInput({
369
+ fileName: options.fileName,
370
+ unitId: options.unitId
371
+ }).toString("utf8"),
372
+ input
373
+ ), unit = completeUnit(JSON.parse(result.payload.toString("utf8")));
374
+ return options.files && await storePdfFiles(unit, options.files), {
375
+ value: unit,
165
376
  diagnostics: parseDiagnostics(result.metadata)
166
377
  };
167
378
  },
168
379
  async export(input, options, config) {
169
- let unit = completeUnit(input), result = await convertPdf(
380
+ let loaded = /* @__PURE__ */ new Map(), complete = completeUnit(input), unit = await loadPdfFiles(complete, options, loaded), result = await convertPdf(
170
381
  2,
171
- encodeInput({ strictResources: options.strictResources ?? !0 }).toString("utf8"),
382
+ encodeInput({
383
+ strictResources: options.strictResources ?? !0
384
+ }).toString("utf8"),
172
385
  encodeInput(unit),
173
386
  config
174
387
  );
175
- return { value: result.payload, diagnostics: parseDiagnostics(result.metadata) };
388
+ return {
389
+ value: result.payload,
390
+ diagnostics: parseDiagnostics(result.metadata)
391
+ };
176
392
  },
177
393
  async toSnapshot(input) {
178
394
  let unit = completeUnit(input), { snapshot } = await (0, import_collaboration.transformPdfDataToSnapshot)(
@@ -0,0 +1 @@
1
+ export { compileMermaid } from '../cjs/mermaid.cjs';
@@ -1,5 +1,6 @@
1
1
  // One physical CommonJS module shared by both public module formats in this JS context.
2
2
  let pdfAdapter;
3
+ let mermaidAdapter;
3
4
  let current;
4
5
  let version = 0;
5
6
  let queue = Promise.resolve();
@@ -52,6 +53,13 @@ module.exports = {
52
53
  pdfAdapter = adapter;
53
54
  },
54
55
  getPdf() { return pdfAdapter; },
56
+ registerMermaid(adapter) {
57
+ if (mermaidAdapter && mermaidAdapter !== adapter) {
58
+ throw new Error('A different Mermaid adapter is already registered for this installation');
59
+ }
60
+ mermaidAdapter = adapter;
61
+ },
62
+ getMermaid() { return mermaidAdapter; },
55
63
  configure(config, prepare) {
56
64
  const validated = validate(config);
57
65
  return enqueue(async () => {
@@ -1,4 +1,4 @@
1
- import { BaseAttachmentPolicy, BaseExportMode, BaseFormulaPolicy, BaseHeaderPolicy, BaseImagePolicy, BaseImportMode, BaseTypeInference, BufferImportOptions, ConversionDiagnosticOptions, CsvFormulaMode, CsvLineEnding, CsvQuoteStyle, CsvTypeInferenceMode, CsvValueMode, DocxCompatibilityMode, ExchangeDiagnostic, ExchangeError, ExchangeErrorCode, ExchangeExportOptionsMap, ExchangeFormat, ExchangeImportOptionsMap, ExchangeUnitDataMap, ExportOptions, ExportQuota, ExportUnitType, FormulaCalculationMode, IBaseExportMapping, IBaseExportOptions, IBaseFieldMapping, IBaseImportMapping, IBaseImportOptions, IBaseTableMapping, ICsvExportOptions, ICsvExportSelector, ICsvImportOptions, IDocExportOptions, IDocImportOptions, IExchangeConfig, IExportOptionsBase, IExportQuotaOptions, IGridImportOptions, IImportOptionsBase, ISheetExportOptions, ISheetImportOptions, ISlideExportOptions, ISlideImportOptions, ISnapshotWithBlocks, ImportOptions } from "./types.js";
1
+ import { BaseAttachmentPolicy, BaseExportMode, BaseFormulaPolicy, BaseHeaderPolicy, BaseImagePolicy, BaseImportMode, BaseTypeInference, BufferImportOptions, ConversionDiagnosticOptions, CsvFormulaMode, CsvLineEnding, CsvQuoteStyle, CsvTypeInferenceMode, CsvValueMode, DocxCompatibilityMode, ExchangeDiagnostic, ExchangeError, ExchangeErrorCode, ExchangeExportOptionsMap, ExchangeFormat, ExchangeImportOptionsMap, ExchangeUnitDataMap, ExportOptions, ExportQuota, ExportUnitType, FormulaCalculationMode, IBaseExportMapping, IBaseExportOptions, IBaseFieldMapping, IBaseImportMapping, IBaseImportOptions, IBaseTableMapping, IBoardExportOptions, ICsvExportOptions, ICsvExportSelector, ICsvImportOptions, IDocExportOptions, IDocImportOptions, IExchangeConfig, IExportFileContent, IExportFileRef, IExportFilesOptions, IExportOleOptions, IExportOptionsBase, IExportQuotaOptions, IGridImportOptions, IImportFileResult, IImportFilesOptions, IImportOptionsBase, IImportedFile, IOleOnlineUnitRef, ISheetExportOptions, ISheetImportOptions, ISlideExportOptions, ISlideImportOptions, ISnapshotWithBlocks, ImportOptions, OleOnlineUnitType } from "./types.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/index.d.ts
4
4
  type ImportResult<T extends ImportOptions> = ExchangeUnitDataMap[T['type']];
@@ -6,16 +6,16 @@ type ImportResult<T extends ImportOptions> = ExchangeUnitDataMap[T['type']];
6
6
  * Configure authorization in this JS context. Each Worker configures itself.
7
7
  * Pass {} to select Free. Await before starting exports with the new credentials.
8
8
  */
9
- declare function configureExchange(config: IExchangeConfig): Promise<void>;
9
+ export declare function configureExchange(config: IExchangeConfig): Promise<void>;
10
10
  /** Query shared quota without consuming/reserving it or checking export eligibility. */
11
- declare function getExportQuota(options?: IExportQuotaOptions): Promise<ExportQuota>;
12
- declare function importFile<T extends ImportOptions>(path: string, options: T): Promise<ImportResult<T>>;
13
- declare function importBuffer<T extends ImportOptions>(input: Buffer, options: BufferImportOptions<T>): Promise<ImportResult<T>>;
14
- declare function importFileToSnapshot(path: string, options: ImportOptions): Promise<ISnapshotWithBlocks>;
15
- declare function importBufferToSnapshot<T extends ImportOptions>(input: Buffer, options: BufferImportOptions<T>): Promise<ISnapshotWithBlocks>;
16
- declare function exportToBuffer<T extends ExportOptions>(data: NoInfer<ExchangeUnitDataMap[T['type']]>, options: T): Promise<Buffer>;
17
- declare function exportToFile<T extends ExportOptions>(data: NoInfer<ExchangeUnitDataMap[T['type']]>, path: string, options: T): Promise<void>;
18
- declare function exportSnapshotToBuffer(snapshot: ISnapshotWithBlocks, options: ExportOptions): Promise<Buffer>;
19
- declare function exportSnapshotToFile(snapshot: ISnapshotWithBlocks, path: string, options: ExportOptions): Promise<void>;
11
+ export declare function getExportQuota(options?: IExportQuotaOptions): Promise<ExportQuota>;
12
+ export declare function importFile<T extends ImportOptions>(path: string, options: T): Promise<ImportResult<T>>;
13
+ export declare function importBuffer<T extends ImportOptions>(input: Buffer, options: BufferImportOptions<T>): Promise<ImportResult<T>>;
14
+ export declare function importFileToSnapshot(path: string, options: ImportOptions): Promise<ISnapshotWithBlocks>;
15
+ export declare function importBufferToSnapshot<T extends ImportOptions>(input: Buffer, options: BufferImportOptions<T>): Promise<ISnapshotWithBlocks>;
16
+ export declare function exportToBuffer<T extends ExportOptions>(data: NoInfer<ExchangeUnitDataMap[T['type']]>, options: T): Promise<Buffer>;
17
+ export declare function exportToFile<T extends ExportOptions>(data: NoInfer<ExchangeUnitDataMap[T['type']]>, path: string, options: T): Promise<void>;
18
+ export declare function exportSnapshotToBuffer(snapshot: ISnapshotWithBlocks, options: ExportOptions): Promise<Buffer>;
19
+ export declare function exportSnapshotToFile(snapshot: ISnapshotWithBlocks, path: string, options: ExportOptions): Promise<void>;
20
20
  //#endregion
21
- export { BaseAttachmentPolicy, BaseExportMode, BaseFormulaPolicy, BaseHeaderPolicy, BaseImagePolicy, BaseImportMode, BaseTypeInference, BufferImportOptions, ConversionDiagnosticOptions, CsvFormulaMode, CsvLineEnding, CsvQuoteStyle, CsvTypeInferenceMode, CsvValueMode, DocxCompatibilityMode, ExchangeDiagnostic, ExchangeError, ExchangeErrorCode, ExchangeExportOptionsMap, ExchangeFormat, ExchangeImportOptionsMap, ExchangeUnitDataMap, ExportOptions, ExportQuota, ExportUnitType, FormulaCalculationMode, IBaseExportMapping, IBaseExportOptions, IBaseFieldMapping, IBaseImportMapping, IBaseImportOptions, IBaseTableMapping, ICsvExportOptions, ICsvExportSelector, ICsvImportOptions, IDocExportOptions, IDocImportOptions, IExchangeConfig, IExportOptionsBase, IExportQuotaOptions, IGridImportOptions, IImportOptionsBase, ISheetExportOptions, ISheetImportOptions, ISlideExportOptions, ISlideImportOptions, ISnapshotWithBlocks, ImportOptions, configureExchange, exportSnapshotToBuffer, exportSnapshotToFile, exportToBuffer, exportToFile, getExportQuota, importBuffer, importBufferToSnapshot, importFile, importFileToSnapshot };
21
+ export { BaseAttachmentPolicy, BaseExportMode, BaseFormulaPolicy, BaseHeaderPolicy, BaseImagePolicy, BaseImportMode, BaseTypeInference, BufferImportOptions, ConversionDiagnosticOptions, CsvFormulaMode, CsvLineEnding, CsvQuoteStyle, CsvTypeInferenceMode, CsvValueMode, DocxCompatibilityMode, ExchangeDiagnostic, ExchangeError, ExchangeErrorCode, ExchangeExportOptionsMap, ExchangeFormat, ExchangeImportOptionsMap, ExchangeUnitDataMap, ExportOptions, ExportQuota, ExportUnitType, FormulaCalculationMode, IBaseExportMapping, IBaseExportOptions, IBaseFieldMapping, IBaseImportMapping, IBaseImportOptions, IBaseTableMapping, IBoardExportOptions, ICsvExportOptions, ICsvExportSelector, ICsvImportOptions, IDocExportOptions, IDocImportOptions, IExchangeConfig, IExportFileContent, IExportFileRef, IExportFilesOptions, IExportOleOptions, IExportOptionsBase, IExportQuotaOptions, IGridImportOptions, IImportFileResult, IImportFilesOptions, IImportOptionsBase, IImportedFile, IOleOnlineUnitRef, ISheetExportOptions, ISheetImportOptions, ISlideExportOptions, ISlideImportOptions, ISnapshotWithBlocks, ImportOptions, OleOnlineUnitType };
@@ -0,0 +1,26 @@
1
+ import { ExchangeFormat, IImportOptionsBase } from "./types.js";
2
+ import "./index.js";
3
+ import { Buffer } from "node:buffer";
4
+ import { UniverInstanceType } from "@univerjs/core";
5
+ import { IBoardImportDraft } from "@univerjs-pro/boards";
6
+ //#region src/mermaid.d.ts
7
+ export interface IMermaidCompileOptions {
8
+ /** CLI resource-manifest JSON content, not a file path. */
9
+ resourceManifest?: string | Buffer;
10
+ }
11
+ /** Complete Board import. Application insertion uses compileMermaid instead. */
12
+ export interface IBoardImportOptions extends IImportOptionsBase<UniverInstanceType.UNIVER_BOARD, ExchangeFormat.MERMAID> {
13
+ mermaid?: IMermaidCompileOptions;
14
+ }
15
+ declare module './types.js' {
16
+ interface ExchangeImportOptionsMap {
17
+ [UniverInstanceType.UNIVER_BOARD]: IBoardImportOptions;
18
+ }
19
+ }
20
+ /** Compile through the same Rust implementation and defaults as the CLI.
21
+ * Uses the existing Boards import type; native JSON and additional fields are preserved.
22
+ * Strings use UTF-8; Buffers accept UTF-8 or BOM-prefixed UTF-16.
23
+ * This method does not materialize a Board, merge resources or insert into a page.
24
+ */
25
+ export declare function compileMermaid(source: string | Buffer, options?: IMermaidCompileOptions): Promise<IBoardImportDraft>;
26
+ //#endregion