@univerjs-pro/exchange-node 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
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 __copyProps = (to, from, except, desc) => {
8
+ if (from && typeof from == "object" || typeof from == "function")
9
+ for (let key of __getOwnPropNames(from))
10
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ return to;
12
+ };
13
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
14
+ // If the importer is in node compatibility mode or this is not an ESM
15
+ // file that has been converted to a CommonJS file using a Babel-
16
+ // compatible transform (i.e. "__esModule" has not been set), then set
17
+ // "default" to the CommonJS "module.exports" for node compatibility.
18
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
+ mod
20
+ )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
21
+
22
+ // src/pdf.ts
23
+ var pdf_exports = {};
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");
26
+
27
+ // src/snapshot-collector.ts
28
+ var import_protocol = require("@univerjs/protocol");
29
+ function createSnapshotCollector() {
30
+ let sheetBlocks = /* @__PURE__ */ new Map();
31
+ return {
32
+ // The public Pro conversion functions accept the host-wide service
33
+ // contract even though these conversion paths use its two write methods.
34
+ service: {
35
+ async saveSheetBlock(_context, { block }) {
36
+ return block ? (sheetBlocks.set(block.id, block), {
37
+ blockID: block.id,
38
+ error: { code: import_protocol.ErrorCode.OK, message: "" }
39
+ }) : {
40
+ blockID: "",
41
+ error: { code: import_protocol.ErrorCode.UNDEFINED, message: "block is required" }
42
+ };
43
+ },
44
+ async saveSnapshot() {
45
+ return { error: { code: import_protocol.ErrorCode.OK, message: "" } };
46
+ }
47
+ },
48
+ get sheetBlocks() {
49
+ return [...sheetBlocks.values()];
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/pdf.ts
55
+ var import_runtime = __toESM(require("../shared/runtime.cjs"), 1), import_index = require("./index.cjs");
56
+
57
+ // src/types.ts
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 {
59
+ constructor(code, message, options) {
60
+ super(message, options);
61
+ this.code = code;
62
+ }
63
+ code;
64
+ name = "ExchangeError";
65
+ };
66
+
67
+ // src/errors.ts
68
+ function structuredExchangeError(error, ErrorClass = ExchangeError) {
69
+ 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, {
70
+ cause: error
71
+ }) : new ErrorClass("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Invalid native exchange error protocol.");
72
+ }
73
+
74
+ // src/pdf.ts
75
+ var require2 = (0, import_node_module.createRequire)(__filename), bindingPromise;
76
+ function loadBinding() {
77
+ return bindingPromise ??= Promise.resolve().then(() => {
78
+ try {
79
+ let binding = require2("@univerjs-pro/exchange-pdf-node-binding");
80
+ if (typeof binding.convert != "function" || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1)
81
+ throw new TypeError("PDF binding does not implement the required configuration protocol");
82
+ return binding;
83
+ } catch (error) {
84
+ throw new import_index.ExchangeError(
85
+ import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED,
86
+ "Unable to load @univerjs-pro/exchange-pdf-node-binding",
87
+ { cause: error }
88
+ );
89
+ }
90
+ });
91
+ }
92
+ async function convertPdf(operation, request, input, config) {
93
+ let configuration = config && encodeInput(config), binding = await loadBinding();
94
+ try {
95
+ return configuration ? await binding.convert(operation, request, input, configuration) : await binding.convert(operation, request, input);
96
+ } catch (error) {
97
+ throw structuredExchangeError(error, import_index.ExchangeError);
98
+ }
99
+ }
100
+ function parseDiagnostics(metadata) {
101
+ try {
102
+ let value = JSON.parse(metadata);
103
+ if (typeof value != "object" || value === null || !("diagnostics" in value) || !Array.isArray(value.diagnostics))
104
+ throw new TypeError("PDF binding returned invalid success metadata");
105
+ for (let item of value.diagnostics)
106
+ if (typeof item != "object" || item === null || typeof item.code != "string" || typeof item.message != "string" || typeof item.details != "object" || item.details === null || Array.isArray(item.details))
107
+ throw new TypeError("PDF binding returned an invalid diagnostic");
108
+ return value.diagnostics;
109
+ } catch (error) {
110
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.CONVERSION_FAILED, "PDF binding returned invalid success metadata", {
111
+ cause: error
112
+ });
113
+ }
114
+ }
115
+ function prepareInput(action) {
116
+ try {
117
+ return action();
118
+ } 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
+ });
122
+ }
123
+ }
124
+ function encodeInput(value) {
125
+ return prepareInput(() => import_node_buffer.Buffer.from(JSON.stringify(value)));
126
+ }
127
+ function completeUnit(input) {
128
+ if (typeof input != "object" || input === null || !("document" in input) || !input.document)
129
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.INCOMPLETE_SNAPSHOT, "PDF conversion requires a complete document");
130
+ if ("documentShell" in input && input.documentShell != null || "fragmentBindings" in input && input.fragmentBindings != null || "fragmentIndex" in input && input.fragmentIndex != null)
131
+ throw new import_index.ExchangeError(
132
+ import_index.ExchangeErrorCode.INCOMPLETE_SNAPSHOT,
133
+ "PDF conversion requires an expanded unit without fragment references"
134
+ );
135
+ return prepareInput(() => (0, import_pdfs.normalizePdfUnitData)(input));
136
+ }
137
+ var adapter = {
138
+ async configure(snapshot) {
139
+ let configuration = encodeInput(snapshot), binding = await loadBinding();
140
+ try {
141
+ await binding.__internalExchangeConfigure(configuration);
142
+ } catch (error) {
143
+ throw structuredExchangeError(error, import_index.ExchangeError);
144
+ }
145
+ },
146
+ async quota(snapshot) {
147
+ let configuration = encodeInput(snapshot), binding = await loadBinding(), result;
148
+ try {
149
+ result = await binding.__internalExchangeGetExportQuota(configuration);
150
+ } catch (error) {
151
+ throw structuredExchangeError(error, import_index.ExchangeError);
152
+ }
153
+ try {
154
+ return JSON.parse(result);
155
+ } catch (error) {
156
+ throw new import_index.ExchangeError(import_index.ExchangeErrorCode.NATIVE_LOAD_FAILED, "PDF binding returned invalid quota metadata", {
157
+ cause: error
158
+ });
159
+ }
160
+ },
161
+ 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"))),
165
+ diagnostics: parseDiagnostics(result.metadata)
166
+ };
167
+ },
168
+ async export(input, options, config) {
169
+ let unit = completeUnit(input), result = await convertPdf(
170
+ 2,
171
+ encodeInput({ strictResources: options.strictResources ?? !0 }).toString("utf8"),
172
+ encodeInput(unit),
173
+ config
174
+ );
175
+ return { value: result.payload, diagnostics: parseDiagnostics(result.metadata) };
176
+ },
177
+ async toSnapshot(input) {
178
+ let unit = completeUnit(input), { snapshot } = await (0, import_collaboration.transformPdfDataToSnapshot)(
179
+ unit,
180
+ unit.id,
181
+ unit.rev ?? 0,
182
+ createSnapshotCollector().service
183
+ );
184
+ return { snapshot, sheetBlocks: [] };
185
+ },
186
+ fromSnapshot(snapshot) {
187
+ return prepareInput(() => completeUnit((0, import_collaboration.transformSnapshotToPdfData)(snapshot.snapshot)));
188
+ }
189
+ };
190
+ import_runtime.default.registerPdf(adapter);
package/lib/es/index.js CHANGED
@@ -1,391 +1 @@
1
- // src/index.ts
2
- import {
3
- transformBaseDataToSnapshot,
4
- transformDocumentDataToSnapshot,
5
- transformSlideDataToSnapshot,
6
- transformSnapshotToBaseData,
7
- transformSnapshotToDocumentData,
8
- transformSnapshotToSlideData,
9
- transformSnapshotToWorkbookData,
10
- transformWorkbookDataToSnapshot
11
- } from "@univerjs-pro/collaboration";
12
- import { UniverInstanceType } from "@univerjs/core";
13
- import { basename, extname } from "node:path";
14
- import { readFile, writeFile } from "node:fs/promises";
15
-
16
- // src/binding.ts
17
- import { createRequire } from "node:module";
18
- import process from "node:process";
19
-
20
- // src/types.ts
21
- var ExchangeFormat = /* @__PURE__ */ ((ExchangeFormat2) => (ExchangeFormat2.XLS = "xls", ExchangeFormat2.XLSX = "xlsx", ExchangeFormat2.CSV = "csv", ExchangeFormat2.TSV = "tsv", ExchangeFormat2.DOC = "doc", ExchangeFormat2.DOCX = "docx", ExchangeFormat2.PPT = "ppt", ExchangeFormat2.PPTX = "pptx", ExchangeFormat2))(ExchangeFormat || {}), FormulaCalculationMode = /* @__PURE__ */ ((FormulaCalculationMode2) => (FormulaCalculationMode2.FORCED = "forced", FormulaCalculationMode2.WHEN_EMPTY = "when_empty", FormulaCalculationMode2.NO = "no", FormulaCalculationMode2))(FormulaCalculationMode || {}), CsvTypeInferenceMode = /* @__PURE__ */ ((CsvTypeInferenceMode2) => (CsvTypeInferenceMode2.OFF = "off", CsvTypeInferenceMode2.SAFE = "safe", CsvTypeInferenceMode2.AGGRESSIVE = "aggressive", CsvTypeInferenceMode2))(CsvTypeInferenceMode || {}), CsvQuoteStyle = /* @__PURE__ */ ((CsvQuoteStyle2) => (CsvQuoteStyle2.MINIMAL = "minimal", CsvQuoteStyle2.ALWAYS = "always", CsvQuoteStyle2))(CsvQuoteStyle || {}), CsvLineEnding = /* @__PURE__ */ ((CsvLineEnding2) => (CsvLineEnding2.LF = "lf", CsvLineEnding2.CRLF = "cr_lf", CsvLineEnding2))(CsvLineEnding || {}), CsvValueMode = /* @__PURE__ */ ((CsvValueMode2) => (CsvValueMode2.DISPLAY = "display", CsvValueMode2.RAW = "raw", CsvValueMode2))(CsvValueMode || {}), CsvFormulaMode = /* @__PURE__ */ ((CsvFormulaMode2) => (CsvFormulaMode2.CACHED = "cached", CsvFormulaMode2.EXPRESSION = "expression", CsvFormulaMode2))(CsvFormulaMode || {}), BaseImportMode = /* @__PURE__ */ ((BaseImportMode2) => (BaseImportMode2.TABLES = "tables", BaseImportMode2.SHEETS = "sheets", BaseImportMode2.HYBRID = "hybrid", BaseImportMode2.AUTO = "auto", BaseImportMode2))(BaseImportMode || {}), BaseTypeInference = /* @__PURE__ */ ((BaseTypeInference2) => (BaseTypeInference2.NONE = "none", BaseTypeInference2.SAFE = "safe", BaseTypeInference2.AGGRESSIVE = "aggressive", BaseTypeInference2))(BaseTypeInference || {}), BaseFormulaPolicy = /* @__PURE__ */ ((BaseFormulaPolicy2) => (BaseFormulaPolicy2.VALUES = "values", BaseFormulaPolicy2.TEXT = "text", BaseFormulaPolicy2.FAIL = "fail", BaseFormulaPolicy2.CONVERT_THEN_VALUES = "convertThenValues", BaseFormulaPolicy2))(BaseFormulaPolicy || {}), BaseImagePolicy = /* @__PURE__ */ ((BaseImagePolicy2) => (BaseImagePolicy2.SAFE = "safe", BaseImagePolicy2.CELL_ONLY = "cell-only", BaseImagePolicy2.MEDIA_TABLE = "media-table", BaseImagePolicy2.NONE = "none", BaseImagePolicy2))(BaseImagePolicy || {}), BaseHeaderPolicy = /* @__PURE__ */ ((BaseHeaderPolicy2) => (BaseHeaderPolicy2.FIRST_ROW = "firstRow", BaseHeaderPolicy2.NONE = "none", BaseHeaderPolicy2))(BaseHeaderPolicy || {}), BaseExportMode = /* @__PURE__ */ ((BaseExportMode2) => (BaseExportMode2.TABLES = "tables", BaseExportMode2.RANGES = "ranges", BaseExportMode2))(BaseExportMode || {}), BaseAttachmentPolicy = /* @__PURE__ */ ((BaseAttachmentPolicy2) => (BaseAttachmentPolicy2.HYBRID = "hybrid", BaseAttachmentPolicy2.MANIFEST = "manifest", BaseAttachmentPolicy2.LINKS = "links", BaseAttachmentPolicy2.NONE = "none", BaseAttachmentPolicy2))(BaseAttachmentPolicy || {}), DocxCompatibilityMode = /* @__PURE__ */ ((DocxCompatibilityMode2) => (DocxCompatibilityMode2.TRADITIONAL = "traditional", DocxCompatibilityMode2.MODERN = "modern", DocxCompatibilityMode2))(DocxCompatibilityMode || {}), ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode2) => (ExchangeErrorCode2.INVALID_ARGUMENT = "INVALID_ARGUMENT", ExchangeErrorCode2.UNSUPPORTED_FORMAT = "UNSUPPORTED_FORMAT", ExchangeErrorCode2.INVALID_FILE = "INVALID_FILE", ExchangeErrorCode2.INCOMPLETE_SNAPSHOT = "INCOMPLETE_SNAPSHOT", ExchangeErrorCode2.IO_ERROR = "IO_ERROR", ExchangeErrorCode2.NATIVE_LOAD_FAILED = "NATIVE_LOAD_FAILED", ExchangeErrorCode2.CONVERSION_FAILED = "CONVERSION_FAILED", ExchangeErrorCode2))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
22
- constructor(code, message, options) {
23
- super(message, options);
24
- this.code = code;
25
- }
26
- code;
27
- name = "ExchangeError";
28
- };
29
-
30
- // src/binding.ts
31
- var nativeBinding = null, nativeBindingSource = null, nodeRequire = createRequire(import.meta.url);
32
- function errorMessage(error) {
33
- return error instanceof Error ? error.message : String(error);
34
- }
35
- async function loadNativeBinding() {
36
- if (nativeBinding)
37
- return nativeBinding;
38
- let errors = [];
39
- try {
40
- return nativeBinding = nodeRequire("@univerjs-pro/exchange-node-binding"), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
41
- } catch (error) {
42
- errors.push(`@univerjs-pro/exchange-node-binding: ${errorMessage(error)}`);
43
- }
44
- throw new ExchangeError(
45
- "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
46
- [
47
- "Failed to load native exchange binding.",
48
- `platform=${process.platform}`,
49
- `arch=${process.arch}`,
50
- "expected npm package=@univerjs-pro/exchange-node-binding",
51
- "attempted paths:",
52
- ...errors.map((item) => `- ${item}`)
53
- ].join(`
54
- `)
55
- );
56
- }
57
-
58
- // src/snapshot-collector.ts
59
- import { ErrorCode } from "@univerjs/protocol";
60
- function createSnapshotCollector() {
61
- let sheetBlocks = /* @__PURE__ */ new Map();
62
- return {
63
- // The public Pro conversion functions accept the host-wide service
64
- // contract even though these conversion paths use its two write methods.
65
- service: {
66
- async saveSheetBlock(_context, { block }) {
67
- return block ? (sheetBlocks.set(block.id, block), {
68
- blockID: block.id,
69
- error: { code: ErrorCode.OK, message: "" }
70
- }) : {
71
- blockID: "",
72
- error: { code: ErrorCode.UNDEFINED, message: "block is required" }
73
- };
74
- },
75
- async saveSnapshot() {
76
- return { error: { code: ErrorCode.OK, message: "" } };
77
- }
78
- },
79
- get sheetBlocks() {
80
- return [...sheetBlocks.values()];
81
- }
82
- };
83
- }
84
-
85
- // src/snapshot.ts
86
- import { Buffer as NodeBuffer } from "node:buffer";
87
- function bufferView(bytes) {
88
- return NodeBuffer.isBuffer(bytes) ? bytes : NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
89
- }
90
- function takeMetadata(owner, kind, metadata, ownerId) {
91
- if (!owner)
92
- return owner;
93
- let { originalMeta, ...rest } = owner;
94
- if (originalMeta instanceof Uint8Array)
95
- metadata.push({ kind, ownerId, data: bufferView(originalMeta) });
96
- else if (originalMeta != null)
97
- throw new TypeError(`${kind} originalMeta must be a Uint8Array`);
98
- return rest;
99
- }
100
- function toNativeSnapshot(value) {
101
- let metadata = [], source = value.snapshot, snapshot = { ...source }, sourceWorkbook = source.workbook;
102
- if (sourceWorkbook) {
103
- let workbook = takeMetadata(sourceWorkbook, "workbook", metadata), sourceSheets = sourceWorkbook.sheets;
104
- sourceSheets && (workbook.sheets = Object.fromEntries(
105
- Object.entries(sourceSheets).map(([sheetId, sheet]) => [
106
- sheetId,
107
- takeMetadata(sheet, "worksheet", metadata, sheetId)
108
- ])
109
- )), snapshot.workbook = workbook;
110
- }
111
- for (let kind of ["doc", "slide"]) {
112
- let owner = source[kind];
113
- owner && (snapshot[kind] = takeMetadata(owner, kind, metadata));
114
- }
115
- return {
116
- snapshotJson: NodeBuffer.from(JSON.stringify(snapshot)),
117
- metadata,
118
- sheetBlocks: value.sheetBlocks.map((block) => ({
119
- id: block.id,
120
- startRow: block.startRow,
121
- endRow: block.endRow,
122
- data: bufferView(block.data)
123
- }))
124
- };
125
- }
126
- function restoreMetadata(snapshot, metadata) {
127
- for (let entry of metadata) {
128
- let owner;
129
- if (entry.kind === "worksheet") {
130
- let sheets = snapshot.workbook?.sheets;
131
- owner = entry.ownerId ? sheets?.[entry.ownerId] : void 0;
132
- } else {
133
- if (entry.kind !== "workbook" && entry.kind !== "doc" && entry.kind !== "slide")
134
- throw new TypeError(`unsupported native snapshot metadata kind ${entry.kind}`);
135
- owner = snapshot[entry.kind];
136
- }
137
- if (!owner)
138
- throw new TypeError(`native snapshot metadata owner ${entry.kind}/${entry.ownerId ?? ""} is missing`);
139
- owner.originalMeta = entry.data;
140
- }
141
- }
142
- function fromNativeSnapshot(value) {
143
- let snapshot = JSON.parse(value.snapshotJson.toString("utf8"));
144
- return restoreMetadata(snapshot, value.metadata), {
145
- snapshot,
146
- sheetBlocks: value.sheetBlocks.map((block) => ({
147
- id: block.id,
148
- startRow: block.startRow,
149
- endRow: block.endRow,
150
- data: block.data
151
- }))
152
- };
153
- }
154
-
155
- // src/index.ts
156
- var FORMAT_BY_EXTENSION = {
157
- ".xls": "xls" /* XLS */,
158
- ".xlsx": "xlsx" /* XLSX */,
159
- ".csv": "csv" /* CSV */,
160
- ".tsv": "tsv" /* TSV */,
161
- ".doc": "doc" /* DOC */,
162
- ".docx": "docx" /* DOCX */,
163
- ".ppt": "ppt" /* PPT */,
164
- ".pptx": "pptx" /* PPTX */
165
- };
166
- function normalizeWorkbookSheetOrder(data) {
167
- let existingOrder = Array.isArray(data.sheetOrder) ? data.sheetOrder.filter((sheetId) => typeof sheetId == "string") : [], ordered = new Set(existingOrder), missingSheetIds = Object.keys(data.sheets).filter((sheetId) => !ordered.has(sheetId));
168
- return missingSheetIds.length === 0 ? data : { ...data, sheetOrder: [...existingOrder, ...missingSheetIds] };
169
- }
170
- function exchangeError(error, fallback) {
171
- if (error instanceof ExchangeError)
172
- return error;
173
- let message = error instanceof Error ? error.message : String(error), nativeCode = /^\[([A-Z_]+)]\s*/.exec(message)?.[1];
174
- return nativeCode && Object.values(ExchangeErrorCode).includes(nativeCode) ? new ExchangeError(nativeCode, message.replace(/^\[[A-Z_]+]\s*/, ""), {
175
- cause: error
176
- }) : error instanceof TypeError ? new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message, { cause: error }) : new ExchangeError(fallback, message, { cause: error });
177
- }
178
- function resolveFormat(fileName, format) {
179
- if (format)
180
- return format;
181
- let inferred = FORMAT_BY_EXTENSION[extname(fileName).toLowerCase()];
182
- if (!inferred)
183
- throw new ExchangeError(
184
- "UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
185
- `Cannot infer an exchange format from fileName: ${fileName}`
186
- );
187
- return inferred;
188
- }
189
- function nativeUnitType(type) {
190
- switch (type) {
191
- case UniverInstanceType.UNIVER_SHEET:
192
- return "sheet";
193
- case UniverInstanceType.UNIVER_BASE:
194
- return "base";
195
- case UniverInstanceType.UNIVER_DOC:
196
- return "doc";
197
- case UniverInstanceType.UNIVER_SLIDE:
198
- return "slide";
199
- default:
200
- throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, `Unsupported Univer unit type: ${type}`);
201
- }
202
- }
203
- function nativeImportOptions(options, fileName) {
204
- return {
205
- format: resolveFormat(fileName, options.format),
206
- unitType: nativeUnitType(options.type),
207
- fileName,
208
- unitId: options.unitId,
209
- minSheetRowCount: "minSheetRowCount" in options ? options.minSheetRowCount : void 0,
210
- minSheetColumnCount: "minSheetColumnCount" in options ? options.minSheetColumnCount : void 0,
211
- compatibilityMode: "compatibilityMode" in options ? options.compatibilityMode : void 0,
212
- csv: "csv" in options ? options.csv : void 0,
213
- base: options.type === UniverInstanceType.UNIVER_BASE ? {
214
- mode: options.mode,
215
- typeInference: options.typeInference,
216
- formulaPolicy: options.formulaPolicy,
217
- imagePolicy: options.imagePolicy,
218
- maxCells: options.maxCells,
219
- mapping: options.mapping
220
- } : void 0,
221
- formulaCalculation: "formulaCalculation" in options ? options.formulaCalculation : void 0
222
- };
223
- }
224
- function nativeExportOptions(options) {
225
- return {
226
- format: options.format,
227
- unitType: nativeUnitType(options.type),
228
- csv: "csv" in options ? options.csv : void 0,
229
- base: options.type === UniverInstanceType.UNIVER_BASE && options.format === "xlsx" /* XLSX */ ? {
230
- mode: options.mode,
231
- formulaPolicy: options.formulaPolicy,
232
- attachmentPolicy: options.attachmentPolicy,
233
- mapping: options.mapping
234
- } : void 0,
235
- formulaCalculation: "formulaCalculation" in options ? options.formulaCalculation : void 0
236
- };
237
- }
238
- async function importSnapshot(input, options, fileName) {
239
- try {
240
- let result = await (await loadNativeBinding()).exchangeImportToSnapshot(
241
- input,
242
- JSON.stringify(nativeImportOptions(options, fileName))
243
- );
244
- return fromNativeSnapshot(result);
245
- } catch (error) {
246
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
247
- }
248
- }
249
- async function snapshotToMemory(snapshot, type) {
250
- try {
251
- switch (type) {
252
- case UniverInstanceType.UNIVER_SHEET:
253
- return await transformSnapshotToWorkbookData(snapshot.snapshot, snapshot.sheetBlocks);
254
- case UniverInstanceType.UNIVER_BASE:
255
- return await transformSnapshotToBaseData(snapshot.snapshot, snapshot.sheetBlocks);
256
- case UniverInstanceType.UNIVER_DOC:
257
- return transformSnapshotToDocumentData(snapshot.snapshot);
258
- case UniverInstanceType.UNIVER_SLIDE:
259
- return transformSnapshotToSlideData(snapshot.snapshot);
260
- default:
261
- throw new TypeError(`Unsupported Univer unit type: ${type}`);
262
- }
263
- } catch (error) {
264
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
265
- }
266
- }
267
- async function memoryToSnapshot(data, options) {
268
- try {
269
- let unitId = data.id;
270
- if (!unitId)
271
- throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, "Export data must have a non-empty id");
272
- let rev = data.rev ?? 0, collector = createSnapshotCollector();
273
- switch (options.type) {
274
- case UniverInstanceType.UNIVER_SHEET: {
275
- let workbook = normalizeWorkbookSheetOrder(data), { snapshot } = await transformWorkbookDataToSnapshot(
276
- { metadata: void 0 },
277
- workbook,
278
- unitId,
279
- rev,
280
- collector.service
281
- );
282
- return { snapshot, sheetBlocks: collector.sheetBlocks };
283
- }
284
- case UniverInstanceType.UNIVER_BASE: {
285
- let { snapshot } = await transformBaseDataToSnapshot(
286
- { metadata: void 0 },
287
- data,
288
- unitId,
289
- rev,
290
- collector.service
291
- );
292
- return { snapshot, sheetBlocks: collector.sheetBlocks };
293
- }
294
- case UniverInstanceType.UNIVER_DOC: {
295
- let { snapshot } = await transformDocumentDataToSnapshot(
296
- { metadata: void 0 },
297
- data,
298
- unitId,
299
- rev,
300
- collector.service
301
- );
302
- return { snapshot, sheetBlocks: [] };
303
- }
304
- case UniverInstanceType.UNIVER_SLIDE: {
305
- let slide = data, { snapshot } = await transformSlideDataToSnapshot(
306
- slide.resources,
307
- slide,
308
- unitId,
309
- rev,
310
- collector.service
311
- );
312
- return { snapshot, sheetBlocks: [] };
313
- }
314
- default:
315
- throw new TypeError("Unsupported Univer unit type");
316
- }
317
- } catch (error) {
318
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
319
- }
320
- }
321
- async function importFile(path, options) {
322
- let snapshot = await importFileToSnapshot(path, options);
323
- return snapshotToMemory(snapshot, options.type);
324
- }
325
- async function importBuffer(input, options) {
326
- let snapshot = await importSnapshot(input, options, options.fileName);
327
- return snapshotToMemory(snapshot, options.type);
328
- }
329
- async function importFileToSnapshot(path, options) {
330
- let fileName = options.fileName ?? basename(path), input;
331
- try {
332
- input = await readFile(path);
333
- } catch (error) {
334
- throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
335
- }
336
- return importSnapshot(input, options, fileName);
337
- }
338
- async function importBufferToSnapshot(input, options) {
339
- return importSnapshot(input, options, options.fileName);
340
- }
341
- async function exportToBuffer(data, options) {
342
- return exportSnapshotToBuffer(await memoryToSnapshot(data, options), options);
343
- }
344
- async function exportToFile(data, path, options) {
345
- await exportSnapshotToFile(await memoryToSnapshot(data, options), path, options);
346
- }
347
- async function exportSnapshotToBuffer(snapshot, options) {
348
- try {
349
- return await (await loadNativeBinding()).exchangeExportSnapshot(
350
- toNativeSnapshot(snapshot),
351
- JSON.stringify(nativeExportOptions(options))
352
- );
353
- } catch (error) {
354
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
355
- }
356
- }
357
- async function exportSnapshotToFile(snapshot, path, options) {
358
- let output = await exportSnapshotToBuffer(snapshot, options);
359
- try {
360
- await writeFile(path, output);
361
- } catch (error) {
362
- throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
363
- }
364
- }
365
- export {
366
- BaseAttachmentPolicy,
367
- BaseExportMode,
368
- BaseFormulaPolicy,
369
- BaseHeaderPolicy,
370
- BaseImagePolicy,
371
- BaseImportMode,
372
- BaseTypeInference,
373
- CsvFormulaMode,
374
- CsvLineEnding,
375
- CsvQuoteStyle,
376
- CsvTypeInferenceMode,
377
- CsvValueMode,
378
- DocxCompatibilityMode,
379
- ExchangeError,
380
- ExchangeErrorCode,
381
- ExchangeFormat,
382
- FormulaCalculationMode,
383
- exportSnapshotToBuffer,
384
- exportSnapshotToFile,
385
- exportToBuffer,
386
- exportToFile,
387
- importBuffer,
388
- importBufferToSnapshot,
389
- importFile,
390
- importFileToSnapshot
391
- };
1
+ export { BaseAttachmentPolicy, BaseExportMode, BaseFormulaPolicy, BaseHeaderPolicy, BaseImagePolicy, BaseImportMode, BaseTypeInference, CsvFormulaMode, CsvLineEnding, CsvQuoteStyle, CsvTypeInferenceMode, CsvValueMode, DocxCompatibilityMode, ExchangeError, ExchangeErrorCode, ExchangeFormat, FormulaCalculationMode, configureExchange, exportSnapshotToBuffer, exportSnapshotToFile, exportToBuffer, exportToFile, getExportQuota, importBuffer, importBufferToSnapshot, importFile, importFileToSnapshot } from '../cjs/index.cjs';
package/lib/es/pdf.js ADDED
@@ -0,0 +1 @@
1
+ import '../cjs/pdf.cjs';
@@ -0,0 +1,93 @@
1
+ // One physical CommonJS module shared by both public module formats in this JS context.
2
+ let pdfAdapter;
3
+ let current;
4
+ let version = 0;
5
+ let queue = Promise.resolve();
6
+ let initialization;
7
+
8
+ function invalid(field) {
9
+ const error = new Error('Invalid argument.');
10
+ error.code = 'INVALID_ARGUMENT';
11
+ error.details = { field };
12
+ return error;
13
+ }
14
+ function validate(config) {
15
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) throw invalid('config');
16
+ const copy = {};
17
+ for (const key of Reflect.ownKeys(config)) {
18
+ if (!['license', 'licenseKey'].includes(key)) throw invalid(String(key));
19
+ const value = config[key];
20
+ if (typeof value !== 'string') throw invalid(key);
21
+ copy[key] = value;
22
+ }
23
+ const hasLicense = Object.hasOwn(copy, 'license');
24
+ const hasKey = Object.hasOwn(copy, 'licenseKey');
25
+ if (hasLicense !== hasKey) throw invalid(hasLicense ? 'licenseKey' : 'license');
26
+ return Object.freeze(copy);
27
+ }
28
+ function enqueue(action) {
29
+ const result = queue.then(action);
30
+ queue = result.then(() => undefined, () => undefined);
31
+ return result;
32
+ }
33
+ function allocate(config) {
34
+ if (version === Number.MAX_SAFE_INTEGER) throw invalid('version');
35
+ return Object.freeze({ protocolVersion: 1, version: ++version, config });
36
+ }
37
+ function candidate(config) {
38
+ if (current && current.version === version && current.config.license === config.license && current.config.licenseKey === config.licenseKey) {
39
+ return current;
40
+ }
41
+ return allocate(config);
42
+ }
43
+ function publish(snapshot) {
44
+ current = snapshot;
45
+ return snapshot;
46
+ }
47
+ module.exports = {
48
+ registerPdf(adapter) {
49
+ if (pdfAdapter && pdfAdapter !== adapter) {
50
+ throw new Error('A different PDF adapter is already registered for this installation');
51
+ }
52
+ pdfAdapter = adapter;
53
+ },
54
+ getPdf() { return pdfAdapter; },
55
+ configure(config, prepare) {
56
+ const validated = validate(config);
57
+ return enqueue(async () => {
58
+ const snapshot = candidate(validated);
59
+ await prepare(snapshot);
60
+ publish(snapshot);
61
+ });
62
+ },
63
+ // Returns the exact snapshot captured at call entry, including during asynchronous initialization.
64
+ capture(override) {
65
+ if (override !== undefined) {
66
+ if (override === null || typeof override !== 'object' || Array.isArray(override)) throw invalid('options');
67
+ const config = {};
68
+ for (const key of ['license', 'licenseKey']) {
69
+ if (Object.hasOwn(override, key)) config[key] = override[key];
70
+ }
71
+ if (Reflect.ownKeys(config).length !== 0) return candidate(validate(config));
72
+ }
73
+ if (current) {
74
+ // Resuming defaults selects them again for native cache residency. Only
75
+ // the snapshot identity changes; credentials and prior captures stay fixed.
76
+ return current.version === version ? current : publish(allocate(current.config));
77
+ }
78
+ if (!initialization) {
79
+ // Fix environment presence and values at entry. A configure already
80
+ // ahead in the queue still takes effect before this lazy selection.
81
+ const config = {};
82
+ if (process.env.UNIVER_LICENSE !== undefined) config.license = process.env.UNIVER_LICENSE;
83
+ if (process.env.UNIVER_LICENSE_KEY !== undefined) config.licenseKey = process.env.UNIVER_LICENSE_KEY;
84
+ const task = enqueue(() => {
85
+ if (current) return current;
86
+ return publish(candidate(validate(config)));
87
+ });
88
+ initialization = task;
89
+ task.then(() => { initialization = undefined; }, () => { initialization = undefined; });
90
+ }
91
+ return initialization;
92
+ },
93
+ };