@geonosis/document 0.1.1 → 0.3.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/dist/index.js CHANGED
@@ -27,35 +27,97 @@ var documentBodyVersioning = (definition) => ({
27
27
  });
28
28
 
29
29
  // src/core/document.ts
30
- import { z } from "zod";
31
- var calendarDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "a calendar date is `YYYY-MM-DD`, never prose").nullable();
32
- var decimalAmount = z.string().regex(/^-?\d+(?:\.\d+)?$/, "an amount is a decimal string, never a float").nullable();
33
- var documentHeadSchema = z.object({
34
- status: z.string().nullable(),
35
- issueDate: calendarDate,
36
- dueDate: calendarDate,
37
- counterparty: z.string().nullable(),
38
- externalRef: z.string().nullable(),
39
- revision: z.string().nullable(),
40
- total: decimalAmount
41
- });
42
- var documentRecordSchema = z.object({
43
- version: z.number().int().positive(),
44
- createdAt: z.number().int(),
45
- updatedAt: z.number().int()
46
- });
30
+ var fieldPatterns = {
31
+ calendarDate: /^\d{4}-\d{2}-\d{2}$/,
32
+ decimal: /^-?\d+(?:\.\d+)?$/
33
+ };
34
+ var FIELD_CHECKS = {
35
+ calendarDate: {
36
+ message: "a calendar date is `YYYY-MM-DD`, never prose",
37
+ test: (value) => typeof value === "string" && fieldPatterns.calendarDate.test(value)
38
+ },
39
+ decimal: {
40
+ message: "an amount is a decimal string, never a float",
41
+ test: (value) => typeof value === "string" && fieldPatterns.decimal.test(value)
42
+ },
43
+ int: {
44
+ message: "an integer",
45
+ test: (value) => typeof value === "number" && Number.isInteger(value)
46
+ },
47
+ positiveInt: {
48
+ message: "a positive integer",
49
+ test: (value) => typeof value === "number" && Number.isInteger(value) && value > 0
50
+ },
51
+ text: { message: "a string", test: (value) => typeof value === "string" }
52
+ };
53
+ var validatorOf = (fields, options) => {
54
+ const nullable2 = options?.nullable ?? false;
55
+ return {
56
+ "~standard": {
57
+ validate: (input) => {
58
+ if (input === null || typeof input !== "object") {
59
+ return { issues: [{ message: "expected an object" }] };
60
+ }
61
+ const record = input;
62
+ const issues = [];
63
+ const value = {};
64
+ for (const [key, kind] of Object.entries(fields)) {
65
+ const held = record[key];
66
+ value[key] = held;
67
+ if (nullable2 && held === null) continue;
68
+ if (!FIELD_CHECKS[kind].test(held)) {
69
+ issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
70
+ }
71
+ }
72
+ return issues.length > 0 ? { issues } : { value };
73
+ },
74
+ vendor: "geonosis-document",
75
+ version: 1
76
+ }
77
+ };
78
+ };
79
+ var parseWith = (schema, input) => {
80
+ const result = schema["~standard"].validate(input);
81
+ if (result instanceof Promise) {
82
+ throw new Error(
83
+ "Document.head and Document.record parse synchronously; an async Standard Schema cannot back them"
84
+ );
85
+ }
86
+ if (result.issues !== void 0) {
87
+ throw new Error(result.issues.map((issue) => issue.message).join("; "));
88
+ }
89
+ return result.value;
90
+ };
91
+ var headFields = {
92
+ status: "text",
93
+ issueDate: "calendarDate",
94
+ dueDate: "calendarDate",
95
+ counterparty: "text",
96
+ externalRef: "text",
97
+ revision: "text",
98
+ total: "decimal"
99
+ };
100
+ var recordFields = {
101
+ version: "positiveInt",
102
+ createdAt: "int",
103
+ updatedAt: "int"
104
+ };
105
+ var headValidator = validatorOf(headFields, { nullable: true });
106
+ var recordValidator = validatorOf(recordFields);
47
107
  var Document = {
48
- head: documentHeadSchema,
49
- record: documentRecordSchema,
108
+ head: headValidator,
109
+ headFields,
110
+ record: recordValidator,
111
+ recordFields,
50
112
  extend: (definition) => ({
51
113
  ...definition,
52
- headOf: (body) => documentHeadSchema.parse(definition.headOf(body)),
53
- is: (document) => document.entity === definition.name
114
+ headOf: (body) => parseWith(headValidator, definition.headOf(body)),
115
+ is: (document) => document.entity === definition.name,
116
+ view: definition.view ?? definition.body
54
117
  })
55
118
  };
56
119
 
57
120
  // src/core/entities.ts
58
- import { z as z2 } from "zod";
59
121
  var documentEntities = (map) => {
60
122
  for (const [key, entity] of Object.entries(map)) {
61
123
  if (entity.name !== key) {
@@ -65,21 +127,39 @@ var documentEntities = (map) => {
65
127
  }
66
128
  }
67
129
  const names = Object.keys(map);
68
- const nameSchema = z2.enum(names);
69
- const distinctBodies = [...new Set(Object.values(map).map((entity) => entity.body))];
70
- const bodySchema = distinctBodies.length === 1 ? distinctBodies[0] : z2.union(distinctBodies);
71
- const bodyDecoder = z2.compile(bodySchema);
130
+ const values = Object.values(map);
131
+ const fold = (pick) => values.map(pick);
132
+ const distinctBy = (pick) => [
133
+ ...new Set(fold(pick))
134
+ ];
72
135
  return {
136
+ bodies: distinctBy((entity) => entity.body),
137
+ cards: distinctBy((entity) => entity.card.schema),
73
138
  entities: map,
74
- names,
75
- nameSchema,
76
- bodySchema,
77
- bodyDecoder,
139
+ fold,
78
140
  instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
79
- named: (name) => map[name]
141
+ named: (name) => map[name],
142
+ names,
143
+ views: distinctBy((entity) => entity.view)
80
144
  };
81
145
  };
82
146
 
147
+ // src/core/actor.ts
148
+ var SYSTEM_PREFIX = "system:";
149
+ var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
150
+ var isSystemActor = (actor) => actor.startsWith(SYSTEM_PREFIX);
151
+
152
+ // src/core/hash.ts
153
+ import { createHash } from "crypto";
154
+ var canonicalOf = (input) => {
155
+ if (input === null || typeof input !== "object") return input;
156
+ if (Array.isArray(input)) return input.map(canonicalOf);
157
+ return Object.fromEntries(
158
+ Object.entries(input).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, held]) => [key, canonicalOf(held)])
159
+ );
160
+ };
161
+ var hashOf = (payload) => createHash("sha256").update(JSON.stringify(canonicalOf(payload))).digest("hex");
162
+
83
163
  // src/core/naming.ts
