@geonosis/document 0.6.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,44 @@
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
+
3
42
  ## 0.6.0
4
43
 
5
44
  ### 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,7 +93,9 @@ 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
 
@@ -231,14 +238,46 @@ schemas of whatever library the caller's `object`/`union`/`enum` wrap them in
231
238
  place it enters a repo composing this domain, never a dependency of `@geonosis/document` itself
232
239
  (`src/no-schema-library-at-runtime.test.ts` holds the built door to that).
233
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
+
234
273
  ## What does not exist yet
235
274
 
236
275
  `src/store/` ships the commits (`commit`, `retire`, `succeed`, `reinstate`, `get`, `at`, `asOf`,
237
276
  `history`, `verify`, `rebuild`, `heads`, `aggregate`) and the archive/timestamp ports declared, not
238
277
  mirrored; it ships no search projection yet. `upsert` and `revisions` are GONE (replaced by
239
- `commit`; `history`). `src/surface/` ships the table above; its saga rows stay PENDING until
240
- `src/workflows/` (the org's engine, the only internal folder that may import it — the archive
241
- 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
242
281
  supersedes — #403), `src/ui/` (the view axis) and `src/conformance/` (the exam a consumer runs
243
282
  against their own provider) are later tickets — the internal layout is declared now (and held by
244
283
  `layer-walls`) so each lands inside the wall already drawn for it.
@@ -246,7 +285,7 @@ against their own provider) are later tickets — the internal layout is declare
246
285
  ## One door, and what holds it
247
286
 
248
287
  `sideEffects: false`; inside the package the in-package wall is `layer-walls`, planted in
