@geonosis/document 0.5.0 → 0.7.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
@@ -1,164 +1,34 @@
1
- // src/core/body-version.ts
2
- var BODY_VERSION_KEY = "_v";
3
- var versionOf = (body) => {
4
- const stamped = body[BODY_VERSION_KEY];
5
- return typeof stamped === "number" && Number.isInteger(stamped) ? stamped : 1;
6
- };
7
- var migrateBody = (definition, stored) => {
8
- if (stored === null || typeof stored !== "object" || Array.isArray(stored)) return stored;
9
- const target = definition.bodyVersion ?? 1;
10
- const steps = definition.migrations ?? {};
11
- let body = stored;
12
- for (let version = versionOf(body); version < target; version += 1) {
13
- const step = steps[version];
14
- if (step === void 0) break;
15
- body = step(body);
16
- }
17
- const { [BODY_VERSION_KEY]: _stamp, ...withoutStamp } = body;
18
- return withoutStamp;
19
- };
20
- var stampBody = (definition, body) => ({
21
- ...body,
22
- [BODY_VERSION_KEY]: definition.bodyVersion ?? 1
23
- });
24
- var documentBodyVersioning = (definition) => ({
25
- migrate: (stored) => migrateBody(definition, stored),
26
- stamp: (body) => stampBody(definition, body)
27
- });
28
-
29
- // src/core/document.ts
30
- var fieldPatterns = {
31
- calendarDate: /^\d{4}-\d{2}-\d{2}$/,
32
- decimal: /^-?\d+(?:\.\d+)?$/
33
- };
34
- var FIELD_CHECKS = {
35
- calendarDate: {
36
- message: "a calendar date is `YYYY-MM-DD`, never prose",
37
- test: (value) => typeof value === "string" && fieldPatterns.calendarDate.test(value)
38
- },
39
- decimal: {
40
- message: "an amount is a decimal string, never a float",
41
- test: (value) => typeof value === "string" && fieldPatterns.decimal.test(value)
42
- },
43
- int: {
44
- message: "an integer",
45
- test: (value) => typeof value === "number" && Number.isInteger(value)
46
- },
47
- positiveInt: {
48
- message: "a positive integer",
49
- test: (value) => typeof value === "number" && Number.isInteger(value) && value > 0
50
- },
51
- text: { message: "a string", test: (value) => typeof value === "string" }
52
- };
53
- var validatorOf = (fields, options) => {
54
- const nullable2 = options?.nullable ?? false;
55
- return {
56
- "~standard": {
57
- validate: (input) => {
58
- if (input === null || typeof input !== "object") {
59
- return { issues: [{ message: "expected an object" }] };
60
- }
61
- const record = input;
62
- const issues = [];
63
- const value = {};
64
- for (const [key, kind] of Object.entries(fields)) {
65
- const held = record[key];
66
- value[key] = held;
67
- if (nullable2 && held === null) continue;
68
- if (!FIELD_CHECKS[kind].test(held)) {
69
- issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
70
- }
71
- }
72
- return issues.length > 0 ? { issues } : { value };
73
- },
74
- vendor: "geonosis-document",
75
- version: 1
76
- }
77
- };
78
- };
79
- var parseWith = (schema, input) => {
80
- const result = schema["~standard"].validate(input);
81
- if (result instanceof Promise) {
82
- throw new Error(
83
- "Document.head and Document.record parse synchronously; an async Standard Schema cannot back them"
84
- );
85
- }
86
- if (result.issues !== void 0) {
87
- throw new Error(result.issues.map((issue) => issue.message).join("; "));
88
- }
89
- return result.value;
90
- };
91
- var headFields = {
92
- status: "text",
93
- issueDate: "calendarDate",
94
- dueDate: "calendarDate",
95
- counterparty: "text",
96
- externalRef: "text",
97
- revision: "text",
98
- total: "decimal"
99
- };
100
- var recordFields = {
101
- version: "positiveInt",
102
- createdAt: "int",
103
- updatedAt: "int"
104
- };
105
- var headValidator = validatorOf(headFields, { nullable: true });
106
- var recordValidator = validatorOf(recordFields);
107
- var Document = {
108
- head: headValidator,
109
- headFields,
110
- record: recordValidator,
111
- recordFields,
112
- extend: (definition) => ({
113
- ...definition,
114
- headOf: (body) => parseWith(headValidator, definition.headOf(body)),
115
- is: (document) => document.entity === definition.name,
116
- view: definition.view ?? definition.body
117
- })
118
- };
119
-
120
- // src/core/entities.ts
121
- var documentEntities = (map) => {
122
- for (const [key, entity] of Object.entries(map)) {
123
- if (entity.name !== key) {
124
- throw new Error(
125
- `documentEntities was handed "${key}" for an entity whose own name is "${entity.name}": the map's key is what a row's \`entity\` column carries, and a mismatch here is a row nothing can find again`
126
- );
127
- }
128
- }
129
- const names = Object.keys(map);
130
- const values = Object.values(map);
131
- const fold = (pick) => values.map(pick);
132
- const distinctBy = (pick) => [
133
- ...new Set(fold(pick))
134
- ];
135
- return {
136
- bodies: distinctBy((entity) => entity.body),
137
- cards: distinctBy((entity) => entity.card.schema),
138
- entities: map,
139
- fold,
140
- instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
141
- named: (name) => map[name],
142
- names,
143
- views: distinctBy((entity) => entity.view)
144
- };
145
- };
146
-
147
- // src/core/actor.ts
148
- var SYSTEM_PREFIX = "system:";
149
- var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
150
- var isSystemActor = (actor) => actor.startsWith(SYSTEM_PREFIX);
151
-
152
- // src/core/hash.ts
153
- import { createHash } from "crypto";
154
- var canonicalOf = (input) => {
155
- if (input === null || typeof input !== "object") return input;
156
- if (Array.isArray(input)) return input.map(canonicalOf);
157
- return Object.fromEntries(
158
- Object.entries(input).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, held]) => [key, canonicalOf(held)])
159
- );
160
- };
161
- var hashOf = (payload) => createHash("sha256").update(JSON.stringify(canonicalOf(payload))).digest("hex");
1
+ import {
2
+ BODY_VERSION_KEY,
3
+ Document,
4
+ canonicalOf,
5
+ documentBodyVersioning,
6
+ documentEntities,
7
+ fieldPatterns,
8
+ migrateBody,
9
+ stampBody,
10
+ validatorOf
11
+ } from "./chunk-7P6FV2YX.js";
12
+ import {
13
+ arrayOf,
14
+ booleanSchema,
15
+ canTransition,
16
+ enumOf,
17
+ isSystemActor,
18
+ isTerminalStatus,
19
+ literalOf,
20
+ merge,
21
+ nonEmptyString,
22
+ nullable,
23
+ numberSchema,
24
+ objectOf,
25
+ optional,
26
+ positiveInt,
27
+ stringSchema,
28
+ systemActor,
29
+ unknownSchema,
30
+ validate
31
+ } from "./chunk-NA3DLROL.js";
162
32
 
