@univerjs-pro/collaboration-database-sqlite 1.3.0 → 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
@@ -4,6 +4,7 @@ English | [简体中文](./README.zh-CN.md)
4
4
 
5
5
  A persistent SQLite `IDatabaseAdapter` using the stable synchronous `libsql` API. Requires Node.js 22 or later.
6
6
 
7
+
7
8
  ## Create the Adapter
8
9
 
9
10
  ```bash
@@ -33,51 +34,65 @@ await database.dispose();
33
34
 
34
35
  Pass the Adapter to `UniverCollabService` as `dbAdapter`.
35
36
 
36
- ## Persistence guarantees
37
-
38
- The Adapter uses foreign keys and `BEGIN IMMEDIATE` write transactions to guarantee:
39
-
40
- - atomic creation of the initial snapshot and Sheet blocks;
41
- - revision CAS with atomic changeset and head publication;
42
- - a snapshot becomes visible to new reads only after all of its dependencies are complete;
43
- - soft-delete, recovery, and hard-delete batches are all-or-nothing;
44
- - hard delete keeps a permanent deletion marker that prevents Unit ID reuse.
45
-
46
- It stores only core collaboration data. Product resources, users, ACLs, History, Comment, and Worktree are managed by the application or their respective Adapters.
47
-
48
37
  ## SQLite behavior
49
38
 
50
39
  - It does not change `journal_mode`; configure WAL, checkpointing, or backup policy before opening the Adapter when needed.
51
- - Core tables use the `collaboration_` prefix.
52
- - Schema version `('core', 2)` is stored in `collaboration_schema_versions`; `PRAGMA user_version` is not used.
40
+ - Core tables use the `collaboration_` prefix. Protocol objects are stored as MessagePack `BLOB` payloads.
41
+ - Schema version `('core', 3)` is stored in `collaboration_schema_versions`, which other Univer collaboration components share; `PRAGMA user_version` is not used.
53
42
  - Changeset scalar columns and the submission unique constraint provide database-level integrity, while commits use revision CAS and do not query the submission key.
54
- - An empty database is initialized automatically. Incomplete or unsupported core schemas are rejected.
43
+ - An empty database is initialized automatically. A core schema version other than 3 is rejected; see Migrations.
55
44
 
56
45
  This implementation suits local applications and small-to-medium single-Node deployments.
57
46
 
58
- ## Explicit v1 → v2 migration
47
+ ## Migrations
48
+
49
+ Each release writes one core schema version and opens only that version. Opening an older database
50
+ fails with an error that points here; migrations never run when the adapter opens a database.
59
51
 
60
- V2 adds required `creator_id` (creator) and `created_at_ms` (creation time, Unix milliseconds)
61
- to `collaboration_units`, and required `created_at_ms` (commit time, Unix milliseconds)
62
- to `collaboration_changesets`.
52
+ | Core schema | Written by |
53
+ | --- | --- |
54
+ | v1 | 1.0.0-rc |
55
+ | v2 | 1.0.0 to 1.3.x |
56
+ | v3 | this release |
63
57
 
64
- Stop writers and back up the file,
65
- then migrate before constructing the Adapter. Opening an old database does not migrate it automatically.
58
+ Stop writers, then let `migrateSQLiteCore` back up the file and apply every missing step:
66
59
 
67
60
  ```ts
68
- import { migrateSQLiteCoreV1ToV2 } from '@univerjs-pro/collaboration-database-sqlite';
61
+ import { migrateSQLiteCore } from '@univerjs-pro/collaboration-database-sqlite';
69
62
 
70
- await migrateSQLiteCoreV1ToV2({ filename: './data/collaboration.sqlite' });
63
+ const result = await migrateSQLiteCore({ filename: './data/collaboration.sqlite' });
64
+ // { from: 2, to: 3, backupFilename: './data/collaboration.sqlite.v2.backup' }
71
65
  ```
72
66
 
73
- Missing data is filled using these rules:
67
+ The backup is a consistent copy written next to the database before anything changes; pass
68
+ `backupFilename` to choose its path. An existing backup file is never overwritten. A database that
69
+ already has the current version is left alone and gets no backup.
70
+
71
+ Each step runs in one transaction. If a step fails, the file stays at the last complete version and
72
+ the backup stays in place; calling `migrateSQLiteCore` again continues from there. Tables of other
73
+ Univer components and application objects that reference the core tables are kept.
74
+
75
+ ### Data added in v2
76
+
77
+ V2 added the creator and creation time of every Unit and the commit time of every changeset. A v1
78
+ database fills them using these rules:
79
+
80
+ - Unit creator and creation time: revision 1's `user_id` and `committed_at` in
81
+ `collaboration_history_revisions` in the same database.
82
+ - Changeset time: payload `createTime` (seconds), then the matching History revision's `committed_at`
83
+ (milliseconds).
84
+ - Otherwise `anonymous` for the creator and the migration start time for timestamps. These fallback
85
+ values do not represent historical facts.
86
+
87
+ Optional `resolveUnitCreation(unitID)` and `resolveChangesetCreatedAt(unitID, revision)` options
88
+ replace the defaults. They may be async and return `{ creatorID, createdAt }` and a timestamp in Unix
89
+ milliseconds. They cover soft-deleted Units too and must not write to the same database. Invalid
90
+ results or exceptions roll back the step.
74
91
 
75
- - Unit creator and creation time: revision 1's `user_id` and `committed_at` in `collaboration_history_revisions` in the same database.
76
- - Changeset time: payload `createTime` (seconds), then the matching History revision's `committed_at` (milliseconds).
77
- - Missing or invalid information: `anonymous` for the creator and the migration start time for timestamps.
78
- These fallback values do not represent historical facts.
92
+ ### Data changed in v3
79
93
 
80
- Optional `resolveUnitCreation(unitID)` and `resolveChangesetCreatedAt(unitID, revision)` callbacks
81
- replace the defaults. They may be async and return `{ creatorID, createdAt }` and a timestamp,
82
- respectively, using Unix milliseconds. They cover soft-deleted Units too and must not write to
83
- the same database. Invalid callback results or exceptions roll back the migration.
94
+ V3 stores protocol objects as MessagePack `BLOB` payloads instead of JSON text, records deletion in
95
+ `collaboration_units` as `deleted_status` and `deleted_at_ms`, and drops the tombstone table and the
96
+ explicit indexes. Each v2 tombstone becomes a hard-delete marker row that keeps its Unit ID reserved;
97
+ the marker carries placeholder values (Sheet type, revision 1, creator `anonymous`, purge time as
98
+ creation time) and is never returned by reads.
package/README.zh-CN.md CHANGED
@@ -5,6 +5,7 @@
5
5
  持久化 SQLite `IDatabaseAdapter`,使用稳定的 `libsql` 同步接口,支持 Node.js 22
6
6
  及以上版本。
7
7
 
8
+
8
9
  ## 创建 Adapter
9
10
 
10
11
  ```bash
@@ -34,51 +35,59 @@ await database.dispose();
34
35
 
35
36
  将 Adapter 作为 `dbAdapter` 传给 `UniverCollabService`。
36
37
 
37
- ## 持久化保证
38
-
39
- Adapter 使用 foreign keys 和 `BEGIN IMMEDIATE` 写事务,保证:
40
-
41
- - 初始 snapshot 与 Sheet blocks 原子创建;
42
- - revision CAS 与 changeset/head 原子发布;
43
- - snapshot 依赖完整后才对新读取可见;
44
- - 软删除、恢复和 hard delete 批次全有或全无;
45
- - hard delete 保留永久删除标记,禁止 Unit ID 复用。
46
-
47
- 它只保存协同核心数据。产品资源、用户、ACL、History、Comment 和 Worktree 分别由应用
48
- 或对应 Adapter 管理。
49
-
50
38
  ## SQLite 行为
51
39
 
52
40
  - 不主动修改 `journal_mode`;需要 WAL、checkpoint 或备份策略时由应用在打开前配置。
53
- - 核心表使用 `collaboration_` 前缀。
54
- - schema 版本以 `('core', 2)` 写入 `collaboration_schema_versions`,不占用
55
- `PRAGMA user_version`。
41
+ - 核心表使用 `collaboration_` 前缀;协议对象以 MessagePack `BLOB` 保存。
42
+ - schema 版本以 `('core', 3)` 写入 `collaboration_schema_versions`,该表与其他 Univer 协同
43
+ 组件共用,不占用 `PRAGMA user_version`。
56
44
  - changeset 标量列和 submission unique constraint 提供数据库级完整性;提交只做 revision
57
45
  CAS,不按 submission key 点查。
58
- - 空库会自动初始化;不完整或不支持的核心 schema 会被拒绝。
46
+ - 空库会自动初始化;版本不为 3 的核心 schema 会被拒绝,见下文的迁移一节。
59
47
 
60
48
  本实现适合本地应用和中小规模单 Node 部署。
61
49
 
62
- ## 显式 v1 → v2 迁移
50
+ ## 迁移
51
+
52
+ 每个版本只写入并打开一个核心 schema 版本。打开旧库会报错并指向这里;打开数据库时从不自动迁移。
63
53
 
64
- v2 为 `collaboration_units` 新增必填的 `creator_id`(创建者)和
65
- `created_at_ms`(创建时间,Unix 毫秒),为 `collaboration_changesets` 新增必填的
66
- `created_at_ms`(提交时间,Unix 毫秒)。
54
+ | 核心 schema | 写入版本 |
55
+ | --- | --- |
56
+ | v1 | 1.0.0-rc |
57
+ | v2 | 1.0.0 至 1.3.x |
58
+ | v3 | 本版本 |
67
59
 
68
- 停止写入并备份后,在构造 Adapter 前执行;打开旧库不会自动迁移。
60
+ 先停止写入,然后由 `migrateSQLiteCore` 备份文件并补齐所有缺少的步骤:
69
61
 
70
62
  ```ts
71
- import { migrateSQLiteCoreV1ToV2 } from '@univerjs-pro/collaboration-database-sqlite';
63
+ import { migrateSQLiteCore } from '@univerjs-pro/collaboration-database-sqlite';
72
64
 
73
- await migrateSQLiteCoreV1ToV2({ filename: './data/collaboration.sqlite' });
65
+ const result = await migrateSQLiteCore({ filename: './data/collaboration.sqlite' });
66
+ // { from: 2, to: 3, backupFilename: './data/collaboration.sqlite.v2.backup' }
74
67
  ```
75
68
 
76
- 默认按以下规则补齐数据:
69
+ 备份是在任何改动之前写到数据库旁边的一致副本,可用 `backupFilename` 指定路径;已有的备份文件永远不会被
70
+ 覆盖。已经是当前版本的数据库原样保留,也不会生成备份。
71
+
72
+ 每一步在一个事务内完成。某一步失败时,文件停在上一个完整版本,备份仍然保留;再次调用
73
+ `migrateSQLiteCore` 会从那里继续。其他 Univer 组件的表以及引用核心表的应用对象都会保留。
74
+
75
+ ### v2 新增的数据
76
+
77
+ v2 增加了每个 Unit 的创建者和创建时间,以及每个 changeset 的提交时间。v1 数据库按以下规则补全:
78
+
79
+ - Unit 创建者和创建时间:同一数据库 `collaboration_history_revisions` 中 revision 1 的 `user_id`
80
+ 和 `committed_at`。
81
+ - changeset 时间:payload 的 `createTime`(秒),其次是对应 History revision 的 `committed_at`(毫秒)。
82
+ - 其余情况创建者为 `anonymous`,时间为迁移开始时刻。这些兜底值不代表历史事实。
83
+
84
+ 可选项 `resolveUnitCreation(unitID)` 和 `resolveChangesetCreatedAt(unitID, revision)` 替代默认规则。
85
+ 它们可以是异步的,分别返回 `{ creatorID, createdAt }` 和 Unix 毫秒时间戳;软删除的 Unit 同样会调用,
86
+ 并且不能写同一数据库。结果无效或抛错会回滚这一步。
77
87
 