249
- `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
250
289
  reach `@geonosis/conformance` and nothing else, the store may reach `@geonosis/db` and
251
290
  `@geonosis/conformance` and nothing else, `src/surface/` may reach the core, the store and the
252
291
  workflows layer and nothing lower, and only `src/workflows/` may reach `@geonosis/workflows`
@@ -138,17 +138,13 @@ var documentEntities = (map) => {
138
138
  entities: map,
139
139
  fold,
140
140
  instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
141
+ keyed: (pick) => Object.fromEntries(names.map((name) => [name, pick(map[name], name)])),
141
142
  named: (name) => map[name],
142
143
  names,
143
144
  views: distinctBy((entity) => entity.view)
144
145
  };
145
146
  };
146
147
 
147
- // src/core/actor.ts
148
- var SYSTEM_PREFIX = "system:";
149
- var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
150
- var isSystemActor = (actor) => actor.startsWith(SYSTEM_PREFIX);
151
-
152
148
  // src/core/canonical.ts
153
149
  var canonicalOf = (input) => {
154
150
  if (input === null || typeof input !== "object") return input;
@@ -158,10 +154,6 @@ var canonicalOf = (input) => {
158
154
  );
159
155
  };
160
156
 
161
- // src/core/status.ts
162
- var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
163
- var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
164
-
165
157
  export {
166
158
  BODY_VERSION_KEY,
167
159
  migrateBody,
@@ -172,9 +164,5 @@ export {
172
164
  headFields,
173
165
  Document,
174
166
  documentEntities,
175
- systemActor,
176
- isSystemActor,
177
- canonicalOf,
178
- canTransition,
179
- isTerminalStatus
167
+ canonicalOf
180
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
+ };
@@ -195,39 +195,11 @@ declare const documentEntities: <Map extends Readonly<Record<string, AnyDocument
195
195
  instance: <Name extends keyof Map & string>(name: Name, parts: Omit<InstanceOf<Map[Name]>, "entity" | "body"> & {
196
196
  body: unknown;
197
197
  }) => DocumentInstance<Name, InstanceOf<Map[Name]>["body"]>;
198
+ /** One answer per entity, keyed by the name its rows carry — total by construction. */
199
+ keyed: <Result>(pick: (entity: Map[keyof Map], name: keyof Map & string) => Result) => { [Name in keyof Map & string]: Result; };
198
200
  named: <Name extends keyof Map & string>(name: Name) => Map[Name];
199
201
  names: readonly (keyof Map & string)[];
200
202
  views: StandardSchemaV1[];
201
203
  };
202
204
 
203
- /**
204
- * The archive's own key convention: `<tenant>/<entity>/<lineage>/<version>.json` — one object per
205
- * revision, named so a lineage's own history sits together and a new lineage (`succeed`) never
206
- * collides with the one it replaced.
207
- */
208
- type ArchivePort = {
209
- head: (key: string) => Promise<{
210
- hash: string;
211
- } | null>;
212
- put: (key: string, bytes: Uint8Array, meta: {
213
- hash: string;
214
- immutable: true;
215
- }) => Promise<void>;
216
- };
217
- /** A trusted third party's timestamp over a hash — never implemented here, only declared. */
218
- type TimestampPort = {
219
- stamp: (hash: string) => Promise<{
220
- at: number;
221
- token: Uint8Array;
222
- }>;
223
- };
224
- type LinkVerifierPort = {
225
- verify: (token: string) => Promise<{
226
- entity: string;
227
- exp: number;
228
- org: string;
229
- ref: string;
230
- } | null>;
231
- };
232
-
233
- export { type AnyDocumentEntity as A, BODY_VERSION_KEY as B, type CardOf as C, Document as D, type FieldKind as F, type IncomingOf as I, type LinkVerifierPort as L, type NameOf as N, type StatusOf as S, type TimestampPort as T, type ViewOf as V, type ArchivePort as a, type BodyOf as b, type DocumentBodyMigrations as c, type DocumentBodyVersion as d, type DocumentDefinition as e, type DocumentEntity as f, type DocumentHead as g, type DocumentInstance as h, type DocumentNumbering as i, type DocumentRecord as j, type DocumentStatusMachine as k, type DraftOf as l, type InstanceOf as m, canTransition as n, documentBodyVersioning as o, documentEntities as p, fieldPatterns as q, isTerminalStatus as r, migrateBody as s, stampBody as t, validatorOf as v };
205
+ export { type AnyDocumentEntity as A, BODY_VERSION_KEY as B, type CardOf as C, Document as D, type FieldKind as F, type IncomingOf as I, type NameOf as N, type StatusOf as S, type ViewOf as V, type BodyOf as a, type DocumentBodyMigrations as b, type DocumentBodyVersion as c, type DocumentDefinition as d, type DocumentEntity as e, type DocumentHead as f, type DocumentInstance as g, type DocumentNumbering as h, type DocumentRecord as i, type DocumentStatusMachine as j, type DraftOf as k, type InstanceOf as l, canTransition as m, documentBodyVersioning as n, documentEntities as o, fieldPatterns as p, isTerminalStatus as q, migrateBody as r, stampBody as s, validatorOf as v };
@@ -195,39 +195,11 @@ declare const documentEntities: <Map extends Readonly<Record<string, AnyDocument
195
195
  instance: <Name extends keyof Map & string>(name: Name, parts: Omit<InstanceOf<Map[Name]>, "entity" | "body"> & {
196
196
  body: unknown;
197
197
  }) => DocumentInstance<Name, InstanceOf<Map[Name]>["body"]>;
198
+ /** One answer per entity, keyed by the name its rows carry — total by construction. */
199
+ keyed: <Result>(pick: (entity: Map[keyof Map], name: keyof Map & string) => Result) => { [Name in keyof Map & string]: Result; };
198
200
  named: <Name extends keyof Map & string>(name: Name) => Map[Name];
199
201
  names: readonly (keyof Map & string)[];
200
202
  views: StandardSchemaV1[];
201
203
  };
202
204
 
203
- /**
204
- * The archive's own key convention: `<tenant>/<entity>/<lineage>/<version>.json` — one object per
205
- * revision, named so a lineage's own history sits together and a new lineage (`succeed`) never
206
- * collides with the one it replaced.
207
- */
208
- type ArchivePort = {
209
- head: (key: string) => Promise<{
210
- hash: string;
211
- } | null>;
212
- put: (key: string, bytes: Uint8Array, meta: {
213
- hash: string;
214
- immutable: true;
215
- }) => Promise<void>;
216
- };
217
- /** A trusted third party's timestamp over a hash — never implemented here, only declared. */
218
- type TimestampPort = {
219
- stamp: (hash: string) => Promise<{
220
- at: number;
221
- token: Uint8Array;
222
- }>;
223
- };
224
- type LinkVerifierPort = {
225
- verify: (token: string) => Promise<{
226
- entity: string;
227
- exp: number;
228
- org: string;
229
- ref: string;
230
- } | null>;
231
- };
232
-
233
- export { type AnyDocumentEntity as A, BODY_VERSION_KEY as B, type CardOf as C, Document as D, type FieldKind as F, type IncomingOf as I, type LinkVerifierPort as L, type NameOf as N, type StatusOf as S, type TimestampPort as T, type ViewOf as V, type ArchivePort as a, type BodyOf as b, type DocumentBodyMigrations as c, type DocumentBodyVersion as d, type DocumentDefinition as e, type DocumentEntity as f, type DocumentHead as g, type DocumentInstance as h, type DocumentNumbering as i, type DocumentRecord as j, type DocumentStatusMachine as k, type DraftOf as l, type InstanceOf as m, canTransition as n, documentBodyVersioning as o, documentEntities as p, fieldPatterns as q, isTerminalStatus as r, migrateBody as s, stampBody as t, validatorOf as v };
205
+ export { type AnyDocumentEntity as A, BODY_VERSION_KEY as B, type CardOf as C, Document as D, type FieldKind as F, type IncomingOf as I, type NameOf as N, type StatusOf as S, type ViewOf as V, type BodyOf as a, type DocumentBodyMigrations as b, type DocumentBodyVersion as c, type DocumentDefinition as d, type DocumentEntity as e, type DocumentHead as f, type DocumentInstance as g, type DocumentNumbering as h, type DocumentRecord as i, type DocumentStatusMachine as j, type DraftOf as k, type InstanceOf as l, canTransition as m, documentBodyVersioning as n, documentEntities as o, fieldPatterns as p, isTerminalStatus as q, migrateBody as r, stampBody as s, validatorOf as v };
package/dist/index.cjs CHANGED
@@ -22,17 +22,31 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  BODY_VERSION_KEY: () => BODY_VERSION_KEY,
24
24
  Document: () => Document,
25
+ arrayOf: () => arrayOf,
26
+ booleanSchema: () => booleanSchema,
25
27
  canTransition: () => canTransition,
26
28
  canonicalOf: () => canonicalOf,
27
29
  documentBodyVersioning: () => documentBodyVersioning,
28
30
  documentEntities: () => documentEntities,
29
31
  documentIdentifiers: () => documentIdentifiers,
32
+ enumOf: () => enumOf,
30
33
  fieldPatterns: () => fieldPatterns,
31
34
  isSystemActor: () => isSystemActor,
32
35
  isTerminalStatus: () => isTerminalStatus,
36
+ literalOf: () => literalOf,
37
+ merge: () => merge,
33
38
  migrateBody: () => migrateBody,
39
+ nonEmptyString: () => nonEmptyString,
40
+ nullable: () => nullable,
41
+ numberSchema: () => numberSchema,
42
+ objectOf: () => objectOf,
43
+ optional: () => optional,
44
+ positiveInt: () => positiveInt,
34
45
  stampBody: () => stampBody,
46
+ stringSchema: () => stringSchema,
35
47
  systemActor: () => systemActor,
48
+ unknownSchema: () => unknownSchema,
49
+ validate: () => validate,
36
50
  validatorOf: () => validatorOf
37
51
  });
38
52
  module.exports = __toCommonJS(index_exports);
@@ -90,7 +104,7 @@ var FIELD_CHECKS = {
90
104
  text: { message: "a string", test: (value) => typeof value === "string" }
91
105
  };
92
106
  var validatorOf = (fields, options) => {
93
- const nullable = options?.nullable ?? false;
107
+ const nullable2 = options?.nullable ?? false;
94
108
  return {
95
109
  "~standard": {
96
110
  validate: (input) => {
@@ -103,7 +117,7 @@ var validatorOf = (fields, options) => {
103
117
  for (const [key, kind] of Object.entries(fields)) {
104
118
  const held = record[key];
105
119
  value[key] = held;
106
- if (nullable && held === null) continue;
120
+ if (nullable2 && held === null) continue;
107
121
  if (!FIELD_CHECKS[kind].test(held)) {
108
122
  issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
109
123
  }
@@ -177,12 +191,155 @@ var documentEntities = (map) => {
177
191
  entities: map,
178
192
  fold,
179
193
  instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
194
+ keyed: (pick) => Object.fromEntries(names.map((name) => [name, pick(map[name], name)])),
180
195
  named: (name) => map[name],
181
196
  names,
182
197
  views: distinctBy((entity) => entity.view)
183
198
  };
184
199
  };
185
200
 
201
+ // src/core/schema.ts
202
+ var VENDOR = "geonosis-document";
203
+ var isString = (value) => typeof value === "string";
204
+ var isNumber = (value) => typeof value === "number";
205
+ var scalar = (test, message) => ({
206
+ "~standard": {
207
+ validate: (input) => test(input) ? { value: input } : { issues: [{ message }] },
208
+ vendor: VENDOR,
209
+ version: 1
210
+ }
211
+ });
212
+ var stringSchema = scalar(isString, "expected a string");
213
+ var numberSchema = scalar(isNumber, "expected a number");
214
+ var booleanSchema = scalar(
215
+ (value) => typeof value === "boolean",
216
+ "expected a boolean"
217
+ );
218
+ var literalOf = (literal) => scalar(
219
+ (value) => value === literal,
220
+ `expected exactly ${JSON.stringify(literal)}`
221
+ );
222
+ var unknownSchema = {
223
+ "~standard": { validate: (input) => ({ value: input }), vendor: VENDOR, version: 1 }
224
+ };
225
+ var syncResult = (schema, input) => {
226
+ const result = schema["~standard"].validate(input);
227
+ if (result instanceof Promise) {
228
+ throw new Error(
229
+ "a document surface schema validates synchronously; an async Standard Schema cannot back a row"
230
+ );
231
+ }
232
+ return result;
233
+ };
234
+ var optional = (inner) => ({
235
+ "~standard": {
236
+ validate: (input) => input === void 0 ? { value: void 0 } : syncResult(inner, input),
237
+ vendor: VENDOR,
238
+ version: 1
239
+ }
240
+ });
241
+ var nullable = (inner) => ({
242
+ "~standard": {
243
+ validate: (input) => input === null ? { value: null } : syncResult(inner, input),
244
+ vendor: VENDOR,
245
+ version: 1
246
+ }
247
+ });
248
+ var arrayOf = (item) => ({
249
+ "~standard": {
250
+ validate: (input) => {
251
+ if (!Array.isArray(input)) return { issues: [{ message: "expected an array" }] };
252
+ const value = [];
253
+ const issues = [];
254
+ input.forEach((one, at) => {
255
+ const result = syncResult(item, one);
256
+ if (result.issues !== void 0) {
257
+ issues.push(
258
+ ...result.issues.map((issue) => ({ ...issue, path: [at, ...issue.path ?? []] }))
259
+ );
260
+ } else {
261
+ value.push(result.value);
262
+ }
263
+ });
264
+ return issues.length > 0 ? { issues } : { value };
265
+ },
266
+ vendor: VENDOR,
267
+ version: 1
268
+ }
269
+ });
270
+ var merge = (schemas) => ({
271
+ "~standard": {
272
+ validate: (input) => {
273
+ let value = {};
274
+ const issues = [];
275
+ for (const schema of schemas) {
276
+ const result = syncResult(schema, input);
277
+ if (result.issues !== void 0) issues.push(...result.issues);
278
+ else value = { ...value, ...result.value };
279
+ }
280
+ return issues.length > 0 ? { issues } : { value };
281
+ },
282
+ vendor: VENDOR,
283
+ version: 1
284
+ }
285
+ });
286
+ var nonEmptyString = scalar(
287
+ (value) => typeof value === "string" && value.length > 0,
288
+ "expected a non-empty string"
289
+ );
290
+ var positiveInt = scalar(
291
+ (value) => Number.isInteger(value) && value > 0,
292
+ "expected a positive integer"
293
+ );
294
+ var validate = async (schema, input) => {
295
+ const result = await schema["~standard"].validate(input);
296
+ if (result.issues !== void 0) {
297
+ throw new Error(
298
+ result.issues.map((issue) => {
299
+ const path = (issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
300
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
301
+ }).join("; ")
302
+ );
303
+ }
304
+ return result.value;
305
+ };
306
+ var enumOf = (values) => scalar(
307
+ (value) => typeof value === "string" && values.includes(value),
308
+ `expected one of ${values.map((value) => JSON.stringify(value)).join(", ")}`
309
+ );
310
+ var settle = (fields) => {
311
+ const value = {};
312
+ const issues = [];
313
+ for (const [key, result] of fields) {
314
+ if (result.issues !== void 0) {
315
+ issues.push(
316
+ ...result.issues.map((issue) => ({ ...issue, path: [key, ...issue.path ?? []] }))
317
+ );
318
+ } else if (result.value !== void 0) {
319
+ value[key] = result.value;
320
+ }
321
+ }
322
+ return issues.length > 0 ? { issues } : { value };
323
+ };
324
+ var objectOf = (shape) => ({
325
+ "~standard": {
326
+ validate: (input) => {
327
+ if (input === null || typeof input !== "object") {
328
+ return { issues: [{ message: "expected an object" }] };
329
+ }
330
+ const record = input;
331
+ const fields = Object.entries(shape).map(
332
+ ([key, schema]) => [key, schema["~standard"].validate(record[key])]
333
+ );
334
+ return fields.some(([, result]) => result instanceof Promise) ? Promise.all(fields.map(async ([key, result]) => [key, await result])).then(
335
+ settle
336
+ ) : settle(fields);
337
+ },
338
+ vendor: VENDOR,
339
+ version: 1
340
+ }
341
+ });
342
+
186
343
  // src/core/actor.ts
187
344
  var SYSTEM_PREFIX = "system:";
188
345
  var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
@@ -218,16 +375,30 @@ var isTerminalStatus = (machine, status) => machine.transitions[status].length =
218
375
  0 && (module.exports = {
219
376
  BODY_VERSION_KEY,
220
377
  Document,
378
+ arrayOf,
379
+ booleanSchema,
221
380
  canTransition,
222
381
  canonicalOf,
223
382
  documentBodyVersioning,
224
383
  documentEntities,
225
384
  documentIdentifiers,
385
+ enumOf,
226
386
  fieldPatterns,
227
387
  isSystemActor,
228
388
  isTerminalStatus,
389
+ literalOf,
390
+ merge,
229
391
  migrateBody,
392
+ nonEmptyString,
393
+ nullable,
394
+ numberSchema,
395
+ objectOf,
396
+ optional,
397
+ positiveInt,
230
398
  stampBody,
399
+ stringSchema,
231
400
  systemActor,
401
+ unknownSchema,
402
+ validate,
232
403
  validatorOf
233
404
  });