@univerjs-pro/collaboration-exchange-service 1.4.0 → 1.6.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/README.md +89 -3
- package/README.zh-CN.md +87 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -12
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -37,6 +37,65 @@ await fileService.dispose();
|
|
|
37
37
|
|
|
38
38
|
The constructor throws a `TypeError` when a required option is missing. Dispose Exchange before the File Service and the collaboration Service.
|
|
39
39
|
|
|
40
|
+
## The core of an import and an export
|
|
41
|
+
|
|
42
|
+
An import is one conversion and one call to the collaboration Service; so is an export. For an XLSX file and a Sheet they look like this:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const unitID = randomUUID();
|
|
46
|
+
const imported = await importBufferToSnapshot(bytes, {
|
|
47
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
48
|
+
format: ExchangeFormat.XLSX,
|
|
49
|
+
fileName,
|
|
50
|
+
unitId: unitID,
|
|
51
|
+
formulaCalculation: FormulaCalculationMode.FORCED,
|
|
52
|
+
files: { store: storeEmbeddedFile },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
await collabService.createUnitFromSnapshot(
|
|
56
|
+
{
|
|
57
|
+
snapshot: { ...imported.snapshot, unitID, type: UniverType.UNIVER_SHEET, rev: 1 },
|
|
58
|
+
sheetBlocks: imported.sheetBlocks,
|
|
59
|
+
},
|
|
60
|
+
context
|
|
61
|
+
);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const data = await collabService.getUnitLoadDataWithBlocks(
|
|
66
|
+
{ unitID, type: UniverType.UNIVER_SHEET, revision: 0 },
|
|
67
|
+
context
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
// `materializer` is one `UnitSnapshotMaterializer`, created once and reused.
|
|
71
|
+
const head =
|
|
72
|
+
data.changesets.length === 0
|
|
73
|
+
? { snapshot: data.snapshot, sheetBlocks: [...data.sheetBlocks] }
|
|
74
|
+
: await materializer.materializeSnapshot(data);
|
|
75
|
+
|
|
76
|
+
const xlsx = await exportSnapshotToBuffer(head, {
|
|
77
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
78
|
+
format: ExchangeFormat.XLSX,
|
|
79
|
+
// Already calculated: by the import, by the collaboration Service when it saved the snapshot,
|
|
80
|
+
// or by `materializeSnapshot`. Calculating again here is not needed.
|
|
81
|
+
formulaCalculation: FormulaCalculationMode.NO,
|
|
82
|
+
files: { load: loadEmbeddedFile },
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The `files.store` and `files.load` callbacks can use the SDK’s [File Service](../collaboration-file-service/README.md) or your application’s own storage to save and retrieve images and attachments.
|
|
87
|
+
|
|
88
|
+
The rest of this Service handles what surrounds those calls:
|
|
89
|
+
|
|
90
|
+
| Concern | What the Service does |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| Tasks | Runs the conversion in the background and keeps each task readable by its creator. |
|
|
93
|
+
| Requests | Validates the input, and resolves the format and the front-end options for each type. |
|
|
94
|
+
| Files | Checks that the caller owns the source file, stores imported images and attachments as files of the new Unit, loads them again on export, and deletes temporary files. |
|
|
95
|
+
| Permissions | Runs the collaboration Service's middleware and its own `import` and `export` middleware. |
|
|
96
|
+
| Snapshot JSON | Imports to a JSON file instead of a Unit (`outputType: 2`) and exports a client snapshot (`jsonID`). |
|
|
97
|
+
| OLE attachments | Converts a stored attachment into an online Unit and embeds online Units in an export. |
|
|
98
|
+
|
|
40
99
|
## Supported conversions
|
|
41
100
|
|
|
42
101
|
| Type | Import | Export |
|
|
@@ -47,11 +106,38 @@ The constructor throws a `TypeError` when a required option is missing. Dispose
|
|
|
47
106
|
| Base | xls, xlsx, csv, tsv | xlsx, csv |
|
|
48
107
|
| PDF | pdf | pdf |
|
|
49
108
|
|
|
50
|
-
The name of the uploaded file decides the import format. Board is rejected.
|
|
109
|
+
The name of the uploaded file decides the import format. Board is rejected.
|
|
110
|
+
|
|
111
|
+
Sheet formulas are calculated on import, not on export. An XLSX import recalculates every formula; XLS, CSV and TSV imports do not yet. An export writes the results the snapshot holds, so a formula without a result is exported without a value.
|
|
112
|
+
|
|
113
|
+
A `unitID` export uses the latest stored snapshot as it is when no changeset follows it, and replays the changesets and recalculates otherwise.
|
|
114
|
+
|
|
115
|
+
### Enable PDF Unit support (optional)
|
|
116
|
+
|
|
117
|
+
Use `UniverType.UNIVER_PDF` as the task’s `type` for both import and export. An import converts a PDF file into a PDF Unit or its snapshot. An export writes a PDF Unit or its snapshot back to a PDF file.
|
|
118
|
+
|
|
119
|
+
To enable this conversion, install the PDF binding.
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
pnpm add @univerjs-pro/exchange-pdf-node-binding
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Register PDF support in the entry point of the import/export process. Without this import, PDF tasks fail with `UNSUPPORTED_FORMAT`.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import '@univerjs-pro/exchange-node/pdf';
|
|
129
|
+
```
|
|
51
130
|
|
|
52
131
|
## License and quota
|
|
53
132
|
|
|
54
|
-
|
|
133
|
+
Set the `UNIVER_LICENSE` and `UNIVER_LICENSE_KEY` environment variables in the import/export process to the full contents of the license and key files, respectively. `exchange-node` reads them automatically. You can also configure the license in code at startup.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { configureExchange, getExportQuota } from '@univerjs-pro/exchange-node';
|
|
137
|
+
|
|
138
|
+
await configureExchange({ license, licenseKey });
|
|
139
|
+
const quota = await getExportQuota(); // Optional: check the remaining export quota.
|
|
140
|
+
```
|
|
55
141
|
|
|
56
142
|
## Methods
|
|
57
143
|
|
|
@@ -86,7 +172,7 @@ Finished tasks stay readable for one hour. Tasks live in this Service instance,
|
|
|
86
172
|
|
|
87
173
|
## Files
|
|
88
174
|
|
|
89
|
-
Importing to a Unit stores images and attachments of Sheet, Doc and
|
|
175
|
+
Importing to a Unit stores images and attachments of Sheet, Doc, Slide and PDF as `UnitEmbedded` files of the new Unit. If the import fails, those files are deleted. Base, PDF fonts and `outputType: 2` keep them inline in the snapshot.
|
|
90
176
|
|
|
91
177
|
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
178
|
|
package/README.zh-CN.md
CHANGED
|
@@ -37,6 +37,64 @@ await fileService.dispose();
|
|
|
37
37
|
|
|
38
38
|
缺少必填选项时构造函数抛 `TypeError`。释放时先释放 Exchange,再释放 File Service 和协同 Service。
|
|
39
39
|
|
|
40
|
+
## 导入与导出的核心
|
|
41
|
+
|
|
42
|
+
一次导入是一次转换加一次协同 Service 调用,导出也是。以 XLSX 文件和 Sheet 为例:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const unitID = randomUUID();
|
|
46
|
+
const imported = await importBufferToSnapshot(bytes, {
|
|
47
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
48
|
+
format: ExchangeFormat.XLSX,
|
|
49
|
+
fileName,
|
|
50
|
+
unitId: unitID,
|
|
51
|
+
formulaCalculation: FormulaCalculationMode.FORCED,
|
|
52
|
+
files: { store: storeEmbeddedFile },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
await collabService.createUnitFromSnapshot(
|
|
56
|
+
{
|
|
57
|
+
snapshot: { ...imported.snapshot, unitID, type: UniverType.UNIVER_SHEET, rev: 1 },
|
|
58
|
+
sheetBlocks: imported.sheetBlocks,
|
|
59
|
+
},
|
|
60
|
+
context
|
|
61
|
+
);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const data = await collabService.getUnitLoadDataWithBlocks(
|
|
66
|
+
{ unitID, type: UniverType.UNIVER_SHEET, revision: 0 },
|
|
67
|
+
context
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
// `materializer` 是一个 `UnitSnapshotMaterializer` 实例,创建一次后复用。
|
|
71
|
+
const head =
|
|
72
|
+
data.changesets.length === 0
|
|
73
|
+
? { snapshot: data.snapshot, sheetBlocks: [...data.sheetBlocks] }
|
|
74
|
+
: await materializer.materializeSnapshot(data);
|
|
75
|
+
|
|
76
|
+
const xlsx = await exportSnapshotToBuffer(head, {
|
|
77
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
78
|
+
format: ExchangeFormat.XLSX,
|
|
79
|
+
// 快照已经算过:导入时、协同 Service 保存快照时,或 `materializeSnapshot` 中。这里不需要再计算。
|
|
80
|
+
formulaCalculation: FormulaCalculationMode.NO,
|
|
81
|
+
files: { load: loadEmbeddedFile },
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
示例中的 `files.store` 和 `files.load` 可以用 SDK 的 [File Service](../collaboration-file-service/README.zh-CN.md) 存取图片和附件,也可以对接应用自己的文件存储。
|
|
86
|
+
|
|
87
|
+
本 Service 的其余部分处理这两段调用周边的事情:
|
|
88
|
+
|
|
89
|
+
| 方面 | 本 Service 做的事 |
|
|
90
|
+
| --- | --- |
|
|
91
|
+
| 任务 | 在后台执行转换,任务只有创建者可以读取。 |
|
|
92
|
+
| 请求 | 校验输入,按类型确定格式并转换前端选项。 |
|
|
93
|
+
| 文件 | 检查源文件属于调用方,把导入的图片和附件存为新 Unit 的文件,导出时再读回,并删除临时文件。 |
|
|
94
|
+
| 权限 | 执行协同 Service 的 middleware 和自己的 `import`、`export` middleware。 |
|
|
95
|
+
| 快照 JSON | 导入为 JSON 文件而不是 Unit(`outputType: 2`),以及导出客户端快照(`jsonID`)。 |
|
|
96
|
+
| OLE 附件 | 把已存储的附件转成在线 Unit,以及在导出中嵌入在线 Unit。 |
|
|
97
|
+
|
|
40
98
|
## 支持的转换
|
|
41
99
|
|
|
42
100
|
| 类型 | 导入 | 导出 |
|
|
@@ -47,11 +105,38 @@ await fileService.dispose();
|
|
|
47
105
|
| Base | xls、xlsx、csv、tsv | xlsx、csv |
|
|
48
106
|
| PDF | pdf | pdf |
|
|
49
107
|
|
|
50
|
-
导入格式由上传文件的文件名决定。Board
|
|
108
|
+
导入格式由上传文件的文件名决定。Board 会被拒绝。
|
|
109
|
+
|
|
110
|
+
Sheet 的公式在导入时计算,导出时不计算。XLSX 导入重算全部公式;XLS、CSV、TSV 导入暂不重算。导出按快照中已有的结果写出,没有结果的公式导出后没有值。
|
|
111
|
+
|
|
112
|
+
按 `unitID` 导出时,最近一次快照之后没有 changeset 就直接使用该快照,否则回放这些 changeset 并重新计算。
|
|
113
|
+
|
|
114
|
+
### 启用 PDF Unit(可选)
|
|
115
|
+
|
|
116
|
+
导入和导出任务的 `type` 均使用 `UniverType.UNIVER_PDF`。导入将 PDF 文件转换为 PDF Unit 或其快照,导出则将 PDF Unit 或其快照写回 PDF 文件。
|
|
117
|
+
|
|
118
|
+
要启用这项转换,先安装 PDF binding。
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pnpm add @univerjs-pro/exchange-pdf-node-binding
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
在导入导出进程的入口注册 PDF 支持。省略这行时,PDF 任务会以 `UNSUPPORTED_FORMAT` 失败。
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import '@univerjs-pro/exchange-node/pdf';
|
|
128
|
+
```
|
|
51
129
|
|
|
52
130
|
## 许可证与额度
|
|
53
131
|
|
|
54
|
-
|
|
132
|
+
在导入导出进程中,将环境变量 `UNIVER_LICENSE` 和 `UNIVER_LICENSE_KEY` 分别设为许可证和密钥文件的完整内容,`exchange-node` 会自动读取。也可以在启动时通过代码配置。
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
import { configureExchange, getExportQuota } from '@univerjs-pro/exchange-node';
|
|
136
|
+
|
|
137
|
+
await configureExchange({ license, licenseKey });
|
|
138
|
+
const quota = await getExportQuota(); // 按需查询剩余导出额度。
|
|
139
|
+
```
|
|
55
140
|
|
|
56
141
|
## 方法
|
|
57
142
|
|
package/dist/index.cjs
CHANGED
|
@@ -1 +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;
|
|
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 ee(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 te(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 p(e){return d[e]??`application/octet-stream`}function ne(e,t,n){let r=e?.trim()||t;return r.toLowerCase().endsWith(`.${n}`)?r:`${r}.${n}`}function m(e){if(!e.isRunning())throw new a(`SERVICE_DISPOSED`,`Exchange Service is disposed`)}var h={"convert-then-values":e.BaseFormulaPolicy.CONVERT_THEN_VALUES,values:e.BaseFormulaPolicy.VALUES,text:e.BaseFormulaPolicy.TEXT,fail:e.BaseFormulaPolicy.FAIL},re=Object.values(e.BaseImportMode),g=Object.values(e.BaseExportMode),_=Object.values(e.DocxCompatibilityMode),v=[`original`,`online`];function y(n,r,i){let a=E(i,`options`),o={type:n,format:r};if(n===t.UniverType.UNIVER_SHEET){let t=E(a?.sheet,`options.sheet`);T(o,`minSheetRowCount`,D(t?.minSheetRowCount,`options.sheet.minSheetRowCount`)),T(o,`minSheetColumnCount`,D(t?.minSheetColumnCount,`options.sheet.minSheetColumnCount`)),r===e.ExchangeFormat.XLSX&&(o.formulaCalculation=e.FormulaCalculationMode.FORCED)}else if(n===t.UniverType.UNIVER_BASE){let e=E(E(a?.base,`options.base`)?.xlsx,`options.base.xlsx`);T(o,`mode`,O(e?.baseMode,re,`options.base.xlsx.baseMode`)),T(o,`formulaPolicy`,k(e?.baseFormulaPolicy,`options.base.xlsx.baseFormulaPolicy`))}else n===t.UniverType.UNIVER_DOC&&T(o,`compatibilityMode`,O(E(a?.doc,`options.doc`)?.docType,_,`options.doc.docType`));return o}function b(n,r,i){let a=E(i,`options`),s={type:n,format:r};if(O(a?.oleAttachmentSource,v,`options.oleAttachmentSource`)===`online`){if(!w(n,r))throw o(`options.oleAttachmentSource "online" is not supported for this export`);s.ole={attachmentSource:`online`}}n===t.UniverType.UNIVER_SHEET&&(s.formulaCalculation=e.FormulaCalculationMode.NO);let c=r===e.ExchangeFormat.CSV||r===e.ExchangeFormat.TSV;if(n===t.UniverType.UNIVER_SHEET&&c)s.csv={worksheetId:A(E(E(a?.sheet,`options.sheet`)?.csv,`options.sheet.csv`)?.sheetId,`options.sheet.csv.sheetId`)};else if(n===t.UniverType.UNIVER_BASE){let e=E(a?.base,`options.base`);if(c)s.csv={tableId:A(E(e?.csv,`options.base.csv`)?.tableId,`options.base.csv.tableId`)};else{let t=E(e?.xlsx,`options.base.xlsx`);T(s,`mode`,O(t?.baseExportMode,g,`options.base.xlsx.baseExportMode`)),T(s,`formulaPolicy`,k(t?.baseFormulaPolicy,`options.base.xlsx.baseFormulaPolicy`))}}return s}function x(e){return e!==t.UniverType.UNIVER_BASE}function S(e,n){return e===t.UniverType.UNIVER_PDF?e=>C(e)?Promise.resolve({mode:`inline`}):n(e):n}function C(e){return e.mimeType.startsWith(`font/`)}function w(n,r){return n!==t.UniverType.UNIVER_BASE&&r!==e.ExchangeFormat.CSV&&r!==e.ExchangeFormat.TSV}function T(e,t,n){n!==void 0&&(e[t]=n)}function E(e,t){if(e!=null){if(typeof e!=`object`||Array.isArray(e))throw o(`${t} must be an object`);return e}}function D(e,t){if(e!=null){if(!Number.isSafeInteger(e)||e<0)throw o(`${t} must be a non-negative integer`);return e}}function O(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 k(e,t){let n=O(e,Object.keys(h),t);return n===void 0?void 0:h[n]}function A(e,t){if(typeof e!=`string`||e.length===0)throw o(`${t} is required for CSV/TSV export`);return e}async function j(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=w(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,M(e),t.context));return s.add(e.unitId),r}},u=await(0,e.exportSnapshotToBuffer)(a,{...t.options,...c?{files:c}:{},...l?{ole:l}:{}});return m(n),{fileID:await r.saveResult({name:ne(N(a.snapshot),o,t.format),contentType:p(t.format),bytes:u},t.context)}}function M(e){return e.type}function N(e){return(e.workbook??e.doc??e.slide??e.pdf??e.board)?.name}var P=new Uint8Array(n.Buffer.from(`iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`,`base64`)),F=new Set,I=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 L(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:R(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??F;return{load:async i=>{if(i.sourceType===`URL`)return{bytes:P};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:P}}}}async saveResult(e,n){return(await this._fileService.createFile({name:e.name,contentType:e.contentType,source:t.FileSource.HttpExport,assign:n.userID,content:R(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:z(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 L(e){let t=[];for await(let n of e)t.push(n);return n.Buffer.concat(t)}async function*R(e){yield e}function z(e){return e instanceof Error?e.message:String(e)}var B=[`workbook`,`doc`,`slide`,`board`,`pdf`];function V(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=G(t,`snapshot JSON`),i=G(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 B)a[e]=U(i[e],`snapshot.${e}`);return{snapshot:a,sheetBlocks:ie(r.sheetBlocks)}}function H(e){let t={...e.snapshot};for(let n of B){let r=e.snapshot[n];r&&(t[n]=W(r))}let r=Object.fromEntries(e.sheetBlocks.map(e=>[e.id,{...e,data:q(e.data)}]));return n.Buffer.from(JSON.stringify({snapshot:t,sheetBlocks:r}),`utf8`)}function U(e,t){if(e==null)return;let n=G(e,t);if(Object.keys(n).length===0)return;let r={...n,originalMeta:K(n.originalMeta,`${t}.originalMeta`)};if(n.sheets!==void 0){let e=G(n.sheets,`${t}.sheets`);r.sheets=Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=G(n,`${t}.sheets.${e}`),i=K(r.originalMeta,`${t}.sheets.${e}.originalMeta`);return[e,{...r,originalMeta:i}]}))}return r}function W(e){let t={...e,originalMeta:q(e.originalMeta)};return e.sheets&&(t.sheets=Object.fromEntries(Object.entries(e.sheets).map(([e,t])=>[e,{...t,originalMeta:q(t.originalMeta)}]))),t}function ie(e){return e==null?[]:Object.entries(G(e,`sheetBlocks`)).map(([e,t])=>{let n=G(t,`sheetBlocks.${e}`);if(typeof n.id!=`string`||n.id.length===0)throw o(`sheetBlocks.${e}.id is required`);return{...n,data:K(n.data,`sheetBlocks.${e}.data`)}})}function G(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw o(`${t} must be an object`);return e}function K(e,t){if(typeof e!=`string`)throw o(`${t} must be a base64 string`);return new Uint8Array(n.Buffer.from(e,`base64`))}function q(e){return e?n.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`):``}var J=Object.freeze({Unit:1,Json:2}),Y=1;async function ae(t,n){let{files:i}=n,a=await i.read(t.source.fileID,t.context);if(t.outputType===J.Json){let r=await(0,e.importBufferToSnapshot)(a,{...t.options,fileName:t.fileName});m(n);let o=await i.saveResult({name:oe(t.fileName),contentType:`application/json`,bytes:H(r)},t.context);return{outputType:J.Json,jsonID:o}}let o=(0,r.randomUUID)(),s=x(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(t.type,s.store)}}:{}});return m(n),await n.units.create({snapshot:{...r.snapshot,unitID:o,type:t.type,rev:Y},sheetBlocks:r.sheetBlocks},t.context),{outputType:J.Unit,unitID:o}}catch(e){throw await s?.discard(),e}}function oe(e){let t=e.lastIndexOf(`.`);return`${t>0?e.slice(0,t):e}.json`}var se=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()}},ce=36e5,le=class{_retentionMs;_tasks=new Map;constructor(e=ce){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?.())}},X=0,ue=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:X},n)}materialize(e){return e.changesets.length===0?Promise.resolve({snapshot:e.snapshot,sheetBlocks:[...e.sheetBlocks]}):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()}},de=class{_files;_units;_tasks=new le;_middleware=new se;_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 I(e.fileService,e.logger??he),this._units=new ue(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=fe(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=ee(r.type,s),l=y(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 ae(u,this._environment)))})}createExportTask(e,t){return this._call(async()=>{let n=Z(t),r=f(e?.type),i=te(r,e.format),a=b(r,i,e.options),s=e.options===void 0?{}:{options:e.options},{unitID:c,jsonID:l}=pe(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=V(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 j(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=me(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 fe(e){let t=f(e?.type);if(e.outputType!==J.Unit&&e.outputType!==J.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!==J.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 pe(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 me(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 he={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=J,exports.UniverExchangeService=de;
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { IUniverFileService } from "@univerjs-pro/collaboration-file-service";
|
|
|
2
2
|
import { CollabContext, CustomData, Disposable, ILogger, IUniverCollabService, UnitRuntimeConfig } from "@univerjs-pro/collaboration-service";
|
|
3
3
|
import { ISheetBlock, ISnapshot, UniverType } from "@univerjs/protocol";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// src/types.d.ts
|
|
6
6
|
/** Protocol `outputType`: `1` stores the result as a collaborative Unit, `2` returns snapshot JSON. @public */
|
|
7
7
|
type ImportOutputType = 1 | 2;
|
|
8
8
|
/** @public */
|
|
@@ -144,8 +144,6 @@ type ExchangeTask = {
|
|
|
144
144
|
readonly status: "failed";
|
|
145
145
|
readonly error: unknown;
|
|
146
146
|
};
|
|
147
|
-
//#endregion
|
|
148
|
-
//#region src/middleware.d.ts
|
|
149
147
|
/** Runs after request validation and the source file ownership check, before the task is created. @public */
|
|
150
148
|
type ImportMiddlewareContext = ExchangeContext<ImportRequest>;
|
|
151
149
|
/**
|
|
@@ -167,8 +165,6 @@ interface ExchangeMiddlewareMap {
|
|
|
167
165
|
readonly import: ExchangeMiddleware<ImportMiddlewareContext>;
|
|
168
166
|
readonly export: ExchangeMiddleware<ExportMiddlewareContext>;
|
|
169
167
|
}
|
|
170
|
-
//#endregion
|
|
171
|
-
//#region src/units.d.ts
|
|
172
168
|
/**
|
|
173
169
|
* The two collaboration Service methods Exchange calls. `UniverCollabService` satisfies it directly;
|
|
174
170
|
* a wrapper must pass the context through unchanged.
|
|
@@ -181,8 +177,6 @@ type IExchangeCollabService = Pick<IUniverCollabService, "createUnitFromSnapshot
|
|
|
181
177
|
* @public
|
|
182
178
|
*/
|
|
183
179
|
type ExchangeRuntimeConfig = Pick<UnitRuntimeConfig, "execution">;
|
|
184
|
-
//#endregion
|
|
185
|
-
//#region src/service.d.ts
|
|
186
180
|
/** @public */
|
|
187
181
|
interface UniverExchangeServiceOptions {
|
|
188
182
|
/** Creates imported Units and reads exported ones; its middleware applies unchanged. */
|
|
@@ -231,8 +225,6 @@ declare class UniverExchangeService implements IUniverExchangeService {
|
|
|
231
225
|
private _call;
|
|
232
226
|
private _assertRunning;
|
|
233
227
|
}
|
|
234
|
-
//#endregion
|
|
235
|
-
//#region src/errors.d.ts
|
|
236
228
|
/**
|
|
237
229
|
* Error codes the Exchange Service raises itself. Failures from File, the collaboration Service and
|
|
238
230
|
* exchange-node keep their own error types.
|
|
@@ -246,12 +238,9 @@ declare class ExchangeServiceError extends Error {
|
|
|
246
238
|
cause?: unknown;
|
|
247
239
|
});
|
|
248
240
|
}
|
|
249
|
-
//#endregion
|
|
250
|
-
//#region src/import-output-type.d.ts
|
|
251
241
|
/** Named `ImportOutputType` values. @internal Used by `@univerjs-pro/collaboration-exchange-endpoint`. */
|
|
252
242
|
declare const IMPORT_OUTPUT_TYPE: Readonly<{
|
|
253
243
|
readonly Unit: 1;
|
|
254
244
|
readonly Json: 2;
|
|
255
245
|
}>;
|
|
256
|
-
//#endregion
|
|
257
246
|
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/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"engines": {
|
|
12
12
|
"node": ">=22"
|
|
13
13
|
},
|
|
14
|
-
"version": "1.
|
|
14
|
+
"version": "1.6.0",
|
|
15
15
|
"main": "./dist/index.cjs",
|
|
16
16
|
"module": "./dist/index.mjs",
|
|
17
17
|
"types": "./dist/index.d.ts",
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
"dist"
|
|
27
27
|
],
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@univerjs-pro/collaboration-file-service": "1.
|
|
30
|
-
"@univerjs-pro/collaboration-service": "1.
|
|
31
|
-
"@univerjs-pro/exchange-node": "1.
|
|
32
|
-
"@univerjs/protocol": "1.
|
|
29
|
+
"@univerjs-pro/collaboration-file-service": "1.6.0",
|
|
30
|
+
"@univerjs-pro/collaboration-service": "1.6.0",
|
|
31
|
+
"@univerjs-pro/exchange-node": "1.6.0",
|
|
32
|
+
"@univerjs/protocol": "1.6.0"
|
|
33
33
|
}
|
|
34
34
|
}
|