@geonosis/document 0.9.1 → 0.9.3

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 (91) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/core/actor.cjs +48 -0
  3. package/dist/core/actor.d.cts +3 -0
  4. package/dist/core/actor.d.ts +3 -0
  5. package/dist/core/actor.js +8 -0
  6. package/dist/core/body-version.cjs +75 -0
  7. package/dist/core/body-version.d.cts +25 -0
  8. package/dist/core/body-version.d.ts +25 -0
  9. package/dist/core/body-version.js +35 -0
  10. package/dist/core/canonical.cjs +55 -0
  11. package/dist/core/canonical.d.cts +5 -0
  12. package/dist/core/canonical.d.ts +5 -0
  13. package/dist/core/canonical.js +15 -0
  14. package/dist/core/document.cjs +136 -0
  15. package/dist/core/document.d.cts +137 -0
  16. package/dist/core/document.d.ts +137 -0
  17. package/dist/core/document.js +96 -0
  18. package/dist/core/entities.cjs +68 -0
  19. package/dist/core/entities.d.cts +42 -0
  20. package/dist/core/entities.d.ts +42 -0
  21. package/dist/core/entities.js +28 -0
  22. package/dist/core/naming.cjs +56 -0
  23. package/dist/core/naming.d.cts +17 -0
  24. package/dist/core/naming.d.ts +17 -0
  25. package/dist/core/naming.js +16 -0
  26. package/dist/core/numbering.cjs +41 -0
  27. package/dist/core/numbering.d.cts +12 -0
  28. package/dist/core/numbering.d.ts +12 -0
  29. package/dist/core/numbering.js +0 -0
  30. package/dist/core/ports.cjs +41 -0
  31. package/dist/core/ports.d.cts +29 -0
  32. package/dist/core/ports.d.ts +29 -0
  33. package/dist/core/ports.js +0 -0
  34. package/dist/core/schema.cjs +173 -0
  35. package/dist/core/schema.d.cts +33 -0
  36. package/dist/core/schema.d.ts +33 -0
  37. package/dist/{chunk-NA3DLROL.js → core/schema.js} +34 -72
  38. package/dist/core/status.cjs +47 -0
  39. package/dist/core/status.d.cts +8 -0
  40. package/dist/core/status.d.ts +8 -0
  41. package/dist/core/status.js +7 -0
  42. package/dist/index.cjs +70 -398
  43. package/dist/index.d.cts +11 -32
  44. package/dist/index.d.ts +11 -32
  45. package/dist/index.js +13 -25
  46. package/dist/store/ddl.cjs +209 -0
  47. package/dist/store/ddl.d.cts +56 -0
  48. package/dist/store/ddl.d.ts +56 -0
  49. package/dist/store/ddl.js +175 -0
  50. package/dist/store/hash.cjs +50 -0
  51. package/dist/store/hash.d.cts +2 -0
  52. package/dist/store/hash.d.ts +2 -0
  53. package/dist/store/hash.js +10 -0
  54. package/dist/store/store.cjs +606 -0
  55. package/dist/store/store.d.cts +169 -0
  56. package/dist/store/store.d.ts +169 -0
  57. package/dist/store/store.js +578 -0
  58. package/dist/store.cjs +51 -1358
  59. package/dist/store.d.cts +4 -277
  60. package/dist/store.d.ts +4 -277
  61. package/dist/store.js +17 -1114
  62. package/dist/surface/table.cjs +326 -0
  63. package/dist/surface/table.d.cts +70 -0
  64. package/dist/surface/table.d.ts +70 -0
  65. package/dist/surface/table.js +296 -0
  66. package/dist/workflows/document-workflows.cjs +314 -0
  67. package/dist/workflows/document-workflows.d.cts +112 -0
  68. package/dist/workflows/document-workflows.d.ts +112 -0
  69. package/dist/workflows/document-workflows.js +281 -0
  70. package/dist/workflows/effects.cjs +41 -0
  71. package/dist/workflows/effects.d.cts +68 -0
  72. package/dist/workflows/effects.d.ts +68 -0
  73. package/dist/workflows/effects.js +0 -0
  74. package/dist/workflows/ports.cjs +50 -0
  75. package/dist/workflows/ports.d.cts +72 -0
  76. package/dist/workflows/ports.d.ts +72 -0
  77. package/dist/workflows/ports.js +10 -0
  78. package/dist/workflows/refusals.cjs +80 -0
  79. package/dist/workflows/refusals.d.cts +59 -0
  80. package/dist/workflows/refusals.d.ts +59 -0
  81. package/dist/workflows/refusals.js +40 -0
  82. package/dist/workflows.cjs +52 -504
  83. package/dist/workflows.d.cts +4 -310
  84. package/dist/workflows.d.ts +4 -310
  85. package/dist/workflows.js +21 -368
  86. package/package.json +8 -8
  87. package/dist/chunk-A6ZU4QU3.js +0 -171
  88. package/dist/entities-DTNJMeVf.d.cts +0 -205
  89. package/dist/entities-DTNJMeVf.d.ts +0 -205
  90. package/dist/ports-C_OfflMQ.d.cts +0 -66
  91. package/dist/ports-C_OfflMQ.d.ts +0 -66