78
- - Unit 创建者和时间:同一数据库中 `collaboration_history_revisions` 的 revision 1 记录中的 `user_id`、`committed_at`。
79
- - Changeset 时间:优先使用 payload 的 `createTime`(秒),其次使用对应 History revision 的 `committed_at`(毫秒)。
80
- - 信息缺失或非法:创建者使用 `anonymous`,时间使用本次迁移开始时间。这些兜底值不代表真实历史。
88
+ ### v3 改变的数据
81
89
 
82
- 可选回调 `resolveUnitCreation(unitID)` 和 `resolveChangesetCreatedAt(unitID, revision)`
83
- 可覆盖默认策略,分别返回 `{ creatorID, createdAt }` 和时间值,时间均为 Unix 毫秒,支持异步。
84
- 回调也包含软删除 Unit,不得写入同一数据库;返回非法值或抛出异常会使迁移整体回滚。
90
+ v3 以 MessagePack `BLOB` 保存协议对象而不再是 JSON 文本,删除状态记录在 `collaboration_units` 的
91
+ `deleted_status` 与 `deleted_at_ms` 中,并移除 tombstone 表和显式索引。每条 v2 tombstone 变成一行
92
+ hard delete 标记,继续占住该 Unit ID;标记行使用占位值(Sheet 类型、revision 1、创建者 `anonymous`、
93
+ 清除时间作为创建时间),读取接口永远不会返回它。
package/dist/index.cjs CHANGED
@@ -1 +1,130 @@
1
- Object['defineProperty'](exports,Symbol['toStringTag'],{'value':'Module'});var e=Object['create'],t=Object['defineProperty'],n=Object['getOwnPropertyDescriptor'],r=Object['getOwnPropertyNames'],i=Object['getPrototypeOf'],a=Object['prototype']['hasOwnProperty'],o=(_0x3a7ee9,_0x28eb0c,_0x50db8a,_0x555717)=>{if(_0x28eb0c&&typeof _0x28eb0c=='object'||typeof _0x28eb0c=='function'){for(var _0x53fd6d=r(_0x28eb0c),_0x337698=0x0,_0x15e1e2=_0x53fd6d['length'],_0x2bbcfd;_0x337698<_0x15e1e2;_0x337698++)_0x2bbcfd=_0x53fd6d[_0x337698],!a['call'](_0x3a7ee9,_0x2bbcfd)&&_0x2bbcfd!==_0x50db8a&&t(_0x3a7ee9,_0x2bbcfd,{'get':(_0x37a1bf=>_0x28eb0c[_0x37a1bf])['bind'](null,_0x2bbcfd),'enumerable':!(_0x555717=n(_0x28eb0c,_0x2bbcfd))||_0x555717['enumerable']});}return _0x3a7ee9;},s=(_0x179223,_0x1f0a96,_0x6673c4)=>(_0x6673c4=_0x179223==null?{}:e(i(_0x179223)),o(_0x1f0a96||!_0x179223||!_0x179223['__esModule']?t(_0x6673c4,'default',{'value':_0x179223,'enumerable':!0x0}):_0x6673c4,_0x179223));let c=require('libsql');c=s(c,0x1);let l=require('@univerjs-pro/collaboration-service');var u=0x1388,d='__univerCollaborationBinary',f='core',p=0x2,m=['collaboration_units','collaboration_unit_tombstones','collaboration_snapshots','collaboration_changesets','collaboration_sheet_blocks'],h=class{['_database'];['_disposed']=!0x1;constructor(_0x5b1441){g(_0x5b1441),this['_database']=new c['default'](_0x5b1441['filename'],{'timeout':_0x5b1441['busyTimeoutMs']??u});try{this['_database']['exec']('PRAGMA\x20foreign_keys\x20=\x20ON;'),this['_database']['exec']('PRAGMA\x20busy_timeout\x20=\x20'+(_0x5b1441['busyTimeoutMs']??u)+';'),this['_initializeSchema']();}catch(_0x482e4c){throw this['_database']['close'](),_0x482e4c;}}async['getUnit'](_0x304f8e,_0x2a3e5e){this['_assertOpen']();let _0x330382=this['_database']['prepare']('SELECT\x20unit_id,\x20type,\x20head_revision,\x20creator_id,\x20created_at_ms,\x20soft_deleted_at_ms\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?\x20AND\x20soft_deleted_at_ms\x20IS\x20NULL')['get'](_0x2a3e5e);return _0x330382?v(_0x330382):null;}async['getSnapshot'](_0x37b2ca,_0x50dd46,_0x1a16cf){this['_assertOpen']();let _0x5af126=_0x1a16cf?.['revision'];if(_0x5af126!==void 0x0&&_0x5af126<0x0)throw y('Snapshot\x20revision\x20cannot\x20be\x20negative');let _0x11725a=this['_database']['prepare']('SELECT\x20collaboration_snapshots.payload_json\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_snapshots\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20JOIN\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20collaboration_units.unit_id\x20=\x20collaboration_snapshots.unit_id\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20collaboration_snapshots.unit_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+(_0x5af126===void 0x0?'':'AND\x20collaboration_snapshots.revision\x20<=\x20?')+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20collaboration_units.soft_deleted_at_ms\x20IS\x20NULL\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20ORDER\x20BY\x20collaboration_snapshots.revision\x20DESC\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20LIMIT\x201')['get'](_0x50dd46,..._0x5af126===void 0x0?[]:[_0x5af126]);return _0x11725a?C(_0x11725a['payload_json']):null;}async['getSnapshotInfo'](_0x5e0084,_0x3dd253,_0x30be3e){this['_assertOpen']();let _0x37f90d=_0x30be3e?.['revision'];if(_0x37f90d!==void 0x0&&_0x37f90d<0x0)throw y('Snapshot\x20revision\x20cannot\x20be\x20negative');let _0x62c7f9=this['_database']['prepare']('SELECT\x20snapshots.unit_id\x20AS\x20unitID,\x20snapshots.type,\x20snapshots.revision\x20AS\x20rev\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_snapshots\x20AS\x20snapshots\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20JOIN\x20collaboration_units\x20AS\x20units\x20ON\x20units.unit_id\x20=\x20snapshots.unit_id\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20snapshots.unit_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20units.soft_deleted_at_ms\x20IS\x20NULL\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+(_0x37f90d===void 0x0?'':'AND\x20snapshots.revision\x20<=\x20?')+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20ORDER\x20BY\x20snapshots.revision\x20DESC\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20LIMIT\x201')['get'](_0x3dd253,..._0x37f90d===void 0x0?[]:[_0x37f90d]);return _0x62c7f9?{'unitID':_0x62c7f9['unitID'],'type':_0x62c7f9['type'],'rev':_0x62c7f9['rev']}:null;}async['getChangesets'](_0x3d95ee,_0x351b47,_0x1486e1){if(this['_assertOpen'](),_0x1486e1['from']<0x0||_0x1486e1['to']!==void 0x0&&_0x1486e1['to']<0x0)throw y('Changeset\x20range\x20revisions\x20cannot\x20be\x20negative');let _0x16817c=this['_database']['prepare']('SELECT\x20collaboration_changesets.payload_json\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20LEFT\x20JOIN\x20collaboration_changesets\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20collaboration_changesets.unit_id\x20=\x20collaboration_units.unit_id\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20collaboration_changesets.revision\x20>\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+(_0x1486e1['to']===void 0x0?'':'AND\x20collaboration_changesets.revision\x20<=\x20?')+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20collaboration_units.unit_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20collaboration_units.soft_deleted_at_ms\x20IS\x20NULL\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20ORDER\x20BY\x20collaboration_changesets.revision\x20ASC')['all'](_0x1486e1['from'],..._0x1486e1['to']===void 0x0?[]:[_0x1486e1['to']],_0x351b47);return _0x16817c['length']===0x0?null:_0x16817c['flatMap'](_0x29f27a=>_0x29f27a['payload_json']?[C(_0x29f27a['payload_json'])]:[]);}async['createUnit'](_0x281bef,_0x40fc9d){this['_assertOpen'](),_(_0x40fc9d);let _0x195eff=S(_0x40fc9d['snapshot']),_0x3cc575=(_0x40fc9d['sheetBlocks']??[])['map'](_0x1cfe96=>({'id':_0x1cfe96['id'],'payload':S(_0x1cfe96)}));return this['_transaction'](()=>{if(this['_hasTombstone'](_0x40fc9d['record']['unitID']))throw y('Cannot\x20reuse\x20a\x20hard-deleted\x20unit\x20ID');let _0x3eafef=this['_getStoredUnitRow'](_0x40fc9d['record']['unitID']);if(_0x3eafef){if(_0x3eafef['soft_deleted_at_ms']!==null)throw y('Cannot\x20reuse\x20a\x20soft-deleted\x20unit\x20ID');return{'status':'already-exists','record':v(_0x3eafef)};}return this['_database']['prepare']('INSERT\x20INTO\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(unit_id,\x20type,\x20head_revision,\x20creator_id,\x20created_at_ms,\x20soft_deleted_at_ms)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x20?,\x201,\x20?,\x20?,\x20NULL)')['run'](_0x40fc9d['record']['unitID'],_0x40fc9d['record']['type'],_0x40fc9d['record']['creatorID'],_0x40fc9d['record']['createdAt']),this['_writeSheetBlocks'](_0x40fc9d['record']['unitID'],_0x3cc575),this['_database']['prepare']('INSERT\x20INTO\x20collaboration_snapshots\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(unit_id,\x20revision,\x20type,\x20payload_json)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x201,\x20?,\x20?)')['run'](_0x40fc9d['record']['unitID'],_0x40fc9d['record']['type'],_0x195eff),{'status':'created','record':{..._0x40fc9d['record']}};});}async['deleteUnits'](_0x4348f1,_0x462f25){return this['_assertOpen'](),this['_transaction'](()=>{let _0x111a7e=x(_0x462f25['unitIDs'])['map'](_0xde64b1=>{let _0x972e45=this['_getStoredUnitRow'](_0xde64b1);if(!_0x972e45){if(_0x462f25['hardDelete']&&this['_hasTombstone'](_0xde64b1))return{'unitID':_0xde64b1,'status':'already-hard-deleted'};throw new l['CollabError']('UNIT_NOT_FOUND','Cannot\x20delete\x20a\x20missing\x20unit');}return _0x462f25['hardDelete']?{'unitID':_0xde64b1,'status':'hard-deleted'}:{'unitID':_0xde64b1,'status':_0x972e45['soft_deleted_at_ms']===null?'soft-deleted':'already-soft-deleted'};}),_0x40ccba=this['_database']['prepare']('UPDATE\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20soft_deleted_at_ms\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?\x20AND\x20soft_deleted_at_ms\x20IS\x20NULL'),_0x300469=this['_database']['prepare']('INSERT\x20INTO\x20collaboration_unit_tombstones\x20(unit_id,\x20purged_at)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x20?)'),_0xedf67e=this['_database']['prepare']('DELETE\x20FROM\x20collaboration_units\x20WHERE\x20unit_id\x20=\x20?'),_0x37cb16=Date['now']();for(let _0x24df5d of _0x111a7e)_0x24df5d['status']==='soft-deleted'?_0x40ccba['run'](_0x37cb16,_0x24df5d['unitID']):_0x24df5d['status']==='hard-deleted'&&(_0x300469['run'](_0x24df5d['unitID'],_0x37cb16),_0xedf67e['run'](_0x24df5d['unitID']));return{'units':_0x111a7e};});}async['recoverUnits'](_0x284c39,_0x58a7e0){return this['_assertOpen'](),this['_transaction'](()=>{let _0x4062c6=x(_0x58a7e0['unitIDs'])['map'](_0x54ac06=>{let _0x1e550b=this['_getStoredUnitRow'](_0x54ac06);if(!_0x1e550b)throw this['_hasTombstone'](_0x54ac06)?y('Cannot\x20recover\x20a\x20hard-deleted\x20unit'):new l['CollabError']('UNIT_NOT_FOUND','Cannot\x20recover\x20a\x20missing\x20unit');return{'unitID':_0x54ac06,'status':_0x1e550b['soft_deleted_at_ms']===null?'already-active':'recovered'};}),_0x24c0f3=this['_database']['prepare']('UPDATE\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20soft_deleted_at_ms\x20=\x20NULL\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?\x20AND\x20soft_deleted_at_ms\x20IS\x20NOT\x20NULL');for(let _0x221a56 of _0x4062c6)_0x221a56['status']==='recovered'&&_0x24c0f3['run'](_0x221a56['unitID']);return{'units':_0x4062c6};});}async['commitChangeset'](_0x473389,_0x2d1c0b){return this['_assertOpen'](),this['_transaction'](()=>{let {changeset:_0xd7e103}=_0x2d1c0b,_0x549fdc=this['_getActiveUnitRow'](_0xd7e103['unitID']);if(!_0x549fdc)throw new l['CollabError']('UNIT_NOT_FOUND','Cannot\x20commit\x20to\x20a\x20missing\x20unit');if(_0x549fdc['head_revision']!==_0xd7e103['revision']-0x1)return{'status':'revision-mismatch','actualHeadRevision':_0x549fdc['head_revision']};let _0x500305=Date['now'](),_0xd15977=S({..._0xd7e103,'createTime':Math['floor'](_0x500305/0x3e8)});if(this['_database']['prepare']('INSERT\x20INTO\x20collaboration_changesets\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(unit_id,\x20revision,\x20base_revision,\x20sid,\x20req_id,\x20created_at_ms,\x20payload_json)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x20?,\x20?,\x20?,\x20?,\x20?,\x20?)')['run'](_0xd7e103['unitID'],_0xd7e103['revision'],_0xd7e103['baseRev'],_0xd7e103['sid'],_0xd7e103['reqId'],_0x500305,_0xd15977),this['_database']['prepare']('UPDATE\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20head_revision\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20head_revision\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20soft_deleted_at_ms\x20IS\x20NULL')['run'](_0xd7e103['revision'],_0xd7e103['unitID'],_0xd7e103['revision']-0x1)['changes']!==0x1)throw new l['CollabError']('INTERNAL_ERROR','SQLite\x20head\x20changed\x20inside\x20an\x20exclusive\x20write\x20transaction');return{'status':'committed','changeset':C(_0xd15977),'headRevision':_0xd7e103['revision']};});}async['saveSnapshot'](_0x169fb3,_0x11ebd4){this['_assertOpen']();let _0x1f2538=S(_0x11ebd4['snapshot']),_0x522a1e=(_0x11ebd4['sheetBlocks']??[])['map'](_0x51d4c4=>({'id':_0x51d4c4['id'],'payload':S(_0x51d4c4)}));this['_transaction'](()=>{let _0x59dfea=this['_getActiveUnitRow'](_0x11ebd4['snapshot']['unitID']);if(!_0x59dfea)throw new l['CollabError']('UNIT_NOT_FOUND','Cannot\x20snapshot\x20a\x20missing\x20unit');if(_0x11ebd4['snapshot']['type']!==_0x59dfea['type']||_0x11ebd4['snapshot']['rev']<0x1||_0x11ebd4['snapshot']['rev']>_0x59dfea['head_revision'])throw y('Snapshot\x20does\x20not\x20match\x20the\x20stored\x20unit\x20head');this['_writeSheetBlocks'](_0x11ebd4['snapshot']['unitID'],_0x522a1e),this['_database']['prepare']('INSERT\x20INTO\x20collaboration_snapshots\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(unit_id,\x20revision,\x20type,\x20payload_json)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x20?,\x20?,\x20?)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20CONFLICT(unit_id,\x20revision)\x20DO\x20UPDATE\x20SET\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20type\x20=\x20excluded.type,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20payload_json\x20=\x20excluded.payload_json')['run'](_0x11ebd4['snapshot']['unitID'],_0x11ebd4['snapshot']['rev'],_0x11ebd4['snapshot']['type'],_0x1f2538);});}async['getSheetBlock'](_0x393faf,_0x4784aa,_0xa120c5){this['_assertOpen']();let _0x28d4ed=this['_database']['prepare']('SELECT\x20collaboration_sheet_blocks.payload_json\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_sheet_blocks\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20JOIN\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20collaboration_units.unit_id\x20=\x20collaboration_sheet_blocks.unit_id\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20collaboration_sheet_blocks.unit_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20collaboration_sheet_blocks.block_id\x20=\x20?\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AND\x20collaboration_units.soft_deleted_at_ms\x20IS\x20NULL')['get'](_0x4784aa,_0xa120c5);return _0x28d4ed?C(_0x28d4ed['payload_json']):null;}async['dispose'](){this['_disposed']||(this['_disposed']=!0x0,this['_database']['close']());}['_initializeSchema'](){this['_transaction'](()=>{if(!this['_hasTable']('collaboration_schema_versions')){if(this['_hasAnyCoreTable']())throw b('SQLite\x20collaboration\x20core\x20tables\x20exist\x20without\x20a\x20schema\x20version');this['_database']['exec']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_schema_versions\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20component\x20TEXT\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20version\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(version\x20>=\x201)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x20\x20\x20\x20\x20\x20\x20\x20');}let _0x2086bb=this['_database']['prepare']('SELECT\x20version\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_schema_versions\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20component\x20=\x20?')['get'](f);if(_0x2086bb){if(_0x2086bb['version']!==p)throw b('SQLite\x20collaboration\x20core\x20schema\x20version\x20'+_0x2086bb['version']+'\x20is\x20not\x20supported;\x20version\x201\x20requires\x20explicit\x20migrateSQLiteCoreV1ToV2\x20with\x20a\x20Unit\x20creation\x20resolver');let _0x5bd141=m['filter'](_0x20248c=>!this['_hasTable'](_0x20248c));if(_0x5bd141['length']>0x0)throw b('SQLite\x20collaboration\x20core\x20schema\x20v'+_0x2086bb['version']+'\x20is\x20incomplete:\x20missing\x20'+_0x5bd141['join'](',\x20'));if(!this['_database']['prepare']('PRAGMA\x20table_info(collaboration_changesets)')['all']()['some'](_0x247949=>_0x247949['name']==='created_at_ms'&&_0x247949['notnull']===0x1))throw b('Changeset\x20schema\x20requires\x20NOT\x20NULL\x20created_at_ms');let _0x224095=this['_database']['prepare']('PRAGMA\x20table_info(collaboration_units)')['all']();if(!['creator_id','created_at_ms']['every'](_0x11e555=>_0x224095['some'](_0x4a0fd8=>_0x4a0fd8['name']===_0x11e555&&_0x4a0fd8['notnull']===0x1)))throw b('SQLite\x20collaboration\x20core\x20schema\x20v2\x20requires\x20NOT\x20NULL\x20creator_id\x20and\x20created_at_ms');return;}if(this['_hasAnyCoreTable']())throw b('SQLite\x20collaboration\x20core\x20tables\x20exist\x20without\x20a\x20schema\x20version');this['_database']['exec']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_units\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20type\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20head_revision\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(head_revision\x20>=\x201),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20creator_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20created_at_ms\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20soft_deleted_at_ms\x20INTEGER\x0a\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_unit_tombstones\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20purged_at\x20INTEGER\x20NOT\x20NULL\x0a\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_snapshots\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20revision\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(revision\x20>=\x201),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20type\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20payload_json\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20PRIMARY\x20KEY\x20(unit_id,\x20revision),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20FOREIGN\x20KEY\x20(unit_id)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20REFERENCES\x20collaboration_units(unit_id)\x20ON\x20DELETE\x20CASCADE\x0a\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_changesets\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20revision\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(revision\x20>=\x202),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20base_revision\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(base_revision\x20>=\x201),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20sid\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20req_id\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(req_id\x20>=\x201),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20created_at_ms\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20payload_json\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20PRIMARY\x20KEY\x20(unit_id,\x20revision),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20UNIQUE\x20(unit_id,\x20sid,\x20req_id),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20FOREIGN\x20KEY\x20(unit_id)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20REFERENCES\x20collaboration_units(unit_id)\x20ON\x20DELETE\x20CASCADE\x0a\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20collaboration_sheet_blocks\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20block_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20payload_json\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20PRIMARY\x20KEY\x20(unit_id,\x20block_id),\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20FOREIGN\x20KEY\x20(unit_id)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20REFERENCES\x20collaboration_units(unit_id)\x20ON\x20DELETE\x20CASCADE\x0a\x20\x20\x20\x20\x20\x20\x20\x20);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20INDEX\x20collaboration_snapshots_nearest_revision\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20collaboration_snapshots(unit_id,\x20revision\x20DESC);\x0a\x20\x20\x20\x20\x20\x20\x20\x20CREATE\x20INDEX\x20collaboration_changesets_revision_range\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ON\x20collaboration_changesets(unit_id,\x20revision\x20ASC);\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20collaboration_schema_versions\x20(component,\x20version)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20(\x27core\x27,\x202);\x0a\x20\x20\x20\x20\x20\x20');});}['_getActiveUnitRow'](_0x11f6e3){return this['_database']['prepare']('SELECT\x20unit_id,\x20type,\x20head_revision,\x20creator_id,\x20created_at_ms,\x20soft_deleted_at_ms\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?\x20AND\x20soft_deleted_at_ms\x20IS\x20NULL')['get'](_0x11f6e3)??null;}['_getStoredUnitRow'](_0x28d583){return this['_database']['prepare']('SELECT\x20unit_id,\x20type,\x20head_revision,\x20creator_id,\x20created_at_ms,\x20soft_deleted_at_ms\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20collaboration_units\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20unit_id\x20=\x20?')['get'](_0x28d583)??null;}['_hasTombstone'](_0x453dd1){return!!this['_database']['prepare']('SELECT\x201\x20FROM\x20collaboration_unit_tombstones\x20WHERE\x20unit_id\x20=\x20?')['get'](_0x453dd1);}['_hasTable'](_0x530db2){return!!this['_database']['prepare']('SELECT\x201\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20FROM\x20sqlite_schema\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20type\x20=\x20\x27table\x27\x20AND\x20name\x20=\x20?')['get'](_0x530db2);}['_hasAnyCoreTable'](){return m['some'](_0x22b420=>this['_hasTable'](_0x22b420));}['_writeSheetBlocks'](_0x468096,_0x45dc42){let _0x5a65a9=this['_database']['prepare']('INSERT\x20INTO\x20collaboration_sheet_blocks\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20(unit_id,\x20block_id,\x20payload_json)\x0a\x20\x20\x20\x20\x20\x20\x20VALUES\x20(?,\x20?,\x20?)\x0a\x20\x20\x20\x20\x20\x20\x20ON\x20CONFLICT(unit_id,\x20block_id)\x20DO\x20UPDATE\x20SET\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20payload_json\x20=\x20excluded.payload_json');for(let _0x43cb8c of _0x45dc42)_0x5a65a9['run'](_0x468096,_0x43cb8c['id'],_0x43cb8c['payload']);}['_transaction'](_0x40ab9f){this['_database']['exec']('BEGIN\x20IMMEDIATE;');try{let _0x25774f=_0x40ab9f();return this['_database']['exec']('COMMIT;'),_0x25774f;}catch(_0x319779){throw this['_database']['inTransaction']&&this['_database']['exec']('ROLLBACK;'),_0x319779;}}['_assertOpen'](){if(this['_disposed'])throw new l['CollabError']('INTERNAL_ERROR','SQLite\x20Database\x20Adapter\x20is\x20disposed');}};function g(_0x2577dd){if(!_0x2577dd['filename'])throw y('SQLite\x20filename\x20is\x20required');if(_0x2577dd['busyTimeoutMs']!==void 0x0&&(!Number['isSafeInteger'](_0x2577dd['busyTimeoutMs'])||_0x2577dd['busyTimeoutMs']<0x0))throw y('SQLite\x20busyTimeoutMs\x20must\x20be\x20a\x20non-negative\x20integer');}function _(_0x2bac71){let {record:_0x3e18ca,snapshot:_0x42e93d}=_0x2bac71;if(_0x3e18ca['headRevision']!==0x1||_0x42e93d['rev']!==0x1||_0x42e93d['unitID']!==_0x3e18ca['unitID']||_0x42e93d['type']!==_0x3e18ca['type'])throw y('Initial\x20unit\x20record\x20and\x20snapshot\x20must\x20match\x20at\x20revision\x201');if(typeof _0x3e18ca['creatorID']!='string'||_0x3e18ca['creatorID']['length']===0x0||!Number['isSafeInteger'](_0x3e18ca['createdAt'])||_0x3e18ca['createdAt']<0x0)throw y('Unit\x20creation\x20requires\x20creatorID\x20and\x20createdAt\x20in\x20Unix\x20milliseconds');}function v(_0xe3164d){return{'unitID':_0xe3164d['unit_id'],'type':_0xe3164d['type'],'headRevision':_0xe3164d['head_revision'],'creatorID':_0xe3164d['creator_id'],'createdAt':_0xe3164d['created_at_ms']};}function y(_0x12298e){return new l['CollabError']('INVALID_REQUEST',_0x12298e);}function b(_0x3715e5){return new l['CollabError']('INTERNAL_ERROR',_0x3715e5);}function x(_0x54b81c){return[...new Set(_0x54b81c)];}function S(_0x504f13){return JSON['stringify'](_0x504f13,function(_0x36cd73,_0x577b5b){let _0xe20e05=this[_0x36cd73];return _0xe20e05 instanceof Uint8Array?{[d]:Buffer['from'](_0xe20e05)['toString']('base64')}:_0x577b5b;});}function C(_0x12a5be){return JSON['parse'](_0x12a5be,(_0x550a96,_0x1b6808)=>w(_0x1b6808)?Uint8Array['from'](Buffer['from'](_0x1b6808[d],'base64')):_0x1b6808);}function w(_0x430302){return typeof _0x430302=='object'&&!!_0x430302&&Object['keys'](_0x430302)['length']===0x1&&typeof _0x430302[d]=='string';}async function T(_0x37e9e6){let _0x61802b=Date['now'](),_0x3c338c=new c['default'](_0x37e9e6['filename'],{'fileMustExist':!0x0}),_0x3a11a8=!0x1;try{if(_0x3c338c['exec']('PRAGMA\x20foreign_keys\x20=\x20OFF;\x20PRAGMA\x20legacy_alter_table\x20=\x20ON;\x20BEGIN\x20IMMEDIATE;'),_0x3a11a8=!0x0,_0x3c338c['prepare']('SELECT\x20version\x20FROM\x20collaboration_schema_versions\x20WHERE\x20component\x20=\x20\x27core\x27')['get']()?.['version']!==0x1)throw new l['CollabError']('INVALID_REQUEST','migrateSQLiteCoreV1ToV2\x20requires\x20core\x20schema\x20version\x201');for(let _0x2a2a00 of['collaboration_unit_tombstones','collaboration_snapshots','collaboration_changesets','collaboration_sheet_blocks'])_0x3c338c['prepare']('SELECT\x201\x20FROM\x20'+_0x2a2a00+'\x20LIMIT\x200')['all']();let _0x22b427=_0x3c338c['prepare']('SELECT\x201\x20FROM\x20sqlite_schema\x20WHERE\x20type\x20=\x20\x27table\x27\x20AND\x20name\x20=\x20\x27collaboration_history_revisions\x27')['get']()?_0x3c338c['prepare']('SELECT\x20user_id,\x20committed_at\x20FROM\x20collaboration_history_revisions\x20WHERE\x20unit_id\x20=\x20?\x20AND\x20revision\x20=\x20?'):void 0x0,_0x1ec095=(_0x6d653f,_0x20683b)=>_0x22b427?.['get'](_0x6d653f,_0x20683b),_0x5df48a=_0x3c338c['prepare']('PRAGMA\x20table_info(collaboration_units)')['all'](),_0x2ce5b9=['unit_id','type','head_revision','soft_deleted_at_ms'];if(_0x5df48a['length']!==_0x2ce5b9['length']||_0x2ce5b9['some'](_0x2458d2=>!_0x5df48a['some'](_0x185c3e=>_0x185c3e['name']===_0x2458d2)))throw new l['CollabError']('INVALID_REQUEST','Core\x20v1\x20Unit\x20columns\x20differ\x20from\x20the\x20supported\x20schema;\x20refusing\x20a\x20potentially\x20lossy\x20migration');let _0x200c00=_0x3c338c['prepare']('SELECT\x20sql\x20FROM\x20sqlite_schema\x20WHERE\x20tbl_name\x20=\x20\x27collaboration_units\x27\x20AND\x20type\x20IN\x20(\x27index\x27,\x20\x27trigger\x27)\x20AND\x20sql\x20IS\x20NOT\x20NULL')['all']();_0x3c338c['exec']('CREATE\x20TABLE\x20collaboration_units_v2\x20(\x0a\x20\x20\x20\x20\x20\x20unit_id\x20TEXT\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20type\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20head_revision\x20INTEGER\x20NOT\x20NULL\x20CHECK\x20(head_revision\x20>=\x201),\x0a\x20\x20\x20\x20\x20\x20creator_id\x20TEXT\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20created_at_ms\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20soft_deleted_at_ms\x20INTEGER\x0a\x20\x20\x20\x20);');let _0x4cbfc0=D(_0x3c338c,'collaboration_units',['unit_id']),_0x174570=_0x3c338c['prepare']('INSERT\x20INTO\x20collaboration_units_v2\x20VALUES\x20(?,\x20?,\x20?,\x20?,\x20?,\x20?)');for(let _0x58560b of _0x4cbfc0){let _0x1ad44a=_0x37e9e6['resolveUnitCreation']?void 0x0:_0x1ec095(_0x58560b['unit_id'],0x1),_0x1b8d20=_0x37e9e6['resolveUnitCreation']?await _0x37e9e6['resolveUnitCreation'](_0x58560b['unit_id']):{'creatorID':_0x1ad44a?.['user_id']||'anonymous','createdAt':E(_0x1ad44a?.['committed_at'])?_0x1ad44a['committed_at']:_0x61802b};if(!_0x1b8d20||typeof _0x1b8d20['creatorID']!='string'||_0x1b8d20['creatorID']['length']===0x0||!Number['isSafeInteger'](_0x1b8d20['createdAt'])||_0x1b8d20['createdAt']<0x0)throw new l['CollabError']('INVALID_REQUEST','Missing\x20or\x20invalid\x20creation\x20facts\x20for\x20Unit\x20'+_0x58560b['unit_id']);_0x174570['run'](_0x58560b['unit_id'],_0x58560b['type'],_0x58560b['head_revision'],_0x1b8d20['creatorID'],_0x1b8d20['createdAt'],_0x58560b['soft_deleted_at_ms']);}_0x3c338c['exec']('DROP\x20TABLE\x20collaboration_units;\x20ALTER\x20TABLE\x20collaboration_units_v2\x20RENAME\x20TO\x20collaboration_units;');for(let _0x4c7260 of _0x200c00)_0x3c338c['exec'](_0x4c7260['sql']);let _0x31b4f4=_0x3c338c['prepare']('SELECT\x20sql\x20FROM\x20sqlite_schema\x20WHERE\x20type\x20=\x20\x27table\x27\x20AND\x20name\x20=\x20\x27collaboration_changesets\x27')['get'](),_0x5c153e=_0x3c338c['prepare']('PRAGMA\x20table_info(collaboration_changesets)')['all']();if(_0x5c153e['some'](_0x2c3275=>_0x2c3275['name']==='created_at_ms'))throw new l['CollabError']('INVALID_REQUEST','Unexpected\x20changeset\x20creation-time\x20column\x20in\x20legacy\x20schema');let _0x73d7fd=_0x3c338c['prepare']('SELECT\x20sql\x20FROM\x20sqlite_schema\x20WHERE\x20tbl_name\x20=\x20\x27collaboration_changesets\x27\x20AND\x20type\x20IN\x20(\x27index\x27,\x20\x27trigger\x27)\x20AND\x20sql\x20IS\x20NOT\x20NULL')['all']();_0x3c338c['exec']('CREATE\x20TABLE\x20collaboration_changesets_new\x20(\x0a\x20\x20\x20\x20\x20\x20created_at_ms\x20INTEGER\x20NOT\x20NULL,\x0a\x20\x20\x20\x20\x20\x20'+_0x31b4f4['sql']['slice'](_0x31b4f4['sql']['indexOf']('(')+0x1));let _0x10c7af=D(_0x3c338c,'collaboration_changesets',['unit_id','revision']),_0x19f325=_0x5c153e['map'](_0x2258b0=>'\x22'+_0x2258b0['name']['replaceAll']('\x22','\x22\x22')+'\x22')['join'](',\x20'),_0x3c9898=_0x3c338c['prepare']('INSERT\x20INTO\x20collaboration_changesets_new\x20('+_0x19f325+',\x20created_at_ms)\x20VALUES\x20('+_0x5c153e['map'](()=>'?')['join'](',\x20')+',\x20?)');for(let _0x7c5db0 of _0x10c7af){let _0x48a2b5=JSON['parse'](_0x7c5db0['payload_json']),_0x12ea9c=typeof _0x48a2b5['createTime']=='number'?_0x48a2b5['createTime']*0x3e8:void 0x0,_0x2309d5=!_0x37e9e6['resolveChangesetCreatedAt']&&!E(_0x12ea9c)?_0x1ec095(_0x7c5db0['unit_id'],_0x7c5db0['revision'])?.['committed_at']:void 0x0,_0xb643d5=_0x37e9e6['resolveChangesetCreatedAt']?await _0x37e9e6['resolveChangesetCreatedAt'](_0x7c5db0['unit_id'],_0x7c5db0['revision']):E(_0x12ea9c)?_0x12ea9c:E(_0x2309d5)?_0x2309d5:_0x61802b;if(!Number['isSafeInteger'](_0xb643d5)||_0xb643d5<0x0)throw new l['CollabError']('INVALID_REQUEST','Missing\x20or\x20invalid\x20changeset\x20time\x20for\x20Unit\x20'+_0x7c5db0['unit_id']+'\x20revision\x20'+_0x7c5db0['revision']);_0x48a2b5['createTime']=Math['floor'](_0xb643d5/0x3e8),_0x3c9898['run'](..._0x5c153e['map'](_0x4b8a3c=>_0x4b8a3c['name']==='payload_json'?JSON['stringify'](_0x48a2b5):_0x7c5db0[_0x4b8a3c['name']]),_0xb643d5);}_0x3c338c['exec']('DROP\x20TABLE\x20collaboration_changesets;\x20ALTER\x20TABLE\x20collaboration_changesets_new\x20RENAME\x20TO\x20collaboration_changesets;');for(let _0x37dabb of _0x73d7fd)_0x3c338c['exec'](_0x37dabb['sql']);if(_0x3c338c['prepare']('PRAGMA\x20foreign_key_check')['all']()['length']>0x0)throw new l['CollabError']('INVALID_REQUEST','Foreign\x20key\x20validation\x20failed\x20during\x20core\x20migration');_0x3c338c['exec']('UPDATE\x20collaboration_schema_versions\x20SET\x20version\x20=\x202\x20WHERE\x20component\x20=\x20\x27core\x27;\x20COMMIT;'),_0x3a11a8=!0x1;}finally{try{_0x3a11a8&&_0x3c338c['exec']('ROLLBACK;');}finally{_0x3c338c['close']();}}}function E(_0x468fc8){return typeof _0x468fc8=='number'&&Number['isSafeInteger'](_0x468fc8)&&_0x468fc8>=0x0;}function*D(_0x4234af,_0x4cce59,_0x1f5d25){let _0x243688=_0x1f5d25['join'](',\x20'),_0x2f56f2=_0x4234af['prepare']('SELECT\x20*\x20FROM\x20'+_0x4cce59+'\x20ORDER\x20BY\x20'+_0x243688+'\x20LIMIT\x20100'),_0x47c832=_0x4234af['prepare']('SELECT\x20*\x20FROM\x20'+_0x4cce59+'\x20WHERE\x20('+_0x243688+')\x20>\x20('+_0x1f5d25['map'](()=>'?')['join'](',\x20')+')\x20ORDER\x20BY\x20'+_0x243688+'\x20LIMIT\x20100'),_0x227f98=_0x2f56f2['all']();for(;_0x227f98['length']>0x0;){yield*_0x227f98;let _0x55eaea=_0x1f5d25['map'](_0x4897df=>_0x227f98[_0x227f98['length']-0x1][_0x4897df]);_0x227f98=[],_0x227f98=_0x47c832['all'](..._0x55eaea);}}exports['SQLiteDatabaseAdapter']=h,exports['migrateSQLiteCoreV1ToV2']=T;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("@msgpack/msgpack"),l=require("libsql");l=s(l,1);let u=require("@univerjs-pro/collaboration-service"),d=require("node:fs"),f=require("node:buffer"),p=require("@univerjs/protocol");var m=`core`,h=`
2
+ CREATE TABLE collaboration_units (
3
+ unit_id TEXT PRIMARY KEY NOT NULL,
4
+ type INTEGER NOT NULL,
5
+ head_revision INTEGER NOT NULL CHECK (head_revision >= 1),
6
+ creator_id TEXT NOT NULL,
7
+ created_at_ms INTEGER NOT NULL,
8
+ deleted_at_ms INTEGER,
9
+ deleted_status TEXT CHECK (deleted_status IN ('soft', 'hard')),
10
+ CHECK ((deleted_status IS NULL) = (deleted_at_ms IS NULL))
11
+ );
12
+ CREATE TABLE collaboration_snapshots (
13
+ unit_id TEXT NOT NULL REFERENCES collaboration_units(unit_id) ON DELETE CASCADE,
14
+ revision INTEGER NOT NULL CHECK (revision >= 1),
15
+ payload BLOB NOT NULL,
16
+ PRIMARY KEY (unit_id, revision)
17
+ );
18
+ CREATE TABLE collaboration_changesets (
19
+ unit_id TEXT NOT NULL REFERENCES collaboration_units(unit_id) ON DELETE CASCADE,
20
+ revision INTEGER NOT NULL CHECK (revision >= 2),
21
+ base_revision INTEGER NOT NULL CHECK (base_revision >= 1),
22
+ sid TEXT NOT NULL,
23
+ req_id INTEGER NOT NULL CHECK (req_id >= 1),
24
+ created_at_ms INTEGER NOT NULL,
25
+ payload BLOB NOT NULL,
26
+ PRIMARY KEY (unit_id, revision),
27
+ UNIQUE (unit_id, sid, req_id)
28
+ );
29
+ CREATE TABLE collaboration_sheet_blocks (
30
+ unit_id TEXT NOT NULL REFERENCES collaboration_units(unit_id) ON DELETE CASCADE,
31
+ block_id TEXT NOT NULL,
32
+ payload BLOB NOT NULL,
33
+ PRIMARY KEY (unit_id, block_id)
34
+ );
35
+ `,g=class{_database;_encoder=new c.Encoder({ignoreUndefined:!0});_decoder=new c.Decoder;_disposed=!1;_getUnit;_getSnapshot;_getSnapshotAtRevision;_getSnapshotInfo;_getSnapshotInfoAtRevision;_getChangesets;_getChangesetsInRange;_getSheetBlock;_insertUnit;_insertChangeset;_updateHeadRevision;_upsertSnapshot;_upsertSheetBlock;_deleteSnapshots;_deleteChangesets;_deleteSheetBlocks;_markSoftDeleted;_markHardDeleted;_markActive;constructor(e){if(!e.filename)throw new u.CollabError(`INVALID_REQUEST`,`SQLite filename is required`);let t=e.busyTimeoutMs??5e3;this._database=new l.default(e.filename,{timeout:t});try{this._database.exec(`PRAGMA foreign_keys = ON; PRAGMA busy_timeout = ${t};`),this._initializeSchema(),this._getUnit=this._database.prepare(`
36
+ SELECT unit_id AS unitID, type, head_revision AS headRevision,
37
+ creator_id AS creatorID, created_at_ms AS createdAt, deleted_status AS deletedStatus
38
+ FROM collaboration_units
39
+ WHERE unit_id = ?
40
+ `),this._getSnapshot=this._database.prepare(`
41
+ SELECT s.payload
42
+ FROM collaboration_snapshots s
43
+ JOIN collaboration_units u ON u.unit_id = s.unit_id
44
+ WHERE s.unit_id = ? AND u.deleted_status IS NULL
45
+ ORDER BY s.revision DESC
46
+ LIMIT 1
47
+ `),this._getSnapshotAtRevision=this._database.prepare(`
48
+ SELECT s.payload
49
+ FROM collaboration_snapshots s
50
+ JOIN collaboration_units u ON u.unit_id = s.unit_id
51
+ WHERE s.unit_id = ? AND u.deleted_status IS NULL AND s.revision <= ?
52
+ ORDER BY s.revision DESC
53
+ LIMIT 1
54
+ `),this._getSnapshotInfo=this._database.prepare(`
55
+ SELECT s.unit_id AS unitID, u.type, s.revision AS rev
56
+ FROM collaboration_snapshots s
57
+ JOIN collaboration_units u ON u.unit_id = s.unit_id
58
+ WHERE s.unit_id = ? AND u.deleted_status IS NULL
59
+ ORDER BY s.revision DESC
60
+ LIMIT 1
61
+ `),this._getSnapshotInfoAtRevision=this._database.prepare(`
62
+ SELECT s.unit_id AS unitID, u.type, s.revision AS rev
63
+ FROM collaboration_snapshots s
64
+ JOIN collaboration_units u ON u.unit_id = s.unit_id
65
+ WHERE s.unit_id = ? AND u.deleted_status IS NULL AND s.revision <= ?
66
+ ORDER BY s.revision DESC
67
+ LIMIT 1
68
+ `),this._getChangesets=this._database.prepare(`
69
+ SELECT c.payload
70
+ FROM collaboration_units u
71
+ LEFT JOIN collaboration_changesets c ON c.unit_id = u.unit_id AND c.revision > ?
72
+ WHERE u.unit_id = ? AND u.deleted_status IS NULL
73
+ ORDER BY c.revision ASC
74
+ `),this._getChangesetsInRange=this._database.prepare(`
75
+ SELECT c.payload
76
+ FROM collaboration_units u
77
+ LEFT JOIN collaboration_changesets c
78
+ ON c.unit_id = u.unit_id AND c.revision > ? AND c.revision <= ?
79
+ WHERE u.unit_id = ? AND u.deleted_status IS NULL
80
+ ORDER BY c.revision ASC
81
+ `),this._getSheetBlock=this._database.prepare(`
82
+ SELECT b.payload
83
+ FROM collaboration_sheet_blocks b
84
+ JOIN collaboration_units u ON u.unit_id = b.unit_id
85
+ WHERE b.unit_id = ? AND b.block_id = ? AND u.deleted_status IS NULL
86
+ `),this._insertUnit=this._database.prepare(`
87
+ INSERT INTO collaboration_units (unit_id, type, head_revision, creator_id, created_at_ms)
88
+ VALUES (?, ?, 1, ?, ?)
89
+ `),this._insertChangeset=this._database.prepare(`
90
+ INSERT INTO collaboration_changesets
91
+ (unit_id, revision, base_revision, sid, req_id, created_at_ms, payload)
92
+ VALUES (?, ?, ?, ?, ?, ?, ?)
93
+ `),this._updateHeadRevision=this._database.prepare(`UPDATE collaboration_units SET head_revision = ? WHERE unit_id = ?`),this._upsertSnapshot=this._database.prepare(`
94
+ INSERT INTO collaboration_snapshots (unit_id, revision, payload) VALUES (?, ?, ?)
95
+ ON CONFLICT (unit_id, revision) DO UPDATE SET payload = excluded.payload
96
+ `),this._upsertSheetBlock=this._database.prepare(`
97
+ INSERT INTO collaboration_sheet_blocks (unit_id, block_id, payload) VALUES (?, ?, ?)
98
+ ON CONFLICT (unit_id, block_id) DO UPDATE SET payload = excluded.payload
99
+ `),this._deleteSnapshots=this._database.prepare(`DELETE FROM collaboration_snapshots WHERE unit_id = ?`),this._deleteChangesets=this._database.prepare(`DELETE FROM collaboration_changesets WHERE unit_id = ?`),this._deleteSheetBlocks=this._database.prepare(`DELETE FROM collaboration_sheet_blocks WHERE unit_id = ?`),this._markSoftDeleted=this._database.prepare(`UPDATE collaboration_units SET deleted_at_ms = ?, deleted_status = 'soft' WHERE unit_id = ?`),this._markHardDeleted=this._database.prepare(`UPDATE collaboration_units SET deleted_at_ms = ?, deleted_status = 'hard' WHERE unit_id = ?`),this._markActive=this._database.prepare(`UPDATE collaboration_units SET deleted_at_ms = NULL, deleted_status = NULL WHERE unit_id = ?`)}catch(e){throw this._database.close(),e}}async getUnit(e,t){this._assertOpen();let n=this._readUnit(t);return n&&n.deletedStatus===null?b(n):null}async getSnapshot(e,t,n){this._assertOpen();let r=v(n?.revision),i=r===void 0?this._getSnapshot.get(t):this._getSnapshotAtRevision.get(t,r);return i?this._decode(i.payload):null}async getSnapshotInfo(e,t,n){this._assertOpen();let r=v(n?.revision),i=r===void 0?this._getSnapshotInfo.get(t):this._getSnapshotInfoAtRevision.get(t,r);return i?{unitID:i.unitID,type:i.type,rev:i.rev}:null}async getChangesets(e,t,n){if(this._assertOpen(),n.from<0||n.to!==void 0&&n.to<0)throw new u.CollabError(`INVALID_REQUEST`,`Changeset range revisions cannot be negative`);let r=n.to===void 0?this._getChangesets.all(n.from,t):this._getChangesetsInRange.all(n.from,n.to,t);if(r.length===0)return null;let i=[];for(let e of r)e.payload!==null&&i.push(this._decode(e.payload));return i}async getSheetBlock(e,t,n){this._assertOpen();let r=this._getSheetBlock.get(t,n);return r?this._decode(r.payload):null}async createUnit(e,t){this._assertOpen(),_(t);let{record:n,snapshot:r,sheetBlocks:i=[]}=t,a=this._encode(r),o=this._encodeBlocks(i);return this._database.transaction(()=>{let e=this._readUnit(n.unitID);if(e){if(e.deletedStatus!==null)throw new u.CollabError(`INVALID_REQUEST`,`A deleted unit ID cannot be reused`);return{status:`already-exists`,record:b(e)}}return this._insertUnit.run(n.unitID,n.type,n.creatorID,n.createdAt),this._writeSnapshot(n.unitID,1,a,o),{status:`created`,record:{...n}}}).immediate()}async commitChangeset(e,t){this._assertOpen();let{changeset:n}=t;return this._database.transaction(()=>{let e=this._requireActiveUnit(n.unitID);if(e.headRevision!==n.revision-1)return{status:`revision-mismatch`,actualHeadRevision:e.headRevision};let t=Date.now(),r={...n,createTime:Math.floor(t/1e3)};return this._insertChangeset.run(n.unitID,n.revision,n.baseRev,n.sid,n.reqId,t,this._encode(r)),this._updateHeadRevision.run(n.revision,n.unitID),{status:`committed`,changeset:r,headRevision:n.revision}}).immediate()}async saveSnapshot(e,t){this._assertOpen();let{snapshot:n,sheetBlocks:r=[]}=t,i=this._encode(n),a=this._encodeBlocks(r);this._database.transaction(()=>{let e=this._requireActiveUnit(n.unitID);if(n.type!==e.type||n.rev<1||n.rev>e.headRevision)throw new u.CollabError(`INVALID_REQUEST`,`Snapshot does not match the stored unit head`);this._writeSnapshot(n.unitID,n.rev,i,a)}).immediate()}async deleteUnits(e,t){this._assertOpen();let{unitIDs:n}=t;return n.length===0?{units:[]}:this._database.transaction(()=>{let e=n.map(e=>{let n=this._readUnit(e);if(!n||n.deletedStatus===`hard`&&!t.hardDelete)throw new u.CollabError(`UNIT_NOT_FOUND`,`Cannot delete a missing unit`);return{unitID:e,status:t.hardDelete?n.deletedStatus===`hard`?`already-hard-deleted`:`hard-deleted`:n.deletedStatus===null?`soft-deleted`:`already-soft-deleted`}}),r=Date.now();for(let t of e)t.status===`hard-deleted`?(this._deleteSnapshots.run(t.unitID),this._deleteChangesets.run(t.unitID),this._deleteSheetBlocks.run(t.unitID),this._markHardDeleted.run(r,t.unitID)):t.status===`soft-deleted`&&this._markSoftDeleted.run(r,t.unitID);return{units:e}}).immediate()}async recoverUnits(e,t){this._assertOpen();let{unitIDs:n}=t;return n.length===0?{units:[]}:this._database.transaction(()=>{let e=n.map(e=>{let t=this._readUnit(e);if(!t)throw new u.CollabError(`UNIT_NOT_FOUND`,`Cannot recover a missing unit`);if(t.deletedStatus===`hard`)throw new u.CollabError(`INVALID_REQUEST`,`A hard-deleted unit cannot be recovered`);return{unitID:e,status:t.deletedStatus===null?`already-active`:`recovered`}});for(let t of e)t.status===`recovered`&&this._markActive.run(t.unitID);return{units:e}}).immediate()}async dispose(){this._disposed||(this._disposed=!0,this._database.close())}_initializeSchema(){this._database.transaction(()=>{this._database.exec(`
100
+ CREATE TABLE IF NOT EXISTS collaboration_schema_versions (
101
+ component TEXT PRIMARY KEY,
102
+ version INTEGER NOT NULL CHECK (version >= 1)
103
+ );
104
+ `);let e=this._readSchemaVersion();if(e!==3){if(e!==void 0)throw y(e);this._createSchema()}}).immediate()}_readSchemaVersion(){return this._database.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = ?`).get(m)?.version}_createSchema(){this._database.exec(`
105
+ ${h}
106
+ INSERT INTO collaboration_schema_versions (component, version)
107
+ VALUES ('${m}', 3);
108
+ `)}_readUnit(e){return this._getUnit.get(e)}_requireActiveUnit(e){let t=this._readUnit(e);if(!t||t.deletedStatus!==null)throw new u.CollabError(`UNIT_NOT_FOUND`,`Unit is not active`);return t}_writeSnapshot(e,t,n,r){for(let t of r)this._upsertSheetBlock.run(e,t.id,t.payload);this._upsertSnapshot.run(e,t,n)}_assertOpen(){if(this._disposed)throw new u.CollabError(`INTERNAL_ERROR`,`SQLite Database Adapter is disposed`)}_encode(e){return this._encoder.encode(e)}_encodeBlocks(e){return e.map(e=>({id:e.id,payload:this._encode(e)}))}_decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return this._decoder.decode(t)}};function _({record:e,snapshot:t}){if(e.headRevision!==1||t.rev!==1||t.unitID!==e.unitID||t.type!==e.type)throw new u.CollabError(`INVALID_REQUEST`,`Initial record and snapshot must match at revision 1`);if(typeof e.creatorID!=`string`||e.creatorID.length===0||!Number.isSafeInteger(e.createdAt)||e.createdAt<0)throw new u.CollabError(`INVALID_REQUEST`,`Unit creation requires creatorID and createdAt in Unix milliseconds`)}function v(e){if(e!==void 0&&e<0)throw new u.CollabError(`INVALID_REQUEST`,`Snapshot revision cannot be negative`);return e}function y(e){return new u.CollabError(`INTERNAL_ERROR`,`Core schema version ${e} is not supported by this adapter (expected 3); ${e<3?`run migrateSQLiteCore first`:`upgrade the adapter`}`)}function b(e){return{unitID:e.unitID,type:e.type,headRevision:e.headRevision,creatorID:e.creatorID,createdAt:e.createdAt}}async function x(e,t){let n=new l.default(e,{fileMustExist:!0}),r=!1;try{n.exec(`PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON; BEGIN IMMEDIATE;`),r=!0,await t(n),n.exec(`COMMIT;`),r=!1}finally{try{r&&n.exec(`ROLLBACK;`)}finally{n.close()}}}function S(e,t,n){if(e.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = 'core'`).get()?.version!==t)throw new u.CollabError(`INVALID_REQUEST`,`${n} requires core schema version ${t}`)}function C(e,t,n){let r=e.prepare(`PRAGMA table_info(${t})`).all().map(e=>e.name);if(r.length===0||n.some(e=>!r.includes(e)))throw new u.CollabError(`INVALID_REQUEST`,`Table ${t} differs from the supported schema; refusing a potentially lossy migration`)}function w(e,t){if(e.prepare(`UPDATE collaboration_schema_versions SET version = ? WHERE component = 'core'`).run(t),e.prepare(`PRAGMA foreign_key_check`).all().length>0)throw new u.CollabError(`INVALID_REQUEST`,`Foreign key validation failed during core migration`)}function T(e,t,n=new Set){let r=t.map(()=>`?`).join(`, `);return e.prepare(`SELECT name, sql FROM sqlite_schema
109
+ WHERE tbl_name IN (${r}) AND type IN ('index', 'trigger') AND sql IS NOT NULL`).all(...t).filter(e=>!n.has(e.name))}function E(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function*D(e,t,n){let r=n.join(`, `),i=e.prepare(`SELECT * FROM ${t} ORDER BY ${r} LIMIT 100`),a=e.prepare(`SELECT * FROM ${t} WHERE (${r}) > (${n.map(()=>`?`).join(`, `)}) ORDER BY ${r} LIMIT 100`),o=i.all();for(;o.length>0;){yield*o;let e=n.map(e=>o[o.length-1][e]);o=[],o=a.all(...e)}}async function O(e){let t=Date.now();await x(e.filename,async n=>{if(S(n,1,`migrateSQLiteCoreV1ToV2`),C(n,`collaboration_units`,[`unit_id`,`type`,`head_revision`,`soft_deleted_at_ms`]),C(n,`collaboration_unit_tombstones`,[`unit_id`]),C(n,`collaboration_snapshots`,[`unit_id`]),C(n,`collaboration_changesets`,[`unit_id`,`revision`,`payload_json`]),C(n,`collaboration_sheet_blocks`,[`unit_id`]),n.prepare(`PRAGMA table_info(collaboration_units)`).all().length!==4)throw new u.CollabError(`INVALID_REQUEST`,`Core v1 Unit columns differ from the supported schema; refusing a potentially lossy migration`);let r=k(n),i=T(n,[`collaboration_units`]);n.exec(`CREATE TABLE collaboration_units_v2 (
110
+ unit_id TEXT PRIMARY KEY,
111
+ type INTEGER NOT NULL,
112
+ head_revision INTEGER NOT NULL CHECK (head_revision >= 1),
113
+ creator_id TEXT NOT NULL,
114
+ created_at_ms INTEGER NOT NULL,
115
+ soft_deleted_at_ms INTEGER
116
+ );`);let a=n.prepare(`INSERT INTO collaboration_units_v2 VALUES (?, ?, ?, ?, ?, ?)`);for(let i of D(n,`collaboration_units`,[`unit_id`])){let n=i.unit_id,o=e.resolveUnitCreation?void 0:r(n,1),s=e.resolveUnitCreation?await e.resolveUnitCreation(n):{creatorID:o?.user_id||`anonymous`,createdAt:E(o?.committed_at)?o.committed_at:t};if(!s||typeof s.creatorID!=`string`||s.creatorID.length===0||!E(s.createdAt))throw new u.CollabError(`INVALID_REQUEST`,`Missing or invalid creation facts for Unit ${n}`);a.run(n,i.type,i.head_revision,s.creatorID,s.createdAt,i.soft_deleted_at_ms)}n.exec(`DROP TABLE collaboration_units; ALTER TABLE collaboration_units_v2 RENAME TO collaboration_units;`);for(let e of i)n.exec(e.sql);let o=n.prepare(`PRAGMA table_info(collaboration_changesets)`).all();if(o.some(e=>e.name===`created_at_ms`))throw new u.CollabError(`INVALID_REQUEST`,`Unexpected changeset creation-time column in legacy schema`);let s=n.prepare(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = 'collaboration_changesets'`).get(),c=T(n,[`collaboration_changesets`]);n.exec(`CREATE TABLE collaboration_changesets_v2 (
117
+ created_at_ms INTEGER NOT NULL,
118
+ ${s.sql.slice(s.sql.indexOf(`(`)+1)}`);let l=o.map(e=>`"${e.name.replaceAll(`"`,`""`)}"`).join(`, `),d=n.prepare(`INSERT INTO collaboration_changesets_v2 (${l}, created_at_ms)
119
+ VALUES (${o.map(()=>`?`).join(`, `)}, ?)`);for(let i of D(n,`collaboration_changesets`,[`unit_id`,`revision`])){let n=i.unit_id,a=i.revision,s=JSON.parse(i.payload_json),c=typeof s.createTime==`number`?s.createTime*1e3:void 0,l=!e.resolveChangesetCreatedAt&&!E(c)?r(n,a)?.committed_at:void 0,f=e.resolveChangesetCreatedAt?await e.resolveChangesetCreatedAt(n,a):E(c)?c:E(l)?l:t;if(!E(f))throw new u.CollabError(`INVALID_REQUEST`,`Missing or invalid changeset time for Unit ${n} revision ${a}`);s.createTime=Math.floor(f/1e3),d.run(...o.map(e=>e.name===`payload_json`?JSON.stringify(s):i[e.name]),f)}n.exec(`DROP TABLE collaboration_changesets; ALTER TABLE collaboration_changesets_v2 RENAME TO collaboration_changesets;`);for(let e of c)n.exec(e.sql);w(n,2)})}function k(e){let t=e.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'collaboration_history_revisions'`).get()?e.prepare(`SELECT user_id, committed_at FROM collaboration_history_revisions WHERE unit_id = ? AND revision = ?`):void 0;return(e,n)=>t?.get(e,n)}var A=[`collaboration_units`,`collaboration_snapshots`,`collaboration_changesets`,`collaboration_sheet_blocks`],j=new Set([`collaboration_snapshots_nearest_revision`,`collaboration_changesets_revision_range`]),M=`__univerCollaborationBinary`;async function N(e){await x(e.filename,e=>{S(e,2,`migrateSQLiteCoreV2ToV3`),C(e,`collaboration_units`,[`unit_id`,`type`,`head_revision`,`creator_id`,`created_at_ms`,`soft_deleted_at_ms`]),C(e,`collaboration_unit_tombstones`,[`unit_id`,`purged_at`]),C(e,`collaboration_snapshots`,[`unit_id`,`revision`,`payload_json`]),C(e,`collaboration_changesets`,[`unit_id`,`revision`,`base_revision`,`sid`,`req_id`,`created_at_ms`,`payload_json`]),C(e,`collaboration_sheet_blocks`,[`unit_id`,`block_id`,`payload_json`]);let t=T(e,A,j);for(let t of A)e.exec(`ALTER TABLE ${t} RENAME TO ${t}_v2;`);e.exec(h),e.exec(`
120
+ INSERT INTO collaboration_units
121
+ (unit_id, type, head_revision, creator_id, created_at_ms, deleted_at_ms, deleted_status)
122
+ SELECT unit_id, type, head_revision, creator_id, created_at_ms, soft_deleted_at_ms,
123
+ CASE WHEN soft_deleted_at_ms IS NULL THEN NULL ELSE 'soft' END
124
+ FROM collaboration_units_v2;
125
+ `),e.exec(`
126
+ INSERT INTO collaboration_units
127
+ (unit_id, type, head_revision, creator_id, created_at_ms, deleted_at_ms, deleted_status)
128
+ SELECT unit_id, ${p.UniverType.UNIVER_SHEET}, 1, 'anonymous', purged_at, purged_at, 'hard'
129
+ FROM collaboration_unit_tombstones;
130
+ `);let n=new c.Encoder({ignoreUndefined:!0}),r=e=>{let t=n.encode(F(e));return f.Buffer.from(t.buffer,t.byteOffset,t.byteLength)};P(e,`collaboration_snapshots`,[`unit_id`,`revision`],r),P(e,`collaboration_changesets`,[`unit_id`,`revision`,`base_revision`,`sid`,`req_id`,`created_at_ms`],r),P(e,`collaboration_sheet_blocks`,[`unit_id`,`block_id`],r);for(let t of A)e.exec(`DROP TABLE ${t}_v2;`);e.exec(`DROP TABLE collaboration_unit_tombstones;`);for(let n of t)e.exec(n.sql);w(e,3)})}function P(e,t,n,r){let i=e.prepare(`INSERT INTO ${t} (${n.join(`, `)}, payload) VALUES (${n.map(()=>`?`).join(`, `)}, ?)`);for(let a of D(e,`${t}_v2`,n.slice(0,2)))i.run(...n.map(e=>a[e]),r(a.payload_json))}function F(e){return JSON.parse(e,(e,t)=>typeof t==`object`&&t&&Object.keys(t).length===1&&typeof t[M]==`string`?Uint8Array.from(f.Buffer.from(t[M],`base64`)):t)}var I=[O,N];async function L(e){let t=R(e.filename);if(t===3)return{from:t,to:t};if(t>3)throw new u.CollabError(`INVALID_REQUEST`,`Core schema version ${t} is newer than this package supports (3)`);let n=e.backupFilename??`${e.filename}.v${t}.backup`;z(e.filename,n);for(let n of I.slice(t-1))await n(e);return{from:t,to:3,backupFilename:n}}function R(e){let t=new l.default(e,{fileMustExist:!0});try{let e=t.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = 'core'`).get();if(!e||!Number.isInteger(e.version)||e.version<1)throw new u.CollabError(`INVALID_REQUEST`,`The database has no core schema version to migrate from`);return e.version}catch(e){throw e instanceof u.CollabError?e:new u.CollabError(`INVALID_REQUEST`,`The database has no core schema version to migrate from`)}finally{t.close()}}function z(e,t){if((0,d.existsSync)(t))throw new u.CollabError(`INVALID_REQUEST`,`Backup target already exists: ${t}`);let n=new l.default(e,{fileMustExist:!0});try{n.prepare(`VACUUM INTO ?`).run(t)}finally{n.close()}}exports.SQLiteDatabaseAdapter=g,exports.migrateSQLiteCore=L,exports.migrateSQLiteCoreV1ToV2=O,exports.migrateSQLiteCoreV2ToV3=N;
package/dist/index.d.ts CHANGED
@@ -1,50 +1,127 @@
1
- import { CommitChangesetInput, CommitChangesetResult, CreateUnitDatabaseInput, CreateUnitDatabaseResult, DatabaseContext, DeleteUnitsDatabaseInput, DeleteUnitsDatabaseResult, IDatabaseAdapter, RecoverUnitsDatabaseInput, RecoverUnitsDatabaseResult, SaveSnapshotInput, SnapshotInfo, UnitRecord } from "@univerjs-pro/collaboration-service";
1
+ import { CommitChangesetInput, CommitChangesetResult, CreateUnitDatabaseInput, CreateUnitDatabaseResult, DatabaseContext, DeleteUnitsDatabaseInput, DeleteUnitsDatabaseResult, IDatabaseAdapter, RecoverUnitsDatabaseInput, RecoverUnitsDatabaseResult, SaveSnapshotInput, SnapshotInfo, SubmitDatabaseContext, UnitRecord } from "@univerjs-pro/collaboration-service";
2
2
  import { IChangeset, ISheetBlock, ISnapshot } from "@univerjs/protocol";
