@geonosis/document 0.9.1 → 0.9.3

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 +18 -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
@@ -0,0 +1,209 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
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 });
13
+ if (from && typeof from === "object" || typeof from === "function") {
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
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
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)
36
+ });
37
+ };
38
+
39
+ // src/store/ddl.ts
40
+ var exports_ddl = {};
41
+ __export(exports_ddl, {
42
+ DEFAULT_DOCUMENT_TABLE: () => DEFAULT_DOCUMENT_TABLE,
43
+ DEFAULT_REVISIONS_TABLE: () => DEFAULT_REVISIONS_TABLE,
44
+ DEFAULT_REVISION_KIND_COLUMN: () => DEFAULT_REVISION_KIND_COLUMN,
45
+ DOCUMENT_MIGRATION_PLACEHOLDERS: () => import_db.ENTITY_PLACEHOLDERS,
46
+ HEAD_FIELDS: () => HEAD_FIELDS,
47
+ appendOnlyTables: () => appendOnlyTables,
48
+ documentMigrations: () => documentMigrations,
49
+ documentRoleStatements: () => documentRoleStatements,
50
+ documentTable: () => documentTable,
51
+ physicalColumnsOf: () => physicalColumnsOf
52
+ });
53
+ module.exports = __toCommonJS(exports_ddl);
54
+ var import_db = require("@geonosis/db");
55
+ var import_document = require("../core/document.cjs");
56
+ var DEFAULT_DOCUMENT_TABLE = "documents";
57
+ var DEFAULT_ENTITY_COLUMN = "entity";
58
+ var DEFAULT_VERSION_COLUMN = "version";
59
+ var DEFAULT_TENANT_COLUMN = "tenant_id";
60
+ var DEFAULT_CREATED_AT_COLUMN = "created_at";
61
+ var DEFAULT_UPDATED_AT_COLUMN = "updated_at";
62
+ var DEFAULT_REVISIONS_TABLE = "document_revisions";
63
+ var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
64
+ var REVISION_KINDS = ["committed", "retired", "reinstated"];
65
+ var HEAD_FIELDS = Object.keys(import_document.headFields);
66
+ var snakeOf = (field) => field.replaceAll(/[A-Z]/g, (upper) => `_${upper.toLowerCase()}`);
67
+ var nameOf = (value, fallback) => value === undefined ? fallback : typeof value === "string" ? value : value.name;
68
+ var physicalColumnsOf = (columns) => {
69
+ const heads = Object.fromEntries(HEAD_FIELDS.map((field) => [
70
+ field,
71
+ nameOf(columns?.heads?.[field] ?? (field === "total" ? columns?.total : undefined), snakeOf(field))
72
+ ]));
73
+ return {
74
+ ...heads,
75
+ createdAt: nameOf(columns?.createdAt, DEFAULT_CREATED_AT_COLUMN),
76
+ entity: columns?.entity ?? DEFAULT_ENTITY_COLUMN,
77
+ tenant: nameOf(columns?.tenant, DEFAULT_TENANT_COLUMN),
78
+ updatedAt: nameOf(columns?.updatedAt, DEFAULT_UPDATED_AT_COLUMN)
79
+ };
80
+ };
81
+ var appendOnlyTables = (options = {}) => {
82
+ if (options.revisions === false)
83
+ return [];
84
+ return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
85
+ };
86
+ var quotedName = (name) => `"${name}"`;
87
+ var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
88
+ var documentRoleStatements = (appRole, options = {}) => {
89
+ if (typeof appRole !== "string" || appRole === "") {
90
+ throw new import_db.DbRefusal("documentRoleStatements needs an `appRole` — the name a consumer’s application connects as belongs to whoever runs the database, and one baked in here would be another repo’s");
91
+ }
92
+ const role = quotedName(appRole);
93
+ const on = (table) => options.schema === undefined ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
94
+ return appendOnlyTables(options).flatMap((table) => [
95
+ `revoke update, delete on ${on(table)} from ${role}`,
96
+ `grant select, insert on ${on(table)} to ${role}`
97
+ ]);
98
+ };
99
+ var DDL_TYPE_OF = { decimal: "numeric" };
100
+ var headIndexedColumns = (physical) => HEAD_FIELDS.map((field) => {
101
+ const type = DDL_TYPE_OF[import_document.headFields[field]];
102
+ return {
103
+ column: physical[field],
104
+ nullable: field !== "status",
105
+ ...type === undefined ? {} : { type }
106
+ };
107
+ });
108
+ var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
109
+ var walls = (options) => ({
110
+ ...options.freeze === undefined ? {} : { freeze: options.freeze },
111
+ ...options.names === undefined ? {} : { names: options.names },
112
+ ...options.schema === undefined ? {} : { schema: options.schema }
113
+ });
114
+ var revisionsMigrations = (options, physical) => {
115
+ if (options.revisions === false)
116
+ return [];
117
+ if (typeof options.appRole !== "string" || options.appRole === "") {
118
+ throw new import_db.DbRefusal("documentMigrations needs an `appRole` to render the log’s wall — the role a consumer’s application connects as belongs to whoever runs the database, and one baked in here would be another repo’s. Pass it, or opt out of the log entirely with `revisions: false`");
119
+ }
120
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
121
+ const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
122
+ const [tableMigration, policies] = import_db.logMigrations({
123
+ appRole: options.appRole,
124
+ columns: { tenant: physical.tenant },
125
+ extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
126
+ key: [physical.entity, "ref", { column: "lineage", type: "integer" }],
127
+ ...walls(options),
128
+ settings: options.settings,
129
+ table
130
+ });
131
+ if (tableMigration === undefined || policies === undefined) {
132
+ throw new Error("logMigrations answered with fewer than the two migrations a log renders");
133
+ }
134
+ return [
135
+ { ...tableMigration, name: `0003_${table}.sql` },
136
+ { ...policies, name: `0004_${table}_policies.sql` }
137
+ ];
138
+ };
139
+ var documentMigrations = (options) => {
140
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
141
+ const physical = physicalColumnsOf(options.columns);
142
+ const {
143
+ entity: _entity,
144
+ heads: _heads,
145
+ revisionKind: _revisionKind,
146
+ total: _total,
147
+ version,
148
+ ...restColumns
149
+ } = options.columns ?? {};
150
+ const [tableMigration, ...rest] = import_db.projectionMigrations({
151
+ carried: [{ column: "lineage", type: "integer not null default 1" }],
152
+ columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
153
+ constants: { [physical.entity]: "" },
154
+ indexed: headIndexedColumns(physical),
155
+ key: "number",
156
+ order: [{ column: "number" }],
157
+ ...walls(options),
158
+ settings: options.settings,
159
+ sortable: [
160
+ ...HEAD_FIELDS.map((field) => physical[field]),
161
+ physical.createdAt,
162
+ physical.updatedAt
163
+ ],
164
+ table
165
+ });
166
+ if (tableMigration === undefined) {
167
+ throw new Error("projectionMigrations answered with no table migration to append the listing index to");
168
+ }
169
+ const listingIndex = `create index if not exists ${quotedName(`${table}_${physical.entity}_${physical.issueDate}_idx`)} on ${quotedName(table)} (${quotedName(physical.entity)}, ${quotedName(physical.issueDate)})`;
170
+ return [
171
+ { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
172
+ ...rest,
173
+ ...revisionsMigrations(options, physical)
174
+ ];
175
+ };
176
+ var TABLE_TYPE_OF = { decimal: "numeric" };
177
+ var documentTable = (options = {}) => {
178
+ const physical = physicalColumnsOf(options.columns);
179
+ const {
180
+ entity: _entity,
181
+ heads: _heads,
182
+ id,
183
+ revisionKind: _revisionKind,
184
+ total: _total,
185
+ version,
186
+ ...restColumns
187
+ } = options.columns ?? {};
188
+ const named = Object.fromEntries(Object.entries(restColumns).map(([column, held]) => [column, nameOf(held, column)]));
189
+ return import_db.entityTable({
190
+ columns: { ...named, version: nameOf(version, DEFAULT_VERSION_COLUMN) },
191
+ constants: [physical.entity],
192
+ extra: {
193
+ ...Object.fromEntries(HEAD_FIELDS.map((field) => [
194
+ physical[field],
195
+ {
196
+ nullable: field !== "status",
197
+ type: TABLE_TYPE_OF[import_document.headFields[field]] ?? "text"
198
+ }
199
+ ])),
200
+ hash: "text",
201
+ lineage: "integer"
202
+ },
203
+ key: "number",
204
+ ...options.schema === undefined ? {} : { schema: options.schema },
205
+ ...options.settings === undefined ? {} : { settings: options.settings },
206
+ ...id === undefined ? {} : { surrogate: nameOf(id.column, "id") },
207
+ table: options.table ?? DEFAULT_DOCUMENT_TABLE
208
+ });
209
+ };
@@ -0,0 +1,56 @@
1
+ import { ENTITY_PLACEHOLDERS, type EntityColumns, type EntityMigration, type EntityName, type FreezeRegister, type SessionSettings, type TenantPolicyNames } from '@geonosis/db';
2
+ import type { PgTable } from 'drizzle-orm/pg-core';
3
+ import { type DocumentHead } from '../core/document.cjs';
4
+ export { ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS };
5
+ export declare const DEFAULT_DOCUMENT_TABLE = "documents";
6
+ export declare const DEFAULT_REVISIONS_TABLE = "document_revisions";
7
+ export declare const DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
8
+ export type HeadField = keyof DocumentHead;
9
+ export declare const HEAD_FIELDS: HeadField[];
10
+ export type DocumentColumns = EntityColumns & {
11
+ entity?: string;
12
+ heads?: Partial<Record<HeadField, EntityName>>;
13
+ revisionKind?: string;
14
+ total?: EntityName;
15
+ };
16
+ export type DocumentPhysicalColumns = Readonly<Record<HeadField, string>> & {
17
+ createdAt: string;
18
+ entity: string;
19
+ tenant: string;
20
+ updatedAt: string;
21
+ };
22
+ export declare const physicalColumnsOf: (columns: DocumentColumns | undefined) => DocumentPhysicalColumns;
23
+ export type DocumentRevisionsOptions = {
24
+ table?: string;
25
+ };
26
+ export type DocumentMigrationsOptions = {
27
+ appRole?: string;
28
+ columns?: DocumentColumns;
29
+ freeze?: FreezeRegister;
30
+ names?: TenantPolicyNames;
31
+ revisions?: DocumentRevisionsOptions | false;
32
+ schema?: string;
33
+ settings: SessionSettings;
34
+ table?: string;
35
+ };
36
+ export type AppendOnlyTablesOptions = {
37
+ table?: string;
38
+ revisions?: DocumentRevisionsOptions | false;
39
+ };
40
+ export declare const appendOnlyTables: (options?: AppendOnlyTablesOptions) => string[];
41
+ export declare const documentRoleStatements: (appRole: string, options?: AppendOnlyTablesOptions & {
42
+ schema?: string;
43
+ }) => string[];
44
+ export declare const documentMigrations: (options: DocumentMigrationsOptions) => EntityMigration[];
45
+ export type DocumentTableOptions = {
46
+ columns?: DocumentColumns;
47
+ schema?: string;
48
+ settings?: SessionSettings;
49
+ table?: string;
50
+ };
51
+ /**
52
+ * The document table as a drizzle table: the same shape `documentMigrations` renders, declared once
53
+ * so the store's reads and writes compose over it (D-069). A consumer with a table of their own
54
+ * hands that in instead.
55
+ */
56
+ export declare const documentTable: (options?: DocumentTableOptions) => PgTable;
@@ -0,0 +1,56 @@
1
+ import { ENTITY_PLACEHOLDERS, type EntityColumns, type EntityMigration, type EntityName, type FreezeRegister, type SessionSettings, type TenantPolicyNames } from '@geonosis/db';
2
+ import type { PgTable } from 'drizzle-orm/pg-core';
3
+ import { type DocumentHead } from '../core/document.js';
4
+ export { ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS };
5
+ export declare const DEFAULT_DOCUMENT_TABLE = "documents";
6
+ export declare const DEFAULT_REVISIONS_TABLE = "document_revisions";
7
+ export declare const DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
8
+ export type HeadField = keyof DocumentHead;
9
+ export declare const HEAD_FIELDS: HeadField[];
10
+ export type DocumentColumns = EntityColumns & {
11
+ entity?: string;
12
+ heads?: Partial<Record<HeadField, EntityName>>;
13
+ revisionKind?: string;
14
+ total?: EntityName;
15
+ };
16
+ export type DocumentPhysicalColumns = Readonly<Record<HeadField, string>> & {
17
+ createdAt: string;
18
+ entity: string;
19
+ tenant: string;
20
+ updatedAt: string;
21
+ };
22
+ export declare const physicalColumnsOf: (columns: DocumentColumns | undefined) => DocumentPhysicalColumns;
23
+ export type DocumentRevisionsOptions = {
24
+ table?: string;
25
+ };
26
+ export type DocumentMigrationsOptions = {
27
+ appRole?: string;
28
+ columns?: DocumentColumns;
29
+ freeze?: FreezeRegister;
30
+ names?: TenantPolicyNames;
31
+ revisions?: DocumentRevisionsOptions | false;
32
+ schema?: string;
33
+ settings: SessionSettings;
34
+ table?: string;
35
+ };
36
+ export type AppendOnlyTablesOptions = {
37
+ table?: string;
38
+ revisions?: DocumentRevisionsOptions | false;
39
+ };
40
+ export declare const appendOnlyTables: (options?: AppendOnlyTablesOptions) => string[];
41
+ export declare const documentRoleStatements: (appRole: string, options?: AppendOnlyTablesOptions & {
42
+ schema?: string;
43
+ }) => string[];
44
+ export declare const documentMigrations: (options: DocumentMigrationsOptions) => EntityMigration[];
45
+ export type DocumentTableOptions = {
46
+ columns?: DocumentColumns;
47
+ schema?: string;
48
+ settings?: SessionSettings;
49
+ table?: string;
50
+ };
51
+ /**
52
+ * The document table as a drizzle table: the same shape `documentMigrations` renders, declared once
53
+ * so the store's reads and writes compose over it (D-069). A consumer with a table of their own
54
+ * hands that in instead.
55
+ */
56
+ export declare const documentTable: (options?: DocumentTableOptions) => PgTable;
@@ -0,0 +1,175 @@
1
+ // src/store/ddl.ts
2
+ import {
3
+ DbRefusal,
4
+ ENTITY_PLACEHOLDERS,
5
+ entityTable,
6
+ logMigrations,
7
+ projectionMigrations
8
+ } from "@geonosis/db";
9
+ import { headFields } from "../core/document.js";
10
+ var DEFAULT_DOCUMENT_TABLE = "documents";
11
+ var DEFAULT_ENTITY_COLUMN = "entity";
12
+ var DEFAULT_VERSION_COLUMN = "version";
13
+ var DEFAULT_TENANT_COLUMN = "tenant_id";
14
+ var DEFAULT_CREATED_AT_COLUMN = "created_at";
15
+ var DEFAULT_UPDATED_AT_COLUMN = "updated_at";
16
+ var DEFAULT_REVISIONS_TABLE = "document_revisions";
17
+ var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
18
+ var REVISION_KINDS = ["committed", "retired", "reinstated"];
19
+ var HEAD_FIELDS = Object.keys(headFields);
20
+ var snakeOf = (field) => field.replaceAll(/[A-Z]/g, (upper) => `_${upper.toLowerCase()}`);
21
+ var nameOf = (value, fallback) => value === undefined ? fallback : typeof value === "string" ? value : value.name;
22
+ var physicalColumnsOf = (columns) => {
23
+ const heads = Object.fromEntries(HEAD_FIELDS.map((field) => [
24
+ field,
25
+ nameOf(columns?.heads?.[field] ?? (field === "total" ? columns?.total : undefined), snakeOf(field))
26
+ ]));
27
+ return {
28
+ ...heads,
29
+ createdAt: nameOf(columns?.createdAt, DEFAULT_CREATED_AT_COLUMN),
30
+ entity: columns?.entity ?? DEFAULT_ENTITY_COLUMN,
31
+ tenant: nameOf(columns?.tenant, DEFAULT_TENANT_COLUMN),
32
+ updatedAt: nameOf(columns?.updatedAt, DEFAULT_UPDATED_AT_COLUMN)
33
+ };
34
+ };
35
+ var appendOnlyTables = (options = {}) => {
36
+ if (options.revisions === false)
37
+ return [];
38
+ return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
39
+ };
40
+ var quotedName = (name) => `"${name}"`;
41
+ var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
42
+ var documentRoleStatements = (appRole, options = {}) => {
43
+ if (typeof appRole !== "string" || appRole === "") {
44
+ throw new DbRefusal("documentRoleStatements needs an `appRole` — the name a consumer’s application connects as belongs to whoever runs the database, and one baked in here would be another repo’s");
45
+ }
46
+ const role = quotedName(appRole);
47
+ const on = (table) => options.schema === undefined ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
48
+ return appendOnlyTables(options).flatMap((table) => [
49
+ `revoke update, delete on ${on(table)} from ${role}`,
50
+ `grant select, insert on ${on(table)} to ${role}`
51
+ ]);
52
+ };
53
+ var DDL_TYPE_OF = { decimal: "numeric" };
54
+ var headIndexedColumns = (physical) => HEAD_FIELDS.map((field) => {
55
+ const type = DDL_TYPE_OF[headFields[field]];
56
+ return {
57
+ column: physical[field],
58
+ nullable: field !== "status",
59
+ ...type === undefined ? {} : { type }
60
+ };
61
+ });
62
+ var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
63
+ var walls = (options) => ({
64
+ ...options.freeze === undefined ? {} : { freeze: options.freeze },
65
+ ...options.names === undefined ? {} : { names: options.names },
66
+ ...options.schema === undefined ? {} : { schema: options.schema }
67
+ });
68
+ var revisionsMigrations = (options, physical) => {
69
+ if (options.revisions === false)
70
+ return [];
71
+ if (typeof options.appRole !== "string" || options.appRole === "") {
72
+ throw new DbRefusal("documentMigrations needs an `appRole` to render the log’s wall — the role a consumer’s application connects as belongs to whoever runs the database, and one baked in here would be another repo’s. Pass it, or opt out of the log entirely with `revisions: false`");
73
+ }
74
+ const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
75
+ const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
76
+ const [tableMigration, policies] = logMigrations({
77
+ appRole: options.appRole,
78
+ columns: { tenant: physical.tenant },
79
+ extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
80
+ key: [physical.entity, "ref", { column: "lineage", type: "integer" }],
81
+ ...walls(options),
82
+ settings: options.settings,
83
+ table
84
+ });
85
+ if (tableMigration === undefined || policies === undefined) {
86
+ throw new Error("logMigrations answered with fewer than the two migrations a log renders");
87
+ }
88
+ return [
89
+ { ...tableMigration, name: `0003_${table}.sql` },
90
+ { ...policies, name: `0004_${table}_policies.sql` }
91
+ ];
92
+ };
93
+ var documentMigrations = (options) => {
94
+ const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
95
+ const physical = physicalColumnsOf(options.columns);
96
+ const {
97
+ entity: _entity,
98
+ heads: _heads,
99
+ revisionKind: _revisionKind,
100
+ total: _total,
101
+ version,
102
+ ...restColumns
103
+ } = options.columns ?? {};
104
+ const [tableMigration, ...rest] = projectionMigrations({
105
+ carried: [{ column: "lineage", type: "integer not null default 1" }],
106
+ columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
107
+ constants: { [physical.entity]: "" },
108
+ indexed: headIndexedColumns(physical),
109
+ key: "number",
110
+ order: [{ column: "number" }],
111
+ ...walls(options),
112
+ settings: options.settings,
113
+ sortable: [
114
+ ...HEAD_FIELDS.map((field) => physical[field]),
115
+ physical.createdAt,
116
+ physical.updatedAt
117
+ ],
118
+ table
119
+ });
120
+ if (tableMigration === undefined) {
121
+ throw new Error("projectionMigrations answered with no table migration to append the listing index to");
122
+ }
123
+ const listingIndex = `create index if not exists ${quotedName(`${table}_${physical.entity}_${physical.issueDate}_idx`)} on ${quotedName(table)} (${quotedName(physical.entity)}, ${quotedName(physical.issueDate)})`;
124
+ return [
125
+ { ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
126
+ ...rest,
127
+ ...revisionsMigrations(options, physical)
128
+ ];
129
+ };
130
+ var TABLE_TYPE_OF = { decimal: "numeric" };
131
+ var documentTable = (options = {}) => {
132
+ const physical = physicalColumnsOf(options.columns);
133
+ const {
134
+ entity: _entity,
135
+ heads: _heads,
136
+ id,
137
+ revisionKind: _revisionKind,
138
+ total: _total,
139
+ version,
140
+ ...restColumns
141
+ } = options.columns ?? {};
142
+ const named = Object.fromEntries(Object.entries(restColumns).map(([column, held]) => [column, nameOf(held, column)]));
143
+ return entityTable({
144
+ columns: { ...named, version: nameOf(version, DEFAULT_VERSION_COLUMN) },
145
+ constants: [physical.entity],
146
+ extra: {
147
+ ...Object.fromEntries(HEAD_FIELDS.map((field) => [
148
+ physical[field],
149
+ {
150
+ nullable: field !== "status",
151
+ type: TABLE_TYPE_OF[headFields[field]] ?? "text"
152
+ }
153
+ ])),
154
+ hash: "text",
155
+ lineage: "integer"
156
+ },
157
+ key: "number",
158
+ ...options.schema === undefined ? {} : { schema: options.schema },
159
+ ...options.settings === undefined ? {} : { settings: options.settings },
160
+ ...id === undefined ? {} : { surrogate: nameOf(id.column, "id") },
161
+ table: options.table ?? DEFAULT_DOCUMENT_TABLE
162
+ });
163
+ };
164
+ export {
165
+ DEFAULT_DOCUMENT_TABLE,
166
+ DEFAULT_REVISIONS_TABLE,
167
+ DEFAULT_REVISION_KIND_COLUMN,
168
+ ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
169
+ HEAD_FIELDS,
170
+ appendOnlyTables,
171
+ documentMigrations,
172
+ documentRoleStatements,
173
+ documentTable,
174
+ physicalColumnsOf
175
+ };
@@ -0,0 +1,50 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
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 });
13
+ if (from && typeof from === "object" || typeof from === "function") {
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
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
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)
36
+ });
37
+ };
38
+
39
+ // src/store/hash.ts
40
+ var exports_hash = {};
41
+ __export(exports_hash, {
42
+ hashOf: () => hashOf
43
+ });
44
+ module.exports = __toCommonJS(exports_hash);
45
+ var import_canonical = require("../core/canonical.cjs");
46
+ var hashOf = async (payload) => {
47
+ const bytes = new TextEncoder().encode(JSON.stringify(import_canonical.canonicalOf(payload)));
48
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
49
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
50
+ };
@@ -0,0 +1,2 @@
1
+ /** sha256 hex over the canonical JSON of `payload` — no whitespace, keys sorted recursively. */
2
+ export declare const hashOf: (payload: unknown) => Promise<string>;
@@ -0,0 +1,2 @@
1
+ /** sha256 hex over the canonical JSON of `payload` — no whitespace, keys sorted recursively. */
2
+ export declare const hashOf: (payload: unknown) => Promise<string>;
@@ -0,0 +1,10 @@
1
+ // src/store/hash.ts
2
+ import { canonicalOf } from "../core/canonical.js";
3
+ var hashOf = async (payload) => {
4
+ const bytes = new TextEncoder().encode(JSON.stringify(canonicalOf(payload)));
5
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
6
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
7
+ };
8
+ export {
9
+ hashOf
10
+ };