@@ -0,0 +1,606 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // src/store/store.ts
40
+ var exports_store = {};
41
+ __export(exports_store, {
42
+ documentStore: () => documentStore
43
+ });
44
+ module.exports = __toCommonJS(exports_store);
45
+ var import_db = require("@geonosis/db");
46
+ var import_actor = require("../core/actor.cjs");
47
+ var import_body_version = require("../core/body-version.cjs");
48
+ var import_canonical = require("../core/canonical.cjs");
49
+ var import_ddl = require("./ddl.cjs");
50
+ var import_hash = require("./hash.cjs");
51
+ var DEFAULT_VERSION_COLUMN = "version";
52
+ var UNDO_ACTOR = import_actor.systemActor("document.undo");
53
+ var nameOf = (value, fallback) => value === undefined ? fallback : typeof value === "string" ? value : value.name;
54
+ var readBody = (entity, entityName, ref, stored) => {
55
+ const migrated = import_body_version.migrateBody(entity, stored);
56
+ const result = entity.body["~standard"].validate(migrated);
57
+ if (result instanceof Promise) {
58
+ throw new Error(`${entityName} ${ref}: this entity's body schema validates asynchronously, and a stored body can only be read synchronously here`);
59
+ }
60
+ if (result.issues !== undefined) {
61
+ throw new Error(`${entityName} ${ref}'s stored body no longer satisfies its own schema after migration: ${result.issues.map((issue) => issue.message).join("; ")}`);
62
+ }
63
+ return result.value;
64
+ };
65
+ var headFrom = (found) => found === undefined ? undefined : {
66
+ body: found.body,
67
+ hash: found.hash,
68
+ lineage: Number(found.carried.lineage ?? 1),
69
+ retiredAt: found.retiredAt,
70
+ version: found.sequence
71
+ };
72
+ var documentStore = (options) => {
73
+ const table = options.table ?? import_ddl.DEFAULT_DOCUMENT_TABLE;
74
+ const revisionKindColumn = options.columns?.revisionKind ?? import_ddl.DEFAULT_REVISION_KIND_COLUMN;
75
+ const physical = import_ddl.physicalColumnsOf(options.columns);
76
+ const {
77
+ entity: _entity,
78
+ heads: _heads,
79
+ revisionKind: _revisionKind,
80
+ total: _total,
81
+ version,
82
+ ...entityColumns
83
+ } = options.columns ?? {};
84
+ const versionColumn = nameOf(version, DEFAULT_VERSION_COLUMN);
85
+ const entityColumn = physical.entity;
86
+ const { archive, registry, schema, seam } = options;
87
+ const tenantKey = seam.tenantKey;
88
+ const placed = schema === undefined ? {} : { schema };
89
+ const declared = import_ddl.documentTable({
90
+ ...options.columns === undefined ? {} : { columns: options.columns },
91
+ ...placed,
92
+ table
93
+ });
94
+ const revisionsTable = options.revisions === false ? undefined : options.revisions?.table ?? import_ddl.DEFAULT_REVISIONS_TABLE;
95
+ const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
96
+ const columnOf = (column) => column === "number" ? "number" : physical[column];
97
+ const physicalHeads = import_ddl.HEAD_FIELDS.map(columnOf);
98
+ const narrowed = (where) => Object.fromEntries(Object.entries(where ?? {}).map(([column, held]) => [
99
+ columnOf(column),
100
+ held
101
+ ]));
102
+ const revisions = revisionsTable === undefined ? undefined : import_db.defineLog({
103
+ columns: { tenant: physical.tenant },
104
+ extra: [{ column: revisionKindColumn, param: "kind" }],
105
+ hash: (row) => import_hash.hashOf({
106
+ actor: row.actor,
107
+ at: row.at,
108
+ body: row.body,
109
+ entity: row.entity,
110
+ kind: row.kind,
111
+ lineage: row.lineage,
112
+ prevHash: row.prevHash,
113
+ reason: row.reason,
114
+ ref: row.ref,
115
+ tenant: row.tenant,
116
+ version: row.sequence
117
+ }),
118
+ key: [
119
+ { column: entityColumn, param: "entity" },
120
+ { column: "ref", param: "ref" },
121
+ { column: "lineage", param: "lineage" }
122
+ ],
123
+ ...placed,
124
+ seam,
125
+ table: revisionsTable
126
+ });
127
+ const needsLog = () => {
128
+ if (revisions === undefined) {
129
+ throw new import_db.DbRefusal("this store has no log — `documentStore({ revisions: false })` opted out of the append-only record entirely, and the write model has no other door");
130
+ }
131
+ return revisions;
132
+ };
133
+ const readers = import_db.defineEntity({
134
+ columns: { ...entityColumns, version: versionColumn },
135
+ filterable: [...physicalHeads, entityColumn, physical.createdAt, physical.updatedAt],
136
+ item: (row) => row,
137
+ key: { column: "number", param: "ref" },
138
+ order: [{ column: "number" }],
139
+ seam,
140
+ sortable: [...physicalHeads, entityColumn, "number", physical.createdAt, physical.updatedAt],
141
+ table: declared
142
+ });
143
+ const entityStoreFor = (name) => {
144
+ const definition = registry.named(name);
145
+ const item = (row) => {
146
+ const body = readBody(definition, name, row.key, row.body);
147
+ const head = definition.headOf(body);
148
+ return registry.instance(name, {
149
+ ...head,
150
+ body,
151
+ createdAt: row.createdAt,
152
+ number: row.key,
153
+ updatedAt: row.updatedAt,
154
+ version: row.version ?? 1
155
+ });
156
+ };
157
+ const instanceFromRevision = (ref, row) => {
158
+ const body = readBody(definition, name, ref, row.body);
159
+ const head = definition.headOf(body);
160
+ return registry.instance(name, {
161
+ ...head,
162
+ body,
163
+ createdAt: row.at,
164
+ number: ref,
165
+ updatedAt: row.at,
166
+ version: row.sequence
167
+ });
168
+ };
169
+ const projection = import_db.projectionOf({
170
+ carried: ["lineage"],
171
+ columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
172
+ constants: { [entityColumn]: name },
173
+ filterable: physicalHeads,
174
+ item,
175
+ key: { column: "number", param: "ref" },
176
+ order: [{ column: "number" }],
177
+ ...placed,
178
+ seam,
179
+ sortable: [...physicalHeads, "number", physical.createdAt, physical.updatedAt],
180
+ table: declared
181
+ });
182
+ const list = (handle, params) => projection.list(handle, {
183
+ ...params,
184
+ ...params.filter === undefined ? {} : { filter: narrowed(params.filter) },
185
+ ...params.order === undefined ? {} : {
186
+ order: {
187
+ column: columnOf(params.order.column),
188
+ ...params.order.direction === undefined ? {} : { direction: params.order.direction }
189
+ }
190
+ }
191
+ });
192
+ const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
193
+ const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
194
+ const stream = (params, lineage) => ({
195
+ ...tenanted(params[tenantKey]),
196
+ entity: name,
197
+ lineage,
198
+ ref: params.ref
199
+ });
200
+ const headColumnsOf = (body) => Object.fromEntries(Object.entries(definition.headOf(body)).map(([key, held]) => [
201
+ columnOf(key),
202
+ held
203
+ ]));
204
+ const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
205
+ const append = async (tx, write) => {
206
+ const log = needsLog();
207
+ const params = {
208
+ ...tenanted(write.tenantId),
209
+ actor: write.actor,
210
+ body: write.body,
211
+ entity: name,
212
+ kind: write.kind,
213
+ lineage: write.lineage,
214
+ ref: write.ref,
215
+ ...write.reason === null ? {} : { reason: write.reason }
216
+ };
217
+ const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
218
+ return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
219
+ };
220
+ const project = async (tx, write) => projection.write(tx, {
221
+ ...tenanted(write.tenantId),
222
+ at: write.at,
223
+ body: write.body,
224
+ carried: { lineage: write.lineage },
225
+ derived: write.head,
226
+ hash: write.hash,
227
+ ref: write.ref,
228
+ retiredAt: write.retiredAt,
229
+ sequence: write.version
230
+ });
231
+ const commitTx = seam.scoped(async (tx, params) => {
232
+ const tenantId = params[tenantKey];
233
+ const prepared = definition.prepare(params.body);
234
+ const stamped = import_body_version.stampBody(definition, prepared);
235
+ const existing = await locked(tx, params);
236
+ if (existing !== undefined && existing.retiredAt !== null) {
237
+ throw new import_db.DbRefusal(`"${params.ref}" (${name}) is retired: commit refuses a retired document — succeed opens a new lineage for it`);
238
+ }
239
+ const changed = existing === undefined || JSON.stringify(import_canonical.canonicalOf(existing.body)) !== JSON.stringify(import_canonical.canonicalOf(stamped));
240
+ if (existing !== undefined && !changed) {
241
+ return {
242
+ committed: false,
243
+ lineage: existing.lineage,
244
+ ref: params.ref,
245
+ version: existing.version
246
+ };
247
+ }
248
+ const lineage = existing?.lineage ?? 1;
249
+ const reason = params.reason ?? null;
250
+ const appended = await append(tx, {
251
+ actor: params.actor,
252
+ body: stamped,
253
+ compensationOf: null,
254
+ kind: "committed",
255
+ lineage,
256
+ reason,
257
+ ref: params.ref,
258
+ tenantId
259
+ });
260
+ await project(tx, {
261
+ at: appended.at,
262
+ body: stamped,
263
+ hash: appended.hash,
264
+ head: headColumnsOf(prepared),
265
+ lineage,
266
+ ref: params.ref,
267
+ retiredAt: null,
268
+ tenantId,
269
+ version: appended.version
270
+ });
271
+ return {
272
+ archivable: {
273
+ actor: params.actor,
274
+ at: appended.at,
275
+ body: stamped,
276
+ prevHash: appended.prevHash,
277
+ reason
278
+ },
279
+ committed: true,
280
+ hash: appended.hash,
281
+ lineage,
282
+ previous: existing === undefined ? null : { hash: existing.hash, version: existing.version },
283
+ ref: params.ref,
284
+ version: appended.version
285
+ };
286
+ });
287
+ const commit = async (handle, params) => {
288
+ const { archivable, ...answer } = await commitTx(handle, params);
289
+ if (archive === undefined || !answer.committed || archivable === undefined)
290
+ return answer;
291
+ const key = `${params[tenantKey]}/${name}/${answer.lineage}/${answer.version}.json`;
292
+ const payload = {
293
+ actor: archivable.actor,
294
+ at: archivable.at,
295
+ body: archivable.body,
296
+ entity: name,
297
+ hash: answer.hash,
298
+ kind: "committed",
299
+ lineage: answer.lineage,
300
+ prevHash: archivable.prevHash,
301
+ ref: params.ref,
302
+ reason: archivable.reason,
303
+ tenant: params[tenantKey],
304
+ version: answer.version
305
+ };
306
+ try {
307
+ await archive.put(key, new TextEncoder().encode(JSON.stringify(payload)), {
308
+ hash: answer.hash,
309
+ immutable: true
310
+ });
311
+ return { ...answer, archived: true };
312
+ } catch {
313
+ return { ...answer, archived: false };
314
+ }
315
+ };
316
+ const retire = seam.scoped(async (tx, params) => {
317
+ const tenantId = params[tenantKey];
318
+ const existing = await locked(tx, params);
319
+ if (existing === undefined) {
320
+ throw new import_db.DbRefusal(`"${params.ref}" (${name}) has no document to retire`);
321
+ }
322
+ if (existing.retiredAt !== null) {
323
+ throw new import_db.DbRefusal(`"${params.ref}" (${name}) is already retired`);
324
+ }
325
+ const appended = await append(tx, {
326
+ actor: params.actor,
327
+ body: existing.body,
328
+ compensationOf: null,
329
+ kind: "retired",
330
+ lineage: existing.lineage,
331
+ reason: params.reason ?? null,
332
+ ref: params.ref,
333
+ tenantId
334
+ });
335
+ await project(tx, {
336
+ at: appended.at,
337
+ body: existing.body,
338
+ hash: appended.hash,
339
+ head: storedHead(params.ref, existing.body),
340
+ lineage: existing.lineage,
341
+ ref: params.ref,
342
+ retiredAt: appended.at,
343
+ tenantId,
344
+ version: appended.version
345
+ });
346
+ return {
347
+ hash: appended.hash,
348
+ lineage: existing.lineage,
349
+ ref: params.ref,
350
+ version: appended.version
351
+ };
352
+ });
353
+ const succeed = seam.scoped(async (tx, params) => {
354
+ const tenantId = params[tenantKey];
355
+ const existing = await locked(tx, params);
356
+ if (existing === undefined || existing.retiredAt === null) {
357
+ throw new import_db.DbRefusal(`"${params.ref}" (${name}) is not retired: succeed opens a new lineage only for a retired document — commit is the door for a live one`);
358
+ }
359
+ const prepared = definition.prepare(params.body);
360
+ const stamped = import_body_version.stampBody(definition, prepared);
361
+ const lineage = existing.lineage + 1;
362
+ const appended = await append(tx, {
363
+ actor: params.actor,
364
+ body: stamped,
365
+ compensationOf: null,
366
+ kind: "committed",
367
+ lineage,
368
+ reason: params.reason ?? null,
369
+ ref: params.ref,
370
+ tenantId
371
+ });
372
+ await project(tx, {
373
+ at: appended.at,
374
+ body: stamped,
375
+ hash: appended.hash,
376
+ head: headColumnsOf(prepared),
377
+ lineage,
378
+ ref: params.ref,
379
+ retiredAt: null,
380
+ tenantId,
381
+ version: appended.version
382
+ });
383
+ return {
384
+ committed: true,
385
+ hash: appended.hash,
386
+ lineage,
387
+ previous: null,
388
+ ref: params.ref,
389
+ version: appended.version
390
+ };
391
+ });
392
+ const reinstate = seam.scoped(async (tx, params) => {
393
+ const tenantId = params[tenantKey];
394
+ const existing = await locked(tx, params);
395
+ if (existing === undefined || existing.retiredAt === null) {
396
+ throw new import_db.DbRefusal(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
397
+ }
398
+ const appended = await append(tx, {
399
+ actor: params.actor,
400
+ body: existing.body,
401
+ compensationOf: null,
402
+ kind: "reinstated",
403
+ lineage: existing.lineage,
404
+ reason: params.reason ?? null,
405
+ ref: params.ref,
406
+ tenantId
407
+ });
408
+ await project(tx, {
409
+ at: appended.at,
410
+ body: existing.body,
411
+ hash: appended.hash,
412
+ head: storedHead(params.ref, existing.body),
413
+ lineage: existing.lineage,
414
+ ref: params.ref,
415
+ retiredAt: null,
416
+ tenantId,
417
+ version: appended.version
418
+ });
419
+ return {
420
+ hash: appended.hash,
421
+ lineage: existing.lineage,
422
+ ref: params.ref,
423
+ version: appended.version
424
+ };
425
+ });
426
+ const at = seam.scoped(async (tx, params) => {
427
+ const lineage = await currentLineageOf(tx, params);
428
+ const row = await needsLog().at(tx, {
429
+ ...stream(params, lineage),
430
+ sequence: params.version
431
+ });
432
+ return row === null ? null : instanceFromRevision(params.ref, row);
433
+ });
434
+ const asOf = seam.scoped(async (tx, params) => {
435
+ const lineage = await currentLineageOf(tx, params);
436
+ const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
437
+ return row === null ? null : instanceFromRevision(params.ref, row);
438
+ });
439
+ const history = seam.scoped(async (tx, params) => {
440
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
441
+ const rows = await needsLog().history(tx, stream(params, lineage));
442
+ return rows.map((row) => ({
443
+ actor: row.actor,
444
+ at: row.at,
445
+ body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
446
+ hash: row.hash,
447
+ kind: row.kind,
448
+ reason: row.reason,
449
+ version: row.sequence
450
+ }));
451
+ });
452
+ const verify = seam.scoped(async (tx, params) => {
453
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
454
+ return needsLog().verify(tx, stream(params, lineage));
455
+ });
456
+ const compensate = async (scoped, tenantId, output, kind, body, retired) => {
457
+ const appended = await append(scoped, {
458
+ actor: UNDO_ACTOR,
459
+ body,
460
+ compensationOf: output.version,
461
+ kind,
462
+ lineage: output.lineage,
463
+ reason: `undo of v${output.version}`,
464
+ ref: output.ref,
465
+ tenantId
466
+ });
467
+ await project(scoped, {
468
+ at: appended.at,
469
+ body,
470
+ hash: appended.hash,
471
+ head: storedHead(output.ref, body),
472
+ lineage: output.lineage,
473
+ ref: output.ref,
474
+ retiredAt: retired ? appended.at : null,
475
+ tenantId,
476
+ version: appended.version
477
+ });
478
+ };
479
+ const lockedForUndo = async (scoped, tenantId, output) => {
480
+ const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
481
+ if (existing === undefined) {
482
+ throw new import_db.DbRefusal(`"${output.ref}" (${name}) has nothing to undo — the row v${output.version} wrote is gone`);
483
+ }
484
+ return existing;
485
+ };
486
+ const undos = {
487
+ commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
488
+ if (!output.committed)
489
+ return;
490
+ const existing = await lockedForUndo(scoped, tenantId, output);
491
+ if (output.previous === null) {
492
+ await compensate(scoped, tenantId, output, "retired", existing.body, true);
493
+ return;
494
+ }
495
+ const prior = await needsLog().at(scoped, {
496
+ ...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
497
+ sequence: output.previous.version
498
+ });
499
+ if (prior === null) {
500
+ throw new import_db.DbRefusal(`"${output.ref}" (${name}) version ${output.previous.version} is gone — cannot undo v${output.version} without it`);
501
+ }
502
+ await compensate(scoped, tenantId, output, "committed", prior.body, false);
503
+ }),
504
+ retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
505
+ const existing = await lockedForUndo(scoped, tenantId, output);
506
+ await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
507
+ })
508
+ };
509
+ const restore = async (tx, row, createdAt) => {
510
+ const ref = String(row.ref);
511
+ await project(tx, {
512
+ at: createdAt,
513
+ body: row.body,
514
+ hash: row.hash,
515
+ head: storedHead(ref, row.body),
516
+ lineage: Number(row.lineage),
517
+ ref,
518
+ retiredAt: row.kind === "retired" ? row.at : null,
519
+ tenantId: row.tenant,
520
+ version: row.sequence
521
+ });
522
+ };
523
+ return {
524
+ door: {
525
+ asOf,
526
+ at,
527
+ commit,
528
+ get: projection.get,
529
+ history,
530
+ list,
531
+ listAll: projection.listAll,
532
+ reinstate,
533
+ retire,
534
+ succeed,
535
+ undos,
536
+ verify
537
+ },
538
+ restore
539
+ };
540
+ };
541
+ const built = registry.names.map((name) => [name, entityStoreFor(name)]);
542
+ const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
543
+ const restorers = Object.fromEntries(built.map(([name, one]) => [name, one.restore]));
544
+ const heads = seam.scoped(async (tx, params) => {
545
+ const { columns, entity, order, where } = params;
546
+ const rows = await readers.project(tx, {
547
+ ...tenanted(params[tenantKey]),
548
+ columns: columns.filter((column) => column !== "number").map(columnOf),
549
+ order: order.map((one) => ({
550
+ column: columnOf(one.column),
551
+ ...one.direction === undefined ? {} : { direction: one.direction }
552
+ })),
553
+ where: {
554
+ ...entity === undefined ? {} : { [entityColumn]: entity },
555
+ ...narrowed(where)
556
+ }
557
+ });
558
+ return rows.map((row) => Object.fromEntries(columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])));
559
+ });
560
+ const aggregate = seam.scoped((tx, params) => {
561
+ const { by, entities, entity, measures, where } = params;
562
+ return readers.aggregate(tx, {
563
+ ...tenanted(params[tenantKey]),
564
+ ...by === undefined ? {} : {
565
+ by: typeof by === "string" ? columnOf(by) : { bucket: by.bucket, of: columnOf(by.of) }
566
+ },
567
+ measures: measures.map((one) => one === "sum:total" ? `sum:${physical.total}` : one),
568
+ where: {
569
+ ...entity === undefined ? {} : { [entityColumn]: entity },
570
+ ...entities === undefined ? {} : { [entityColumn]: entities },
571
+ ...narrowed(where)
572
+ }
573
+ });
574
+ });
575
+ const rebuild = seam.scoped(async (tx, params) => {
576
+ const log = needsLog();
577
+ const tenant = tenanted(params[tenantKey]);
578
+ const latest = new Map;
579
+ for (const row of await log.latestPerStream(tx, tenant)) {
580
+ if (params.entity !== undefined && row.entity !== params.entity)
581
+ continue;
582
+ const address = `${String(row.entity)} ${String(row.ref)}`;
583
+ const held = latest.get(address);
584
+ if (held === undefined || Number(row.lineage) > Number(held.lineage)) {
585
+ latest.set(address, row);
586
+ }
587
+ }
588
+ let rows = 0;
589
+ for (const row of latest.values()) {
590
+ const restore = restorers[String(row.entity)];
591
+ if (restore === undefined)
592
+ continue;
593
+ const first = await log.at(tx, {
594
+ ...tenant,
595
+ entity: row.entity,
596
+ lineage: row.lineage,
597
+ ref: row.ref,
598
+ sequence: 1
599
+ });
600
+ await restore(tx, row, first?.at ?? row.at);
601
+ rows += 1;
602
+ }
603
+ return { rows };
604
+ });
605
+ return { ...rawEntities, aggregate, heads, rebuild };
606
+ };