3
3
 
4
4
  //#region src/sqlite-database-adapter.d.ts
5
5
  interface SQLiteDatabaseAdapterOptions {
6
+ /** SQLite filename or `:memory:`. The parent directory must already exist. */
6
7
  readonly filename: string;
8
+ /** How long SQLite waits for another writer before reporting SQLITE_BUSY. Defaults to 5000. */
7
9
  readonly busyTimeoutMs?: number;
8
10
  }
11
+ /**
12
+ * SQLite implementation of the collaboration persistence contract, built on the synchronous
13
+ * `libsql` API. Protocol objects are stored as MessagePack blobs.
14
+ *
15
+ * The constructor initializes an empty database and rejects a database whose core schema
16
+ * version differs from the one this adapter writes; migrations are always explicit.
17
+ */
9
18
  declare class SQLiteDatabaseAdapter implements IDatabaseAdapter {
10
19
  private readonly _database;
20
+ private readonly _encoder;
21
+ private readonly _decoder;
11
22
  private _disposed;
23
+ private readonly _getUnit;
24
+ private readonly _getSnapshot;
25
+ private readonly _getSnapshotAtRevision;
26
+ private readonly _getSnapshotInfo;
27
+ private readonly _getSnapshotInfoAtRevision;
28
+ private readonly _getChangesets;
29
+ private readonly _getChangesetsInRange;
30
+ private readonly _getSheetBlock;
31
+ private readonly _insertUnit;
32
+ private readonly _insertChangeset;
33
+ private readonly _updateHeadRevision;
34
+ private readonly _upsertSnapshot;
35
+ private readonly _upsertSheetBlock;
36
+ private readonly _deleteSnapshots;
37
+ private readonly _deleteChangesets;
38
+ private readonly _deleteSheetBlocks;
39
+ private readonly _markSoftDeleted;
40
+ private readonly _markHardDeleted;
41
+ private readonly _markActive;
12
42
  constructor(options: SQLiteDatabaseAdapterOptions);
13
- getUnit(_context: DatabaseContext, unitID: string): Promise<UnitRecord | null>;
14
- getSnapshot(_context: DatabaseContext, unitID: string, options?: {
43
+ getUnit(_ctx: DatabaseContext, unitID: string): Promise<UnitRecord | null>;
44
+ /** Reads the latest snapshot, optionally bounded by the specified revision. */
45
+ getSnapshot(_ctx: DatabaseContext, unitID: string, options?: {
15
46
  readonly revision?: number;
16
47
  }): Promise<ISnapshot | null>;
17
- getSnapshotInfo(_context: DatabaseContext, unitID: string, options?: {
48
+ /** Reads metadata with the same selection rules as getSnapshot, without decoding the payload. */
49
+ getSnapshotInfo(_ctx: DatabaseContext, unitID: string, options?: {
18
50
  readonly revision?: number;
19
51
  }): Promise<SnapshotInfo | null>;
20
- getChangesets(_context: DatabaseContext, unitID: string, range: {
52
+ /** Reads changesets in (from, to], ordered by revision. */
53
+ getChangesets(_ctx: DatabaseContext, unitID: string, range: {
21
54
  readonly from: number;
22
55
  readonly to?: number;
23
56
  }): Promise<readonly IChangeset[] | null>;
24
- createUnit(_context: DatabaseContext, input: CreateUnitDatabaseInput): Promise<CreateUnitDatabaseResult>;
25
- deleteUnits(_context: DatabaseContext, input: DeleteUnitsDatabaseInput): Promise<DeleteUnitsDatabaseResult>;
26
- recoverUnits(_context: DatabaseContext, input: RecoverUnitsDatabaseInput): Promise<RecoverUnitsDatabaseResult>;
27
- commitChangeset(_context: DatabaseContext, input: CommitChangesetInput): Promise<CommitChangesetResult>;
28
- saveSnapshot(_context: DatabaseContext, input: SaveSnapshotInput): Promise<void>;
29
- getSheetBlock(_context: DatabaseContext, unitID: string, blockID: string): Promise<ISheetBlock | null>;
57
+ getSheetBlock(_ctx: DatabaseContext, unitID: string, blockID: string): Promise<ISheetBlock | null>;
58
+ /** Atomically creates a Unit at revision 1 with its snapshot and blocks; an existing active Unit returns its record. */
59
+ createUnit(_ctx: DatabaseContext, input: CreateUnitDatabaseInput): Promise<CreateUnitDatabaseResult>;
60
+ /** Confirms the changeset when the stored head equals `revision - 1`; otherwise reports the actual head. */
61
+ commitChangeset(_ctx: SubmitDatabaseContext, input: CommitChangesetInput): Promise<CommitChangesetResult>;
62
+ /** Publishes a snapshot together with the blocks it references. */
63
+ saveSnapshot(_ctx: DatabaseContext, input: SaveSnapshotInput): Promise<void>;
64
+ /** Deletes the whole batch or fails it; hard deletion keeps the Unit row as a permanent marker. */
65
+ deleteUnits(_ctx: DatabaseContext, input: DeleteUnitsDatabaseInput): Promise<DeleteUnitsDatabaseResult>;
66
+ /** Recovers the whole batch or fails it; hard-deleted IDs cannot be recovered. */
67
+ recoverUnits(_ctx: DatabaseContext, input: RecoverUnitsDatabaseInput): Promise<RecoverUnitsDatabaseResult>;
30
68
  dispose(): Promise<void>;
31
69
  private _initializeSchema;
32
- private _getActiveUnitRow;
33
- private _getStoredUnitRow;
34
- private _hasTombstone;
35
- private _hasTable;
36
- private _hasAnyCoreTable;
37
- private _writeSheetBlocks;
38
- private _transaction;
70
+ private _readSchemaVersion;
71
+ private _createSchema;
72
+ private _readUnit;
73
+ private _requireActiveUnit;
74
+ private _writeSnapshot;
39
75
  private _assertOpen;
76
+ private _encode;
77
+ private _encodeBlocks;
78
+ private _decode;
40
79
  }
41
80
  //#endregion
42
81
  //#region src/migrations/v1-to-v2.d.ts
43
82
  interface SQLiteCoreV1ToV2MigrationOptions {
44
83
  readonly filename: string;
84
+ /** Override default History lookup and fallback for every Unit, including soft-deleted Units. */
45
85
  readonly resolveUnitCreation?: (unitID: string) => Pick<UnitRecord, "creatorID" | "createdAt"> | Promise<Pick<UnitRecord, "creatorID" | "createdAt">>;
86
+ /** Override default changeset time resolution; return Unix milliseconds. */
46
87
  readonly resolveChangesetCreatedAt?: (unitID: string, revision: number) => number | Promise<number>;
47
88
  }
89
+ /**
90
+ * Explicit, atomic migration from core schema v1 to v2. V2 adds the creator and creation time of
91
+ * every Unit and the commit time of every changeset. Stop writers before calling; the resolvers
92
+ * must not write to this database.
93
+ */
48
94
  declare function migrateSQLiteCoreV1ToV2(options: SQLiteCoreV1ToV2MigrationOptions): Promise<void>;
49
95
  //#endregion
50
- export { type SQLiteCoreV1ToV2MigrationOptions, SQLiteDatabaseAdapter, type SQLiteDatabaseAdapterOptions, migrateSQLiteCoreV1ToV2 };
96
+ //#region src/migrations/migrate.d.ts
97
+ interface SQLiteCoreMigrationOptions extends SQLiteCoreV1ToV2MigrationOptions {
98
+ /** Where the backup is written before any change. Defaults to `<filename>.v<from>.backup`. */
99
+ readonly backupFilename?: string;
100
+ }
101
+ interface SQLiteCoreMigrationResult {
102
+ /** Core schema version found in the file. */
103
+ readonly from: number;
104
+ /** Core schema version after the call; always the version this package writes. */
105
+ readonly to: number;
106
+ /** Backup written before migrating; undefined when the file already had the current version. */
107
+ readonly backupFilename?: string;
108
+ }
109
+ /**
110
+ * Brings a database to the core schema version this package writes. The file is backed up first,
111
+ * then every missing step runs in its own transaction. A failed step leaves the file at the last
112
+ * complete version, so the call can be repeated after the cause is fixed. Stop writers before calling.
113
+ */
114
+ declare function migrateSQLiteCore(options: SQLiteCoreMigrationOptions): Promise<SQLiteCoreMigrationResult>;
115
+ //#endregion
116
+ //#region src/migrations/v2-to-v3.d.ts
117
+ interface SQLiteCoreV2ToV3MigrationOptions {
118
+ readonly filename: string;
119
+ }
120
+ /**
121
+ * Explicit, atomic migration from core schema v2 to v3. V3 stores protocol objects as MessagePack
122
+ * blobs and keeps hard-deleted Units as marker rows in `collaboration_units` instead of a tombstone
123
+ * table. Stop writers before calling.
124
+ */
125
+ declare function migrateSQLiteCoreV2ToV3(options: SQLiteCoreV2ToV3MigrationOptions): Promise<void>;
126
+ //#endregion
127
+ export { type SQLiteCoreMigrationOptions, type SQLiteCoreMigrationResult, type SQLiteCoreV1ToV2MigrationOptions, type SQLiteCoreV2ToV3MigrationOptions, SQLiteDatabaseAdapter, type SQLiteDatabaseAdapterOptions, migrateSQLiteCore, migrateSQLiteCoreV1ToV2, migrateSQLiteCoreV2ToV3 };
package/dist/index.mjs CHANGED
@@ -1 +1,6 @@
1
- const _0x315494=_0x5dad;(function(_0x349f79,_0x486a05){const _0x4a0e2c=_0x5dad,_0x19d842=_0x349f79();while(!![]){try{const _0x3efee9=-parseInt(_0x4a0e2c(0x120))/0x1*(-parseInt(_0x4a0e2c(0x119))/0x2)+-parseInt(_0x4a0e2c(0x11d))/0x3+parseInt(_0x4a0e2c(0x11c))/0x4+-parseInt(_0x4a0e2c(0x11a))/0x5+parseInt(_0x4a0e2c(0x11b))/0x6+-parseInt(_0x4a0e2c(0x118))/0x7*(parseInt(_0x4a0e2c(0x11e))/0x8)+parseInt(_0x4a0e2c(0x117))/0x9;if(_0x3efee9===_0x486a05)break;else _0x19d842['push'](_0x19d842['shift']());}catch(_0x13166c){_0x19d842['push'](_0x19d842['shift']());}}}(_0x36aa,0x597ee));import _0x32031e from'./index.cjs';function _0x5dad(_0x20b476,_0x2eb83c){_0x20b476=_0x20b476-0x117;const _0x36aa17=_0x36aa();let _0x5dadd2=_0x36aa17[_0x20b476];return _0x5dadd2;}function _0x36aa(){const _0x2ec71f=['120561dcYRaL','47688kQIVjM','2739695nmZEkn','1318188soUXIQ','97420bTIJuy','248127rjDffB','24VDtDgm','SQLiteDatabaseAdapter','30lCCkWX','805662QslfSi'];_0x36aa=function(){return _0x2ec71f;};return _0x36aa();}const facadeExport0=_0x32031e[_0x315494(0x11f)],facadeExport1=_0x32031e['migrateSQLiteCoreV1ToV2'];export{facadeExport0 as SQLiteDatabaseAdapter,facadeExport1 as migrateSQLiteCoreV1ToV2};
1
+ import cjsModule from "./index.cjs";
2
+ const facadeExport0 = cjsModule["SQLiteDatabaseAdapter"];
3
+ const facadeExport1 = cjsModule["migrateSQLiteCore"];
4
+ const facadeExport2 = cjsModule["migrateSQLiteCoreV1ToV2"];
5
+ const facadeExport3 = cjsModule["migrateSQLiteCoreV2ToV3"];
6
+ export { facadeExport0 as SQLiteDatabaseAdapter, facadeExport1 as migrateSQLiteCore, facadeExport2 as migrateSQLiteCoreV1ToV2, facadeExport3 as migrateSQLiteCoreV2ToV3 };
package/package.json CHANGED
@@ -1,10 +1,17 @@
1
1
  {
2
2
  "name": "@univerjs-pro/collaboration-database-sqlite",
3
+ "description": "SQLite IDatabaseAdapter for Univer Collaboration built on libsql",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/dream-num/univer-collaboration-sdk-community.git",
7
+ "directory": "packages/collaboration-database-sqlite"
8
+ },
9
+ "license": "Apache-2.0",
3
10
  "type": "module",
4
11
  "engines": {
5
12
  "node": ">=22"
6
13
  },
7
- "version": "1.3.0",
14
+ "version": "1.4.0",
8
15
  "main": "./dist/index.cjs",
9
16
  "module": "./dist/index.mjs",
10
17
  "types": "./dist/index.d.ts",
@@ -19,8 +26,11 @@
19
26
  "dist"
20
27
  ],
21
28
  "dependencies": {
22
- "@univerjs-pro/collaboration-service": "1.3.0",
23
- "@univerjs/protocol": "1.3.0",
29
+ "@msgpack/msgpack": "^3.1.3",
24
30
  "libsql": "^0.5.29"
31
+ },
32
+ "peerDependencies": {
33
+ "@univerjs-pro/collaboration-service": "1.4.0",
34
+ "@univerjs/protocol": "1.4.0"
25
35
  }
26
36
  }