@geonosis/document 0.9.3 → 0.10.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.
Files changed (79) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +78 -13
  3. package/dist/core/actor.d.cts +0 -1
  4. package/dist/core/actor.d.ts +0 -1
  5. package/dist/core/body-version.d.cts +0 -9
  6. package/dist/core/body-version.d.ts +0 -9
  7. package/dist/core/canonical.cjs +2 -3
  8. package/dist/core/canonical.d.cts +0 -4
  9. package/dist/core/canonical.d.ts +0 -4
  10. package/dist/core/canonical.js +2 -3
  11. package/dist/core/document.cjs +28 -25
  12. package/dist/core/document.d.cts +3 -22
  13. package/dist/core/document.d.ts +3 -22
  14. package/dist/core/document.js +28 -25
  15. package/dist/core/entities.d.cts +0 -19
  16. package/dist/core/entities.d.ts +0 -19
  17. package/dist/core/naming.d.cts +0 -5
  18. package/dist/core/naming.d.ts +0 -5
  19. package/dist/core/numbering.d.cts +0 -4
  20. package/dist/core/numbering.d.ts +0 -4
  21. package/dist/core/ports.d.cts +0 -6
  22. package/dist/core/ports.d.ts +0 -6
  23. package/dist/core/schema.cjs +44 -76
  24. package/dist/core/schema.d.cts +1 -13
  25. package/dist/core/schema.d.ts +1 -13
  26. package/dist/core/schema.js +44 -76
  27. package/dist/core/status.d.cts +0 -1
  28. package/dist/core/status.d.ts +0 -1
  29. package/dist/index.cjs +1 -0
  30. package/dist/index.d.cts +1 -1
  31. package/dist/index.d.ts +1 -1
  32. package/dist/index.js +2 -0
  33. package/dist/store/ddl.cjs +35 -38
  34. package/dist/store/ddl.d.cts +6 -6
  35. package/dist/store/ddl.d.ts +6 -6
  36. package/dist/store/ddl.js +37 -39
  37. package/dist/store/hash.d.cts +0 -1
  38. package/dist/store/hash.d.ts +0 -1
  39. package/dist/store/number-for.cjs +52 -0
  40. package/dist/store/number-for.d.cts +11 -0
  41. package/dist/store/number-for.d.ts +11 -0
  42. package/dist/store/number-for.js +12 -0
  43. package/dist/store/store.cjs +188 -162
  44. package/dist/store/store.d.cts +57 -16
  45. package/dist/store/store.d.ts +57 -16
  46. package/dist/store/store.js +190 -163
  47. package/dist/store.cjs +2 -0
  48. package/dist/store.d.cts +3 -2
  49. package/dist/store.d.ts +3 -2
  50. package/dist/store.js +2 -0
  51. package/dist/surface/table.cjs +129 -66
  52. package/dist/surface/table.d.cts +20 -28
  53. package/dist/surface/table.d.ts +20 -28
  54. package/dist/surface/table.js +132 -66
  55. package/dist/workflows/bindings.cjs +48 -0
  56. package/dist/workflows/bindings.d.cts +15 -0
  57. package/dist/workflows/bindings.d.ts +15 -0
  58. package/dist/workflows/bindings.js +10 -0
  59. package/dist/workflows/document-workflows.cjs +29 -40
  60. package/dist/workflows/document-workflows.d.cts +0 -12
  61. package/dist/workflows/document-workflows.d.ts +0 -12
  62. package/dist/workflows/document-workflows.js +29 -40
  63. package/dist/workflows/effects.d.cts +0 -12
  64. package/dist/workflows/effects.d.ts +0 -12
  65. package/dist/workflows/ports.d.cts +0 -17
  66. package/dist/workflows/ports.d.ts +0 -17
  67. package/dist/workflows/refusals.cjs +30 -0
  68. package/dist/workflows/refusals.d.cts +37 -9
  69. package/dist/workflows/refusals.d.ts +37 -9
  70. package/dist/workflows/refusals.js +30 -0
  71. package/dist/workflows/shared.cjs +93 -0
  72. package/dist/workflows/shared.d.cts +28 -0
  73. package/dist/workflows/shared.d.ts +28 -0
  74. package/dist/workflows/shared.js +60 -0
  75. package/dist/workflows.cjs +16 -1
  76. package/dist/workflows.d.cts +3 -1
  77. package/dist/workflows.d.ts +3 -1
  78. package/dist/workflows.js +31 -1
  79. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # @geonosis/document
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - dd5f57a: Every write answers the `head` it computed: `CommitOutput`, `RetireOutput` and `ReinstateOutput` carry `head`. `DocumentStoreOptions` gains `search`, the post-commit port of a consumer's search index, called inside the write's transaction: `index` after a commit that changed something, a succeed, a reinstate and the undo that restores a body, `remove` after a retire and the undo of a first commit. It also gains `views`, the way an entity that declares a view of its own is rendered; a store built without one still builds and serves every other door, and only `render` on such an entity refuses.
8
+
9
+ `DocumentStore` gains `count` and `keys` per entity, `list` across entities (one keyset page, `(entity, number)` breaking every tie), `render` per entity, and `tables.documents` and `tables.revisions` row doors in the shape `relocateTenant` moves a table by. `HeadsArgs` takes `columns: 'all'` and `HeadRow` is the full row then. `numberFor({ counter, scope, seam })` is the workflows' `counter` port read from a `defineCounter` table.
10
+
11
+ `DocumentHead.status` is a `string`: `validatorOf` takes `required` fields and refuses a head with no status, and `requiredHeadFields` names it so a fold of `headFields` knows which fields to make nullable.
12
+
13
+ `documentShared(registry, ports)` is the `document.shared` workflow, and `DocumentRefusal` gains its named refusals: an invalid signature, an expired link, another organisation, something that is not a document, a retired document.
14
+
15
+ `DocumentSurfaceOptions` takes `workflows`, `runFor`, `launcher` and `shared`, and every `SurfaceRow` is a function: `create` and `duplicate` run their workflow, `send` starts a durable run and answers its id, `shared` runs `document.shared`. `PendingCall` and the `runStarted` row are gone. The table gains `resolve.counterpartyName` for the cards of a page, a `documents.list` row, the `head` on write outputs and `columns: 'all'` on `heads`.
16
+ - 58eaf3a: `AppendOnlyTablesOptions` no longer declares `table` (it was `table?: string`, now `table?: never`), and `appendOnlyTables` and `documentRoleStatements` refuse a `table` option at runtime. It was read as the revisions table, while `table` is the documents table in `documentStore` and `documentMigrations`: a caller who passed the documents table name there had the one table an application must update lose its UPDATE and DELETE, and the log keep them. A caller who passed the log's name as `table` must write `revisions: { table }`; one who passes it through an untyped options object gets a `DbRefusal` saying so instead of a silent default.
17
+
18
+ `documentRoleStatements` and the log's check constraint quote a name that holds a double quote instead of letting it close its own quoting.
19
+ - 58eaf3a: The archive key of a revision names its document: `<tenant>/<entity>/<ref>/<lineage>/<version>.json`, the ref percent-encoded and the tenant and entity written as before. It was `<tenant>/<entity>/<lineage>/<version>.json`, which two documents of one entity share at their first version, so the second commit overwrote the first one's archive object. The store only writes archives (`ArchivePort.put`); nothing in this package reads one back.
20
+
21
+ A consumer with existing archives: every object an earlier version wrote stays under the old key, and for an entity holding more than one document each old object holds only one of the documents that shared its key. Anything that computes a key to read, verify or restore must try the new key and fall back to the old one, or copy the old objects to their new keys. A commit retried after the upgrade writes under the new key.
22
+
23
+ A tenant or entity with an empty, `.` or `..` path segment (split on `/` and `\`, so `a/../b`, `./a` and `a/.` are refused as well as `..`) is refused with a `DbRefusal` before the transaction opens, because it would map documents onto one key in a store that normalises dot segments. A ref is refused only when it is empty, `.` or `..` as a whole, or when it is not well-formed text, which `encodeURIComponent` throws on: a `/` or `\` inside a ref is percent-encoded and never forms a path segment, so `a/b`, `a/`, `a//b`, `a/../b` and `./a` are accepted. Tenant ids and entity names therefore must not contain a dot or empty segment. Only a store configured with `archive` refuses them.
24
+ - 58eaf3a: `fieldPatterns.calendarDate`, and the validator derived from it, refuse a date no calendar has (`2026-02-30`, `2026-13-01`, `2025-02-29`): they matched any `YYYY-MM-DD`, and such a head then failed every aggregate that buckets it with a date cast.
25
+
26
+ The check applies on read as well as on write: a stored row whose head date is one of these now fails `Document.head` and any output schema built from `documentSurface` that parses stored heads. Correct such rows (find them with a date cast over the head column) before upgrading.
27
+
28
+ ### Patch Changes
29
+
30
+ - a4a7bba: The floor READMEs state what a consumer does with the DDL a floor renders: commit the rendered files beside its own, apply them with its own runner, and hold them with a committed-vs-rendered test, since DDL kept only in incremental migrations is lost when they are squashed. They also state that `create index if not exists` leaves an old index in place under a new definition, so an index whose definition changed is re-created with `drop index` and `create index`. `@geonosis/db` adds what a stored row an older shape wrote does to `list` once `body` is declared (a `DbRefusal` at the first non-conforming row) and that the stored rows are censused first.
31
+ - 58eaf3a: `DocumentKind` is derived from `REVISION_KINDS` instead of spelled a second time as a union. It has the same members (`'committed' | 'reinstated' | 'retired'`), so a kind added to one list can no longer be missing from the other.
32
+ - 58eaf3a: A stored body that no longer satisfies its entity's schema after migration, and a body schema that validates asynchronously, are refused as a `DbRefusal` with `code: 'body-refused'`, the code `@geonosis/db` gives the same refusal on a write. They were a bare `Error` with no code.
33
+ - Updated dependencies [58eaf3a]
34
+ - Updated dependencies [a4a7bba]
35
+ - Updated dependencies [dd5f57a]
36
+ - Updated dependencies [a4a7bba]
37
+ - Updated dependencies [dd5f57a]
38
+ - Updated dependencies [a4a7bba]
39
+ - Updated dependencies [a4a7bba]
40
+ - Updated dependencies [a4a7bba]
41
+ - Updated dependencies [a4a7bba]
42
+ - Updated dependencies [58eaf3a]
43
+ - Updated dependencies [58eaf3a]
44
+ - Updated dependencies [58eaf3a]
45
+ - Updated dependencies [58eaf3a]
46
+ - Updated dependencies [58eaf3a]
47
+ - Updated dependencies [58eaf3a]
48
+ - Updated dependencies [58eaf3a]
49
+ - Updated dependencies [dd5f57a]
50
+ - Updated dependencies [f5632b7]
51
+ - Updated dependencies
52
+ - Updated dependencies [deef511]
53
+ - @geonosis/db@0.15.0
54
+ - @geonosis/workflows@0.8.0
55
+
3
56
  ## 0.9.3
4
57
 
5
58
  ### Patch Changes
package/README.md CHANGED
@@ -18,7 +18,10 @@ shouldn't know anything about schema; we extend, we do it.
18
18
  `Document = { headFields, head, recordFields, record, extend }`. `headFields` is the declarative
19
19
  FIELD SPEC every document's indexed facts are named from — `{ status: 'text', issueDate:
20
20
  'calendarDate', dueDate: 'calendarDate', counterparty: 'text', externalRef: 'text', revision:
21
- 'text', total: 'decimal' }`, every field nullable. `head` is a `StandardSchemaV1` DERIVED from
21
+ 'text', total: 'decimal' }`, every field nullable but the ones `requiredHeadFields` names — `status`,
22
+ because a document always has one (`statuses.initial` is the floor): `DocumentHead.status` is a
23
+ `string`, a `headOf` that answers `null` for it is refused at `Document.head`, and a consumer's fold
24
+ of the spec makes every other field nullable (#442). `head` is a `StandardSchemaV1` DERIVED from
22
25
  `headFields` by `validatorOf` (exported, one small checker per `FieldKind`) — the base enforcing
23
26
  its own contract, never a second listing of the fields. A consumer's wire schema folds
24
27
  `headFields` into its own library instead of naming the seven fields by hand, and `fieldPatterns`
@@ -131,6 +134,23 @@ same law as `@geonosis/db`'s own `appRoleStatements`. The log's own kind column
131
134
  `columns.revisionKind`, `'revision_kind'` when unnamed — never `'kind'`, which is what these docs
132
135
  use for `columns.entity` (#407).
133
136
 
137
+ ### The consumer applies what the floor renders
138
+
139
+ `documentMigrations` renders the DDL as `{ name, statements }[]`, and the same files ship under
140
+ `migrations/`. The floor applies neither. The consumer commits the rendered files beside its own
141
+ and applies them with its own runner, and holds them with a committed-vs-rendered test: render,
142
+ compare with the committed folder, fail on a difference — `src/store/ddl.test.ts` does it for the
143
+ shipped folder. DDL kept only inside a consumer's incremental migrations is lost on the day those
144
+ are squashed.
145
+
146
+ ### An index whose definition changed is not replaced by a re-run
147
+
148
+ The head and listing indexes are `create index if not exists`. A table created under an older
149
+ definition keeps its old index when a release changes it (0.4.0 renamed the head columns and
150
+ moved the constants inside every index): same name, old shape, no error. The consumer re-creates an
151
+ index whose definition changed — `drop index <name>` and `create index <name> …` from the rendered
152
+ statement, in a migration of its own.
153
+
134
154
  ## Writes
135
155
 
136
156
  There is ONE write verb, `commit`. `store.<entity>.commit({ ref, body, actor, reason? })` appends
@@ -150,6 +170,17 @@ version an undo compensates). `at` is the DATABASE clock, never the application'
150
170
  from the first write; a consumer's own archive recomputes the SAME `hashOf`/`canonicalOf`, the one
151
171
  canonicaliser both sides use.
152
172
 
173
+ Every write answers the `head` it computed — `CommitOutput`, `RetireOutput` and `ReinstateOutput`
174
+ carry `head: DocumentHead` (the unchanged `committed: false` answer too, read off the body that was
175
+ handed in), so a consumer that indexes search or emits an event pays no select per write (#446).
176
+
177
+ `documentStore({ search })` is the post-commit port of a consumer's search index (#431): `{ index(handle,
178
+ { entity, ref, head, text }), remove(handle, { entity, ref }) }`, called INSIDE the write's own
179
+ transaction — `index` on a commit that changed something, a succeed, a reinstate and the undo that
180
+ restores a body; `remove` on a retire and on the undo of a first commit — handed the head the write
181
+ computed and `searchText(body)` (`{ body }`), never a re-read. A port that throws rolls the write back.
182
+ It is a PORT: a domain imports no domain, so the search index is the consumer's to hand in.
183
+
153
184
  `store.<entity>.retire({ ref, actor, reason? })` is a commit of kind `retired` — the body is the
154
185
  last one, unchanged; the projection's `retired_at` is set; a retired document refuses `commit`.
155
186
  `store.<entity>.succeed({ ref, body, actor, reason? })` is the only door back from retired: it opens
@@ -176,7 +207,7 @@ compensating revision carries `compensationOf`, naming the version it undoes —
176
207
  the rollback structurally, never in prose.
177
208
 
178
209
  `documentStore({ archive })` (optional, `ArchivePort` from `core/ports`) copies a commit's revision
179
- to `<tenant>/<entity>/<lineage>/<version>.json` AFTER its own transaction has committed — never
210
+ to `<tenant>/<entity>/<ref>/<lineage>/<version>.json` (the ref percent-encoded; a tenant, entity or ref that is empty, `.` or `..` is refused before the write) AFTER its own transaction has committed — never
180
211
  inside it, so an archive that is down never rolls a durable write back; the answer carries
181
212
  `archived: false` instead, and a later ticket's workflow is what retries it. `TimestampPort` (a
182
213
  trusted third party's timestamp over a hash) is declared beside it, not implemented by anything
@@ -194,12 +225,31 @@ lineage? })` recomputes every hash of a lineage from version 1 and answers `{ ok
194
225
  or `{ ok: false, brokenAt, expected, found }` — a fact no privilege can hide, since the log's own
195
226
  bytes are what it reads.
196
227
 
228
+ `store.<entity>.count({ where? })` and `store.<entity>.keys({ where?, order? })` count the living
229
+ documents of the entity the `where` keeps, and answer their bare refs (by `number` unless an order
230
+ is asked), over the head columns `heads` reads (#445). `store.list({ entities?, order?, cursor?,
231
+ limit?, filter? })` is ONE keyset page across the entities, ordered by any sortable column with
232
+ `(entity, number)` breaking every tie — a ref two entities share is never skipped or repeated across
233
+ pages — and answers each item as the instance of its own entity (#434). `store.<entity>.render({ ref
234
+ })` is the single-document read that answers a VIEW: `documentStore({ views: { [entity]: (handle,
235
+ instance) => view } })` runs in the scope of the read and is typed off `ViewOf`; an entity that
236
+ declares no `view` of its own renders its body, and a store built for one that does and handed no
237
+ `views` for it refuses at construction (#444). `store.tables.documents` and `store.tables.revisions`
238
+ (absent when `revisions: false`) are the two tables' row doors — `rows`, `restore`, `size`, and
239
+ `purge` on the documents — in the shape `relocateTenant` from `@geonosis/db` moves a table by; a
240
+ log's rows are written byte for byte, so a moved lineage still `verify`s.
241
+
242
+ `numberFor({ counter, scope, seam })` (`@geonosis/document/store`) is the workflows' `counter` port read
243
+ from a `defineCounter` table: `scope(ctx)` names the handle and the tenant of the run, and the number
244
+ is the counter's own `next` — one atomic statement, so racing creates are issued a number each.
245
+
197
246
  `store.rebuild({ entity? })` (tenant-scoped) rewrites the projection from the log's own latest
198
247
  version of its latest lineage, per `(entity, ref)`, and answers how many rows it wrote — a
199
248
  consumer's repair tool, and the exam's own way of proving the projection is truly DERIVED.
200
249
 
201
250
  `store.heads({ columns, entity?, order, where? })` is a PROJECTION, never an aggregate: the head
202
- fields plus `entity` and `number`, typed off `columns` (`HeadRow<Columns>` — no cast), `entity` one
251
+ fields plus `entity` and `number`, typed off `columns` (`HeadRow<Columns>` — no cast; `columns: 'all'`
252
+ answers every head field, `entity`, `number` and both clocks as the full row, #447), `entity` one
203
253
  kind or a set, `order` every column a page is ordered by (the tie-break included; the two clocks
204
254
  sort too), `where` any head field as equality, a set, or `{ from, to }`, plus `createdAt`/`updatedAt`
205
255
  ranges. `store.aggregate({ by?, entity?, entities?, measures, where? })` answers `count` and
@@ -220,13 +270,19 @@ call }`), derived by FOLDING over the registry, never a map a caller fills: per
220
270
  envelope with each item's own instance AND card), `history`, `verify`, `commit`, `retire`,
