@geonosis/document 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -51,7 +51,7 @@ var FIELD_CHECKS = {
51
51
  text: { message: "a string", test: (value) => typeof value === "string" }
52
52
  };
53
53
  var validatorOf = (fields, options) => {
54
- const nullable = options?.nullable ?? false;
54
+ const nullable2 = options?.nullable ?? false;
55
55
  return {
56
56
  "~standard": {
57
57
  validate: (input) => {
@@ -64,7 +64,7 @@ var validatorOf = (fields, options) => {
64
64
  for (const [key, kind] of Object.entries(fields)) {
65
65
  const held = record[key];
66
66
  value[key] = held;
67
- if (nullable && held === null) continue;
67
+ if (nullable2 && held === null) continue;
68
68
  if (!FIELD_CHECKS[kind].test(held)) {
69
69
  issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
70
70
  }
@@ -112,7 +112,8 @@ var Document = {
112
112
  extend: (definition) => ({
113
113
  ...definition,
114
114
  headOf: (body) => parseWith(headValidator, definition.headOf(body)),
115
- is: (document) => document.entity === definition.name
115
+ is: (document) => document.entity === definition.name,
116
+ view: definition.view ?? definition.body
116
117
  })
117
118
  };
118
119
 
@@ -138,7 +139,8 @@ var documentEntities = (map) => {
138
139
  fold,
139
140
  instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
140
141
  named: (name) => map[name],
141
- names
142
+ names,
143
+ views: distinctBy((entity) => entity.view)
142
144
  };
143
145
  };
144
146
 
@@ -176,24 +178,438 @@ var documentIdentifiers = (name) => {
176
178
  var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
177
179
  var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
178
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 SORT_COLUMNS = [...HEAD_COLUMNS, "number", "createdAt", "updatedAt"];
277
+ var rowsFor = (definition, store, schema) => {
278
+ const { name } = definition;
279
+ const door = doorFor(store, name);
280
+ const basePath = `/${definition.basePath}`;
281
+ const instanceSchema = merge([
282
+ Document.head,
283
+ Document.record,
284
+ schema.object({ body: definition.view, entity: schema.enum([name]), number: stringSchema })
285
+ ]);
286
+ const commitOutput = schema.union([
287
+ schema.object({
288
+ committed: literalOf(false),
289
+ lineage: numberSchema,
290
+ ref: stringSchema,
291
+ version: numberSchema
292
+ }),
293
+ schema.object({
294
+ archived: optional(booleanSchema),
295
+ committed: literalOf(true),
296
+ hash: stringSchema,
297
+ lineage: numberSchema,
298
+ previous: nullable(schema.object({ hash: stringSchema, version: numberSchema })),
299
+ ref: stringSchema,
300
+ version: numberSchema
301
+ })
302
+ ]);
303
+ const retireLikeOutput = schema.object({
304
+ hash: stringSchema,
305
+ lineage: numberSchema,
306
+ ref: stringSchema,
307
+ version: numberSchema
308
+ });
309
+ const verifyOutput = schema.union([
310
+ schema.object({ ok: literalOf(true), versions: numberSchema }),
311
+ schema.object({
312
+ brokenAt: numberSchema,
313
+ expected: stringSchema,
314
+ found: stringSchema,
315
+ ok: literalOf(false)
316
+ })
317
+ ]);
318
+ const historyOutput = arrayOf(
319
+ schema.object({
320
+ actor: stringSchema,
321
+ at: numberSchema,
322
+ body: unknownSchema,
323
+ hash: stringSchema,
324
+ kind: schema.enum(["committed", "retired", "reinstated"]),
325
+ reason: nullable(stringSchema),
326
+ version: numberSchema
327
+ })
328
+ );
329
+ const listInput = schema.object({
330
+ cursor: optional(nullable(stringSchema)),
331
+ filter: optional(
332
+ schema.object(
333
+ Object.fromEntries(HEAD_COLUMNS.map((column) => [column, optional(stringSchema)]))
334
+ )
335
+ ),
336
+ limit: optional(numberSchema),
337
+ order: optional(
338
+ schema.object({
339
+ column: schema.enum(SORT_COLUMNS),
340
+ direction: optional(schema.enum(["asc", "desc"]))
341
+ })
342
+ )
343
+ });
344
+ const listOutput = schema.object({
345
+ items: arrayOf(merge([instanceSchema, schema.object({ card: definition.card.schema })])),
346
+ nextCursor: nullable(stringSchema)
347
+ });
348
+ const ackOutput = schema.object({ ref: stringSchema });
349
+ return [
350
+ {
351
+ call: (handle, params) => door.get(handle, params),
352
+ input: schema.object({ ref: stringSchema }),
353
+ name: `${name}.get`,
354
+ output: nullable(instanceSchema),
355
+ path: `${basePath}/:ref`,
356
+ scope: "org",
357
+ verb: "query"
358
+ },
359
+ {
360
+ call: async (handle, params) => {
361
+ const page = await door.list(handle, params);
362
+ return {
363
+ items: page.items.map((item) => ({
364
+ ...item,
365
+ card: definition.card.of(item, { counterpartyName: "" })
366
+ })),
367
+ nextCursor: page.nextCursor
368
+ };
369
+ },
370
+ input: listInput,
371
+ name: `${name}.list`,
372
+ output: listOutput,
373
+ path: basePath,
374
+ scope: "org",
375
+ verb: "query"
376
+ },
377
+ {
378
+ call: (handle, params) => door.history(handle, params),
379
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
380
+ name: `${name}.history`,
381
+ output: historyOutput,
382
+ path: `${basePath}/:ref/history`,
383
+ scope: "org",
384
+ verb: "query"
385
+ },
386
+ {
387
+ call: (handle, params) => door.verify(handle, params),
388
+ input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
389
+ name: `${name}.verify`,
390
+ output: verifyOutput,
391
+ path: `${basePath}/:ref/verify`,
392
+ scope: "org",
393
+ verb: "query"
394
+ },
395
+ {
396
+ call: (handle, params) => door.commit(handle, params),
397
+ input: schema.object({
398
+ actor: stringSchema,
399
+ body: definition.body,
400
+ reason: optional(stringSchema),
401
+ ref: stringSchema
402
+ }),
403
+ name: `${name}.commit`,
404
+ output: commitOutput,
405
+ path: basePath,
406
+ scope: "org",
407
+ verb: "mutation"
408
+ },
409
+ {
410
+ call: (handle, params) => door.retire(handle, params),
411
+ input: schema.object({
412
+ actor: stringSchema,
413
+ reason: optional(stringSchema),
414
+ ref: stringSchema
415
+ }),
416
+ name: `${name}.retire`,
417
+ output: retireLikeOutput,
418
+ path: `${basePath}/:ref/retire`,
419
+ scope: "org",
420
+ verb: "mutation"
421
+ },
422
+ {
423
+ call: (handle, params) => door.reinstate(handle, params),
424
+ input: schema.object({
425
+ actor: stringSchema,
426
+ reason: optional(stringSchema),
427
+ ref: stringSchema
428
+ }),
429
+ name: `${name}.reinstate`,
430
+ output: retireLikeOutput,
431
+ path: `${basePath}/:ref/reinstate`,
432
+ scope: "org",
433
+ verb: "mutation"
434
+ },
435
+ {
436
+ call: async (handle, params) => {
437
+ const asked = params;
438
+ const current = await door.get(handle, params);
439
+ if (current === null) {
440
+ throw new Error(`"${asked.ref}" (${name}) has no document to set a status on`);
441
+ }
442
+ const from = definition.statusOf(current.body);
443
+ if (!canTransition(definition.statuses, from, asked.status)) {
444
+ throw new Error(
445
+ `"${name}" cannot move "${asked.ref}" from "${from}" to "${asked.status}": the status machine declares no such transition`
446
+ );
447
+ }
448
+ const body = definition.withStatus(
449
+ current.body,
450
+ asked.status,
451
+ (/* @__PURE__ */ new Date()).toISOString()
452
+ );
453
+ return door.commit(handle, { ...asked, body });
454
+ },
455
+ input: schema.object({
456
+ actor: stringSchema,
457
+ reason: optional(stringSchema),
458
+ ref: stringSchema,
459
+ status: schema.enum(definition.statuses.statuses)
460
+ }),
461
+ name: `${name}.setStatus`,
462
+ output: commitOutput,
463
+ path: `${basePath}/:ref/status`,
464
+ scope: "org",
465
+ verb: "mutation"
466
+ },
467
+ {
468
+ call: { pending: "T3", workflow: `${name}.create` },
469
+ input: schema.object({ draft: definition.draft }),
470
+ name: `${name}.create`,
471
+ output: commitOutput,
472
+ path: basePath,
473
+ scope: "org",
474
+ verb: "mutation"
475
+ },
476
+ {
477
+ call: { pending: "T3", workflow: `${name}.send` },
478
+ input: schema.object({ ref: stringSchema }),
479
+ name: `${name}.send`,
480
+ output: ackOutput,
481
+ path: `${basePath}/:ref/send`,
482
+ scope: "org",
483
+ verb: "mutation"
484
+ },
485
+ {
486
+ call: { pending: "T3", workflow: `${name}.duplicate` },
487
+ input: schema.object({ ref: stringSchema }),
488
+ name: `${name}.duplicate`,
489
+ output: commitOutput,
490
+ path: `${basePath}/:ref/duplicate`,
491
+ scope: "org",
492
+ verb: "mutation"
493
+ },
494
+ {
495
+ call: { pending: "T3", workflow: `${name}.runStarted` },
496
+ input: schema.object({ ref: stringSchema }),
497
+ name: `${name}.runStarted`,
498
+ output: ackOutput,
499
+ path: `${basePath}/:ref/run-started`,
500
+ scope: "org",
501
+ verb: "mutation"
502
+ }
503
+ ];
504
+ };
505
+ var documentSurface = (options) => {
506
+ const { registry, schema, store } = options;
507
+ const headsColumns = [...HEAD_COLUMNS, "entity", "number"];
508
+ const headsInput = schema.object({
509
+ columns: arrayOf(schema.enum(headsColumns)),
510
+ entity: optional(schema.union([stringSchema, arrayOf(stringSchema)])),
511
+ order: arrayOf(
512
+ schema.object({
513
+ column: schema.enum([...SORT_COLUMNS, "entity"]),
514
+ direction: optional(schema.enum(["asc", "desc"]))
515
+ })
516
+ ),
517
+ where: optional(unknownSchema)
518
+ });
519
+ const aggregateInput = schema.object({
520
+ by: optional(unknownSchema),
521
+ entities: optional(arrayOf(stringSchema)),
522
+ entity: optional(stringSchema),
523
+ measures: arrayOf(schema.enum(["count", "sum:total"])),
524
+ where: optional(unknownSchema)
525
+ });
526
+ const aggregateOutput = arrayOf(
527
+ schema.object({
528
+ by: optional(stringSchema),
529
+ count: optional(numberSchema),
530
+ sum: optional(stringSchema)
531
+ })
532
+ );
533
+ const sharedOutput = schema.union(
534
+ registry.fold(
535
+ (entity) => schema.object({ entity: schema.enum([entity.name]), view: entity.view })
536
+ )
537
+ );
538
+ return [
539
+ ...registry.fold((entity) => rowsFor(entity, store, schema)).flat(),
540
+ {
541
+ call: (handle, params) => store.heads(handle, params),
542
+ input: headsInput,
543
+ name: "heads",
544
+ output: arrayOf(unknownSchema),
545
+ path: "/documents/heads",
546
+ scope: "org",
547
+ verb: "query"
548
+ },
549
+ {
550
+ call: (handle, params) => store.aggregate(handle, params),
551
+ input: aggregateInput,
552
+ name: "aggregate",
553
+ output: aggregateOutput,
554
+ path: "/documents/aggregate",
555
+ scope: "org",
556
+ verb: "query"
557
+ },
558
+ {
559
+ call: { pending: "T3", workflow: "document.shared" },
560
+ input: schema.object({ token: stringSchema }),
561
+ name: "shared",
562
+ output: sharedOutput,
563
+ path: "/documents/shared",
564
+ scope: "token",
565
+ verb: "query"
566
+ }
567
+ ];
568
+ };
569
+
179
570
  // src/store/ddl.ts
180
571
  import {
181
572
  DbRefusal,
182
573
  ENTITY_PLACEHOLDERS,
183
- entityMigrations
574
+ logMigrations,
575
+ projectionMigrations
184
576
  } from "@geonosis/db";
185
577
  var DEFAULT_DOCUMENT_TABLE = "documents";
186
578
  var DEFAULT_ENTITY_COLUMN = "entity";
187
579
  var DEFAULT_VERSION_COLUMN = "version";
188
- var DEFAULT_TOTAL_COLUMN = "total";
189
580
  var DEFAULT_TENANT_COLUMN = "tenant_id";
581
+ var DEFAULT_CREATED_AT_COLUMN = "created_at";
582
+ var DEFAULT_UPDATED_AT_COLUMN = "updated_at";
190
583
  var DEFAULT_REVISIONS_TABLE = "document_revisions";
191
584
  var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
585
+ var REVISION_KINDS = ["committed", "retired", "reinstated"];
586
+ var HEAD_FIELDS = Object.keys(headFields);
587
+ var snakeOf = (field) => field.replaceAll(/[A-Z]/g, (upper) => `_${upper.toLowerCase()}`);
192
588
  var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
589
+ var physicalColumnsOf = (columns) => {
590
+ const heads = Object.fromEntries(
591
+ HEAD_FIELDS.map((field) => [
592
+ field,
593
+ nameOf(
594
+ columns?.heads?.[field] ?? (field === "total" ? columns?.total : void 0),
595
+ snakeOf(field)
596
+ )
597
+ ])
598
+ );
599
+ return {
600
+ ...heads,
601
+ createdAt: nameOf(columns?.createdAt, DEFAULT_CREATED_AT_COLUMN),
602
+ entity: columns?.entity ?? DEFAULT_ENTITY_COLUMN,
603
+ tenant: nameOf(columns?.tenant, DEFAULT_TENANT_COLUMN),
604
+ updatedAt: nameOf(columns?.updatedAt, DEFAULT_UPDATED_AT_COLUMN)
605
+ };
606
+ };
193
607
  var appendOnlyTables = (options = {}) => {
194
608
  if (options.revisions === false) return [];
195
609
  return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
196
610
  };
611
+ var quotedName = (name) => `"${name}"`;
612
+ var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
197
613
  var documentRoleStatements = (appRole, options = {}) => {
198
614
  if (typeof appRole !== "string" || appRole === "") {
199
615
  throw new DbRefusal(
@@ -208,147 +624,96 @@ var documentRoleStatements = (appRole, options = {}) => {
208
624
  ]);
209
625
  };
210
626
  var DDL_TYPE_OF = { decimal: "numeric" };
211
- var headIndexedColumns = (totalColumn) => Object.entries(headFields).map(([key, kind]) => {
212
- const column = key === "total" ? totalColumn : key;
213
- const type = DDL_TYPE_OF[kind];
214
- return type === void 0 ? column : { column, type };
627
+ var headIndexedColumns = (physical) => HEAD_FIELDS.map((field) => {
628
+ const type = DDL_TYPE_OF[headFields[field]];
629
+ return {
630
+ column: physical[field],
631
+ nullable: field !== "status",
632
+ ...type === void 0 ? {} : { type }
633
+ };
215
634
  });
216
- var quotedName = (name) => `"${name}"`;
217
- var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
218
- var settingDefault = (name) => `current_setting('${name}', true)`;
219
- var immutableFunctionName = (table) => `${table}_immutable`;
220
- var noUpdateOrDeleteTriggerName = (table) => `${table}_no_update_or_delete`;
221
- var revisionsMigrations = (options, entityColumn, tenantColumn) => {
222
- const revisions = options.revisions;
223
- if (revisions === false) return [];
635
+ var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
636
+ var walls = (options) => ({
637
+ ...options.freeze === void 0 ? {} : { freeze: options.freeze },
638
+ ...options.names === void 0 ? {} : { names: options.names },
639
+ ...options.schema === void 0 ? {} : { schema: options.schema }
640
+ });
641
+ var revisionsMigrations = (options, physical) => {
642
+ if (options.revisions === false) return [];
224
643
  if (typeof options.appRole !== "string" || options.appRole === "") {
225
644
  throw new DbRefusal(
226
645
  "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`"
227
646
  );
228
647
  }
229
- const appRole = options.appRole;
230
648
  const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
231
- const table = revisions?.table ?? DEFAULT_REVISIONS_TABLE;
232
- const on = options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
233
- const [, policies] = entityMigrations({
234
- columns: { tenant: tenantColumn },
235
- ...options.schema === void 0 ? {} : { schema: options.schema },
649
+ const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
650
+ const [tableMigration, policies] = logMigrations({
651
+ appRole: options.appRole,
652
+ columns: { tenant: physical.tenant },
653
+ extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
654
+ key: [physical.entity, "ref", { column: "lineage", type: "integer" }],
655
+ ...walls(options),
236
656
  settings: options.settings,
237
657
  table
238
658
  });
239
- if (policies === void 0) {
240
- throw new Error(
241
- "entityMigrations answered with no policies migration to borrow for the log\u2019s tenant wall"
242
- );
659
+ if (tableMigration === void 0 || policies === void 0) {
660
+ throw new Error("logMigrations answered with fewer than the two migrations a log renders");
243
661
  }
244
- const functionName = immutableFunctionName(table);
245
- const triggerName = noUpdateOrDeleteTriggerName(table);
246
- const qualifiedFunction = options.schema === void 0 ? quotedName(functionName) : `${quotedName(options.schema)}.${quotedName(functionName)}`;
247
662
  return [
248
- {
249
- name: `0003_${table}.sql`,
250
- statements: [
251
- `create table if not exists ${on} (
252
- ${quotedName(tenantColumn)} text not null default ${settingDefault(options.settings.tenantSetting)},
253
- ${quotedName(entityColumn)} text not null,
254
- ${quotedName("ref")} text not null,
255
- ${quotedName("lineage")} integer not null,
256
- ${quotedName("version")} integer not null,
257
- ${quotedName(revisionKindColumn)} text not null,
258
- ${quotedName("body")} jsonb not null,
259
- ${quotedName("actor")} text not null,
260
- ${quotedName("reason")} text,
261
- ${quotedName("at")} bigint not null default (extract(epoch from clock_timestamp()) * 1000)::bigint,
262
- ${quotedName("prev_hash")} text,
263
- ${quotedName("hash")} text not null,
264
- ${quotedName("compensation_of")} integer,
265
- constraint ${quotedName(`${table}_pkey`)} primary key (${quotedName(tenantColumn)}, ${quotedName(entityColumn)}, ${quotedName("ref")}, ${quotedName("lineage")}, ${quotedName("version")}),
266
- constraint ${quotedName(`${table}_${revisionKindColumn}_check`)} check (${quotedName(revisionKindColumn)} in ('committed', 'retired', 'reinstated'))
267
- )`
268
- ]
269
- },
270
- {
271
- ...policies,
272
- name: `0004_${table}_policies.sql`,
273
- statements: [
274
- ...policies.statements,
275
- `create or replace function ${qualifiedFunction}() returns trigger language plpgsql as $$ begin raise exception 'this table is append-only: % is not permitted', tg_op; end; $$`,
276
- `drop trigger if exists ${quotedName(triggerName)} on ${on}`,
277
- `create trigger ${quotedName(triggerName)} before update or delete on ${on} for each row execute function ${qualifiedFunction}()`,
278
- `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 $$`
279
- ]
280
- }
663
+ { ...tableMigration, name: `0003_${table}.sql` },
664
+ { ...policies, name: `0004_${table}_policies.sql` }
281
665
  ];
282
666
  };
283
667
  var documentMigrations = (options) => {
284
668
  const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
285
- const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN;
286
- const totalColumn = nameOf(options.columns?.total, DEFAULT_TOTAL_COLUMN);
287
- const tenantColumn = nameOf(options.columns?.tenant, DEFAULT_TENANT_COLUMN);
288
- const { entity: _entity, total: _total, version, ...restColumns } = options.columns ?? {};
289
- const migrations = entityMigrations({
290
- columns: { ...restColumns, version: version ?? DEFAULT_VERSION_COLUMN },
291
- constants: { [entityColumn]: "" },
292
- indexed: headIndexedColumns(totalColumn),
669
+ const physical = physicalColumnsOf(options.columns);
670
+ const {
671
+ entity: _entity,
672
+ heads: _heads,
673
+ revisionKind: _revisionKind,
674
+ total: _total,
675
+ version,
676
+ ...restColumns
677
+ } = options.columns ?? {};
678
+ const [tableMigration, ...rest] = projectionMigrations({
679
+ carried: [{ column: "lineage", type: "integer not null default 1" }],
680
+ columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
681
+ constants: { [physical.entity]: "" },
682
+ indexed: headIndexedColumns(physical),
293
683
  key: "number",
294
684
  order: [{ column: "number" }],
295
- ...options.schema === void 0 ? {} : { schema: options.schema },
685
+ ...walls(options),
296
686
  settings: options.settings,
297
- sortable: Object.keys(headFields).map((key) => key === "total" ? totalColumn : key),
687
+ sortable: [
688
+ ...HEAD_FIELDS.map((field) => physical[field]),
689
+ physical.createdAt,
690
+ physical.updatedAt
691
+ ],
298
692
  table
299
693
  });
300
- const [tableMigration, ...rest] = migrations;
301
694
  if (tableMigration === void 0) {
302
695
  throw new Error(
303
- "entityMigrations answered with no table migration to append the listing index to"
696
+ "projectionMigrations answered with no table migration to append the listing index to"
304
697
  );
305
698
  }
306
- const listingIndex = `create index if not exists ${quotedName(`${table}_${entityColumn}_issueDate_idx`)} on ${quotedName(table)} (${quotedName(entityColumn)}, ${quotedName("issueDate")})`;
307
- const on = options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
308
- const lineageAndHash = [
309
- `alter table ${on} add column if not exists ${quotedName("lineage")} integer not null default 1`,
310
- `alter table ${on} add column if not exists ${quotedName("hash")} text`
311
- ];
699
+ const listingIndex = `create index if not exists ${quotedName(`${table}_${physical.entity}_${physical.issueDate}_idx`)} on ${quotedName(table)} (${quotedName(physical.entity)}, ${quotedName(physical.issueDate)})`;
312
700
  return [
313
- {
314
- ...tableMigration,
315
- statements: [...tableMigration.statements, listingIndex, ...lineageAndHash]
316
- },
701
+ { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
317
702
  ...rest,
318
- ...revisionsMigrations(options, entityColumn, tenantColumn)
703
+ ...revisionsMigrations(options, physical)
319
704
  ];
320
705
  };
321
706
 
322
707
  // src/store/store.ts
323
- import { rowsOf } from "@geonosis/conformance";
324
708
  import {
325
709
  DbRefusal as DbRefusal2,
326
710
  defineEntity,
327
- fragment
711
+ defineLog,
712
+ projectionOf
328
713
  } from "@geonosis/db";
329
- var DEFAULT_ENTITY_COLUMN2 = "entity";
330
714
  var DEFAULT_VERSION_COLUMN2 = "version";
331
- var DEFAULT_TOTAL_COLUMN2 = "total";
332
- var DEFAULT_COLUMNS = { createdAt: "created_at", retiredAt: "retired_at", tenant: "tenant_id" };
333
715
  var UNDO_ACTOR = systemActor("document.undo");
334
716
  var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
335
- var quote = (name) => `"${name}"`;
336
- var chain = (before, after) => ({
337
- chunks: [
338
- ...before.chunks.slice(0, -1),
339
- `${before.chunks.at(-1) ?? ""}${after.chunks[0] ?? ""}`,
340
- ...after.chunks.slice(1)
341
- ],
342
- values: [...before.values, ...after.values]
343
- });
344
- var chainAll = (pieces) => pieces.reduce((built, piece) => chain(built, piece), fragment([""]));
345
- var text = (chunk) => fragment([chunk]);
346
- var bound = (held) => fragment(["", ""], [held]);
347
- var setList = (columns) => columns.flatMap((one, at) => [
348
- text(`${at === 0 ? "" : ", "}${quote(one.column)} = `),
349
- bound(one.held)
350
- ]);
351
- var valuesList = (columns) => columns.flatMap((one, at) => [text(at === 0 ? "" : ", "), bound(one.held)]);
352
717
  var readBody = (entity, entityName, ref, stored) => {
353
718
  const migrated = migrateBody(entity, stored);
354
719
  const result = entity.body["~standard"].validate(migrated);
@@ -364,289 +729,84 @@ var readBody = (entity, entityName, ref, stored) => {
364
729
  }
365
730
  return result.value;
366
731
  };
367
- var bucketExpr = (unit, column) => `to_char(date_trunc('${unit}', ${quote(column)}::date), 'YYYY-MM-DD')`;
368
- var byExpr = (by, columnOf) => by === "entity" ? quote(columnOf("entity")) : by === "status" ? quote(columnOf("status")) : bucketExpr(by.bucket, columnOf(by.of));
732
+ var headFrom = (found) => found === void 0 ? void 0 : {
733
+ body: found.body,
734
+ hash: found.hash,
735
+ lineage: Number(found.carried.lineage ?? 1),
736
+ retiredAt: found.retiredAt,
737
+ version: found.sequence
738
+ };
369
739
  var documentStore = (options) => {
370
740
  const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
371
- const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN2;
372
- const versionColumn = nameOf2(options.columns?.version, DEFAULT_VERSION_COLUMN2);
373
- const tenantColumn = nameOf2(options.columns?.tenant, DEFAULT_COLUMNS.tenant);
374
- const createdAtColumn = nameOf2(options.columns?.createdAt, DEFAULT_COLUMNS.createdAt);
375
- const retiredAtColumn = nameOf2(options.columns?.retiredAt, DEFAULT_COLUMNS.retiredAt);
376
- const totalColumn = nameOf2(options.columns?.total, DEFAULT_TOTAL_COLUMN2);
377
741
  const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
742
+ const physical = physicalColumnsOf(options.columns);
743
+ const {
744
+ entity: _entity,
745
+ heads: _heads,
746
+ revisionKind: _revisionKind,
747
+ total: _total,
748
+ version,
749
+ ...entityColumns
750
+ } = options.columns ?? {};
751
+ const versionColumn = nameOf2(version, DEFAULT_VERSION_COLUMN2);
752
+ const entityColumn = physical.entity;
378
753
  const { archive, registry, schema, seam } = options;
379
754
  const tenantKey = seam.tenantKey;
755
+ const placed = schema === void 0 ? {} : { schema };
380
756
  const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
381
- const columnOf = (column) => column === "entity" ? entityColumn : column === "total" ? totalColumn : column;
757
+ const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
758
+ const columnOf = (column) => column === "number" ? "number" : physical[column];
759
+ const physicalHeads = HEAD_FIELDS.map(columnOf);
760
+ const narrowed = (where) => Object.fromEntries(
761
+ Object.entries(where ?? {}).map(([column, held]) => [
762
+ columnOf(column),
763
+ held
764
+ ])
765
+ );
766
+ const revisions = revisionsTable === void 0 ? void 0 : defineLog({
767
+ columns: { tenant: physical.tenant },
768
+ extra: [{ column: revisionKindColumn, param: "kind" }],
769
+ hash: (row) => hashOf({
770
+ actor: row.actor,
771
+ at: row.at,
772
+ body: row.body,
773
+ entity: row.entity,
774
+ kind: row.kind,
775
+ lineage: row.lineage,
776
+ prevHash: row.prevHash,
777
+ reason: row.reason,
778
+ ref: row.ref,
779
+ tenant: row.tenant,
780
+ version: row.sequence
781
+ }),
782
+ key: [
783
+ { column: entityColumn, param: "entity" },
784
+ { column: "ref", param: "ref" },
785
+ { column: "lineage", param: "lineage" }
786
+ ],
787
+ ...placed,
788
+ seam,
789
+ table: revisionsTable
790
+ });
382
791
  const needsLog = () => {
383
- if (revisionsTable === void 0) {
792
+ if (revisions === void 0) {
384
793
  throw new DbRefusal2(
385
794
  "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"
386
795
  );
387
796
  }
388
- return revisionsTable;
389
- };
390
- const currentDbTime = async (tx) => {
391
- const [row] = rowsOf(
392
- await seam.send(
393
- tx,
394
- text('select (extract(epoch from clock_timestamp()) * 1000)::bigint as "now"')
395
- )
396
- );
397
- return Number(row?.now ?? Date.now());
398
- };
399
- const lockedProjection = async (tx, tenantId, entityName, ref) => {
400
- const [row] = rowsOf(
401
- await seam.send(
402
- tx,
403
- chainAll([
404
- text(
405
- `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)} = `
406
- ),
407
- bound(tenantId),
408
- text(` and ${quote(entityColumn)} = `),
409
- bound(entityName),
410
- text(` and ${quote("number")} = `),
411
- bound(ref),
412
- text(" for update")
413
- ])
414
- )
415
- );
416
- if (row === void 0) return void 0;
417
- return {
418
- body: row.body,
419
- hash: row.hash ?? "",
420
- lineage: row.lineage,
421
- retiredAt: row.retiredAt === null ? null : Number(row.retiredAt),
422
- version: row.version
423
- };
424
- };
425
- const currentLineageOf = async (tx, tenantId, entityName, ref) => {
426
- const [row] = rowsOf(
427
- await seam.send(
428
- tx,
429
- chainAll([
430
- text(
431
- `select ${quote("lineage")} as "lineage" from ${quote(table)} where ${quote(tenantColumn)} = `
432
- ),
433
- bound(tenantId),
434
- text(` and ${quote(entityColumn)} = `),
435
- bound(entityName),
436
- text(` and ${quote("number")} = `),
437
- bound(ref)
438
- ])
439
- )
440
- );
441
- return row?.lineage ?? 1;
442
- };
443
- const insertRevisionRow = async (tx, write) => {
444
- const log = needsLog();
445
- const hash = hashOf({
446
- actor: write.actor,
447
- at: write.at,
448
- body: write.body,
449
- entity: write.entityName,
450
- kind: write.kind,
451
- lineage: write.lineage,
452
- prevHash: write.prevHash,
453
- reason: write.reason,
454
- ref: write.ref,
455
- tenant: write.tenantId,
456
- version: write.version
457
- });
458
- await seam.send(
459
- tx,
460
- chainAll([
461
- text(
462
- `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 (`
463
- ),
464
- ...valuesList([
465
- { column: tenantColumn, held: write.tenantId },
466
- { column: entityColumn, held: write.entityName },
467
- { column: "ref", held: write.ref },
468
- { column: "lineage", held: write.lineage },
469
- { column: "version", held: write.version },
470
- { column: revisionKindColumn, held: write.kind },
471
- { column: "body", held: write.body },
472
- { column: "actor", held: write.actor },
473
- { column: "reason", held: write.reason },
474
- { column: "at", held: write.at },
475
- { column: "prev_hash", held: write.prevHash },
476
- { column: "hash", held: hash },
477
- { column: "compensation_of", held: write.compensationOf }
478
- ]),
479
- text(")")
480
- ])
481
- );
482
- return hash;
483
- };
484
- const writeProjection = async (tx, write) => {
485
- const headColumns = Object.entries(write.head).map(([key, held]) => ({
486
- column: columnOf(key),
487
- held
488
- }));
489
- if (write.create) {
490
- await seam.send(
491
- tx,
492
- chainAll([
493
- text(
494
- `insert into ${quote(table)} (${[
495
- tenantColumn,
496
- entityColumn,
497
- "number",
498
- createdAtColumn,
499
- "updated_at",
500
- retiredAtColumn,
501
- versionColumn,
502
- "lineage",
503
- "hash",
504
- "body",
505
- ...headColumns.map((one) => one.column)
506
- ].map(quote).join(", ")}) values (`
507
- ),
508
- ...valuesList([
509
- { column: tenantColumn, held: write.tenantId },
510
- { column: entityColumn, held: write.entityName },
511
- { column: "number", held: write.ref },
512
- { column: createdAtColumn, held: write.at },
513
- { column: "updated_at", held: write.at },
514
- { column: retiredAtColumn, held: write.retiredAt },
515
- { column: versionColumn, held: write.version },
516
- { column: "lineage", held: write.lineage },
517
- { column: "hash", held: write.hash },
518
- { column: "body", held: write.body },
519
- ...headColumns
520
- ]),
521
- text(")")
522
- ])
523
- );
524
- return;
525
- }
526
- await seam.send(
527
- tx,
528
- chainAll([
529
- text(`update ${quote(table)} set `),
530
- ...setList([
531
- { column: "updated_at", held: write.at },
532
- { column: retiredAtColumn, held: write.retiredAt },
533
- { column: versionColumn, held: write.version },
534
- { column: "lineage", held: write.lineage },
535
- { column: "hash", held: write.hash },
536
- { column: "body", held: write.body },
537
- ...headColumns
538
- ]),
539
- text(` where ${quote(tenantColumn)} = `),
540
- bound(write.tenantId),
541
- text(` and ${quote(entityColumn)} = `),
542
- bound(write.entityName),
543
- text(` and ${quote("number")} = `),
544
- bound(write.ref)
545
- ])
546
- );
547
- };
548
- const upsertProjection = async (tx, write) => {
549
- const headColumns = Object.entries(write.head).map(([key, held]) => ({
550
- column: columnOf(key),
551
- held
552
- }));
553
- const inserted = [
554
- { column: tenantColumn, held: write.tenantId },
555
- { column: entityColumn, held: write.entityName },
556
- { column: "number", held: write.ref },
557
- { column: createdAtColumn, held: write.at },
558
- { column: "updated_at", held: write.at },
559
- { column: retiredAtColumn, held: write.retiredAt },
560
- { column: versionColumn, held: write.version },
561
- { column: "lineage", held: write.lineage },
562
- { column: "hash", held: write.hash },
563
- { column: "body", held: write.body },
564
- ...headColumns
565
- ];
566
- const conflictColumns = /* @__PURE__ */ new Set([tenantColumn, entityColumn, "number"]);
567
- const conflict = [...conflictColumns].map(quote).join(", ");
568
- const updated = inserted.filter((one) => !conflictColumns.has(one.column));
569
- await seam.send(
570
- tx,
571
- chainAll([
572
- text(
573
- `insert into ${quote(table)} (${inserted.map((one) => quote(one.column)).join(", ")}) values (`
574
- ),
575
- ...valuesList(inserted),
576
- text(`) on conflict (${conflict}) do update set `),
577
- ...setList(updated)
578
- ])
579
- );
580
- };
581
- const revisionRowAt = async (tx, tenantId, entityName, ref, lineage, version) => {
582
- const log = needsLog();
583
- const [row] = rowsOf(
584
- await seam.send(
585
- tx,
586
- chainAll([
587
- text(
588
- `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)} = `
589
- ),
590
- bound(tenantId),
591
- text(` and ${quote(entityColumn)} = `),
592
- bound(entityName),
593
- text(` and ${quote("ref")} = `),
594
- bound(ref),
595
- text(` and ${quote("lineage")} = `),
596
- bound(lineage),
597
- text(` and ${quote("version")} = `),
598
- bound(version)
599
- ])
600
- )
601
- );
602
- return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
603
- };
604
- const revisionRowAsOf = async (tx, tenantId, entityName, ref, lineage, at) => {
605
- const log = needsLog();
606
- const [row] = rowsOf(
607
- await seam.send(
608
- tx,
609
- chainAll([
610
- text(
611
- `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)} = `
612
- ),
613
- bound(tenantId),
614
- text(` and ${quote(entityColumn)} = `),
615
- bound(entityName),
616
- text(` and ${quote("ref")} = `),
617
- bound(ref),
618
- text(` and ${quote("lineage")} = `),
619
- bound(lineage),
620
- text(` and ${quote("at")} <= `),
621
- bound(at),
622
- text(` order by ${quote("version")} desc limit 1`)
623
- ])
624
- )
625
- );
626
- return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
627
- };
628
- const revisionRowsFor = async (tx, tenantId, entityName, ref, lineage) => {
629
- const log = needsLog();
630
- const rows = rowsOf(
631
- await seam.send(
632
- tx,
633
- chainAll([
634
- text(
635
- `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)} = `
636
- ),
637
- bound(tenantId),
638
- text(` and ${quote(entityColumn)} = `),
639
- bound(entityName),
640
- text(` and ${quote("ref")} = `),
641
- bound(ref),
642
- text(` and ${quote("lineage")} = `),
643
- bound(lineage),
644
- text(` order by ${quote("version")} asc`)
645
- ])
646
- )
647
- );
648
- return rows.map((row) => ({ ...row, at: Number(row.at), kind: row.kind }));
797
+ return revisions;
649
798
  };
799
+ const readers = defineEntity({
800
+ columns: { ...entityColumns, version: versionColumn },
801
+ filterable: [...physicalHeads, entityColumn, physical.createdAt, physical.updatedAt],
802
+ item: (row) => row,
803
+ key: { column: "number", param: "ref" },
804
+ order: [{ column: "number" }],
805
+ ...placed,
806
+ seam,
807
+ sortable: [...physicalHeads, entityColumn, "number", physical.createdAt, physical.updatedAt],
808
+ table
809
+ });
650
810
  const entityStoreFor = (name) => {
651
811
  const definition = registry.named(name);
652
812
  const item = (row) => {
@@ -670,36 +830,86 @@ var documentStore = (options) => {
670
830
  createdAt: row.at,
671
831
  number: ref,
672
832
  updatedAt: row.at,
673
- version: row.version
833
+ version: row.sequence
674
834
  });
675
835
  };
676
- const raw = defineEntity({
677
- columns: { ...options.columns, version: versionColumn },
836
+ const projection = projectionOf({
837
+ carried: ["lineage"],
838
+ columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
678
839
  constants: { [entityColumn]: name },
679
- filterable: Object.keys(headFields),
680
- indexed: (body) => definition.headOf(body),
840
+ filterable: physicalHeads,
681
841
  item,
682
842
  key: { column: "number", param: "ref" },
683
843
  order: [{ column: "number" }],
684
- ...schema === void 0 ? {} : { schema },
844
+ ...placed,
685
845
  seam,
686
- sortable: Object.keys(headFields),
846
+ sortable: [...physicalHeads, "number", physical.createdAt, physical.updatedAt],
687
847
  table
688
848
  });
849
+ const list = (handle, params) => projection.list(handle, {
850
+ ...params,
851
+ ...params.filter === void 0 ? {} : { filter: narrowed(params.filter) },
852
+ ...params.order === void 0 ? {} : {
853
+ order: {
854
+ column: columnOf(params.order.column),
855
+ ...params.order.direction === void 0 ? {} : { direction: params.order.direction }
856
+ }
857
+ }
858
+ });
859
+ const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
860
+ const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
861
+ const stream = (params, lineage) => ({
862
+ ...tenanted(params[tenantKey]),
863
+ entity: name,
864
+ lineage,
865
+ ref: params.ref
866
+ });
867
+ const headColumnsOf = (body) => Object.fromEntries(
868
+ Object.entries(definition.headOf(body)).map(([key, held]) => [
869
+ columnOf(key),
870
+ held
871
+ ])
872
+ );
873
+ const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
874
+ const append = async (tx, write) => {
875
+ const log = needsLog();
876
+ const params = {
877
+ ...tenanted(write.tenantId),
878
+ actor: write.actor,
879
+ body: write.body,
880
+ entity: name,
881
+ kind: write.kind,
882
+ lineage: write.lineage,
883
+ ref: write.ref,
884
+ ...write.reason === null ? {} : { reason: write.reason }
885
+ };
886
+ const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
887
+ return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
888
+ };
889
+ const project = async (tx, write) => projection.write(tx, {
890
+ ...tenanted(write.tenantId),
891
+ at: write.at,
892
+ body: write.body,
893
+ carried: { lineage: write.lineage },
894
+ derived: write.head,
895
+ hash: write.hash,
896
+ ref: write.ref,
897
+ retiredAt: write.retiredAt,
898
+ sequence: write.version
899
+ });
689
900
  const commitTx = seam.scoped(
690
901
  async (tx, params) => {
691
902
  const tenantId = params[tenantKey];
692
903
  const prepared = definition.prepare(params.body);
693
904
  const stamped = stampBody(definition, prepared);
694
- const now = await currentDbTime(tx);
695
- const existing = await lockedProjection(tx, tenantId, name, params.ref);
905
+ const existing = await locked(tx, params);
696
906
  if (existing !== void 0 && existing.retiredAt !== null) {
697
907
  throw new DbRefusal2(
698
908
  `"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
699
909
  );
700
910
  }
701
- const bodyChanged = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
702
- if (existing !== void 0 && !bodyChanged) {
911
+ const changed = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
912
+ if (existing !== void 0 && !changed) {
703
913
  return {
704
914
  committed: false,
705
915
  lineage: existing.lineage,
@@ -708,50 +918,42 @@ var documentStore = (options) => {
708
918
  };
709
919
  }
710
920
  const lineage = existing?.lineage ?? 1;
711
- const version = existing === void 0 ? 1 : existing.version + 1;
712
- const prevHash = existing?.hash ?? null;
713
- const head = definition.headOf(prepared);
714
- const hash = await insertRevisionRow(tx, {
921
+ const reason = params.reason ?? null;
922
+ const appended = await append(tx, {
715
923
  actor: params.actor,
716
- at: now,
717
924
  body: stamped,
718
925
  compensationOf: null,
719
- entityName: name,
720
926
  kind: "committed",
721
927
  lineage,
722
- prevHash,
928
+ reason,
723
929
  ref: params.ref,
724
- reason: params.reason ?? null,
725
- tenantId,
726
- version
930
+ tenantId
727
931
  });
728
- await writeProjection(tx, {
729
- at: now,
932
+ await project(tx, {
933
+ at: appended.at,
730
934
  body: stamped,
731
- create: existing === void 0,
732
- entityName: name,
733
- hash,
734
- head,
935
+ hash: appended.hash,
936
+ head: headColumnsOf(prepared),
735
937
  lineage,
736
938
  ref: params.ref,
737
939
  retiredAt: null,
738
940
  tenantId,
739
- version
941
+ version: appended.version
740
942
  });
741
943
  return {
742
944
  archivable: {
743
945
  actor: params.actor,
744
- at: now,
946
+ at: appended.at,
745
947
  body: stamped,
746
- prevHash,
747
- reason: params.reason ?? null
948
+ prevHash: appended.prevHash,
949
+ reason
748
950
  },
749
951
  committed: true,
750
- hash,
952
+ hash: appended.hash,
751
953
  lineage,
752
954
  previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
753
955
  ref: params.ref,
754
- version
956
+ version: appended.version
755
957
  };
756
958
  }
757
959
  );
@@ -786,53 +988,46 @@ var documentStore = (options) => {
786
988
  const retire = seam.scoped(
787
989
  async (tx, params) => {
788
990
  const tenantId = params[tenantKey];
789
- const now = await currentDbTime(tx);
790
- const existing = await lockedProjection(tx, tenantId, name, params.ref);
991
+ const existing = await locked(tx, params);
791
992
  if (existing === void 0) {
792
993
  throw new DbRefusal2(`"${params.ref}" (${name}) has no document to retire`);
793
994
  }
794
995
  if (existing.retiredAt !== null) {
795
996
  throw new DbRefusal2(`"${params.ref}" (${name}) is already retired`);
796
997
  }
797
- const version = existing.version + 1;
798
- const head = definition.headOf(
799
- readBody(definition, name, params.ref, existing.body)
800
- );
801
- const hash = await insertRevisionRow(tx, {
998
+ const appended = await append(tx, {
802
999
  actor: params.actor,
803
- at: now,
804
1000
  body: existing.body,
805
1001
  compensationOf: null,
806
- entityName: name,
807
1002
  kind: "retired",
808
1003
  lineage: existing.lineage,
809
- prevHash: existing.hash,
810
- ref: params.ref,
811
1004
  reason: params.reason ?? null,
812
- tenantId,
813
- version
1005
+ ref: params.ref,
1006
+ tenantId
814
1007
  });
815
- await writeProjection(tx, {
816
- at: now,
1008
+ await project(tx, {
1009
+ at: appended.at,
817
1010
  body: existing.body,
818
- create: false,
819
- entityName: name,
820
- hash,
821
- head,
1011
+ hash: appended.hash,
1012
+ head: storedHead(params.ref, existing.body),
822
1013
  lineage: existing.lineage,
823
1014
  ref: params.ref,
824
- retiredAt: now,
1015
+ retiredAt: appended.at,
825
1016
  tenantId,
826
- version
1017
+ version: appended.version
827
1018
  });
828
- return { hash, lineage: existing.lineage, ref: params.ref, version };
1019
+ return {
1020
+ hash: appended.hash,
1021
+ lineage: existing.lineage,
1022
+ ref: params.ref,
1023
+ version: appended.version
1024
+ };
829
1025
  }
830
1026
  );
831
1027
  const succeed = seam.scoped(
832
1028
  async (tx, params) => {
833
1029
  const tenantId = params[tenantKey];
834
- const now = await currentDbTime(tx);
835
- const existing = await lockedProjection(tx, tenantId, name, params.ref);
1030
+ const existing = await locked(tx, params);
836
1031
  if (existing === void 0 || existing.retiredAt === null) {
837
1032
  throw new DbRefusal2(
838
1033
  `"${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`
@@ -840,413 +1035,274 @@ var documentStore = (options) => {
840
1035
  }
841
1036
  const prepared = definition.prepare(params.body);
842
1037
  const stamped = stampBody(definition, prepared);
843
- const head = definition.headOf(prepared);
844
1038
  const lineage = existing.lineage + 1;
845
- const hash = await insertRevisionRow(tx, {
1039
+ const appended = await append(tx, {
846
1040
  actor: params.actor,
847
- at: now,
848
1041
  body: stamped,
849
1042
  compensationOf: null,
850
- entityName: name,
851
1043
  kind: "committed",
852
1044
  lineage,
853
- prevHash: null,
854
- ref: params.ref,
855
1045
  reason: params.reason ?? null,
856
- tenantId,
857
- version: 1
1046
+ ref: params.ref,
1047
+ tenantId
858
1048
  });
859
- await writeProjection(tx, {
860
- at: now,
1049
+ await project(tx, {
1050
+ at: appended.at,
861
1051
  body: stamped,
862
- create: false,
863
- entityName: name,
864
- hash,
865
- head,
1052
+ hash: appended.hash,
1053
+ head: headColumnsOf(prepared),
866
1054
  lineage,
867
1055
  ref: params.ref,
868
1056
  retiredAt: null,
869
1057
  tenantId,
870
- version: 1
1058
+ version: appended.version
871
1059
  });
872
- return { committed: true, hash, lineage, previous: null, ref: params.ref, version: 1 };
1060
+ return {
1061
+ committed: true,
1062
+ hash: appended.hash,
1063
+ lineage,
1064
+ previous: null,
1065
+ ref: params.ref,
1066
+ version: appended.version
1067
+ };
873
1068
  }
874
1069
  );
875
1070
  const reinstate = seam.scoped(
876
1071
  async (tx, params) => {
877
1072
  const tenantId = params[tenantKey];
878
- const now = await currentDbTime(tx);
879
- const existing = await lockedProjection(tx, tenantId, name, params.ref);
1073
+ const existing = await locked(tx, params);
880
1074
  if (existing === void 0 || existing.retiredAt === null) {
881
1075
  throw new DbRefusal2(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
882
1076
  }
883
- const version = existing.version + 1;
884
- const head = definition.headOf(
885
- readBody(definition, name, params.ref, existing.body)
886
- );
887
- const hash = await insertRevisionRow(tx, {
1077
+ const appended = await append(tx, {
888
1078
  actor: params.actor,
889
- at: now,
890
1079
  body: existing.body,
891
1080
  compensationOf: null,
892
- entityName: name,
893
1081
  kind: "reinstated",
894
1082
  lineage: existing.lineage,
895
- prevHash: existing.hash,
896
- ref: params.ref,
897
1083
  reason: params.reason ?? null,
898
- tenantId,
899
- version
1084
+ ref: params.ref,
1085
+ tenantId
900
1086
  });
901
- await writeProjection(tx, {
902
- at: now,
1087
+ await project(tx, {
1088
+ at: appended.at,
903
1089
  body: existing.body,
904
- create: false,
905
- entityName: name,
906
- hash,
907
- head,
1090
+ hash: appended.hash,
1091
+ head: storedHead(params.ref, existing.body),
908
1092
  lineage: existing.lineage,
909
1093
  ref: params.ref,
910
1094
  retiredAt: null,
911
1095
  tenantId,
912
- version
1096
+ version: appended.version
913
1097
  });
914
- return { hash, lineage: existing.lineage, ref: params.ref, version };
1098
+ return {
1099
+ hash: appended.hash,
1100
+ lineage: existing.lineage,
1101
+ ref: params.ref,
1102
+ version: appended.version
1103
+ };
915
1104
  }
916
1105
  );
917
1106
  const at = seam.scoped(
918
1107
  async (tx, params) => {
919
- const tenantId = params[tenantKey];
920
- const lineage = await currentLineageOf(tx, tenantId, name, params.ref);
921
- const row = await revisionRowAt(tx, tenantId, name, params.ref, lineage, params.version);
922
- return row === void 0 ? null : instanceFromRevision(params.ref, row);
1108
+ const lineage = await currentLineageOf(tx, params);
1109
+ const row = await needsLog().at(tx, {
1110
+ ...stream(params, lineage),
1111
+ sequence: params.version
1112
+ });
1113
+ return row === null ? null : instanceFromRevision(params.ref, row);
923
1114
  }
924
1115
  );
925
1116
  const asOf = seam.scoped(
926
1117
  async (tx, params) => {
927
- const tenantId = params[tenantKey];
928
- const lineage = await currentLineageOf(tx, tenantId, name, params.ref);
929
- const row = await revisionRowAsOf(tx, tenantId, name, params.ref, lineage, params.at);
930
- return row === void 0 ? null : instanceFromRevision(params.ref, row);
1118
+ const lineage = await currentLineageOf(tx, params);
1119
+ const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
1120
+ return row === null ? null : instanceFromRevision(params.ref, row);
931
1121
  }
932
1122
  );
933
1123
  const history = seam.scoped(
934
1124
  async (tx, params) => {
935
- const tenantId = params[tenantKey];
936
- const lineage = params.lineage ?? await currentLineageOf(tx, tenantId, name, params.ref);
937
- const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
1125
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
1126
+ const rows = await needsLog().history(tx, stream(params, lineage));
938
1127
  return rows.map((row) => ({
939
1128
  actor: row.actor,
940
1129
  at: row.at,
941
- body: readBody(definition, name, `${params.ref} version ${row.version}`, row.body),
1130
+ body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
942
1131
  hash: row.hash,
943
1132
  kind: row.kind,
944
1133
  reason: row.reason,
945
- version: row.version
1134
+ version: row.sequence
946
1135
  }));
947
1136
  }
948
1137
  );
949
1138
  const verify = seam.scoped(
950
1139
  async (tx, params) => {
951
- const tenantId = params[tenantKey];
952
- const lineage = params.lineage ?? await currentLineageOf(tx, tenantId, name, params.ref);
953
- const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
954
- let previousHash = null;
955
- for (const row of rows) {
956
- const expected = hashOf({
957
- actor: row.actor,
958
- at: row.at,
959
- body: row.body,
960
- entity: name,
961
- kind: row.kind,
962
- lineage,
963
- prevHash: previousHash,
964
- reason: row.reason,
965
- ref: params.ref,
966
- tenant: tenantId,
967
- version: row.version
968
- });
969
- if (expected !== row.hash) {
970
- return { brokenAt: row.version, expected, found: row.hash, ok: false };
971
- }
972
- previousHash = row.hash;
973
- }
974
- return { ok: true, versions: rows.length };
1140
+ const lineage = params.lineage ?? await currentLineageOf(tx, params);
1141
+ return needsLog().verify(tx, stream(params, lineage));
975
1142
  }
976
1143
  );
977
- const undoRestoreOrRetire = async (scoped, output, tenantId) => {
978
- if (!output.committed) return;
979
- const now = await currentDbTime(scoped);
980
- const existing = await lockedProjection(scoped, tenantId, name, output.ref);
981
- if (existing === void 0) {
982
- throw new DbRefusal2(
983
- `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
984
- );
985
- }
986
- const version = existing.version + 1;
987
- const reason = `undo of v${output.version}`;
988
- if (output.previous === null) {
989
- const head2 = definition.headOf(
990
- readBody(definition, name, output.ref, existing.body)
991
- );
992
- const hash2 = await insertRevisionRow(scoped, {
993
- actor: UNDO_ACTOR,
994
- at: now,
995
- body: existing.body,
996
- compensationOf: output.version,
997
- entityName: name,
998
- kind: "retired",
999
- lineage: output.lineage,
1000
- prevHash: existing.hash,
1001
- ref: output.ref,
1002
- reason,
1003
- tenantId,
1004
- version
1005
- });
1006
- await writeProjection(scoped, {
1007
- at: now,
1008
- body: existing.body,
1009
- create: false,
1010
- entityName: name,
1011
- hash: hash2,
1012
- head: head2,
1013
- lineage: output.lineage,
1014
- ref: output.ref,
1015
- retiredAt: now,
1016
- tenantId,
1017
- version
1018
- });
1019
- return;
1020
- }
1021
- const prior = await revisionRowAt(
1022
- scoped,
1023
- tenantId,
1024
- name,
1025
- output.ref,
1026
- output.lineage,
1027
- output.previous.version
1028
- );
1029
- if (prior === void 0) {
1030
- throw new DbRefusal2(
1031
- `"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
1032
- );
1033
- }
1034
- const head = definition.headOf(readBody(definition, name, output.ref, prior.body));
1035
- const hash = await insertRevisionRow(scoped, {
1144
+ const compensate = async (scoped, tenantId, output, kind, body, retired) => {
1145
+ const appended = await append(scoped, {
1036
1146
  actor: UNDO_ACTOR,
1037
- at: now,
1038
- body: prior.body,
1147
+ body,
1039
1148
  compensationOf: output.version,
1040
- entityName: name,
1041
- kind: "committed",
1149
+ kind,
1042
1150
  lineage: output.lineage,
1043
- prevHash: existing.hash,
1151
+ reason: `undo of v${output.version}`,
1044
1152
  ref: output.ref,
1045
- reason,
1046
- tenantId,
1047
- version
1153
+ tenantId
1048
1154
  });
1049
- await writeProjection(scoped, {
1050
- at: now,
1051
- body: prior.body,
1052
- create: false,
1053
- entityName: name,
1054
- hash,
1055
- head,
1155
+ await project(scoped, {
1156
+ at: appended.at,
1157
+ body,
1158
+ hash: appended.hash,
1159
+ head: storedHead(output.ref, body),
1056
1160
  lineage: output.lineage,
1057
1161
  ref: output.ref,
1058
- retiredAt: null,
1162
+ retiredAt: retired ? appended.at : null,
1059
1163
  tenantId,
1060
- version
1164
+ version: appended.version
1061
1165
  });
1062
1166
  };
1167
+ const lockedForUndo = async (scoped, tenantId, output) => {
1168
+ const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
1169
+ if (existing === void 0) {
1170
+ throw new DbRefusal2(
1171
+ `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
1172
+ );
1173
+ }
1174
+ return existing;
1175
+ };
1063
1176
  const undos = {
1064
- commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, (scoped) => undoRestoreOrRetire(scoped, output, tenantId)),
1065
- retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1066
- const now = await currentDbTime(scoped);
1067
- const existing = await lockedProjection(scoped, tenantId, name, output.ref);
1068
- if (existing === void 0) {
1177
+ commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1178
+ if (!output.committed) return;
1179
+ const existing = await lockedForUndo(scoped, tenantId, output);
1180
+ if (output.previous === null) {
1181
+ await compensate(scoped, tenantId, output, "retired", existing.body, true);
1182
+ return;
1183
+ }
1184
+ const prior = await needsLog().at(scoped, {
1185
+ ...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
1186
+ sequence: output.previous.version
1187
+ });
1188
+ if (prior === null) {
1069
1189
  throw new DbRefusal2(
1070
- `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
1190
+ `"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
1071
1191
  );
1072
1192
  }
1073
- const version = existing.version + 1;
1074
- const head = definition.headOf(
1075
- readBody(definition, name, output.ref, existing.body)
1076
- );
1077
- const hash = await insertRevisionRow(scoped, {
1078
- actor: UNDO_ACTOR,
1079
- at: now,
1080
- body: existing.body,
1081
- compensationOf: output.version,
1082
- entityName: name,
1083
- kind: "reinstated",
1084
- lineage: output.lineage,
1085
- prevHash: existing.hash,
1086
- ref: output.ref,
1087
- reason: `undo of v${output.version}`,
1088
- tenantId,
1089
- version
1090
- });
1091
- await writeProjection(scoped, {
1092
- at: now,
1093
- body: existing.body,
1094
- create: false,
1095
- entityName: name,
1096
- hash,
1097
- head,
1098
- lineage: output.lineage,
1099
- ref: output.ref,
1100
- retiredAt: null,
1101
- tenantId,
1102
- version
1103
- });
1193
+ await compensate(scoped, tenantId, output, "committed", prior.body, false);
1194
+ }),
1195
+ retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1196
+ const existing = await lockedForUndo(scoped, tenantId, output);
1197
+ await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
1104
1198
  })
1105
1199
  };
1200
+ const restore = async (tx, row, createdAt) => {
1201
+ const ref = String(row.ref);
1202
+ await project(tx, {
1203
+ at: createdAt,
1204
+ body: row.body,
1205
+ hash: row.hash,
1206
+ head: storedHead(ref, row.body),
1207
+ lineage: Number(row.lineage),
1208
+ ref,
1209
+ retiredAt: row.kind === "retired" ? row.at : null,
1210
+ tenantId: row.tenant,
1211
+ version: row.sequence
1212
+ });
1213
+ };
1106
1214
  return {
1107
- asOf,
1108
- at,
1109
- commit,
1110
- get: raw.get,
1111
- history,
1112
- list: raw.list,
1113
- listAll: raw.listAll,
1114
- reinstate,
1115
- retire,
1116
- succeed,
1117
- undos,
1118
- verify
1215
+ door: {
1216
+ asOf,
1217
+ at,
1218
+ commit,
1219
+ get: projection.get,
1220
+ history,
1221
+ list,
1222
+ listAll: projection.listAll,
1223
+ reinstate,
1224
+ retire,
1225
+ succeed,
1226
+ undos,
1227
+ verify
1228
+ },
1229
+ restore
1119
1230
  };
1120
1231
  };
1121
- const rawEntities = Object.fromEntries(
1122
- registry.names.map((name) => [name, entityStoreFor(name)])
1232
+ const built = registry.names.map((name) => [name, entityStoreFor(name)]);
1233
+ const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
1234
+ const restorers = Object.fromEntries(
1235
+ built.map(([name, one]) => [name, one.restore])
1123
1236
  );
1124
- const heads = seam.scoped(async (tx, params) => {
1125
- const { columns, entity, order, where } = params;
1126
- const tenantId = params[tenantKey];
1127
- const selectList = columns.map((column) => `${quote(columnOf(column))} as ${quote(column)}`).join(", ");
1128
- const predicates = [
1129
- text(`select ${selectList} from ${quote(table)} where ${quote(tenantColumn)} = `),
1130
- bound(tenantId),
1131
- text(` and ${quote(retiredAtColumn)} is null`)
1132
- ];
1133
- if (entity !== void 0) {
1134
- predicates.push(
1135
- Array.isArray(entity) ? chainAll([text(` and ${quote(entityColumn)} = any(`), bound(entity), text(")")]) : chainAll([text(` and ${quote(entityColumn)} = `), bound(entity)])
1136
- );
1137
- }
1138
- if (where?.status !== void 0) {
1139
- predicates.push(text(` and ${quote(columnOf("status"))} = `), bound(where.status));
1140
- }
1141
- if (where?.createdAt !== void 0) {
1142
- predicates.push(
1143
- text(` and ${quote(createdAtColumn)} between `),
1144
- bound(where.createdAt[0]),
1145
- text(" and "),
1146
- bound(where.createdAt[1])
1147
- );
1148
- }
1149
- predicates.push(
1150
- text(
1151
- ` order by ${order.map((one) => `${quote(columnOf(one.column))} ${one.direction === "desc" ? "desc" : "asc"}`).join(", ")}`
1152
- )
1153
- );
1154
- return rowsOf(
1155
- await seam.send(tx, chainAll(predicates))
1156
- );
1157
- });
1158
- const aggregate = seam.scoped(async (tx, params) => {
1159
- const { by, entities, entity, measures, where } = params;
1160
- const tenantId = params[tenantKey];
1161
- const wantsCount = measures.includes("count");
1162
- const wantsSum = measures.includes("sum:total");
1163
- const groupSelect = by === void 0 ? [] : [`${byExpr(by, columnOf)} as "by"`];
1164
- const measureSelect = [
1165
- ...wantsCount ? ['count(*)::int as "count"'] : [],
1166
- ...wantsSum ? [`sum(${quote(columnOf("total"))})::text as "sum"`] : []
1167
- ];
1168
- const predicates = [
1169
- text(
1170
- `select ${[...groupSelect, ...measureSelect].join(", ")} from ${quote(table)} where ${quote(tenantColumn)} = `
1171
- ),
1172
- bound(tenantId),
1173
- text(` and ${quote(retiredAtColumn)} is null`)
1174
- ];
1175
- if (entity !== void 0)
1176
- predicates.push(text(` and ${quote(entityColumn)} = `), bound(entity));
1177
- if (entities !== void 0) {
1178
- predicates.push(text(` and ${quote(entityColumn)} = any(`), bound(entities), text(")"));
1179
- }
1180
- if (where?.status !== void 0) {
1181
- predicates.push(text(` and ${quote(columnOf("status"))} = `), bound(where.status));
1182
- }
1183
- if (where !== void 0 && "issueDate" in where) {
1184
- predicates.push(
1185
- text(` and ${quote(columnOf("issueDate"))} between `),
1186
- bound(where.issueDate[0]),
1187
- text(" and "),
1188
- bound(where.issueDate[1])
1189
- );
1190
- }
1191
- if (where !== void 0 && "createdAt" in where) {
1192
- predicates.push(
1193
- text(` and ${quote(createdAtColumn)} between `),
1194
- bound(where.createdAt[0]),
1195
- text(" and "),
1196
- bound(where.createdAt[1])
1237
+ const heads = seam.scoped(
1238
+ async (tx, params) => {
1239
+ const { columns, entity, order, where } = params;
1240
+ const rows = await readers.project(tx, {
1241
+ ...tenanted(params[tenantKey]),
1242
+ columns: columns.filter((column) => column !== "number").map(columnOf),
1243
+ order: order.map((one) => ({
1244
+ column: columnOf(one.column),
1245
+ ...one.direction === void 0 ? {} : { direction: one.direction }
1246
+ })),
1247
+ where: {
1248
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1249
+ ...narrowed(where)
1250
+ }
1251
+ });
1252
+ return rows.map(
1253
+ (row) => Object.fromEntries(
1254
+ columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])
1255
+ )
1197
1256
  );
1198
1257
  }
1199
- if (by !== void 0) predicates.push(text(' group by "by" order by "by"'));
1200
- const rows = rowsOf(
1201
- await seam.send(tx, chainAll(predicates))
1202
- );
1203
- if (rows.length === 0 && by === void 0) {
1204
- return [{ ...wantsCount ? { count: 0 } : {}, ...wantsSum ? { sum: "0" } : {} }];
1258
+ );
1259
+ const aggregate = seam.scoped(
1260
+ (tx, params) => {
1261
+ const { by, entities, entity, measures, where } = params;
1262
+ return readers.aggregate(tx, {
1263
+ ...tenanted(params[tenantKey]),
1264
+ ...by === void 0 ? {} : {
1265
+ by: typeof by === "string" ? columnOf(by) : { bucket: by.bucket, of: columnOf(by.of) }
1266
+ },
1267
+ measures: measures.map(
1268
+ (one) => one === "sum:total" ? `sum:${physical.total}` : one
1269
+ ),
1270
+ where: {
1271
+ ...entity === void 0 ? {} : { [entityColumn]: entity },
1272
+ ...entities === void 0 ? {} : { [entityColumn]: entities },
1273
+ ...narrowed(where)
1274
+ }
1275
+ });
1205
1276
  }
1206
- return rows.map((row) => ({
1207
- ...by === void 0 ? {} : { by: row.by },
1208
- ...wantsCount ? { count: row.count ?? 0 } : {},
1209
- ...wantsSum ? { sum: row.sum ?? "0" } : {}
1210
- }));
1211
- });
1277
+ );
1212
1278
  const rebuild = seam.scoped(
1213
1279
  async (tx, params) => {
1214
1280
  const log = needsLog();
1215
- const tenantId = params[tenantKey];
1216
- const predicates = [
1217
- text(
1218
- `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)} = `
1219
- ),
1220
- bound(tenantId)
1221
- ];
1222
- if (params.entity !== void 0) {
1223
- predicates.push(text(` and ${quote(entityColumn)} = `), bound(params.entity));
1281
+ const tenant = tenanted(params[tenantKey]);
1282
+ const latest = /* @__PURE__ */ new Map();
1283
+ for (const row of await log.latestPerStream(tx, tenant)) {
1284
+ if (params.entity !== void 0 && row.entity !== params.entity) continue;
1285
+ const address = `${String(row.entity)} ${String(row.ref)}`;
1286
+ const held = latest.get(address);
1287
+ if (held === void 0 || Number(row.lineage) > Number(held.lineage)) {
1288
+ latest.set(address, row);
1289
+ }
1224
1290
  }
1225
- predicates.push(
1226
- text(
1227
- ` order by ${quote(entityColumn)}, ${quote("ref")}, ${quote("lineage")} desc, ${quote("version")} desc`
1228
- )
1229
- );
1230
- const rows = rowsOf(await seam.send(tx, chainAll(predicates)));
1231
- for (const row of rows) {
1232
- const definition = registry.named(row.entity);
1233
- if (definition === void 0) continue;
1234
- const clean = readBody(definition, row.entity, row.ref, row.body);
1235
- const head = definition.headOf(clean);
1236
- await upsertProjection(tx, {
1237
- at: Number(row.createdAt),
1238
- body: row.body,
1239
- entityName: row.entity,
1240
- hash: row.hash,
1241
- head,
1291
+ let rows = 0;
1292
+ for (const row of latest.values()) {
1293
+ const restore = restorers[String(row.entity)];
1294
+ if (restore === void 0) continue;
1295
+ const first = await log.at(tx, {
1296
+ ...tenant,
1297
+ entity: row.entity,
1242
1298
  lineage: row.lineage,
1243
1299
  ref: row.ref,
1244
- retiredAt: row.kind === "retired" ? Number(row.at) : null,
1245
- tenantId,
1246
- version: row.version
1300
+ sequence: 1
1247
1301
  });
1302
+ await restore(tx, row, first?.at ?? row.at);
1303
+ rows += 1;
1248
1304
  }
1249
- return { rows: rows.length };
1305
+ return { rows };
1250
1306
  }
1251
1307
  );
1252
1308
  return { ...rawEntities, aggregate, heads, rebuild };
@@ -1258,6 +1314,7 @@ export {
1258
1314
  DEFAULT_REVISION_KIND_COLUMN,
1259
1315
  ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
1260
1316
  Document,
1317
+ HEAD_FIELDS,
1261
1318
  appendOnlyTables,
1262
1319
  canTransition,
1263
1320
  canonicalOf,
@@ -1267,11 +1324,13 @@ export {
1267
1324
  documentMigrations,
1268
1325
  documentRoleStatements,
1269
1326
  documentStore,
1327
+ documentSurface,
1270
1328
  fieldPatterns,
1271
1329
  hashOf,
1272
1330
  isSystemActor,
1273
1331
  isTerminalStatus,
1274
1332
  migrateBody,
1333
+ physicalColumnsOf,
1275
1334
  stampBody,
1276
1335
  systemActor,
1277
1336
  validatorOf