@onereach/state-machine-validation 0.0.0-stage → 1.0.0-framework.2
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 +230 -2
- package/dist/index.d.mts +132 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +33 -3
package/README.md
CHANGED
|
@@ -1,3 +1,231 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @onereach/state-machine-validation
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Engine-independent preparation of template-supplied JSON Schemas and validation
|
|
4
|
+
of state, function input, and function output. This package depends on contracts'
|
|
5
|
+
data types, not on AJV or another runtime schema engine. The
|
|
6
|
+
runtime compiler protocol belongs here, not in contracts.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { CachedStateTemplatePreparer } from '@onereach/state-machine-validation';
|
|
10
|
+
import { AjvJsonSchemaValidatorCompiler } from '@onereach/state-machine-json-schema-ajv';
|
|
11
|
+
import { StateTemplateStore } from '@onereach/state-machine-store';
|
|
12
|
+
|
|
13
|
+
const preparer = new CachedStateTemplatePreparer(new AjvJsonSchemaValidatorCompiler(), { maxRevisions: 256 });
|
|
14
|
+
const templates = new StateTemplateStore(driver, preparer);
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`StateTemplatePreparer.prepare(template)` prepares state/input/output validators and checks
|
|
18
|
+
`initialState` before returning a complete validator collection. The injected
|
|
19
|
+
`JsonSchemaValidatorCompiler` owns dialect, keyword, and reference validation.
|
|
20
|
+
The store still prepares before persistence and binds successful preparation to
|
|
21
|
+
the revision returned by storage without recompiling.
|
|
22
|
+
|
|
23
|
+
`StateTemplatePreparer` is uncached: each call compiles all schemas and checks
|
|
24
|
+
initial state again. Its `bind(identity, validators)` deliberately does nothing:
|
|
25
|
+
it accepts post-persistence notifications without inspecting or retaining them.
|
|
26
|
+
It can be used independently or injected into a store for uncached preparation.
|
|
27
|
+
Both preparers structurally satisfy the store-owned `StateTemplatePreparation`
|
|
28
|
+
capability; validation has no dependency on the store. Composition chooses the
|
|
29
|
+
compiler and caching policy, never the store.
|
|
30
|
+
`CachedStateTemplatePreparer` wraps the same preparation operation with:
|
|
31
|
+
|
|
32
|
+
- Schema and parsed-template identities use weak maps.
|
|
33
|
+
- Immutable revision identities use an LRU map with `get`, `bind`, `invalidate`,
|
|
34
|
+
and `clearRevisionCache` operations. Capacity defaults to 256 revisions;
|
|
35
|
+
`maxRevisions: 0` disables strong revision retention. Negative, fractional,
|
|
36
|
+
infinite, and unsafe capacities are rejected.
|
|
37
|
+
- Only successful schema compilations and complete preparations are cached.
|
|
38
|
+
- Schemas, templates, and initial state must remain immutable after preparation;
|
|
39
|
+
callers must not reuse an identity for different content.
|
|
40
|
+
- Clearing or evicting revisions does not clear weak identity caches. A retained
|
|
41
|
+
template object can still reuse its result; use a new object graph for new data.
|
|
42
|
+
|
|
43
|
+
Neither preparer freezes or clones caller-owned templates. Preparation assumes
|
|
44
|
+
canonical contract validation has already completed. Runtime data validation
|
|
45
|
+
remains non-transforming. Treat the complete schema/template graph as immutable
|
|
46
|
+
once supplied to the cached preparer; mutation is unsupported, not detected or
|
|
47
|
+
automatically recompiled.
|
|
48
|
+
|
|
49
|
+
Preparation accepts `ReadonlyStateMachineTemplate` views as well as mutable
|
|
50
|
+
authored templates. Store callers supply owned immutable snapshots; direct
|
|
51
|
+
preparer callers remain responsible for immutable input graphs. Preparation does
|
|
52
|
+
not apply the store's additional JSON-data snapshot restrictions by itself.
|
|
53
|
+
|
|
54
|
+
Prepared collections and per-function entries are frozen. The function lookup
|
|
55
|
+
implements `ReadonlyMap` without exposing a mutable `Map`, including through
|
|
56
|
+
iteration and `forEach`. Adapter-provided validator objects remain adapter-owned.
|
|
57
|
+
|
|
58
|
+
## Revision identity and compiler scope
|
|
59
|
+
|
|
60
|
+
`prepare(template, identity)`, `get(identity)`, `bind(identity, validators)`, and
|
|
61
|
+
`invalidate(identity)` accept `StateTemplateRevisionIdentity`:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const identity = {
|
|
65
|
+
namespace: 'tenant-a:templates',
|
|
66
|
+
templateId: template.id,
|
|
67
|
+
templateVersion: template.version,
|
|
68
|
+
revision: persistedRevision,
|
|
69
|
+
};
|
|
70
|
+
const validators = preparer.prepare(template, identity);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Namespace must identify the tenant and storage location; revision must identify
|
|
74
|
+
immutable content within that namespace and template ID/version. Omitted version
|
|
75
|
+
is distinct from a literal version such as `"latest"`. The store supplies its own
|
|
76
|
+
isolated namespace per driver identity, so sharing a preparer cannot mix drivers.
|
|
77
|
+
Stores sharing the same driver object can reuse prepared revisions.
|
|
78
|
+
Preparation rejects identities whose template ID/version do not match the input.
|
|
79
|
+
|
|
80
|
+
The revision LRU is retained independently of the store's loaded-snapshot LRU:
|
|
81
|
+
new snapshots created after store eviction/reset and snapshots loaded by another
|
|
82
|
+
store have different object identities. Revision reuse avoids recompiling their
|
|
83
|
+
schemas without retaining the loaded wrapper or executable as a cache artifact.
|
|
84
|
+
Injected engine validators may themselves retain schema graphs; this is not a
|
|
85
|
+
global memory bound. Configure `maxRevisions` separately from the store's
|
|
86
|
+
`maxCachedTemplates`. Zero store capacity alone does not disable validator reuse.
|
|
87
|
+
|
|
88
|
+
Each preparer is scoped to one fixed compiler configuration. Do not mutate that
|
|
89
|
+
configuration after use; create a new preparer instead. `bind` accepts only
|
|
90
|
+
complete results produced by that cached preparer, preventing cross-compiler reuse.
|
|
91
|
+
Bind only after successful persistence. Revision eviction releases this cache's
|
|
92
|
+
strong reference, not references held by adapters, stores, runtimes, or callers.
|
|
93
|
+
|
|
94
|
+
`assertSchema` throws `SchemaValidationError` with the target, message, and
|
|
95
|
+
`readonly issues: readonly SchemaValidationIssue[]`. The constructor requires an
|
|
96
|
+
array (use `[]` when empty) and copies the array, issue records, and any path
|
|
97
|
+
arrays/segment objects. Omitted paths remain omitted.
|
|
98
|
+
Engine-specific nested parameters remain the adapter's per-call snapshots.
|
|
99
|
+
Contract errors and pure semantic checks remain in contracts.
|
|
100
|
+
|
|
101
|
+
## Compiled validation results
|
|
102
|
+
|
|
103
|
+
`JsonSchemaValidatorCompiler.compile<T>(schema)` returns a
|
|
104
|
+
`SynchronousDataValidator<T, SchemaValidationIssue>`, which implements Standard Schema v1 directly.
|
|
105
|
+
Its synchronous `validator['~standard'].validate(value)` method returns:
|
|
106
|
+
|
|
107
|
+
- `{ value: T }`, where `value` is the original input.
|
|
108
|
+
- `{ issues: readonly SchemaValidationIssue[] }`, with issues
|
|
109
|
+
owned by that validation call.
|
|
110
|
+
|
|
111
|
+
Validation never clones successful values, supplies defaults, coerces input, or
|
|
112
|
+
strips properties. Earlier results remain independent of subsequent validations;
|
|
113
|
+
there is no mutable "last issues" property. Adapters must normalize and snapshot
|
|
114
|
+
their engine's errors before returning a failure.
|
|
115
|
+
|
|
116
|
+
The generic `T` is a caller-supplied type assertion, not TypeScript inference from
|
|
117
|
+
an arbitrary runtime JSON Schema. These validators do not implement creation
|
|
118
|
+
transformations or the full `Contract` interface.
|
|
119
|
+
|
|
120
|
+
## Standard Schema as the engine protocol
|
|
121
|
+
|
|
122
|
+
Pass a compiled runtime validator directly to a Standard Schema consumer.
|
|
123
|
+
There is no adapter or separate native validation method:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { AjvJsonSchemaValidatorCompiler } from '@onereach/state-machine-json-schema-ajv';
|
|
127
|
+
|
|
128
|
+
const compiler = new AjvJsonSchemaValidatorCompiler();
|
|
129
|
+
const compiled = compiler.compile<{ counter: number }>({
|
|
130
|
+
type: 'object',
|
|
131
|
+
properties: { counter: { type: 'integer' } },
|
|
132
|
+
required: ['counter'],
|
|
133
|
+
});
|
|
134
|
+
const result = compiled['~standard'].validate({ counter: 1 });
|
|
135
|
+
if (result.issues) {
|
|
136
|
+
console.error(result.issues);
|
|
137
|
+
} else {
|
|
138
|
+
console.log(result.value.counter);
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`SynchronousDataValidator<T, Issue>` narrows Standard Schema's allowed result to
|
|
143
|
+
synchronous, non-transforming validation. `Issue` defaults to
|
|
144
|
+
`StandardSchemaV1.Issue`; runtime execution requires no JSON Schema compilation
|
|
145
|
+
or engine fields. Engines
|
|
146
|
+
identify themselves through the standard vendor metadata (AJV uses
|
|
147
|
+
`@onereach/state-machine-json-schema-ajv`). Input and output types are the same
|
|
148
|
+
caller-asserted `T`, not inferred from arbitrary runtime JSON Schema.
|
|
149
|
+
Unexpected engine exceptions propagate rather than becoming data issues.
|
|
150
|
+
Standard Schema permits synchronous results; generic consumers should still
|
|
151
|
+
support promises from other implementations.
|
|
152
|
+
|
|
153
|
+
JSON Schema engines expose required messages and decoded JSON Pointer segments. Root paths become
|
|
154
|
+
`[]`; escaped property names are decoded once. Numeric segments remain strings
|
|
155
|
+
because JSON Pointers cannot distinguish array indices from numeric object keys.
|
|
156
|
+
Missing messages fall back to the engine keyword, then `Invalid value`.
|
|
157
|
+
Engine paths are preserved semantically: required-property paths are not rewritten
|
|
158
|
+
using engine-specific parameters. `keyword`, `schemaPath`, and `params` remain
|
|
159
|
+
available as optional issue extensions on that same result. Generic Standard
|
|
160
|
+
Schema consumers may discard these extensions. Other data validators may use any
|
|
161
|
+
Standard Schema path form, including omitted paths, numeric/symbol keys, and
|
|
162
|
+
`{ key }` segments. `assertSchema`, template preparation,
|
|
163
|
+
and runtime execution all consume this one Standard Schema operation.
|
|
164
|
+
|
|
165
|
+
This protocol does not add parsing defaults, transformations, JSON Schema
|
|
166
|
+
conversion, or the contracts package's `Contract` interface. Compilation, dialect
|
|
167
|
+
validation, and reference resolution remain the injected engine's responsibility.
|
|
168
|
+
|
|
169
|
+
## Compilation versus execution
|
|
170
|
+
|
|
171
|
+
`JsonSchemaValidatorCompiler` remains the preparation boundary for persisted
|
|
172
|
+
JSON Schemas. It returns data validators with optional engine diagnostics.
|
|
173
|
+
The optional `@onereach/state-machine-json-schema-ajv` integration implements that
|
|
174
|
+
compiler using AJV. The composition root selects it; this package has no AJV
|
|
175
|
+
dependency or engine-specific setup logic.
|
|
176
|
+
`FunctionValidators` and `StateTemplateValidators` are execution-facing
|
|
177
|
+
collections of `SynchronousDataValidator` values, with no compilation requirement.
|
|
178
|
+
The JSON Schema preparers produce these same collections, but callers may also
|
|
179
|
+
provide independent data validators directly to the runtime.
|
|
180
|
+
|
|
181
|
+
Keep `assertSchema` as the common targeted-error boundary. Do not add store,
|
|
182
|
+
service, or runtime wrappers to reinterpret validation results. Validators supplied
|
|
183
|
+
directly must preserve successful input identity and never coerce, default, strip,
|
|
184
|
+
or otherwise transform data. Standard Schema compatibility alone does not enforce
|
|
185
|
+
these semantic guarantees; potentially asynchronous or transforming validators
|
|
186
|
+
are not automatically suitable for runtime execution.
|
|
187
|
+
|
|
188
|
+
## Import migration
|
|
189
|
+
|
|
190
|
+
These exports moved out of the former `@onereach/state-machine-core` package
|
|
191
|
+
(now `@onereach/state-machine-contracts`) to this package:
|
|
192
|
+
|
|
193
|
+
- Template preparation (now `StateTemplatePreparer` / `CachedStateTemplatePreparer`)
|
|
194
|
+
- Execution collections (now `FunctionValidators` and `StateTemplateValidators`)
|
|
195
|
+
- `assertSchema`, `SchemaValidationError`, and `SchemaValidationTarget`
|
|
196
|
+
- `JsonSchemaValidatorCompiler`
|
|
197
|
+
- `SchemaValidationIssue`
|
|
198
|
+
|
|
199
|
+
Replace `SchemaValidator<T>` / `CompiledJsonSchemaValidator<T>` with
|
|
200
|
+
`SynchronousDataValidator<T>`. Replace `CompiledFunctionValidators` and
|
|
201
|
+
`CompiledStateTemplateValidators` with `FunctionValidators` and
|
|
202
|
+
`StateTemplateValidators`. No compatibility aliases are exported.
|
|
203
|
+
Call `validator['~standard'].validate(value)`, then inspect `result.issues`:
|
|
204
|
+
if present, validation failed (including an empty issue array); otherwise read
|
|
205
|
+
`result.value`. Remove `toStandardSchema` wrappers. `StandardSchemaAdapter` and
|
|
206
|
+
`SchemaValidationResult` are no longer exported, and there is no duplicate
|
|
207
|
+
`validator.validate()` method or compatibility alias.
|
|
208
|
+
|
|
209
|
+
Runtime `SchemaValidationIssue` values require only `message`, support all
|
|
210
|
+
optional Standard Schema `path` forms, and allow optional `keyword`, `schemaPath`,
|
|
211
|
+
and `params` extensions.
|
|
212
|
+
This applies to both validation results and `SchemaValidationError.issues`,
|
|
213
|
+
including forwarded step error payloads. Step error display messages still use
|
|
214
|
+
escaped JSON Pointers. Runtime issues are distinct from contracts' engine-independent
|
|
215
|
+
`ContractIssue` values (`path` and required `message` only).
|
|
216
|
+
Contract errors and runtime errors are converted to their own public diagnostics
|
|
217
|
+
at their respective boundaries.
|
|
218
|
+
|
|
219
|
+
There is no contracts re-export of the runtime validation protocol, avoiding a
|
|
220
|
+
dependency back from contracts to preparation. The step-service public
|
|
221
|
+
`SchemaValidationError` re-export remains available.
|
|
222
|
+
|
|
223
|
+
Replace `new StateTemplateValidatorCompiler(engine).compile(template, key)` with
|
|
224
|
+
`new CachedStateTemplatePreparer(engine).prepare(template, identity)`, or use
|
|
225
|
+
`StateTemplatePreparer` when caching is unnecessary. There is no old-name alias.
|
|
226
|
+
Replace `SchemaValidationError.errors` with `.issues`; nullable diagnostics are
|
|
227
|
+
no longer accepted. Step validation error data now also uses `issues`.
|
|
228
|
+
|
|
229
|
+
Build dependencies first with
|
|
230
|
+
`pnpm exec turbo run build --filter=@onereach/state-machine-validation`, then run
|
|
231
|
+
`pnpm --filter @onereach/state-machine-validation exec vitest run`.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { JsonSchema, ReadonlyStateMachineTemplate } from "@onereach/state-machine-contracts";
|
|
2
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Standard Schema diagnostic with optional runtime-engine details.
|
|
6
|
+
* Consumers require only standard messages and optional paths. JSON Schema
|
|
7
|
+
* engines decode pointers into string segments; other implementations may use
|
|
8
|
+
* any Standard Schema path representation.
|
|
9
|
+
*/
|
|
10
|
+
interface SchemaValidationIssue extends StandardSchemaV1.Issue {
|
|
11
|
+
keyword?: string;
|
|
12
|
+
schemaPath?: string;
|
|
13
|
+
params?: unknown;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Synchronous, non-transforming data validation, independent of compilation.
|
|
17
|
+
* Success returns the original value; failure returns issues owned by that call.
|
|
18
|
+
* Implementations must preserve input identity and must not coerce, default,
|
|
19
|
+
* strip, or otherwise transform successful input. Standard Schema alone does
|
|
20
|
+
* not enforce these guarantees. Generic Standard Schema validators are not
|
|
21
|
+
* interchangeable unless they honor this stricter contract.
|
|
22
|
+
*/
|
|
23
|
+
interface SynchronousDataValidator<T = unknown, Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> extends StandardSchemaV1<T, T> {
|
|
24
|
+
readonly '~standard': Omit<StandardSchemaV1.Props<T, T>, 'validate'> & {
|
|
25
|
+
readonly validate: (value: unknown) => StandardSchemaV1.SuccessResult<T> | {
|
|
26
|
+
readonly issues: readonly Issue[];
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Lowest-level adapter interface.
|
|
32
|
+
*
|
|
33
|
+
* Contracts' embedded-schema checks establish shape only. An adapter must validate
|
|
34
|
+
* the schema against its supported dialect's meta-schema, reject unsupported
|
|
35
|
+
* dialects/keywords and unresolved references, then compile a synchronous
|
|
36
|
+
* validator. Any preparation failure must throw before returning a validator.
|
|
37
|
+
*
|
|
38
|
+
* Schemas without $schema use the adapter's documented default dialect.
|
|
39
|
+
* Implementations must not silently ignore unsupported validation constraints
|
|
40
|
+
* or fetch external references implicitly; references must already be resolvable.
|
|
41
|
+
*/
|
|
42
|
+
interface JsonSchemaValidatorCompiler {
|
|
43
|
+
/**
|
|
44
|
+
* Validate and compile a schema, or throw. Never returns an async validator.
|
|
45
|
+
*/
|
|
46
|
+
compile<T = unknown>(schema: JsonSchema): SynchronousDataValidator<T, SchemaValidationIssue>;
|
|
47
|
+
}
|
|
48
|
+
interface FunctionValidators {
|
|
49
|
+
readonly input: SynchronousDataValidator<Record<string, unknown>>;
|
|
50
|
+
readonly output?: SynchronousDataValidator;
|
|
51
|
+
}
|
|
52
|
+
interface StateTemplateValidators {
|
|
53
|
+
readonly state: SynchronousDataValidator<Record<string, unknown>>;
|
|
54
|
+
readonly functions: ReadonlyMap<string, FunctionValidators>;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Persistent identity within one storage namespace. A revision must identify
|
|
58
|
+
* immutable content; version distinguishes independently versioned templates.
|
|
59
|
+
* Namespace must distinguish tenants, drivers, and storage locations.
|
|
60
|
+
*/
|
|
61
|
+
interface StateTemplateRevisionIdentity {
|
|
62
|
+
readonly namespace: string;
|
|
63
|
+
readonly templateId: string;
|
|
64
|
+
readonly templateVersion?: string;
|
|
65
|
+
readonly revision: string;
|
|
66
|
+
}
|
|
67
|
+
interface StateTemplatePreparationCacheOptions {
|
|
68
|
+
/**
|
|
69
|
+
* Maximum strongly retained revisions, using least-recently-used eviction.
|
|
70
|
+
* Defaults to 256. Zero disables revision retention, not weak identity caches.
|
|
71
|
+
*/
|
|
72
|
+
readonly maxRevisions?: number;
|
|
73
|
+
}
|
|
74
|
+
type SchemaValidationTarget = 'initial-state' | 'input' | 'output' | 'state-before' | 'state-after';
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/preparer.d.ts
|
|
77
|
+
/**
|
|
78
|
+
* Uncached preparation using one fixed compiler configuration.
|
|
79
|
+
* Templates and their schema graphs must remain immutable after preparation.
|
|
80
|
+
* This operation does not freeze or clone caller-owned data.
|
|
81
|
+
*/
|
|
82
|
+
declare class StateTemplatePreparer {
|
|
83
|
+
private readonly schemaCompiler;
|
|
84
|
+
constructor(schemaCompiler: JsonSchemaValidatorCompiler);
|
|
85
|
+
prepare(definition: ReadonlyStateMachineTemplate): StateTemplateValidators;
|
|
86
|
+
/**
|
|
87
|
+
* Deliberately retain no revision association. This uncached policy accepts
|
|
88
|
+
* post-persistence binding notifications but does not inspect or cache them.
|
|
89
|
+
*/
|
|
90
|
+
bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void;
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/cached-preparer.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Compiler-scoped weak identity caches plus bounded LRU revision retention.
|
|
96
|
+
* Inputs must remain immutable and identities must never be reused for new content.
|
|
97
|
+
* Use a new preparer when compiler configuration changes.
|
|
98
|
+
*/
|
|
99
|
+
declare class CachedStateTemplatePreparer {
|
|
100
|
+
private readonly schemaCache;
|
|
101
|
+
private readonly templateCache;
|
|
102
|
+
private readonly revisionCache;
|
|
103
|
+
private readonly preparer;
|
|
104
|
+
private readonly maxRevisions;
|
|
105
|
+
private readonly owned;
|
|
106
|
+
constructor(schemaCompiler: JsonSchemaValidatorCompiler, options?: StateTemplatePreparationCacheOptions);
|
|
107
|
+
get(identity: StateTemplateRevisionIdentity): StateTemplateValidators | undefined;
|
|
108
|
+
prepare(definition: ReadonlyStateMachineTemplate, identity?: StateTemplateRevisionIdentity): StateTemplateValidators;
|
|
109
|
+
/**
|
|
110
|
+
* Bind this preparer's complete result after a successful persistence operation.
|
|
111
|
+
* Results from another preparer/compiler configuration are rejected.
|
|
112
|
+
*/
|
|
113
|
+
bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void;
|
|
114
|
+
invalidate(identity: StateTemplateRevisionIdentity): void;
|
|
115
|
+
/**
|
|
116
|
+
* Release strongly retained revisions; weak identity caches remain intact.
|
|
117
|
+
*/
|
|
118
|
+
clearRevisionCache(): void;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/errors.d.ts
|
|
122
|
+
declare class SchemaValidationError extends Error {
|
|
123
|
+
readonly target: SchemaValidationTarget;
|
|
124
|
+
readonly issues: readonly SchemaValidationIssue[];
|
|
125
|
+
constructor(target: SchemaValidationTarget, issues: readonly SchemaValidationIssue[]);
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/validation.d.ts
|
|
129
|
+
declare function assertSchema<T>(validator: SynchronousDataValidator<T>, value: unknown, target: SchemaValidationTarget): asserts value is T;
|
|
130
|
+
//#endregion
|
|
131
|
+
export { CachedStateTemplatePreparer, type FunctionValidators, type JsonSchemaValidatorCompiler, SchemaValidationError, type SchemaValidationIssue, type SchemaValidationTarget, type StateTemplatePreparationCacheOptions, StateTemplatePreparer, type StateTemplateRevisionIdentity, type StateTemplateValidators, type SynchronousDataValidator, assertSchema };
|
|
132
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/preparer.ts","../src/cached-preparer.ts","../src/errors.ts","../src/validation.ts"],"mappings":";;;;;;;;;UASiB,8BAA8B,iBAAiB;EAC9D;EAEA;EAEA;;;;;;;;;;UAWe,yBACf,aACA,cAAc,iBAAiB,QAAQ,iBAAiB,eAChD,iBAAiB,GAAG;WACnB,aAAa,KAAK,iBAAiB,MAAM,GAAG;aAC1C,WAAW,mBAAmB,iBAAiB,cAAc;eAAgB,iBAAiB;;;;;;;;;;;;;;;;UAgB1F;;;;EAIf,QAAQ,aAAa,QAAQ,aAAa,yBAAyB,GAAG;;UAGvD;WACN,OAAO,yBAAyB;WAEhC,SAAS;;UAGH;WACN,OAAO,yBAAyB;WAEhC,WAAW,oBAAoB;;;;;;;UAQzB;WACN;WACA;WACA;WACA;;UAGM;;;;;WAKN;;KAGC;;;;;;;;cCtEC;mBACM;EAEL,YAAA,gBAAgB;EAIrB,QAAQ,YAAY,+BAA+B;;;;;EAqBnD,KAAK,UAAU,+BAA+B,YAAY;;;;;;;;;cC1BtD;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,gBAAgB,6BAA6B,UAAS;EAgB3D,IAAI,UAAU,gCAAgC;EAU9C,QACL,YAAY,8BACZ,WAAW,gCACV;;;;;EAmBI,KAAK,UAAU,+BAA+B,YAAY;EAe1D,WAAW,UAAU;;;;EAOrB;;;;cC7FI,8BAA8B;WACzB,QAAQ;WACR,iBAAiB;EAErB,YAAA,QAAQ,wBAAwB,iBAAiB;;;;iBCH/C,aAAa,GAC3B,WAAW,yBAAyB,IACpC,gBACA,QAAQ,iCACC,SAAS"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class extends Error{target;issues;constructor(e,t){super(`Schema validation failed: ${e}`),this.name=`SchemaValidationError`,this.target=e,this.issues=t.map(e=>({...e,...e.path!==void 0&&{path:e.path.map(e=>typeof e==`object`?{...e}:e)}}))}};function t(t,n,r){let i=t[`~standard`].validate(n);if(i.issues)throw new e(r,i.issues)}var n=class{schemaCompiler;constructor(e){this.schemaCompiler=e}prepare(e){let n=this.schemaCompiler.compile(e.stateSchema);t(n,e.initialState,`initial-state`);let i=new Map;for(let t of e.functions)i.set(t.name,Object.freeze({input:this.schemaCompiler.compile(t.inputSchema),output:t.outputSchema?this.schemaCompiler.compile(t.outputSchema):void 0}));return Object.freeze({state:n,functions:r(i)})}bind(e,t){}};function r(e){let t={size:e.size,get:t=>e.get(t),has:t=>e.has(t),entries:()=>e.entries(),keys:()=>e.keys(),values:()=>e.values(),[Symbol.iterator]:()=>e[Symbol.iterator](),forEach(n,r){for(let[i,a]of e)n.call(r,a,i,t)}};return Object.freeze(t)}var i=class{schemaCache=new WeakMap;templateCache=new WeakMap;revisionCache=new Map;preparer;maxRevisions;owned=new WeakMap;constructor(e,t={}){if(this.maxRevisions=t.maxRevisions??256,!Number.isSafeInteger(this.maxRevisions)||this.maxRevisions<0)throw RangeError(`maxRevisions must be a non-negative safe integer`);let r=this.schemaCache;this.preparer=new n({compile(t){let n=r.get(t);if(n)return n;let i=e.compile(t);return r.set(t,i),i}})}get(e){let t=a(e),n=this.revisionCache.get(t);return n&&(this.revisionCache.delete(t),this.revisionCache.set(t,n)),n}prepare(e,t){if(t&&(t.templateId!==e.id||t.templateVersion!==e.version))throw Error(`Revision identity does not match the template`);let n=t?this.get(t):void 0;if(n)return n;let r=this.templateCache.get(e);return r||(r=this.preparer.prepare(e),this.templateCache.set(e,r),this.owned.set(r,{id:e.id,version:e.version})),t&&this.bind(t,r),r}bind(e,t){let n=this.owned.get(t);if(!n)throw Error(`Cannot bind validators from another preparer`);if(e.templateId!==n.id||e.templateVersion!==n.version)throw Error(`Revision identity does not match the template`);let r=a(e);if(this.revisionCache.delete(r),this.maxRevisions!==0&&(this.revisionCache.set(r,t),this.revisionCache.size>this.maxRevisions)){let e=this.revisionCache.keys().next().value;e!==void 0&&this.revisionCache.delete(e)}}invalidate(e){this.revisionCache.delete(a(e))}clearRevisionCache(){this.revisionCache.clear()}};function a(e){return JSON.stringify([e.namespace,e.templateId,e.templateVersion,e.revision])}export{i as CachedStateTemplatePreparer,e as SchemaValidationError,n as StateTemplatePreparer,t as assertSchema};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/validation.ts","../src/preparer.ts","../src/cached-preparer.ts"],"sourcesContent":["import type { SchemaValidationIssue, SchemaValidationTarget } from './types.ts';\n\nexport class SchemaValidationError extends Error {\n public readonly target: SchemaValidationTarget;\n public readonly issues: readonly SchemaValidationIssue[];\n\n constructor(target: SchemaValidationTarget, issues: readonly SchemaValidationIssue[]) {\n super(`Schema validation failed: ${target}`);\n\n this.name = 'SchemaValidationError';\n this.target = target;\n this.issues = issues.map((issue) => ({\n ...issue,\n ...(issue.path !== undefined && {\n path: issue.path.map((segment) => (typeof segment === 'object' ? { ...segment } : segment)),\n }),\n }));\n }\n}\n","import { SchemaValidationError } from './errors.ts';\nimport type { SynchronousDataValidator, SchemaValidationTarget } from './types.ts';\n\nexport function assertSchema<T>(\n validator: SynchronousDataValidator<T>,\n value: unknown,\n target: SchemaValidationTarget,\n): asserts value is T {\n const result = validator['~standard'].validate(value);\n if (result.issues) throw new SchemaValidationError(target, result.issues);\n}\n","import type { ReadonlyStateMachineTemplate } from '@onereach/state-machine-contracts';\n\nimport type {\n FunctionValidators,\n StateTemplateValidators,\n JsonSchemaValidatorCompiler,\n StateTemplateRevisionIdentity,\n} from './types.ts';\nimport { assertSchema } from './validation.ts';\n\n/**\n * Uncached preparation using one fixed compiler configuration.\n * Templates and their schema graphs must remain immutable after preparation.\n * This operation does not freeze or clone caller-owned data.\n */\nexport class StateTemplatePreparer {\n private readonly schemaCompiler: JsonSchemaValidatorCompiler;\n\n constructor(schemaCompiler: JsonSchemaValidatorCompiler) {\n this.schemaCompiler = schemaCompiler;\n }\n\n public prepare(definition: ReadonlyStateMachineTemplate): StateTemplateValidators {\n const state = this.schemaCompiler.compile<Record<string, unknown>>(definition.stateSchema);\n // Reject invalid initial state before a template can be persisted.\n assertSchema(state, definition.initialState, 'initial-state');\n const functions = new Map<string, FunctionValidators>();\n for (const function_ of definition.functions) {\n functions.set(\n function_.name,\n Object.freeze({\n input: this.schemaCompiler.compile<Record<string, unknown>>(function_.inputSchema),\n output: function_.outputSchema ? this.schemaCompiler.compile(function_.outputSchema) : undefined,\n }),\n );\n }\n return Object.freeze({ state, functions: readonlyFunctions(functions) });\n }\n\n /**\n * Deliberately retain no revision association. This uncached policy accepts\n * post-persistence binding notifications but does not inspect or cache them.\n */\n public bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void {\n void identity;\n void validators;\n }\n}\n\n// Expose no mutable Map, including through forEach's third argument.\nfunction readonlyFunctions(functions: Map<string, FunctionValidators>): ReadonlyMap<string, FunctionValidators> {\n const view: ReadonlyMap<string, FunctionValidators> = {\n size: functions.size,\n get: (key) => functions.get(key),\n has: (key) => functions.has(key),\n entries: () => functions.entries(),\n keys: () => functions.keys(),\n values: () => functions.values(),\n [Symbol.iterator]: () => functions[Symbol.iterator](),\n forEach(callback, thisArgument) {\n for (const [key, value] of functions) callback.call(thisArgument, value, key, view);\n },\n };\n return Object.freeze(view);\n}\n","import type { JsonSchema, ReadonlyStateMachineTemplate } from '@onereach/state-machine-contracts';\n\nimport { StateTemplatePreparer } from './preparer.ts';\nimport type {\n SynchronousDataValidator,\n StateTemplateValidators,\n SchemaValidationIssue,\n JsonSchemaValidatorCompiler,\n StateTemplatePreparationCacheOptions,\n StateTemplateRevisionIdentity,\n} from './types.ts';\n\n/**\n * Compiler-scoped weak identity caches plus bounded LRU revision retention.\n * Inputs must remain immutable and identities must never be reused for new content.\n * Use a new preparer when compiler configuration changes.\n */\nexport class CachedStateTemplatePreparer {\n private readonly schemaCache = new WeakMap<object, SynchronousDataValidator<unknown, SchemaValidationIssue>>();\n private readonly templateCache = new WeakMap<ReadonlyStateMachineTemplate, StateTemplateValidators>();\n private readonly revisionCache = new Map<string, StateTemplateValidators>();\n private readonly preparer: StateTemplatePreparer;\n private readonly maxRevisions: number;\n private readonly owned = new WeakMap<StateTemplateValidators, { id: string; version?: string }>();\n\n constructor(schemaCompiler: JsonSchemaValidatorCompiler, options: StateTemplatePreparationCacheOptions = {}) {\n this.maxRevisions = options.maxRevisions ?? 256;\n if (!Number.isSafeInteger(this.maxRevisions) || this.maxRevisions < 0)\n throw new RangeError('maxRevisions must be a non-negative safe integer');\n const cache = this.schemaCache;\n this.preparer = new StateTemplatePreparer({\n compile<T>(schema: JsonSchema): SynchronousDataValidator<T, SchemaValidationIssue> {\n const cached = cache.get(schema);\n if (cached) return cached as SynchronousDataValidator<T, SchemaValidationIssue>;\n const compiled = schemaCompiler.compile<T>(schema);\n cache.set(schema, compiled);\n return compiled;\n },\n });\n }\n\n public get(identity: StateTemplateRevisionIdentity): StateTemplateValidators | undefined {\n const key = revisionKey(identity);\n const cached = this.revisionCache.get(key);\n if (cached) {\n this.revisionCache.delete(key);\n this.revisionCache.set(key, cached);\n }\n return cached;\n }\n\n public prepare(\n definition: ReadonlyStateMachineTemplate,\n identity?: StateTemplateRevisionIdentity,\n ): StateTemplateValidators {\n if (identity && (identity.templateId !== definition.id || identity.templateVersion !== definition.version))\n throw new Error('Revision identity does not match the template');\n const revisionCached = identity ? this.get(identity) : undefined;\n if (revisionCached) return revisionCached;\n let prepared = this.templateCache.get(definition);\n if (!prepared) {\n prepared = this.preparer.prepare(definition);\n this.templateCache.set(definition, prepared);\n this.owned.set(prepared, { id: definition.id, version: definition.version });\n }\n if (identity) this.bind(identity, prepared);\n return prepared;\n }\n\n /**\n * Bind this preparer's complete result after a successful persistence operation.\n * Results from another preparer/compiler configuration are rejected.\n */\n public bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void {\n const template = this.owned.get(validators);\n if (!template) throw new Error('Cannot bind validators from another preparer');\n if (identity.templateId !== template.id || identity.templateVersion !== template.version)\n throw new Error('Revision identity does not match the template');\n const key = revisionKey(identity);\n this.revisionCache.delete(key);\n if (this.maxRevisions === 0) return;\n this.revisionCache.set(key, validators);\n if (this.revisionCache.size > this.maxRevisions) {\n const oldest = this.revisionCache.keys().next().value;\n if (oldest !== undefined) this.revisionCache.delete(oldest);\n }\n }\n\n public invalidate(identity: StateTemplateRevisionIdentity): void {\n this.revisionCache.delete(revisionKey(identity));\n }\n\n /**\n * Release strongly retained revisions; weak identity caches remain intact.\n */\n public clearRevisionCache(): void {\n this.revisionCache.clear();\n }\n}\n\nfunction revisionKey(identity: StateTemplateRevisionIdentity): string {\n return JSON.stringify([identity.namespace, identity.templateId, identity.templateVersion, identity.revision]);\n}\n"],"mappings":"AAEA,IAAa,EAAb,cAA2C,KAAM,CAC/C,OACA,OAEA,YAAY,EAAgC,EAA0C,CACpF,MAAM,6BAA6B,GAAQ,EAE3C,KAAK,KAAO,wBACZ,KAAK,OAAS,EACd,KAAK,OAAS,EAAO,IAAK,IAAW,CACnC,GAAG,EACH,GAAI,EAAM,OA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M,8CAA8C,EAC7E,GAAI,EAAS,aAAe,EAAS,IAAM,EAAS,kBAAoB,EAAS,QAC/E,MAAU,MAAM,+CAA+C,EACjE,IAAM,EAAM,EAAY,CAAQ,EAChC,QAAK,cAAc,OAAO,CAAG,EACzB,KAAK,eAAiB,IAC1B,KAAK,cAAc,IAAI,EAAK,CAAU,EAClC,KAAK,cAAc,KAAO,KAAK,cAAc,CAC/C,IAAM,EAAS,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAC5C,IAAW,IAAA,IAAW,KAAK,cAAc,OAAO,CAAM,CAC5D,CACF,CAEA,WAAkB,EAA+C,CAC/D,KAAK,cAAc,OAAO,EAAY,CAAQ,CAAC,CACjD,CAKA,oBAAkC,CAChC,KAAK,cAAc,MAAM,CAC3B,CACF,EAEA,SAAS,EAAY,EAAiD,CACpE,OAAO,KAAK,UAAU,CAAC,EAAS,UAAW,EAAS,WAAY,EAAS,gBAAiB,EAAS,QAAQ,CAAC,CAC9G"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onereach/state-machine-validation",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-framework.2",
|
|
4
|
+
"description": "Engine-independent State Machine schema preparation and validation",
|
|
5
|
+
"author": "OneReach Development Team <dev.team@onereach.ai>",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"sideEffects": false,
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"@arethetypeswrong/core": "^0.18.5",
|
|
17
|
+
"publint": "^0.3.24",
|
|
18
|
+
"tsdown": "^0.22.14",
|
|
19
|
+
"typescript": "^6.0.3"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@onereach/state-machine-contracts": "1.0.0-framework.12",
|
|
23
|
+
"@standard-schema/spec": "^1.1.0"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./dist/index.mjs",
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsdown --config tsdown.config.mts",
|
|
31
|
+
"typecheck": "tsc --noEmit --incremental --tsBuildInfoFile .cache/typecheck/source.tsbuildinfo && tsc --noEmit -p test/tsconfig.json --incremental --tsBuildInfoFile .cache/typecheck/test.tsbuildinfo",
|
|
32
|
+
"test": "pnpm run unit",
|
|
33
|
+
"unit": "vitest run",
|
|
34
|
+
"unit:coverage": "vitest run --coverage"
|
|
35
|
+
}
|
|
6
36
|
}
|