@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/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # @geonosis/document
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d90986b: Every refusal the document workflows throw is named. `DocumentNotFound` (entity, ref),
8
+ `DocumentTaken` (entity, ref), `NumberingRefused` (entity, mode `given` | `counter`),
9
+ `TransitionRefused` (entity, ref, from, to), `DocumentNotRemovable` (entity) and
10
+ `ConversionRefused` (entity, ref) are `TaggedError`s exported from `./workflows` with their tags
11
+ and a `DocumentRefusal` union; the messages are the sentences they always were. The engine wraps
12
+ what a body throws in `RunFailedError` with the refusal as `cause`, so a host reads the name off
13
+ the cause and answers 404, 409 or 400 — during.day's `/v1` answered 500 to a missing ref, with the
14
+ sentence inside the problem document, because a plain `Error` is all `problemOf` had to map.
15
+ - d90986b: `heads` carries the record's clocks: `HeadColumn` admits `createdAt` and `updatedAt` beside the
16
+ business head, the entity and the number, and `HeadRow` types them as instants. The store already
17
+ projected them — `where` and `order` took the clocks — but the column type did not, so a consumer
18
+ bucketing documents by the month they were created read every instance through `listAll`
19
+ (during.day `documents.ts:350`). A type fixture pins it and the Postgres exam reads them back.
20
+ - c8c5d51: `documentWorkflows(entity, { effects, ports })` at `@geonosis/document/workflows` — T3, the org
21
+ workflows over the engine, one body per Document: `create`, `save`, `setStatus`, `remove`, `send`
22
+ (durable), `convert`, `duplicate`, `share`, each named for the entity. A host decides
23
+ `effects.announce(fact)` — the product's events off a `DocumentFact` — and answers three ports,
24
+ `door`, `link` and `mail` (`Result<void, MailUndelivered>` from `better-result`); `beforeCreate`,
25
+ `conversion`, the mail words, `counter`, `actor`, `guard`, `now` and `seed` default, and a
26
+ counter-numbered entity or a template on a host that declares neither is refused by name. The
27
+ factory makes the two steps that reach the outside world, so the durable-body law holds on every
28
+ host. A third entry, like `./store`, so the core stays off every floor and browser-safe. The
29
+ Standard Schema builders the surface wrote for itself move to the core (`objectOf`, `enumOf`,
30
+ `optional`, `nullable`, `arrayOf`, `merge`, the scalars, `validate`) and `SchemaAdapter` is the
31
+ adapter's name (`SurfaceSchemaAdapter` stays as an alias). `@geonosis/workflows` and
32
+ `better-result` join the package's dependencies. The plugin's `document-sagas-are-generic` and
33
+ `documents-share-one-table` no longer carry `floor: pending`: the store shipped at 0.4 and the
34
+ workflows ship here. `documentIdentifiers` spells every identifier as a literal type off the name it was given (`CamelOf`, `DocumentIdentifiers`), so a consumer indexes a typed router map by the camel name without a cast. `documentEntities(map).keyed(pick)` answers one value per entity under its name, total by construction.
35
+
36
+ ### Patch Changes
37
+
38
+ - Updated dependencies [d90986b]
39
+ - Updated dependencies [d90986b]
40
+ - @geonosis/db@0.12.0
41
+
42
+ ## 0.6.0
43
+
44
+ ### Minor Changes
45
+
46
+ - db89b0b: The core entry (`@geonosis/document`) reaches no floor: `documentStore`, `documentMigrations`,
47
+ `documentTable`, `appendOnlyTables`, `documentRoleStatements`, `HEAD_FIELDS`, `physicalColumnsOf`,
48
+ the `DEFAULT_*` names and `documentSurface` move to `@geonosis/document/store`. A consumer's DOMAIN
49
+ package imports the core for `Document.extend`/`documentEntities` and is bundled for browsers and
50
+ edge runtimes, where `@geonosis/db`'s `async_hooks`, `fs/promises` and `pg` do not exist — measured
51
+ on during.day, whose dashboard stopped compiling its sign-in page (#463). Migration: a server
52
+ package that builds the store or renders the DDL imports those names from `@geonosis/document/store`;
53
+ everything else is unchanged.
54
+
55
+ ### Patch Changes
56
+
57
+ - db89b0b: The core entry carries no node builtin: `hashOf` (sha256 over `node:crypto`) moves to
58
+ `@geonosis/document/store` beside the store that writes the chain; `canonicalOf` stays on the core.
59
+ The pre-release review of 0.6.0 measured the core still failing a browser resolve on `crypto`;
60
+ `@geonosis/document` now sits in the repo's `BROWSER_SAFE` guard, which bundle-resolves the built
61
+ core entry for a browser on every run.
62
+
3
63
  ## 0.5.0
4
64
 
5
65
  ### Minor Changes
package/README.md CHANGED
@@ -70,6 +70,11 @@ keyed by name, and:
70
70
  - `instance(name, parts)` stamps a document with the entity name it was minted for; `named(name)`
71
71
  hands back one entity's own definition.
72
72
 
73
+ `registry.keyed(pick)` is the fold a consumer keys a map by: one answer per entity under the
74
+ name its rows carry, total by construction — `registry.keyed((entity, name) => …)` gives
75
+ `{ [name]: … }` over every entity the registry holds, so no layer writes `Object.fromEntries`
76
+ over `names` and casts the result.
77
+
73
78
  ## Per-entity body versioning
74
79
 
75
80
  `documentBodyVersioning(definition)` returns `{ migrate, stamp }`, bound to ONE entity's own
@@ -88,10 +93,16 @@ nothing.
88
93
  ## `documentIdentifiers`
89
94
 
90
95
  `documentIdentifiers(name)` derives every spelling a surface needs from one hyphenated entity name:
91
- `camel`, `pascal`, `pluralCamel`, `snake`, `snakePlural`, `path`.
96
+ `camel`, `pascal`, `pluralCamel`, `snake`, `snakePlural`, `path` — each a literal type off the name
97
+ (`documentIdentifiers('purchase-order').camel` is `'purchaseOrder'`), so a consumer keys a router
98
+ map or a path table by them with no cast.
92
99
 
93
100
  ## Store
94
101
 
102
+ `documentStore`, the DDL and the surface are the `@geonosis/document/store` entry — a server's
103
+ import. The main entry is the core alone and reaches no floor, so a domain package bundled for a
104
+ browser or an edge runtime carries neither drizzle nor pg (#463).
105
+
95
106
  `documentStore({ registry, seam, table?, schema?, columns?, revisions?, archive? })` is ONE table
96
107
  for every document entity the registry holds — never one table per entity — plus the append-only
97
108
  log beside it, and it spells no SQL: the log is `@geonosis/db`'s `defineLog` keyed by `(entity,
@@ -227,14 +238,46 @@ schemas of whatever library the caller's `object`/`union`/`enum` wrap them in
227
238
  place it enters a repo composing this domain, never a dependency of `@geonosis/document` itself
228
239
  (`src/no-schema-library-at-runtime.test.ts` holds the built door to that).
229
240
 
241
+ ## Workflows
242
+
243
+ `documentWorkflows(entity, { effects, ports })` is the `@geonosis/document/workflows` entry — a
244
+ server's import, like `./store`, because it reaches `@geonosis/workflows`. It mints the whole of
245
+ what a Document can do for one entity, from one body: `create` (guarded, seeded, numbered — the
246
+ `ref` given by the caller or minted from the entity's counter off the series the draft names),
247
+ `save` (merged through the entity), `setStatus` (guarded by `canTransition`), `remove` (refused
248
+ when the entity is not `removable`), `send` (durable: the share link, the paper marked `onSent`,
249
+ the mail — in that order, so a mail that never goes reverses the move), `convert` (into the entity
250
+ `effects.conversion` names, at the same ref, the source marked once), `duplicate` (a copy under
251
+ `targetRef` or a minted number) and `share` (a link). Every workflow is named for the entity
252
+ (`invoice.create`, `purchase-order.send`, `memo.set-status`); `document-sagas-are-generic` refuses
253
+ the literal spelling anywhere else. Inputs are Standard Schemas built in the core (`objectOf`,
254
+ `enumOf`, `nonEmptyString`, `positiveInt`, `optional`) over the entity's own `draft` and
255
+ `incoming`; the wire's copy in a consumer's own library stays the surface's business.
256
+
257
+ A host writes only what the kit cannot decide for it. `effects.announce(fact)` is the one required
258
+ decision: a `DocumentFact` (`created`, `saved`, `moved`, `deleted`, `sent`, `shared`, `converted`)
259
+ becomes the product's own events, one or several, or `null`. `beforeCreate`, `conversion` and the
260
+ mail words are optional — absent, nothing runs before the write, nothing converts, and the mail
261
+ reads `<Noun> <number> is ready for you to read.` off the entity's noun. `ports` names three the
262
+ host alone can answer — `door(ctx, entity)` to a store door bound to the run's organisation,
263
+ `link`, and `mail` (answering `Result<void, MailUndelivered>` from `better-result`) — and the rest
264
+ default: `counter` is asked for only by an entity numbered from one and refused by name when
265
+ absent, `actor` reads a string `actor` off the context or names the system, `guard` allows, `now`
266
+ is the clock, `seed` refuses a template. Ports are plain functions: the factory makes the steps
267
+ (`create-share-link`, `send-email`) of the two that reach the outside world, so a replayed durable
268
+ body answers from the journal on every host, and a door bound through `stepsOf` journals every
269
+ read and write of its own. `src/workflows/document-workflows.test.ts` runs every workflow over an
270
+ in-memory door and the memory journal, `send` through the durable door, and one entity on nothing
271
+ but `announce` and the three required ports.
272
+
230
273
  ## What does not exist yet
231
274
 
232
275
  `src/store/` ships the commits (`commit`, `retire`, `succeed`, `reinstate`, `get`, `at`, `asOf`,
233
276
  `history`, `verify`, `rebuild`, `heads`, `aggregate`) and the archive/timestamp ports declared, not
234
277
  mirrored; it ships no search projection yet. `upsert` and `revisions` are GONE (replaced by
235
- `commit`; `history`). `src/surface/` ships the table above; its saga rows stay PENDING until
236
- `src/workflows/` (the org's engine, the only internal folder that may import it — the archive
237
- mirror lands there too) lands and binds them. `src/contract/` (a layer the surface table already
278
+ `commit`; `history`). `src/surface/` ships the table above; its saga rows still say `pending: 'T3'` because a row's
279
+ `call(handle, params)` has no runtime to open a run with — binding them to `documentWorkflows` is
280
+ #512, and the archive mirror still lands in `src/workflows/`. `src/contract/` (a layer the surface table already
238
281
  supersedes — #403), `src/ui/` (the view axis) and `src/conformance/` (the exam a consumer runs
239
282
  against their own provider) are later tickets — the internal layout is declared now (and held by
240
283
  `layer-walls`) so each lands inside the wall already drawn for it.
@@ -242,7 +285,7 @@ against their own provider) are later tickets — the internal layout is declare
242
285
  ## One door, and what holds it
243
286
 
244
287
  `sideEffects: false`; inside the package the in-package wall is `layer-walls`, planted in
245
- `src/__fixtures__/walls/` and proved through the real binary in `src/walls.test.ts` — the core may
288
+ `src/__fixtures__/walls/` and proved through the real binary in `src/walls.bin.test.ts` — the core may
246
289
  reach `@geonosis/conformance` and nothing else, the store may reach `@geonosis/db` and
247
290
  `@geonosis/conformance` and nothing else, `src/surface/` may reach the core, the store and the
248
291
  workflows layer and nothing lower, and only `src/workflows/` may reach `@geonosis/workflows`
@@ -0,0 +1,168 @@
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 nullable = 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 (nullable && 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
+ keyed: (pick) => Object.fromEntries(names.map((name) => [name, pick(map[name], name)])),
142
+ named: (name) => map[name],
143
+ names,
144
+ views: distinctBy((entity) => entity.view)
145
+ };
146
+ };
147
+
148
+ // src/core/canonical.ts
149
+ var canonicalOf = (input) => {
150
+ if (input === null || typeof input !== "object") return input;
151
+ if (Array.isArray(input)) return input.map(canonicalOf);
152
+ return Object.fromEntries(
153
+ Object.entries(input).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, held]) => [key, canonicalOf(held)])
154
+ );
155
+ };
156
+
157
+ export {
158
+ BODY_VERSION_KEY,
159
+ migrateBody,
160
+ stampBody,
161
+ documentBodyVersioning,
162
+ fieldPatterns,
163
+ validatorOf,
164
+ headFields,
165
+ Document,
166
+ documentEntities,
167
+ canonicalOf
168
+ };
@@ -0,0 +1,171 @@
1
+ // src/core/schema.ts
2
+ var VENDOR = "geonosis-document";
3
+ var isString = (value) => typeof value === "string";
4
+ var isNumber = (value) => typeof value === "number";
5
+ var scalar = (test, message) => ({
6
+ "~standard": {
7
+ validate: (input) => test(input) ? { value: input } : { issues: [{ message }] },
8
+ vendor: VENDOR,
9
+ version: 1
10
+ }
11
+ });
12
+ var stringSchema = scalar(isString, "expected a string");
13
+ var numberSchema = scalar(isNumber, "expected a number");
14
+ var booleanSchema = scalar(
15
+ (value) => typeof value === "boolean",
16
+ "expected a boolean"
17
+ );
18
+ var literalOf = (literal) => scalar(
19
+ (value) => value === literal,
20
+ `expected exactly ${JSON.stringify(literal)}`
21
+ );
22
+ var unknownSchema = {
23
+ "~standard": { validate: (input) => ({ value: input }), vendor: VENDOR, version: 1 }
24
+ };
25
+ var syncResult = (schema, input) => {
26
+ const result = schema["~standard"].validate(input);
27
+ if (result instanceof Promise) {
28
+ throw new Error(
29
+ "a document surface schema validates synchronously; an async Standard Schema cannot back a row"
30
+ );
31
+ }
32
+ return result;
33
+ };
34
+ var optional = (inner) => ({
35
+ "~standard": {
36
+ validate: (input) => input === void 0 ? { value: void 0 } : syncResult(inner, input),
37
+ vendor: VENDOR,
38
+ version: 1
39
+ }
40
+ });
41
+ var nullable = (inner) => ({
42
+ "~standard": {
43
+ validate: (input) => input === null ? { value: null } : syncResult(inner, input),
44
+ vendor: VENDOR,
45
+ version: 1
46
+ }
47
+ });
48
+ var arrayOf = (item) => ({
49
+ "~standard": {
50
+ validate: (input) => {
51
+ if (!Array.isArray(input)) return { issues: [{ message: "expected an array" }] };
52
+ const value = [];
53
+ const issues = [];
54
+ input.forEach((one, at) => {
55
+ const result = syncResult(item, one);
56
+ if (result.issues !== void 0) {
57
+ issues.push(
58
+ ...result.issues.map((issue) => ({ ...issue, path: [at, ...issue.path ?? []] }))
59
+ );
60
+ } else {
61
+ value.push(result.value);
62
+ }
63
+ });
64
+ return issues.length > 0 ? { issues } : { value };
65
+ },
66
+ vendor: VENDOR,
67
+ version: 1
68
+ }
69
+ });
70
+ var merge = (schemas) => ({
71
+ "~standard": {
72
+ validate: (input) => {
73
+ let value = {};
74
+ const issues = [];
75
+ for (const schema of schemas) {
76
+ const result = syncResult(schema, input);
77
+ if (result.issues !== void 0) issues.push(...result.issues);
78
+ else value = { ...value, ...result.value };
79
+ }
80
+ return issues.length > 0 ? { issues } : { value };
81
+ },
82
+ vendor: VENDOR,
83
+ version: 1
84
+ }
85
+ });
86
+ var nonEmptyString = scalar(
87
+ (value) => typeof value === "string" && value.length > 0,
88
+ "expected a non-empty string"
89
+ );
90
+ var positiveInt = scalar(
91
+ (value) => Number.isInteger(value) && value > 0,
92
+ "expected a positive integer"
93
+ );
94
+ var validate = async (schema, input) => {
95
+ const result = await schema["~standard"].validate(input);
96
+ if (result.issues !== void 0) {
97
+ throw new Error(
98
+ result.issues.map((issue) => {
99
+ const path = (issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
100
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
101
+ }).join("; ")
102
+ );
103
+ }
104
+ return result.value;
105
+ };
106
+ var enumOf = (values) => scalar(
107
+ (value) => typeof value === "string" && values.includes(value),
108
+ `expected one of ${values.map((value) => JSON.stringify(value)).join(", ")}`
109
+ );
110
+ var settle = (fields) => {
111
+ const value = {};
112
+ const issues = [];
113
+ for (const [key, result] of fields) {
114
+ if (result.issues !== void 0) {
115
+ issues.push(
116
+ ...result.issues.map((issue) => ({ ...issue, path: [key, ...issue.path ?? []] }))
117
+ );
118
+ } else if (result.value !== void 0) {
119
+ value[key] = result.value;
120
+ }
121
+ }
122
+ return issues.length > 0 ? { issues } : { value };
123
+ };
124
+ var objectOf = (shape) => ({
125
+ "~standard": {
126
+ validate: (input) => {
127
+ if (input === null || typeof input !== "object") {
128
+ return { issues: [{ message: "expected an object" }] };
129
+ }
130
+ const record = input;
131
+ const fields = Object.entries(shape).map(
132
+ ([key, schema]) => [key, schema["~standard"].validate(record[key])]
133
+ );
134
+ return fields.some(([, result]) => result instanceof Promise) ? Promise.all(fields.map(async ([key, result]) => [key, await result])).then(
135
+ settle
136
+ ) : settle(fields);
137
+ },
138
+ vendor: VENDOR,
139
+ version: 1
140
+ }
141
+ });
142
+
143
+ // src/core/actor.ts
144
+ var SYSTEM_PREFIX = "system:";
145
+ var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
146
+ var isSystemActor = (actor) => actor.startsWith(SYSTEM_PREFIX);
147
+
148
+ // src/core/status.ts
149
+ var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
150
+ var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
151
+
152
+ export {
153
+ stringSchema,
154
+ numberSchema,
155
+ booleanSchema,
156
+ literalOf,
157
+ unknownSchema,
158
+ optional,
159
+ nullable,
160
+ arrayOf,
161
+ merge,
162
+ nonEmptyString,
163
+ positiveInt,
164
+ validate,
165
+ enumOf,
166
+ objectOf,
167
+ systemActor,
168
+ isSystemActor,
169
+ canTransition,
170
+ isTerminalStatus
171
+ };