221
271
  `reinstate`, `setStatus` (a `commit` of `withStatus(body)` guarded by `canTransition` — refuses a
222
272
  transition the entity's own status machine never declared, before it writes); across entities,
273
+ `documents.list` (the cross-entity page of `store.list`, each item its own instance and card),
223
274
  `heads`, `aggregate` and `shared`. `shared` is the link door: `scope: 'token'`, input `{ token }`,
224
- output the union over every entity of `{ entity, view }` folded off the registry, the tenant read
225
- from the token by `LinkVerifierPort` and never from the handle; it is declared pending on the
226
- `document.shared` workflow like the saga rows. The saga rows an entity gets for free — `create`
227
- (with numbering), `send`, `duplicate`, `runStarted` — are DECLARED with their own input/output and
228
- `call: { pending: 'T3', workflow }` in place of a function: an adapter mounting the table refuses
229
- those BY NAME (`typeof row.call !== 'function'`), never with a stub answer.
275
+ output the union over every entity of `{ entity, view }` folded off the registry, bound to the
276
+ `document.shared` workflow (below), the tenant read from the token and never from the handle. The
277
+ saga rows an entity gets for free are bound too (#512): `documentSurface({ workflows, runFor,
278
+ launcher, shared })` takes the minted `documentWorkflows` per entity, a `runFor(handle, call)`
279
+ returning the `WorkflowRuntime` narrowed to the call's tenant, and the platform `launcher` —
280
+ `create` and `duplicate` run their workflow inline and answer `{ entity, number, body, minted }`,
281
+ `send` is a durable start and answers `{ runId, deduplicated }`. No row is a declaration in place of
282
+ a function. `runStarted` tracks runs, which is the consumer's: it declares that row itself.
283
+ `resolve: { counterpartyName(ids) }` is a port answered once per page, with the page's distinct
284
+ counterparty ids, so every card carries its `counterpartyName` (`''` when nothing resolves it) (#431).
285
+ Write outputs carry `head`, and the `heads` row takes `columns: 'all'`.
230
286
 
231
287
  The table is the contract; an adapter (tRPC, REST, MCP) is thin — it reads a row's `name`, `verb`,
232
288
  `path` and `scope` for its own wiring, hands `input`/`output` to whatever transport-level
@@ -270,14 +326,23 @@ read and write of its own. `src/workflows/document-workflows.test.ts` runs every
270
326
  in-memory door and the memory journal, `send` through the durable door, and one entity on nothing
271
327
  but `announce` and the three required ports.
272
328
 
329
+ `documentShared(registry, { verifier, door, now?, org? })` is the `document.shared` workflow (#413):
330
+ the token door refused in the order a caller can act on it, each refusal a NAMED, tagged error —
331
+ `DocumentLinkInvalid` (the signature does not verify), `DocumentLinkExpired` (`exp` has passed),
332
+ `DocumentLinkWrongOrg` (the request is already scoped to another organisation: `org(ctx)`),
333
+ `DocumentLinkNotADocument` (the token verifies but names an entity outside the registry, such as a
334
+ vault file), `DocumentLinkRetired`, and `DocumentNotFound` — before it answers `{ entity, view }`.
335
+ The organisation is read from the token and nowhere else; `door(ctx, { entity, org })` answers
336
+ `{ render, retired }` for that organisation, which a host builds from the store's `render` and the
337
+ last kind of `history`.
338
+
273
339
  ## What does not exist yet
274
340
 
275
341
  `src/store/` ships the commits (`commit`, `retire`, `succeed`, `reinstate`, `get`, `at`, `asOf`,
276
342
  `history`, `verify`, `rebuild`, `heads`, `aggregate`) and the archive/timestamp ports declared, not
277
- mirrored; it ships no search projection yet. `upsert` and `revisions` are GONE (replaced by
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
343
+ mirrored; it ships the `search` port and no search projection of its own. `upsert` and `revisions`
344
+ are GONE (replaced by `commit`; `history`). `src/surface/` ships the table above, every row a function;
345
+ the archive mirror still lands in `src/workflows/`. `src/contract/` (a layer the surface table already
281
346
  supersedes — #403), `src/ui/` (the view axis) and `src/conformance/` (the exam a consumer runs
282
347
  against their own provider) are later tickets — the internal layout is declared now (and held by
283
348
  `layer-walls`) so each lands inside the wall already drawn for it.
@@ -1,3 +1,2 @@
1
- /** An unattended write's principal — `systemActor('recurring.generate')` — never a bare `'system'`. */
2
1
  export declare const systemActor: (name: string) => string;
3
2
  export declare const isSystemActor: (actor: string) => boolean;
@@ -1,3 +1,2 @@
1
- /** An unattended write's principal — `systemActor('recurring.generate')` — never a bare `'system'`. */
2
1
  export declare const systemActor: (name: string) => string;
3
2
  export declare const isSystemActor: (actor: string) => boolean;
@@ -1,23 +1,14 @@
1
1
  export declare const BODY_VERSION_KEY = "_v";
2
2
  type StoredBody = Record<string, unknown>;
3
- /** A step declared for ONE entity's stored shape, keyed by the version it reads FROM. */
4
3
  export type DocumentBodyMigrations<Body extends StoredBody = StoredBody> = Readonly<Record<number, (body: Body) => Body>>;
5
- /**
6
- * What an entity declares about its own body's history: the version it is at today, and the steps
7
- * that bring an older stored body up to it. Absent, an entity is at version 1 with no steps —
8
- * every field here is per-entity, so a step declared on one entity's `migrations` can never run on
9
- * another's body, which is the gap a single shared step table left open.
10
- */
11
4
  export type DocumentBodyVersion<Body extends StoredBody = StoredBody> = {
12
5
  bodyVersion?: number;
13
6
  migrations?: DocumentBodyMigrations<Body>;
14
7
  };
15
- /** Runs BEFORE the entity's schema parses: an older stored shape does not satisfy today's schema. */
16
8
  export declare const migrateBody: <Body extends StoredBody>(definition: DocumentBodyVersion<Body>, stored: unknown) => unknown;
17
9
  export declare const stampBody: <Body>(definition: {
18
10
  bodyVersion?: number;
19
11
  }, body: Body) => unknown;
20
- /** The migrate/stamp pair, bound to ONE entity's own declared version and steps. */
21
12
  export declare const documentBodyVersioning: <Body extends StoredBody>(definition: DocumentBodyVersion<Body>) => {
22
13
  migrate: (stored: unknown) => unknown;
23
14
  stamp: (body: Body) => unknown;
@@ -1,23 +1,14 @@
1
1
  export declare const BODY_VERSION_KEY = "_v";
2
2
  type StoredBody = Record<string, unknown>;
3
- /** A step declared for ONE entity's stored shape, keyed by the version it reads FROM. */
4
3
  export type DocumentBodyMigrations<Body extends StoredBody = StoredBody> = Readonly<Record<number, (body: Body) => Body>>;
5
- /**
6
- * What an entity declares about its own body's history: the version it is at today, and the steps
7
- * that bring an older stored body up to it. Absent, an entity is at version 1 with no steps —
8
- * every field here is per-entity, so a step declared on one entity's `migrations` can never run on
9
- * another's body, which is the gap a single shared step table left open.
10
- */
11
4
  export type DocumentBodyVersion<Body extends StoredBody = StoredBody> = {
12
5
  bodyVersion?: number;
13
6
  migrations?: DocumentBodyMigrations<Body>;
14
7
  };
15
- /** Runs BEFORE the entity's schema parses: an older stored shape does not satisfy today's schema. */
16
8
  export declare const migrateBody: <Body extends StoredBody>(definition: DocumentBodyVersion<Body>, stored: unknown) => unknown;
17
9
  export declare const stampBody: <Body>(definition: {
18
10
  bodyVersion?: number;
19
11
  }, body: Body) => unknown;
20
- /** The migrate/stamp pair, bound to ONE entity's own declared version and steps. */
21
12
  export declare const documentBodyVersioning: <Body extends StoredBody>(definition: DocumentBodyVersion<Body>) => {
22
13
  migrate: (stored: unknown) => unknown;
23
14
  stamp: (body: Body) => unknown;
@@ -46,9 +46,8 @@ var KEY_ORDER = new Intl.Collator("en-US");
46
46
  var canonicalOf = (input) => {
47
47
  if (input === null || typeof input !== "object")
48
48
  return input;
49
- const { toJSON } = input;
50
- if (typeof toJSON === "function")
51
- return canonicalOf(toJSON.call(input));
49
+ if ("toJSON" in input && typeof input.toJSON === "function")
50
+ return canonicalOf(input.toJSON());
52
51
  if (Array.isArray(input))
53
52
  return input.map(canonicalOf);
54
53
  return Object.fromEntries(Object.entries(input).toSorted(([a], [b]) => KEY_ORDER.compare(a, b)).map(([key, held]) => [key, canonicalOf(held)]));
@@ -1,5 +1 @@
1
- /**
2
- * Deep, key-order-independent, and read as JSON writes it (a `Date` is its ISO string). The ONE
3
- * canonicaliser both sides use — a consumer's archive recomputes `hashOf` over the identical form.
4
- */
5
1
  export declare const canonicalOf: (input: unknown) => unknown;
@@ -1,5 +1 @@
1
- /**
2
- * Deep, key-order-independent, and read as JSON writes it (a `Date` is its ISO string). The ONE
3
- * canonicaliser both sides use — a consumer's archive recomputes `hashOf` over the identical form.
4
- */
5
1
  export declare const canonicalOf: (input: unknown) => unknown;
@@ -3,9 +3,8 @@ var KEY_ORDER = new Intl.Collator("en-US");
3
3
  var canonicalOf = (input) => {
4
4
  if (input === null || typeof input !== "object")
5
5
  return input;
6
- const { toJSON } = input;
7
- if (typeof toJSON === "function")
8
- return canonicalOf(toJSON.call(input));
6
+ if ("toJSON" in input && typeof input.toJSON === "function")
7
+ return canonicalOf(input.toJSON());
9
8
  if (Array.isArray(input))
10
9
  return input.map(canonicalOf);
11
10
  return Object.fromEntries(Object.entries(input).toSorted(([a], [b]) => KEY_ORDER.compare(a, b)).map(([key, held]) => [key, canonicalOf(held)]));
@@ -43,11 +43,15 @@ __export(exports_document, {
43
43
  fieldPatterns: () => fieldPatterns,
44
44
  headFields: () => headFields,
45
45
  recordFields: () => recordFields,
46
+ requiredHeadFields: () => requiredHeadFields,
46
47
  validatorOf: () => validatorOf
47
48
  });
48
49
  module.exports = __toCommonJS(exports_document);
50
+ var import_schema = require("./schema.cjs");
51
+ var LEAP_FEBRUARY_29 = "(?:\\d\\d(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29";
52
+ var CALENDAR_DATE = new RegExp(`^(?!0000)(?:\\d{4}-(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|\\d{4}-(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|\\d{4}-02-(?:0[1-9]|1\\d|2[0-8])|${LEAP_FEBRUARY_29})$`);
49
53
  var fieldPatterns = {
50
- calendarDate: /^\d{4}-\d{2}-\d{2}$/,
54
+ calendarDate: CALENDAR_DATE,
51
55
  decimal: /^-?\d+(?:\.\d+)?$/
52
56
  };
53
57
  var FIELD_CHECKS = {
@@ -71,30 +75,25 @@ var FIELD_CHECKS = {
71
75
  };
72
76
  var validatorOf = (fields, options) => {
73
77
  const nullable = options?.nullable ?? false;
74
- return {
75
- "~standard": {
76
- validate: (input) => {
77
- if (input === null || typeof input !== "object") {
78
- return { issues: [{ message: "expected an object" }] };
79
- }
80
- const record = input;
81
- const issues = [];
82
- const value = {};
83
- for (const [key, kind] of Object.entries(fields)) {
84
- const held = record[key];
85
- value[key] = held;
86
- if (nullable && held === null)
87
- continue;
88
- if (!FIELD_CHECKS[kind].test(held)) {
89
- issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
90
- }
91
- }
92
- return issues.length > 0 ? { issues } : { value };
93
- },
94
- vendor: "geonosis-document",
95
- version: 1
78
+ const required = options?.required ?? [];
79
+ return import_schema.schemaOf((input) => {
80
+ if (input === null || typeof input !== "object") {
81
+ return { issues: [{ message: "expected an object" }] };
96
82
  }
97
- };
83
+ const record = input;
84
+ const issues = [];
85
+ const value = {};
86
+ for (const [key, kind] of Object.entries(fields)) {
87
+ const held = record[key];
88
+ value[key] = held;
89
+ if (nullable && held === null && !required.includes(key))
90
+ continue;
91
+ if (!FIELD_CHECKS[kind].test(held)) {
92
+ issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
93
+ }
94
+ }
95
+ return issues.length > 0 ? { issues } : { value };
96
+ });
98
97
  };
99
98
  var parseWith = (schema, input) => {
100
99
  const result = schema["~standard"].validate(input);
@@ -120,7 +119,11 @@ var recordFields = {
120
119
  createdAt: "int",
121
120
  updatedAt: "int"
122
121
  };
123
- var headValidator = validatorOf(headFields, { nullable: true });
122
+ var requiredHeadFields = ["status"];
123
+ var headValidator = validatorOf(headFields, {
124
+ nullable: true,
125
+ required: requiredHeadFields
126
+ });
124
127
  var recordValidator = validatorOf(recordFields);
125
128
  var Document = {
126
129
  head: headValidator,
@@ -2,21 +2,12 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import type { DocumentBodyMigrations } from './body-version.cjs';
3
3
  import type { DocumentNumbering } from './numbering.cjs';
4
4
  import type { DocumentStatusMachine } from './status.cjs';
5
- /** The five checks `Document.head` and `Document.record` are built from — never a sixth kind. */
6
5
  export type FieldKind = 'calendarDate' | 'decimal' | 'int' | 'positiveInt' | 'text';
7
- /** The two `FieldKind`s a consumer's own schema library validates by pattern — `validatorOf`'s own regexes, on the door, so a fold names one pattern once (#409). */
8
6
  export declare const fieldPatterns: Record<'calendarDate' | 'decimal', RegExp>;
9
- /**
10
- * A `StandardSchemaV1` derived from a declarative field spec — one small checker per `FieldKind`,
11
- * never a second listing of the fields `Document.head`/`Document.record` already carry.
12
- */
13
7
  export declare const validatorOf: <Output>(fields: Readonly<Record<string, FieldKind>>, options?: {
14
8
  nullable?: boolean;
9
+ required?: readonly string[];
15
10
  }) => StandardSchemaV1<unknown, Output>;
16
- /**
17
- * What every document has before anything knows what kind it is — the indexed facts a list sorts
18
- * and filters by. Every entity derives these from its own body (`headOf`).
19
- */
20
11
  export declare const headFields: {
21
12
  readonly status: 'text';
22
13
  readonly issueDate: 'calendarDate';
@@ -26,14 +17,14 @@ export declare const headFields: {
26
17
  readonly revision: 'text';
27
18
  readonly total: 'decimal';
28
19
  };
29
- /** What storage adds: the version a history counts, and the two clocks. */
30
20
  export declare const recordFields: {
31
21
  readonly version: 'positiveInt';
32
22
  readonly createdAt: 'int';
33
23
  readonly updatedAt: 'int';
34
24
  };
25
+ export declare const requiredHeadFields: readonly ['status'];
35
26
  export type DocumentHead = {
36
- status: string | null;
27
+ status: string;
37
28
  issueDate: string | null;
38
29
  dueDate: string | null;
39
30
  counterparty: string | null;
@@ -46,7 +37,6 @@ export type DocumentRecord = {
46
37
  createdAt: number;
47
38
  updatedAt: number;
48
39
  };
49
- /** What an entity decides when it extends `Document`; every side effect is written once over these. */
50
40
  export type DocumentDefinition<Name extends string, BodySchema extends StandardSchemaV1, DraftSchema extends StandardSchemaV1, IncomingSchema extends StandardSchemaV1, Status extends string, CardSchema extends StandardSchemaV1, Path extends string, ViewSchema extends StandardSchemaV1 = BodySchema> = {
51
41
  name: Name;
52
42
  noun: string;
@@ -56,11 +46,8 @@ export type DocumentDefinition<Name extends string, BodySchema extends StandardS
56
46
  incoming: IncomingSchema;
57
47
  statuses: DocumentStatusMachine<Status>;
58
48
  numbering: DocumentNumbering<StandardSchemaV1.InferOutput<DraftSchema>>;
59
- /** The version this entity's stored body is at today — absent, it is 1. */
60
49
  bodyVersion?: number;
61
- /** Steps that bring an older stored body up to `bodyVersion`, keyed by the version they read. */
62
50
  migrations?: DocumentBodyMigrations<Record<string, unknown>>;
63
- /** `number` is the MINTED number — read off the numbering before the counter moves, never a series. */
64
51
  fromDraft: (draft: StandardSchemaV1.InferOutput<DraftSchema>, number: string) => StandardSchemaV1.InferOutput<BodySchema>;
65
52
  headOf: (body: StandardSchemaV1.InferOutput<BodySchema>) => DocumentHead;
66
53
  searchText: (body: StandardSchemaV1.InferOutput<BodySchema>) => {
@@ -79,10 +66,8 @@ export type DocumentDefinition<Name extends string, BodySchema extends StandardS
79
66
  counterpartyName: string;
80
67
  }) => StandardSchemaV1.InferOutput<CardSchema>;
81
68
  };
82
- /** What a single-document read RENDERS — absent, the body a consumer already declared. */
83
69
  view?: ViewSchema;
84
70
  };
85
- /** A stored document of one entity: the head every document has, the record's clocks, its body. */
86
71
  export type DocumentInstance<Name extends string, Body> = DocumentHead & DocumentRecord & {
87
72
  entity: Name;
88
73
  number: string;
@@ -94,10 +79,6 @@ export type DocumentEntity<Name extends string, BodySchema extends StandardSchem
94
79
  }) => document is DocumentInstance<Name, StandardSchemaV1.InferOutput<BodySchema>>;
95
80
  view: ViewSchema;
96
81
  };
97
- /**
98
- * The abstract Document. Never stored as itself — a consumer's entities extend it, and everything
99
- * written against `Document` runs for every one of them.
100
- */
101
82
  export declare const Document: {
102
83
  head: StandardSchemaV1<unknown, DocumentHead>;
103
84
  headFields: {
@@ -2,21 +2,12 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import type { DocumentBodyMigrations } from './body-version.js';
3
3
  import type { DocumentNumbering } from './numbering.js';
4
4
  import type { DocumentStatusMachine } from './status.js';
5
- /** The five checks `Document.head` and `Document.record` are built from — never a sixth kind. */
6
5
  export type FieldKind = 'calendarDate' | 'decimal' | 'int' | 'positiveInt' | 'text';
7
- /** The two `FieldKind`s a consumer's own schema library validates by pattern — `validatorOf`'s own regexes, on the door, so a fold names one pattern once (#409). */
8
6
  export declare const fieldPatterns: Record<'calendarDate' | 'decimal', RegExp>;
9
- /**
10
- * A `StandardSchemaV1` derived from a declarative field spec — one small checker per `FieldKind`,
11
- * never a second listing of the fields `Document.head`/`Document.record` already carry.
12
- */
13
7
  export declare const validatorOf: <Output>(fields: Readonly<Record<string, FieldKind>>, options?: {
14
8
  nullable?: boolean;
9
+ required?: readonly string[];
15
10
  }) => StandardSchemaV1<unknown, Output>;
16
- /**
17
- * What every document has before anything knows what kind it is — the indexed facts a list sorts
18
- * and filters by. Every entity derives these from its own body (`headOf`).
19
- */
20
11
  export declare const headFields: {
21
12
  readonly status: 'text';
22
13
  readonly issueDate: 'calendarDate';
@@ -26,14 +17,14 @@ export declare const headFields: {
26
17
  readonly revision: 'text';
27
18
  readonly total: 'decimal';
28
19
  };
29
- /** What storage adds: the version a history counts, and the two clocks. */
30
20
  export declare const recordFields: {
31
21
  readonly version: 'positiveInt';
32
22
  readonly createdAt: 'int';
33
23
  readonly updatedAt: 'int';
34
24
  };
25
+ export declare const requiredHeadFields: readonly ['status'];
35
26
  export type DocumentHead = {
36
- status: string | null;
27
+ status: string;
37
28
  issueDate: string | null;
38
29
  dueDate: string | null;
39
30
  counterparty: string | null;
@@ -46,7 +37,6 @@ export type DocumentRecord = {
46
37
  createdAt: number;
47
38
  updatedAt: number;
48
39
  };
49
- /** What an entity decides when it extends `Document`; every side effect is written once over these. */
50
40
  export type DocumentDefinition<Name extends string, BodySchema extends StandardSchemaV1, DraftSchema extends StandardSchemaV1, IncomingSchema extends StandardSchemaV1, Status extends string, CardSchema extends StandardSchemaV1, Path extends string, ViewSchema extends StandardSchemaV1 = BodySchema> = {
51
41
  name: Name;
52
42
  noun: string;
@@ -56,11 +46,8 @@ export type DocumentDefinition<Name extends string, BodySchema extends StandardS
56
46
  incoming: IncomingSchema;
57
47
  statuses: DocumentStatusMachine<Status>;
58
48
  numbering: DocumentNumbering<StandardSchemaV1.InferOutput<DraftSchema>>;
59
- /** The version this entity's stored body is at today — absent, it is 1. */
60
49
  bodyVersion?: number;
61
- /** Steps that bring an older stored body up to `bodyVersion`, keyed by the version they read. */
62
50
  migrations?: DocumentBodyMigrations<Record<string, unknown>>;
63
- /** `number` is the MINTED number — read off the numbering before the counter moves, never a series. */
64
51
  fromDraft: (draft: StandardSchemaV1.InferOutput<DraftSchema>, number: string) => StandardSchemaV1.InferOutput<BodySchema>;
65
52
  headOf: (body: StandardSchemaV1.InferOutput<BodySchema>) => DocumentHead;
66
53
  searchText: (body: StandardSchemaV1.InferOutput<BodySchema>) => {
@@ -79,10 +66,8 @@ export type DocumentDefinition<Name extends string, BodySchema extends StandardS
79
66
  counterpartyName: string;
80
67
  }) => StandardSchemaV1.InferOutput<CardSchema>;
81
68
  };
82
- /** What a single-document read RENDERS — absent, the body a consumer already declared. */
83
69
  view?: ViewSchema;
84
70
  };
85
- /** A stored document of one entity: the head every document has, the record's clocks, its body. */
86
71
  export type DocumentInstance<Name extends string, Body> = DocumentHead & DocumentRecord & {
87
72
  entity: Name;
88
73
  number: string;
@@ -94,10 +79,6 @@ export type DocumentEntity<Name extends string, BodySchema extends StandardSchem
94
79
  }) => document is DocumentInstance<Name, StandardSchemaV1.InferOutput<BodySchema>>;
95
80
  view: ViewSchema;
96
81
  };
97
- /**
98
- * The abstract Document. Never stored as itself — a consumer's entities extend it, and everything
99
- * written against `Document` runs for every one of them.
100
- */
101
82
  export declare const Document: {
102
83
  head: StandardSchemaV1<unknown, DocumentHead>;
103
84
  headFields: {
@@ -1,6 +1,9 @@
1
1
  // src/core/document.ts
2
+ import { schemaOf } from "./schema.js";
3
+ var LEAP_FEBRUARY_29 = "(?:\\d\\d(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29";
4
+ var CALENDAR_DATE = new RegExp(`^(?!0000)(?:\\d{4}-(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|\\d{4}-(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|\\d{4}-02-(?:0[1-9]|1\\d|2[0-8])|${LEAP_FEBRUARY_29})$`);
2
5
  var fieldPatterns = {
3
- calendarDate: /^\d{4}-\d{2}-\d{2}$/,
6
+ calendarDate: CALENDAR_DATE,
4
7
  decimal: /^-?\d+(?:\.\d+)?$/
5
8
  };
6
9
  var FIELD_CHECKS = {
@@ -24,30 +27,25 @@ var FIELD_CHECKS = {
24
27
  };
25
28
  var validatorOf = (fields, options) => {
26
29
  const nullable = options?.nullable ?? false;
27
- return {
28
- "~standard": {
29
- validate: (input) => {
30
- if (input === null || typeof input !== "object") {
31
- return { issues: [{ message: "expected an object" }] };
32
- }
33
- const record = input;
34
- const issues = [];
35
- const value = {};
36
- for (const [key, kind] of Object.entries(fields)) {
37
- const held = record[key];
38
- value[key] = held;
39
- if (nullable && held === null)
40
- continue;
41
- if (!FIELD_CHECKS[kind].test(held)) {
42
- issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
43
- }
44
- }
45
- return issues.length > 0 ? { issues } : { value };
46
- },
47
- vendor: "geonosis-document",
48
- version: 1
30
+ const required = options?.required ?? [];
31
+ return schemaOf((input) => {
32
+ if (input === null || typeof input !== "object") {
33
+ return { issues: [{ message: "expected an object" }] };
49
34
  }
50
- };
35
+ const record = input;
36
+ const issues = [];
37
+ const value = {};
38
+ for (const [key, kind] of Object.entries(fields)) {
39
+ const held = record[key];
40
+ value[key] = held;
41
+ if (nullable && held === null && !required.includes(key))
42
+ continue;
43
+ if (!FIELD_CHECKS[kind].test(held)) {
44
+ issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
45
+ }
46
+ }
47
+ return issues.length > 0 ? { issues } : { value };
48
+ });
51
49
  };
52
50
  var parseWith = (schema, input) => {
53
51
  const result = schema["~standard"].validate(input);
@@ -73,7 +71,11 @@ var recordFields = {
73
71
  createdAt: "int",
74
72
  updatedAt: "int"
75
73
  };
76
- var headValidator = validatorOf(headFields, { nullable: true });
74
+ var requiredHeadFields = ["status"];
75
+ var headValidator = validatorOf(headFields, {
76
+ nullable: true,
77
+ required: requiredHeadFields
78
+ });
77
79
  var recordValidator = validatorOf(recordFields);
78
80
  var Document = {
79
81
  head: headValidator,
@@ -92,5 +94,6 @@ export {
92
94
  fieldPatterns,
93
95
  headFields,
94
96
  recordFields,
97
+ requiredHeadFields,
95
98
  validatorOf
96
99
  };