84
164
  var camelOf = (name) => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
85
165
  var documentIdentifiers = (name) => {
@@ -97,14 +177,1119 @@ var documentIdentifiers = (name) => {
97
177
  // src/core/status.ts
98
178
  var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
99
179
  var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
180
+
181
+ // src/surface/table.ts
182
+ var VENDOR = "geonosis-document-surface";
183
+ var isString = (value) => typeof value === "string";
184
+ var isNumber = (value) => typeof value === "number";
185
+ var scalar = (test, message) => ({
186
+ "~standard": {
187
+ validate: (input) => test(input) ? { value: input } : { issues: [{ message }] },
188
+ vendor: VENDOR,
189
+ version: 1
190
+ }
191
+ });
192
+ var stringSchema = scalar(isString, "expected a string");
193
+ var numberSchema = scalar(isNumber, "expected a number");
194
+ var booleanSchema = scalar(
195
+ (value) => typeof value === "boolean",
196
+ "expected a boolean"
197
+ );
198
+ var literalOf = (literal) => scalar(
199
+ (value) => value === literal,
200
+ `expected exactly ${JSON.stringify(literal)}`
201
+ );
202
+ var unknownSchema = {
203
+ "~standard": { validate: (input) => ({ value: input }), vendor: VENDOR, version: 1 }
204
+ };
205
+ var syncResult = (schema, input) => {
206
+ const result = schema["~standard"].validate(input);
207
+ if (result instanceof Promise) {
208
+ throw new Error(
209
+ "a document surface schema validates synchronously; an async Standard Schema cannot back a row"
210
+ );
211
+ }
212
+ return result;
213
+ };
214
+ var optional = (inner) => ({
215
+ "~standard": {
216
+ validate: (input) => input === void 0 ? { value: void 0 } : syncResult(inner, input),
217
+ vendor: VENDOR,
218
+ version: 1
219
+ }
220
+ });
221
+ var nullable = (inner) => ({
222
+ "~standard": {
223
+ validate: (input) => input === null ? { value: null } : syncResult(inner, input),
224
+ vendor: VENDOR,
225
+ version: 1
226
+ }
227
+ });
228
+ var arrayOf = (item) => ({
229
+ "~standard": {
230
+ validate: (input) => {
231
+ if (!Array.isArray(input)) return { issues: [{ message: "expected an array" }] };
232
+ const value = [];
233
+ const issues = [];
234
+ input.forEach((one, at) => {
235
+ const result = syncResult(item, one);
236
+ if (result.issues !== void 0) {
237
+ issues.push(
238
+ ...result.issues.map((issue) => ({ ...issue, path: [at, ...issue.path ?? []] }))
239
+ );
240
+ } else {
241
+ value.push(result.value);
242
+ }
243
+ });
244
+ return issues.length > 0 ? { issues } : { value };
245
+ },
246
+ vendor: VENDOR,
247
+ version: 1
248
+ }
249
+ });
250
+ var merge = (schemas) => ({
251
+ "~standard": {
252
+ validate: (input) => {
253
+ let value = {};
254
+ const issues = [];
255
+ for (const schema of schemas) {
256
+ const result = syncResult(schema, input);
257
+ if (result.issues !== void 0) issues.push(...result.issues);
258
+ else value = { ...value, ...result.value };
259
+ }
260
+ return issues.length > 0 ? { issues } : { value };
261
+ },
262
+ vendor: VENDOR,
263
+ version: 1
264
+ }
265
+ });
266
+ var doorFor = (store, name) => {
267
+ const door = store[name];
268
+ if (door === void 0) {
269
+ throw new Error(
270
+ `"${name}" names no store this table's registry can find \u2014 the table and the store must share one registry`
271
+ );
272
+ }
273
+ return door;
274
+ };
275
+ var HEAD_COLUMNS = Object.keys(Document.headFields);
276
+ var rowsFor = (definition, store, schema) => {
277
+ const { name } = definition;
278
+ const door = doorFor(store, name);
279
+ const basePath = `/${definition.basePath}`;
280
+ const instanceSchema = merge([
281
+ Document.head,
282
+ Document.record,
283
+ schema.object({ body: definition.view, entity: schema.enum([name]), number: stringSchema })
284
+ ]);
285
+ const commitOutput = schema.union([
286
+ schema.object({
287
+ committed: literalOf(false),
288
+ lineage: numberSchema,
289
+ ref: stringSchema,
290
+ version: numberSchema
291
+ }),
292
+ schema.object({
293
+ archived: optional(booleanSchema),
294
+ committed: literalOf(true),
295
+ hash: stringSchema,
296
+ lineage: numberSchema,
297
+ previous: nullable(schema.object({ hash: stringSchema, version: numberSchema })),
298
+ ref: stringSchema,
299
+ version: numberSchema
300
+ })
301
+ ]);
302
+ const retireLikeOutput = schema.object({
303
+ hash: stringSchema,
304
+ lineage: numberSchema,
305
+ ref: stringSchema,
306
+ version: numberSchema
307
+ });
308
+ const verifyOutput = schema.union([
309
+ schema.object({ ok: literalOf(true), versions: numberSchema }),
310
+ schema.object({
311
+ brokenAt: numberSchema,
312
+ expected: stringSchema,
313
+ found: stringSchema,
314
+ ok: literalOf(false)
315
+ })
316
+ ]);
317
+ const historyOutput = arrayOf(
318
+ schema.object({
319
+ actor: stringSchema,
320
+ at: numberSchema,
321
+ body: unknownSchema,
322
+ hash: stringSchema,
323
+ kind: schema.enum(["committed", "retired", "reinstated"]),
324
+ reason: nullable(stringSchema),
325
+ version: numberSchema
326
+ })
327
+ );
328
+ const listInput = schema.object({
329
+ cursor: optional(nullable(stringSchema)),
330
+ filter: optional(
331
+ schema.object(
332
+ Object.fromEntries(HEAD_COLUMNS.map((column) => [column, optional(stringSchema)]))
333
+ )
334
+ ),
335
+ limit: optional(numberSchema),
336
+ order: optional(
337
+ schema.object({
338
+ column: schema.enum(HEAD_COLUMNS),
339
+ direction: optional(schema.enum(["asc", "desc"]))
340
+ })
341
+ )
342
+ });
343
+ const listOutput = schema.object({
344
+ items: arrayOf(merge([instanceSchema, schema.object({ card: definition.card.schema })])),
345
+ nextCursor: nullable(stringSchema)
346
+ });
347
+ const ackOutput = schema.object({ ref: stringSchema });
348
+ return [
349
+ {
350
+ call: (handle, params) => door.get(handle, params),
351
+ input: schema.object({ ref: stringSchema }),
352
+ name: `${name}.get`,
353
+ output: nullable(instanceSchema),
354
+ path: `${basePath}/:ref`,
355
+ scope: "org",
356
+ verb: "query"
357
+ },
358
+ {
359
+ call: async (handle, params) => {
360
+ const page = await door.list(handle, params);
361
+ return {
362
+ items: page.items.map((item) => ({
363
+ ...item,
364
+ card: definition.card.of(item, { counterpartyName: "" })
365
+ })),
366
+ nextCursor: page.nextCursor
367
+ };
368
+ },
369
+ input: listInput,
370
+ name: `${name}.list`,
371
+ output: listOutput,
372
+ path: basePath,
373
+ scope: "org",
374
+ verb: "query"
375
+ },
376
+ {
377
+ call: (handle, params) => door.history(handle, params),
378
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
379
+ name: `${name}.history`,
380
+ output: historyOutput,
381
+ path: `${basePath}/:ref/history`,
382
+ scope: "org",
383
+ verb: "query"
384
+ },
385
+ {
386
+ call: (handle, params) => door.verify(handle, params),
387
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
388
+ name: `${name}.verify`,
389
+ output: verifyOutput,
390
+ path: `${basePath}/:ref/verify`,
391
+ scope: "org",
392
+ verb: "query"
393
+ },
394
+ {
395
+ call: (handle, params) => door.commit(handle, params),
396
+ input: schema.object({
397
+ actor: stringSchema,
398
+ body: definition.body,
399
+ reason: optional(stringSchema),
400
+ ref: stringSchema
401
+ }),
402
+ name: `${name}.commit`,
403
+ output: commitOutput,
404
+ path: basePath,
405
+ scope: "org",
406
+ verb: "mutation"
407
+ },
408
+ {
409
+ call: (handle, params) => door.retire(handle, params),
410
+ input: schema.object({
411
+ actor: stringSchema,
412
+ reason: optional(stringSchema),
413
+ ref: stringSchema
414
+ }),
415
+ name: `${name}.retire`,
416
+ output: retireLikeOutput,
417
+ path: `${basePath}/:ref/retire`,
418
+ scope: "org",
419
+ verb: "mutation"
420
+ },
421
+ {
422
+ call: (handle, params) => door.reinstate(handle, params),
423
+ input: schema.object({
424
+ actor: stringSchema,
425
+ reason: optional(stringSchema),
426
+ ref: stringSchema
427
+ }),
428
+ name: `${name}.reinstate`,
429
+ output: retireLikeOutput,
430
+ path: `${basePath}/:ref/reinstate`,
431
+ scope: "org",
432
+ verb: "mutation"
433
+ },
434
+ {
435
+ call: async (handle, params) => {
436
+ const asked = params;
437
+ const current = await door.get(handle, params);
438
+ if (current === null) {
439
+ throw new Error(`"${asked.ref}" (${name}) has no document to set a status on`);
440
+ }
441
+ const from = definition.statusOf(current.body);
442
+ if (!canTransition(definition.statuses, from, asked.status)) {
443
+ throw new Error(
444
+ `"${name}" cannot move "${asked.ref}" from "${from}" to "${asked.status}": the status machine declares no such transition`
445
+ );
446
+ }
447
+ const body = definition.withStatus(
448
+ current.body,
449
+ asked.status,
450
+ (/* @__PURE__ */ new Date()).toISOString()
451
+ );
452
+ return door.commit(handle, { ...asked, body });
453
+ },
454
+ input: schema.object({
455
+ actor: stringSchema,
456
+ reason: optional(stringSchema),
457
+ ref: stringSchema,
458
+ status: schema.enum(definition.statuses.statuses)
459
+ }),
460
+ name: `${name}.setStatus`,
461
+ output: commitOutput,
462
+ path: `${basePath}/:ref/status`,
463
+ scope: "org",
464
+ verb: "mutation"
465
+ },
466
+ {
467
+ call: { pending: "T3", workflow: `${name}.create` },
468
+ input: schema.object({ draft: definition.draft }),
469
+ name: `${name}.create`,
470
+ output: commitOutput,
471
+ path: basePath,
472
+ scope: "org",
473
+ verb: "mutation"
474
+ },
475
+ {
476
+ call: { pending: "T3", workflow: `${name}.send` },
477
+ input: schema.object({ ref: stringSchema }),
478
+ name: `${name}.send`,
479
+ output: ackOutput,
480
+ path: `${basePath}/:ref/send`,
481
+ scope: "org",
482
+ verb: "mutation"
483
+ },
484
+ {
485
+ call: { pending: "T3", workflow: `${name}.duplicate` },
486
+ input: schema.object({ ref: stringSchema }),
487
+ name: `${name}.duplicate`,
488
+ output: commitOutput,
489
+ path: `${basePath}/:ref/duplicate`,
490
+ scope: "org",
491
+ verb: "mutation"
492
+ },
493
+ {
494
+ call: { pending: "T3", workflow: `${name}.runStarted` },
495
+ input: schema.object({ ref: stringSchema }),
496
+ name: `${name}.runStarted`,
497
+ output: ackOutput,
498
+ path: `${basePath}/:ref/run-started`,
499
+ scope: "org",
500
+ verb: "mutation"
501
+ }
502
+ ];
503
+ };
504
+ var documentSurface = (options) => {
505
+ const { registry, schema, store } = options;
506
+ const headsColumns = [...HEAD_COLUMNS, "entity", "number"];
507
+ const headsInput = schema.object({
508
+ columns: arrayOf(schema.enum(headsColumns)),
509
+ entity: optional(schema.union([stringSchema, arrayOf(stringSchema)])),
510
+ order: arrayOf(
511
+ schema.object({
512
+ column: schema.enum(headsColumns),
513
+ direction: optional(schema.enum(["asc", "desc"]))
514
+ })
515
+ ),
516
+ where: optional(
517
+ schema.object({ createdAt: optional(arrayOf(numberSchema)), status: optional(stringSchema) })
518
+ )
519
+ });
520
+ const aggregateInput = schema.object({
521
+ by: optional(unknownSchema),
522
+ entities: optional(arrayOf(stringSchema)),
523
+ entity: optional(stringSchema),
524
+ measures: arrayOf(schema.enum(["count", "sum:total"])),
525
+ where: optional(unknownSchema)
526
+ });
527
+ const aggregateOutput = arrayOf(
528
+ schema.object({
529
+ by: optional(stringSchema),
530
+ count: optional(numberSchema),
531
+ sum: optional(stringSchema)
532
+ })
533
+ );
534
+ const sharedOutput = schema.union(
535
+ registry.fold(
536
+ (entity) => schema.object({ entity: schema.enum([entity.name]), view: entity.view })
537
+ )
538
+ );
539
+ return [
540
+ ...registry.fold((entity) => rowsFor(entity, store, schema)).flat(),
541
+ {
542
+ call: (handle, params) => store.heads(handle, params),
543
+ input: headsInput,
544
+ name: "heads",
545
+ output: arrayOf(unknownSchema),
546
+ path: "/documents/heads",
547
+ scope: "org",
548
+ verb: "query"
549
+ },
550
+ {
551
+ call: (handle, params) => store.aggregate(handle, params),
552
+ input: aggregateInput,
553
+ name: "aggregate",
554
+ output: aggregateOutput,
555
+ path: "/documents/aggregate",
556
+ scope: "org",
557
+ verb: "query"
558
+ },
559
+ {
560
+ call: { pending: "T3", workflow: "document.shared" },
561
+ input: schema.object({ token: stringSchema }),
562
+ name: "shared",
563
+ output: sharedOutput,
564
+ path: "/documents/shared",
565
+ scope: "token",
566
+ verb: "query"
567
+ }
568
+ ];
569
+ };
570
+
571
+ // src/store/ddl.ts
572
+ import {
573
+ DbRefusal,
574
+ ENTITY_PLACEHOLDERS,
575
+ logMigrations,
576
+ projectionMigrations
577
+ } from "@geonosis/db";
578
+ var DEFAULT_DOCUMENT_TABLE = "documents";
579
+ var DEFAULT_ENTITY_COLUMN = "entity";
580
+ var DEFAULT_VERSION_COLUMN = "version";
581
+ var DEFAULT_TOTAL_COLUMN = "total";
582
+ var DEFAULT_TENANT_COLUMN = "tenant_id";
583
+ var DEFAULT_REVISIONS_TABLE = "document_revisions";
584
+ var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
585
+ var REVISION_KINDS = ["committed", "retired", "reinstated"];
586
+ var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
587
+ var appendOnlyTables = (options = {}) => {
588
+ if (options.revisions === false) return [];
589
+ return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
590
+ };
591
+ var quotedName = (name) => `"${name}"`;
592
+ var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
593
+ var documentRoleStatements = (appRole, options = {}) => {
594
+ if (typeof appRole !== "string" || appRole === "") {
595
+ throw new DbRefusal(
596
+ "documentRoleStatements needs an `appRole` \u2014 the name a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s"
597
+ );
598
+ }
599
+ const role = quotedName(appRole);
600
+ const on = (table) => options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
601
+ return appendOnlyTables(options).flatMap((table) => [
602
+ `revoke update, delete on ${on(table)} from ${role}`,
603
+ `grant select, insert on ${on(table)} to ${role}`
604
+ ]);
605
+ };
606
+ var DDL_TYPE_OF = { decimal: "numeric" };
607
+ var headIndexedColumns = (totalColumn) => Object.entries(headFields).map(([key, kind]) => {
608
+ const column = key === "total" ? totalColumn : key;
609
+ const type = DDL_TYPE_OF[kind];
610
+ return type === void 0 ? column : { column, type };
611
+ });
612
+ var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
613
+ var revisionsMigrations = (options, entityColumn, tenantColumn) => {
614
+ if (options.revisions === false) return [];
615
+ if (typeof options.appRole !== "string" || options.appRole === "") {
616
+ throw new DbRefusal(
617
+ "documentMigrations needs an `appRole` to render the log\u2019s wall \u2014 the role a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s. Pass it, or opt out of the log entirely with `revisions: false`"
618
+ );
619
+ }
620
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
621
+ const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
622
+ const [tableMigration, policies] = logMigrations({
623
+ appRole: options.appRole,
624
+ columns: { tenant: tenantColumn },
625
+ extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
626
+ key: [entityColumn, "ref", { column: "lineage", type: "integer" }],
627
+ ...options.schema === void 0 ? {} : { schema: options.schema },
628
+ settings: options.settings,
629
+ table
630
+ });
631
+ if (tableMigration === void 0 || policies === void 0) {
632
+ throw new Error("logMigrations answered with fewer than the two migrations a log renders");
633
+ }
634
+ return [
635
+ { ...tableMigration, name: `0003_${table}.sql` },
636
+ { ...policies, name: `0004_${table}_policies.sql` }
637
+ ];
638
+ };
639
+ var documentMigrations = (options) => {
640
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
641
+ const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN;
642
+ const totalColumn = nameOf(options.columns?.total, DEFAULT_TOTAL_COLUMN);
643
+ const tenantColumn = nameOf(options.columns?.tenant, DEFAULT_TENANT_COLUMN);
644
+ const {
645
+ entity: _entity,
646
+ revisionKind: _revisionKind,
647
+ total: _total,
648
+ version,
649
+ ...restColumns
650
+ } = options.columns ?? {};
651
+ const [tableMigration, ...rest] = projectionMigrations({
652
+ carried: [{ column: "lineage", type: "integer not null default 1" }],
653
+ columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
654
+ constants: { [entityColumn]: "" },
655
+ indexed: headIndexedColumns(totalColumn),
656
+ key: "number",
657
+ order: [{ column: "number" }],
658
+ ...options.schema === void 0 ? {} : { schema: options.schema },
659
+ settings: options.settings,
660
+ sortable: Object.keys(headFields).map((key) => key === "total" ? totalColumn : key),
661
+ table
662
+ });
663
+ if (tableMigration === void 0) {
664
+ throw new Error(
665
+ "projectionMigrations answered with no table migration to append the listing index to"
666
+ );
667
+ }
668
+ const listingIndex = `create index if not exists ${quotedName(`${table}_${entityColumn}_issueDate_idx`)} on ${quotedName(table)} (${quotedName(entityColumn)}, ${quotedName("issueDate")})`;
669
+ return [
670
+ { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
671
+ ...rest,
672
+ ...revisionsMigrations(options, entityColumn, tenantColumn)
673
+ ];
674
+ };
675
+
676
+ // src/store/store.ts
677
+ import {
678
+ DbRefusal as DbRefusal2,
679
+ defineEntity,
680
+ defineLog,
681
+ projectionOf
682
+ } from "@geonosis/db";
683
+ var DEFAULT_ENTITY_COLUMN2 = "entity";
684
+ var DEFAULT_VERSION_COLUMN2 = "version";
685
+ var DEFAULT_TOTAL_COLUMN2 = "total";
686
+ var DEFAULT_TENANT_COLUMN2 = "tenant_id";
687
+ var DEFAULT_CREATED_AT_COLUMN = "created_at";
688
+ var UNDO_ACTOR = systemActor("document.undo");
689
+ var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
690
+ var readBody = (entity, entityName, ref, stored) => {
691
+ const migrated = migrateBody(entity, stored);
692
+ const result = entity.body["~standard"].validate(migrated);
693
+ if (result instanceof Promise) {
694
+ throw new Error(
695
+ `${entityName} ${ref}: this entity's body schema validates asynchronously, and a stored body can only be read synchronously here`
696
+ );
697
+ }
698
+ if (result.issues !== void 0) {
699
+ throw new Error(
700
+ `${entityName} ${ref}'s stored body no longer satisfies its own schema after migration: ${result.issues.map((issue) => issue.message).join("; ")}`
701
+ );
702
+ }
703
+ return result.value;
704
+ };
705
+ var HEAD_COLUMNS2 = Object.keys(headFields);
706
+ var headFrom = (found) => found === void 0 ? void 0 : {
707
+ body: found.body,
708
+ hash: found.hash,
709
+ lineage: Number(found.carried.lineage ?? 1),
710
+ retiredAt: found.retiredAt,
711
+ version: found.sequence
712
+ };
713
+ var documentStore = (options) => {
714
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
715
+ const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN2;
716
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
717
+ const {
718
+ entity: _entity,
719
+ revisionKind: _revisionKind,
720
+ total,
721
+ version,
722
+ ...entityColumns
723
+ } = options.columns ?? {};
724
+ const versionColumn = nameOf2(version, DEFAULT_VERSION_COLUMN2);
725
+ const totalColumn = nameOf2(total, DEFAULT_TOTAL_COLUMN2);
726
+ const tenantColumn = nameOf2(entityColumns.tenant, DEFAULT_TENANT_COLUMN2);
727
+ const createdAtColumn = nameOf2(entityColumns.createdAt, DEFAULT_CREATED_AT_COLUMN);
728
+ const { archive, registry, schema, seam } = options;
729
+ const tenantKey = seam.tenantKey;
730
+ const placed = schema === void 0 ? {} : { schema };
731
+ const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
732
+ const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
733
+ const columnOf = (column) => column === "entity" ? entityColumn : column === "total" ? totalColumn : column;
734
+ const physicalHeads = HEAD_COLUMNS2.map(columnOf);
735
+ const revisions = revisionsTable === void 0 ? void 0 : defineLog({
736
+ columns: { tenant: tenantColumn },
737
+ extra: [{ column: revisionKindColumn, param: "kind" }],
738
+ hash: (row) => hashOf({
739
+ actor: row.actor,
740
+ at: row.at,
741
+ body: row.body,
742
+ entity: row.entity,
743
+ kind: row.kind,
744
+ lineage: row.lineage,
745
+ prevHash: row.prevHash,
746
+ reason: row.reason,
747
+ ref: row.ref,
748
+ tenant: row.tenant,
749
+ version: row.sequence
750
+ }),
751
+ key: [
752
+ { column: entityColumn, param: "entity" },
753
+ { column: "ref", param: "ref" },
754
+ { column: "lineage", param: "lineage" }
755
+ ],
756
+ ...placed,
757
+ seam,
758
+ table: revisionsTable
759
+ });
760
+ const needsLog = () => {
761
+ if (revisions === void 0) {
762
+ throw new DbRefusal2(
763
+ "this store has no log \u2014 `documentStore({ revisions: false })` opted out of the append-only record entirely, and the write model has no other door"
764
+ );
765
+ }
766
+ return revisions;
767
+ };
768
+ const readers = defineEntity({
769
+ columns: { ...entityColumns, version: versionColumn },
770
+ filterable: [...physicalHeads, entityColumn, createdAtColumn],
771
+ item: (row) => row,
772
+ key: { column: "number", param: "ref" },
773
+ order: [{ column: "number" }],
774
+ ...placed,
775
+ seam,
776
+ sortable: [...physicalHeads, entityColumn, "number"],
777
+ table
778
+ });
779
+ const entityStoreFor = (name) => {
780
+ const definition = registry.named(name);
781
+ const item = (row) => {
782
+ const body = readBody(definition, name, row.key, row.body);
783
+ const head = definition.headOf(body);
784
+ return registry.instance(name, {
785
+ ...head,
786
+ body,
787
+ createdAt: row.createdAt,
788
+ number: row.key,
789
+ updatedAt: row.updatedAt,
790
+ version: row.version ?? 1
791
+ });
792
+ };
793
+ const instanceFromRevision = (ref, row) => {
794
+ const body = readBody(definition, name, ref, row.body);
795
+ const head = definition.headOf(body);
796
+ return registry.instance(name, {
797
+ ...head,
798
+ body,
799
+ createdAt: row.at,
800
+ number: ref,
801
+ updatedAt: row.at,
802
+ version: row.sequence
803
+ });
804
+ };
805
+ const projection = projectionOf({
806
+ carried: ["lineage"],
807
+ columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
808
+ constants: { [entityColumn]: name },
809
+ filterable: HEAD_COLUMNS2,
810
+ item,
811
+ key: { column: "number", param: "ref" },
812
+ order: [{ column: "number" }],
813
+ ...placed,
814
+ seam,
815
+ sortable: HEAD_COLUMNS2,
816
+ table
817
+ });
818
+ const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
819
+ const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
820
+ const stream = (params, lineage) => ({
821
+ ...tenanted(params[tenantKey]),
822
+ entity: name,
823
+ lineage,
824
+ ref: params.ref
825
+ });
826
+ const headColumnsOf = (body) => Object.fromEntries(
827
+ Object.entries(definition.headOf(body)).map(([key, held]) => [
828
+ columnOf(key),
829
+ held
830
+ ])
831
+ );
832
+ const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
833
+ const append = async (tx, write) => {
834
+ const log = needsLog();
835
+ const params = {
836
+ ...tenanted(write.tenantId),
837
+ actor: write.actor,
838
+ body: write.body,
839
+ entity: name,
840
+ kind: write.kind,
841
+ lineage: write.lineage,
842
+ ref: write.ref,
843
+ ...write.reason === null ? {} : { reason: write.reason }
844
+ };
845
+ const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
846
+ return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
847
+ };
848
+ const project = async (tx, write) => projection.write(tx, {
849
+ ...tenanted(write.tenantId),
850
+ at: write.at,
851
+ body: write.body,
852
+ carried: { lineage: write.lineage },
853
+ derived: write.head,
854
+ hash: write.hash,
855
+ ref: write.ref,
856
+ retiredAt: write.retiredAt,
857
+ sequence: write.version
858
+ });
859
+ const commitTx = seam.scoped(
860
+ async (tx, params) => {
861
+ const tenantId = params[tenantKey];
862
+ const prepared = definition.prepare(params.body);
863
+ const stamped = stampBody(definition, prepared);
864
+ const existing = await locked(tx, params);
865
+ if (existing !== void 0 && existing.retiredAt !== null) {
866
+ throw new DbRefusal2(
867
+ `"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
868
+ );
869
+ }
870
+ const changed = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
871
+ if (existing !== void 0 && !changed) {
872
+ return {
873
+ committed: false,
874
+ lineage: existing.lineage,
875
+ ref: params.ref,
876
+ version: existing.version
877
+ };
878
+ }
879
+ const lineage = existing?.lineage ?? 1;
880
+ const reason = params.reason ?? null;
881
+ const appended = await append(tx, {
882
+ actor: params.actor,
883
+ body: stamped,
884
+ compensationOf: null,
885
+ kind: "committed",
886
+ lineage,
887
+ reason,
888
+ ref: params.ref,
889
+ tenantId
890
+ });
891
+ await project(tx, {
892
+ at: appended.at,
893
+ body: stamped,
894
+ hash: appended.hash,
895
+ head: headColumnsOf(prepared),
896
+ lineage,
897
+ ref: params.ref,
898
+ retiredAt: null,
899
+ tenantId,
900
+ version: appended.version
901
+ });
902
+ return {
903
+ archivable: {
904
+ actor: params.actor,
905
+ at: appended.at,
906
+ body: stamped,
907
+ prevHash: appended.prevHash,
908
+ reason
909
+ },
910
+ committed: true,
911
+ hash: appended.hash,
912
+ lineage,
913
+ previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
914
+ ref: params.ref,
915
+ version: appended.version
916
+ };
917
+ }
918
+ );
919
+ const commit = async (handle, params) => {
920
+ const { archivable, ...answer } = await commitTx(handle, params);
921
+ if (archive === void 0 || !answer.committed || archivable === void 0) return answer;
922
+ const key = `${params[tenantKey]}/${name}/${answer.lineage}/${answer.version}.json`;
923
+ const payload = {
924
+ actor: archivable.actor,
925
+ at: archivable.at,
926
+ body: archivable.body,
927
+ entity: name,
928
+ hash: answer.hash,
929
+ kind: "committed",
930
+ lineage: answer.lineage,
931
+ prevHash: archivable.prevHash,
932
+ ref: params.ref,
933
+ reason: archivable.reason,
934
+ tenant: params[tenantKey],
935
+ version: answer.version
936
+ };
937
+ try {
938
+ await archive.put(key, new TextEncoder().encode(JSON.stringify(payload)), {
939
+ hash: answer.hash,
940
+ immutable: true
941
+ });
942
+ return { ...answer, archived: true };
943
+ } catch {
944
+ return { ...answer, archived: false };
945
+ }
946
+ };
947
+ const retire = seam.scoped(
948
+ async (tx, params) => {
949
+ const tenantId = params[tenantKey];
950
+ const existing = await locked(tx, params);
951
+ if (existing === void 0) {
952
+ throw new DbRefusal2(`"${params.ref}" (${name}) has no document to retire`);
953
+ }
954
+ if (existing.retiredAt !== null) {
955
+ throw new DbRefusal2(`"${params.ref}" (${name}) is already retired`);
956
+ }
957
+ const appended = await append(tx, {
958
+ actor: params.actor,
959
+ body: existing.body,
960
+ compensationOf: null,
961
+ kind: "retired",
962
+ lineage: existing.lineage,
963
+ reason: params.reason ?? null,
964
+ ref: params.ref,
965
+ tenantId
966
+ });
967
+ await project(tx, {
968
+ at: appended.at,
969
+ body: existing.body,
970
+ hash: appended.hash,
971
+ head: storedHead(params.ref, existing.body),
972
+ lineage: existing.lineage,
973
+ ref: params.ref,
974
+ retiredAt: appended.at,
975
+ tenantId,
976
+ version: appended.version
977
+ });
978
+ return {
979
+ hash: appended.hash,
980
+ lineage: existing.lineage,
981
+ ref: params.ref,
982
+ version: appended.version
983
+ };
984
+ }
985
+ );
986
+ const succeed = seam.scoped(
987
+ async (tx, params) => {
988
+ const tenantId = params[tenantKey];
989
+ const existing = await locked(tx, params);
990
+ if (existing === void 0 || existing.retiredAt === null) {
991
+ throw new DbRefusal2(
992
+ `"${params.ref}" (${name}) is not retired: succeed opens a new lineage only for a retired document \u2014 commit is the door for a live one`
993
+ );
994
+ }
995
+ const prepared = definition.prepare(params.body);
996
+ const stamped = stampBody(definition, prepared);
997
+ const lineage = existing.lineage + 1;
998
+ const appended = await append(tx, {
999
+ actor: params.actor,
1000
+ body: stamped,
1001
+ compensationOf: null,
1002
+ kind: "committed",
1003
+ lineage,
1004
+ reason: params.reason ?? null,
1005
+ ref: params.ref,
1006
+ tenantId
1007
+ });
1008
+ await project(tx, {
1009
+ at: appended.at,
1010
+ body: stamped,
1011
+ hash: appended.hash,
1012
+ head: headColumnsOf(prepared),
1013
+ lineage,
1014
+ ref: params.ref,
1015
+ retiredAt: null,
1016
+ tenantId,
1017
+ version: appended.version
1018
+ });
1019
+ return {
1020
+ committed: true,
1021
+ hash: appended.hash,
1022
+ lineage,
1023
+ previous: null,
1024
+ ref: params.ref,
1025
+ version: appended.version
1026
+ };
1027
+ }
1028
+ );
1029
+ const reinstate = seam.scoped(
1030
+ async (tx, params) => {
1031
+ const tenantId = params[tenantKey];
1032
+ const existing = await locked(tx, params);
1033
+ if (existing === void 0 || existing.retiredAt === null) {
1034
+ throw new DbRefusal2(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
1035
+ }
1036
+ const appended = await append(tx, {
1037
+ actor: params.actor,
1038
+ body: existing.body,
1039
+ compensationOf: null,
1040
+ kind: "reinstated",
1041
+ lineage: existing.lineage,
1042
+ reason: params.reason ?? null,
1043
+ ref: params.ref,
1044
+ tenantId
1045
+ });
1046
+ await project(tx, {
1047
+ at: appended.at,
1048
+ body: existing.body,
1049
+ hash: appended.hash,
1050
+ head: storedHead(params.ref, existing.body),
1051
+ lineage: existing.lineage,
1052
+ ref: params.ref,
1053
+ retiredAt: null,
1054
+ tenantId,
1055
+ version: appended.version
1056
+ });
1057
+ return {
1058
+ hash: appended.hash,
1059
+ lineage: existing.lineage,
1060
+ ref: params.ref,
1061
+ version: appended.version
1062
+ };
1063
+ }
1064
+ );
1065
+ const at = seam.scoped(
1066
+ async (tx, params) => {
1067
+ const lineage = await currentLineageOf(tx, params);
1068
+ const row = await needsLog().at(tx, {
1069
+ ...stream(params, lineage),
1070
+ sequence: params.version
1071
+ });
1072
+ return row === null ? null : instanceFromRevision(params.ref, row);
1073
+ }
1074
+ );
1075
+ const asOf = seam.scoped(
1076
+ async (tx, params) => {
1077
+ const lineage = await currentLineageOf(tx, params);
1078
+ const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
1079
+ return row === null ? null : instanceFromRevision(params.ref, row);
1080
+ }
1081
+ );
1082
+ const history = seam.scoped(
1083
+ async (tx, params) => {
1084
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
1085
+ const rows = await needsLog().history(tx, stream(params, lineage));
1086
+ return rows.map((row) => ({
1087
+ actor: row.actor,
1088
+ at: row.at,
1089
+ body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
1090
+ hash: row.hash,
1091
+ kind: row.kind,
1092
+ reason: row.reason,
1093
+ version: row.sequence
1094
+ }));
1095
+ }
1096
+ );
1097
+ const verify = seam.scoped(
1098
+ async (tx, params) => {
1099
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
1100
+ return needsLog().verify(tx, stream(params, lineage));
1101
+ }
1102
+ );
1103
+ const compensate = async (scoped, tenantId, output, kind, body, retired) => {
1104
+ const appended = await append(scoped, {
1105
+ actor: UNDO_ACTOR,
1106
+ body,
1107
+ compensationOf: output.version,
1108
+ kind,
1109
+ lineage: output.lineage,
1110
+ reason: `undo of v${output.version}`,
1111
+ ref: output.ref,
1112
+ tenantId
1113
+ });
1114
+ await project(scoped, {
1115
+ at: appended.at,
1116
+ body,
1117
+ hash: appended.hash,
1118
+ head: storedHead(output.ref, body),
1119
+ lineage: output.lineage,
1120
+ ref: output.ref,
1121
+ retiredAt: retired ? appended.at : null,
1122
+ tenantId,
1123
+ version: appended.version
1124
+ });
1125
+ };
1126
+ const lockedForUndo = async (scoped, tenantId, output) => {
1127
+ const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
1128
+ if (existing === void 0) {
1129
+ throw new DbRefusal2(
1130
+ `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
1131
+ );
1132
+ }
1133
+ return existing;
1134
+ };
1135
+ const undos = {
1136
+ commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1137
+ if (!output.committed) return;
1138
+ const existing = await lockedForUndo(scoped, tenantId, output);
1139
+ if (output.previous === null) {
1140
+ await compensate(scoped, tenantId, output, "retired", existing.body, true);
1141
+ return;
1142
+ }
1143
+ const prior = await needsLog().at(scoped, {
1144
+ ...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
1145
+ sequence: output.previous.version
1146
+ });
1147
+ if (prior === null) {
1148
+ throw new DbRefusal2(
1149
+ `"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
1150
+ );
1151
+ }
1152
+ await compensate(scoped, tenantId, output, "committed", prior.body, false);
1153
+ }),
1154
+ retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1155
+ const existing = await lockedForUndo(scoped, tenantId, output);
1156
+ await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
1157
+ })
1158
+ };
1159
+ const restore = async (tx, row, createdAt) => {
1160
+ const ref = String(row.ref);
1161
+ await project(tx, {
1162
+ at: createdAt,
1163
+ body: row.body,
1164
+ hash: row.hash,
1165
+ head: storedHead(ref, row.body),
1166
+ lineage: Number(row.lineage),
1167
+ ref,
1168
+ retiredAt: row.kind === "retired" ? row.at : null,
1169
+ tenantId: row.tenant,
1170
+ version: row.sequence
1171
+ });
1172
+ };
1173
+ return {
1174
+ door: {
1175
+ asOf,
1176
+ at,
1177
+ commit,
1178
+ get: projection.get,
1179
+ history,
1180
+ list: projection.list,
1181
+ listAll: projection.listAll,
1182
+ reinstate,
1183
+ retire,
1184
+ succeed,
1185
+ undos,
1186
+ verify
1187
+ },
1188
+ restore
1189
+ };
1190
+ };
1191
+ const built = registry.names.map((name) => [name, entityStoreFor(name)]);
1192
+ const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
1193
+ const restorers = Object.fromEntries(
1194
+ built.map(([name, one]) => [name, one.restore])
1195
+ );
1196
+ const heads = seam.scoped(async (tx, params) => {
1197
+ const { columns, entity, order, where } = params;
1198
+ const rows = await readers.project(tx, {
1199
+ ...tenanted(params[tenantKey]),
1200
+ columns: columns.filter((column) => column !== "number").map(columnOf),
1201
+ order: order.map((one) => ({
1202
+ column: columnOf(one.column),
1203
+ ...one.direction === void 0 ? {} : { direction: one.direction }
1204
+ })),
1205
+ where: {
1206
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1207
+ ...where?.status === void 0 ? {} : { status: where.status },
1208
+ ...where?.createdAt === void 0 ? {} : { [createdAtColumn]: { from: where.createdAt[0], to: where.createdAt[1] } }
1209
+ }
1210
+ });
1211
+ return rows.map(
1212
+ (row) => Object.fromEntries(
1213
+ columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])
1214
+ )
1215
+ );
1216
+ });
1217
+ const aggregate = seam.scoped(
1218
+ (tx, params) => {
1219
+ const { by, entities, entity, measures, where } = params;
1220
+ return readers.aggregate(tx, {
1221
+ ...tenanted(params[tenantKey]),
1222
+ ...by === void 0 ? {} : {
1223
+ by: by === "entity" ? entityColumn : by === "status" ? "status" : { bucket: by.bucket, of: by.of }
1224
+ },
1225
+ measures: measures.map(
1226
+ (one) => one === "sum:total" ? `sum:${totalColumn}` : one
1227
+ ),
1228
+ where: {
1229
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1230
+ ...entities === void 0 ? {} : { [entityColumn]: entities },
1231
+ ...where?.status === void 0 ? {} : { status: where.status },
1232
+ ...where !== void 0 && "issueDate" in where ? { issueDate: { from: where.issueDate[0], to: where.issueDate[1] } } : {},
1233
+ ...where !== void 0 && "createdAt" in where ? { [createdAtColumn]: { from: where.createdAt[0], to: where.createdAt[1] } } : {}
1234
+ }
1235
+ });
1236
+ }
1237
+ );
1238
+ const rebuild = seam.scoped(
1239
+ async (tx, params) => {
1240
+ const log = needsLog();
1241
+ const tenant = tenanted(params[tenantKey]);
1242
+ const latest = /* @__PURE__ */ new Map();
1243
+ for (const row of await log.latestPerStream(tx, tenant)) {
1244
+ if (params.entity !== void 0 && row.entity !== params.entity) continue;
1245
+ const address = `${String(row.entity)} ${String(row.ref)}`;
1246
+ const held = latest.get(address);
1247
+ if (held === void 0 || Number(row.lineage) > Number(held.lineage)) {
1248
+ latest.set(address, row);
1249
+ }
1250
+ }
1251
+ let rows = 0;
1252
+ for (const row of latest.values()) {
1253
+ const restore = restorers[String(row.entity)];
1254
+ if (restore === void 0) continue;
1255
+ const first = await log.at(tx, {
1256
+ ...tenant,
1257
+ entity: row.entity,
1258
+ lineage: row.lineage,
1259
+ ref: row.ref,
1260
+ sequence: 1
1261
+ });
1262
+ await restore(tx, row, first?.at ?? row.at);
1263
+ rows += 1;
1264
+ }
1265
+ return { rows };
1266
+ }
1267
+ );
1268
+ return { ...rawEntities, aggregate, heads, rebuild };
1269
+ };
100
1270
  export {
101
1271
  BODY_VERSION_KEY,
1272
+ DEFAULT_DOCUMENT_TABLE,
1273
+ DEFAULT_REVISIONS_TABLE,
1274
+ DEFAULT_REVISION_KIND_COLUMN,
1275
+ ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
102
1276
  Document,
1277
+ appendOnlyTables,
103
1278
  canTransition,
1279
+ canonicalOf,
104
1280
  documentBodyVersioning,
105
1281
  documentEntities,
106
1282
  documentIdentifiers,
1283
+ documentMigrations,
1284
+ documentRoleStatements,
1285
+ documentStore,
1286
+ documentSurface,
1287
+ fieldPatterns,
1288
+ hashOf,
1289
+ isSystemActor,
107
1290
  isTerminalStatus,
108
1291
  migrateBody,
109
- stampBody
1292
+ stampBody,
1293
+ systemActor,
1294
+ validatorOf
110
1295
  };