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