@univerjs-pro/exchange-node 1.2.0 → 1.3.1
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/README.md +127 -3
- package/lib/cjs/index.cjs +156 -29
- package/lib/cjs/pdf.cjs +190 -0
- package/lib/es/index.js +1 -391
- package/lib/es/pdf.js +1 -0
- package/lib/shared/runtime.cjs +96 -0
- package/lib/types/index.d.ts +14 -249
- package/lib/types/pdf.d.ts +23 -0
- package/lib/types/types.d.ts +299 -0
- package/package.json +26 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @univerjs-pro/exchange-node
|
|
2
2
|
|
|
3
|
-
Node.js SDK for converting between Office formats, Univer unit data, and complete Univer snapshots.
|
|
3
|
+
Node.js SDK for converting between Office/PDF formats, Univer unit data, and complete Univer snapshots.
|
|
4
4
|
|
|
5
5
|
The package exposes two API families:
|
|
6
6
|
|
|
@@ -9,12 +9,14 @@ The package exposes two API families:
|
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
12
|
-
Keep this package and its Univer SDK dependencies on the same SDK version:
|
|
12
|
+
Keep this package and its Univer SDK dependencies on the same SDK version for non-dev releases:
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
15
|
pnpm add @univerjs-pro/exchange-node
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
Native Binding dependencies allow same-minor patches from the version paired with the SDK; the application lock controls the installed patch.
|
|
19
|
+
|
|
18
20
|
## Import
|
|
19
21
|
|
|
20
22
|
```ts
|
|
@@ -68,4 +70,126 @@ Snapshot APIs materialize the complete aggregate in memory. They do not call a S
|
|
|
68
70
|
|
|
69
71
|
The initial release supports Sheet and Base import from XLS, XLSX, CSV, and TSV; Doc import from DOC and DOCX; and Slide import from PPT and PPTX. Export supports XLSX, CSV, TSV, DOCX, and PPTX for their corresponding unit types.
|
|
70
72
|
|
|
71
|
-
|
|
73
|
+
Office native packages are published for Linux x64 GNU, Linux arm64 GNU, Windows x64 MSVC, and macOS x64/arm64.
|
|
74
|
+
|
|
75
|
+
## License and monthly export quota
|
|
76
|
+
|
|
77
|
+
Set both `UNIVER_LICENSE` and `UNIVER_LICENSE_KEY` for automatic configuration. The first export or quota query reads them once; no `configureExchange` call is required. Unset, empty or whitespace-only environment values count as absent; when both are absent, Free applies. A single nonblank value is an incomplete pair. Nonblank contents are passed unchanged. This normalization applies only to environment fallbacks; explicit configuration and per-operation values remain unchanged and are strictly validated.
|
|
78
|
+
|
|
79
|
+
To configure credentials explicitly:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { configureExchange, getExportQuota } from '@univerjs-pro/exchange-node';
|
|
83
|
+
|
|
84
|
+
await configureExchange({
|
|
85
|
+
license: '<license content>',
|
|
86
|
+
licenseKey: '<licenseKey content>',
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const quota = await getExportQuota();
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`license` and `licenseKey` are the complete credential contents, not file paths. Provide both together. Explicit configuration completely ignores the environment. `configureExchange({})` explicitly selects Free; an incomplete pair returns `INVALID_ARGUMENT` without mixing sources. The first complete environment configuration is fixed even if a later native operation fails. An incomplete environment pair rejects without committing configuration and a new call may try again. The environment is not reread after initialization; use an explicit call to replace credentials, and await it before starting exports that should use the new configuration.
|
|
93
|
+
|
|
94
|
+
Exports and quota queries also accept a complete `license` / `licenseKey` pair in their options. This overrides defaults for that operation only:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const quota = await getExportQuota({ license, licenseKey });
|
|
98
|
+
const output = await exportToBuffer(workbook, {
|
|
99
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
100
|
+
format: ExchangeFormat.XLSX,
|
|
101
|
+
license,
|
|
102
|
+
licenseKey,
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Omitting both fields uses the default configuration. A partial pair returns `INVALID_ARGUMENT`; credentials are never combined across sources. Explicit values, including empty strings, are strictly validated as supplied; they are not treated as absent or retried with the default credentials. Per-operation credentials do not initialize or modify defaults. Successful commercial exports are tracked separately for each License ID; returning to the same ID resumes its usage. Free usage uses the shared Office/PDF quota.
|
|
107
|
+
|
|
108
|
+
`getExportQuota({ license, licenseKey })` queries shared Office/PDF quota. Omit credentials to query the default configuration. It accepts no Unit type and does not check the SDK version, activation time, or type entitlement; actual exports perform those checks. Importing `/pdf` selects the PDF query backend, so PDF-only consumers do not load Office binding. No alternate backend is tried on failure.
|
|
109
|
+
|
|
110
|
+
The response has nine fields:
|
|
111
|
+
|
|
112
|
+
- `licenseStatus`: `not_configured`, `expired`, or `valid` (not expired); this status does not grant permission to export. Invalid credentials reject the Promise.
|
|
113
|
+
- `expiresAt`: UTC ISO export subscription expiry, or `null` if absent.
|
|
114
|
+
- `observedAt`: UTC ISO snapshot time.
|
|
115
|
+
- `limit`, `used`, `reserved`, `remaining`: monthly limit, successful uses, in-flight uses and available balance; all `null` when unlimited.
|
|
116
|
+
- `periodStart`, `periodEnd`: UTC ISO monthly quota bounds, inclusive start and exclusive end; `null` when unlimited.
|
|
117
|
+
|
|
118
|
+
Queries neither reserve nor consume quota. Before activation, limited quota describes the first authorization month with a future `periodStart`. Zero remaining is a successful query. The snapshot does not guarantee admission of the next export. `periodEnd` is the next monthly quota boundary, while `expiresAt` ends the subscription. A valid subscription always uses commercial quota: exhaustion or unavailable type entitlement cannot select Free. Subscription expiry selects the existing remaining Free quota without resetting it.
|
|
119
|
+
|
|
120
|
+
Free allows 10 successful exports per authorization month. Purchased licenses determine commercial quota, concurrency and version entitlements. Neither Free nor commercial licenses impose file-size or cell-count limits. Use the query response for the applicable period and balance. Unused monthly quota does not carry over. Office and PDF exports share quota. Imports do not require export authorization and do not consume export quota.
|
|
121
|
+
|
|
122
|
+
Ordinary-user installation and export do not require sudo. The process needs writable local persistent storage for export usage. If that storage cannot be used, the SDK returns `LICENSE_USAGE_STORAGE_ERROR`; preserve the complete error and contact technical support.
|
|
123
|
+
|
|
124
|
+
A successful Buffer conversion counts once. File APIs then write that Buffer: a subsequent file-write failure is `IO_ERROR` and does not refund the conversion. Upload or download failures after successful conversion do not refund usage either. Each successful repeated conversion counts again. When quota is exhausted, wait for the next authorization period or update the license.
|
|
125
|
+
|
|
126
|
+
Errors use `ExchangeError` with a stable `code`, a diagnostic `message` containing the concrete failure reason, and `cause` where available. Handle `code` rather than parsing message text. Applications decide how to log errors and what to display to their end users.
|
|
127
|
+
|
|
128
|
+
The following table compares quota queries and actual exports. Both APIs return Promises; use `await` and `try/catch` to handle failures.
|
|
129
|
+
|
|
130
|
+
| Code | Operation | Meaning and action |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `LICENSE_EXPORT_QUOTA_EXCEEDED` | Export only | Insufficient export quota for the current period. Query quota or contact sales to adjust the license. |
|
|
133
|
+
| `LICENSE_INVALID` | Query, export | The license is invalid. Check the complete credentials or contact the license provider for an update. |
|
|
134
|
+
| `LICENSE_POLICY_INVALID` | Query, export | The authorization configuration does not meet SDK requirements. Contact the license provider for an update. |
|
|
135
|
+
| `LICENSE_UNIT_TYPE_REJECTED` | Export only | This export type is not licensed or its type entitlement has expired. Provide a valid license covering the type. |
|
|
136
|
+
| `LICENSE_NOT_YET_EFFECTIVE` | Export only | Authorization has not started yet. Use it after its effective date. |
|
|
137
|
+
| `LICENSE_VERSION_NOT_ALLOWED` | Export only | The current SDK version is outside the licensed range. Use a matching version or update the license. |
|
|
138
|
+
| `LICENSE_CONCURRENCY_TIMEOUT` | Export only | Waiting for available export concurrency timed out. Reduce concurrent exports before submitting again. |
|
|
139
|
+
| `LICENSE_USAGE_STATE_INVALID` | Query, export | License usage status cannot be verified. Preserve the error and contact technical support. |
|
|
140
|
+
| `LICENSE_USAGE_STORAGE_ERROR` | Query, export | License usage processing failed. Preserve the error, contact technical support, and avoid automatic resubmission. |
|
|
141
|
+
| `INVALID_ARGUMENT` | Query, export | Incomplete arguments or credentials. Check the configuration. |
|
|
142
|
+
| `NATIVE_LOAD_FAILED` | Query, export | A native SDK component could not load. Check package and runtime compatibility. |
|
|
143
|
+
| `IO_ERROR` | Export only | File input/output failed. An output-write failure after successful conversion has already consumed an export. |
|
|
144
|
+
| `UNSUPPORTED_FORMAT` | Export only | The format is unsupported or incompatible with the Unit type. Check export options. |
|
|
145
|
+
| `INVALID_FILE` | Export only | The conversion input is invalid. Check its contents. |
|
|
146
|
+
| `INCOMPLETE_SNAPSHOT` | Export only | Export data is incomplete. Provide complete data or a complete Snapshot. |
|
|
147
|
+
| `CONVERSION_FAILED` | Export only | Conversion failed. Retain the error and check the input contents. |
|
|
148
|
+
|
|
149
|
+
Applications may derive expiry reminders from `licenseStatus` and `expiresAt`. No separate notice list or automatic logging is emitted. Supplied invalid credentials reject configuration, queries and exports with `LICENSE_INVALID`. If usage processing fails, do not infer whether a count was consumed from the error alone; preserve the complete error for support.
|
|
150
|
+
ESM and CommonJS share configuration within the same JavaScript context. Each `worker_threads` Worker must configure itself or initialize from its environment; Workers share the export quota, not their configuration. Exports capture configuration when the public method is called; a later configuration change applies to subsequently started exports. A failed explicit configuration leaves the previous configuration in effect.
|
|
151
|
+
|
|
152
|
+
## Optional PDF support
|
|
153
|
+
|
|
154
|
+
Install the optional backend with the SDK, then execute the PDF side-effect import before converting:
|
|
155
|
+
|
|
156
|
+
```sh
|
|
157
|
+
pnpm add @univerjs-pro/exchange-node @univerjs-pro/exchange-pdf-node-binding
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import '@univerjs-pro/exchange-node/pdf';
|
|
162
|
+
import { UniverInstanceType } from '@univerjs/core';
|
|
163
|
+
import { ExchangeFormat, importBuffer, exportToBuffer } from '@univerjs-pro/exchange-node';
|
|
164
|
+
|
|
165
|
+
const pdf = await importBuffer(pdfBuffer, {
|
|
166
|
+
type: UniverInstanceType.UNIVER_PDF,
|
|
167
|
+
format: ExchangeFormat.PDF,
|
|
168
|
+
fileName: 'input.pdf',
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const output = await exportToBuffer(pdf, {
|
|
172
|
+
type: UniverInstanceType.UNIVER_PDF,
|
|
173
|
+
format: ExchangeFormat.PDF,
|
|
174
|
+
onDiagnostics: async (items) => {
|
|
175
|
+
// The application decides whether to display or record these messages.
|
|
176
|
+
for (const item of items) console.warn(item.code, item.message, item.details);
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The same eight Buffer/File and Unit/Snapshot methods support PDF. PDF conversion operates between PDF files and PDF Unit/Snapshot data; it does not convert Office units to PDF. The optional backend loads when a PDF conversion, PDF quota query, or configuration after registration is requested. Import `/pdf` before calling `configureExchange` in PDF-only applications so configuration uses the PDF backend without loading the Office native library. The side-effect import itself does not load native code. Office-only applications do not need it. Without the runtime side-effect import, PDF conversion rejects with `UNSUPPORTED_FORMAT`. TypeScript augmentation applies to the compilation program; importing only its types does not initialize the runtime.
|
|
182
|
+
|
|
183
|
+
PDF native packages support Linux x64/arm64 with glibc, macOS x64/arm64, and Windows x64. Linux musl and Windows arm64 are unsupported. Each platform package contains a single `.node` file; applications do not need a separate Go executable or project dynamic library.
|
|
184
|
+
|
|
185
|
+
For services that require process-level fault isolation, run PDF conversion in a dedicated Node process or conversion worker service. The addon runs native code in its host process; `worker_threads` and asynchronous APIs do not isolate fatal native crashes. Limit in-flight conversions based on document size and measured process memory, and report abnormal worker exits as task failures.
|
|
186
|
+
|
|
187
|
+
Imported PDF units contain their document resources. Preserve `document`, its asset streams, `metadata`, and `editState` when saving them. Snapshot APIs use the existing complete aggregate representation; server resource IDs alone do not provide the bytes required for offline export, and the SDK does not fetch external resources automatically. The SDK performs the Unit/Snapshot transforms without creating a Univer runtime or applying edits a second time.
|
|
188
|
+
|
|
189
|
+
Export fails by default if a required image is missing or undecodable. Set `strictResources: false` only when the application accepts omission of those images. It does not ignore file IO, engine, or unrelated conversion failures. Use `onDiagnostics` to receive the resulting messages and their asset/page identifiers.
|
|
190
|
+
|
|
191
|
+
`onDiagnostics` is optional on import and export. It receives one nonempty batch per successful conversion and is awaited before the method returns or writes the destination file. An empty batch does not invoke it; the SDK does not log or retain a global history. Conversion failures reject the Promise instead of reporting a successful diagnostic batch. Exceptions thrown or rejected by the application's callback propagate unchanged. A destination write failure uses `IO_ERROR`; it does not trigger another conversion.
|
|
192
|
+
|
|
193
|
+
Handle conversion failures through the existing `ExchangeError` and its `code`. `NATIVE_LOAD_FAILED` means that the optional platform package could not initialize; `CONVERSION_FAILED` means the conversion failed. For PDF resource failures, the message includes the applicable asset, page and entry identifiers; the native error remains available as `error.cause`. These failures do not invoke `onDiagnostics`.
|
|
194
|
+
|
|
195
|
+
The PDF backend uses private per-conversion temporary files and requires writable OS temporary storage. Embedded resources are materialized there and removed before returning. Existing system/configured font lookup still applies; this package does not promise identical font appearance across hosts.
|
package/lib/cjs/index.cjs
CHANGED
|
@@ -42,23 +42,25 @@ __export(index_exports, {
|
|
|
42
42
|
ExchangeErrorCode: () => ExchangeErrorCode,
|
|
43
43
|
ExchangeFormat: () => ExchangeFormat,
|
|
44
44
|
FormulaCalculationMode: () => FormulaCalculationMode,
|
|
45
|
+
configureExchange: () => configureExchange,
|
|
45
46
|
exportSnapshotToBuffer: () => exportSnapshotToBuffer,
|
|
46
47
|
exportSnapshotToFile: () => exportSnapshotToFile,
|
|
47
48
|
exportToBuffer: () => exportToBuffer,
|
|
48
49
|
exportToFile: () => exportToFile,
|
|
50
|
+
getExportQuota: () => getExportQuota,
|
|
49
51
|
importBuffer: () => importBuffer,
|
|
50
52
|
importBufferToSnapshot: () => importBufferToSnapshot,
|
|
51
53
|
importFile: () => importFile,
|
|
52
54
|
importFileToSnapshot: () => importFileToSnapshot
|
|
53
55
|
});
|
|
54
56
|
module.exports = __toCommonJS(index_exports);
|
|
55
|
-
var import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core"), import_node_path = require("node:path"), import_promises = require("node:fs/promises");
|
|
57
|
+
var import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core"), import_node_path = require("node:path"), import_promises = require("node:fs/promises"), import_node_buffer2 = require("node:buffer");
|
|
56
58
|
|
|
57
59
|
// src/binding.ts
|
|
58
60
|
var import_node_module = require("node:module"), import_node_process = __toESM(require("node:process"), 1);
|
|
59
61
|
|
|
60
62
|
// src/types.ts
|
|
61
|
-
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 {
|
|
63
|
+
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.PDF = "pdf", 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.LICENSE_EXPORT_QUOTA_EXCEEDED = "LICENSE_EXPORT_QUOTA_EXCEEDED", ExchangeErrorCode2.LICENSE_INVALID = "LICENSE_INVALID", ExchangeErrorCode2.LICENSE_POLICY_INVALID = "LICENSE_POLICY_INVALID", ExchangeErrorCode2.LICENSE_NOT_YET_EFFECTIVE = "LICENSE_NOT_YET_EFFECTIVE", ExchangeErrorCode2.LICENSE_UNIT_TYPE_REJECTED = "LICENSE_UNIT_TYPE_REJECTED", ExchangeErrorCode2.LICENSE_VERSION_NOT_ALLOWED = "LICENSE_VERSION_NOT_ALLOWED", ExchangeErrorCode2.LICENSE_CONCURRENCY_TIMEOUT = "LICENSE_CONCURRENCY_TIMEOUT", ExchangeErrorCode2.LICENSE_USAGE_STATE_INVALID = "LICENSE_USAGE_STATE_INVALID", ExchangeErrorCode2.LICENSE_USAGE_STORAGE_ERROR = "LICENSE_USAGE_STORAGE_ERROR", ExchangeErrorCode2))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
|
|
62
64
|
constructor(code, message, options) {
|
|
63
65
|
super(message, options);
|
|
64
66
|
this.code = code;
|
|
@@ -72,12 +74,21 @@ var nativeBinding = null, nativeBindingSource = null, nodeRequire = (0, import_n
|
|
|
72
74
|
function errorMessage(error) {
|
|
73
75
|
return error instanceof Error ? error.message : String(error);
|
|
74
76
|
}
|
|
77
|
+
function validateBinding(binding) {
|
|
78
|
+
try {
|
|
79
|
+
if (!binding || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1 || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.exchangeExportSnapshot != "function")
|
|
80
|
+
throw new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
|
|
81
|
+
return binding;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw error instanceof ExchangeError ? error : new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
75
86
|
async function loadNativeBinding() {
|
|
76
87
|
if (nativeBinding)
|
|
77
88
|
return nativeBinding;
|
|
78
89
|
let errors = [];
|
|
79
90
|
try {
|
|
80
|
-
return nativeBinding = nodeRequire("@univerjs-pro/exchange-node-binding"), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
|
|
91
|
+
return nativeBinding = validateBinding(nodeRequire("@univerjs-pro/exchange-node-binding")), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
|
|
81
92
|
} catch (error) {
|
|
82
93
|
errors.push(`@univerjs-pro/exchange-node-binding: ${errorMessage(error)}`);
|
|
83
94
|
}
|
|
@@ -95,6 +106,13 @@ async function loadNativeBinding() {
|
|
|
95
106
|
);
|
|
96
107
|
}
|
|
97
108
|
|
|
109
|
+
// src/errors.ts
|
|
110
|
+
function structuredExchangeError(error, ErrorClass = ExchangeError) {
|
|
111
|
+
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, {
|
|
112
|
+
cause: error
|
|
113
|
+
}) : new ErrorClass("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Invalid native exchange error protocol.");
|
|
114
|
+
}
|
|
115
|
+
|
|
98
116
|
// src/snapshot-collector.ts
|
|
99
117
|
var import_protocol = require("@univerjs/protocol");
|
|
100
118
|
function createSnapshotCollector() {
|
|
@@ -192,6 +210,14 @@ function fromNativeSnapshot(value) {
|
|
|
192
210
|
};
|
|
193
211
|
}
|
|
194
212
|
|
|
213
|
+
// src/index.ts
|
|
214
|
+
var import_runtime = __toESM(require("../shared/runtime.cjs"), 1);
|
|
215
|
+
|
|
216
|
+
// src/diagnostics.ts
|
|
217
|
+
async function deliverDiagnostics(options, diagnostics) {
|
|
218
|
+
diagnostics.length !== 0 && options.onDiagnostics && await options.onDiagnostics(diagnostics);
|
|
219
|
+
}
|
|
220
|
+
|
|
195
221
|
// src/index.ts
|
|
196
222
|
var FORMAT_BY_EXTENSION = {
|
|
197
223
|
".xls": "xls" /* XLS */,
|
|
@@ -201,8 +227,25 @@ var FORMAT_BY_EXTENSION = {
|
|
|
201
227
|
".doc": "doc" /* DOC */,
|
|
202
228
|
".docx": "docx" /* DOCX */,
|
|
203
229
|
".ppt": "ppt" /* PPT */,
|
|
204
|
-
".pptx": "pptx" /* PPTX
|
|
230
|
+
".pptx": "pptx" /* PPTX */,
|
|
231
|
+
".pdf": "pdf" /* PDF */
|
|
205
232
|
};
|
|
233
|
+
function pdfAdapter(type, format) {
|
|
234
|
+
if (type !== import_core.UniverInstanceType.UNIVER_PDF && format !== "pdf" /* PDF */)
|
|
235
|
+
return;
|
|
236
|
+
if (type !== import_core.UniverInstanceType.UNIVER_PDF || format !== "pdf" /* PDF */)
|
|
237
|
+
throw new ExchangeError(
|
|
238
|
+
"UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
|
|
239
|
+
"PDF conversion requires PDF unit type and PDF format"
|
|
240
|
+
);
|
|
241
|
+
let adapter = import_runtime.default.getPdf();
|
|
242
|
+
if (!adapter)
|
|
243
|
+
throw new ExchangeError(
|
|
244
|
+
"UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
|
|
245
|
+
"Enable PDF conversion by importing '@univerjs-pro/exchange-node/pdf' first"
|
|
246
|
+
);
|
|
247
|
+
return adapter;
|
|
248
|
+
}
|
|
206
249
|
function normalizeWorkbookSheetOrder(data) {
|
|
207
250
|
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));
|
|
208
251
|
return missingSheetIds.length === 0 ? data : { ...data, sheetOrder: [...existingOrder, ...missingSheetIds] };
|
|
@@ -215,6 +258,31 @@ function exchangeError(error, fallback) {
|
|
|
215
258
|
cause: error
|
|
216
259
|
}) : error instanceof TypeError ? new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message, { cause: error }) : new ExchangeError(fallback, message, { cause: error });
|
|
217
260
|
}
|
|
261
|
+
async function configureExchange(config) {
|
|
262
|
+
try {
|
|
263
|
+
let adapter = import_runtime.default.getPdf();
|
|
264
|
+
await import_runtime.default.configure(config, async (snapshot) => {
|
|
265
|
+
adapter ? await adapter.configure(snapshot) : await (await loadNativeBinding()).__internalExchangeConfigure(configBuffer(snapshot));
|
|
266
|
+
});
|
|
267
|
+
} catch (error) {
|
|
268
|
+
throw structuredExchangeError(error);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function configBuffer(snapshot) {
|
|
272
|
+
return import_node_buffer2.Buffer.from(JSON.stringify(snapshot));
|
|
273
|
+
}
|
|
274
|
+
async function getExportQuota(options = {}) {
|
|
275
|
+
try {
|
|
276
|
+
if (options === null || typeof options != "object" || Array.isArray(options) || Reflect.ownKeys(options).some((key) => key !== "license" && key !== "licenseKey"))
|
|
277
|
+
throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, "Invalid argument: options.");
|
|
278
|
+
let snapshot = await import_runtime.default.capture(options), adapter = import_runtime.default.getPdf();
|
|
279
|
+
if (adapter) return await adapter.quota(snapshot);
|
|
280
|
+
let binding = await loadNativeBinding();
|
|
281
|
+
return JSON.parse(await binding.__internalExchangeGetExportQuota(configBuffer(snapshot)));
|
|
282
|
+
} catch (error) {
|
|
283
|
+
throw structuredExchangeError(error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
218
286
|
function resolveFormat(fileName, format) {
|
|
219
287
|
if (format)
|
|
220
288
|
return format;
|
|
@@ -358,49 +426,106 @@ async function memoryToSnapshot(data, options) {
|
|
|
358
426
|
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
359
427
|
}
|
|
360
428
|
}
|
|
429
|
+
async function readInput(path) {
|
|
430
|
+
try {
|
|
431
|
+
return await (0, import_promises.readFile)(path);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async function importResult(input, options, fileName, asSnapshot) {
|
|
437
|
+
let result;
|
|
438
|
+
try {
|
|
439
|
+
let adapter = pdfAdapter(options.type, resolveFormat(fileName, options.format));
|
|
440
|
+
if (adapter) {
|
|
441
|
+
let converted = await adapter.import(input, { fileName, unitId: options.unitId });
|
|
442
|
+
result = {
|
|
443
|
+
value: asSnapshot ? await adapter.toSnapshot(converted.value) : converted.value,
|
|
444
|
+
diagnostics: converted.diagnostics
|
|
445
|
+
};
|
|
446
|
+
} else {
|
|
447
|
+
let snapshot = await importSnapshot(input, options, fileName);
|
|
448
|
+
result = { value: asSnapshot ? snapshot : await snapshotToMemory(snapshot, options.type), diagnostics: [] };
|
|
449
|
+
}
|
|
450
|
+
} catch (error) {
|
|
451
|
+
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
452
|
+
}
|
|
453
|
+
return await deliverDiagnostics(options, result.diagnostics), result.value;
|
|
454
|
+
}
|
|
361
455
|
async function importFile(path, options) {
|
|
362
|
-
|
|
363
|
-
return snapshotToMemory(snapshot, options.type);
|
|
456
|
+
return importResult(await readInput(path), options, options.fileName ?? (0, import_node_path.basename)(path), !1);
|
|
364
457
|
}
|
|
365
458
|
async function importBuffer(input, options) {
|
|
366
|
-
|
|
367
|
-
return snapshotToMemory(snapshot, options.type);
|
|
459
|
+
return importResult(input, options, options.fileName, !1);
|
|
368
460
|
}
|
|
369
461
|
async function importFileToSnapshot(path, options) {
|
|
370
|
-
|
|
462
|
+
return importResult(
|
|
463
|
+
await readInput(path),
|
|
464
|
+
options,
|
|
465
|
+
options.fileName ?? (0, import_node_path.basename)(path),
|
|
466
|
+
!0
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
async function importBufferToSnapshot(input, options) {
|
|
470
|
+
return importResult(input, options, options.fileName, !0);
|
|
471
|
+
}
|
|
472
|
+
async function exportResult(data, options, isSnapshot, captured) {
|
|
473
|
+
let result;
|
|
371
474
|
try {
|
|
372
|
-
|
|
475
|
+
let config = await captured, adapter = pdfAdapter(options.type, options.format);
|
|
476
|
+
if (adapter) {
|
|
477
|
+
let unit = isSnapshot ? adapter.fromSnapshot(data) : data;
|
|
478
|
+
result = await adapter.export(
|
|
479
|
+
unit,
|
|
480
|
+
{ strictResources: "strictResources" in options ? options.strictResources : void 0 },
|
|
481
|
+
config
|
|
482
|
+
);
|
|
483
|
+
} else {
|
|
484
|
+
let snapshot = isSnapshot ? data : await memoryToSnapshot(data, options), input, nativeOptions;
|
|
485
|
+
try {
|
|
486
|
+
input = toNativeSnapshot(snapshot), nativeOptions = JSON.stringify(nativeExportOptions(options));
|
|
487
|
+
} catch (error) {
|
|
488
|
+
throw error instanceof ExchangeError ? error : new ExchangeError(
|
|
489
|
+
"INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
|
|
490
|
+
`Invalid export arguments: ${error instanceof Error ? error.message : String(error)}`,
|
|
491
|
+
{ cause: error }
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
result = {
|
|
495
|
+
value: await (await loadNativeBinding()).exchangeExportSnapshot(input, nativeOptions, configBuffer(config)),
|
|
496
|
+
diagnostics: []
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw structuredExchangeError(error);
|
|
501
|
+
}
|
|
502
|
+
return await deliverDiagnostics(options, result.diagnostics), result.value;
|
|
503
|
+
}
|
|
504
|
+
async function writeOutput(path, output) {
|
|
505
|
+
try {
|
|
506
|
+
await (0, import_promises.writeFile)(path, output);
|
|
373
507
|
} catch (error) {
|
|
374
508
|
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
375
509
|
}
|
|
376
|
-
return importSnapshot(input, options, fileName);
|
|
377
510
|
}
|
|
378
|
-
|
|
379
|
-
|
|
511
|
+
function captureExportConfig(options) {
|
|
512
|
+
try {
|
|
513
|
+
return import_runtime.default.capture(options);
|
|
514
|
+
} catch (error) {
|
|
515
|
+
return Promise.reject(structuredExchangeError(error));
|
|
516
|
+
}
|
|
380
517
|
}
|
|
381
518
|
async function exportToBuffer(data, options) {
|
|
382
|
-
return
|
|
519
|
+
return exportResult(data, options, !1, captureExportConfig(options));
|
|
383
520
|
}
|
|
384
521
|
async function exportToFile(data, path, options) {
|
|
385
|
-
await
|
|
522
|
+
await writeOutput(path, await exportResult(data, options, !1, captureExportConfig(options)));
|
|
386
523
|
}
|
|
387
524
|
async function exportSnapshotToBuffer(snapshot, options) {
|
|
388
|
-
|
|
389
|
-
return await (await loadNativeBinding()).exchangeExportSnapshot(
|
|
390
|
-
toNativeSnapshot(snapshot),
|
|
391
|
-
JSON.stringify(nativeExportOptions(options))
|
|
392
|
-
);
|
|
393
|
-
} catch (error) {
|
|
394
|
-
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
395
|
-
}
|
|
525
|
+
return exportResult(snapshot, options, !0, captureExportConfig(options));
|
|
396
526
|
}
|
|
397
527
|
async function exportSnapshotToFile(snapshot, path, options) {
|
|
398
|
-
|
|
399
|
-
try {
|
|
400
|
-
await (0, import_promises.writeFile)(path, output);
|
|
401
|
-
} catch (error) {
|
|
402
|
-
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
403
|
-
}
|
|
528
|
+
await writeOutput(path, await exportResult(snapshot, options, !0, captureExportConfig(options)));
|
|
404
529
|
}
|
|
405
530
|
// Annotate the CommonJS export names for ESM import in node:
|
|
406
531
|
0 && (module.exports = {
|
|
@@ -421,10 +546,12 @@ async function exportSnapshotToFile(snapshot, path, options) {
|
|
|
421
546
|
ExchangeErrorCode,
|
|
422
547
|
ExchangeFormat,
|
|
423
548
|
FormulaCalculationMode,
|
|
549
|
+
configureExchange,
|
|
424
550
|
exportSnapshotToBuffer,
|
|
425
551
|
exportSnapshotToFile,
|
|
426
552
|
exportToBuffer,
|
|
427
553
|
exportToFile,
|
|
554
|
+
getExportQuota,
|
|
428
555
|
importBuffer,
|
|
429
556
|
importBufferToSnapshot,
|
|
430
557
|
importFile,
|
package/lib/cjs/pdf.cjs
ADDED
|
@@ -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);
|