@onereach/state-machine-validation 1.0.0-framework.2 → 1.0.0-framework.4
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 +34 -0
- package/dist/index.d.mts +6 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -19,6 +19,9 @@ const templates = new StateTemplateStore(driver, preparer);
|
|
|
19
19
|
`JsonSchemaValidatorCompiler` owns dialect, keyword, and reference validation.
|
|
20
20
|
The store still prepares before persistence and binds successful preparation to
|
|
21
21
|
the revision returned by storage without recompiling.
|
|
22
|
+
`SchemaTarget` (`state`, `input`, or `output`) belongs to the validation type layer;
|
|
23
|
+
preparation and its telemetry adapter share it without deriving domain types from
|
|
24
|
+
instrumentation.
|
|
22
25
|
|
|
23
26
|
`StateTemplatePreparer` is uncached: each call compiles all schemas and checks
|
|
24
27
|
initial state again. Its `bind(identity, validators)` deliberately does nothing:
|
|
@@ -168,6 +171,37 @@ validation, and reference resolution remain the injected engine's responsibility
|
|
|
168
171
|
|
|
169
172
|
## Compilation versus execution
|
|
170
173
|
|
|
174
|
+
### Preparation tracing
|
|
175
|
+
|
|
176
|
+
Cache lookups also increment the API-only
|
|
177
|
+
`state_machine.preparation.cache.requests` counter with only `cache` (`revision`,
|
|
178
|
+
`template`, `schema`) and `result` (`hit`, `miss`). Only reached lookups count:
|
|
179
|
+
a revision hit skips template/schema lookups, and a template hit skips schemas.
|
|
180
|
+
Explicit revision `get` counts; bind/invalidate/clear and uncached preparation do
|
|
181
|
+
not. Failed compilation/preparation still counts its reached misses. These are
|
|
182
|
+
lookup counts, not cache occupancy or proof of fresh engine compilation.
|
|
183
|
+
Metrics work independently of spans; hosts own meter providers/readers/exporters.
|
|
184
|
+
Reporting failures cannot alter caching or replay compilation.
|
|
185
|
+
|
|
186
|
+
`template.prepare` measures synchronous preparation and initial-state validation.
|
|
187
|
+
`schema.compile` measures calls to the injected compiler with only a bounded
|
|
188
|
+
`state_machine.preparation.schema_target` (`state`, `input`, or `output`).
|
|
189
|
+
The uncached preparer emits spans on every call. The cached preparer emits them
|
|
190
|
+
only on the corresponding template/revision or schema-identity miss. A new
|
|
191
|
+
template reusing compiled schemas emits no schema spans; a template/revision hit
|
|
192
|
+
emits neither. Successful schema compilations remain cached after a later
|
|
193
|
+
preparation failure, but partial template collections are never published.
|
|
194
|
+
|
|
195
|
+
These are compiler-call spans, not evidence of fresh engine code generation;
|
|
196
|
+
engine-internal caches remain opaque. Direct compiler calls are not instrumented.
|
|
197
|
+
The package uses only the OpenTelemetry API; hosts own providers and context
|
|
198
|
+
management, including parent correlation and nested schema spans. Preparation
|
|
199
|
+
remains synchronous and runs once even if tracing fails, preserving return/error
|
|
200
|
+
identity. No schemas, state, names, revisions, or raw errors are recorded.
|
|
201
|
+
See the [telemetry reference](../../docs/architecture/telemetry.md).
|
|
202
|
+
|
|
203
|
+
### Execution-facing validators
|
|
204
|
+
|
|
171
205
|
`JsonSchemaValidatorCompiler` remains the preparation boundary for persisted
|
|
172
206
|
JSON Schemas. It returns data validators with optional engine diagnostics.
|
|
173
207
|
The optional `@onereach/state-machine-json-schema-ajv` integration implements that
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { JsonSchema, ReadonlyStateMachineTemplate } from "@onereach/state-machine-contracts";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
//#region src/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Preparation role of a template-supplied schema, independent of instrumentation.
|
|
6
|
+
*/
|
|
7
|
+
type SchemaTarget = 'state' | 'input' | 'output';
|
|
4
8
|
/**
|
|
5
9
|
* Standard Schema diagnostic with optional runtime-engine details.
|
|
6
10
|
* Consumers require only standard messages and optional paths. JSON Schema
|
|
@@ -100,7 +104,7 @@ declare class CachedStateTemplatePreparer {
|
|
|
100
104
|
private readonly schemaCache;
|
|
101
105
|
private readonly templateCache;
|
|
102
106
|
private readonly revisionCache;
|
|
103
|
-
private readonly
|
|
107
|
+
private readonly compiler;
|
|
104
108
|
private readonly maxRevisions;
|
|
105
109
|
private readonly owned;
|
|
106
110
|
constructor(schemaCompiler: JsonSchemaValidatorCompiler, options?: StateTemplatePreparationCacheOptions);
|
|
@@ -128,5 +132,5 @@ declare class SchemaValidationError extends Error {
|
|
|
128
132
|
//#region src/validation.d.ts
|
|
129
133
|
declare function assertSchema<T>(validator: SynchronousDataValidator<T>, value: unknown, target: SchemaValidationTarget): asserts value is T;
|
|
130
134
|
//#endregion
|
|
131
|
-
export { CachedStateTemplatePreparer, type FunctionValidators, type JsonSchemaValidatorCompiler, SchemaValidationError, type SchemaValidationIssue, type SchemaValidationTarget, type StateTemplatePreparationCacheOptions, StateTemplatePreparer, type StateTemplateRevisionIdentity, type StateTemplateValidators, type SynchronousDataValidator, assertSchema };
|
|
135
|
+
export { CachedStateTemplatePreparer, type FunctionValidators, type JsonSchemaValidatorCompiler, type SchemaTarget, SchemaValidationError, type SchemaValidationIssue, type SchemaValidationTarget, type StateTemplatePreparationCacheOptions, StateTemplatePreparer, type StateTemplateRevisionIdentity, type StateTemplateValidators, type SynchronousDataValidator, assertSchema };
|
|
132
136
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +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":"
|
|
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":";;;;;;KAMY;;;;;;;UAQK,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;;;;;;;;cC5CC;mBACM;EAEL,YAAA,gBAAgB;EAIrB,QAAQ,YAAY,+BAA+B;;;;;EAWnD,KAAK,UAAU,+BAA+B,YAAY;;;;;;;;;cC5CtD;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,gBAAgB,6BAA6B,UAAS;EAiB3D,IAAI,UAAU,gCAAgC;EAW9C,QACL,YAAY,8BACZ,WAAW,gCACV;;;;;EAoBI,KAAK,UAAU,+BAA+B,YAAY;EAe1D,WAAW,UAAU;;;;EAOrB;;;;cCnGI,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
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
import{recordCounter as e,traceSynchronous as t}from"@onereach/state-machine-telemetry";function n(t,n){e(`@onereach/state-machine-validation`,`state_machine.preparation.cache.requests`,`{request}`,1,{cache:t,result:n?`hit`:`miss`})}function r(e,n,r){return t(`@onereach/state-machine-validation`,e,n,e===`schema.compile`?`schema_compilation_failed`:`template_preparation_failed`,r?{"state_machine.preparation.schema_target":r}:void 0)}var i=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 a(e,t,n){let r=e[`~standard`].validate(t);if(r.issues)throw new i(n,r.issues)}function o(e,t){return r(`template.prepare`,()=>{let n=t.compile(e.stateSchema,`state`);a(n,e.initialState,`initial-state`);let r=new Map;for(let n of e.functions)r.set(n.name,Object.freeze({input:t.compile(n.inputSchema,`input`),output:n.outputSchema?t.compile(n.outputSchema,`output`):void 0}));return Object.freeze({state:n,functions:c(r)})})}var s=class{schemaCompiler;constructor(e){this.schemaCompiler=e}prepare(e){return o(e,{compile:(e,t)=>r(`schema.compile`,()=>this.schemaCompiler.compile(e),t)})}bind(e,t){}};function c(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 l=class{schemaCache=new WeakMap;templateCache=new WeakMap;revisionCache=new Map;compiler;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 i=this.schemaCache;this.compiler={compile(t,a){let o=i.get(t);if(n(`schema`,o!==void 0),o)return o;let s=r(`schema.compile`,()=>e.compile(t),a);return i.set(t,s),s}}}get(e){let t=u(e),r=this.revisionCache.get(t);return n(`revision`,r!==void 0),r&&(this.revisionCache.delete(t),this.revisionCache.set(t,r)),r}prepare(e,t){if(t&&(t.templateId!==e.id||t.templateVersion!==e.version))throw Error(`Revision identity does not match the template`);let r=t?this.get(t):void 0;if(r)return r;let i=this.templateCache.get(e);return n(`template`,i!==void 0),i||(i=o(e,this.compiler),this.templateCache.set(e,i),this.owned.set(i,{id:e.id,version:e.version})),t&&this.bind(t,i),i}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=u(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(u(e))}clearRevisionCache(){this.revisionCache.clear()}};function u(e){return JSON.stringify([e.namespace,e.templateId,e.templateVersion,e.revision])}export{l as CachedStateTemplatePreparer,i as SchemaValidationError,s as StateTemplatePreparer,a as assertSchema};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +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,OAAS,IAAA,IAAa,CAC9B,KAAM,EAAM,KAAK,IAAK,GAAa,OAAO,GAAY,SAAW,CAAE,GAAG,CAAQ,EAAI,CAAQ,CAC5F,CACF,EAAE,CACJ,CACF,ECfA,SAAgB,EACd,EACA,EACA,EACoB,CACpB,IAAM,EAAS,EAAU,YAAY,CAAC,SAAS,CAAK,EACpD,GAAI,EAAO,OAAQ,MAAM,IAAI,EAAsB,EAAQ,EAAO,MAAM,CAC1E,CCKA,IAAa,EAAb,KAAmC,CACjC,eAEA,YAAY,EAA6C,CACvD,KAAK,e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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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/telemetry.ts","../src/errors.ts","../src/validation.ts","../src/preparer.ts","../src/cached-preparer.ts"],"sourcesContent":["import { recordCounter, traceSynchronous } from '@onereach/state-machine-telemetry';\n\nimport type { SchemaTarget } from './types.ts';\n\nexport function recordPreparationCache(cache: 'revision' | 'template' | 'schema', isHit: boolean): void {\n recordCounter('@onereach/state-machine-validation', 'state_machine.preparation.cache.requests', '{request}', 1, {\n cache,\n result: isHit ? 'hit' : 'miss',\n });\n}\n\n/**\n * Keep preparation synchronous and run it once even if host tracing fails.\n */\nexport function tracePreparation<T>(\n name: 'template.prepare' | 'schema.compile',\n prepare: () => T,\n target?: SchemaTarget,\n): T {\n return traceSynchronous(\n '@onereach/state-machine-validation',\n name,\n prepare,\n name === 'schema.compile' ? 'schema_compilation_failed' : 'template_preparation_failed',\n target ? { 'state_machine.preparation.schema_target': target } : undefined,\n );\n}\n","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 { JsonSchema, ReadonlyStateMachineTemplate } from '@onereach/state-machine-contracts';\n\nimport { tracePreparation } from './telemetry.ts';\nimport type {\n FunctionValidators,\n StateTemplateValidators,\n JsonSchemaValidatorCompiler,\n StateTemplateRevisionIdentity,\n SynchronousDataValidator,\n SchemaValidationIssue,\n SchemaTarget,\n} from './types.ts';\nimport { assertSchema } from './validation.ts';\n\nexport interface PreparationCompiler {\n compile<T>(schema: JsonSchema, target: SchemaTarget): SynchronousDataValidator<T, SchemaValidationIssue>;\n}\n\n// Shared work boundary; cache-owning callers decide when compilation really runs.\nexport function prepareDefinition(\n definition: ReadonlyStateMachineTemplate,\n compiler: PreparationCompiler,\n): StateTemplateValidators {\n return tracePreparation('template.prepare', () => {\n const state = compiler.compile<Record<string, unknown>>(definition.stateSchema, 'state');\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: compiler.compile<Record<string, unknown>>(function_.inputSchema, 'input'),\n output: function_.outputSchema ? compiler.compile(function_.outputSchema, 'output') : undefined,\n }),\n );\n }\n return Object.freeze({ state, functions: readonlyFunctions(functions) });\n });\n}\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 return prepareDefinition(definition, {\n compile: <T>(schema: JsonSchema, target: SchemaTarget) =>\n tracePreparation('schema.compile', () => this.schemaCompiler.compile<T>(schema), target),\n });\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 { prepareDefinition } from './preparer.ts';\nimport type { PreparationCompiler } from './preparer.ts';\nimport { recordPreparationCache, tracePreparation } from './telemetry.ts';\nimport type {\n SynchronousDataValidator,\n StateTemplateValidators,\n SchemaValidationIssue,\n JsonSchemaValidatorCompiler,\n StateTemplatePreparationCacheOptions,\n StateTemplateRevisionIdentity,\n SchemaTarget,\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 compiler: PreparationCompiler;\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.compiler = {\n compile<T>(schema: JsonSchema, target: SchemaTarget): SynchronousDataValidator<T, SchemaValidationIssue> {\n const cached = cache.get(schema);\n recordPreparationCache('schema', cached !== undefined);\n if (cached) return cached as SynchronousDataValidator<T, SchemaValidationIssue>;\n const compiled = tracePreparation('schema.compile', () => schemaCompiler.compile<T>(schema), target);\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 recordPreparationCache('revision', cached !== undefined);\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 recordPreparationCache('template', prepared !== undefined);\n if (!prepared) {\n prepared = prepareDefinition(definition, this.compiler);\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":"wFAIA,SAAgB,EAAuB,EAA2C,EAAsB,CACtG,EAAc,qCAAsC,2CAA4C,YAAa,EAAG,CAC9G,QACA,OAAQ,EAAQ,MAAQ,MAC1B,CAAC,CACH,CAKA,SAAgB,EACd,EACA,EACA,EACG,CACH,OAAO,EACL,qCACA,EACA,EACA,IAAS,iBAAmB,4BAA8B,8BAC1D,EAAS,CAAE,0CAA2C,CAAO,EAAI,IAAA,EACnE,CACF,CCxBA,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,OAAS,IAAA,IAAa,CAC9B,KAAM,EAAM,KAAK,IAAK,GAAa,OAAO,GAAY,SAAW,CAAE,GAAG,CAAQ,EAAI,CAAQ,CAC5F,CACF,EAAE,CACJ,CACF,ECfA,SAAgB,EACd,EACA,EACA,EACoB,CACpB,IAAM,EAAS,EAAU,YAAY,CAAC,SAAS,CAAK,EACpD,GAAI,EAAO,OAAQ,MAAM,IAAI,EAAsB,EAAQ,EAAO,MAAM,CAC1E,CCSA,SAAgB,EACd,EACA,EACyB,CACzB,OAAO,EAAiB,uBAA0B,CAChD,IAAM,EAAQ,EAAS,QAAiC,EAAW,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AAS,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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onereach/state-machine-validation",
|
|
3
|
-
"version": "1.0.0-framework.
|
|
3
|
+
"version": "1.0.0-framework.4",
|
|
4
4
|
"description": "Engine-independent State Machine schema preparation and validation",
|
|
5
5
|
"author": "OneReach Development Team <dev.team@onereach.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -14,12 +14,17 @@
|
|
|
14
14
|
],
|
|
15
15
|
"devDependencies": {
|
|
16
16
|
"@arethetypeswrong/core": "^0.18.5",
|
|
17
|
+
"@opentelemetry/context-async-hooks": "^2.12.1",
|
|
18
|
+
"@opentelemetry/sdk-metrics": "^2.12.1",
|
|
19
|
+
"@opentelemetry/sdk-trace-base": "^2.12.1",
|
|
17
20
|
"publint": "^0.3.24",
|
|
18
21
|
"tsdown": "^0.22.14",
|
|
19
22
|
"typescript": "^6.0.3"
|
|
20
23
|
},
|
|
21
24
|
"dependencies": {
|
|
22
|
-
"@onereach/state-machine-contracts": "1.0.0-framework.
|
|
25
|
+
"@onereach/state-machine-contracts": "1.0.0-framework.13",
|
|
26
|
+
"@onereach/state-machine-telemetry": "1.0.0-framework.2",
|
|
27
|
+
"@opentelemetry/api": "~1.9.1",
|
|
23
28
|
"@standard-schema/spec": "^1.1.0"
|
|
24
29
|
},
|
|
25
30
|
"exports": {
|