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