@geonosis/document 0.9.1 → 0.9.2

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