163
33
  // src/core/naming.ts
164
34
  var camelOf = (name) => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
@@ -173,1208 +43,33 @@ var documentIdentifiers = (name) => {
173
43
  path: `/${name}s`
174
44
  };
175
45
  };
176
-
177
- // src/core/status.ts
178
- var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
179
- var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
180
-
181
- // src/surface/table.ts
182
- var VENDOR = "geonosis-document-surface";
183
- var isString = (value) => typeof value === "string";
184
- var isNumber = (value) => typeof value === "number";
185
- var scalar = (test, message) => ({
186
- "~standard": {
187
- validate: (input) => test(input) ? { value: input } : { issues: [{ message }] },
188
- vendor: VENDOR,
189
- version: 1
190
- }
191
- });
192
- var stringSchema = scalar(isString, "expected a string");
193
- var numberSchema = scalar(isNumber, "expected a number");
194
- var booleanSchema = scalar(
195
- (value) => typeof value === "boolean",
196
- "expected a boolean"
197
- );
198
- var literalOf = (literal) => scalar(
199
- (value) => value === literal,
200
- `expected exactly ${JSON.stringify(literal)}`
201
- );
202
- var unknownSchema = {
203
- "~standard": { validate: (input) => ({ value: input }), vendor: VENDOR, version: 1 }
204
- };
205
- var syncResult = (schema, input) => {
206
- const result = schema["~standard"].validate(input);
207
- if (result instanceof Promise) {
208
- throw new Error(
209
- "a document surface schema validates synchronously; an async Standard Schema cannot back a row"
210
- );
211
- }
212
- return result;
213
- };
214
- var optional = (inner) => ({
215
- "~standard": {
216
- validate: (input) => input === void 0 ? { value: void 0 } : syncResult(inner, input),
217
- vendor: VENDOR,
218
- version: 1
219
- }
220
- });
221
- var nullable = (inner) => ({
222
- "~standard": {
223
- validate: (input) => input === null ? { value: null } : syncResult(inner, input),
224
- vendor: VENDOR,
225
- version: 1
226
- }
227
- });
228
- var arrayOf = (item) => ({
229
- "~standard": {
230
- validate: (input) => {
231
- if (!Array.isArray(input)) return { issues: [{ message: "expected an array" }] };
232
- const value = [];
233
- const issues = [];
234
- input.forEach((one, at) => {
235
- const result = syncResult(item, one);
236
- if (result.issues !== void 0) {
237
- issues.push(
238
- ...result.issues.map((issue) => ({ ...issue, path: [at, ...issue.path ?? []] }))
239
- );
240
- } else {
241
- value.push(result.value);
242
- }
243
- });
244
- return issues.length > 0 ? { issues } : { value };
245
- },
246
- vendor: VENDOR,
247
- version: 1
248
- }
249
- });
250
- var merge = (schemas) => ({
251
- "~standard": {
252
- validate: (input) => {
253
- let value = {};
254
- const issues = [];
255
- for (const schema of schemas) {
256
- const result = syncResult(schema, input);
257
- if (result.issues !== void 0) issues.push(...result.issues);
258
- else value = { ...value, ...result.value };
259
- }
260
- return issues.length > 0 ? { issues } : { value };
261
- },
262
- vendor: VENDOR,
263
- version: 1
264
- }
265
- });
266
- var doorFor = (store, name) => {
267
- const door = store[name];
268
- if (door === void 0) {
269
- throw new Error(
270
- `"${name}" names no store this table's registry can find \u2014 the table and the store must share one registry`
271
- );
272
- }
273
- return door;
274
- };
275
- var HEAD_COLUMNS = Object.keys(Document.headFields);
276
- var 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
-
570
- // src/store/ddl.ts
571
- import {
572
- DbRefusal,
573
- ENTITY_PLACEHOLDERS,
574
- entityTable,
575
- logMigrations,
576
- projectionMigrations
577
- } from "@geonosis/db";
578
- var DEFAULT_DOCUMENT_TABLE = "documents";
579
- var DEFAULT_ENTITY_COLUMN = "entity";
580
- var DEFAULT_VERSION_COLUMN = "version";
581
- var DEFAULT_TENANT_COLUMN = "tenant_id";
582
- var DEFAULT_CREATED_AT_COLUMN = "created_at";
583
- var DEFAULT_UPDATED_AT_COLUMN = "updated_at";
584
- var DEFAULT_REVISIONS_TABLE = "document_revisions";
585
- var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
586
- var REVISION_KINDS = ["committed", "retired", "reinstated"];
587
- var HEAD_FIELDS = Object.keys(headFields);
588
- var snakeOf = (field) => field.replaceAll(/[A-Z]/g, (upper) => `_${upper.toLowerCase()}`);
589
- var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
590
- var physicalColumnsOf = (columns) => {
591
- const heads = Object.fromEntries(
592
- HEAD_FIELDS.map((field) => [
593
- field,
594
- nameOf(
595
- columns?.heads?.[field] ?? (field === "total" ? columns?.total : void 0),
596
- snakeOf(field)
597
- )
598
- ])
599
- );
600
- return {
601
- ...heads,
602
- createdAt: nameOf(columns?.createdAt, DEFAULT_CREATED_AT_COLUMN),
603
- entity: columns?.entity ?? DEFAULT_ENTITY_COLUMN,
604
- tenant: nameOf(columns?.tenant, DEFAULT_TENANT_COLUMN),
605
- updatedAt: nameOf(columns?.updatedAt, DEFAULT_UPDATED_AT_COLUMN)
606
- };
607
- };
608
- var appendOnlyTables = (options = {}) => {
609
- if (options.revisions === false) return [];
610
- return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
611
- };
612
- var quotedName = (name) => `"${name}"`;
613
- var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
614
- var documentRoleStatements = (appRole, options = {}) => {
615
- if (typeof appRole !== "string" || appRole === "") {
616
- throw new DbRefusal(
617
- "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"
618
- );
619
- }
620
- const role = quotedName(appRole);
621
- const on = (table) => options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
622
- return appendOnlyTables(options).flatMap((table) => [
623
- `revoke update, delete on ${on(table)} from ${role}`,
624
- `grant select, insert on ${on(table)} to ${role}`
625
- ]);
626
- };
627
- var DDL_TYPE_OF = { decimal: "numeric" };
628
- var headIndexedColumns = (physical) => HEAD_FIELDS.map((field) => {
629
- const type = DDL_TYPE_OF[headFields[field]];
630
- return {
631
- column: physical[field],
632
- nullable: field !== "status",
633
- ...type === void 0 ? {} : { type }
634
- };
635
- });
636
- var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
637
- var walls = (options) => ({
638
- ...options.freeze === void 0 ? {} : { freeze: options.freeze },
639
- ...options.names === void 0 ? {} : { names: options.names },
640
- ...options.schema === void 0 ? {} : { schema: options.schema }
641
- });
642
- var revisionsMigrations = (options, physical) => {
643
- if (options.revisions === false) return [];
644
- if (typeof options.appRole !== "string" || options.appRole === "") {
645
- throw new DbRefusal(
646
- "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`"
647
- );
648
- }
649
- const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
650
- const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
651
- const [tableMigration, policies] = logMigrations({
652
- appRole: options.appRole,
653
- columns: { tenant: physical.tenant },
654
- extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
655
- key: [physical.entity, "ref", { column: "lineage", type: "integer" }],
656
- ...walls(options),
657
- settings: options.settings,
658
- table
659
- });
660
- if (tableMigration === void 0 || policies === void 0) {
661
- throw new Error("logMigrations answered with fewer than the two migrations a log renders");
662
- }
663
- return [
664
- { ...tableMigration, name: `0003_${table}.sql` },
665
- { ...policies, name: `0004_${table}_policies.sql` }
666
- ];
667
- };
668
- var documentMigrations = (options) => {
669
- const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
670
- const physical = physicalColumnsOf(options.columns);
671
- const {
672
- entity: _entity,
673
- heads: _heads,
674
- revisionKind: _revisionKind,
675
- total: _total,
676
- version,
677
- ...restColumns
678
- } = options.columns ?? {};
679
- const [tableMigration, ...rest] = projectionMigrations({
680
- carried: [{ column: "lineage", type: "integer not null default 1" }],
681
- columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
682
- constants: { [physical.entity]: "" },
683
- indexed: headIndexedColumns(physical),
684
- key: "number",
685
- order: [{ column: "number" }],
686
- ...walls(options),
687
- settings: options.settings,
688
- sortable: [
689
- ...HEAD_FIELDS.map((field) => physical[field]),
690
- physical.createdAt,
691
- physical.updatedAt
692
- ],
693
- table
694
- });
695
- if (tableMigration === void 0) {
696
- throw new Error(
697
- "projectionMigrations answered with no table migration to append the listing index to"
698
- );
699
- }
700
- const listingIndex = `create index if not exists ${quotedName(`${table}_${physical.entity}_${physical.issueDate}_idx`)} on ${quotedName(table)} (${quotedName(physical.entity)}, ${quotedName(physical.issueDate)})`;
701
- return [
702
- { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
703
- ...rest,
704
- ...revisionsMigrations(options, physical)
705
- ];
706
- };
707
- var TABLE_TYPE_OF = { decimal: "numeric" };
708
- var documentTable = (options = {}) => {
709
- const physical = physicalColumnsOf(options.columns);
710
- const {
711
- entity: _entity,
712
- heads: _heads,
713
- id,
714
- revisionKind: _revisionKind,
715
- total: _total,
716
- version,
717
- ...restColumns
718
- } = options.columns ?? {};
719
- const named = Object.fromEntries(
720
- Object.entries(restColumns).map(([column, held]) => [column, nameOf(held, column)])
721
- );
722
- return entityTable({
723
- columns: { ...named, version: nameOf(version, DEFAULT_VERSION_COLUMN) },
724
- constants: [physical.entity],
725
- extra: {
726
- ...Object.fromEntries(
727
- HEAD_FIELDS.map((field) => [
728
- physical[field],
729
- {
730
- nullable: field !== "status",
731
- type: TABLE_TYPE_OF[headFields[field]] ?? "text"
732
- }
733
- ])
734
- ),
735
- hash: "text",
736
- lineage: "integer"
737
- },
738
- key: "number",
739
- ...options.schema === void 0 ? {} : { schema: options.schema },
740
- ...options.settings === void 0 ? {} : { settings: options.settings },
741
- ...id === void 0 ? {} : { surrogate: nameOf(id.column, "id") },
742
- table: options.table ?? DEFAULT_DOCUMENT_TABLE
743
- });
744
- };
745
-
746
- // src/store/store.ts
747
- import {
748
- DbRefusal as DbRefusal2,
749
- defineEntity,
750
- defineLog,
751
- projectionOf
752
- } from "@geonosis/db";
753
- var DEFAULT_VERSION_COLUMN2 = "version";
754
- var UNDO_ACTOR = systemActor("document.undo");
755
- var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
756
- var readBody = (entity, entityName, ref, stored) => {
757
- const migrated = migrateBody(entity, stored);
758
- const result = entity.body["~standard"].validate(migrated);
759
- if (result instanceof Promise) {
760
- throw new Error(
761
- `${entityName} ${ref}: this entity's body schema validates asynchronously, and a stored body can only be read synchronously here`
762
- );
763
- }
764
- if (result.issues !== void 0) {
765
- throw new Error(
766
- `${entityName} ${ref}'s stored body no longer satisfies its own schema after migration: ${result.issues.map((issue) => issue.message).join("; ")}`
767
- );
768
- }
769
- return result.value;
770
- };
771
- var headFrom = (found) => found === void 0 ? void 0 : {
772
- body: found.body,
773
- hash: found.hash,
774
- lineage: Number(found.carried.lineage ?? 1),
775
- retiredAt: found.retiredAt,
776
- version: found.sequence
777
- };
778
- var documentStore = (options) => {
779
- const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
780
- const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
781
- const physical = physicalColumnsOf(options.columns);
782
- const {
783
- entity: _entity,
784
- heads: _heads,
785
- revisionKind: _revisionKind,
786
- total: _total,
787
- version,
788
- ...entityColumns
789
- } = options.columns ?? {};
790
- const versionColumn = nameOf2(version, DEFAULT_VERSION_COLUMN2);
791
- const entityColumn = physical.entity;
792
- const { archive, registry, schema, seam } = options;
793
- const tenantKey = seam.tenantKey;
794
- const placed = schema === void 0 ? {} : { schema };
795
- const declared = documentTable({
796
- ...options.columns === void 0 ? {} : { columns: options.columns },
797
- ...placed,
798
- table
799
- });
800
- const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
801
- const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
802
- const columnOf = (column) => column === "number" ? "number" : physical[column];
803
- const physicalHeads = HEAD_FIELDS.map(columnOf);
804
- const narrowed = (where) => Object.fromEntries(
805
- Object.entries(where ?? {}).map(([column, held]) => [
806
- columnOf(column),
807
- held
808
- ])
809
- );
810
- const revisions = revisionsTable === void 0 ? void 0 : defineLog({
811
- columns: { tenant: physical.tenant },
812
- extra: [{ column: revisionKindColumn, param: "kind" }],
813
- hash: (row) => hashOf({
814
- actor: row.actor,
815
- at: row.at,
816
- body: row.body,
817
- entity: row.entity,
818
- kind: row.kind,
819
- lineage: row.lineage,
820
- prevHash: row.prevHash,
821
- reason: row.reason,
822
- ref: row.ref,
823
- tenant: row.tenant,
824
- version: row.sequence
825
- }),
826
- key: [
827
- { column: entityColumn, param: "entity" },
828
- { column: "ref", param: "ref" },
829
- { column: "lineage", param: "lineage" }
830
- ],
831
- ...placed,
832
- seam,
833
- table: revisionsTable
834
- });
835
- const needsLog = () => {
836
- if (revisions === void 0) {
837
- throw new DbRefusal2(
838
- "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"
839
- );
840
- }
841
- return revisions;
842
- };
843
- const readers = defineEntity({
844
- columns: { ...entityColumns, version: versionColumn },
845
- filterable: [...physicalHeads, entityColumn, physical.createdAt, physical.updatedAt],
846
- item: (row) => row,
847
- key: { column: "number", param: "ref" },
848
- order: [{ column: "number" }],
849
- seam,
850
- sortable: [...physicalHeads, entityColumn, "number", physical.createdAt, physical.updatedAt],
851
- table: declared
852
- });
853
- const entityStoreFor = (name) => {
854
- const definition = registry.named(name);
855
- const item = (row) => {
856
- const body = readBody(definition, name, row.key, row.body);
857
- const head = definition.headOf(body);
858
- return registry.instance(name, {
859
- ...head,
860
- body,
861
- createdAt: row.createdAt,
862
- number: row.key,
863
- updatedAt: row.updatedAt,
864
- version: row.version ?? 1
865
- });
866
- };
867
- const instanceFromRevision = (ref, row) => {
868
- const body = readBody(definition, name, ref, row.body);
869
- const head = definition.headOf(body);
870
- return registry.instance(name, {
871
- ...head,
872
- body,
873
- createdAt: row.at,
874
- number: ref,
875
- updatedAt: row.at,
876
- version: row.sequence
877
- });
878
- };
879
- const projection = projectionOf({
880
- carried: ["lineage"],
881
- columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
882
- constants: { [entityColumn]: name },
883
- filterable: physicalHeads,
884
- item,
885
- key: { column: "number", param: "ref" },
886
- order: [{ column: "number" }],
887
- ...placed,
888
- seam,
889
- sortable: [...physicalHeads, "number", physical.createdAt, physical.updatedAt],
890
- table: declared
891
- });
892
- const list = (handle, params) => projection.list(handle, {
893
- ...params,
894
- ...params.filter === void 0 ? {} : { filter: narrowed(params.filter) },
895
- ...params.order === void 0 ? {} : {
896
- order: {
897
- column: columnOf(params.order.column),
898
- ...params.order.direction === void 0 ? {} : { direction: params.order.direction }
899
- }
900
- }
901
- });
902
- const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
903
- const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
904
- const stream = (params, lineage) => ({
905
- ...tenanted(params[tenantKey]),
906
- entity: name,
907
- lineage,
908
- ref: params.ref
909
- });
910
- const headColumnsOf = (body) => Object.fromEntries(
911
- Object.entries(definition.headOf(body)).map(([key, held]) => [
912
- columnOf(key),
913
- held
914
- ])
915
- );
916
- const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
917
- const append = async (tx, write) => {
918
- const log = needsLog();
919
- const params = {
920
- ...tenanted(write.tenantId),
921
- actor: write.actor,
922
- body: write.body,
923
- entity: name,
924
- kind: write.kind,
925
- lineage: write.lineage,
926
- ref: write.ref,
927
- ...write.reason === null ? {} : { reason: write.reason }
928
- };
929
- const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
930
- return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
931
- };
932
- const project = async (tx, write) => projection.write(tx, {
933
- ...tenanted(write.tenantId),
934
- at: write.at,
935
- body: write.body,
936
- carried: { lineage: write.lineage },
937
- derived: write.head,
938
- hash: write.hash,
939
- ref: write.ref,
940
- retiredAt: write.retiredAt,
941
- sequence: write.version
942
- });
943
- const commitTx = seam.scoped(
944
- async (tx, params) => {
945
- const tenantId = params[tenantKey];
946
- const prepared = definition.prepare(params.body);
947
- const stamped = stampBody(definition, prepared);
948
- const existing = await locked(tx, params);
949
- if (existing !== void 0 && existing.retiredAt !== null) {
950
- throw new DbRefusal2(
951
- `"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
952
- );
953
- }
954
- const changed = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
955
- if (existing !== void 0 && !changed) {
956
- return {
957
- committed: false,
958
- lineage: existing.lineage,
959
- ref: params.ref,
960
- version: existing.version
961
- };
962
- }
963
- const lineage = existing?.lineage ?? 1;
964
- const reason = params.reason ?? null;
965
- const appended = await append(tx, {
966
- actor: params.actor,
967
- body: stamped,
968
- compensationOf: null,
969
- kind: "committed",
970
- lineage,
971
- reason,
972
- ref: params.ref,
973
- tenantId
974
- });
975
- await project(tx, {
976
- at: appended.at,
977
- body: stamped,
978
- hash: appended.hash,
979
- head: headColumnsOf(prepared),
980
- lineage,
981
- ref: params.ref,
982
- retiredAt: null,
983
- tenantId,
984
- version: appended.version
985
- });
986
- return {
987
- archivable: {
988
- actor: params.actor,
989
- at: appended.at,
990
- body: stamped,
991
- prevHash: appended.prevHash,
992
- reason
993
- },
994
- committed: true,
995
- hash: appended.hash,
996
- lineage,
997
- previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
998
- ref: params.ref,
999
- version: appended.version
1000
- };
1001
- }
1002
- );
1003
- const commit = async (handle, params) => {
1004
- const { archivable, ...answer } = await commitTx(handle, params);
1005
- if (archive === void 0 || !answer.committed || archivable === void 0) return answer;
1006
- const key = `${params[tenantKey]}/${name}/${answer.lineage}/${answer.version}.json`;
1007
- const payload = {
1008
- actor: archivable.actor,
1009
- at: archivable.at,
1010
- body: archivable.body,
1011
- entity: name,
1012
- hash: answer.hash,
1013
- kind: "committed",
1014
- lineage: answer.lineage,
1015
- prevHash: archivable.prevHash,
1016
- ref: params.ref,
1017
- reason: archivable.reason,
1018
- tenant: params[tenantKey],
1019
- version: answer.version
1020
- };
1021
- try {
1022
- await archive.put(key, new TextEncoder().encode(JSON.stringify(payload)), {
1023
- hash: answer.hash,
1024
- immutable: true
1025
- });
1026
- return { ...answer, archived: true };
1027
- } catch {
1028
- return { ...answer, archived: false };
1029
- }
1030
- };
1031
- const retire = seam.scoped(
1032
- async (tx, params) => {
1033
- const tenantId = params[tenantKey];
1034
- const existing = await locked(tx, params);
1035
- if (existing === void 0) {
1036
- throw new DbRefusal2(`"${params.ref}" (${name}) has no document to retire`);
1037
- }
1038
- if (existing.retiredAt !== null) {
1039
- throw new DbRefusal2(`"${params.ref}" (${name}) is already retired`);
1040
- }
1041
- const appended = await append(tx, {
1042
- actor: params.actor,
1043
- body: existing.body,
1044
- compensationOf: null,
1045
- kind: "retired",
1046
- lineage: existing.lineage,
1047
- reason: params.reason ?? null,
1048
- ref: params.ref,
1049
- tenantId
1050
- });
1051
- await project(tx, {
1052
- at: appended.at,
1053
- body: existing.body,
1054
- hash: appended.hash,
1055
- head: storedHead(params.ref, existing.body),
1056
- lineage: existing.lineage,
1057
- ref: params.ref,
1058
- retiredAt: appended.at,
1059
- tenantId,
1060
- version: appended.version
1061
- });
1062
- return {
1063
- hash: appended.hash,
1064
- lineage: existing.lineage,
1065
- ref: params.ref,
1066
- version: appended.version
1067
- };
1068
- }
1069
- );
1070
- const succeed = seam.scoped(
1071
- async (tx, params) => {
1072
- const tenantId = params[tenantKey];
1073
- const existing = await locked(tx, params);
1074
- if (existing === void 0 || existing.retiredAt === null) {
1075
- throw new DbRefusal2(
1076
- `"${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`
1077
- );
1078
- }
1079
- const prepared = definition.prepare(params.body);
1080
- const stamped = stampBody(definition, prepared);
1081
- const lineage = existing.lineage + 1;
1082
- const appended = await append(tx, {
1083
- actor: params.actor,
1084
- body: stamped,
1085
- compensationOf: null,
1086
- kind: "committed",
1087
- lineage,
1088
- reason: params.reason ?? null,
1089
- ref: params.ref,
1090
- tenantId
1091
- });
1092
- await project(tx, {
1093
- at: appended.at,
1094
- body: stamped,
1095
- hash: appended.hash,
1096
- head: headColumnsOf(prepared),
1097
- lineage,
1098
- ref: params.ref,
1099
- retiredAt: null,
1100
- tenantId,
1101
- version: appended.version
1102
- });
1103
- return {
1104
- committed: true,
1105
- hash: appended.hash,
1106
- lineage,
1107
- previous: null,
1108
- ref: params.ref,
1109
- version: appended.version
1110
- };
1111
- }
1112
- );
1113
- const reinstate = seam.scoped(
1114
- async (tx, params) => {
1115
- const tenantId = params[tenantKey];
1116
- const existing = await locked(tx, params);
1117
- if (existing === void 0 || existing.retiredAt === null) {
1118
- throw new DbRefusal2(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
1119
- }
1120
- const appended = await append(tx, {
1121
- actor: params.actor,
1122
- body: existing.body,
1123
- compensationOf: null,
1124
- kind: "reinstated",
1125
- lineage: existing.lineage,
1126
- reason: params.reason ?? null,
1127
- ref: params.ref,
1128
- tenantId
1129
- });
1130
- await project(tx, {
1131
- at: appended.at,
1132
- body: existing.body,
1133
- hash: appended.hash,
1134
- head: storedHead(params.ref, existing.body),
1135
- lineage: existing.lineage,
1136
- ref: params.ref,
1137
- retiredAt: null,
1138
- tenantId,
1139
- version: appended.version
1140
- });
1141
- return {
1142
- hash: appended.hash,
1143
- lineage: existing.lineage,
1144
- ref: params.ref,
1145
- version: appended.version
1146
- };
1147
- }
1148
- );
1149
- const at = seam.scoped(
1150
- async (tx, params) => {
1151
- const lineage = await currentLineageOf(tx, params);
1152
- const row = await needsLog().at(tx, {
1153
- ...stream(params, lineage),
1154
- sequence: params.version
1155
- });
1156
- return row === null ? null : instanceFromRevision(params.ref, row);
1157
- }
1158
- );
1159
- const asOf = seam.scoped(
1160
- async (tx, params) => {
1161
- const lineage = await currentLineageOf(tx, params);
1162
- const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
1163
- return row === null ? null : instanceFromRevision(params.ref, row);
1164
- }
1165
- );
1166
- const history = seam.scoped(
1167
- async (tx, params) => {
1168
- const lineage = params.lineage ?? await currentLineageOf(tx, params);
1169
- const rows = await needsLog().history(tx, stream(params, lineage));
1170
- return rows.map((row) => ({
1171
- actor: row.actor,
1172
- at: row.at,
1173
- body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
1174
- hash: row.hash,
1175
- kind: row.kind,
1176
- reason: row.reason,
1177
- version: row.sequence
1178
- }));
1179
- }
1180
- );
1181
- const verify = seam.scoped(
1182
- async (tx, params) => {
1183
- const lineage = params.lineage ?? await currentLineageOf(tx, params);
1184
- return needsLog().verify(tx, stream(params, lineage));
1185
- }
1186
- );
1187
- const compensate = async (scoped, tenantId, output, kind, body, retired) => {
1188
- const appended = await append(scoped, {
1189
- actor: UNDO_ACTOR,
1190
- body,
1191
- compensationOf: output.version,
1192
- kind,
1193
- lineage: output.lineage,
1194
- reason: `undo of v${output.version}`,
1195
- ref: output.ref,
1196
- tenantId
1197
- });
1198
- await project(scoped, {
1199
- at: appended.at,
1200
- body,
1201
- hash: appended.hash,
1202
- head: storedHead(output.ref, body),
1203
- lineage: output.lineage,
1204
- ref: output.ref,
1205
- retiredAt: retired ? appended.at : null,
1206
- tenantId,
1207
- version: appended.version
1208
- });
1209
- };
1210
- const lockedForUndo = async (scoped, tenantId, output) => {
1211
- const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
1212
- if (existing === void 0) {
1213
- throw new DbRefusal2(
1214
- `"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
1215
- );
1216
- }
1217
- return existing;
1218
- };
1219
- const undos = {
1220
- commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1221
- if (!output.committed) return;
1222
- const existing = await lockedForUndo(scoped, tenantId, output);
1223
- if (output.previous === null) {
1224
- await compensate(scoped, tenantId, output, "retired", existing.body, true);
1225
- return;
1226
- }
1227
- const prior = await needsLog().at(scoped, {
1228
- ...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
1229
- sequence: output.previous.version
1230
- });
1231
- if (prior === null) {
1232
- throw new DbRefusal2(
1233
- `"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
1234
- );
1235
- }
1236
- await compensate(scoped, tenantId, output, "committed", prior.body, false);
1237
- }),
1238
- retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
1239
- const existing = await lockedForUndo(scoped, tenantId, output);
1240
- await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
1241
- })
1242
- };
1243
- const restore = async (tx, row, createdAt) => {
1244
- const ref = String(row.ref);
1245
- await project(tx, {
1246
- at: createdAt,
1247
- body: row.body,
1248
- hash: row.hash,
1249
- head: storedHead(ref, row.body),
1250
- lineage: Number(row.lineage),
1251
- ref,
1252
- retiredAt: row.kind === "retired" ? row.at : null,
1253
- tenantId: row.tenant,
1254
- version: row.sequence
1255
- });
1256
- };
1257
- return {
1258
- door: {
1259
- asOf,
1260
- at,
1261
- commit,
1262
- get: projection.get,
1263
- history,
1264
- list,
1265
- listAll: projection.listAll,
1266
- reinstate,
1267
- retire,
1268
- succeed,
1269
- undos,
1270
- verify
1271
- },
1272
- restore
1273
- };
1274
- };
1275
- const built = registry.names.map((name) => [name, entityStoreFor(name)]);
1276
- const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
1277
- const restorers = Object.fromEntries(
1278
- built.map(([name, one]) => [name, one.restore])
1279
- );
1280
- const heads = seam.scoped(
1281
- async (tx, params) => {
1282
- const { columns, entity, order, where } = params;
1283
- const rows = await readers.project(tx, {
1284
- ...tenanted(params[tenantKey]),
1285
- columns: columns.filter((column) => column !== "number").map(columnOf),
1286
- order: order.map((one) => ({
1287
- column: columnOf(one.column),
1288
- ...one.direction === void 0 ? {} : { direction: one.direction }
1289
- })),
1290
- where: {
1291
- ...entity === void 0 ? {} : { [entityColumn]: entity },
1292
- ...narrowed(where)
1293
- }
1294
- });
1295
- return rows.map(
1296
- (row) => Object.fromEntries(
1297
- columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])
1298
- )
1299
- );
1300
- }
1301
- );
1302
- const aggregate = seam.scoped(
1303
- (tx, params) => {
1304
- const { by, entities, entity, measures, where } = params;
1305
- return readers.aggregate(tx, {
1306
- ...tenanted(params[tenantKey]),
1307
- ...by === void 0 ? {} : {
1308
- by: typeof by === "string" ? columnOf(by) : { bucket: by.bucket, of: columnOf(by.of) }
1309
- },
1310
- measures: measures.map(
1311
- (one) => one === "sum:total" ? `sum:${physical.total}` : one
1312
- ),
1313
- where: {
1314
- ...entity === void 0 ? {} : { [entityColumn]: entity },
1315
- ...entities === void 0 ? {} : { [entityColumn]: entities },
1316
- ...narrowed(where)
1317
- }
1318
- });
1319
- }
1320
- );
1321
- const rebuild = seam.scoped(
1322
- async (tx, params) => {
1323
- const log = needsLog();
1324
- const tenant = tenanted(params[tenantKey]);
1325
- const latest = /* @__PURE__ */ new Map();
1326
- for (const row of await log.latestPerStream(tx, tenant)) {
1327
- if (params.entity !== void 0 && row.entity !== params.entity) continue;
1328
- const address = `${String(row.entity)} ${String(row.ref)}`;
1329
- const held = latest.get(address);
1330
- if (held === void 0 || Number(row.lineage) > Number(held.lineage)) {
1331
- latest.set(address, row);
1332
- }
1333
- }
1334
- let rows = 0;
1335
- for (const row of latest.values()) {
1336
- const restore = restorers[String(row.entity)];
1337
- if (restore === void 0) continue;
1338
- const first = await log.at(tx, {
1339
- ...tenant,
1340
- entity: row.entity,
1341
- lineage: row.lineage,
1342
- ref: row.ref,
1343
- sequence: 1
1344
- });
1345
- await restore(tx, row, first?.at ?? row.at);
1346
- rows += 1;
1347
- }
1348
- return { rows };
1349
- }
1350
- );
1351
- return { ...rawEntities, aggregate, heads, rebuild };
1352
- };
1353
46
  export {
1354
47
  BODY_VERSION_KEY,
1355
- DEFAULT_DOCUMENT_TABLE,
1356
- DEFAULT_REVISIONS_TABLE,
1357
- DEFAULT_REVISION_KIND_COLUMN,
1358
- ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
1359
48
  Document,
1360
- HEAD_FIELDS,
1361
- appendOnlyTables,
49
+ arrayOf,
50
+ booleanSchema,
1362
51
  canTransition,
1363
52
  canonicalOf,
1364
53
  documentBodyVersioning,
1365
54
  documentEntities,
1366
55
  documentIdentifiers,
1367
- documentMigrations,
1368
- documentRoleStatements,
1369
- documentStore,
1370
- documentSurface,
56
+ enumOf,
1371
57
  fieldPatterns,
1372
- hashOf,
1373
58
  isSystemActor,
1374
59
  isTerminalStatus,
60
+ literalOf,
61
+ merge,
1375
62
  migrateBody,
1376
- physicalColumnsOf,
63
+ nonEmptyString,
64
+ nullable,
65
+ numberSchema,
66
+ objectOf,
67
+ optional,
68
+ positiveInt,
1377
69
  stampBody,
70
+ stringSchema,
1378
71
  systemActor,
72
+ unknownSchema,
73
+ validate,
1379
74
  validatorOf
1380
75
  };