@onereach/state-machine-contracts 0.0.0-stage → 1.0.0-framework.12
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/README.md +455 -2
- package/dist/index.d.mts +741 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +14 -0
- package/dist/index.mjs.map +1 -0
- package/dist/json-schemas/CreateStateMachineInstanceRequestSchema.json +64 -0
- package/dist/json-schemas/CreateStateMachineTemplateSchema.json +203 -0
- package/dist/json-schemas/ExecuteStateMachineFunctionRequestSchema.json +38 -0
- package/dist/json-schemas/FunctionImplementationSchema.json +55 -0
- package/dist/json-schemas/FunctionKindSchema.json +8 -0
- package/dist/json-schemas/JsonSchemaSchema.json +7 -0
- package/dist/json-schemas/ObjectJsonSchemaSchema.json +16 -0
- package/dist/json-schemas/StateMachineFunctionDefinitionSchema.json +140 -0
- package/dist/json-schemas/StateMachineInstanceSchema.json +99 -0
- package/dist/json-schemas/StateMachineTemplateBindingSchema.json +26 -0
- package/dist/json-schemas/StateMachineTemplateSchema.json +203 -0
- package/dist/schemas/index.d.mts +732 -0
- package/dist/schemas/index.d.mts.map +1 -0
- package/dist/schemas/index.mjs +2 -0
- package/dist/schemas/index.mjs.map +1 -0
- package/package.json +59 -3
package/README.md
CHANGED
|
@@ -1,3 +1,456 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @onereach/state-machine-contracts
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This package defines the persisted format for State Machine templates and instances.
|
|
4
|
+
|
|
5
|
+
## Schema ownership
|
|
6
|
+
|
|
7
|
+
Author definitions in `src/schemas/`; these modules must not import generated
|
|
8
|
+
artifacts, public types, or contracts. The generator reads `src/schemas/index.ts`
|
|
9
|
+
directly. `src/types.ts` re-exports generated data types for downstream source;
|
|
10
|
+
`src/schemas.ts` provides schema objects only; the root owns domain types and contracts.
|
|
11
|
+
`src/contracts/` owns executable boundaries, issue normalization, creation
|
|
12
|
+
transformations, and pure semantic checks.
|
|
13
|
+
|
|
14
|
+
Run `pnpm --filter @onereach/state-machine-contracts typecheck:schemas` to check authoring
|
|
15
|
+
without generating artifacts. Normal builds generate before bundling downstream
|
|
16
|
+
consumers; whole-package typechecking still requires generation.
|
|
17
|
+
|
|
18
|
+
`ReadonlyStateMachineTemplate` and `ReadonlyStateMachineFunctionDefinition` are
|
|
19
|
+
readonly views used by storage/preparation/execution APIs. These types alone do
|
|
20
|
+
not establish ownership or freeze data. Mutable authored domain types remain
|
|
21
|
+
available, and pure contract parsing retains its documented copy/reference
|
|
22
|
+
semantics; the template store separately enforces owned immutable JSON-data
|
|
23
|
+
snapshots and documents unsupported values.
|
|
24
|
+
|
|
25
|
+
## Strict template contracts
|
|
26
|
+
|
|
27
|
+
The [current framework architecture](../../docs/architecture/README.md#contracts-and-persisted-data)
|
|
28
|
+
describes the separation of draft creation, strict canonical validation, and
|
|
29
|
+
explicit migrations. Template contracts are available through
|
|
30
|
+
the `@onereach/state-machine-contracts` root entry point. Stores use
|
|
31
|
+
these contracts for creation, canonical saves, and canonical loads. Function,
|
|
32
|
+
implementation, binding, and embedded-schema contracts follow the same strict
|
|
33
|
+
canonical policy. Instance creation and function execution have separate request
|
|
34
|
+
contracts; step-configuration contracts and package restructuring remain separate work.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import {
|
|
38
|
+
CreateStateMachineTemplateContract,
|
|
39
|
+
StateMachineTemplateContract,
|
|
40
|
+
} from '@onereach/state-machine-contracts';
|
|
41
|
+
import type { StateMachineTemplateDraft, StateMachineTemplate } from '@onereach/state-machine-contracts';
|
|
42
|
+
|
|
43
|
+
const template = CreateStateMachineTemplateContract.parse(rawDraft);
|
|
44
|
+
const canonical = StateMachineTemplateContract.parse(storedValue);
|
|
45
|
+
const schema = StateMachineTemplateContract['~standard'].jsonSchema.input({
|
|
46
|
+
target: 'draft-2020-12',
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Creation validates the draft, explicitly transforms omitted implementation
|
|
51
|
+
`capabilities` into fresh authored defaults, then validates the canonical result.
|
|
52
|
+
The draft validator itself neither claims to produce canonical data nor applies defaults.
|
|
53
|
+
Canonical validation requires that field and never repairs missing data. Both
|
|
54
|
+
reject unknown closed-contract properties, invalid supplied defaults, non-record
|
|
55
|
+
contract objects, and duplicate function names. Neither coerces or mutates input.
|
|
56
|
+
Embedded schemas, state, and metadata preserve their open-record keys.
|
|
57
|
+
|
|
58
|
+
Function names must contain 1–64 ASCII letters, digits, underscores, or hyphens
|
|
59
|
+
(`^[a-zA-Z0-9_-]{1,64}$`) and remain unique within a template. This constraint
|
|
60
|
+
applies to drafts, canonical templates, and standalone function definitions,
|
|
61
|
+
including functions excluded from tool advertising.
|
|
62
|
+
|
|
63
|
+
Parsing does not provide a deep-clone or immutability boundary. Contract envelopes,
|
|
64
|
+
declared records, and arrays are copied, but values below opaque open-record keys
|
|
65
|
+
(such as nested state, metadata, and embedded schema keywords) can retain input
|
|
66
|
+
references. Clone explicitly when independent ownership is required.
|
|
67
|
+
|
|
68
|
+
### Pure execution declaration
|
|
69
|
+
|
|
70
|
+
Functions may declare `annotations: { pure: true }`: an author assertion that the
|
|
71
|
+
function uses only input/state and local computation, with no host context or
|
|
72
|
+
external effects. The field is optional in drafts and canonical templates;
|
|
73
|
+
creation preserves it without defaulting it. Omission or `pure: false` keeps
|
|
74
|
+
functions on trusted execution. Non-boolean values are rejected. The former
|
|
75
|
+
`implementation.execution` field is not supported; move its declaration to
|
|
76
|
+
`annotations.pure` explicitly rather than relying on normalization.
|
|
77
|
+
|
|
78
|
+
This declaration is platform-neutral. It permits a composition-selected backend
|
|
79
|
+
to choose isolated execution; it does not import Node APIs or enable a backend.
|
|
80
|
+
The optional Node worker compiler automatically selects declared-pure functions
|
|
81
|
+
and rejects host capabilities for selected functions. Core runtime without that
|
|
82
|
+
compiler keeps trusted execution. Contracts validate the declaration's shape,
|
|
83
|
+
not code purity or backend-specific capability policy.
|
|
84
|
+
|
|
85
|
+
`annotations.idempotent` remains a separate descriptive hint: it does not imply
|
|
86
|
+
purity, worker eligibility, retry authorization, or transactional external effects.
|
|
87
|
+
Neither declaration is a security sandbox or proof that code obeys its promise.
|
|
88
|
+
|
|
89
|
+
### Tool discovery declaration
|
|
90
|
+
|
|
91
|
+
Functions may set `annotations: { exposeAsTool: false }` to opt out of tool
|
|
92
|
+
advertising. Omission or explicit `true` makes a function eligible for export.
|
|
93
|
+
The optional boolean is preserved without adding a persisted default in creation
|
|
94
|
+
or canonical parsing. It is provider-neutral discovery policy, not execution
|
|
95
|
+
authorization, purity, or permission to retry. New functions are eligible by
|
|
96
|
+
default; review their schemas and intended exposure before publishing tools.
|
|
97
|
+
The [OpenAI adapter](../state-machine-openai/README.md) owns provider-specific
|
|
98
|
+
formatting, separate from persisted contracts and runtime behavior.
|
|
99
|
+
|
|
100
|
+
Both contracts implement Standard Schema and Standard JSON Schema, with synchronous
|
|
101
|
+
`parse` and `safeParse` conveniences. Errors use JSON Pointers for conveniences and
|
|
102
|
+
path segments for standard validation. `Contract<Input, Output>` and the named
|
|
103
|
+
draft/canonical types are exported from the same entry point.
|
|
104
|
+
|
|
105
|
+
Synchronous `contract['~standard'].validate(value)` is the canonical operation.
|
|
106
|
+
`parse` and `safeParse` delegate to it; only those conveniences construct
|
|
107
|
+
`ContractValidationError` and convert diagnostic paths back to JSON Pointers.
|
|
108
|
+
`StandardContractResult<T>` is compatible with Standard Schema v1, and its
|
|
109
|
+
`StandardContractIssue` diagnostics contain messages and decoded string path
|
|
110
|
+
segments only, without custom rule codes. Numeric path segments remain
|
|
111
|
+
strings, preserving numeric property names without guessing array indices.
|
|
112
|
+
Template creation composes draft validation, typed defaulting, and canonical
|
|
113
|
+
validation through this same synchronous protocol.
|
|
114
|
+
|
|
115
|
+
Contracts and runtime validators remain separate abstractions: contract creation
|
|
116
|
+
can intentionally transform drafts, whereas runtime data validation is
|
|
117
|
+
non-transforming. Standard JSON Schema projections remain structural only and
|
|
118
|
+
preserve the distinction between creation input and canonical output.
|
|
119
|
+
|
|
120
|
+
JSON Schema converters support **Draft 2020-12 only** and return independent
|
|
121
|
+
structural projections. They do not encode unique function names, JavaScript
|
|
122
|
+
prototype checks, default execution, or embedded-schema preparation. Unsupported
|
|
123
|
+
targets and nonempty `libraryOptions` (including requests for exact fidelity) throw.
|
|
124
|
+
Embedded-schema dialects are not rewritten.
|
|
125
|
+
|
|
126
|
+
Portable schemas are named `CreateStateMachineTemplateSchema` (draft structure)
|
|
127
|
+
and `StateMachineTemplateSchema` (canonical structure) under `/json-schemas/*`.
|
|
128
|
+
Internal generated validators check structure only; they do not perform creation
|
|
129
|
+
or semantic validation and are not public package exports.
|
|
130
|
+
|
|
131
|
+
The prior template schema, validator, and input/definition type exports have been
|
|
132
|
+
removed, not retained as aliases. `StateMachineTemplateDraft` is creation input;
|
|
133
|
+
`StateMachineTemplate` is canonical persisted data. Stored templates missing
|
|
134
|
+
required fields or containing unknown contract keys are rejected. There is no
|
|
135
|
+
automatic legacy normalization or migration, and loading never writes repairs.
|
|
136
|
+
|
|
137
|
+
## Strict instance contract
|
|
138
|
+
|
|
139
|
+
`StateMachineInstanceContract`, available from `/contracts` and the root entry
|
|
140
|
+
point, replaces the instance validator without a compatibility alias. It
|
|
141
|
+
implements both standard interfaces and provides synchronous `parse` / `safeParse`.
|
|
142
|
+
Its canonical input and output have the same `StateMachineInstance` type and
|
|
143
|
+
Draft 2020-12 structural schema; `StateMachineInstanceSchema` and its standalone
|
|
144
|
+
artifacts retain their names.
|
|
145
|
+
|
|
146
|
+
Validation rejects unknown instance and template-binding properties, missing
|
|
147
|
+
required fields, and invalid values without stripping, defaulting, or coercion.
|
|
148
|
+
State and metadata remain open records. UTC-only timestamp and safe-integer
|
|
149
|
+
sequence constraints are unchanged.
|
|
150
|
+
|
|
151
|
+
Instances now use persisted `schemaVersion: 2` and require
|
|
152
|
+
`retention: { ttlMs: number }`. The duration is a non-negative safe integer in
|
|
153
|
+
milliseconds; zero means no expiration. This policy is outside application `state`
|
|
154
|
+
and is not an execution argument. Template format remains version 1.
|
|
155
|
+
Version-1 instances and version-2 instances missing retention are rejected, not
|
|
156
|
+
defaulted or repaired on load. Migrate explicitly with a known TTL and a
|
|
157
|
+
revision-checked write; the previous duration cannot be recovered from old
|
|
158
|
+
instance documents. See the [store migration guidance](../state-machine-store/README.md#instance-retention-and-migration).
|
|
159
|
+
|
|
160
|
+
The instance store uses this contract on creation, loading, and saving. Creation
|
|
161
|
+
is still a domain operation: the store resolves the exact template revision,
|
|
162
|
+
clones and validates initial state, and assigns sequence and timestamps. There is
|
|
163
|
+
no pure creation-defaulting wrapper for instances. Saves validate the loaded
|
|
164
|
+
instance before constructing an update; neither saves nor loads repair malformed
|
|
165
|
+
persisted data. Revision checks and template-revision mismatch behavior remain.
|
|
166
|
+
|
|
167
|
+
## Instance creation request
|
|
168
|
+
|
|
169
|
+
`CreateStateMachineInstanceRequestContract` validates the request accepted by
|
|
170
|
+
`StateMachineInstanceStore.create` and `StateMachineService.create`. Its generated
|
|
171
|
+
`CreateStateMachineInstanceRequest` type is exported from core and `/contracts`.
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { CreateStateMachineInstanceRequestContract } from '@onereach/state-machine-contracts';
|
|
175
|
+
|
|
176
|
+
const request = CreateStateMachineInstanceRequestContract.parse({
|
|
177
|
+
id: 'conversation-123',
|
|
178
|
+
template: { id: 'counter', version: '1' },
|
|
179
|
+
// state and metadata are optional open records.
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Only `id`, `template`, optional `state`, optional `metadata`, and optional
|
|
184
|
+
`retention` are accepted.
|
|
185
|
+
Template references accept `id` and optional `version`, not a caller-provided
|
|
186
|
+
revision. Unknown fields, invalid supplied values, and persisted lifecycle fields
|
|
187
|
+
such as `sequence` or timestamps are rejected before template lookup or writes.
|
|
188
|
+
|
|
189
|
+
The contract is pure: it does not select state, resolve templates, read clocks,
|
|
190
|
+
or assign lifecycle fields. Both standard interfaces have identical request
|
|
191
|
+
input/output shapes and Draft 2020-12 structural projections, with `parse` and
|
|
192
|
+
`safeParse` conveniences. Missing state/metadata remain omitted; the store later
|
|
193
|
+
clones supplied state or the resolved template's initial state and validates it.
|
|
194
|
+
Structural request validation alone does not establish that a template exists or
|
|
195
|
+
that a state override satisfies its embedded schema.
|
|
196
|
+
|
|
197
|
+
The store assigns `{ ttlMs: 604_800_000 }` (one week) when creation omits retention.
|
|
198
|
+
This is a creation-time domain default, not a parser or load-time transformation.
|
|
199
|
+
An explicit `{ ttlMs: 0 }` is preserved.
|
|
200
|
+
|
|
201
|
+
`CreateStateMachineInstanceRequestSchema` is published under `/schemas`,
|
|
202
|
+
and `/json-schemas/*`. It is not the persisted instance schema.
|
|
203
|
+
|
|
204
|
+
## Execution request
|
|
205
|
+
|
|
206
|
+
`ExecuteStateMachineFunctionRequestContract` validates the service execution
|
|
207
|
+
envelope, with the generated `ExecuteStateMachineFunctionRequest` type available
|
|
208
|
+
from core and `/contracts`:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
const request = {
|
|
212
|
+
instance: { id: 'conversation-123' },
|
|
213
|
+
functionName: 'increment',
|
|
214
|
+
input: { amount: 1 },
|
|
215
|
+
};
|
|
216
|
+
await service.execute(request, context);
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
All three envelope fields are required; missing or `undefined` input is rejected.
|
|
220
|
+
The instance reference accepts only a nonempty `id`, and `functionName` must be a
|
|
221
|
+
nonempty string. Unknown envelope/reference fields are rejected before instance
|
|
222
|
+
lookup, preparation, execution, or writes. Context is a separate live argument,
|
|
223
|
+
not a field in the request.
|
|
224
|
+
|
|
225
|
+
Input is opaque to the envelope contract: it is neither inspected nor normalized.
|
|
226
|
+
Envelope acceptance does not establish that a function exists or that input
|
|
227
|
+
satisfies its schema. The prepared template performs function-specific validation
|
|
228
|
+
before implementation execution. Query/mutation semantics and concurrency checks
|
|
229
|
+
are unchanged; this envelope adds no command identity, retries, or durability.
|
|
230
|
+
|
|
231
|
+
The contract implements both standard interfaces and `parse` / `safeParse`.
|
|
232
|
+
`ExecuteStateMachineFunctionRequestSchema` is exported through `/schemas` and the
|
|
233
|
+
standalone JSON/compiled artifact paths, with matching structural input/output
|
|
234
|
+
projections. The old positional service execution API has no compatibility overload.
|
|
235
|
+
|
|
236
|
+
## Remaining canonical contracts
|
|
237
|
+
|
|
238
|
+
The root and `/contracts` entry points also export:
|
|
239
|
+
|
|
240
|
+
- `FunctionKindContract`
|
|
241
|
+
- `FunctionImplementationContract`
|
|
242
|
+
- `StateMachineFunctionDefinitionContract`
|
|
243
|
+
- `StateMachineTemplateBindingContract`
|
|
244
|
+
- `JsonSchemaContract`
|
|
245
|
+
- `ObjectJsonSchemaContract`
|
|
246
|
+
|
|
247
|
+
All implement both standard interfaces with identical canonical input/output
|
|
248
|
+
types and structural projections. Standalone function and binding validation
|
|
249
|
+
matches the same definitions nested inside templates and instances. Canonical
|
|
250
|
+
implementations require `capabilities`; only template creation supplies `[]` when
|
|
251
|
+
it is omitted. There are no standalone function-creation wrappers.
|
|
252
|
+
|
|
253
|
+
The former `*Validator` exports and `/validators` entry point are removed, not
|
|
254
|
+
retained as aliases. `FunctionImplementationInput` and
|
|
255
|
+
`StateMachineFunctionDefinitionInput` are removed: use the canonical named types,
|
|
256
|
+
or derive draft field types from `StateMachineTemplateDraft` when authoring drafts.
|
|
257
|
+
The standalone function schemas now describe canonical data and never declare
|
|
258
|
+
creation defaults. Template-binding types, schemas, and artifacts now use the
|
|
259
|
+
`StateMachineTemplateBinding` name, with no old-name aliases.
|
|
260
|
+
|
|
261
|
+
## Contract behavior
|
|
262
|
+
|
|
263
|
+
Contracts are authored once with TypeBox in `src/schemas/`. The tsdown build
|
|
264
|
+
projects those definitions to plain JSON Schema, uses Ajv standalone compilation
|
|
265
|
+
for structural validators, and uses `json-schema-to-typescript` for independent,
|
|
266
|
+
documented declarations. These tools are **development dependencies**; published
|
|
267
|
+
JavaScript imports no schema engine or builder and does not generate code at runtime.
|
|
268
|
+
Any Ajv/format runtime helpers are bundled into the package.
|
|
269
|
+
The shared build-time pipeline is owned by
|
|
270
|
+
[`@onereach/json-schema-aot`](../../tools/json-schema-aot/README.md).
|
|
271
|
+
The local build configuration selects authored schemas and opts into default validation;
|
|
272
|
+
domain semantics and creation transformations remain in this package.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import { StateMachineTemplateContract } from '@onereach/state-machine-contracts';
|
|
276
|
+
import type { StateMachineTemplate } from '@onereach/state-machine-contracts';
|
|
277
|
+
|
|
278
|
+
const template: StateMachineTemplate = StateMachineTemplateContract.parse(untrustedValue);
|
|
279
|
+
const result = StateMachineTemplateContract.safeParse(untrustedValue);
|
|
280
|
+
if (!result.success) console.error(result.error.issues);
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Every public `*Contract` implements `StandardSchemaV1` and `StandardJSONSchemaV1` from
|
|
284
|
+
`@standard-schema/spec`, including distinct input/output types where defaults are
|
|
285
|
+
applied. Standard Schema consumers can call `contract['~standard'].validate(value)`
|
|
286
|
+
and receive `{ value }` or `{ issues }`. The implementation is synchronous; the
|
|
287
|
+
standard interface permits asynchronous consumers as well.
|
|
288
|
+
|
|
289
|
+
All contracts reject unknown closed-contract properties; only template creation
|
|
290
|
+
supplies defaults. Canonical validation never strips fields, supplies defaults,
|
|
291
|
+
coerces primitive types, or mutates inputs.
|
|
292
|
+
Embedded JSON Schemas, state records, and metadata retain
|
|
293
|
+
their arbitrary keys. Arbitrary nested values in records are not deep-cloned.
|
|
294
|
+
Schema-defined object nodes must be plain or null-prototype records; class
|
|
295
|
+
instances, Dates, Maps, and Sets are rejected rather than converted to `{}`.
|
|
296
|
+
Plain records from other realms (such as Node VM contexts or iframes) are accepted.
|
|
297
|
+
Arrays are copied by index without invoking input-owned methods or iterators.
|
|
298
|
+
Unknown getters on closed contract structures are not evaluated when rejecting
|
|
299
|
+
extra properties. Instance timestamps retain UTC-only, non-leap-second behavior.
|
|
300
|
+
Template validation also rejects duplicate function names. Errors use JSON
|
|
301
|
+
Pointers in `ContractValidationError.issues`, and path segments at the Standard
|
|
302
|
+
Schema boundary, including the missing field for required-property errors.
|
|
303
|
+
|
|
304
|
+
## Exported artifacts
|
|
305
|
+
|
|
306
|
+
| Import path | Contents |
|
|
307
|
+
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
308
|
+
| `@onereach/state-machine-contracts` | Domain types, executable contracts, and engine-independent diagnostics |
|
|
309
|
+
| `@onereach/state-machine-contracts/schemas` | Deeply frozen plain JSON Schema objects only |
|
|
310
|
+
| `@onereach/state-machine-contracts/json-schemas/StateMachineTemplateSchema` | Portable canonical Draft 2020-12 JSON file |
|
|
311
|
+
|
|
312
|
+
The JSON path is available for every exported `*Schema`. Generated standalone
|
|
313
|
+
validators are internal build/test artifacts, not published `/compiled/*` APIs.
|
|
314
|
+
Use `*Contract.parse` / `safeParse` for complete validation, including semantic
|
|
315
|
+
and JavaScript object checks; portable JSON Schemas express structure only.
|
|
316
|
+
|
|
317
|
+
Portable JSON files are a supported interface for editors, external validators,
|
|
318
|
+
and non-JavaScript tooling. Exported JavaScript definitions are deeply frozen,
|
|
319
|
+
including nested arrays and default values. Standard JSON Schema converters
|
|
320
|
+
return independent, mutable projections for consumers that need customization.
|
|
321
|
+
|
|
322
|
+
Import contracts and domain types from the root, not the removed `/contracts`
|
|
323
|
+
subpath. Import schema objects from `/schemas`, not the root.
|
|
324
|
+
|
|
325
|
+
`JsonSchemaSchema` and `ObjectJsonSchemaSchema` (and the root's
|
|
326
|
+
`JsonSchemaContract` / `ObjectJsonSchemaContract`) check embedded **shape only**.
|
|
327
|
+
The persisted format accepts object-form schemas; boolean schemas are excluded.
|
|
328
|
+
`JsonSchema` remains an opaque record, not a claim that its keywords are valid.
|
|
329
|
+
|
|
330
|
+
The static contracts check embedded schema shapes, not their meta-schema validity
|
|
331
|
+
or the validity of state/input/output values against them. Those schemas arrive at
|
|
332
|
+
runtime and remain the responsibility of an injected
|
|
333
|
+
`JsonSchemaValidatorCompiler` used by `StateTemplatePreparer` from
|
|
334
|
+
`@onereach/state-machine-validation`. That package owns the compiler interfaces,
|
|
335
|
+
compiled validators, per-call validation results, preparation, caches, and runtime
|
|
336
|
+
data-validation errors, including `SchemaValidationIssue`; contracts owns
|
|
337
|
+
`ContractIssue` and `ContractValidationError` instead.
|
|
338
|
+
`JsonSchemaValidatorCompiler`, `SynchronousDataValidator`,
|
|
339
|
+
`StateTemplatePreparer`, `CachedStateTemplatePreparer`, compiled template-validator types,
|
|
340
|
+
`assertSchema`, `SchemaValidationError`, and `SchemaValidationTarget` are exported
|
|
341
|
+
by that validation package, not contracts. The adapter must validate schemas
|
|
342
|
+
against its supported dialect, reject unsupported dialects/keywords and unresolved
|
|
343
|
+
references, and return only synchronous validators. `StateTemplateStore.create` and `.save`
|
|
344
|
+
prepares state/input/output schemas and validates `initialState` before writing.
|
|
345
|
+
|
|
346
|
+
## Contract diagnostics
|
|
347
|
+
|
|
348
|
+
`ContractValidationError.issues` contains `ContractIssue` values exported from the
|
|
349
|
+
root entry point. Each issue has a JSON Pointer `path` and a required `message`.
|
|
350
|
+
Generated validator errors are normalized into this representation;
|
|
351
|
+
runtime-engine fields such as `keyword`, `schemaPath`, `params`, and `instancePath`
|
|
352
|
+
are not exposed, and contract issues do not carry rule `code` values.
|
|
353
|
+
Standard Schema validation returns message/path-segment issues. Use error types
|
|
354
|
+
to classify contract versus runtime failures; messages are for display, not
|
|
355
|
+
machine-readable rule classification.
|
|
356
|
+
|
|
357
|
+
Runtime JSON Schema diagnostics are a separate `SchemaValidationIssue` type owned
|
|
358
|
+
by `@onereach/state-machine-validation`. Import it there, not from contracts. Contracts does
|
|
359
|
+
not depend on the runtime validation package to describe its contract errors.
|
|
360
|
+
|
|
361
|
+
## Building and testing
|
|
362
|
+
|
|
363
|
+
Run `pnpm build`, `pnpm unit`, or `pnpm typecheck` inside this package.
|
|
364
|
+
Tests and typechecking build the artifacts through Turbo first; the root
|
|
365
|
+
`pnpm unit` builds the workspace through Turbo before running Vitest. Turbo caches
|
|
366
|
+
both `dist/` and `generated/` so source-based tests also work after a cache hit.
|
|
367
|
+
Root ESLint runs the cached contracts build first for the same reason.
|
|
368
|
+
Root `pnpm test` builds once before running typechecks, coverage, and lint
|
|
369
|
+
concurrently, preventing independent builds from competing over the same outputs.
|
|
370
|
+
The `@onereach/json-schema-aot/rolldown` plugin generates from `src/schemas/index.ts`
|
|
371
|
+
before module loading and declaration generation. It is registered through
|
|
372
|
+
tsdown's `inputOptions`; tsdown's `copy` configuration
|
|
373
|
+
publishes portable JSON alongside the bundled entry points. Standalone validators
|
|
374
|
+
are bundled into contracts rather than exposed as generator-specific subpaths.
|
|
375
|
+
Compilation is staged under `.build/`; failures preserve working generated
|
|
376
|
+
artifacts. Completed artifacts replace the previous directory only after all
|
|
377
|
+
schemas and declarations have been produced, with rollback if promotion fails.
|
|
378
|
+
The build validates authored creation defaults against their field constraints
|
|
379
|
+
with default application disabled. Invalid defaults fail before output promotion;
|
|
380
|
+
default values, examples, metadata, and embedded schemas are not traversed as
|
|
381
|
+
additional schema definitions.
|
|
382
|
+
|
|
383
|
+
Run `pnpm dev` (or `pnpm watch`) for native tsdown watch mode. The schema plugin
|
|
384
|
+
watches transitive authoring inputs, evaluates them in fresh workers, and
|
|
385
|
+
regenerates before declaration generation and bundling. Generation is serialized;
|
|
386
|
+
failures preserve the last generated artifacts and watch mode permits recovery
|
|
387
|
+
after a fix. There is no separate custom watcher.
|
|
388
|
+
Build workspace dependencies first. After editing the AOT tool itself, rebuild
|
|
389
|
+
it and restart watch; build configuration changes also require a restart.
|
|
390
|
+
Generation runs after tsdown's cleanup: `dist/` is not transactionally retained
|
|
391
|
+
on failure. The rollback-safe guarantee applies to `generated/`.
|
|
392
|
+
|
|
393
|
+
- `src/`: authored contracts, wrappers, and interfaces.
|
|
394
|
+
- `src/schemas/`: build-time TypeBox definitions, not runtime entry points.
|
|
395
|
+
- `.build/`: ignored temporary compiler inputs/outputs.
|
|
396
|
+
- `generated/`: ignored generated modules, declarations, and JSON assets.
|
|
397
|
+
- `dist/`: ignored publishable contracts, declarations, and portable JSON.
|
|
398
|
+
|
|
399
|
+
Tests cover creation, strict canonical validation, semantic checks, standard types/results and
|
|
400
|
+
paths, per-contract acceptance/rejection corpora, runtime/AOT agreement,
|
|
401
|
+
generation failure recovery (including failed installation and rollback), and an
|
|
402
|
+
isolated consumer with no TypeBox, Ajv, declaration generator, or Zod installed and
|
|
403
|
+
runtime code generation disabled. Generated `schema-values` modules contain
|
|
404
|
+
deeply frozen plain literals; runtime contracts and `/schemas` use these modules,
|
|
405
|
+
not TypeBox builder calls. Published declarations require only the existing
|
|
406
|
+
Standard Schema type dependency.
|
|
407
|
+
|
|
408
|
+
## Persisted schema evolution
|
|
409
|
+
|
|
410
|
+
`schemaVersion` identifies a persisted document format, not the npm package
|
|
411
|
+
version, a template's logical `version`, a storage revision, or an instance's
|
|
412
|
+
`sequence`. Template and instance contracts currently require the literal `1`.
|
|
413
|
+
|
|
414
|
+
Change the relevant document's `schemaVersion` when its persisted representation
|
|
415
|
+
or interpretation changes incompatibly: for example, renaming a stored field,
|
|
416
|
+
adding a required field without existing data, or changing a field's meaning.
|
|
417
|
+
Compatible optional additions, documentation changes, tooling changes, and public
|
|
418
|
+
API renames do not by themselves require a persisted version bump. Version each
|
|
419
|
+
document format independently; review acceptance/rejection fixtures for every
|
|
420
|
+
format change. npm breaking-change releases and persisted format versions are
|
|
421
|
+
separate decisions.
|
|
422
|
+
|
|
423
|
+
Missing and unsupported versions fail normal contract validation. `safeParse`
|
|
424
|
+
returns `success: false` with `ContractValidationError`; `parse` throws that
|
|
425
|
+
error. Parsing neither detects and upgrades older formats nor falls back to
|
|
426
|
+
another version. Creation defaults do not supply or upgrade `schemaVersion`.
|
|
427
|
+
|
|
428
|
+
Migrations must be explicit, version-specific operations outside ordinary parsing
|
|
429
|
+
and loading. Put application-specific conversions in application tooling; reusable
|
|
430
|
+
format conversions may live in a dedicated migration module or package when needed.
|
|
431
|
+
No migration API is currently shipped. A migration should validate its source
|
|
432
|
+
format, transform it, and validate the result with the target canonical contract.
|
|
433
|
+
The persistence layer owns rollout, backups, and revision-checked writes, not the
|
|
434
|
+
contracts package. Do not hide migration side effects in validators or store loads.
|
|
435
|
+
|
|
436
|
+
## Migrating template consumers
|
|
437
|
+
|
|
438
|
+
This package replaces `@onereach/state-machine-core` without a compatibility
|
|
439
|
+
package. Update workspace and application imports to `@onereach/state-machine-contracts`.
|
|
440
|
+
Persisted formats remain unchanged. Import schema objects from `/schemas` and
|
|
441
|
+
contracts and domain types from the root. The embedded-schema contracts are now
|
|
442
|
+
`JsonSchemaContract` and `ObjectJsonSchemaContract`, matching `JsonSchema` /
|
|
443
|
+
`ObjectJsonSchema` and `JsonSchemaSchema` / `ObjectJsonSchemaSchema`; no old-name
|
|
444
|
+
aliases are exported. Replace
|
|
445
|
+
raw `/compiled/*` imports with contract operations or structural schema exports.
|
|
446
|
+
|
|
447
|
+
Use `CreateStateMachineTemplateContract` for draft creation and
|
|
448
|
+
`StateMachineTemplateContract` for canonical values. Plain `*Schema` objects do
|
|
449
|
+
not have parser methods. `safeParse` retains the `success` discriminator and
|
|
450
|
+
failures contain `ContractValidationError`.
|
|
451
|
+
|
|
452
|
+
Call `StateTemplateStore.create(draft)` to apply creation defaults, prepare schemas,
|
|
453
|
+
and persist with create-only semantics. Use `.save(canonical, options)` for strict
|
|
454
|
+
canonical publication with existing conditional-write options. Existing
|
|
455
|
+
noncanonical documents must be explicitly upgraded outside the load path before
|
|
456
|
+
they can be used. No compatibility adapters or old template contract aliases ship.
|