@univerjs-pro/collaboration-exchange-service 0.0.0-stage → 1.4.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # @univerjs-pro/collaboration-exchange-service
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ `UniverExchangeService` imports Office and PDF files into Univer and exports Univer data back to files. It converts with `@univerjs-pro/exchange-node` inside the process, creates and reads Units through the collaboration Service, and stores source files and results in the File Service.
6
+
7
+ The Service has no network dependency. `@univerjs-pro/collaboration-exchange-endpoint` serves the import and export requests of the Univer frontend on top of it.
8
+
9
+ ## Installation and usage
10
+
11
+ ```bash
12
+ pnpm add \
13
+ @univerjs-pro/collaboration-exchange-service \
14
+ @univerjs-pro/exchange-node
15
+ ```
16
+
17
+ `@univerjs-pro/exchange-node` is a peer dependency: install the version this package declares.
18
+
19
+ ```ts
20
+ const exchangeService = new UniverExchangeService({ collabService, fileService });
21
+
22
+ exchangeService.use('export', async (ctx, next) => {
23
+ if (ctx.snapshot) await requireUnitViewIfExists(ctx.userID, ctx.snapshot.snapshot.unitID);
24
+ await next();
25
+ });
26
+
27
+ await exchangeService.dispose();
28
+ await fileService.dispose();
29
+ ```
30
+
31
+ | Option | Description |
32
+ | --- | --- |
33
+ | `collabService` | Required. A `UniverCollabService`, or a wrapper with `createUnitFromSnapshot` and `getUnitLoadDataWithBlocks` that passes the context through unchanged. Its `createUnit` and `readUnitData` middleware apply to every import and export. |
34
+ | `fileService` | Required. The `UniverFileService` that receives client uploads. |
35
+ | `logger` | Receives failures the Service handles itself, such as a failed early file delete. Without it, `warn` and `error` go to the console. |
36
+ | `runtime` | Optional. `{ execution }`, with the same values as the `UniverCollabService` `runtime.execution` option, for the Runtime that materializes snapshots for `unitID` exports. It defaults to Worker execution with Workers started when the Service is constructed. `in-process` starts no Worker, but materialization then runs on the main thread and a large Unit blocks the event loop. |
37
+
38
+ The constructor throws a `TypeError` when a required option is missing. Dispose Exchange before the File Service and the collaboration Service.
39
+
40
+ ## Supported conversions
41
+
42
+ | Type | Import | Export |
43
+ | --- | --- | --- |
44
+ | Sheet | xls, xlsx, csv, tsv | xlsx, csv, tsv |
45
+ | Doc | doc, docx | docx |
46
+ | Slide | ppt, pptx | pptx |
47
+ | Base | xls, xlsx, csv, tsv | xlsx, csv |
48
+ | PDF | pdf | pdf |
49
+
50
+ The name of the uploaded file decides the import format. Board is rejected. For PDF, install `@univerjs-pro/exchange-pdf-node-binding` and run `import '@univerjs-pro/exchange-node/pdf'` at startup; without them a PDF task fails with `UNSUPPORTED_FORMAT`.
51
+
52
+ ## License and quota
53
+
54
+ Configure the License through `exchange-node`: set `UNIVER_LICENSE` and `UNIVER_LICENSE_KEY`, or call `configureExchange()`. A License passed only to the `UniverCollabService` constructor does not reach `exchange-node`. Query the remaining quota with `getExportQuota()` from `exchange-node`.
55
+
56
+ ## Methods
57
+
58
+ Every method takes a caller context `{ userID, customData? }` and reports failures as a rejected Promise.
59
+
60
+ | Method | Result |
61
+ | --- | --- |
62
+ | `createImportTask(input, ctx)` | the `taskID` |
63
+ | `createExportTask(input, ctx)` | the `taskID` |
64
+ | `getTask(taskID, ctx)` | the task; only its creator can read it |
65
+
66
+ A create call validates the request, checks ownership and runs middleware before it resolves. A rejected call creates no task. Conversion then runs in the background.
67
+
68
+ | `ImportInput` field | Description |
69
+ | --- | --- |
70
+ | `type` | `UniverType` |
71
+ | `outputType` | `1` creates a collaborative Unit, `2` writes snapshot JSON to a file |
72
+ | `fileID` | an `HttpImport` file uploaded by the caller, or with `sourceUnitID` a `UnitEmbedded` attachment of that Unit |
73
+ | `sourceUnitID` | optional; the Unit whose stored attachment `fileID` is converted into an online Unit, requires `outputType: 1` |
74
+ | `options` | front-end import options |
75
+
76
+ | `ExportInput` field | Description |
77
+ | --- | --- |
78
+ | `type` | `UniverType` |
79
+ | `unitID` or `jsonID` | exactly one: a stored Unit, or an `HttpImport` file holding `{ snapshot, sheetBlocks }` JSON |
80
+ | `format` | the target format |
81
+ | `options` | front-end export options; Sheet CSV/TSV needs `sheet.csv.sheetId` and Base CSV needs `base.csv.tableId`; `oleAttachmentSource` picks the attachment version |
82
+
83
+ Tasks are `pending`, `done` with `result`, or `failed` with the original `error`. Results are `{ outputType: 1, unitID }`, `{ outputType: 2, jsonID }` or `{ fileID }`; `jsonID` and `fileID` are `HttpExport` files owned by the caller.
84
+
85
+ Finished tasks stay readable for one hour. Tasks live in this Service instance, so run one import and export node and route all three Endpoint routes to it. After a restart, `getTask` reports the task as missing.
86
+
87
+ ## Files
88
+
89
+ Importing to a Unit stores images and attachments of Sheet, Doc and Slide as `UnitEmbedded` files of the new Unit. If the import fails, those files are deleted. Base, PDF and `outputType: 2` keep them inline in the snapshot.
90
+
91
+ The source upload and the snapshot JSON of a `jsonID` export are deleted when their task ends. Results stay until File cleanup removes them.
92
+
93
+ Exporting reads `UnitEmbedded` files of the exported Unit. URL images export as a transparent placeholder, and `options.sheet.useImageUrl` has no effect.
94
+
95
+ When the import and export node is separate from the collaboration node, give both `UniverFileService` instances the same storage (`@univerjs-pro/collaboration-file-database-postgres` with `@univerjs-pro/collaboration-file-blob-s3`), and install the same permission middleware on both `UniverCollabService` instances. The SQLite and local directory adapters are for single-node deployments.
96
+
97
+ ## OLE attachments
98
+
99
+ Exports write embedded attachments back as their original files.
100
+
101
+ An import with `sourceUnitID` (`importAttachmentToUnitId`) converts a stored attachment into an online Unit: `fileID` is then a `UnitEmbedded` file of that Unit, not an upload, and `outputType` must be `1`. The Service checks that the file belongs to `sourceUnitID`; check the caller's access to that Unit in `import` middleware, where `request.sourceUnitID` is set. The new Unit is created like any other import, and the attachment stays with its host Unit. Configure `ole.getLink` on `UniverDrawingPlugin` so that the attachment toolbar offers "convert to online".
102
+
103
+ Exports embed the original attachment unless `options.oleAttachmentSource` is `'online'`. Then every attachment that was converted to an online Unit is exported from that Unit's current content instead: the Service reads each child Unit with the caller's context, so `readUnitData` middleware runs for it, and its `UnitEmbedded` files are read like the host's. `exchange-node` walks nested attachments, limits them to 8 levels, 64 Units and 50 MiB of embedded output, and fails the task if any child cannot be loaded; a failed task never falls back to the originals. The task counts as one export. Only exports that take files accept `'online'` (Sheet XLSX, Doc, Slide and PDF); CSV, TSV and Base exports return `INVALID_REQUEST`.
104
+
105
+ ## Middleware
106
+
107
+ `use(action, middleware)` returns a `Disposable`. Middleware calls `next()` to continue or throws to reject; the call then rejects with that error and creates no task. `ctx.request` is read-only. Each action runs once per request and is never retried.
108
+
109
+ | Action | Runs | Visible fields | Typical use |
110
+ | --- | --- | --- | --- |
111
+ | `import` | after validation and the source ownership check, before the task is created | `userID`, `customData`, `request` (`type`, `outputType`, `fileID`, `sourceUnitID`, `options`) | rate limits, quota, restricting document types, audit, access to `sourceUnitID` |
112
+ | `export` | after validation, before the task is created; after the Unit is read for `unitID`, after the snapshot is decoded for `jsonID` | `userID`, `customData`, `request` (`type`, `unitID` or `jsonID`, `format`, `options`); `snapshot` for `jsonID` | restricting exports per user, audit; child Units of an online export are read later and pass `readUnitData` instead |
113
+
114
+ A `jsonID` snapshot comes from the client, so `snapshot.unitID` is unverified and may name a Unit that does not exist. Applications that serve both `jsonID` export and collaborative images check in `export` middleware that the caller can view `snapshot.unitID` when that Unit exists, as the example above does. `ctx.snapshot` is shared by reference and is read-only by contract.
115
+
116
+ ## Errors
117
+
118
+ The Service raises `ExchangeServiceError` with a `code`. Failures from the File Service, the collaboration Service and `exchange-node` keep their own error types.
119
+
120
+ | `code` | Meaning |
121
+ | --- | --- |
122
+ | `INVALID_REQUEST` | invalid or unsupported input |
123
+ | `FILE_NOT_FOUND` | the file does not exist or does not belong to the caller |
124
+ | `TASK_NOT_FOUND` | the task does not exist or does not belong to the caller |
125
+ | `UNAUTHENTICATED` | raised by the Endpoint for a request without a user |
126
+ | `SERVICE_DISPOSED` | the Service is disposed |
127
+
128
+ `dispose()` drops all tasks. Conversions still running end without creating a Unit or a result file.
@@ -0,0 +1,128 @@
1
+ # @univerjs-pro/collaboration-exchange-service
2
+
3
+ [English](./README.md) | 简体中文
4
+
5
+ `UniverExchangeService` 把 Office 和 PDF 文件导入 Univer,并把 Univer 数据导出为文件。它在进程内用 `@univerjs-pro/exchange-node` 转换,通过协同 Service 创建和读取 Unit,把源文件和结果存入 File Service。
6
+
7
+ Service 不依赖网络。`@univerjs-pro/collaboration-exchange-endpoint` 在它之上处理 Univer 前端的导入导出请求。
8
+
9
+ ## 安装与使用
10
+
11
+ ```bash
12
+ pnpm add \
13
+ @univerjs-pro/collaboration-exchange-service \
14
+ @univerjs-pro/exchange-node
15
+ ```
16
+
17
+ `@univerjs-pro/exchange-node` 是 peer dependency,安装本包声明的版本。
18
+
19
+ ```ts
20
+ const exchangeService = new UniverExchangeService({ collabService, fileService });
21
+
22
+ exchangeService.use('export', async (ctx, next) => {
23
+ if (ctx.snapshot) await requireUnitViewIfExists(ctx.userID, ctx.snapshot.snapshot.unitID);
24
+ await next();
25
+ });
26
+
27
+ await exchangeService.dispose();
28
+ await fileService.dispose();
29
+ ```
30
+
31
+ | 选项 | 说明 |
32
+ | --- | --- |
33
+ | `collabService` | 必填。`UniverCollabService`,或带 `createUnitFromSnapshot`、`getUnitLoadDataWithBlocks` 且原样传递 context 的包装层。它的 `createUnit`、`readUnitData` middleware 对每次导入导出生效。 |
34
+ | `fileService` | 必填。接收客户端上传的 `UniverFileService`。 |
35
+ | `logger` | 接收 Service 自行处理的失败,例如提前删除文件失败。未传时 `warn`、`error` 写 console。 |
36
+ | `runtime` | 可选。`{ execution }`,取值与 `UniverCollabService` 的 `runtime.execution` 相同,用于按 `unitID` 导出时生成快照的 Runtime。默认用 Worker 执行,Worker 在构造 Service 时启动。`in-process` 不启动 Worker,但生成快照在主线程运行,大 Unit 会阻塞事件循环。 |
37
+
38
+ 缺少必填选项时构造函数抛 `TypeError`。释放时先释放 Exchange,再释放 File Service 和协同 Service。
39
+
40
+ ## 支持的转换
41
+
42
+ | 类型 | 导入 | 导出 |
43
+ | --- | --- | --- |
44
+ | Sheet | xls、xlsx、csv、tsv | xlsx、csv、tsv |
45
+ | Doc | doc、docx | docx |
46
+ | Slide | ppt、pptx | pptx |
47
+ | Base | xls、xlsx、csv、tsv | xlsx、csv |
48
+ | PDF | pdf | pdf |
49
+
50
+ 导入格式由上传文件的文件名决定。Board 会被拒绝。使用 PDF 时安装 `@univerjs-pro/exchange-pdf-node-binding`,并在启动时执行 `import '@univerjs-pro/exchange-node/pdf'`;否则 PDF 任务以 `UNSUPPORTED_FORMAT` 失败。
51
+
52
+ ## 许可证与额度
53
+
54
+ 通过 `exchange-node` 配置许可证:设置 `UNIVER_LICENSE` 和 `UNIVER_LICENSE_KEY`,或调用 `configureExchange()`。只传给 `UniverCollabService` 构造参数的许可证不会到达 `exchange-node`。用 `exchange-node` 的 `getExportQuota()` 查询剩余额度。
55
+
56
+ ## 方法
57
+
58
+ 每个方法都接收调用方 context `{ userID, customData? }`,失败时返回 rejected Promise。
59
+
60
+ | 方法 | 结果 |
61
+ | --- | --- |
62
+ | `createImportTask(input, ctx)` | `taskID` |
63
+ | `createExportTask(input, ctx)` | `taskID` |
64
+ | `getTask(taskID, ctx)` | 任务;只有发起人能读取 |
65
+
66
+ 创建调用在 resolve 前完成请求校验、归属检查和 middleware。被拒绝的调用不创建任务。之后转换在后台执行。
67
+
68
+ | `ImportInput` 字段 | 说明 |
69
+ | --- | --- |
70
+ | `type` | `UniverType` |
71
+ | `outputType` | `1` 创建协同 Unit,`2` 把快照 JSON 写入文件 |
72
+ | `fileID` | 调用方上传的 `HttpImport` 文件;带 `sourceUnitID` 时为该 Unit 的 `UnitEmbedded` 附件 |
73
+ | `sourceUnitID` | 可选。把该 Unit 已存储的附件 `fileID` 转成在线 Unit;要求 `outputType: 1` |
74
+ | `options` | 前端导入选项 |
75
+
76
+ | `ExportInput` 字段 | 说明 |
77
+ | --- | --- |
78
+ | `type` | `UniverType` |
79
+ | `unitID` 或 `jsonID` | 二选一:已存储的 Unit,或内容为 `{ snapshot, sheetBlocks }` JSON 的 `HttpImport` 文件 |
80
+ | `format` | 目标格式 |
81
+ | `options` | 前端导出选项;Sheet CSV/TSV 需要 `sheet.csv.sheetId`,Base CSV 需要 `base.csv.tableId`;`oleAttachmentSource` 选择附件版本 |
82
+
83
+ 任务状态为 `pending`、带 `result` 的 `done`,或带原始 `error` 的 `failed`。结果是 `{ outputType: 1, unitID }`、`{ outputType: 2, jsonID }` 或 `{ fileID }`;`jsonID` 和 `fileID` 是属于调用方的 `HttpExport` 文件。
84
+
85
+ 结束的任务保留 1 小时可读。任务保存在这个 Service 实例中,因此只部署一个导入导出节点,并把 Endpoint 的三条路由都发到这个节点。节点重启后,`getTask` 报告任务不存在。
86
+
87
+ ## 文件
88
+
89
+ 导入成 Unit 时,Sheet、Doc、Slide 的图片和附件存为新 Unit 的 `UnitEmbedded` 文件;导入失败时这些文件被删除。Base、PDF 和 `outputType: 2` 把它们内联在快照中。
90
+
91
+ 源文件和 `jsonID` 导出的快照 JSON 在任务结束时删除。结果文件保留到 File 清理。
92
+
93
+ 导出时读取被导出 Unit 的 `UnitEmbedded` 文件。URL 图片导出为透明占位图,`options.sheet.useImageUrl` 不生效。
94
+
95
+ 导入导出节点与协同节点分开部署时,两边的 `UniverFileService` 使用同一份存储(`@univerjs-pro/collaboration-file-database-postgres` 与 `@univerjs-pro/collaboration-file-blob-s3`),两边的 `UniverCollabService` 安装相同的权限 middleware。SQLite 和本地目录 adapter 用于单机部署。
96
+
97
+ ## OLE 附件
98
+
99
+ 导出时把嵌入的附件写回原始文件。
100
+
101
+ 导入时传 `sourceUnitID`(`importAttachmentToUnitId`)把已存储的附件转成在线 Unit:此时 `fileID` 是该 Unit 的 `UnitEmbedded` 文件而不是上传文件,`outputType` 必须为 `1`。Service 校验文件属于 `sourceUnitID`;发起人对该 Unit 的访问权限在 `import` middleware 中检查,那里 `request.sourceUnitID` 有值。新 Unit 与普通导入一样创建,附件仍属于宿主 Unit。在 `UniverDrawingPlugin` 配置 `ole.getLink`,附件工具栏才会出现“转为在线”。
102
+
103
+ 导出默认嵌入原始附件;`options.oleAttachmentSource` 为 `'online'` 时,已转成在线 Unit 的附件改为按该 Unit 的当前内容导出:Service 用调用方 context 读取每个子 Unit,`readUnitData` middleware 对其生效,子 Unit 的 `UnitEmbedded` 文件与宿主的一样读取。`exchange-node` 自行遍历嵌套附件,限制为 8 层、64 个 Unit、50 MiB 嵌入输出,任一子 Unit 读不到则任务失败,不回退到原始附件。整个任务计一次导出额度。只有接受文件的导出接受 `'online'`(Sheet XLSX、Doc、Slide、PDF);CSV、TSV 与 Base 导出返回 `INVALID_REQUEST`。
104
+
105
+ ## Middleware
106
+
107
+ `use(action, middleware)` 返回 `Disposable`。Middleware 调用 `next()` 继续,抛错则拒绝;调用随之以该错误 reject,不创建任务。`ctx.request` 只读。每个 action 每次请求执行一次,不重试。
108
+
109
+ | Action | 触发时机 | 可见字段 | 典型用途 |
110
+ | --- | --- | --- | --- |
111
+ | `import` | 校验与源文件归属检查之后、创建任务前 | `userID`、`customData`、`request`(`type`、`outputType`、`fileID`、`sourceUnitID`、`options`) | 限流、配额、限制文档类型、审计、`sourceUnitID` 的访问权限 |
112
+ | `export` | 校验之后、创建任务前;`unitID` 导出在读取 Unit 之后,`jsonID` 导出在解码快照之后 | `userID`、`customData`、`request`(`type`、`unitID` 或 `jsonID`、`format`、`options`);`jsonID` 导出另有 `snapshot` | 按用户限制导出、审计;在线导出的子 Unit 在之后读取,走 `readUnitData` |
113
+
114
+ `jsonID` 的快照来自客户端,`snapshot.unitID` 未经验证,也可能指向不存在的 Unit。同时开放 `jsonID` 导出和协同图片的应用,在 `export` middleware 中检查:该 Unit 存在时调用方对 `snapshot.unitID` 有查看权限,做法见上面的示例。`ctx.snapshot` 按引用共享,约定只读。
115
+
116
+ ## 错误
117
+
118
+ Service 抛出带 `code` 的 `ExchangeServiceError`。来自 File Service、协同 Service 和 `exchange-node` 的失败保留各自的错误类型。
119
+
120
+ | `code` | 含义 |
121
+ | --- | --- |
122
+ | `INVALID_REQUEST` | 输入无效或不支持 |
123
+ | `FILE_NOT_FOUND` | 文件不存在或不属于调用方 |
124
+ | `TASK_NOT_FOUND` | 任务不存在或不属于调用方 |
125
+ | `UNAUTHENTICATED` | Endpoint 对没有用户的请求抛出 |
126
+ | `SERVICE_DISPOSED` | Service 已释放 |
127
+
128
+ `dispose()` 丢弃所有任务。仍在运行的转换结束时不创建 Unit,也不写结果文件。
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs-pro/exchange-node"),t=require("@univerjs/protocol"),n=require("node:buffer"),r=require("node:crypto"),i=require("@univerjs-pro/collaboration-service");var a=class extends Error{code;constructor(e,t,n={}){super(t,{cause:n.cause}),this.name=`ExchangeServiceError`,this.code=e}};function o(e){return new a(`INVALID_REQUEST`,e)}function s(e){return new a(`FILE_NOT_FOUND`,`File ${e} does not exist`)}function c(e){return new a(`TASK_NOT_FOUND`,`Task ${e} does not exist`)}var l=new Map([[t.UniverType.UNIVER_SHEET,[e.ExchangeFormat.XLS,e.ExchangeFormat.XLSX,e.ExchangeFormat.CSV,e.ExchangeFormat.TSV]],[t.UniverType.UNIVER_DOC,[e.ExchangeFormat.DOC,e.ExchangeFormat.DOCX]],[t.UniverType.UNIVER_SLIDE,[e.ExchangeFormat.PPT,e.ExchangeFormat.PPTX]],[t.UniverType.UNIVER_BASE,[e.ExchangeFormat.XLS,e.ExchangeFormat.XLSX,e.ExchangeFormat.CSV,e.ExchangeFormat.TSV]],[t.UniverType.UNIVER_PDF,[e.ExchangeFormat.PDF]]]),u=new Map([[t.UniverType.UNIVER_SHEET,[e.ExchangeFormat.XLSX,e.ExchangeFormat.CSV,e.ExchangeFormat.TSV]],[t.UniverType.UNIVER_DOC,[e.ExchangeFormat.DOCX]],[t.UniverType.UNIVER_SLIDE,[e.ExchangeFormat.PPTX]],[t.UniverType.UNIVER_BASE,[e.ExchangeFormat.XLSX,e.ExchangeFormat.CSV]],[t.UniverType.UNIVER_PDF,[e.ExchangeFormat.PDF]]]),d={[e.ExchangeFormat.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,[e.ExchangeFormat.CSV]:`text/csv; charset=utf-8`,[e.ExchangeFormat.TSV]:`text/tab-separated-values; charset=utf-8`,[e.ExchangeFormat.DOCX]:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,[e.ExchangeFormat.PPTX]:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,[e.ExchangeFormat.PDF]:`application/pdf`};function f(e){if(typeof e==`number`&&l.has(e))return e;throw o(`Unsupported Unit type ${String(e)}`)}function p(e,t){let n=t.lastIndexOf(`.`),r=n<0?``:t.slice(n+1).toLowerCase(),i=l.get(e)?.find(e=>e===r);if(!i)throw o(`Cannot import "${t}" as Unit type ${e}`);return i}function m(e,t){let n=u.get(e)?.find(e=>e===t);if(!n)throw o(`Cannot export Unit type ${e} as ${String(t)}`);return n}function h(e){return d[e]??`application/octet-stream`}function g(e,t,n){let r=e?.trim()||t;return r.toLowerCase().endsWith(`.${n}`)?r:`${r}.${n}`}function _(e){if(!e.isRunning())throw new a(`SERVICE_DISPOSED`,`Exchange Service is disposed`)}var v={"convert-then-values":e.BaseFormulaPolicy.CONVERT_THEN_VALUES,values:e.BaseFormulaPolicy.VALUES,text:e.BaseFormulaPolicy.TEXT,fail:e.BaseFormulaPolicy.FAIL},y=Object.values(e.BaseImportMode),ee=Object.values(e.BaseExportMode),te=Object.values(e.DocxCompatibilityMode),ne=[`original`,`online`];function b(e,n,r){let i=w(r,`options`),a={type:e,format:n};if(e===t.UniverType.UNIVER_SHEET){let e=w(i?.sheet,`options.sheet`);C(a,`minSheetRowCount`,T(e?.minSheetRowCount,`options.sheet.minSheetRowCount`)),C(a,`minSheetColumnCount`,T(e?.minSheetColumnCount,`options.sheet.minSheetColumnCount`))}else if(e===t.UniverType.UNIVER_BASE){let e=w(w(i?.base,`options.base`)?.xlsx,`options.base.xlsx`);C(a,`mode`,E(e?.baseMode,y,`options.base.xlsx.baseMode`)),C(a,`formulaPolicy`,D(e?.baseFormulaPolicy,`options.base.xlsx.baseFormulaPolicy`))}else e===t.UniverType.UNIVER_DOC&&C(a,`compatibilityMode`,E(w(i?.doc,`options.doc`)?.docType,te,`options.doc.docType`));return a}function x(n,r,i){let a=w(i,`options`),s={type:n,format:r};if(E(a?.oleAttachmentSource,ne,`options.oleAttachmentSource`)===`online`){if(!S(n,r))throw o(`options.oleAttachmentSource "online" is not supported for this export`);s.ole={attachmentSource:`online`}}let c=r===e.ExchangeFormat.CSV||r===e.ExchangeFormat.TSV;if(n===t.UniverType.UNIVER_SHEET&&c)s.csv={worksheetId:O(w(w(a?.sheet,`options.sheet`)?.csv,`options.sheet.csv`)?.sheetId,`options.sheet.csv.sheetId`)};else if(n===t.UniverType.UNIVER_BASE){let e=w(a?.base,`options.base`);if(c)s.csv={tableId:O(w(e?.csv,`options.base.csv`)?.tableId,`options.base.csv.tableId`)};else{let t=w(e?.xlsx,`options.base.xlsx`);C(s,`mode`,E(t?.baseExportMode,ee,`options.base.xlsx.baseExportMode`)),C(s,`formulaPolicy`,D(t?.baseFormulaPolicy,`options.base.xlsx.baseFormulaPolicy`))}}return s}function re(e){return e===t.UniverType.UNIVER_SHEET||e===t.UniverType.UNIVER_DOC||e===t.UniverType.UNIVER_SLIDE}function S(n,r){return n===t.UniverType.UNIVER_SHEET?r===e.ExchangeFormat.XLSX:n===t.UniverType.UNIVER_DOC||n===t.UniverType.UNIVER_SLIDE||n===t.UniverType.UNIVER_PDF}function C(e,t,n){n!==void 0&&(e[t]=n)}function w(e,t){if(e!=null){if(typeof e!=`object`||Array.isArray(e))throw o(`${t} must be an object`);return e}}function T(e,t){if(e!=null){if(!Number.isSafeInteger(e)||e<0)throw o(`${t} must be a non-negative integer`);return e}}function E(e,t,n){if(e!=null){if(typeof e!=`string`||!t.includes(e))throw o(`${n} must be one of ${t.join(`, `)}`);return e}}function D(e,t){let n=E(e,Object.keys(v),t);return n===void 0?void 0:v[n]}function O(e,t){if(typeof e!=`string`||e.length===0)throw o(`${t} is required for CSV/TSV export`);return e}async function ie(t,n){let{files:r}=n,{source:i}=t,a=i.kind===`unit`?await n.units.materialize(i.data):i.snapshot,o=a.snapshot.unitID,s=new Set,c=S(t.type,t.format)?r.exportLoader(o,t.context,{trustedHost:i.kind===`unit`,children:s}):void 0,l=t.options.ole&&{attachmentSource:`online`,loadOnlineUnit:async e=>{let r=await n.units.materialize(await n.units.read(e.unitId,k(e),t.context));return s.add(e.unitId),r}},u=await(0,e.exportSnapshotToBuffer)(a,{...t.options,...c?{files:c}:{},...l?{ole:l}:{}});return _(n),{fileID:await r.saveResult({name:g(A(a.snapshot),o,t.format),contentType:h(t.format),bytes:u},t.context)}}function k(e){return e.type}function A(e){return(e.workbook??e.doc??e.slide??e.pdf??e.board)?.name}var j=new Uint8Array(n.Buffer.from(`iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`,`base64`)),M=new Set,N=class{_fileService;_logger;constructor(e,t){this._fileService=e,this._logger=t}async requireUpload(e,n){let r=await this._fileService.getFile(e,n);if(!r||r.source!==t.FileSource.HttpImport||r.assign!==n.userID)throw s(e);return r}async requireAttachment(e,n,r){let i=await this._fileService.getFile(e,r);if(!i||i.source!==t.FileSource.UnitEmbedded||i.assign!==n)throw s(e);return i}async read(e,t){let{content:n}=await this._fileService.openFile(e,t);return P(n)}createUnitFileSink(e,n){let r=[];return{store:async i=>{let a=await this._fileService.createFile({name:i.name,contentType:i.mimeType||`application/octet-stream`,source:t.FileSource.UnitEmbedded,assign:e,content:F(i.bytes)},n);return r.push(a.fileID),{mode:`reference`,source:a.fileID}},discard:async()=>{for(let e of r.splice(0))await this.deleteQuietly(e,n)}}}exportLoader(e,t,n){let r=n.children??M;return{load:async i=>{if(i.sourceType===`URL`)return{bytes:j};let a=r.has(i.unitId),o=a||i.unitId===e?await this._loadEmbedded(i,t):void 0;if(o)return{bytes:o};if(a||n.trustedHost)throw s(i.source);return{bytes:j}}}}async saveResult(e,n){return(await this._fileService.createFile({name:e.name,contentType:e.contentType,source:t.FileSource.HttpExport,assign:n.userID,content:F(e.bytes)},n)).fileID}async deleteQuietly(e,t){try{await this._fileService.deleteFile(e,t)}catch(t){this._logger.warn(`Exchange could not delete a file`,{fileID:e,error:I(t)})}}async _loadEmbedded(e,n){let r=await this._fileService.getFile(e.source,n);if(!(!r||r.source!==t.FileSource.UnitEmbedded||r.assign!==e.unitId))return this.read(e.source,n)}};async function P(e){let t=[];for await(let n of e)t.push(n);return n.Buffer.concat(t)}async function*F(e){yield e}function I(e){return e instanceof Error?e.message:String(e)}var L=[`workbook`,`doc`,`slide`,`board`,`pdf`];function R(e){let t;try{t=JSON.parse(n.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`))}catch{throw o(`Snapshot JSON is not valid JSON`)}let r=U(t,`snapshot JSON`),i=U(r.snapshot,`snapshot`);if(typeof i.unitID!=`string`||i.unitID.length===0)throw o(`snapshot.unitID is required`);if(!Number.isSafeInteger(i.type))throw o(`snapshot.type must be an integer`);if(!Number.isSafeInteger(i.rev))throw o(`snapshot.rev must be an integer`);let a={...i};for(let e of L)a[e]=B(i[e],`snapshot.${e}`);return{snapshot:a,sheetBlocks:H(r.sheetBlocks)}}function z(e){let t={...e.snapshot};for(let n of L){let r=e.snapshot[n];r&&(t[n]=V(r))}let r=Object.fromEntries(e.sheetBlocks.map(e=>[e.id,{...e,data:G(e.data)}]));return n.Buffer.from(JSON.stringify({snapshot:t,sheetBlocks:r}),`utf8`)}function B(e,t){if(e==null)return;let n=U(e,t);if(Object.keys(n).length===0)return;let r={...n,originalMeta:W(n.originalMeta,`${t}.originalMeta`)};if(n.sheets!==void 0){let e=U(n.sheets,`${t}.sheets`);r.sheets=Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=U(n,`${t}.sheets.${e}`),i=W(r.originalMeta,`${t}.sheets.${e}.originalMeta`);return[e,{...r,originalMeta:i}]}))}return r}function V(e){let t={...e,originalMeta:G(e.originalMeta)};return e.sheets&&(t.sheets=Object.fromEntries(Object.entries(e.sheets).map(([e,t])=>[e,{...t,originalMeta:G(t.originalMeta)}]))),t}function H(e){return e==null?[]:Object.entries(U(e,`sheetBlocks`)).map(([e,t])=>{let n=U(t,`sheetBlocks.${e}`);if(typeof n.id!=`string`||n.id.length===0)throw o(`sheetBlocks.${e}.id is required`);return{...n,data:W(n.data,`sheetBlocks.${e}.data`)}})}function U(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw o(`${t} must be an object`);return e}function W(e,t){if(typeof e!=`string`)throw o(`${t} must be a base64 string`);return new Uint8Array(n.Buffer.from(e,`base64`))}function G(e){return e?n.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`):``}var K=Object.freeze({Unit:1,Json:2}),q=1;async function J(t,n){let{files:i}=n,a=await i.read(t.source.fileID,t.context);if(t.outputType===K.Json){let r=await(0,e.importBufferToSnapshot)(a,{...t.options,fileName:t.fileName});_(n);let o=await i.saveResult({name:Y(t.fileName),contentType:`application/json`,bytes:z(r)},t.context);return{outputType:K.Json,jsonID:o}}let o=(0,r.randomUUID)(),s=re(t.type)?i.createUnitFileSink(o,t.context):void 0;try{let r=await(0,e.importBufferToSnapshot)(a,{...t.options,fileName:t.fileName,unitId:o,...s?{files:{store:s.store}}:{}});return _(n),await n.units.create({snapshot:{...r.snapshot,unitID:o,type:t.type,rev:q},sheetBlocks:r.sheetBlocks},t.context),{outputType:K.Unit,unitID:o}}catch(e){throw await s?.discard(),e}}function Y(e){let t=e.lastIndexOf(`.`);return`${t>0?e.slice(0,t):e}.json`}var ae=class{_middlewares=new Map;use(e,t){let n=this._middlewares.get(e)??[],r=t;n.push(r),this._middlewares.set(e,n);let i=!1;return{dispose:()=>{if(i)return;i=!0;let e=n.indexOf(r);e>=0&&n.splice(e,1)}}}async run(e,t){let n=[...this._middlewares.get(e)??[]],r=async i=>{let a=n[i];if(!a)return;let o=!1,s,c=()=>{if(o)throw Error(`Middleware for action ${e} called next() more than once`);return o=!0,s=r(i+1),s};try{await a(t,c)}catch(e){throw s&&await s.catch(()=>void 0),e}if(!o)throw Error(`Middleware for action ${e} completed without calling next()`);await s};await r(0)}clear(){this._middlewares.clear()}},oe=3600*1e3,X=class{_retentionMs;_tasks=new Map;constructor(e=oe){this._retentionMs=e}create(e,t){let n=(0,r.randomUUID)();return this._tasks.set(n,{userID:t,task:{taskID:n,kind:e,status:`pending`}}),n}completeImport(e,t){this._finish(e,{taskID:e,kind:`import`,status:`done`,result:t})}completeExport(e,t){this._finish(e,{taskID:e,kind:`export`,status:`done`,result:t})}fail(e,t){let n=this._tasks.get(e);n&&this._finish(e,{taskID:e,kind:n.task.kind,status:`failed`,error:t})}get(e,t){let n=this._tasks.get(e);return n?.userID===t?n.task:void 0}clear(){for(let e of this._tasks.values())clearTimeout(e.expiry);this._tasks.clear()}_finish(e,t){let n=this._tasks.get(e);!n||n.task.status!==`pending`||(n.task=t,n.expiry=setTimeout(()=>this._tasks.delete(e),this._retentionMs),n.expiry.unref?.())}},se=0,ce=class{_collabService;_materializer;constructor(e,t){this._collabService=e,this._materializer=new i.UnitSnapshotMaterializer(t)}read(e,t,n){return this._collabService.getUnitLoadDataWithBlocks({unitID:e,type:t,revision:se},n)}materialize(e){return this._materializer.materializeSnapshot(e)}async create(e,t){let n=await this._collabService.createUnitFromSnapshot(e,t);if(n.status!==`created`)throw Error(`Unit ${n.unitID} already exists`)}dispose(){return this._materializer.dispose()}},le=class{_files;_units;_tasks=new X;_middleware=new ae;_environment;_disposePromise;constructor(e){if(!e?.collabService)throw TypeError(`UniverExchangeService requires a collabService`);if(!e?.fileService)throw TypeError(`UniverExchangeService requires a fileService`);this._files=new N(e.fileService,e.logger??pe),this._units=new ce(e.collabService,e.runtime),this._environment={files:this._files,units:this._units,isRunning:()=>!this._disposePromise}}use(e,t){return this._assertRunning(),this._middleware.use(e,t)}createImportTask(e,t){return this._call(async()=>{let n=Z(t),r=ue(e),{fileID:i,sourceUnitID:a}=r,o,s;a===void 0?(s=(await this._files.requireUpload(i,n)).name,o={kind:`upload`,fileID:i}):(s=(await this._files.requireAttachment(i,a,n)).name,o={kind:`attachment`,fileID:i,unitID:a});let c=p(r.type,s),l=b(r.type,c,r.options);await this._middleware.run(`import`,{...n,request:r}),this._assertRunning();let u={context:n,type:r.type,outputType:r.outputType,source:o,fileName:s,options:l};return this._start(`import`,n,o,async e=>this._tasks.completeImport(e,await J(u,this._environment)))})}createExportTask(e,t){return this._call(async()=>{let n=Z(t),r=f(e?.type),i=m(r,e.format),a=x(r,i,e.options),s=e.options===void 0?{}:{options:e.options},{unitID:c,jsonID:l}=de(e),u;if(c!==void 0){let e=await this._units.read(c,r,n),t=Object.freeze({type:r,unitID:c,format:i,...s});await this._middleware.run(`export`,{...n,request:t}),u={kind:`unit`,unitID:c,data:e}}else{await this._files.requireUpload(l,n);let e=R(await this._files.read(l,n));if(e.snapshot.type!==r)throw o(`Snapshot type ${e.snapshot.type} does not match Unit type ${r}`);let t=Object.freeze({type:r,jsonID:l,format:i,...s});await this._middleware.run(`export`,{...n,request:t,snapshot:e}),u={kind:`json`,jsonID:l,snapshot:e}}this._assertRunning();let d={context:n,type:r,format:i,source:u,options:a};return this._start(`export`,n,u,async e=>this._tasks.completeExport(e,await ie(d,this._environment)))})}getTask(e,t){return this._call(async()=>{let n=Z(t),r=typeof e==`string`?this._tasks.get(e,n.userID):void 0;if(!r)throw c(String(e));return r})}dispose(){return this._disposePromise||=(async()=>{this._tasks.clear(),this._middleware.clear(),await this._units.dispose()})(),this._disposePromise}_start(e,t,n,r){let i=this._tasks.create(e,t.userID);return(async()=>{try{await r(i)}catch(e){this._tasks.fail(i,e)}let e=fe(n);e!==void 0&&!this._disposePromise&&await this._files.deleteQuietly(e,t)})(),i}_call(e){try{return this._assertRunning(),e()}catch(e){return Promise.reject(e)}}_assertRunning(){if(this._disposePromise)throw new a(`SERVICE_DISPOSED`,`Exchange Service is disposed`)}};function Z(e){if(typeof e?.userID!=`string`||e.userID.length===0)throw o(`context.userID is required`);return{userID:e.userID,customData:e.customData??Object.create(null)}}function ue(e){let t=f(e?.type);if(e.outputType!==K.Unit&&e.outputType!==K.Json)throw o(`outputType must be 1 or 2`);let n=Q(e.fileID,`fileID`),r=e.outputType,i=$(e.sourceUnitID,`sourceUnitID`);if(i!==void 0&&r!==K.Unit)throw o(`sourceUnitID requires outputType 1`);return Object.freeze({type:t,outputType:r,fileID:n,...i===void 0?{}:{sourceUnitID:i},...e.options===void 0?{}:{options:e.options}})}function de(e){let t=$(e.unitID,`unitID`),n=$(e.jsonID,`jsonID`);if(t===void 0==(n===void 0))throw o(`Exactly one of unitID and jsonID is required`);return t===void 0?{jsonID:n}:{unitID:t}}function fe(e){switch(e.kind){case`upload`:return e.fileID;case`json`:return e.jsonID;default:return}}function Q(e,t){if(typeof e!=`string`||e.length===0)throw o(`${t} must be a non-empty string`);return e}function $(e,t){if(!(e==null||e===``))return Q(e,t)}var pe={debug:()=>void 0,info:()=>void 0,warn:(e,t)=>console.warn(e,t??{}),error:(e,t)=>console.error(e,t??{})};exports.ExchangeServiceError=a,exports.IMPORT_OUTPUT_TYPE=K,exports.UniverExchangeService=le;
@@ -0,0 +1,257 @@
1
+ import { IUniverFileService } from "@univerjs-pro/collaboration-file-service";
2
+ import { CollabContext, CustomData, Disposable, ILogger, IUniverCollabService, UnitRuntimeConfig } from "@univerjs-pro/collaboration-service";
3
+ import { ISheetBlock, ISnapshot, UniverType } from "@univerjs/protocol";
4
+
5
+ //#region src/types.d.ts
6
+ /** Protocol `outputType`: `1` stores the result as a collaborative Unit, `2` returns snapshot JSON. @public */
7
+ type ImportOutputType = 1 | 2;
8
+ /** @public */
9
+ interface ExchangeImportOptions {
10
+ readonly sheet?: {
11
+ readonly minSheetRowCount?: number;
12
+ readonly minSheetColumnCount?: number;
13
+ };
14
+ readonly base?: {
15
+ readonly xlsx?: {
16
+ readonly baseMode?: "auto" | "tables" | "sheets" | "hybrid";
17
+ readonly baseFormulaPolicy?: "convert-then-values" | "values" | "text" | "fail";
18
+ };
19
+ };
20
+ readonly doc?: {
21
+ readonly docType?: "modern" | "traditional";
22
+ };
23
+ }
24
+ /** @public */
25
+ interface ExchangeExportOptions {
26
+ /**
27
+ * Which version of converted attachments the export embeds: their original file (default), or
28
+ * `online`, the current content of each attachment's online Unit, read with the caller's context.
29
+ */
30
+ readonly oleAttachmentSource?: "original" | "online";
31
+ readonly sheet?: {
32
+ /** Accepted for compatibility and ignored: URL images always export as a transparent placeholder. */readonly useImageUrl?: boolean;
33
+ readonly csv?: {
34
+ readonly sheetId?: string;
35
+ };
36
+ };
37
+ readonly base?: {
38
+ readonly csv?: {
39
+ readonly tableId?: string;
40
+ };
41
+ readonly xlsx?: {
42
+ readonly baseExportMode?: "tables" | "ranges";
43
+ readonly baseFormulaPolicy?: "convert-then-values" | "values" | "text" | "fail";
44
+ };
45
+ };
46
+ }
47
+ /** @public */
48
+ interface ImportInput {
49
+ readonly type: UniverType;
50
+ readonly outputType: ImportOutputType;
51
+ /**
52
+ * The source file; its name decides the source format. Without `sourceUnitID`, an `HttpImport`
53
+ * file uploaded by the caller. With `sourceUnitID`, a `UnitEmbedded` attachment of that Unit.
54
+ */
55
+ readonly fileID: string;
56
+ /**
57
+ * Converts a stored attachment of this Unit into an online Unit (`importAttachmentToUnitId`). The
58
+ * attachment stays with its host Unit after the task ends.
59
+ */
60
+ readonly sourceUnitID?: string;
61
+ readonly options?: ExchangeImportOptions;
62
+ }
63
+ /** The read-only view of an import that middleware sees. @public */
64
+ interface ImportRequest {
65
+ readonly type: UniverType;
66
+ readonly outputType: ImportOutputType;
67
+ readonly fileID: string;
68
+ /** Present when a stored attachment of this Unit is being converted; check the caller's access to it here. */
69
+ readonly sourceUnitID?: string;
70
+ readonly options?: ExchangeImportOptions;
71
+ }
72
+ /** Exactly one of `unitID` and `jsonID` must be set. @public */
73
+ interface ExportInput {
74
+ readonly type: UniverType;
75
+ readonly unitID?: string;
76
+ /** An `HttpImport` upload holding `{ snapshot, sheetBlocks }` JSON. */
77
+ readonly jsonID?: string;
78
+ readonly format: string;
79
+ readonly options?: ExchangeExportOptions;
80
+ }
81
+ /** The read-only view of an export that middleware sees; carries the one source that was given. @public */
82
+ type ExportRequest = {
83
+ readonly type: UniverType;
84
+ readonly unitID: string;
85
+ readonly format: string;
86
+ readonly options?: ExchangeExportOptions;
87
+ } | {
88
+ readonly type: UniverType;
89
+ readonly jsonID: string;
90
+ readonly format: string;
91
+ readonly options?: ExchangeExportOptions;
92
+ };
93
+ /** @public */
94
+ type ExchangeRequest = ImportRequest | ExportRequest;
95
+ /**
96
+ * The resolved context that middleware receives: `customData` is always present and is the caller's
97
+ * object when one was passed. The same object is shared for the whole request phase.
98
+ * @public
99
+ */
100
+ interface ExchangeContext<TRequest extends ExchangeRequest = ExchangeRequest> {
101
+ readonly userID: string;
102
+ readonly customData: CustomData;
103
+ readonly request: TRequest;
104
+ }
105
+ /** A decoded snapshot aggregate, shared by reference and read-only by contract. @public */
106
+ interface ExchangeSnapshot {
107
+ readonly snapshot: Readonly<ISnapshot>;
108
+ readonly sheetBlocks: readonly ISheetBlock[];
109
+ }
110
+ /** @public */
111
+ type ImportTaskResult = {
112
+ readonly outputType: 1;
113
+ readonly unitID: string;
114
+ } | {
115
+ readonly outputType: 2;
116
+ readonly jsonID: string;
117
+ };
118
+ /** `fileID` is an `HttpExport` file owned by the task's creator. @public */
119
+ interface ExportTaskResult {
120
+ readonly fileID: string;
121
+ }
122
+ /**
123
+ * A task as its creator sees it. `error` is the original failure (an `ExchangeServiceError`,
124
+ * `FileError`, `CollabError`, exchange-node `ExchangeError` or any other thrown value).
125
+ * @public
126
+ */
127
+ type ExchangeTask = {
128
+ readonly taskID: string;
129
+ readonly kind: "import" | "export";
130
+ readonly status: "pending";
131
+ } | {
132
+ readonly taskID: string;
133
+ readonly kind: "import";
134
+ readonly status: "done";
135
+ readonly result: ImportTaskResult;
136
+ } | {
137
+ readonly taskID: string;
138
+ readonly kind: "export";
139
+ readonly status: "done";
140
+ readonly result: ExportTaskResult;
141
+ } | {
142
+ readonly taskID: string;
143
+ readonly kind: "import" | "export";
144
+ readonly status: "failed";
145
+ readonly error: unknown;
146
+ };
147
+ //#endregion
148
+ //#region src/middleware.d.ts
149
+ /** Runs after request validation and the source file ownership check, before the task is created. @public */
150
+ type ImportMiddlewareContext = ExchangeContext<ImportRequest>;
151
+ /**
152
+ * Runs before the task is created: after the Unit is read for a `unitID` export, after the snapshot
153
+ * is decoded for a `jsonID` export. `snapshot` is present only for `jsonID` exports.
154
+ * @public
155
+ */
156
+ interface ExportMiddlewareContext extends ExchangeContext<ExportRequest> {
157
+ readonly snapshot?: ExchangeSnapshot;
158
+ }
159
+ /** @public */
160
+ type ExchangeMiddlewareNext = () => Promise<void>;
161
+ /** @public */
162
+ type ExchangeMiddleware<TContext> = (context: TContext, next: ExchangeMiddlewareNext) => void | Promise<void>;
163
+ /** @public */
164
+ type ExchangeMiddlewareAction = "import" | "export";
165
+ /** @public */
166
+ interface ExchangeMiddlewareMap {
167
+ readonly import: ExchangeMiddleware<ImportMiddlewareContext>;
168
+ readonly export: ExchangeMiddleware<ExportMiddlewareContext>;
169
+ }
170
+ //#endregion
171
+ //#region src/units.d.ts
172
+ /**
173
+ * The two collaboration Service methods Exchange calls. `UniverCollabService` satisfies it directly;
174
+ * a wrapper must pass the context through unchanged.
175
+ * @public
176
+ */
177
+ type IExchangeCollabService = Pick<IUniverCollabService, "createUnitFromSnapshot" | "getUnitLoadDataWithBlocks">;
178
+ /**
179
+ * Where snapshots are materialized for `unitID` exports. Only `execution` applies: the materializer
180
+ * releases each Unit when it finishes, so the cache options have no effect here.
181
+ * @public
182
+ */
183
+ type ExchangeRuntimeConfig = Pick<UnitRuntimeConfig, "execution">;
184
+ //#endregion
185
+ //#region src/service.d.ts
186
+ /** @public */
187
+ interface UniverExchangeServiceOptions {
188
+ /** Creates imported Units and reads exported ones; its middleware applies unchanged. */
189
+ readonly collabService: IExchangeCollabService;
190
+ /** Source uploads, files split out of imported Units, and results are stored here. */
191
+ readonly fileService: IUniverFileService;
192
+ /** Receives failures the Service swallows, such as early file deletes. Without it, warn and error go to the console. */
193
+ readonly logger?: ILogger;
194
+ /** Where `unitID` exports materialize snapshots. Defaults to the collaboration Runtime's Worker execution. */
195
+ readonly runtime?: ExchangeRuntimeConfig;
196
+ }
197
+ /**
198
+ * The Exchange Service contract. `createImportTask` and `createExportTask` validate and authorize in
199
+ * the request, then convert in the background; a rejected request creates no task.
200
+ * @public
201
+ */
202
+ interface IUniverExchangeService {
203
+ use<K extends ExchangeMiddlewareAction>(action: K, middleware: ExchangeMiddlewareMap[K]): Disposable;
204
+ /** Resolves to the taskID. */
205
+ createImportTask(input: ImportInput, context: CollabContext): Promise<string>;
206
+ /** Resolves to the taskID. */
207
+ createExportTask(input: ExportInput, context: CollabContext): Promise<string>;
208
+ /** Only the task's creator can read it; other callers get `TASK_NOT_FOUND`. */
209
+ getTask(taskID: string, context: CollabContext): Promise<ExchangeTask>;
210
+ dispose(): Promise<void>;
211
+ }
212
+ /**
213
+ * Runs Office/PDF import and export with `@univerjs-pro/exchange-node` inside this process. Tasks live
214
+ * in memory on this instance only.
215
+ * @public
216
+ */
217
+ declare class UniverExchangeService implements IUniverExchangeService {
218
+ private readonly _files;
219
+ private readonly _units;
220
+ private readonly _tasks;
221
+ private readonly _middleware;
222
+ private readonly _environment;
223
+ private _disposePromise;
224
+ constructor(options: UniverExchangeServiceOptions);
225
+ use<K extends ExchangeMiddlewareAction>(action: K, middleware: ExchangeMiddlewareMap[K]): Disposable;
226
+ createImportTask(input: ImportInput, context: CollabContext): Promise<string>;
227
+ createExportTask(input: ExportInput, context: CollabContext): Promise<string>;
228
+ getTask(taskID: string, context: CollabContext): Promise<ExchangeTask>;
229
+ dispose(): Promise<void>;
230
+ private _start;
231
+ private _call;
232
+ private _assertRunning;
233
+ }
234
+ //#endregion
235
+ //#region src/errors.d.ts
236
+ /**
237
+ * Error codes the Exchange Service raises itself. Failures from File, the collaboration Service and
238
+ * exchange-node keep their own error types.
239
+ * @public
240
+ */
241
+ type ExchangeServiceErrorCode = "INVALID_REQUEST" | "UNAUTHENTICATED" | "FILE_NOT_FOUND" | "TASK_NOT_FOUND" | "SERVICE_DISPOSED";
242
+ /** @public */
243
+ declare class ExchangeServiceError extends Error {
244
+ readonly code: ExchangeServiceErrorCode;
245
+ constructor(code: ExchangeServiceErrorCode, message: string, options?: {
246
+ cause?: unknown;
247
+ });
248
+ }
249
+ //#endregion
250
+ //#region src/import-output-type.d.ts
251
+ /** Named `ImportOutputType` values. @internal Used by `@univerjs-pro/collaboration-exchange-endpoint`. */
252
+ declare const IMPORT_OUTPUT_TYPE: Readonly<{
253
+ readonly Unit: 1;
254
+ readonly Json: 2;
255
+ }>;
256
+ //#endregion
257
+ export { type ExchangeContext, type ExchangeExportOptions, type ExchangeImportOptions, type ExchangeMiddleware, type ExchangeMiddlewareAction, type ExchangeMiddlewareMap, type ExchangeMiddlewareNext, type ExchangeRequest, type ExchangeRuntimeConfig, ExchangeServiceError, type ExchangeServiceErrorCode, type ExchangeSnapshot, type ExchangeTask, type ExportInput, type ExportMiddlewareContext, type ExportRequest, type ExportTaskResult, type IExchangeCollabService, IMPORT_OUTPUT_TYPE, type IUniverExchangeService, type ImportInput, type ImportMiddlewareContext, type ImportOutputType, type ImportRequest, type ImportTaskResult, UniverExchangeService, type UniverExchangeServiceOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import cjsModule from "./index.cjs";
2
+ const facadeExport0 = cjsModule["ExchangeServiceError"];
3
+ const facadeExport1 = cjsModule["IMPORT_OUTPUT_TYPE"];
4
+ const facadeExport2 = cjsModule["UniverExchangeService"];
5
+ export { facadeExport0 as ExchangeServiceError, facadeExport1 as IMPORT_OUTPUT_TYPE, facadeExport2 as UniverExchangeService };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@univerjs-pro/collaboration-exchange-service",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Exchange Service of Univer Collaboration: Office and PDF import and export through exchange-node, the collaboration Service and the File Service",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/dream-num/univer-collaboration-sdk-community.git",
7
+ "directory": "packages/collaboration-exchange-service"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=22"
13
+ },
14
+ "version": "1.4.0",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.mjs",
22
+ "require": "./dist/index.cjs"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "peerDependencies": {
29
+ "@univerjs-pro/collaboration-file-service": "1.4.0",
30
+ "@univerjs-pro/collaboration-service": "1.4.0",
31
+ "@univerjs-pro/exchange-node": "1.4.0",
32
+ "@univerjs/protocol": "1.4.0"
33
+ }
6
34
  }