@aiao/rxdb-plugin-history 0.0.0-stage → 0.0.26

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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +70 -2
  3. package/dist/HistoryManager.d.ts +79 -0
  4. package/dist/HistoryManager.d.ts.map +1 -0
  5. package/dist/VersionManager.d.ts +233 -0
  6. package/dist/VersionManager.d.ts.map +1 -0
  7. package/dist/create-branch.d.ts +29 -0
  8. package/dist/create-branch.d.ts.map +1 -0
  9. package/dist/detached-event-error.d.ts +28 -0
  10. package/dist/detached-event-error.d.ts.map +1 -0
  11. package/dist/find-switch-branch-step.d.ts +45 -0
  12. package/dist/find-switch-branch-step.d.ts.map +1 -0
  13. package/dist/history-filters.d.ts +78 -0
  14. package/dist/history-filters.d.ts.map +1 -0
  15. package/dist/history-item-builder.d.ts +25 -0
  16. package/dist/history-item-builder.d.ts.map +1 -0
  17. package/dist/history-scope-api.d.ts +41 -0
  18. package/dist/history-scope-api.d.ts.map +1 -0
  19. package/dist/history-undo-session.types.d.ts +32 -0
  20. package/dist/history-undo-session.types.d.ts.map +1 -0
  21. package/dist/index.d.ts +35 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +1480 -0
  24. package/dist/merge-branch.d.ts +22 -0
  25. package/dist/merge-branch.d.ts.map +1 -0
  26. package/dist/plugin.d.ts +58 -0
  27. package/dist/plugin.d.ts.map +1 -0
  28. package/dist/pullable-count.d.ts +37 -0
  29. package/dist/pullable-count.d.ts.map +1 -0
  30. package/dist/push-inflight.d.ts +60 -0
  31. package/dist/push-inflight.d.ts.map +1 -0
  32. package/dist/redo-stack.d.ts +56 -0
  33. package/dist/redo-stack.d.ts.map +1 -0
  34. package/dist/remove-branch.d.ts +16 -0
  35. package/dist/remove-branch.d.ts.map +1 -0
  36. package/dist/restore-entity.d.ts +15 -0
  37. package/dist/restore-entity.d.ts.map +1 -0
  38. package/dist/scope-selection.d.ts +55 -0
  39. package/dist/scope-selection.d.ts.map +1 -0
  40. package/dist/switch-branch-actions.d.ts +16 -0
  41. package/dist/switch-branch-actions.d.ts.map +1 -0
  42. package/dist/sync-history-bridge.d.ts +87 -0
  43. package/dist/sync-history-bridge.d.ts.map +1 -0
  44. package/dist/undo-redo-apply.d.ts +47 -0
  45. package/dist/undo-redo-apply.d.ts.map +1 -0
  46. package/dist/version-manager.utils.d.ts +30 -0
  47. package/dist/version-manager.utils.d.ts.map +1 -0
  48. package/package.json +57 -3
  49. package/src/HistoryManager.ts +770 -0
  50. package/src/VersionManager.ts +451 -0
  51. package/src/create-branch.ts +154 -0
  52. package/src/detached-event-error.ts +43 -0
  53. package/src/find-switch-branch-step.ts +277 -0
  54. package/src/history-filters.ts +157 -0
  55. package/src/history-item-builder.ts +101 -0
  56. package/src/history-scope-api.ts +189 -0
  57. package/src/history-undo-session.types.ts +37 -0
  58. package/src/index.ts +46 -0
  59. package/src/merge-branch.ts +153 -0
  60. package/src/plugin.ts +93 -0
  61. package/src/pullable-count.ts +67 -0
  62. package/src/push-inflight.ts +91 -0
  63. package/src/redo-stack.ts +79 -0
  64. package/src/remove-branch.ts +89 -0
  65. package/src/restore-entity.ts +97 -0
  66. package/src/scope-selection.ts +132 -0
  67. package/src/switch-branch-actions.ts +238 -0
  68. package/src/sync-history-bridge.ts +131 -0
  69. package/src/undo-redo-apply.ts +260 -0
  70. package/src/version-manager.utils.ts +43 -0
