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