package/dist/index.js ADDED
@@ -0,0 +1,1480 @@
1
+ import { ENTITY_LOCAL_CREATE_EVENT as e, MergeBranchBeginEvent as t, MergeBranchCommitEvent as n, MergeBranchFailedEvent as r, REPOSITORY_SYNC_COMPLETE_EVENT as i, RxDBBranch as a, RxDBChange as o, RxDBError as s, RxDBPluginBase as c, RxDBSync as l, SwitchBranchBeginEvent as u, SwitchBranchCommitEvent as d, SwitchBranchRollbackEvent as f, TRANSACTION_BEGIN as p, TRANSACTION_COMMIT as m, TRANSACTION_ROLLBACK as h, buildPushableRepositoryRules as ee, getCurrentBranch as te, getEntityMetadata as g, getLocalSystemRepositories as ne, getRemoteSystemRepositories as re, getRxDBChangeKey as _, getRxDBEntityIdentityKey as v, isAdapterShutdownError as y, resolve_current_branch as ie } from "@aiao/rxdb";
2
+ import { BehaviorSubject as b, EMPTY as ae, Observable as x, ReplaySubject as oe, Subject as se, catchError as ce, combineLatest as S, filter as C, firstValueFrom as w, map as T, shareReplay as E, switchMap as D, takeUntil as O } from "rxjs";
3
+ import { isNil as k } from "@aiao/utils";
4
+ //#region src/create-branch.ts
5
+ var le = async (e, t, n) => {
6
+ let { branchRepository: r, adapter: i } = await e.getLocalRepositories();
7
+ if ((await r.find({
8
+ where: {
9
+ combinator: "and",
10
+ rules: [{
11
+ field: "id",
12
+ operator: "=",
13
+ value: t
14
+ }]
15
+ },
16
+ limit: 1
17
+ })).length) throw new s(`Branch id (${t}) already exists`);
18
+ if (e.rxdb.config.sync?.remote?.adapter) {
19
+ let { adapter: n } = await e.getRemoteRepositories();
20
+ if (n.branchExists && await n.branchExists(t)) throw new s(`Branch id (${t}) already exists on remote`);
21
+ }
22
+ let c = await i.transaction(async (r) => {
23
+ let i = r.getRepository(a), s = r.getRepository(o);
24
+ if ((await i.find({
25
+ where: {
26
+ combinator: "and",
27
+ rules: [{
28
+ field: "id",
29
+ operator: "=",
30
+ value: t
31
+ }]
32
+ },
33
+ limit: 1
34
+ })).length) return `Branch id (${t}) already exists`;
35
+ let c, l;
36
+ if (n) {
37
+ let e = (await s.find({
38
+ where: {
39
+ combinator: "and",
40
+ rules: [{
41
+ field: "id",
42
+ operator: "=",
43
+ value: n
44
+ }]
45
+ },
46
+ limit: 1
47
+ }))[0];
48
+ if (!e) return `Change ID (${n}) not found`;
49
+ l = e, c = (await i.find({
50
+ where: {
51
+ combinator: "and",
52
+ rules: [{
53
+ field: "id",
54
+ operator: "=",
55
+ value: e.branchId
56
+ }]
57
+ },
58
+ limit: 1
59
+ }))[0];
60
+ } else c = await ie(i, e.rxdb), l = await ue(s, c.id);
61
+ if (!c) return "Source branch not found";
62
+ let u = e.rxdb.entityManager.instantiate(a);
63
+ return u.id = t, u.activated = !1, u.local = !0, u.remote = !1, u.fromChangeId = l?.id ?? null, u.parentId = c.id, await i.create(u), u;
64
+ });
65
+ if (typeof c == "string") throw new s(c);
66
+ return c;
67
+ }, ue = async (e, t) => (await e.find({
68
+ where: {
69
+ combinator: "and",
70
+ rules: [t ? {
71
+ field: "branchId",
72
+ operator: "=",
73
+ value: t
74
+ } : {
75
+ field: "branch.activated",
76
+ operator: "=",
77
+ value: !0
78
+ }, {
79
+ field: "revertChangeId",
80
+ operator: "=",
81
+ value: null
82
+ }]
83
+ },
84
+ orderBy: [{
85
+ field: "id",
86
+ sort: "desc"
87
+ }],
88
+ limit: 1
89
+ }))[0], A = (e) => {
90
+ if (!e || typeof e != "object") return !1;
91
+ let t = "name" in e ? String(e.name) : "";
92
+ return ("errno" in e ? Number(e.errno) : void 0) === 44 || t === "AbortError" || y(e);
93
+ };
94
+ //#endregion
95
+ //#region src/history-item-builder.ts
96
+ function j(e) {
97
+ if (e.length === 1) {
98
+ let t = e[0];
99
+ return `${t.type === "INSERT" ? "创建" : t.type === "UPDATE" ? "更新" : "删除"} ${t.entity}`;
100
+ }
101
+ let t = {};
102
+ for (let n of e) {
103
+ let e = n.type.toLowerCase();
104
+ t[e] = (t[e] ?? 0) + 1;
105
+ }
106
+ let n = [];
107
+ return t.insert && n.push(`创建${t.insert}条`), t.update && n.push(`更新${t.update}条`), t.delete && n.push(`删除${t.delete}条`), `事务: ${n.join(", ")}`;
108
+ }
109
+ function M(e) {
110
+ let t = e[0], n = e.length, r = t.transactionId ?? null, i = t.createdAt, a = t.namespace, o = t.entity, s = r ? "TRANSACTION" : t.type, c = [
111
+ s,
112
+ v(t.entityId),
113
+ i.getTime()
114
+ ].join(":"), l = e.some((e) => k(e.revertChangeId) === !1), u = e.some((e) => k(e.redoInvalidatedAt) === !1);
115
+ return {
116
+ transactionId: r,
117
+ changeId: e.reduce((e, t) => t.id > e ? t.id : e, e[0].id),
118
+ fingerprint: c,
119
+ changes: e,
120
+ type: s,
121
+ count: n,
122
+ createdAt: i,
123
+ description: j(e),
124
+ namespace: a,
125
+ entity: o,
126
+ reverted: l,
127
+ redoInvalidated: u
128
+ };
129
+ }
130
+ function N(e) {
131
+ let t = [], n = [], r;
132
+ return e.forEach((e) => {
133
+ e.transactionId && e.transactionId === r ? n.push(e) : (r = e.transactionId, n.length &&= (t.push(M([...n])), 0), e.transactionId ? n.push(e) : t.push(M([e])));
134
+ }), n.length && t.push(M([...n])), t;
135
+ }
136
+ //#endregion
137
+ //#region src/history-filters.ts
138
+ var P = (e) => `${e.namespace}:${e.entity}`;
139
+ function F(e, t) {
140
+ let n = new Map(t);
141
+ for (let t of e) {
142
+ if (t.lastPushedChangeId === null) continue;
143
+ let e = P(t), r = n.get(e);
144
+ r !== void 0 && r >= t.lastPushedChangeId || n.set(e, t.lastPushedChangeId);
145
+ }
146
+ return n;
147
+ }
148
+ function I(e, t) {
149
+ return t.type === "database" ? e : e.map((e) => {
150
+ let n = e.changes.filter((e) => t.type === "repository" ? e.namespace === t.namespace && e.entity === t.entity : e.namespace === t.namespace && e.entity === t.entity && e.entityId === t.entityId);
151
+ return n.length === 0 ? null : {
152
+ ...e,
153
+ changes: n,
154
+ count: n.length,
155
+ description: j(n)
156
+ };
157
+ }).filter((e) => e !== null);
158
+ }
159
+ function L(e, t, n = 0, r = null) {
160
+ return e.filter((e) => !e.reverted && e.changes.every((e) => {
161
+ let i = e.remoteId == null, a = t.get(P(e)), o = a == null || e.id > a, s = e.id > n, c = r === null || e.createdAt.getTime() > r.getTime();
162
+ return i && o && s && c;
163
+ }));
164
+ }
165
+ function de(e) {
166
+ return e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}:${v(e.entityId)}`;
167
+ }
168
+ //#endregion
169
+ //#region src/history-scope-api.ts
170
+ function fe(e) {
171
+ if (!e) return { type: "database" };
172
+ if (Object.getPrototypeOf(e) === Object.prototype && "type" in e) return e;
173
+ let t = g(e), n = "id" in e ? e.id : void 0, r = typeof n == "string" || typeof n == "number" || typeof n == "bigint" ? n : void 0;
174
+ return r === void 0 ? {
175
+ type: "repository",
176
+ namespace: t.namespace,
177
+ entity: t.name
178
+ } : {
179
+ type: "entity",
180
+ namespace: t.namespace,
181
+ entity: t.name,
182
+ entityId: r
183
+ };
184
+ }
185
+ function pe(e, t) {
186
+ let n = fe(t), r = de(n), i = e.history_cache.get(r);
187
+ if (i) return i;
188
+ let a = () => {
189
+ let t = (e.history_ref_counts.get(r) || 0) - 1;
190
+ t <= 0 ? (e.history_cache.delete(r), e.history_ref_counts.delete(r)) : e.history_ref_counts.set(r, t);
191
+ }, o = () => {
192
+ let t = (e.history_ref_counts.get(r) || 0) + 1;
193
+ e.history_ref_counts.set(r, t), e.history_cache.set(r, h);
194
+ }, s = (e) => new x((t) => {
195
+ o();
196
+ let n = e.subscribe(t);
197
+ return () => {
198
+ n.unsubscribe(), a();
199
+ };
200
+ }), c = e.histories$.pipe(T((e) => I(e, n)), E({
201
+ bufferSize: 1,
202
+ refCount: !0
203
+ })), l = s(c), u = s(e.undoHistories$.pipe(T((e) => I(e, n)), E({
204
+ bufferSize: 1,
205
+ refCount: !0
206
+ }))), d = s(e.redoHistories$.pipe(T((e) => I(e, n)), E({
207
+ bufferSize: 1,
208
+ refCount: !0
209
+ }))), f = s(c.pipe(T((e) => e.length), E({
210
+ bufferSize: 1,
211
+ refCount: !0
212
+ }))), p = s(u.pipe(T((e) => e.length), E({
213
+ bufferSize: 1,
214
+ refCount: !0
215
+ }))), m = s(d.pipe(T((e) => e.length), E({
216
+ bufferSize: 1,
217
+ refCount: !0
218
+ }))), h = {
219
+ type: n.type,
220
+ histories$: l,
221
+ undoHistories$: u,
222
+ redoHistories$: d,
223
+ count$: f,
224
+ undoCount$: p,
225
+ redoCount$: m,
226
+ undo: (t = 1) => e.runSerialized(async () => {
227
+ let r = e.undoSession$.value;
228
+ if (r.state === "cleared") return;
229
+ let { histories: i, lastPushedMap: a } = await e.fetchLatestHistories(r.boundary);
230
+ if (!e.isUndoSessionCurrent(r)) return;
231
+ let o = L(i, a, r.boundary.changeId, r.boundary.createdAfter), s = e.selectWholeTransactions(o, n, t);
232
+ s.length !== 0 && await e.applyUndoRedoHistories("undo", s, r);
233
+ }),
234
+ redo: (t = 1) => e.runSerialized(async () => {
235
+ let r = await w(e.redoHistories$), i = e.selectWholeTransactions(r, n, t);
236
+ i.length !== 0 && await e.applyUndoRedoHistories("redo", i);
237
+ })
238
+ };
239
+ return h;
240
+ }
241
+ //#endregion
242
+ //#region src/history-undo-session.types.ts
243
+ var R = {
244
+ changeId: 0,
245
+ createdAfter: null
246
+ };
247
+ //#endregion
248
+ //#region src/pullable-count.ts
249
+ function z(e, t) {
250
+ return e?.repositoryFilter !== void 0 && e.repositoryFilter.length > 0 ? !1 : !t.hasMore && t.failures.length === 0;
251
+ }
252
+ function B(e, t) {
253
+ return t.complete && !t.concurrent ? 0 : Math.max(0, e - t.pulled);
254
+ }
255
+ //#endregion
256
+ //#region src/redo-stack.ts
257
+ var me = 1e3, he = class {
258
+ #e = new b([]);
259
+ get items$() {
260
+ return this.#e.asObservable();
261
+ }
262
+ get value() {
263
+ return this.#e.value;
264
+ }
265
+ push(e) {
266
+ let t = [...e, ...this.#e.value], n = t.length > 1e3 ? t.slice(0, me) : t;
267
+ this.#e.next(n);
268
+ }
269
+ remove(e) {
270
+ let t = new Set(e.map((e) => e.fingerprint)), n = this.#e.value, r = n.filter((e) => t.has(e.fingerprint));
271
+ return r.length === 0 || this.#e.next(n.filter((e) => !t.has(e.fingerprint))), r;
272
+ }
273
+ clear() {
274
+ this.#e.next([]);
275
+ }
276
+ };
277
+ //#endregion
278
+ //#region src/scope-selection.ts
279
+ function V(e, t) {
280
+ return t.type === "database" ? !0 : e.namespace !== t.namespace || e.entity !== t.entity ? !1 : t.type === "repository" || e.entityId === t.entityId;
281
+ }
282
+ function ge(e, t) {
283
+ return e.changes.some((e) => V(e, t));
284
+ }
285
+ function _e(e, t) {
286
+ return e.changes.every((e) => V(e, t));
287
+ }
288
+ function ve(e, t, n) {
289
+ let r = e.filter((e) => ge(e, t)).slice(0, Math.max(0, n)), i = [], a = [];
290
+ for (let e of r) _e(e, t) ? a.push(e) : i.push(e);
291
+ return {
292
+ crossScope: i,
293
+ selected: a
294
+ };
295
+ }
296
+ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}#${String(e.entityId)}`, be = (e, t) => {
297
+ let n = /* @__PURE__ */ new Set();
298
+ for (let r of e) for (let e of r.changes) V(e, t) || n.add(t.type === "entity" ? `${e.namespace}:${e.entity}#${String(e.entityId)}` : `${e.namespace}:${e.entity}`);
299
+ return [...n].join(", ");
300
+ }, H = class e extends s {
301
+ scope;
302
+ histories;
303
+ constructor(t, n) {
304
+ super(`Scoped history operation would split a transaction: scope ${ye(t)} also changes ${be(n, t)}. Use the database scope to apply the whole transaction.`), this.scope = t, this.histories = n, this.name = "RxDBCrossScopeTransactionError", Object.setPrototypeOf(this, e.prototype);
305
+ }
306
+ }, U = (e) => e.fromChangeId ?? 0, xe = (e) => {
307
+ let { branches: t, currentBranch: n, nextBranch: r } = e, i = e.currentChangeId ?? U(n), a = e.nextChangeId ?? U(r);
308
+ if (i === a) return [];
309
+ if (n.id === r.id) return [{
310
+ branch: n,
311
+ fromChangeId: i,
312
+ toChangeId: a
313
+ }];
314
+ let o = /* @__PURE__ */ new Map();
315
+ for (let e of t) o.set(e.id, e);
316
+ let c = (e) => {
317
+ let t = [e], n = /* @__PURE__ */ new Set([e.id]), r = e;
318
+ for (; r.parentId;) {
319
+ if (n.has(r.parentId)) throw new s(`Branch history is corrupt: cycle detected at branch '${r.id}' (parentId '${r.parentId}' already visited)`);
320
+ let e = o.get(r.parentId);
321
+ if (!e) throw new s(`Branch history is corrupt: branch '${r.id}' references missing parent '${r.parentId}'`);
322
+ n.add(e.id), t.push(e), r = e;
323
+ }
324
+ return t;
325
+ }, l = c(n), u = c(r), d = null, f = -1;
326
+ for (let e = 0; e < l.length; e++) if (u.findIndex((t) => t.id === l[e].id) !== -1) {
327
+ d = l[e], f = e;
328
+ break;
329
+ }
330
+ let p = [];
331
+ if (d) {
332
+ for (let e = 0; e < f; e++) {
333
+ let t = l[e], n = e === 0 ? i : U(l[e - 1]), r = U(t);
334
+ n !== r && p.push({
335
+ branch: t,
336
+ fromChangeId: n,
337
+ toChangeId: r
338
+ });
339
+ }
340
+ let e = u.findIndex((e) => e.id === d.id);
341
+ if (e === 0) {
342
+ let e = f === 0 ? i : U(l[f - 1]), t = a;
343
+ e !== t && p.push({
344
+ branch: d,
345
+ fromChangeId: e,
346
+ toChangeId: t
347
+ });
348
+ } else if (e > 0) {
349
+ let t = f === 0 ? i : U(l[f - 1]), n = U(u[e - 1]);
350
+ t !== n && p.push({
351
+ branch: d,
352
+ fromChangeId: t,
353
+ toChangeId: n
354
+ });
355
+ }
356
+ let t = u.slice(0, e).reverse();
357
+ for (let e = 0; e < t.length; e++) {
358
+ let n = t[e], r = U(n), i = e === t.length - 1 ? a : U(t[e + 1]);
359
+ r !== i && p.push({
360
+ branch: n,
361
+ fromChangeId: r,
362
+ toChangeId: i
363
+ });
364
+ }
365
+ } else {
366
+ for (let e = 0; e < l.length; e++) {
367
+ let t = l[e], n = e === 0 ? i : U(l[e - 1]), r = U(t);
368
+ n !== r && p.push({
369
+ branch: t,
370
+ fromChangeId: n,
371
+ toChangeId: r
372
+ });
373
+ }
374
+ let e = l[l.length - 1], t = U(e);
375
+ t !== 0 && p.push({
376
+ branch: e,
377
+ fromChangeId: t,
378
+ toChangeId: 0
379
+ });
380
+ let n = u[u.length - 1], r = u.length > 1 ? U(u[u.length - 2]) : a;
381
+ r !== 0 && p.push({
382
+ branch: n,
383
+ fromChangeId: 0,
384
+ toChangeId: r
385
+ });
386
+ let o = u.slice(0, u.length - 1).reverse();
387
+ for (let e = 0; e < o.length; e++) {
388
+ let t = o[e], n = U(t), r = e === o.length - 1 ? a : U(o[e + 1]);
389
+ n !== r && p.push({
390
+ branch: t,
391
+ fromChangeId: n,
392
+ toChangeId: r
393
+ });
394
+ }
395
+ }
396
+ return p;
397
+ }, Se = async (e, t) => {
398
+ let { branchRepository: n, changeRepository: r } = await e.getLocalRepositories(), i = (await n.find({
399
+ where: {
400
+ combinator: "and",
401
+ rules: [{
402
+ field: "activated",
403
+ operator: "=",
404
+ value: !0
405
+ }]
406
+ },
407
+ limit: 1
408
+ }))[0];
409
+ if (!i) throw new s("Current branch not found");
410
+ let a = await n.find({ where: {
411
+ combinator: "and",
412
+ rules: []
413
+ } }), o = a.find((e) => e.id === t);
414
+ if (!o) throw new s(`Branch (${t}) not found`);
415
+ if (i.id === o.id) throw new s("Cannot switch to the same branch");
416
+ let c = await G(r, i.id), l = await G(r, o.id), u = xe({
417
+ branches: a,
418
+ currentBranch: i,
419
+ currentChangeId: c ? c.id : null,
420
+ nextBranch: o,
421
+ nextChangeId: l ? l.id : null
422
+ }), d = {
423
+ deletes: /* @__PURE__ */ new Map(),
424
+ updates: /* @__PURE__ */ new Map(),
425
+ inserts: /* @__PURE__ */ new Map()
426
+ };
427
+ for (let e = 0; e < u.length; e++) {
428
+ let { branch: t, fromChangeId: n, toChangeId: i } = u[e], a = n < i, o = n > i, s = Math.min(n, i), c = Math.max(n, i), l = { where: {
429
+ combinator: "and",
430
+ rules: [
431
+ {
432
+ field: "branchId",
433
+ operator: "=",
434
+ value: t.id
435
+ },
436
+ {
437
+ field: "id",
438
+ operator: ">",
439
+ value: s
440
+ },
441
+ {
442
+ field: "id",
443
+ operator: "<=",
444
+ value: c
445
+ },
446
+ {
447
+ field: "revertChangeId",
448
+ operator: "=",
449
+ value: null
450
+ }
451
+ ]
452
+ } };
453
+ t.fromChangeId && s < t.fromChangeId && l.where.rules.push({
454
+ field: "id",
455
+ operator: ">",
456
+ value: t.fromChangeId
457
+ });
458
+ let f = await r.find(l);
459
+ o ? we(f, d) : a && Ce(f, d);
460
+ }
461
+ return d;
462
+ }, Ce = (e, t) => W(e, !0, t), we = (e, t) => W(e, !1, t), W = (e, t, n = {
463
+ deletes: /* @__PURE__ */ new Map(),
464
+ updates: /* @__PURE__ */ new Map(),
465
+ inserts: /* @__PURE__ */ new Map()
466
+ }) => {
467
+ if (t) {
468
+ let t = [...e].sort((e, t) => e.id - t.id);
469
+ for (let e of t) {
470
+ let t = _(e);
471
+ switch (e.type) {
472
+ case "INSERT":
473
+ n.inserts.set(t, {
474
+ patch: { ...e.patch },
475
+ inversePatch: null
476
+ });
477
+ break;
478
+ case "UPDATE":
479
+ {
480
+ let r = n.inserts.get(t) || n.updates.get(t);
481
+ r ? (r.patch && e.patch && Object.assign(r.patch, e.patch), r.inversePatch === null && e.inversePatch ? r.inversePatch = { ...e.inversePatch } : r.inversePatch && e.inversePatch && Object.assign(r.inversePatch, e.inversePatch)) : n.updates.set(t, {
482
+ patch: { ...e.patch },
483
+ inversePatch: { ...e.inversePatch }
484
+ });
485
+ }
486
+ break;
487
+ case "DELETE": n.deletes.set(t, {
488
+ patch: null,
489
+ inversePatch: { ...e.inversePatch }
490
+ }), n.inserts.delete(t), n.updates.delete(t);
491
+ }
492
+ }
493
+ } else {
494
+ let t = [...e].sort((e, t) => t.id - e.id);
495
+ for (let e of t) {
496
+ let t = _(e);
497
+ switch (e.type) {
498
+ case "INSERT":
499
+ n.deletes.set(t, {
500
+ patch: null,
501
+ inversePatch: { ...e.patch }
502
+ }), n.inserts.delete(t), n.updates.delete(t);
503
+ break;
504
+ case "UPDATE":
505
+ {
506
+ let r = n.inserts.get(t) || n.updates.get(t);
507
+ r ? (r.patch && e.inversePatch && Object.assign(r.patch, e.inversePatch), r.inversePatch && e.patch && Object.assign(r.inversePatch, e.patch)) : n.updates.set(t, {
508
+ patch: { ...e.inversePatch },
509
+ inversePatch: { ...e.patch }
510
+ });
511
+ }
512
+ break;
513
+ case "DELETE": n.inserts.set(t, {
514
+ patch: { ...e.inversePatch },
515
+ inversePatch: null
516
+ });
517
+ }
518
+ }
519
+ }
520
+ return n;
521
+ }, G = async (e, t) => (await e.find({
522
+ where: {
523
+ combinator: "and",
524
+ rules: [{
525
+ field: "branchId",
526
+ operator: "=",
527
+ value: t
528
+ }, {
529
+ field: "revertChangeId",
530
+ operator: "=",
531
+ value: null
532
+ }]
533
+ },
534
+ orderBy: [{
535
+ field: "id",
536
+ sort: "desc"
537
+ }],
538
+ limit: 1
539
+ }))[0], K = (e) => e.getRepository(l);
540
+ async function Te(e, t) {
541
+ let { changeRepository: n, branchRepository: r } = await e.rxdb.versionManager.getLocalRepositories(), i = await r.find({ where: {
542
+ combinator: "and",
543
+ rules: [{
544
+ field: "activated",
545
+ operator: "=",
546
+ value: !0
547
+ }]
548
+ } });
549
+ if (i.length === 0) return {
550
+ histories: [],
551
+ lastPushedMap: /* @__PURE__ */ new Map()
552
+ };
553
+ let a = i[0], o = F(await K(await w(e.rxdb.localAdapter$)).find({ where: {
554
+ combinator: "and",
555
+ rules: [{
556
+ field: "branchId",
557
+ operator: "=",
558
+ value: a.id
559
+ }]
560
+ } }), e.rxdb.versionManager.pushInFlight.snapshot()), s = [{
561
+ field: "branchId",
562
+ operator: "=",
563
+ value: a.id
564
+ }, {
565
+ field: "createdAt",
566
+ operator: ">=",
567
+ value: e.getFirstConnectedAt()
568
+ }];
569
+ return t.changeId > 0 && s.push({
570
+ field: "id",
571
+ operator: ">",
572
+ value: t.changeId
573
+ }), {
574
+ histories: N(await n.find({
575
+ where: {
576
+ combinator: "and",
577
+ rules: s
578
+ },
579
+ orderBy: [{
580
+ field: "id",
581
+ sort: "desc"
582
+ }]
583
+ })),
584
+ lastPushedMap: o
585
+ };
586
+ }
587
+ async function Ee(e, t, n, r) {
588
+ e.isUndoRedoInProgress = !0;
589
+ try {
590
+ let i = n.flatMap((e) => e.changes).sort((e, n) => t === "undo" ? n.id - e.id : e.id - n.id), a = W(i, t === "redo"), o = e.getNextRevertStateUpdatedAt(i);
591
+ if (t === "undo") {
592
+ let { adapter: t } = await e.rxdb.versionManager.getLocalRepositories(), n = await t.getRxDBChangeSequence(), r = /* @__PURE__ */ new Date();
593
+ i.forEach((e, t) => {
594
+ let i = `rxdb:RxDBChange:${e.id}`, s = a.updates.get(i) || {
595
+ patch: {},
596
+ inversePatch: null
597
+ };
598
+ a.updates.set(i, {
599
+ patch: {
600
+ ...s.patch,
601
+ revertChangeId: n + t + 1,
602
+ revertChangedAt: r,
603
+ updatedAt: o
604
+ },
605
+ inversePatch: s.inversePatch
606
+ });
607
+ }), a.updateRxDBChangeSequence = n + i.length, e.redoInvalidationFloor = n + i.length;
608
+ } else i.forEach((e) => {
609
+ let t = `rxdb:RxDBChange:${e.id}`, n = a.updates.get(t) || {
610
+ patch: {},
611
+ inversePatch: null
612
+ };
613
+ a.updates.set(t, {
614
+ patch: {
615
+ ...n.patch,
616
+ revertChangeId: null,
617
+ updatedAt: o
618
+ },
619
+ inversePatch: n.inversePatch
620
+ });
621
+ });
622
+ let { adapter: s } = await e.rxdb.versionManager.getLocalRepositories();
623
+ if (t === "undo" && (r === void 0 || !e.isUndoSessionCurrent(r))) return;
624
+ await s.switchBranch({ actions: a }), e.pushableCountTrigger$.next(Date.now()), e.setRevertStateWatermarks(i, t === "undo", o), t === "undo" ? e.pushToRedoStack(n) : e.removeFromRedoStack(n);
625
+ } finally {
626
+ e.isUndoRedoInProgress = !1;
627
+ }
628
+ }
629
+ async function De(e) {
630
+ let t = ++e.pushableGeneration, n = (n) => {
631
+ t === e.pushableGeneration && e.pushableCount$.next(n);
632
+ };
633
+ try {
634
+ if (!await w(e.rxdb.connected$)) {
635
+ n(0);
636
+ return;
637
+ }
638
+ let t = K(await w(e.rxdb.localAdapter$)), r = e.rxdb.entityManager.getRepository(o), i = await w(e.rxdb.entityManager.getRepository(a).findOne({ where: {
639
+ combinator: "and",
640
+ rules: [{
641
+ field: "activated",
642
+ operator: "=",
643
+ value: !0
644
+ }]
645
+ } }));
646
+ if (!i) {
647
+ n(0);
648
+ return;
649
+ }
650
+ let s = await t.find({ where: {
651
+ combinator: "and",
652
+ rules: [{
653
+ field: "branchId",
654
+ operator: "=",
655
+ value: i.id
656
+ }]
657
+ } }), c = ee(e.rxdb.config.entities, e.rxdb.config.sync, s);
658
+ if (c.length === 0) {
659
+ n(0);
660
+ return;
661
+ }
662
+ n(await w(r.count({ where: {
663
+ combinator: "and",
664
+ rules: [
665
+ {
666
+ field: "branchId",
667
+ operator: "=",
668
+ value: i.id
669
+ },
670
+ {
671
+ field: "revertChangeId",
672
+ operator: "=",
673
+ value: null
674
+ },
675
+ {
676
+ field: "remoteId",
677
+ operator: "=",
678
+ value: null
679
+ },
680
+ {
681
+ combinator: "or",
682
+ rules: c
683
+ }
684
+ ]
685
+ } })));
686
+ } catch (t) {
687
+ !e.destroyed && !y(t) && (console.error("[#updatePushableCount] error", t), e.errors$.next(t instanceof Error ? t : Error(String(t)))), n(0);
688
+ }
689
+ }
690
+ //#endregion
691
+ //#region src/HistoryManager.ts
692
+ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
693
+ rxdb;
694
+ #e = [];
695
+ #t = !1;
696
+ #n;
697
+ #r;
698
+ #i = new oe(1);
699
+ #a = Promise.resolve();
700
+ #o = new b(0);
701
+ #s = 0;
702
+ #c = new b(0);
703
+ #l = 0;
704
+ #u = new b(0);
705
+ #d = /* @__PURE__ */ new Map();
706
+ #f = new b(0);
707
+ #p = 0;
708
+ #m;
709
+ #h = null;
710
+ #g = /* @__PURE__ */ new Date();
711
+ #_ = /* @__PURE__ */ new Map();
712
+ #v = null;
713
+ #y = 0;
714
+ #b = null;
715
+ #x = new b({
716
+ generation: 0,
717
+ state: "active",
718
+ boundary: R
719
+ });
720
+ isUndoRedoInProgress = !1;
721
+ isInvalidatingRedo = !1;
722
+ syncDepth = 0;
723
+ redoStack = new he();
724
+ history_cache = /* @__PURE__ */ new Map();
725
+ history_ref_counts = /* @__PURE__ */ new Map();
726
+ histories$;
727
+ undoHistories$;
728
+ redoHistories$;
729
+ undoCount$;
730
+ redoCount$;
731
+ errors$ = new se();
732
+ pushableCount$;
733
+ pullableCount$;
734
+ count$;
735
+ get undoSessionGeneration() {
736
+ return this.#x.value.generation;
737
+ }
738
+ constructor(e) {
739
+ this.rxdb = e, this.#n = this.#R(), this.#r = this.#z();
740
+ let t = e.entityManager.getRepository(a), n = e.entityManager.getRepository(o), r = t.findOne({ where: {
741
+ combinator: "and",
742
+ rules: [{
743
+ field: "activated",
744
+ operator: "=",
745
+ value: !0
746
+ }]
747
+ } });
748
+ this.#e.push(r.pipe(O(this.#i)).subscribe({
749
+ next: (e) => this.#E(e?.id ?? null),
750
+ error: (e) => this.#T("undo session 分支跟随的活跃分支流已中断", e)
751
+ })), this.#m = S({
752
+ connected: this.rxdb.connected$,
753
+ branch: r
754
+ }).pipe(C(({ connected: e, branch: t }) => e && !!t), D(({ branch: e }) => {
755
+ let t = this.#M();
756
+ return n.findAll({
757
+ where: {
758
+ combinator: "and",
759
+ rules: [{
760
+ field: "branchId",
761
+ operator: "=",
762
+ value: e.id
763
+ }, {
764
+ field: "createdAt",
765
+ operator: ">=",
766
+ value: t
767
+ }]
768
+ },
769
+ orderBy: [{
770
+ field: "id",
771
+ sort: "desc"
772
+ }]
773
+ });
774
+ }), O(this.#i));
775
+ let s = this.#m.pipe(T((e) => N(e)), E({
776
+ bufferSize: 1,
777
+ refCount: !0
778
+ }));
779
+ this.histories$ = S([s, this.#f]).pipe(T(([e]) => this.#O(e)), E({
780
+ bufferSize: 1,
781
+ refCount: !0
782
+ })), this.count$ = this.histories$.pipe(T((e) => e.length), E({
783
+ bufferSize: 1,
784
+ refCount: !0
785
+ })), this.undoHistories$ = S({
786
+ histories: this.histories$,
787
+ undoSession: this.#x,
788
+ trigger: this.#u
789
+ }).pipe(D(async ({ histories: e, undoSession: t }) => {
790
+ if (t.state === "cleared") return [];
791
+ try {
792
+ let n = await w(this.rxdb.entityManager.getRepository(a).findOne({ where: {
793
+ combinator: "and",
794
+ rules: [{
795
+ field: "activated",
796
+ operator: "=",
797
+ value: !0
798
+ }]
799
+ } }));
800
+ return n ? L(e, F(await K(await w(this.rxdb.localAdapter$)).find({ where: {
801
+ combinator: "and",
802
+ rules: [{
803
+ field: "branchId",
804
+ operator: "=",
805
+ value: n.id
806
+ }]
807
+ } }), this.rxdb.versionManager.pushInFlight.snapshot()), t.boundary.changeId, t.boundary.createdAfter) : [];
808
+ } catch (e) {
809
+ let t = e instanceof Error ? e : Error(String(e));
810
+ return this.errors$.next(t), [];
811
+ }
812
+ }), E({
813
+ bufferSize: 1,
814
+ refCount: !0
815
+ })), this.redoHistories$ = this.redoStack.items$, this.undoCount$ = this.undoHistories$.pipe(T((e) => e.length), E({
816
+ bufferSize: 1,
817
+ refCount: !0
818
+ })), this.redoCount$ = this.redoHistories$.pipe(T((e) => e.length), E({
819
+ bufferSize: 1,
820
+ refCount: !0
821
+ })), this.pushableCount$ = this.#c.asObservable(), this.pullableCount$ = this.#o.asObservable();
822
+ let c = S({
823
+ connected: this.rxdb.connected$,
824
+ branch: r
825
+ }).pipe(C(({ connected: e, branch: t }) => e && !!t), D(({ branch: e }) => {
826
+ let t = [
827
+ {
828
+ field: "branchId",
829
+ operator: "=",
830
+ value: e.id
831
+ },
832
+ {
833
+ field: "revertChangeId",
834
+ operator: "=",
835
+ value: null
836
+ },
837
+ {
838
+ field: "remoteId",
839
+ operator: "=",
840
+ value: null
841
+ }
842
+ ];
843
+ return n.count({ where: {
844
+ combinator: "and",
845
+ rules: t
846
+ } }).pipe(ce((e) => (this.#T("pushableCount 的变更计数查询", e), ae)));
847
+ })).subscribe({
848
+ next: () => {
849
+ this.#L();
850
+ },
851
+ error: (e) => this.#T("pushableCount 重算的活跃分支流已中断", e)
852
+ });
853
+ this.#e.push(c), this.rxdb.addEventListener(i, this.#F), this.#L();
854
+ }
855
+ destroy() {
856
+ this.#t = !0, this.#i.next(), this.#i.complete();
857
+ for (let e of this.#e) e.unsubscribe();
858
+ this.#e.length = 0, this.rxdb.removeEventListener(i, this.#F), this.#d.clear(), this.errors$.complete();
859
+ }
860
+ incrementPullableCount(e) {
861
+ this.#s++;
862
+ let t = this.#o.value + e;
863
+ this.#o.next(t);
864
+ }
865
+ resetPullableCount() {
866
+ this.#s++, this.#o.next(0);
867
+ }
868
+ beginPullableSettlement() {
869
+ return this.#s;
870
+ }
871
+ reconcilePullableCount(e, t) {
872
+ let n = e === this.#s ? t : Math.max(this.#o.value, t);
873
+ this.#o.next(n);
874
+ }
875
+ settlePullableCount(e, t) {
876
+ this.#o.next(B(this.#o.value, {
877
+ complete: t.complete,
878
+ concurrent: e !== this.#s,
879
+ pulled: t.pulled
880
+ }));
881
+ }
882
+ pushToRedoStack(e) {
883
+ this.redoStack.push(e);
884
+ }
885
+ removeFromRedoStack(e) {
886
+ return this.redoStack.remove(e);
887
+ }
888
+ clearRedoStack() {
889
+ this.redoStack.clear();
890
+ }
891
+ setUndoBranch(e) {
892
+ this.#E(e);
893
+ }
894
+ clearUndoHistory() {
895
+ this.#w({
896
+ generation: this.#C(),
897
+ state: "cleared",
898
+ boundary: this.#x.value.boundary,
899
+ clearedAt: /* @__PURE__ */ new Date()
900
+ }), this.clearRedoStack();
901
+ }
902
+ clearAllUndoHistory() {
903
+ let e = /* @__PURE__ */ new Date(), t = (t) => ({
904
+ generation: this.#C(),
905
+ state: "cleared",
906
+ boundary: t.boundary,
907
+ clearedAt: e
908
+ });
909
+ for (let [e, n] of this.#_) this.#_.set(e, t(n));
910
+ this.#v = t(this.#v ?? {
911
+ generation: 0,
912
+ state: "active",
913
+ boundary: R
914
+ });
915
+ let n = this.#b === null ? void 0 : this.#_.get(this.#b);
916
+ this.#x.next(n ?? this.#v), this.clearRedoStack();
917
+ }
918
+ resetSyncCleared(e = [], t) {
919
+ let n = this.#x.value;
920
+ if (n.state === "active") return;
921
+ let r = e.filter((e) => Number.isSafeInteger(e) && e > 0);
922
+ if (t === void 0) {
923
+ if (r.length === 0) return;
924
+ let e = q(r);
925
+ this.#w({
926
+ generation: n.generation,
927
+ state: "active",
928
+ boundary: {
929
+ changeId: Math.max(n.boundary.changeId, e - 1),
930
+ createdAfter: n.boundary.createdAfter
931
+ }
932
+ });
933
+ return;
934
+ }
935
+ if (!(t.generation === null ? t.recordAt !== null && Number.isFinite(t.recordAt.getTime()) && t.recordAt.getTime() > n.clearedAt.getTime() : t.generation === n.generation)) return;
936
+ let i = r.length > 0 ? q(r) : null, a = i === null && (n.boundary.createdAfter === null || n.boundary.createdAfter.getTime() < n.clearedAt.getTime()) ? n.clearedAt : n.boundary.createdAfter;
937
+ this.#w({
938
+ generation: n.generation,
939
+ state: "active",
940
+ boundary: {
941
+ changeId: i === null ? n.boundary.changeId : Math.max(n.boundary.changeId, i - 1),
942
+ createdAfter: a
943
+ }
944
+ });
945
+ }
946
+ isExecutingUndoRedo() {
947
+ return this.isUndoRedoInProgress || this.isInvalidatingRedo || this.syncDepth > 0;
948
+ }
949
+ async syncing(e) {
950
+ this.syncDepth += 1;
951
+ try {
952
+ return await e();
953
+ } finally {
954
+ --this.syncDepth;
955
+ }
956
+ }
957
+ async invalidateRedoStack(e) {
958
+ return this.#j(async () => {
959
+ if (!(this.isUndoRedoInProgress || this.isInvalidatingRedo) && !(e?.length && e.every((e) => e <= this.#p))) {
960
+ this.isInvalidatingRedo = !0;
961
+ try {
962
+ let e = await w(this.redoHistories$);
963
+ if (e.length === 0) return;
964
+ let t = e.flatMap((e) => e.changes), n = /* @__PURE__ */ new Date(), r = W([], !1), { adapter: i } = await this.rxdb.versionManager.getLocalRepositories();
965
+ t.forEach((e) => {
966
+ let t = `rxdb:RxDBChange:${e.id}`;
967
+ r.updates.set(t, {
968
+ patch: { redoInvalidatedAt: n },
969
+ inversePatch: { redoInvalidatedAt: null }
970
+ });
971
+ }), await i.switchBranch({ actions: r }), this.clearRedoStack();
972
+ } catch (e) {
973
+ throw console.error("[HistoryManager] Failed to invalidate redo stack:", e), e;
974
+ } finally {
975
+ this.isInvalidatingRedo = !1;
976
+ }
977
+ }
978
+ });
979
+ }
980
+ history(e) {
981
+ return pe(this.#n, e);
982
+ }
983
+ #S(e, t, n) {
984
+ let { crossScope: r, selected: i } = ve(e, t, n);
985
+ if (r.length > 0) throw new H(t, r);
986
+ return i;
987
+ }
988
+ #C() {
989
+ return ++this.#y;
990
+ }
991
+ #w(e) {
992
+ this.#b !== null && this.#_.set(this.#b, e), this.#x.next(e);
993
+ }
994
+ #T(e, t) {
995
+ this.#t || y(t) || (console.error(`[HistoryManager] ${e}:`, t), this.errors$.next(t instanceof Error ? t : Error(String(t))));
996
+ }
997
+ #E(e) {
998
+ if (e === this.#b || (this.#b === null && e !== null && !this.#_.has(e) && this.#_.set(e, this.#x.value), this.#b = e, e === null)) return;
999
+ let t = this.#_.get(e) ?? this.#D();
1000
+ this.#_.set(e, t), this.#x.next(t);
1001
+ }
1002
+ #D() {
1003
+ let e = this.#C(), t = this.#v;
1004
+ return t === null ? {
1005
+ generation: e,
1006
+ state: "active",
1007
+ boundary: R
1008
+ } : {
1009
+ ...t,
1010
+ generation: e
1011
+ };
1012
+ }
1013
+ #O(e) {
1014
+ return e.map((e) => {
1015
+ let t = !1;
1016
+ for (let n of e.changes) {
1017
+ let e = {
1018
+ reverted: n.revertChangeId != null,
1019
+ updatedAt: n.updatedAt.getTime()
1020
+ }, r = this.#d.get(n.id), i = r && r.updatedAt >= e.updatedAt ? r : e;
1021
+ r && e.updatedAt > r.updatedAt && this.#d.set(n.id, e), t ||= i.reverted;
1022
+ }
1023
+ return t === e.reverted ? e : {
1024
+ ...e,
1025
+ reverted: t
1026
+ };
1027
+ });
1028
+ }
1029
+ #k(e) {
1030
+ let t = Date.now();
1031
+ for (let n of e) {
1032
+ let e = this.#d.get(n.id)?.updatedAt ?? 0;
1033
+ t = Math.max(t, n.updatedAt.getTime() + 1, e + 1);
1034
+ }
1035
+ return new Date(t);
1036
+ }
1037
+ #A(e, t, n) {
1038
+ for (let r of e) this.#d.set(r.id, {
1039
+ reverted: t,
1040
+ updatedAt: n.getTime()
1041
+ });
1042
+ this.#f.next(this.#f.value + 1);
1043
+ }
1044
+ #j(e) {
1045
+ let t = this.#a.then(e, e);
1046
+ return this.#a = t.catch(() => void 0), t;
1047
+ }
1048
+ #M() {
1049
+ return this.#h ||= this.rxdb.firstConnectedAt ?? this.#g, this.#h;
1050
+ }
1051
+ #N(e) {
1052
+ return this.#x.value === e;
1053
+ }
1054
+ async #P(e) {
1055
+ return Te(this.#r, e);
1056
+ }
1057
+ #F = () => {
1058
+ this.#L(), this.#u.next(Date.now());
1059
+ };
1060
+ async #I(e, t, n) {
1061
+ return Ee(this.#r, e, t, n);
1062
+ }
1063
+ async #L() {
1064
+ return De(this.#r);
1065
+ }
1066
+ #R() {
1067
+ let e = this;
1068
+ return {
1069
+ get history_cache() {
1070
+ return e.history_cache;
1071
+ },
1072
+ get history_ref_counts() {
1073
+ return e.history_ref_counts;
1074
+ },
1075
+ get histories$() {
1076
+ return e.histories$;
1077
+ },
1078
+ get undoHistories$() {
1079
+ return e.undoHistories$;
1080
+ },
1081
+ get redoHistories$() {
1082
+ return e.redoHistories$;
1083
+ },
1084
+ get undoSession$() {
1085
+ return e.#x;
1086
+ },
1087
+ runSerialized: (t) => e.#j(t),
1088
+ fetchLatestHistories: (t) => e.#P(t),
1089
+ isUndoSessionCurrent: (t) => e.#N(t),
1090
+ selectWholeTransactions: (t, n, r) => e.#S(t, n, r),
1091
+ applyUndoRedoHistories: (t, n, r) => e.#I(t, n, r)
1092
+ };
1093
+ }
1094
+ #z() {
1095
+ let e = this;
1096
+ return {
1097
+ get rxdb() {
1098
+ return e.rxdb;
1099
+ },
1100
+ get destroyed() {
1101
+ return e.#t;
1102
+ },
1103
+ get isUndoRedoInProgress() {
1104
+ return e.isUndoRedoInProgress;
1105
+ },
1106
+ set isUndoRedoInProgress(t) {
1107
+ e.isUndoRedoInProgress = t;
1108
+ },
1109
+ get redoInvalidationFloor() {
1110
+ return e.#p;
1111
+ },
1112
+ set redoInvalidationFloor(t) {
1113
+ e.#p = t;
1114
+ },
1115
+ get pushableGeneration() {
1116
+ return e.#l;
1117
+ },
1118
+ set pushableGeneration(t) {
1119
+ e.#l = t;
1120
+ },
1121
+ get pushableCount$() {
1122
+ return e.#c;
1123
+ },
1124
+ get pushableCountTrigger$() {
1125
+ return e.#u;
1126
+ },
1127
+ get errors$() {
1128
+ return e.errors$;
1129
+ },
1130
+ getFirstConnectedAt: () => e.#M(),
1131
+ isUndoSessionCurrent: (t) => e.#N(t),
1132
+ getNextRevertStateUpdatedAt: (t) => e.#k(t),
1133
+ setRevertStateWatermarks: (t, n, r) => e.#A(t, n, r),
1134
+ pushToRedoStack: (t) => e.pushToRedoStack(t),
1135
+ removeFromRedoStack: (t) => e.removeFromRedoStack(t)
1136
+ };
1137
+ }
1138
+ }, Y = async (e, t) => {
1139
+ let { adapter: n } = await e.getLocalRepositories();
1140
+ if (t === "main") throw new s("Cannot remove main branch");
1141
+ let r = await n.transaction(async (e) => {
1142
+ let n = e.getRepository(a), r = e.getRepository(o), i = (await n.find({
1143
+ where: {
1144
+ combinator: "and",
1145
+ rules: [{
1146
+ field: "id",
1147
+ operator: "=",
1148
+ value: t
1149
+ }]
1150
+ },
1151
+ limit: 1
1152
+ }))[0];
1153
+ if (!i) return `Branch '${t}' not found`;
1154
+ if (i.activated) return `Cannot remove active branch '${t}'. Switch to another branch first.`;
1155
+ if ((await n.find({
1156
+ where: {
1157
+ combinator: "and",
1158
+ rules: [{
1159
+ field: "parentId",
1160
+ operator: "=",
1161
+ value: t
1162
+ }, {
1163
+ field: "id",
1164
+ operator: "!=",
1165
+ value: t
1166
+ }]
1167
+ },
1168
+ limit: 1
1169
+ }))?.length) return `Cannot remove branch '${t}' because it has child branches`;
1170
+ let s = await r.find({ where: {
1171
+ combinator: "and",
1172
+ rules: [{
1173
+ field: "branchId",
1174
+ operator: "=",
1175
+ value: t
1176
+ }]
1177
+ } });
1178
+ await e.removeMany([...s, i]);
1179
+ });
1180
+ if (r) throw new s(r);
1181
+ }, Oe = async (e, t, n, r) => {
1182
+ let i = r?.strategy ?? "squash", a = r?.deleteSource ?? !1, { branchRepository: o, changeRepository: c, adapter: l } = await e.getLocalRepositories();
1183
+ if (t === n) throw new s(`Cannot merge branch '${t}' into itself`);
1184
+ let u = (await o.find({
1185
+ where: {
1186
+ combinator: "and",
1187
+ rules: [{
1188
+ field: "id",
1189
+ operator: "=",
1190
+ value: t
1191
+ }]
1192
+ },
1193
+ limit: 1
1194
+ }))[0];
1195
+ if (!u) throw new s(`Branch '${t}' not found`);
1196
+ let d = await c.find({
1197
+ where: {
1198
+ combinator: "and",
1199
+ rules: [
1200
+ {
1201
+ field: "branchId",
1202
+ operator: "=",
1203
+ value: t
1204
+ },
1205
+ {
1206
+ field: "revertChangeId",
1207
+ operator: "=",
1208
+ value: null
1209
+ },
1210
+ ...u.fromChangeId == null ? [] : [{
1211
+ field: "id",
1212
+ operator: ">",
1213
+ value: u.fromChangeId
1214
+ }]
1215
+ ]
1216
+ },
1217
+ orderBy: [{
1218
+ field: "id",
1219
+ sort: "asc"
1220
+ }]
1221
+ }), f = async () => {
1222
+ if (!a) return { deleted: !1 };
1223
+ try {
1224
+ return await Y(e, t), { deleted: !0 };
1225
+ } catch (e) {
1226
+ return {
1227
+ deleted: !1,
1228
+ error: e instanceof Error ? e : Error(String(e))
1229
+ };
1230
+ }
1231
+ }, p = (e, t) => ({
1232
+ merged: e,
1233
+ strategy: i,
1234
+ sourceDeleted: t.deleted,
1235
+ ...t.error ? { sourceDeleteError: t.error } : {}
1236
+ });
1237
+ if (d.length === 0) return p(0, await f());
1238
+ let m;
1239
+ if (i === "normal") await l.transaction(async (e) => {
1240
+ for (let t of d) {
1241
+ let n = {
1242
+ deletes: /* @__PURE__ */ new Map(),
1243
+ updates: /* @__PURE__ */ new Map(),
1244
+ inserts: /* @__PURE__ */ new Map()
1245
+ }, r = _(t);
1246
+ t.type === "INSERT" ? n.inserts.set(r, {
1247
+ patch: t.patch,
1248
+ inversePatch: null
1249
+ }) : t.type === "UPDATE" ? n.updates.set(r, {
1250
+ patch: t.patch,
1251
+ inversePatch: t.inversePatch
1252
+ }) : t.type === "DELETE" && n.deletes.set(r, {
1253
+ patch: null,
1254
+ inversePatch: t.inversePatch
1255
+ }), await e.mergeChanges(n, void 0, !1);
1256
+ }
1257
+ }), m = d.length;
1258
+ else {
1259
+ let e = W(d, !0), t = new Set(d.filter((e) => e.type === "INSERT").map((e) => _(e)));
1260
+ for (let n of t) e.deletes.has(n) && e.deletes.delete(n);
1261
+ if (m = e.inserts.size + e.updates.size + e.deletes.size, m === 0) return p(0, await f());
1262
+ await l.mergeChanges(e, void 0, !1);
1263
+ }
1264
+ return p(m, await f());
1265
+ }, X = class {
1266
+ #e = /* @__PURE__ */ new Map();
1267
+ #t = 0;
1268
+ session() {
1269
+ let e = ++this.#t, t = /* @__PURE__ */ new Map();
1270
+ return this.#e.set(e, t), {
1271
+ claim: (e, n) => {
1272
+ let r = t.get(e);
1273
+ r !== void 0 && r >= n || t.set(e, n);
1274
+ },
1275
+ release: () => {
1276
+ this.#e.delete(e);
1277
+ }
1278
+ };
1279
+ }
1280
+ snapshot() {
1281
+ let e = /* @__PURE__ */ new Map();
1282
+ for (let t of this.#e.values()) for (let [n, r] of t) {
1283
+ let t = e.get(n);
1284
+ t !== void 0 && t >= r || e.set(n, r);
1285
+ }
1286
+ return e;
1287
+ }
1288
+ };
1289
+ //#endregion
1290
+ //#region src/restore-entity.ts
1291
+ async function ke(e, t, n) {
1292
+ let { changeRepository: r, adapter: i } = await e.getLocalRepositories(), a = await r.find({
1293
+ where: {
1294
+ combinator: "and",
1295
+ rules: [{
1296
+ field: "id",
1297
+ operator: "=",
1298
+ value: Number(n.changeId)
1299
+ }]
1300
+ },
1301
+ limit: 1
1302
+ });
1303
+ if (a.length === 0) throw new s(`RxDBChange not found: ${n.changeId}`);
1304
+ let o = a[0];
1305
+ if (o.type !== "DELETE") throw new s(`Cannot restore from non-DELETE change (type=${o.type})`);
1306
+ if (!o.inversePatch) throw new s(`RxDBChange ${n.changeId} has no inversePatch`);
1307
+ let c = t.constructor, l = g(c), u = await e.getCurrentBranch();
1308
+ if (o.namespace !== l.namespace || o.entity !== l.name) throw new s(`RxDBChange ${n.changeId} belongs to ${o.namespace}:${o.entity}, not ${l.namespace}:${l.name}`);
1309
+ if (o.branchId != null && o.branchId !== u.id) throw new s(`RxDBChange ${n.changeId} belongs to branch '${o.branchId}', current branch is '${u.id}'`);
1310
+ let d = W([o], !1);
1311
+ await i.mergeChanges(d, void 0, !1);
1312
+ let f = await i.getRepository(c).find({
1313
+ where: {
1314
+ combinator: "and",
1315
+ rules: [{
1316
+ field: "id",
1317
+ operator: "=",
1318
+ value: o.entityId
1319
+ }]
1320
+ },
1321
+ limit: 1
1322
+ });
1323
+ if (!f[0]) throw new s(`Restore produced no row for ${l.namespace}:${l.name} id=${String(o.entityId)}`);
1324
+ return f[0];
1325
+ }
1326
+ //#endregion
1327
+ //#region src/sync-history-bridge.ts
1328
+ var Z = (e, t) => ({
1329
+ pushInFlight: t,
1330
+ syncing: (t) => e().syncing(t),
1331
+ clearUndoHistory: () => e().clearUndoHistory(),
1332
+ beginPullableSettlement: () => e().beginPullableSettlement(),
1333
+ settlePull: (t, n, r) => e().settlePullableCount(t, {
1334
+ complete: z(n, r),
1335
+ pulled: r.pulled
1336
+ }),
1337
+ settleAbortedPull: (t, n) => e().settlePullableCount(t, {
1338
+ complete: !1,
1339
+ pulled: n
1340
+ }),
1341
+ reconcilePullableCount: (t, n) => e().reconcilePullableCount(t, n),
1342
+ incrementPullableCount: (t) => e().incrementPullableCount(t)
1343
+ }), Q = (e) => typeof e == "number" && Number.isSafeInteger(e) && e > 0 ? e : null, Ae = (e) => {
1344
+ let t = Q(e.id);
1345
+ return t === null ? typeof e.patch != "object" || e.patch === null || !("id" in e.patch) ? null : Q(e.patch.id) : t;
1346
+ }, je = (e) => {
1347
+ let t = null;
1348
+ for (let n of e) n.recordAt instanceof Date && Number.isFinite(n.recordAt.getTime()) && (t === null || n.recordAt.getTime() < t.getTime()) && (t = n.recordAt);
1349
+ return t;
1350
+ }, Me = class {
1351
+ rxdb;
1352
+ #e = [];
1353
+ #t = 0;
1354
+ #n = null;
1355
+ #r = !1;
1356
+ #i = !1;
1357
+ historyManager;
1358
+ pushInFlight = new X();
1359
+ syncBridge = Z(() => this.historyManager, this.pushInFlight);
1360
+ get pushableCount$() {
1361
+ return this.historyManager.pushableCount$;
1362
+ }
1363
+ get pullableCount$() {
1364
+ return this.historyManager.pullableCount$;
1365
+ }
1366
+ constructor(e) {
1367
+ this.rxdb = e, this.historyManager = new J(this.rxdb);
1368
+ }
1369
+ init() {
1370
+ this.#i &&= (this.historyManager = new J(this.rxdb), !1);
1371
+ let t = () => {
1372
+ if (!this.#r) {
1373
+ this.#r = !0;
1374
+ let e = () => {
1375
+ if (this.#t > 1) {
1376
+ --this.#t;
1377
+ return;
1378
+ }
1379
+ this.#t = 0, this.#n = null;
1380
+ }, t = () => {
1381
+ this.#t = 0, this.#n = null;
1382
+ };
1383
+ this.rxdb.addEventListener(m, e), this.rxdb.addEventListener(h, t), this.#e.push(() => this.rxdb.removeEventListener(m, e), () => this.rxdb.removeEventListener(h, t));
1384
+ }
1385
+ this.#t === 0 && (this.#n = this.historyManager.undoSessionGeneration), this.#t += 1;
1386
+ };
1387
+ this.rxdb.addEventListener(p, t), this.#e.push(() => this.rxdb.removeEventListener(p, t));
1388
+ let n = (e) => {
1389
+ let t = e.entities?.filter((e) => e.namespace === "rxdb" && e.entity === "RxDBChange") ?? [];
1390
+ if (t.length > 0 && !this.historyManager.isExecutingUndoRedo()) {
1391
+ let e = t.flatMap((e) => {
1392
+ let t = Ae(e);
1393
+ return t === null ? [] : [t];
1394
+ });
1395
+ this.#a(this.historyManager.invalidateRedoStack(e), "invalidateRedoStack");
1396
+ let n = je(t);
1397
+ this.#n !== null || n !== null ? this.historyManager.resetSyncCleared(e, {
1398
+ generation: this.#n,
1399
+ recordAt: n
1400
+ }) : this.historyManager.resetSyncCleared(e);
1401
+ }
1402
+ };
1403
+ this.rxdb.addEventListener(e, n), this.#e.push(() => this.rxdb.removeEventListener(e, n));
1404
+ }
1405
+ destroy() {
1406
+ if (!this.#i) {
1407
+ this.#i = !0, this.historyManager.destroy();
1408
+ for (let e of this.#e) e();
1409
+ this.#e.length = 0, this.#t = 0, this.#n = null, this.#r = !1;
1410
+ }
1411
+ }
1412
+ resetSessionState() {
1413
+ this.historyManager.clearAllUndoHistory(), this.historyManager.resetPullableCount();
1414
+ }
1415
+ async createBranch(e, t) {
1416
+ return le(this, e, t);
1417
+ }
1418
+ async removeBranch(e) {
1419
+ return Y(this, e);
1420
+ }
1421
+ async switchBranch(e) {
1422
+ if ((await this.getCurrentBranch())?.id === e) return;
1423
+ let t = !1;
1424
+ try {
1425
+ this.rxdb.dispatchEvent(new u(e));
1426
+ let { adapter: n } = await this.getLocalRepositories(), r = await Se(this, e), i = await n.switchBranch({
1427
+ branchId: e,
1428
+ actions: r
1429
+ });
1430
+ return t = !0, this.historyManager.clearRedoStack(), this.historyManager.setUndoBranch(e), this.rxdb.dispatchEvent(new d(e)), i;
1431
+ } catch (n) {
1432
+ throw t || this.rxdb.dispatchEvent(new f(e)), n;
1433
+ }
1434
+ }
1435
+ async mergeBranch(e, i) {
1436
+ let a = await this.getCurrentBranch();
1437
+ if (!a) throw new s("No active branch found");
1438
+ let o = a.id;
1439
+ try {
1440
+ this.rxdb.dispatchEvent(new t(e, o));
1441
+ let r = await Oe(this, e, o, i);
1442
+ return r.merged > 0 && this.historyManager.clearUndoHistory(), this.rxdb.dispatchEvent(new n(e, o)), r;
1443
+ } catch (t) {
1444
+ throw this.rxdb.dispatchEvent(new r(e, o)), t;
1445
+ }
1446
+ }
1447
+ history(e) {
1448
+ return this.historyManager.history(e);
1449
+ }
1450
+ async restoreEntity(e, t) {
1451
+ return ke(this, e, t);
1452
+ }
1453
+ async getLocalRepositories() {
1454
+ return ne(this.rxdb);
1455
+ }
1456
+ async getRemoteRepositories() {
1457
+ return re(this.rxdb);
1458
+ }
1459
+ async getCurrentBranch() {
1460
+ return te(this.rxdb);
1461
+ }
1462
+ #a(e, t) {
1463
+ e.catch((e) => {
1464
+ A(e) || console.error(`[VersionManager] ${t} failed:`, e);
1465
+ });
1466
+ }
1467
+ }, $ = class extends c {
1468
+ lifecycle = "scoped";
1469
+ name = "history";
1470
+ install(e) {
1471
+ let t = new Me(this.rxdb);
1472
+ e.acquire(() => (Object.defineProperty(this.rxdb, "versionManager", {
1473
+ value: t,
1474
+ configurable: !0,
1475
+ enumerable: !0
1476
+ }), () => void Reflect.deleteProperty(this.rxdb, "versionManager")), "history:slot"), e.acquire(() => () => t.destroy(), "history:versionManager"), t.init(), e.acquire(() => this.rxdb.syncState.bindPushableCount(t.pushableCount$), "history:pushableCount");
1477
+ }
1478
+ }, Ne = (e) => new $(e);
1479
+ //#endregion
1480
+ export { X as PushInFlightRegistry, H as RxDBCrossScopeTransactionError, $ as RxDBPluginHistory, A as isIgnorableDetachedVersionEventError, Ne as rxDBPluginHistory };