constructa-core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,13 @@ Current APIs define trusted generator implementations, portable typed definition
19
19
 
20
20
  Use `defineGenerator()` for developer-authored executable implementations. An implementation declares a stable lowercase `type`, positive integer `version`, definition validator, optional dependency analysis hook, and `generate({ definition, context })` function. Validation returns schema `ValidationIssue` objects without imposing a validation-library dependency.
21
21
 
22
- `GeneratorDefinition<Output>` carries output information only at compile time; emitted definitions remain plain JSON data. Factories should use `createGeneratorDefinition()` so literal fields are preserved and the resulting definition is portable. Implementations receive randomness and child generation through `GenerationContext`; they must not use global randomness or built-in-specific execution switches.
22
+ `GeneratorDefinition<Output>` carries output information only at compile time; emitted definitions remain plain JSON data. Factories should use `createGeneratorDefinition()` so literal fields are preserved and the resulting definition is portable. Implementations receive a frozen `GenerationContext` capability view: validated random draws, the current definition path, and typed `executeChild(definition, pathSegment)`. Child dispatch uses the executor's registry snapshot, inherits the root random source, and appends exactly one path segment; implementations must not use global randomness or built-in-specific execution switches.
23
+
24
+ ## Runtime parsing
25
+
26
+ Use `parseDefinition(value, { registry, limits? })` for untrusted runtime definition data, or `parseDocument(value, { registry, limits? })` for a versioned document. Both validate portable JSON, registered generator IDs, each implementation's configuration, and nested typed definitions without invoking `generate`. `safeParseDefinition()` and `safeParseDocument()` return all bounded, deterministic structured issues; the throwing forms return the first issue. Definitions parsed from dynamic data intentionally have broad `GeneratorDefinition` output typing.
27
+
28
+ `parseTemplateTokens(source, { path? })` parses the MVP `{field}` and `{sibling.nested}` reference syntax into literal and reference tokens without resolving a value. Use `{{` and `}}` for literal braces. Empty paths, whitespace, braces inside a reference, and empty dot segments fail with `INVALID_TEMPLATE_TOKEN` at the supplied definition path.
23
29
 
24
30
  ## Random sources
25
31
 
@@ -31,6 +37,10 @@ Use `defineGenerator()` for developer-authored executable implementations. An im
31
37
 
32
38
  `createRegistry()` is advanced infrastructure. Register trusted implementations explicitly with `register()`. Duplicate type IDs fail without changing registry state; `replace()` is the deliberate replacement path and requires the type to already be registered. `lookup(type, path?)` resolves a registered implementation without a central built-in switch. Unknown IDs throw a dependency `UNKNOWN_GENERATOR` error at the supplied definition path plus `type`, with safe registered-type diagnostics. `snapshot()` returns an immutable, type-sorted registry view with the same lookup behavior; later registry changes do not affect it. Dispatch remains a separate concern.
33
39
 
40
+ ## Single-value execution
41
+
42
+ `createExecutor(registry)` is advanced infrastructure for executing one root definition. It snapshots the supplied registry, parses untrusted definitions, runs dependency analysis, and dispatches the resolved implementation. Its `generate(definition, options?)` method returns the definition's inferred output type. Supply either `{ seed }` for a fresh reproducible source or `{ random }` for a caller-owned injected source; supplying both is invalid. Definitions returned by `parseDefinition()` are recognized by the executor and are not validated again, while ordinary definitions are parsed once before dispatch. `maxDepth` bounds recursive child execution (default: 64). Bulk output is intentionally not part of this boundary.
43
+
34
44
  ## Dependency Boundary
35
45
 
36
46
  `constructa-schema` is the only Constructa runtime dependency that `constructa-core` may depend on.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { GeneratorDefinition, GeneratorDefinition as GeneratorDefinition$1, Infer, ValidationIssue, ValidationIssue as ValidationIssue$1, ValidationPath, ValidationPath as ValidationPath$1 } from "constructa-schema";
1
+ import { ConstructaError, GeneratorDefinition, GeneratorDefinition as GeneratorDefinition$1, Infer, ValidationIssue, ValidationIssue as ValidationIssue$1, ValidationPath, ValidationPath as ValidationPath$1, ValidationPathSegment, ValidationPathSegment as ValidationPathSegment$1 } from "constructa-schema";
2
2
  //#region src/index.d.ts
3
3
  /**
4
4
  * Random values are always half-open: `float()` returns [0, 1), while
@@ -11,6 +11,20 @@ type RandomSource = {
11
11
  };
12
12
  type RandomSourceAdapter = RandomSource;
13
13
  type Seed = number | string;
14
+ type ExecutionOptions = {
15
+ /** Uses a fresh deterministic source for this root execution. */
16
+ readonly seed?: Seed;
17
+ /**
18
+ * A caller-owned source consumed by this execution. The executor does not
19
+ * reset, clone, or otherwise retain it after the call returns.
20
+ */
21
+ readonly random?: RandomSource;
22
+ /** Maximum child-definition nesting below the root. Defaults to 64. */
23
+ readonly maxDepth?: number;
24
+ };
25
+ type Executor = {
26
+ generate: <Definition extends GeneratorDefinition$1>(definition: Definition, options?: ExecutionOptions) => import("constructa-schema").Infer<Definition>;
27
+ };
14
28
  declare const SEEDED_RANDOM_ALGORITHM = "mulberry32";
15
29
  declare const SEEDED_RANDOM_ALGORITHM_VERSION = 1;
16
30
  type SeededRandomMetadata = {
@@ -44,17 +58,132 @@ declare function getSeededRandomMetadata(): SeededRandomMetadata;
44
58
  /** Services supplied by the engine. Implementations must not use global randomness. */
45
59
  type GenerationContext = {
46
60
  readonly random: RandomSource;
47
- readonly generateChild: <Output>(definition: GeneratorDefinition$1<Output>) => Output;
61
+ /** The definition path currently being generated. */
62
+ readonly path: ValidationPath$1;
63
+ /** Delegates a typed child definition to the engine. */
64
+ readonly executeChild: <Output>(definition: GeneratorDefinition$1<Output>, pathSegment: ValidationPathSegment$1) => Output;
65
+ /**
66
+ * Read-only values from the object currently being generated. Values are
67
+ * available only after their field has completed.
68
+ */
69
+ readonly references: ReferenceResolver;
70
+ /** Creates an isolated scope for the fields of one composite object. */
71
+ readonly createObjectScope: () => ObjectGenerationScope;
72
+ /** Returns value dependencies declared by one direct child definition. */
73
+ readonly analyzeChildValueDependencies: (definition: GeneratorDefinition$1, pathSegment: ValidationPathSegment$1) => readonly ValueDependency[];
74
+ };
75
+ /** A property path relative to the object containing a reference. */
76
+ type ReferencePath = readonly string[];
77
+ /** A parsed template fragment. Braces are escaped with `{{` and `}}`. */
78
+ type TemplateToken = {
79
+ readonly type: "literal";
80
+ readonly value: string;
81
+ } | {
82
+ readonly type: "reference";
83
+ readonly path: ReferencePath;
84
+ };
85
+ type ParseTemplateTokensOptions = {
86
+ /** Definition-relative path reported for malformed template syntax. */
87
+ readonly path?: ValidationPath$1;
88
+ };
89
+ /**
90
+ * Parses MVP template syntax without executing or resolving references.
91
+ *
92
+ * `{field}` addresses a sibling and `{field.nested}` addresses a value below
93
+ * that sibling. `{{` and `}}` emit literal braces. Whitespace, empty path
94
+ * segments, and brace characters inside a reference are unsupported.
95
+ */
96
+ declare function parseTemplateTokens(source: string, options?: ParseTemplateTokensOptions): readonly TemplateToken[];
97
+ /** Parses one dot-separated object-local reference path. */
98
+ declare function parseReferencePath(source: string, path?: ValidationPath$1): ReferencePath;
99
+ /** A portable value dependency declared by a generator definition. */
100
+ type ValueDependency = {
101
+ readonly path: ReferencePath;
102
+ };
103
+ /** Dependencies for a direct field in a composite definition. */
104
+ type CompositeDependencyNode = {
105
+ readonly fieldPath: readonly [string];
106
+ readonly dependencies: readonly ValueDependency[];
107
+ };
108
+ /** Portable dependency data used to schedule one composite object. */
109
+ type CompositeDependencyAnalysis = {
110
+ readonly nodes: readonly CompositeDependencyNode[];
48
111
  };
112
+ /** The read-only capability supplied to generators that resolve references. */
113
+ type ReferenceResolver = {
114
+ resolve: (path: ReferencePath) => unknown;
115
+ };
116
+ /** Executes and records completed fields within one isolated object scope. */
117
+ type ObjectGenerationScope = {
118
+ executeChild: <Output>(definition: GeneratorDefinition$1<Output>, pathSegment: string) => Output;
119
+ };
120
+ type GenerationContextOptions = {
121
+ readonly random: RandomSource;
122
+ readonly path?: ValidationPath$1;
123
+ readonly executeChild?: GenerationContext["executeChild"];
124
+ readonly references?: ReferenceResolver;
125
+ readonly createObjectScope?: GenerationContext["createObjectScope"];
126
+ readonly analyzeChildValueDependencies?: GenerationContext["analyzeChildValueDependencies"];
127
+ };
128
+ /**
129
+ * Creates the engine-owned capability view supplied to implementations.
130
+ * Application code normally receives this through `generate`, rather than
131
+ * constructing one directly.
132
+ */
133
+ declare function createGenerationContext(options: GenerationContextOptions): GenerationContext;
134
+ /** Freezes direct-field dependency declarations into portable analysis data. */
135
+ declare function createCompositeDependencyAnalysis(nodes: readonly CompositeDependencyNode[]): CompositeDependencyAnalysis;
136
+ /**
137
+ * Returns a deterministic execution order for direct object fields. A
138
+ * dependency path may target a nested value below another direct field.
139
+ */
140
+ declare function scheduleCompositeDependencies(analysis: CompositeDependencyAnalysis): readonly string[];
141
+ type ParseLimits = {
142
+ readonly maxDepth?: number;
143
+ readonly maxIssues?: number;
144
+ readonly maxNodes?: number;
145
+ };
146
+ type ParseDefinitionOptions = {
147
+ readonly registry: Pick<GeneratorRegistry | GeneratorRegistrySnapshot, "lookup">;
148
+ readonly limits?: ParseLimits;
149
+ };
150
+ type ParseDocumentOptions = ParseDefinitionOptions;
151
+ type DefinitionParseResult = {
152
+ readonly success: true;
153
+ readonly value: ParsedGeneratorDefinition;
154
+ } | {
155
+ readonly success: false;
156
+ readonly issues: readonly ConstructaError[];
157
+ };
158
+ type DocumentParseResult = {
159
+ readonly success: true;
160
+ readonly value: import("constructa-schema").GeneratorDocumentV1;
161
+ } | {
162
+ readonly success: false;
163
+ readonly issues: readonly ConstructaError[];
164
+ };
165
+ /** Parses untrusted runtime definition data without executing generator code. */
166
+ declare function parseDefinition(value: unknown, options: ParseDefinitionOptions): ParsedGeneratorDefinition;
167
+ declare function safeParseDefinition(value: unknown, options: ParseDefinitionOptions): DefinitionParseResult;
168
+ /** Parses a versioned document and its root definition through the same pipeline. */
169
+ declare function parseDocument(value: unknown, options: ParseDocumentOptions): import("constructa-schema").GeneratorDocumentV1;
170
+ declare function safeParseDocument(value: unknown, options: ParseDocumentOptions): DocumentParseResult;
49
171
  type GeneratorDependency = {
50
172
  readonly typeId: string;
51
173
  readonly path: ValidationPath$1;
52
174
  };
175
+ declare const parsedGeneratorDefinition: unique symbol;
176
+ /** A runtime-validated definition accepted by an executor without revalidation. */
177
+ type ParsedGeneratorDefinition = GeneratorDefinition$1 & {
178
+ readonly [parsedGeneratorDefinition]: true;
179
+ };
53
180
  type GeneratorImplementation<Definition extends GeneratorDefinition$1<Output>, Output> = {
54
181
  readonly type: string;
55
182
  readonly version: number;
56
183
  readonly validateDefinition: (definition: unknown) => readonly ValidationIssue$1[];
57
184
  readonly analyzeDependencies?: (definition: Definition) => readonly GeneratorDependency[];
185
+ /** Declares object-local value references used by this definition. */
186
+ readonly analyzeValueDependencies?: (definition: Definition) => readonly ValueDependency[];
58
187
  readonly generate: (input: {
59
188
  readonly definition: Definition;
60
189
  readonly context: GenerationContext;
@@ -76,6 +205,11 @@ type GeneratorRegistry = {
76
205
  };
77
206
  /** Creates advanced registry infrastructure. Normal factories do not require it. */
78
207
  declare function createRegistry(): GeneratorRegistry;
208
+ /**
209
+ * Creates an advanced single-value executor over an immutable registry
210
+ * snapshot. Normal applications will receive this behavior through the SDK.
211
+ */
212
+ declare function createExecutor(registry: GeneratorRegistry | GeneratorRegistrySnapshot): Executor;
79
213
  /**
80
214
  * Defines a trusted, developer-authored generator implementation. This API has
81
215
  * no dependency on a particular validation library.
@@ -94,5 +228,5 @@ declare function invokeGeneratorImplementation<Definition extends GeneratorDefin
94
228
  readonly path?: ValidationPath$1;
95
229
  }): Output;
96
230
  //#endregion
97
- export { DeterminismCompatibility, GenerationContext, type GeneratorDefinition, GeneratorDependency, GeneratorImplementation, GeneratorRegistry, GeneratorRegistrySnapshot, type Infer, RandomSource, RandomSourceAdapter, RegisteredGenerator, SEEDED_RANDOM_ALGORITHM, SEEDED_RANDOM_ALGORITHM_VERSION, Seed, SeededRandomMetadata, type ValidationIssue, type ValidationPath, createDefaultRandomSource, createGeneratorDefinition, createRandomSource, createRegistry, createSeededRandom, defineGenerator, getSeededRandomMetadata, invokeGeneratorImplementation, normalizeSeed };
231
+ export { CompositeDependencyAnalysis, CompositeDependencyNode, DefinitionParseResult, DeterminismCompatibility, DocumentParseResult, ExecutionOptions, Executor, GenerationContext, GenerationContextOptions, type GeneratorDefinition, GeneratorDependency, GeneratorImplementation, GeneratorRegistry, GeneratorRegistrySnapshot, type Infer, ObjectGenerationScope, ParseDefinitionOptions, ParseDocumentOptions, ParseLimits, ParseTemplateTokensOptions, ParsedGeneratorDefinition, RandomSource, RandomSourceAdapter, ReferencePath, ReferenceResolver, RegisteredGenerator, SEEDED_RANDOM_ALGORITHM, SEEDED_RANDOM_ALGORITHM_VERSION, Seed, SeededRandomMetadata, TemplateToken, type ValidationIssue, type ValidationPath, type ValidationPathSegment, ValueDependency, createCompositeDependencyAnalysis, createDefaultRandomSource, createExecutor, createGenerationContext, createGeneratorDefinition, createRandomSource, createRegistry, createSeededRandom, defineGenerator, getSeededRandomMetadata, invokeGeneratorImplementation, normalizeSeed, parseDefinition, parseDocument, parseReferencePath, parseTemplateTokens, safeParseDefinition, safeParseDocument, scheduleCompositeDependencies };
98
232
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;KAoBY;EACV;EACA,QAAQ;EACR,MAAM,iBAAiB;;KAGb,sBAAsB;KAEtB;cAEC;cACA;KAED;WACD,kBAAkB;WAClB,gBAAgB;;KAGf;WACD;WACA;WACA,QAAQ;WACR,YAAY;WACZ,MAAM;WACN;;;;;;iBAYK,mBAAmB,SAAS,sBAAsB;;iBA0ClD,6BAA6B;;;;;iBAwC7B,cAAc,MAAM;;iBAcpB,mBAAmB,MAAM,OAAO;;iBAuChC,2BAA2B;;KAK/B;WACD,QAAQ;WACR,gBAAgB,QACvB,YAAY,sBAAoB,YAC7B;;KAGK;WACD;WACA,MAAM;;KAGL,wBACV,mBAAmB,sBAAoB,SACvC;WAES;WACA;WACA,qBACP,iCACY;WACL,uBACP,YAAY,wBACA;WACL,WAAW;aACT,YAAY;aACZ,SAAS;QACd;;KAGI;WACD;WACA;;KAGC;WACD,qBAAqB;WACrB,SACP,cACA,OAAO,qBACJ,wBAAwB;;KAGnB;EACV,WAAW,mBAAmB,sBAAoB,SAAS,QACzD,gBAAgB,wBAAwB,YAAY;EAEtD,UAAU,mBAAmB,sBAAoB,SAAS,QACxD,gBAAgB,wBAAwB,YAAY;EAEtD,SACE,cACA,OAAO,qBACJ,wBAAwB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,SAAS;WACT,OAAO;IAEjB"}
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
- import { ConstructaError, assertGeneratorDefinition, normalizeConstructaError } from "constructa-schema";
1
+ import { ConstructaError, assertGeneratorDefinition, normalizeConstructaError, parseDocument as parseDocument$1, validateDocument, validateGeneratorDefinition } from "constructa-schema";
2
2
  //#region src/index.ts
3
+ const validatedRandomSources = /* @__PURE__ */ new WeakSet();
3
4
  const SEEDED_RANDOM_ALGORITHM = "mulberry32";
4
5
  const SEEDED_RANDOM_ALGORITHM_VERSION = 1;
5
6
  const SEEDED_RANDOM_METADATA = Object.freeze({
@@ -12,7 +13,7 @@ const SEEDED_RANDOM_METADATA = Object.freeze({
12
13
  */
13
14
  function createRandomSource(adapter) {
14
15
  assertRandomSourceAdapter(adapter);
15
- return Object.freeze({
16
+ const source = Object.freeze({
16
17
  float() {
17
18
  const value = adapter.float();
18
19
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value >= 1) throw invalidRandomSource("float() must return a finite number in [0, 1).");
@@ -31,6 +32,8 @@ function createRandomSource(adapter) {
31
32
  return value;
32
33
  }
33
34
  });
35
+ validatedRandomSources.add(source);
36
+ return source;
34
37
  }
35
38
  /** Creates the default platform-backed random source. It makes no security claim. */
36
39
  function createDefaultRandomSource() {
@@ -115,6 +118,218 @@ function createSeededRandom(seed) {
115
118
  function getSeededRandomMetadata() {
116
119
  return SEEDED_RANDOM_METADATA;
117
120
  }
121
+ /**
122
+ * Parses MVP template syntax without executing or resolving references.
123
+ *
124
+ * `{field}` addresses a sibling and `{field.nested}` addresses a value below
125
+ * that sibling. `{{` and `}}` emit literal braces. Whitespace, empty path
126
+ * segments, and brace characters inside a reference are unsupported.
127
+ */
128
+ function parseTemplateTokens(source, options = {}) {
129
+ const path = options.path ?? [];
130
+ if (typeof source !== "string") throw templateTokenError(path, "Template source must be a string.");
131
+ assertContextPath(path);
132
+ const tokens = [];
133
+ let literal = "";
134
+ const appendLiteral = (value) => {
135
+ literal += value;
136
+ };
137
+ const flushLiteral = () => {
138
+ if (literal.length === 0) return;
139
+ tokens.push(Object.freeze({
140
+ type: "literal",
141
+ value: literal
142
+ }));
143
+ literal = "";
144
+ };
145
+ for (let index = 0; index < source.length; index += 1) {
146
+ const character = source[index];
147
+ if (character === "{") {
148
+ if (source[index + 1] === "{") {
149
+ appendLiteral("{");
150
+ index += 1;
151
+ continue;
152
+ }
153
+ const closingIndex = source.indexOf("}", index + 1);
154
+ if (closingIndex === -1) throw templateTokenError(path, "Template reference is missing a closing brace.");
155
+ const referencePath = parseReferencePath(source.slice(index + 1, closingIndex), path);
156
+ flushLiteral();
157
+ tokens.push(Object.freeze({
158
+ type: "reference",
159
+ path: referencePath
160
+ }));
161
+ index = closingIndex;
162
+ continue;
163
+ }
164
+ if (character === "}") {
165
+ if (source[index + 1] === "}") {
166
+ appendLiteral("}");
167
+ index += 1;
168
+ continue;
169
+ }
170
+ throw templateTokenError(path, "Template contains an unmatched closing brace.");
171
+ }
172
+ appendLiteral(character ?? "");
173
+ }
174
+ flushLiteral();
175
+ return Object.freeze(tokens);
176
+ }
177
+ /** Parses one dot-separated object-local reference path. */
178
+ function parseReferencePath(source, path = []) {
179
+ if (typeof source !== "string" || source.length === 0) throw templateTokenError(path, "Template reference must not be empty.");
180
+ assertContextPath(path);
181
+ const segments = source.split(".");
182
+ if (segments.some((segment) => segment.length === 0 || /[{}\s]/u.test(segment))) throw templateTokenError(path, "Template reference segments must be non-empty and cannot contain whitespace or braces.");
183
+ return Object.freeze(segments);
184
+ }
185
+ function templateTokenError(path, message) {
186
+ return new ConstructaError({
187
+ kind: "configuration",
188
+ code: "INVALID_TEMPLATE_TOKEN",
189
+ path,
190
+ message
191
+ });
192
+ }
193
+ /**
194
+ * Creates the engine-owned capability view supplied to implementations.
195
+ * Application code normally receives this through `generate`, rather than
196
+ * constructing one directly.
197
+ */
198
+ function createGenerationContext(options) {
199
+ if (typeof options !== "object" || options === null) throw contextError("INVALID_GENERATION_CONTEXT", [], "Context options must be an object.");
200
+ assertContextPath(options.path ?? []);
201
+ if (typeof options.executeChild !== "undefined" && typeof options.executeChild !== "function") throw contextError("INVALID_GENERATION_CONTEXT", [], "executeChild must be a function when present.");
202
+ const random = validatedRandomSources.has(options.random) ? options.random : createRandomSource(options.random);
203
+ const path = Object.freeze([...options.path ?? []]);
204
+ const executeChild = options.executeChild ?? ((definition, pathSegment) => {
205
+ assertGeneratorDefinition(definition, [...path, pathSegment]);
206
+ assertContextPathSegment(pathSegment);
207
+ throw new ConstructaError({
208
+ kind: "execution",
209
+ code: "CHILD_EXECUTION_UNAVAILABLE",
210
+ path: [...path, pathSegment],
211
+ message: "Child execution is not available in this generation context."
212
+ });
213
+ });
214
+ const references = options.references ?? unavailableReferenceResolver(path);
215
+ if (typeof references !== "object" || references === null || typeof references.resolve !== "function") throw contextError("INVALID_GENERATION_CONTEXT", [], "references must provide a resolve function when present.");
216
+ const createObjectScope = options.createObjectScope ?? (() => Object.freeze({ executeChild(definition, pathSegment) {
217
+ return executeChild(definition, pathSegment);
218
+ } }));
219
+ if (typeof createObjectScope !== "function") throw contextError("INVALID_GENERATION_CONTEXT", [], "createObjectScope must be a function when present.");
220
+ const analyzeChildValueDependencies = options.analyzeChildValueDependencies ?? (() => []);
221
+ if (typeof analyzeChildValueDependencies !== "function") throw contextError("INVALID_GENERATION_CONTEXT", [], "analyzeChildValueDependencies must be a function when present.");
222
+ return Object.freeze({
223
+ random,
224
+ path,
225
+ executeChild,
226
+ references: Object.freeze({ resolve: references.resolve }),
227
+ createObjectScope,
228
+ analyzeChildValueDependencies
229
+ });
230
+ }
231
+ /** Freezes direct-field dependency declarations into portable analysis data. */
232
+ function createCompositeDependencyAnalysis(nodes) {
233
+ if (!Array.isArray(nodes)) throw contextError("INVALID_COMPOSITE_DEPENDENCIES", [], "Composite dependency nodes must be an array.");
234
+ const names = /* @__PURE__ */ new Set();
235
+ const normalized = nodes.map((node, index) => {
236
+ if (!isCompositeDependencyNode(node) || names.has(node.fieldPath[0])) throw contextError("INVALID_COMPOSITE_DEPENDENCIES", ["nodes", index], "Each composite dependency node must name one unique field.");
237
+ names.add(node.fieldPath[0]);
238
+ return Object.freeze({
239
+ fieldPath: Object.freeze([...node.fieldPath]),
240
+ dependencies: Object.freeze(node.dependencies.map((dependency) => Object.freeze({ path: Object.freeze([...dependency.path]) })))
241
+ });
242
+ });
243
+ return Object.freeze({ nodes: Object.freeze(normalized) });
244
+ }
245
+ /**
246
+ * Returns a deterministic execution order for direct object fields. A
247
+ * dependency path may target a nested value below another direct field.
248
+ */
249
+ function scheduleCompositeDependencies(analysis) {
250
+ const nodes = analysis.nodes;
251
+ const byName = new Map(nodes.map((node) => [node.fieldPath[0], node]));
252
+ const remaining = /* @__PURE__ */ new Map();
253
+ const dependents = /* @__PURE__ */ new Map();
254
+ for (const node of nodes) {
255
+ const dependencies = /* @__PURE__ */ new Set();
256
+ for (const dependency of node.dependencies) {
257
+ const target = dependency.path[0];
258
+ if (target === void 0 || !byName.has(target)) throw new ConstructaError({
259
+ kind: "dependency",
260
+ code: "REFERENCE_NOT_FOUND",
261
+ path: [...node.fieldPath],
262
+ message: "A referenced object field could not be found."
263
+ });
264
+ dependencies.add(target);
265
+ const targets = dependents.get(target) ?? [];
266
+ targets.push(node.fieldPath[0]);
267
+ dependents.set(target, targets);
268
+ }
269
+ remaining.set(node.fieldPath[0], dependencies);
270
+ }
271
+ const ready = nodes.filter((node) => (remaining.get(node.fieldPath[0])?.size ?? 0) === 0).map((node) => node.fieldPath[0]);
272
+ const ordered = [];
273
+ while (ready.length > 0) {
274
+ const field = ready.shift();
275
+ if (field === void 0) continue;
276
+ ordered.push(field);
277
+ for (const dependent of dependents.get(field) ?? []) {
278
+ const dependencies = remaining.get(dependent);
279
+ dependencies?.delete(field);
280
+ if (dependencies?.size === 0) ready.push(dependent);
281
+ }
282
+ }
283
+ if (ordered.length !== nodes.length) {
284
+ const field = nodes.find((node) => !ordered.includes(node.fieldPath[0]));
285
+ throw new ConstructaError({
286
+ kind: "dependency",
287
+ code: "CIRCULAR_REFERENCE",
288
+ path: field?.fieldPath ?? [],
289
+ message: "Circular object value references were detected."
290
+ });
291
+ }
292
+ return Object.freeze(ordered);
293
+ }
294
+ /** Parses untrusted runtime definition data without executing generator code. */
295
+ function parseDefinition(value, options) {
296
+ return parseDefinitionAtPath(value, [], options.registry, options.limits);
297
+ }
298
+ function parseDefinitionAtPath(value, path, registry, limits) {
299
+ const result = parseRuntimeDefinition(value, path, {
300
+ registry,
301
+ limits
302
+ });
303
+ if (result.success) return result.value;
304
+ throw result.issues[0];
305
+ }
306
+ function safeParseDefinition(value, options) {
307
+ return parseRuntimeDefinition(value, [], options);
308
+ }
309
+ /** Parses a versioned document and its root definition through the same pipeline. */
310
+ function parseDocument(value, options) {
311
+ const result = safeParseDocument(value, options);
312
+ if (result.success) return result.value;
313
+ throw result.issues[0];
314
+ }
315
+ function safeParseDocument(value, options) {
316
+ const limits = resolveParseLimits(options);
317
+ const documentIssues = validationIssuesToErrors(validateDocumentSafely(value), [], limits.maxIssues);
318
+ if (documentIssues.length > 0) return {
319
+ success: false,
320
+ issues: documentIssues
321
+ };
322
+ const document = parseDocument$1(value);
323
+ const definition = parseRuntimeDefinition(document.definition, ["definition"], options);
324
+ return definition.success ? {
325
+ success: true,
326
+ value: document
327
+ } : {
328
+ success: false,
329
+ issues: definition.issues
330
+ };
331
+ }
332
+ const parsedDefinitions = /* @__PURE__ */ new WeakSet();
118
333
  const RESERVED_GENERATOR_TYPE_IDS = /* @__PURE__ */ new Set([
119
334
  "__proto__",
120
335
  "constructor",
@@ -143,6 +358,209 @@ function createRegistry() {
143
358
  };
144
359
  }
145
360
  /**
361
+ * Creates an advanced single-value executor over an immutable registry
362
+ * snapshot. Normal applications will receive this behavior through the SDK.
363
+ */
364
+ function createExecutor(registry) {
365
+ const snapshot = createExecutionSnapshot(registry);
366
+ return Object.freeze({ generate(definition, options) {
367
+ const execution = resolveExecutionOptions(options);
368
+ return executeParsedDefinition(parsedDefinitions.has(definition) ? definition : parseDefinition(definition, { registry: snapshot }), [], 0, {
369
+ snapshot,
370
+ ...execution
371
+ });
372
+ } });
373
+ }
374
+ function executeParsedDefinition(definition, path, depth, state, references = unavailableReferenceResolver(path)) {
375
+ const implementation = state.snapshot.lookup(definition.type, path);
376
+ analyzeGeneratorDependencies(implementation, definition, state.snapshot, path);
377
+ return invokeValidatedGeneratorImplementation(implementation, definition, createGenerationContext({
378
+ random: state.random,
379
+ path,
380
+ references,
381
+ createObjectScope() {
382
+ return createObjectGenerationScope(path, (child, pathSegment, scopeReferences) => {
383
+ assertChildPathSegment(pathSegment, path);
384
+ const childPath = [...path, pathSegment];
385
+ if (depth >= state.maxDepth) throw new ConstructaError({
386
+ kind: "execution",
387
+ code: "MAX_EXECUTION_DEPTH",
388
+ path: childPath,
389
+ message: "Child execution exceeds the configured maximum depth."
390
+ });
391
+ return executeParsedDefinition(parseDefinitionAtPath(child, childPath, state.snapshot), childPath, depth + 1, state, scopeReferences);
392
+ });
393
+ },
394
+ analyzeChildValueDependencies(child, pathSegment) {
395
+ assertChildPathSegment(pathSegment, path);
396
+ const childPath = [...path, pathSegment];
397
+ const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);
398
+ return analyzeValueDependencies(state.snapshot.lookup(parsed.type, childPath), parsed, childPath);
399
+ },
400
+ executeChild(child, pathSegment) {
401
+ assertChildPathSegment(pathSegment, path);
402
+ const childPath = [...path, pathSegment];
403
+ if (depth >= state.maxDepth) throw new ConstructaError({
404
+ kind: "execution",
405
+ code: "MAX_EXECUTION_DEPTH",
406
+ path: childPath,
407
+ message: "Child execution exceeds the configured maximum depth."
408
+ });
409
+ return executeParsedDefinition(parseDefinitionAtPath(child, childPath, state.snapshot), childPath, depth + 1, state, references);
410
+ }
411
+ }), path);
412
+ }
413
+ function createObjectGenerationScope(path, executeChild) {
414
+ const completed = /* @__PURE__ */ new Map();
415
+ const resolver = Object.freeze({ resolve(referencePath) {
416
+ assertReferencePath(referencePath, path);
417
+ const key = referencePathKey(referencePath);
418
+ if (!completed.has(key)) throw new ConstructaError({
419
+ kind: "dependency",
420
+ code: "REFERENCE_NOT_AVAILABLE",
421
+ path,
422
+ message: "The referenced object value has not completed."
423
+ });
424
+ return completed.get(key);
425
+ } });
426
+ return Object.freeze({ executeChild(definition, pathSegment) {
427
+ const value = executeChild(definition, pathSegment, resolver);
428
+ recordCompletedValue(completed, [pathSegment], value);
429
+ return value;
430
+ } });
431
+ }
432
+ function recordCompletedValue(completed, referencePath, value, visited = /* @__PURE__ */ new WeakSet()) {
433
+ completed.set(referencePathKey(referencePath), value);
434
+ if (typeof value !== "object" || value === null || visited.has(value)) return;
435
+ visited.add(value);
436
+ for (const [key, child] of Object.entries(value)) recordCompletedValue(completed, [...referencePath, key], child, visited);
437
+ }
438
+ function unavailableReferenceResolver(path) {
439
+ return Object.freeze({ resolve(referencePath) {
440
+ assertReferencePath(referencePath, path);
441
+ throw new ConstructaError({
442
+ kind: "dependency",
443
+ code: "REFERENCE_RESOLUTION_UNAVAILABLE",
444
+ path,
445
+ message: "Reference resolution is available only inside an object field."
446
+ });
447
+ } });
448
+ }
449
+ function assertReferencePath(referencePath, contextPath) {
450
+ if (!Array.isArray(referencePath) || referencePath.length === 0 || referencePath.some((segment) => typeof segment !== "string" || segment.length === 0)) throw contextError("INVALID_REFERENCE_PATH", contextPath, "Reference paths must contain one or more non-empty string segments.");
451
+ }
452
+ function referencePathKey(path) {
453
+ return JSON.stringify(path);
454
+ }
455
+ function createExecutionSnapshot(registry) {
456
+ if (typeof registry !== "object" || registry === null) throw contextError("INVALID_EXECUTOR_REGISTRY", ["registry"], "Executor requires a generator registry.");
457
+ if (typeof registry.snapshot === "function") return registry.snapshot();
458
+ if (typeof registry.lookup === "function") return registry;
459
+ throw contextError("INVALID_EXECUTOR_REGISTRY", ["registry"], "Executor requires a generator registry.");
460
+ }
461
+ function resolveExecutionOptions(options) {
462
+ if (options === void 0) return {
463
+ random: createDefaultRandomSource(),
464
+ maxDepth: 64
465
+ };
466
+ if (typeof options !== "object" || options === null) throw contextError("INVALID_EXECUTION_OPTIONS", [], "Execution options must be an object.");
467
+ if (options.seed !== void 0 && options.random !== void 0) throw contextError("CONFLICTING_RANDOM_OPTIONS", ["seed"], "seed and random cannot be supplied together.");
468
+ const maxDepth = options.maxDepth ?? 64;
469
+ if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) throw contextError("INVALID_EXECUTION_OPTIONS", ["maxDepth"], "maxDepth must be a non-negative safe integer.");
470
+ return {
471
+ random: options.seed !== void 0 ? createSeededRandom(options.seed) : options.random !== void 0 ? createRandomSource(options.random) : createDefaultRandomSource(),
472
+ maxDepth
473
+ };
474
+ }
475
+ function analyzeGeneratorDependencies(implementation, definition, registry, path) {
476
+ if (implementation.analyzeDependencies === void 0) return;
477
+ let dependencies;
478
+ try {
479
+ dependencies = implementation.analyzeDependencies(definition);
480
+ } catch (cause) {
481
+ throw normalizeConstructaError(cause, {
482
+ kind: "dependency",
483
+ code: "DEPENDENCY_ANALYSIS_FAILED",
484
+ path,
485
+ message: "Generator dependency analysis failed."
486
+ });
487
+ }
488
+ if (!Array.isArray(dependencies)) throw new ConstructaError({
489
+ kind: "system",
490
+ code: "DEPENDENCY_ANALYSIS_FAILED",
491
+ path,
492
+ message: "Generator dependency analysis returned an invalid result."
493
+ });
494
+ for (const dependency of dependencies) {
495
+ if (!isGeneratorDependency(dependency)) throw new ConstructaError({
496
+ kind: "system",
497
+ code: "DEPENDENCY_ANALYSIS_FAILED",
498
+ path,
499
+ message: "Generator dependency analysis returned an invalid dependency."
500
+ });
501
+ registry.lookup(dependency.typeId, [...path, ...dependency.path]);
502
+ }
503
+ }
504
+ function analyzeValueDependencies(implementation, definition, path) {
505
+ if (implementation.analyzeValueDependencies === void 0) return [];
506
+ let dependencies;
507
+ try {
508
+ dependencies = implementation.analyzeValueDependencies(definition);
509
+ } catch (cause) {
510
+ throw normalizeConstructaError(cause, {
511
+ kind: "dependency",
512
+ code: "DEPENDENCY_ANALYSIS_FAILED",
513
+ path,
514
+ message: "Value dependency analysis failed."
515
+ });
516
+ }
517
+ if (!Array.isArray(dependencies) || !dependencies.every(isValueDependency)) throw new ConstructaError({
518
+ kind: "system",
519
+ code: "DEPENDENCY_ANALYSIS_FAILED",
520
+ path,
521
+ message: "Value dependency analysis returned an invalid result."
522
+ });
523
+ return Object.freeze(dependencies.map((dependency) => Object.freeze({ path: Object.freeze([...dependency.path]) })));
524
+ }
525
+ function isGeneratorDependency(value) {
526
+ return typeof value === "object" && value !== null && typeof value.typeId === "string" && Array.isArray(value.path) && value.path.every((segment) => typeof segment === "string" || Number.isSafeInteger(segment));
527
+ }
528
+ function isValueDependency(value) {
529
+ return typeof value === "object" && value !== null && Array.isArray(value.path) && value.path.length > 0 && value.path.every((segment) => typeof segment === "string" && segment.length > 0);
530
+ }
531
+ function isCompositeDependencyNode(value) {
532
+ return typeof value === "object" && value !== null && Array.isArray(value.fieldPath) && value.fieldPath.length === 1 && typeof value.fieldPath[0] === "string" && Array.isArray(value.dependencies) && value.dependencies.every(isValueDependency);
533
+ }
534
+ function invokeValidatedGeneratorImplementation(implementation, definition, context, path) {
535
+ try {
536
+ return implementation.generate({
537
+ definition,
538
+ context
539
+ });
540
+ } catch (cause) {
541
+ if (cause instanceof ConstructaError) return throwWithExecutionPath(cause, path);
542
+ throw normalizeConstructaError(cause, {
543
+ kind: "execution",
544
+ code: "EXECUTION_FAILED",
545
+ path,
546
+ message: "Generator execution failed."
547
+ });
548
+ }
549
+ }
550
+ function throwWithExecutionPath(error, path) {
551
+ if (path.length === 0 || startsWithPath(error.path, path)) throw error;
552
+ throw new ConstructaError({
553
+ kind: error.kind,
554
+ code: error.code,
555
+ path: [...path, ...error.path],
556
+ message: error.message,
557
+ details: error.details
558
+ });
559
+ }
560
+ function startsWithPath(path, prefix) {
561
+ return prefix.every((segment, index) => path[index] === segment);
562
+ }
563
+ /**
146
564
  * Defines a trusted, developer-authored generator implementation. This API has
147
565
  * no dependency on a particular validation library.
148
566
  */
@@ -177,7 +595,7 @@ function invokeGeneratorImplementation(implementation, input) {
177
595
  const [issue] = issues;
178
596
  if (issue !== void 0) throw new ConstructaError({
179
597
  kind: "configuration",
180
- code: "INVALID_CONFIGURATION",
598
+ code: errorCodeForValidationIssue(issue.code),
181
599
  path: [...path, ...issue.path],
182
600
  message: issue.message,
183
601
  details: { issueCode: issue.code }
@@ -203,6 +621,165 @@ function invokeGeneratorImplementation(implementation, input) {
203
621
  });
204
622
  }
205
623
  }
624
+ const DEFAULT_PARSE_LIMITS = Object.freeze({
625
+ maxDepth: 64,
626
+ maxIssues: 100,
627
+ maxNodes: 1e4
628
+ });
629
+ function parseRuntimeDefinition(value, path, options) {
630
+ const limits = resolveParseLimits(options);
631
+ const schemaIssues = validationIssuesToErrors(validateDefinitionSafely(value, path), path, limits.maxIssues);
632
+ if (schemaIssues.length > 0) return {
633
+ success: false,
634
+ issues: schemaIssues
635
+ };
636
+ const issues = [];
637
+ const visited = /* @__PURE__ */ new Set();
638
+ visitRuntimeDefinition(value, path, 0, options.registry, limits, visited, issues);
639
+ return issues.length === 0 ? {
640
+ success: true,
641
+ value: markParsedDefinitions(visited, value)
642
+ } : {
643
+ success: false,
644
+ issues: Object.freeze(issues)
645
+ };
646
+ }
647
+ function markParsedDefinitions(definitions, definition) {
648
+ for (const parsed of definitions) parsedDefinitions.add(parsed);
649
+ return definition;
650
+ }
651
+ function visitRuntimeDefinition(definition, path, depth, registry, limits, visited, issues) {
652
+ if (issues.length >= limits.maxIssues) return;
653
+ if (depth > limits.maxDepth) {
654
+ addParseIssue(issues, limits, "PARSE_DEPTH_LIMIT", path, "Generator definition exceeds the maximum nesting depth.");
655
+ return;
656
+ }
657
+ if (visited.size >= limits.maxNodes) {
658
+ addParseIssue(issues, limits, "PARSE_NODE_LIMIT", path, "Generator definition exceeds the maximum node count.");
659
+ return;
660
+ }
661
+ visited.add(definition);
662
+ let implementation;
663
+ try {
664
+ implementation = registry.lookup(definition.type, path);
665
+ } catch (cause) {
666
+ addExistingParseIssue(issues, limits, normalizeConstructaError(cause, {
667
+ kind: "dependency",
668
+ code: "UNKNOWN_GENERATOR",
669
+ path: [...path, "type"],
670
+ message: "Generator type could not be resolved."
671
+ }));
672
+ return;
673
+ }
674
+ let validationIssues;
675
+ try {
676
+ validationIssues = implementation.validateDefinition(definition);
677
+ } catch (cause) {
678
+ addExistingParseIssue(issues, limits, normalizeConstructaError(cause, {
679
+ kind: "configuration",
680
+ code: "INVALID_CONFIGURATION",
681
+ path,
682
+ message: "Generator definition validation failed."
683
+ }));
684
+ return;
685
+ }
686
+ if (!Array.isArray(validationIssues)) {
687
+ addParseIssue(issues, limits, "INVALID_CONFIGURATION", path, "Generator definition validation returned an invalid result.", "system");
688
+ return;
689
+ }
690
+ for (const issue of validationIssues) {
691
+ if (!isValidationIssue(issue)) {
692
+ addParseIssue(issues, limits, "INVALID_CONFIGURATION", path, "Generator definition validation returned an invalid issue.", "system");
693
+ return;
694
+ }
695
+ addParseIssue(issues, limits, errorCodeForValidationIssue(issue.code), [...path, ...issue.path], issue.message);
696
+ }
697
+ for (const [key, child] of Object.entries(definition)) {
698
+ if (key !== "type") visitEmbeddedDefinitions(child, [...path, key], depth + 1, registry, limits, visited, issues);
699
+ if (issues.length >= limits.maxIssues) return;
700
+ }
701
+ }
702
+ function visitEmbeddedDefinitions(value, path, depth, registry, limits, visited, issues) {
703
+ if (issues.length >= limits.maxIssues || value === null || typeof value !== "object") return;
704
+ if (Array.isArray(value)) {
705
+ for (let index = 0; index < value.length; index += 1) {
706
+ visitEmbeddedDefinitions(value[index], [...path, index], depth, registry, limits, visited, issues);
707
+ if (issues.length >= limits.maxIssues) return;
708
+ }
709
+ return;
710
+ }
711
+ if (Object.hasOwn(value, "type")) {
712
+ visitRuntimeDefinition(value, path, depth, registry, limits, visited, issues);
713
+ return;
714
+ }
715
+ for (const [key, child] of Object.entries(value)) {
716
+ visitEmbeddedDefinitions(child, [...path, key], depth, registry, limits, visited, issues);
717
+ if (issues.length >= limits.maxIssues) return;
718
+ }
719
+ }
720
+ function resolveParseLimits(options) {
721
+ if (typeof options !== "object" || options === null || typeof options.registry !== "object" || options.registry === null || typeof options.registry.lookup !== "function") throw contextError("INVALID_PARSE_OPTIONS", [], "Parsing requires a registry with a lookup function.");
722
+ const supplied = options.limits ?? {};
723
+ const resolved = {
724
+ maxDepth: supplied.maxDepth ?? DEFAULT_PARSE_LIMITS.maxDepth,
725
+ maxIssues: supplied.maxIssues ?? DEFAULT_PARSE_LIMITS.maxIssues,
726
+ maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes
727
+ };
728
+ for (const [name, value] of Object.entries(resolved)) if (!Number.isSafeInteger(value) || value < 1) throw contextError("INVALID_PARSE_LIMITS", ["limits", name], `${name} must be a positive safe integer.`);
729
+ return resolved;
730
+ }
731
+ function validateDefinitionSafely(value, path) {
732
+ try {
733
+ return validateGeneratorDefinition(value, path);
734
+ } catch (_cause) {
735
+ return [{
736
+ code: "invalid_json_value",
737
+ path,
738
+ message: "Definition could not be safely inspected."
739
+ }];
740
+ }
741
+ }
742
+ function validateDocumentSafely(value) {
743
+ try {
744
+ return validateDocument(value);
745
+ } catch {
746
+ return [{
747
+ code: "invalid_json_value",
748
+ path: [],
749
+ message: "Document could not be safely inspected."
750
+ }];
751
+ }
752
+ }
753
+ function validationIssuesToErrors(issues, fallbackPath, maxIssues = Number.POSITIVE_INFINITY) {
754
+ return issues.slice(0, maxIssues).map((issue) => new ConstructaError({
755
+ kind: "configuration",
756
+ code: isValidationIssue(issue) ? errorCodeForValidationIssue(issue.code) : "INVALID_CONFIGURATION",
757
+ path: isValidationIssue(issue) ? issue.path : fallbackPath,
758
+ message: isValidationIssue(issue) ? issue.message : "Validation returned an invalid issue.",
759
+ details: isValidationIssue(issue) ? { issueCode: issue.code } : void 0
760
+ }));
761
+ }
762
+ function errorCodeForValidationIssue(code) {
763
+ return {
764
+ empty_choice: "EMPTY_CHOICE",
765
+ invalid_length: "INVALID_LENGTH",
766
+ invalid_range: "INVALID_RANGE"
767
+ }[code] ?? "INVALID_CONFIGURATION";
768
+ }
769
+ function isValidationIssue(value) {
770
+ return typeof value === "object" && value !== null && typeof value.code === "string" && typeof value.message === "string" && Array.isArray(value.path);
771
+ }
772
+ function addParseIssue(issues, limits, code, path, message, kind = "configuration") {
773
+ if (issues.length < limits.maxIssues) issues.push(new ConstructaError({
774
+ kind,
775
+ code,
776
+ path,
777
+ message
778
+ }));
779
+ }
780
+ function addExistingParseIssue(issues, limits, error) {
781
+ if (issues.length < limits.maxIssues) issues.push(error);
782
+ }
206
783
  function assertGeneratorImplementation(implementation) {
207
784
  if (!isStableTypeId(implementation.type)) throw new TypeError("generator type must be a stable lowercase identifier");
208
785
  if (!Number.isSafeInteger(implementation.version) || implementation.version < 1) throw new TypeError("generator version must be a positive safe integer");
@@ -271,6 +848,23 @@ function invalidRandomSource(message) {
271
848
  message
272
849
  });
273
850
  }
851
+ function assertContextPath(path) {
852
+ for (const segment of path) assertContextPathSegment(segment);
853
+ }
854
+ function assertContextPathSegment(segment) {
855
+ if (typeof segment !== "string" && (!Number.isSafeInteger(segment) || typeof segment !== "number")) throw contextError("INVALID_GENERATION_CONTEXT", ["path"], "Context path segments must be strings or safe integers.");
856
+ }
857
+ function assertChildPathSegment(segment, path) {
858
+ if (typeof segment !== "string" && (typeof segment !== "number" || !Number.isSafeInteger(segment))) throw contextError("INVALID_CHILD_PATH", path, "Child path segments must be strings or safe integers.");
859
+ }
860
+ function contextError(code, path, message) {
861
+ return new ConstructaError({
862
+ kind: "configuration",
863
+ code,
864
+ path,
865
+ message
866
+ });
867
+ }
274
868
  function hashSeed(seed) {
275
869
  let hash = 2166136261;
276
870
  for (const byte of new TextEncoder().encode(seed)) hash = Math.imul(hash ^ byte, 16777619) >>> 0;
@@ -280,6 +874,6 @@ function isStableTypeId(value) {
280
874
  return /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);
281
875
  }
282
876
  //#endregion
283
- export { SEEDED_RANDOM_ALGORITHM, SEEDED_RANDOM_ALGORITHM_VERSION, createDefaultRandomSource, createGeneratorDefinition, createRandomSource, createRegistry, createSeededRandom, defineGenerator, getSeededRandomMetadata, invokeGeneratorImplementation, normalizeSeed };
877
+ export { SEEDED_RANDOM_ALGORITHM, SEEDED_RANDOM_ALGORITHM_VERSION, createCompositeDependencyAnalysis, createDefaultRandomSource, createExecutor, createGenerationContext, createGeneratorDefinition, createRandomSource, createRegistry, createSeededRandom, defineGenerator, getSeededRandomMetadata, invokeGeneratorImplementation, normalizeSeed, parseDefinition, parseDocument, parseReferencePath, parseTemplateTokens, safeParseDefinition, safeParseDocument, scheduleCompositeDependencies };
284
878
 
285
879
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import {\n assertGeneratorDefinition,\n ConstructaError,\n type GeneratorDefinition,\n normalizeConstructaError,\n type ValidationIssue,\n type ValidationPath,\n} from \"constructa-schema\";\n\nexport type {\n GeneratorDefinition,\n Infer,\n ValidationIssue,\n ValidationPath,\n} from \"constructa-schema\";\n\n/**\n * Random values are always half-open: `float()` returns [0, 1), while\n * `integer(maxExclusive)` returns an integer in [0, maxExclusive).\n */\nexport type RandomSource = {\n float(): number;\n integer(maxExclusive: number): number;\n bytes(length: number): Uint8Array;\n};\n\nexport type RandomSourceAdapter = RandomSource;\n\nexport type Seed = number | string;\n\nexport const SEEDED_RANDOM_ALGORITHM = \"mulberry32\";\nexport const SEEDED_RANDOM_ALGORITHM_VERSION = 1;\n\nexport type SeededRandomMetadata = {\n readonly algorithm: typeof SEEDED_RANDOM_ALGORITHM;\n readonly version: typeof SEEDED_RANDOM_ALGORITHM_VERSION;\n};\n\nexport type DeterminismCompatibility = {\n readonly engineVersion: string;\n readonly generatorImplementationVersion: number;\n readonly random: SeededRandomMetadata;\n readonly definition: GeneratorDefinition;\n readonly seed: Seed;\n readonly executionMode: string;\n};\n\nconst SEEDED_RANDOM_METADATA: SeededRandomMetadata = Object.freeze({\n algorithm: SEEDED_RANDOM_ALGORITHM,\n version: SEEDED_RANDOM_ALGORITHM_VERSION,\n});\n\n/**\n * Validates an injected source and guards every produced value. No fallback\n * randomness is used when an adapter violates its contract.\n */\nexport function createRandomSource(adapter: RandomSourceAdapter): RandomSource {\n assertRandomSourceAdapter(adapter);\n\n return Object.freeze({\n float() {\n const value = adapter.float();\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < 0 ||\n value >= 1\n ) {\n throw invalidRandomSource(\n \"float() must return a finite number in [0, 1).\",\n );\n }\n return value;\n },\n integer(maxExclusive: number) {\n assertRandomLength(maxExclusive, \"maxExclusive\");\n const value = adapter.integer(maxExclusive);\n if (!Number.isSafeInteger(value) || value < 0 || value >= maxExclusive) {\n throw invalidRandomSource(\n \"integer(maxExclusive) must return a safe integer in [0, maxExclusive).\",\n );\n }\n return value;\n },\n bytes(length: number) {\n assertByteLength(length);\n const value = adapter.bytes(length);\n if (!(value instanceof Uint8Array) || value.length !== length) {\n throw invalidRandomSource(\n \"bytes(length) must return a Uint8Array with exactly length bytes.\",\n );\n }\n return value;\n },\n });\n}\n\n/** Creates the default platform-backed random source. It makes no security claim. */\nexport function createDefaultRandomSource(): RandomSource {\n const crypto = globalThis.crypto;\n if (crypto?.getRandomValues === undefined) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"SYSTEM_RANDOM_UNAVAILABLE\",\n path: [],\n message: \"Platform cryptographic random values are unavailable.\",\n });\n }\n\n const randomBytes = (length: number) => {\n const bytes = new Uint8Array(length);\n for (let offset = 0; offset < length; offset += 65_536) {\n crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));\n }\n return bytes;\n };\n const uint32 = () => new DataView(randomBytes(4).buffer).getUint32(0);\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes: randomBytes,\n });\n}\n\n/**\n * Returns a canonical seed representation. Strings use UTF-8 exactly; finite\n * numbers use their JavaScript numeric representation, with -0 normalized to 0.\n */\nexport function normalizeSeed(seed: Seed): string {\n if (typeof seed === \"string\") return `string:${seed}`;\n if (typeof seed === \"number\" && Number.isFinite(seed)) {\n return `number:${Object.is(seed, -0) ? \"0\" : String(seed)}`;\n }\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_SEED\",\n path: [\"seed\"],\n message: \"seed must be a string or finite number.\",\n });\n}\n\n/** Creates an isolated deterministic random source for the current algorithm version. */\nexport function createSeededRandom(seed: Seed): RandomSource {\n let state = hashSeed(normalizeSeed(seed));\n const uint32 = () => {\n state = (state + 0x6d2b_79f5) >>> 0;\n let value = state;\n value = Math.imul(value ^ (value >>> 15), value | 1);\n value ^= value + Math.imul(value ^ (value >>> 7), value | 61);\n return (value ^ (value >>> 14)) >>> 0;\n };\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes(length: number) {\n const bytes = new Uint8Array(length);\n for (let index = 0; index < length; index += 1) {\n if (index % 4 === 0) {\n const value = uint32();\n bytes[index] = value & 0xff;\n if (index + 1 < length) bytes[index + 1] = (value >>> 8) & 0xff;\n if (index + 2 < length) bytes[index + 2] = (value >>> 16) & 0xff;\n if (index + 3 < length) bytes[index + 3] = value >>> 24;\n }\n }\n return bytes;\n },\n });\n}\n\n/** Metadata for reproducibility diagnostics. It intentionally contains no seed. */\nexport function getSeededRandomMetadata(): SeededRandomMetadata {\n return SEEDED_RANDOM_METADATA;\n}\n\n/** Services supplied by the engine. Implementations must not use global randomness. */\nexport type GenerationContext = {\n readonly random: RandomSource;\n readonly generateChild: <Output>(\n definition: GeneratorDefinition<Output>,\n ) => Output;\n};\n\nexport type GeneratorDependency = {\n readonly typeId: string;\n readonly path: ValidationPath;\n};\n\nexport type GeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n> = {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: (\n definition: unknown,\n ) => readonly ValidationIssue[];\n readonly analyzeDependencies?: (\n definition: Definition,\n ) => readonly GeneratorDependency[];\n readonly generate: (input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n }) => Output;\n};\n\nexport type RegisteredGenerator = {\n readonly type: string;\n readonly version: number;\n};\n\nexport type GeneratorRegistrySnapshot = {\n readonly generators: readonly RegisteredGenerator[];\n readonly lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n};\n\nexport type GeneratorRegistry = {\n register: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n replace: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n snapshot: () => GeneratorRegistrySnapshot;\n};\n\nconst RESERVED_GENERATOR_TYPE_IDS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/** Creates advanced registry infrastructure. Normal factories do not require it. */\nexport function createRegistry(): GeneratorRegistry {\n const implementations = new Map<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >();\n\n return {\n register(implementation) {\n assertRegistryImplementation(implementation);\n if (implementations.has(implementation.type)) {\n throw registryError(\n \"DUPLICATE_GENERATOR\",\n [\"type\"],\n `A generator with type \"${implementation.type}\" is already registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n replace(implementation) {\n assertRegistryImplementation(implementation);\n if (!implementations.has(implementation.type)) {\n throw registryError(\n \"UNKNOWN_GENERATOR\",\n [\"type\"],\n `No generator with type \"${implementation.type}\" is registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n lookup(type, path = []) {\n return lookupImplementation(implementations, type, path);\n },\n snapshot() {\n return createRegistrySnapshot(implementations);\n },\n };\n}\n\n/**\n * Defines a trusted, developer-authored generator implementation. This API has\n * no dependency on a particular validation library.\n */\nexport function defineGenerator<\n const Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n assertGeneratorImplementation(implementation);\n return implementation;\n}\n\n/** Builds a portable definition while preserving literal fields and output inference. */\nexport function createGeneratorDefinition<\n Output,\n const Definition extends GeneratorDefinition<Output>,\n>(definition: Definition): Definition {\n assertGeneratorDefinition(definition);\n return definition;\n}\n\n/**\n * Invokes one validated implementation. Registry lookup and dispatch are added\n * later; this function keeps validation and execution failure normalization in\n * the same shared contract today.\n */\nexport function invokeGeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n readonly path?: ValidationPath;\n },\n): Output {\n const path = input.path ?? [];\n let issues: readonly ValidationIssue[];\n\n try {\n issues = implementation.validateDefinition(input.definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n });\n }\n\n if (issues.length > 0) {\n const [issue] = issues;\n if (issue !== undefined) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path: [...path, ...issue.path],\n message: issue.message,\n details: { issueCode: issue.code },\n });\n }\n\n throw new ConstructaError({\n kind: \"system\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator validation returned an invalid result.\",\n });\n }\n\n try {\n return implementation.generate({\n definition: input.definition,\n context: input.context,\n });\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nfunction assertGeneratorImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n if (!isStableTypeId(implementation.type)) {\n throw new TypeError(\"generator type must be a stable lowercase identifier\");\n }\n if (\n !Number.isSafeInteger(implementation.version) ||\n implementation.version < 1\n ) {\n throw new TypeError(\"generator version must be a positive safe integer\");\n }\n if (typeof implementation.validateDefinition !== \"function\") {\n throw new TypeError(\"validateDefinition must be a function\");\n }\n if (typeof implementation.generate !== \"function\") {\n throw new TypeError(\"generate must be a function\");\n }\n if (\n implementation.analyzeDependencies !== undefined &&\n typeof implementation.analyzeDependencies !== \"function\"\n ) {\n throw new TypeError(\"analyzeDependencies must be a function when present\");\n }\n}\n\nfunction assertRegistryImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n try {\n assertGeneratorImplementation(implementation);\n } catch {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"implementation\"],\n \"Generator implementation is invalid.\",\n );\n }\n if (RESERVED_GENERATOR_TYPE_IDS.has(implementation.type)) {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"type\"],\n `Generator type \"${implementation.type}\" is reserved.`,\n );\n }\n}\n\nfunction freezeImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n return Object.freeze({ ...implementation });\n}\n\nfunction createRegistrySnapshot(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n): GeneratorRegistrySnapshot {\n const snapshotImplementations = new Map(implementations);\n const generators = [...snapshotImplementations.values()]\n .map(({ type, version }) => Object.freeze({ type, version }))\n .sort((left, right) => left.type.localeCompare(right.type));\n\n return Object.freeze({\n generators: Object.freeze(generators),\n lookup(type: string, path: ValidationPath = []) {\n return lookupImplementation(snapshotImplementations, type, path);\n },\n });\n}\n\nfunction lookupImplementation(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n type: string,\n path: ValidationPath,\n): GeneratorImplementation<GeneratorDefinition, unknown> {\n const implementation = implementations.get(type);\n if (implementation !== undefined) return implementation;\n\n const registeredTypes = [...implementations.keys()].sort((left, right) =>\n left.localeCompare(right),\n );\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: `No generator with type \"${type}\" is registered.`,\n details: { registeredTypes },\n });\n}\n\nfunction registryError(\n code: \"DUPLICATE_GENERATOR\" | \"INVALID_CONFIGURATION\" | \"UNKNOWN_GENERATOR\",\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({ kind: \"configuration\", code, path, message });\n}\n\nfunction assertRandomSourceAdapter(adapter: RandomSourceAdapter): void {\n if (\n typeof adapter !== \"object\" ||\n adapter === null ||\n typeof adapter.float !== \"function\" ||\n typeof adapter.integer !== \"function\" ||\n typeof adapter.bytes !== \"function\"\n ) {\n throw invalidRandomSource(\n \"A random source must provide float(), integer(), and bytes() methods.\",\n );\n }\n}\n\nfunction assertRandomLength(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw invalidRandomSource(`${name} must be a positive safe integer.`);\n }\n}\n\nfunction assertByteLength(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw invalidRandomSource(\"length must be a non-negative safe integer.\");\n }\n}\n\nfunction invalidRandomSource(message: string): ConstructaError {\n return new ConstructaError({\n kind: \"system\",\n code: \"INVALID_RANDOM_SOURCE\",\n path: [\"random\"],\n message,\n });\n}\n\nfunction hashSeed(seed: string): number {\n let hash = 0x811c_9dc5;\n for (const byte of new TextEncoder().encode(seed)) {\n hash = Math.imul(hash ^ byte, 0x0100_0193) >>> 0;\n }\n return hash;\n}\n\nfunction isStableTypeId(value: string): boolean {\n return /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(value);\n}\n"],"mappings":";;AA8BA,MAAa,0BAA0B;AACvC,MAAa,kCAAkC;AAgB/C,MAAM,yBAA+C,OAAO,OAAO;CACjE,WAAW;CACX,SAAA;AACF,CAAC;;;;;AAMD,SAAgB,mBAAmB,SAA4C;CAC7E,0BAA0B,OAAO;CAEjC,OAAO,OAAO,OAAO;EACnB,QAAQ;GACN,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,SAAS,KAAK,KACtB,QAAQ,KACR,SAAS,GAET,MAAM,oBACJ,gDACF;GAEF,OAAO;EACT;EACA,QAAQ,cAAsB;GAC5B,mBAAmB,cAAc,cAAc;GAC/C,MAAM,QAAQ,QAAQ,QAAQ,YAAY;GAC1C,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,KAAK,SAAS,cACxD,MAAM,oBACJ,wEACF;GAEF,OAAO;EACT;EACA,MAAM,QAAgB;GACpB,iBAAiB,MAAM;GACvB,MAAM,QAAQ,QAAQ,MAAM,MAAM;GAClC,IAAI,EAAE,iBAAiB,eAAe,MAAM,WAAW,QACrD,MAAM,oBACJ,mEACF;GAEF,OAAO;EACT;CACF,CAAC;AACH;;AAGA,SAAgB,4BAA0C;CACxD,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,oBAAoB,KAAA,GAC9B,MAAM,IAAI,gBAAgB;EACxB,MAAM;EACN,MAAM;EACN,MAAM,CAAC;EACP,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MAAM;EACN,MAAM,CAAC,GAAG,MAAM,MAAM;EACtB,SAAS,2BAA2B,KAAK;EACzC,SAAS,EAAE,gBAAgB;CAC7B,CAAC;AACH;AAEA,SAAS,cACP,MACA,MACA,SACiB;CACjB,OAAO,IAAI,gBAAgB;EAAE,MAAM;EAAiB;EAAM;EAAM;CAAQ,CAAC;AAC3E;AAEA,SAAS,0BAA0B,SAAoC;CACrE,IACE,OAAO,YAAY,YACnB,YAAY,QACZ,OAAO,QAAQ,UAAU,cACzB,OAAO,QAAQ,YAAY,cAC3B,OAAO,QAAQ,UAAU,YAEzB,MAAM,oBACJ,uEACF;AAEJ;AAEA,SAAS,mBAAmB,OAAe,MAAoB;CAC7D,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,oBAAoB,GAAG,KAAK,kCAAkC;AAExE;AAEA,SAAS,iBAAiB,QAAsB;CAC9C,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,SAAS,GAC5C,MAAM,oBAAoB,6CAA6C;AAE3E;AAEA,SAAS,oBAAoB,SAAkC;CAC7D,OAAO,IAAI,gBAAgB;EACzB,MAAM;EACN,MAAM;EACN,MAAM,CAAC,QAAQ;EACf;CACF,CAAC;AACH;AAEA,SAAS,SAAS,MAAsB;CACtC,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,GAC9C,OAAO,KAAK,KAAK,OAAO,MAAM,QAAW,MAAM;CAEjD,OAAO;AACT;AAEA,SAAS,eAAe,OAAwB;CAC9C,OAAO,uCAAuC,KAAK,KAAK;AAC1D"}
1
+ {"version":3,"file":"index.js","names":["parseSchemaDocument"],"sources":["../src/index.ts"],"sourcesContent":["import {\n assertGeneratorDefinition,\n ConstructaError,\n type GeneratorDefinition,\n normalizeConstructaError,\n parseDocument as parseSchemaDocument,\n type ValidationIssue,\n type ValidationPath,\n type ValidationPathSegment,\n validateDocument,\n validateGeneratorDefinition,\n} from \"constructa-schema\";\n\nexport type {\n GeneratorDefinition,\n Infer,\n ValidationIssue,\n ValidationPath,\n ValidationPathSegment,\n} from \"constructa-schema\";\n\n/**\n * Random values are always half-open: `float()` returns [0, 1), while\n * `integer(maxExclusive)` returns an integer in [0, maxExclusive).\n */\nexport type RandomSource = {\n float(): number;\n integer(maxExclusive: number): number;\n bytes(length: number): Uint8Array;\n};\n\nexport type RandomSourceAdapter = RandomSource;\n\nconst validatedRandomSources = new WeakSet<object>();\n\nexport type Seed = number | string;\n\nexport type ExecutionOptions = {\n /** Uses a fresh deterministic source for this root execution. */\n readonly seed?: Seed;\n /**\n * A caller-owned source consumed by this execution. The executor does not\n * reset, clone, or otherwise retain it after the call returns.\n */\n readonly random?: RandomSource;\n /** Maximum child-definition nesting below the root. Defaults to 64. */\n readonly maxDepth?: number;\n};\n\nexport type Executor = {\n generate: <Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ) => import(\"constructa-schema\").Infer<Definition>;\n};\n\nexport const SEEDED_RANDOM_ALGORITHM = \"mulberry32\";\nexport const SEEDED_RANDOM_ALGORITHM_VERSION = 1;\n\nexport type SeededRandomMetadata = {\n readonly algorithm: typeof SEEDED_RANDOM_ALGORITHM;\n readonly version: typeof SEEDED_RANDOM_ALGORITHM_VERSION;\n};\n\nexport type DeterminismCompatibility = {\n readonly engineVersion: string;\n readonly generatorImplementationVersion: number;\n readonly random: SeededRandomMetadata;\n readonly definition: GeneratorDefinition;\n readonly seed: Seed;\n readonly executionMode: string;\n};\n\nconst SEEDED_RANDOM_METADATA: SeededRandomMetadata = Object.freeze({\n algorithm: SEEDED_RANDOM_ALGORITHM,\n version: SEEDED_RANDOM_ALGORITHM_VERSION,\n});\n\n/**\n * Validates an injected source and guards every produced value. No fallback\n * randomness is used when an adapter violates its contract.\n */\nexport function createRandomSource(adapter: RandomSourceAdapter): RandomSource {\n assertRandomSourceAdapter(adapter);\n\n const source = Object.freeze({\n float() {\n const value = adapter.float();\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < 0 ||\n value >= 1\n ) {\n throw invalidRandomSource(\n \"float() must return a finite number in [0, 1).\",\n );\n }\n return value;\n },\n integer(maxExclusive: number) {\n assertRandomLength(maxExclusive, \"maxExclusive\");\n const value = adapter.integer(maxExclusive);\n if (!Number.isSafeInteger(value) || value < 0 || value >= maxExclusive) {\n throw invalidRandomSource(\n \"integer(maxExclusive) must return a safe integer in [0, maxExclusive).\",\n );\n }\n return value;\n },\n bytes(length: number) {\n assertByteLength(length);\n const value = adapter.bytes(length);\n if (!(value instanceof Uint8Array) || value.length !== length) {\n throw invalidRandomSource(\n \"bytes(length) must return a Uint8Array with exactly length bytes.\",\n );\n }\n return value;\n },\n });\n validatedRandomSources.add(source);\n return source;\n}\n\n/** Creates the default platform-backed random source. It makes no security claim. */\nexport function createDefaultRandomSource(): RandomSource {\n const crypto = globalThis.crypto;\n if (crypto?.getRandomValues === undefined) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"SYSTEM_RANDOM_UNAVAILABLE\",\n path: [],\n message: \"Platform cryptographic random values are unavailable.\",\n });\n }\n\n const randomBytes = (length: number) => {\n const bytes = new Uint8Array(length);\n for (let offset = 0; offset < length; offset += 65_536) {\n crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));\n }\n return bytes;\n };\n const uint32 = () => new DataView(randomBytes(4).buffer).getUint32(0);\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes: randomBytes,\n });\n}\n\n/**\n * Returns a canonical seed representation. Strings use UTF-8 exactly; finite\n * numbers use their JavaScript numeric representation, with -0 normalized to 0.\n */\nexport function normalizeSeed(seed: Seed): string {\n if (typeof seed === \"string\") return `string:${seed}`;\n if (typeof seed === \"number\" && Number.isFinite(seed)) {\n return `number:${Object.is(seed, -0) ? \"0\" : String(seed)}`;\n }\n throw new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_SEED\",\n path: [\"seed\"],\n message: \"seed must be a string or finite number.\",\n });\n}\n\n/** Creates an isolated deterministic random source for the current algorithm version. */\nexport function createSeededRandom(seed: Seed): RandomSource {\n let state = hashSeed(normalizeSeed(seed));\n const uint32 = () => {\n state = (state + 0x6d2b_79f5) >>> 0;\n let value = state;\n value = Math.imul(value ^ (value >>> 15), value | 1);\n value ^= value + Math.imul(value ^ (value >>> 7), value | 61);\n return (value ^ (value >>> 14)) >>> 0;\n };\n const uint53 = () => (uint32() & 0x1f_ffff) * 2 ** 32 + uint32();\n\n return createRandomSource({\n float() {\n return uint53() / 2 ** 53;\n },\n integer(maxExclusive: number) {\n const range = 2 ** 53;\n const upperLimit = range - (range % maxExclusive);\n let value = uint53();\n while (value >= upperLimit) value = uint53();\n return value % maxExclusive;\n },\n bytes(length: number) {\n const bytes = new Uint8Array(length);\n for (let index = 0; index < length; index += 1) {\n if (index % 4 === 0) {\n const value = uint32();\n bytes[index] = value & 0xff;\n if (index + 1 < length) bytes[index + 1] = (value >>> 8) & 0xff;\n if (index + 2 < length) bytes[index + 2] = (value >>> 16) & 0xff;\n if (index + 3 < length) bytes[index + 3] = value >>> 24;\n }\n }\n return bytes;\n },\n });\n}\n\n/** Metadata for reproducibility diagnostics. It intentionally contains no seed. */\nexport function getSeededRandomMetadata(): SeededRandomMetadata {\n return SEEDED_RANDOM_METADATA;\n}\n\n/** Services supplied by the engine. Implementations must not use global randomness. */\nexport type GenerationContext = {\n readonly random: RandomSource;\n /** The definition path currently being generated. */\n readonly path: ValidationPath;\n /** Delegates a typed child definition to the engine. */\n readonly executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ) => Output;\n /**\n * Read-only values from the object currently being generated. Values are\n * available only after their field has completed.\n */\n readonly references: ReferenceResolver;\n /** Creates an isolated scope for the fields of one composite object. */\n readonly createObjectScope: () => ObjectGenerationScope;\n /** Returns value dependencies declared by one direct child definition. */\n readonly analyzeChildValueDependencies: (\n definition: GeneratorDefinition,\n pathSegment: ValidationPathSegment,\n ) => readonly ValueDependency[];\n};\n\n/** A property path relative to the object containing a reference. */\nexport type ReferencePath = readonly string[];\n\n/** A parsed template fragment. Braces are escaped with `{{` and `}}`. */\nexport type TemplateToken =\n | { readonly type: \"literal\"; readonly value: string }\n | { readonly type: \"reference\"; readonly path: ReferencePath };\n\nexport type ParseTemplateTokensOptions = {\n /** Definition-relative path reported for malformed template syntax. */\n readonly path?: ValidationPath;\n};\n\n/**\n * Parses MVP template syntax without executing or resolving references.\n *\n * `{field}` addresses a sibling and `{field.nested}` addresses a value below\n * that sibling. `{{` and `}}` emit literal braces. Whitespace, empty path\n * segments, and brace characters inside a reference are unsupported.\n */\nexport function parseTemplateTokens(\n source: string,\n options: ParseTemplateTokensOptions = {},\n): readonly TemplateToken[] {\n const path = options.path ?? [];\n if (typeof source !== \"string\") {\n throw templateTokenError(path, \"Template source must be a string.\");\n }\n assertContextPath(path);\n\n const tokens: TemplateToken[] = [];\n let literal = \"\";\n const appendLiteral = (value: string) => {\n literal += value;\n };\n const flushLiteral = () => {\n if (literal.length === 0) return;\n tokens.push(Object.freeze({ type: \"literal\", value: literal }));\n literal = \"\";\n };\n\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n if (character === \"{\") {\n if (source[index + 1] === \"{\") {\n appendLiteral(\"{\");\n index += 1;\n continue;\n }\n const closingIndex = source.indexOf(\"}\", index + 1);\n if (closingIndex === -1) {\n throw templateTokenError(\n path,\n \"Template reference is missing a closing brace.\",\n );\n }\n const reference = source.slice(index + 1, closingIndex);\n const referencePath = parseReferencePath(reference, path);\n flushLiteral();\n tokens.push(Object.freeze({ type: \"reference\", path: referencePath }));\n index = closingIndex;\n continue;\n }\n if (character === \"}\") {\n if (source[index + 1] === \"}\") {\n appendLiteral(\"}\");\n index += 1;\n continue;\n }\n throw templateTokenError(\n path,\n \"Template contains an unmatched closing brace.\",\n );\n }\n appendLiteral(character ?? \"\");\n }\n flushLiteral();\n return Object.freeze(tokens);\n}\n\n/** Parses one dot-separated object-local reference path. */\nexport function parseReferencePath(\n source: string,\n path: ValidationPath = [],\n): ReferencePath {\n if (typeof source !== \"string\" || source.length === 0) {\n throw templateTokenError(path, \"Template reference must not be empty.\");\n }\n assertContextPath(path);\n const segments = source.split(\".\");\n if (\n segments.some((segment) => segment.length === 0 || /[{}\\s]/u.test(segment))\n ) {\n throw templateTokenError(\n path,\n \"Template reference segments must be non-empty and cannot contain whitespace or braces.\",\n );\n }\n return Object.freeze(segments);\n}\n\nfunction templateTokenError(\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: \"INVALID_TEMPLATE_TOKEN\",\n path,\n message,\n });\n}\n\n/** A portable value dependency declared by a generator definition. */\nexport type ValueDependency = {\n readonly path: ReferencePath;\n};\n\n/** Dependencies for a direct field in a composite definition. */\nexport type CompositeDependencyNode = {\n readonly fieldPath: readonly [string];\n readonly dependencies: readonly ValueDependency[];\n};\n\n/** Portable dependency data used to schedule one composite object. */\nexport type CompositeDependencyAnalysis = {\n readonly nodes: readonly CompositeDependencyNode[];\n};\n\n/** The read-only capability supplied to generators that resolve references. */\nexport type ReferenceResolver = {\n resolve: (path: ReferencePath) => unknown;\n};\n\n/** Executes and records completed fields within one isolated object scope. */\nexport type ObjectGenerationScope = {\n executeChild: <Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ) => Output;\n};\n\nexport type GenerationContextOptions = {\n readonly random: RandomSource;\n readonly path?: ValidationPath;\n readonly executeChild?: GenerationContext[\"executeChild\"];\n readonly references?: ReferenceResolver;\n readonly createObjectScope?: GenerationContext[\"createObjectScope\"];\n readonly analyzeChildValueDependencies?: GenerationContext[\"analyzeChildValueDependencies\"];\n};\n\n/**\n * Creates the engine-owned capability view supplied to implementations.\n * Application code normally receives this through `generate`, rather than\n * constructing one directly.\n */\nexport function createGenerationContext(\n options: GenerationContextOptions,\n): GenerationContext {\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"Context options must be an object.\",\n );\n }\n assertContextPath(options.path ?? []);\n if (\n typeof options.executeChild !== \"undefined\" &&\n typeof options.executeChild !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"executeChild must be a function when present.\",\n );\n }\n\n // This validates the Phase 012 source contract without drawing from it.\n const random = validatedRandomSources.has(options.random)\n ? options.random\n : createRandomSource(options.random);\n const path = Object.freeze([...(options.path ?? [])]);\n const executeChild =\n options.executeChild ??\n ((definition, pathSegment) => {\n assertGeneratorDefinition(definition, [...path, pathSegment]);\n assertContextPathSegment(pathSegment);\n throw new ConstructaError({\n kind: \"execution\",\n code: \"CHILD_EXECUTION_UNAVAILABLE\",\n path: [...path, pathSegment],\n message: \"Child execution is not available in this generation context.\",\n });\n });\n\n const references = options.references ?? unavailableReferenceResolver(path);\n if (\n typeof references !== \"object\" ||\n references === null ||\n typeof references.resolve !== \"function\"\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"references must provide a resolve function when present.\",\n );\n }\n const createObjectScope =\n options.createObjectScope ??\n (() =>\n Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n return executeChild(definition, pathSegment);\n },\n }));\n if (typeof createObjectScope !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"createObjectScope must be a function when present.\",\n );\n }\n const analyzeChildValueDependencies =\n options.analyzeChildValueDependencies ?? (() => []);\n if (typeof analyzeChildValueDependencies !== \"function\") {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [],\n \"analyzeChildValueDependencies must be a function when present.\",\n );\n }\n\n return Object.freeze({\n random,\n path,\n executeChild,\n references: Object.freeze({ resolve: references.resolve }),\n createObjectScope,\n analyzeChildValueDependencies,\n });\n}\n\n/** Freezes direct-field dependency declarations into portable analysis data. */\nexport function createCompositeDependencyAnalysis(\n nodes: readonly CompositeDependencyNode[],\n): CompositeDependencyAnalysis {\n if (!Array.isArray(nodes)) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [],\n \"Composite dependency nodes must be an array.\",\n );\n }\n const names = new Set<string>();\n const normalized = nodes.map((node, index) => {\n if (!isCompositeDependencyNode(node) || names.has(node.fieldPath[0])) {\n throw contextError(\n \"INVALID_COMPOSITE_DEPENDENCIES\",\n [\"nodes\", index],\n \"Each composite dependency node must name one unique field.\",\n );\n }\n names.add(node.fieldPath[0]);\n return Object.freeze({\n fieldPath: Object.freeze([...node.fieldPath]) as readonly [string],\n dependencies: Object.freeze(\n node.dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n ),\n });\n });\n return Object.freeze({ nodes: Object.freeze(normalized) });\n}\n\n/**\n * Returns a deterministic execution order for direct object fields. A\n * dependency path may target a nested value below another direct field.\n */\nexport function scheduleCompositeDependencies(\n analysis: CompositeDependencyAnalysis,\n): readonly string[] {\n const nodes = analysis.nodes;\n const byName = new Map(nodes.map((node) => [node.fieldPath[0], node]));\n const remaining = new Map<string, Set<string>>();\n const dependents = new Map<string, string[]>();\n\n for (const node of nodes) {\n const dependencies = new Set<string>();\n for (const dependency of node.dependencies) {\n const target = dependency.path[0];\n if (target === undefined || !byName.has(target)) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_FOUND\",\n path: [...node.fieldPath],\n message: \"A referenced object field could not be found.\",\n });\n }\n dependencies.add(target);\n const targets = dependents.get(target) ?? [];\n targets.push(node.fieldPath[0]);\n dependents.set(target, targets);\n }\n remaining.set(node.fieldPath[0], dependencies);\n }\n\n const ready = nodes\n .filter((node) => (remaining.get(node.fieldPath[0])?.size ?? 0) === 0)\n .map((node) => node.fieldPath[0]);\n const ordered: string[] = [];\n while (ready.length > 0) {\n const field = ready.shift();\n if (field === undefined) continue;\n ordered.push(field);\n for (const dependent of dependents.get(field) ?? []) {\n const dependencies = remaining.get(dependent);\n dependencies?.delete(field);\n if (dependencies?.size === 0) ready.push(dependent);\n }\n }\n if (ordered.length !== nodes.length) {\n const field = nodes.find((node) => !ordered.includes(node.fieldPath[0]));\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"CIRCULAR_REFERENCE\",\n path: field?.fieldPath ?? [],\n message: \"Circular object value references were detected.\",\n });\n }\n return Object.freeze(ordered);\n}\n\nexport type ParseLimits = {\n readonly maxDepth?: number;\n readonly maxIssues?: number;\n readonly maxNodes?: number;\n};\n\nexport type ParseDefinitionOptions = {\n readonly registry: Pick<\n GeneratorRegistry | GeneratorRegistrySnapshot,\n \"lookup\"\n >;\n readonly limits?: ParseLimits;\n};\n\nexport type ParseDocumentOptions = ParseDefinitionOptions;\n\nexport type DefinitionParseResult =\n | { readonly success: true; readonly value: ParsedGeneratorDefinition }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\nexport type DocumentParseResult =\n | {\n readonly success: true;\n readonly value: import(\"constructa-schema\").GeneratorDocumentV1;\n }\n | { readonly success: false; readonly issues: readonly ConstructaError[] };\n\n/** Parses untrusted runtime definition data without executing generator code. */\nexport function parseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): ParsedGeneratorDefinition {\n return parseDefinitionAtPath(value, [], options.registry, options.limits);\n}\n\nfunction parseDefinitionAtPath(\n value: unknown,\n path: ValidationPath,\n registry: ParseDefinitionOptions[\"registry\"],\n limits?: ParseLimits,\n): ParsedGeneratorDefinition {\n const result = parseRuntimeDefinition(value, path, { registry, limits });\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDefinition(\n value: unknown,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n return parseRuntimeDefinition(value, [], options);\n}\n\n/** Parses a versioned document and its root definition through the same pipeline. */\nexport function parseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): import(\"constructa-schema\").GeneratorDocumentV1 {\n const result = safeParseDocument(value, options);\n if (result.success) return result.value;\n throw result.issues[0];\n}\n\nexport function safeParseDocument(\n value: unknown,\n options: ParseDocumentOptions,\n): DocumentParseResult {\n const limits = resolveParseLimits(options);\n const documentIssues = validationIssuesToErrors(\n validateDocumentSafely(value),\n [],\n limits.maxIssues,\n );\n if (documentIssues.length > 0)\n return { success: false, issues: documentIssues };\n\n // Schema parsing is now safe because validation has rejected hostile shapes.\n const document = parseSchemaDocument(value);\n const definition = parseRuntimeDefinition(\n document.definition,\n [\"definition\"],\n options,\n );\n return definition.success\n ? { success: true, value: document }\n : { success: false, issues: definition.issues };\n}\n\nexport type GeneratorDependency = {\n readonly typeId: string;\n readonly path: ValidationPath;\n};\n\ndeclare const parsedGeneratorDefinition: unique symbol;\n\n/** A runtime-validated definition accepted by an executor without revalidation. */\nexport type ParsedGeneratorDefinition = GeneratorDefinition & {\n readonly [parsedGeneratorDefinition]: true;\n};\n\nconst parsedDefinitions = new WeakSet<object>();\n\nexport type GeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n> = {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: (\n definition: unknown,\n ) => readonly ValidationIssue[];\n readonly analyzeDependencies?: (\n definition: Definition,\n ) => readonly GeneratorDependency[];\n /** Declares object-local value references used by this definition. */\n readonly analyzeValueDependencies?: (\n definition: Definition,\n ) => readonly ValueDependency[];\n readonly generate: (input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n }) => Output;\n};\n\nexport type RegisteredGenerator = {\n readonly type: string;\n readonly version: number;\n};\n\nexport type GeneratorRegistrySnapshot = {\n readonly generators: readonly RegisteredGenerator[];\n readonly lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n};\n\nexport type GeneratorRegistry = {\n register: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n replace: <Definition extends GeneratorDefinition<Output>, Output>(\n implementation: GeneratorImplementation<Definition, Output>,\n ) => void;\n lookup: (\n type: string,\n path?: ValidationPath,\n ) => GeneratorImplementation<GeneratorDefinition, unknown>;\n snapshot: () => GeneratorRegistrySnapshot;\n};\n\nconst RESERVED_GENERATOR_TYPE_IDS = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/** Creates advanced registry infrastructure. Normal factories do not require it. */\nexport function createRegistry(): GeneratorRegistry {\n const implementations = new Map<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >();\n\n return {\n register(implementation) {\n assertRegistryImplementation(implementation);\n if (implementations.has(implementation.type)) {\n throw registryError(\n \"DUPLICATE_GENERATOR\",\n [\"type\"],\n `A generator with type \"${implementation.type}\" is already registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n replace(implementation) {\n assertRegistryImplementation(implementation);\n if (!implementations.has(implementation.type)) {\n throw registryError(\n \"UNKNOWN_GENERATOR\",\n [\"type\"],\n `No generator with type \"${implementation.type}\" is registered.`,\n );\n }\n implementations.set(\n implementation.type,\n freezeImplementation(\n implementation,\n ) as unknown as GeneratorImplementation<GeneratorDefinition, unknown>,\n );\n },\n lookup(type, path = []) {\n return lookupImplementation(implementations, type, path);\n },\n snapshot() {\n return createRegistrySnapshot(implementations);\n },\n };\n}\n\n/**\n * Creates an advanced single-value executor over an immutable registry\n * snapshot. Normal applications will receive this behavior through the SDK.\n */\nexport function createExecutor(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): Executor {\n const snapshot = createExecutionSnapshot(registry);\n\n return Object.freeze({\n generate<Definition extends GeneratorDefinition>(\n definition: Definition,\n options?: ExecutionOptions,\n ): import(\"constructa-schema\").Infer<Definition> {\n const execution = resolveExecutionOptions(options);\n const parsed = parsedDefinitions.has(definition)\n ? definition\n : parseDefinition(definition, { registry: snapshot });\n return executeParsedDefinition(parsed, [], 0, {\n snapshot,\n ...execution,\n }) as import(\"constructa-schema\").Infer<Definition>;\n },\n });\n}\n\ntype ExecutionState = {\n readonly snapshot: GeneratorRegistrySnapshot;\n readonly random: RandomSource;\n readonly maxDepth: number;\n};\n\nfunction executeParsedDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n state: ExecutionState,\n references: ReferenceResolver = unavailableReferenceResolver(path),\n): unknown {\n const implementation = state.snapshot.lookup(definition.type, path);\n analyzeGeneratorDependencies(\n implementation,\n definition,\n state.snapshot,\n path,\n );\n const context = createGenerationContext({\n random: state.random,\n path,\n references,\n createObjectScope() {\n return createObjectGenerationScope(\n path,\n (child, pathSegment, scopeReferences) => {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(\n child,\n childPath,\n state.snapshot,\n );\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n scopeReferences,\n );\n },\n );\n },\n analyzeChildValueDependencies(child, pathSegment) {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n const childImplementation = state.snapshot.lookup(parsed.type, childPath);\n return analyzeValueDependencies(childImplementation, parsed, childPath);\n },\n executeChild<Output>(\n child: GeneratorDefinition<Output>,\n pathSegment: ValidationPathSegment,\n ): Output {\n assertChildPathSegment(pathSegment, path);\n const childPath = [...path, pathSegment];\n if (depth >= state.maxDepth) {\n throw new ConstructaError({\n kind: \"execution\",\n code: \"MAX_EXECUTION_DEPTH\",\n path: childPath,\n message: \"Child execution exceeds the configured maximum depth.\",\n });\n }\n const parsed = parseDefinitionAtPath(child, childPath, state.snapshot);\n return executeParsedDefinition(\n parsed,\n childPath,\n depth + 1,\n state,\n references,\n ) as Output;\n },\n });\n return invokeValidatedGeneratorImplementation(\n implementation,\n definition,\n context,\n path,\n );\n}\n\nfunction createObjectGenerationScope(\n path: ValidationPath,\n executeChild: (\n definition: GeneratorDefinition,\n pathSegment: string,\n references: ReferenceResolver,\n ) => unknown,\n): ObjectGenerationScope {\n const completed = new Map<string, unknown>();\n const resolver: ReferenceResolver = Object.freeze({\n resolve(referencePath: ReferencePath): unknown {\n assertReferencePath(referencePath, path);\n const key = referencePathKey(referencePath);\n if (!completed.has(key)) {\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_NOT_AVAILABLE\",\n path,\n message: \"The referenced object value has not completed.\",\n });\n }\n return completed.get(key);\n },\n });\n return Object.freeze({\n executeChild<Output>(\n definition: GeneratorDefinition<Output>,\n pathSegment: string,\n ): Output {\n const value = executeChild(definition, pathSegment, resolver) as Output;\n recordCompletedValue(completed, [pathSegment], value);\n return value;\n },\n });\n}\n\nfunction recordCompletedValue(\n completed: Map<string, unknown>,\n referencePath: readonly string[],\n value: unknown,\n visited = new WeakSet<object>(),\n): void {\n completed.set(referencePathKey(referencePath), value);\n if (typeof value !== \"object\" || value === null || visited.has(value)) return;\n visited.add(value);\n for (const [key, child] of Object.entries(value)) {\n recordCompletedValue(completed, [...referencePath, key], child, visited);\n }\n}\n\nfunction unavailableReferenceResolver(path: ValidationPath): ReferenceResolver {\n return Object.freeze({\n resolve(referencePath: ReferencePath): never {\n assertReferencePath(referencePath, path);\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"REFERENCE_RESOLUTION_UNAVAILABLE\",\n path,\n message:\n \"Reference resolution is available only inside an object field.\",\n });\n },\n });\n}\n\nfunction assertReferencePath(\n referencePath: ReferencePath,\n contextPath: ValidationPath,\n): void {\n if (\n !Array.isArray(referencePath) ||\n referencePath.length === 0 ||\n referencePath.some(\n (segment) => typeof segment !== \"string\" || segment.length === 0,\n )\n ) {\n throw contextError(\n \"INVALID_REFERENCE_PATH\",\n contextPath,\n \"Reference paths must contain one or more non-empty string segments.\",\n );\n }\n}\n\nfunction referencePathKey(path: readonly string[]): string {\n return JSON.stringify(path);\n}\n\nfunction createExecutionSnapshot(\n registry: GeneratorRegistry | GeneratorRegistrySnapshot,\n): GeneratorRegistrySnapshot {\n if (typeof registry !== \"object\" || registry === null) {\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n }\n if (typeof (registry as GeneratorRegistry).snapshot === \"function\") {\n return (registry as GeneratorRegistry).snapshot();\n }\n if (typeof (registry as GeneratorRegistrySnapshot).lookup === \"function\") {\n return registry as GeneratorRegistrySnapshot;\n }\n throw contextError(\n \"INVALID_EXECUTOR_REGISTRY\",\n [\"registry\"],\n \"Executor requires a generator registry.\",\n );\n}\n\nfunction resolveExecutionOptions(\n options: ExecutionOptions | undefined,\n): Omit<ExecutionState, \"snapshot\"> {\n if (options === undefined) {\n return { random: createDefaultRandomSource(), maxDepth: 64 };\n }\n if (typeof options !== \"object\" || options === null) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [],\n \"Execution options must be an object.\",\n );\n }\n if (options.seed !== undefined && options.random !== undefined) {\n throw contextError(\n \"CONFLICTING_RANDOM_OPTIONS\",\n [\"seed\"],\n \"seed and random cannot be supplied together.\",\n );\n }\n const maxDepth = options.maxDepth ?? 64;\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {\n throw contextError(\n \"INVALID_EXECUTION_OPTIONS\",\n [\"maxDepth\"],\n \"maxDepth must be a non-negative safe integer.\",\n );\n }\n const random =\n options.seed !== undefined\n ? createSeededRandom(options.seed)\n : options.random !== undefined\n ? createRandomSource(options.random)\n : createDefaultRandomSource();\n return { random, maxDepth };\n}\n\nfunction analyzeGeneratorDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n registry: GeneratorRegistrySnapshot,\n path: ValidationPath,\n): void {\n if (implementation.analyzeDependencies === undefined) return;\n let dependencies: readonly GeneratorDependency[];\n try {\n dependencies = implementation.analyzeDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Generator dependency analysis returned an invalid result.\",\n });\n }\n for (const dependency of dependencies) {\n if (!isGeneratorDependency(dependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message:\n \"Generator dependency analysis returned an invalid dependency.\",\n });\n }\n registry.lookup(dependency.typeId, [...path, ...dependency.path]);\n }\n}\n\nfunction analyzeValueDependencies(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n path: ValidationPath,\n): readonly ValueDependency[] {\n if (implementation.analyzeValueDependencies === undefined) return [];\n let dependencies: readonly ValueDependency[];\n try {\n dependencies = implementation.analyzeValueDependencies(definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis failed.\",\n });\n }\n if (!Array.isArray(dependencies) || !dependencies.every(isValueDependency)) {\n throw new ConstructaError({\n kind: \"system\",\n code: \"DEPENDENCY_ANALYSIS_FAILED\",\n path,\n message: \"Value dependency analysis returned an invalid result.\",\n });\n }\n return Object.freeze(\n dependencies.map((dependency) =>\n Object.freeze({ path: Object.freeze([...dependency.path]) }),\n ),\n );\n}\n\nfunction isGeneratorDependency(value: unknown): value is GeneratorDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as GeneratorDependency).typeId === \"string\" &&\n Array.isArray((value as GeneratorDependency).path) &&\n (value as GeneratorDependency).path.every(\n (segment) => typeof segment === \"string\" || Number.isSafeInteger(segment),\n )\n );\n}\n\nfunction isValueDependency(value: unknown): value is ValueDependency {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as ValueDependency).path) &&\n (value as ValueDependency).path.length > 0 &&\n (value as ValueDependency).path.every(\n (segment) => typeof segment === \"string\" && segment.length > 0,\n )\n );\n}\n\nfunction isCompositeDependencyNode(\n value: unknown,\n): value is CompositeDependencyNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as CompositeDependencyNode).fieldPath) &&\n (value as CompositeDependencyNode).fieldPath.length === 1 &&\n typeof (value as CompositeDependencyNode).fieldPath[0] === \"string\" &&\n Array.isArray((value as CompositeDependencyNode).dependencies) &&\n (value as CompositeDependencyNode).dependencies.every(isValueDependency)\n );\n}\n\nfunction invokeValidatedGeneratorImplementation(\n implementation: GeneratorImplementation<GeneratorDefinition, unknown>,\n definition: GeneratorDefinition,\n context: GenerationContext,\n path: ValidationPath,\n): unknown {\n try {\n return implementation.generate({ definition, context });\n } catch (cause) {\n if (cause instanceof ConstructaError) {\n return throwWithExecutionPath(cause, path);\n }\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nfunction throwWithExecutionPath(\n error: ConstructaError,\n path: ValidationPath,\n): never {\n if (path.length === 0 || startsWithPath(error.path, path)) throw error;\n throw new ConstructaError({\n kind: error.kind,\n code: error.code,\n path: [...path, ...error.path],\n message: error.message,\n details: error.details,\n });\n}\n\nfunction startsWithPath(path: ValidationPath, prefix: ValidationPath): boolean {\n return prefix.every((segment, index) => path[index] === segment);\n}\n\n/**\n * Defines a trusted, developer-authored generator implementation. This API has\n * no dependency on a particular validation library.\n */\nexport function defineGenerator<\n const Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n assertGeneratorImplementation(implementation);\n return implementation;\n}\n\n/** Builds a portable definition while preserving literal fields and output inference. */\nexport function createGeneratorDefinition<\n Output,\n const Definition extends GeneratorDefinition<Output>,\n>(definition: Definition): Definition {\n assertGeneratorDefinition(definition);\n return definition;\n}\n\n/**\n * Invokes one validated implementation. Registry lookup and dispatch are added\n * later; this function keeps validation and execution failure normalization in\n * the same shared contract today.\n */\nexport function invokeGeneratorImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n input: {\n readonly definition: Definition;\n readonly context: GenerationContext;\n readonly path?: ValidationPath;\n },\n): Output {\n const path = input.path ?? [];\n let issues: readonly ValidationIssue[];\n\n try {\n issues = implementation.validateDefinition(input.definition);\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n });\n }\n\n if (issues.length > 0) {\n const [issue] = issues;\n if (issue !== undefined) {\n throw new ConstructaError({\n kind: \"configuration\",\n code: errorCodeForValidationIssue(issue.code),\n path: [...path, ...issue.path],\n message: issue.message,\n details: { issueCode: issue.code },\n });\n }\n\n throw new ConstructaError({\n kind: \"system\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator validation returned an invalid result.\",\n });\n }\n\n try {\n return implementation.generate({\n definition: input.definition,\n context: input.context,\n });\n } catch (cause) {\n throw normalizeConstructaError(cause, {\n kind: \"execution\",\n code: \"EXECUTION_FAILED\",\n path,\n message: \"Generator execution failed.\",\n });\n }\n}\n\nconst DEFAULT_PARSE_LIMITS = Object.freeze({\n maxDepth: 64,\n maxIssues: 100,\n maxNodes: 10_000,\n});\n\ntype ResolvedParseLimits = {\n readonly maxDepth: number;\n readonly maxIssues: number;\n readonly maxNodes: number;\n};\n\nfunction parseRuntimeDefinition(\n value: unknown,\n path: ValidationPath,\n options: ParseDefinitionOptions,\n): DefinitionParseResult {\n const limits = resolveParseLimits(options);\n const schemaIssues = validationIssuesToErrors(\n validateDefinitionSafely(value, path),\n path,\n limits.maxIssues,\n );\n if (schemaIssues.length > 0) return { success: false, issues: schemaIssues };\n\n const issues: ConstructaError[] = [];\n const visited = new Set<object>();\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n 0,\n options.registry,\n limits,\n visited,\n issues,\n );\n return issues.length === 0\n ? {\n success: true,\n value: markParsedDefinitions(visited, value as GeneratorDefinition),\n }\n : { success: false, issues: Object.freeze(issues) };\n}\n\nfunction markParsedDefinitions(\n definitions: ReadonlySet<object>,\n definition: GeneratorDefinition,\n): ParsedGeneratorDefinition {\n for (const parsed of definitions) parsedDefinitions.add(parsed);\n return definition as ParsedGeneratorDefinition;\n}\n\nfunction visitRuntimeDefinition(\n definition: GeneratorDefinition,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (issues.length >= limits.maxIssues) return;\n if (depth > limits.maxDepth) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_DEPTH_LIMIT\",\n path,\n \"Generator definition exceeds the maximum nesting depth.\",\n );\n return;\n }\n if (visited.size >= limits.maxNodes) {\n addParseIssue(\n issues,\n limits,\n \"PARSE_NODE_LIMIT\",\n path,\n \"Generator definition exceeds the maximum node count.\",\n );\n return;\n }\n visited.add(definition);\n\n let implementation: GeneratorImplementation<GeneratorDefinition, unknown>;\n try {\n implementation = registry.lookup(definition.type, path);\n } catch (cause) {\n const error = normalizeConstructaError(cause, {\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: \"Generator type could not be resolved.\",\n });\n addExistingParseIssue(issues, limits, error);\n return;\n }\n\n let validationIssues: readonly ValidationIssue[];\n try {\n validationIssues = implementation.validateDefinition(definition);\n } catch (cause) {\n addExistingParseIssue(\n issues,\n limits,\n normalizeConstructaError(cause, {\n kind: \"configuration\",\n code: \"INVALID_CONFIGURATION\",\n path,\n message: \"Generator definition validation failed.\",\n }),\n );\n return;\n }\n if (!Array.isArray(validationIssues)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid result.\",\n \"system\",\n );\n return;\n }\n for (const issue of validationIssues) {\n if (!isValidationIssue(issue)) {\n addParseIssue(\n issues,\n limits,\n \"INVALID_CONFIGURATION\",\n path,\n \"Generator definition validation returned an invalid issue.\",\n \"system\",\n );\n return;\n }\n addParseIssue(\n issues,\n limits,\n errorCodeForValidationIssue(issue.code),\n [...path, ...issue.path],\n issue.message,\n );\n }\n\n // Configurations are portable JSON. Every embedded object with a generator\n // discriminator is another definition and must pass the same pipeline.\n for (const [key, child] of Object.entries(definition)) {\n if (key !== \"type\")\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth + 1,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction visitEmbeddedDefinitions(\n value: unknown,\n path: ValidationPath,\n depth: number,\n registry: ParseDefinitionOptions[\"registry\"],\n limits: ResolvedParseLimits,\n visited: Set<object>,\n issues: ConstructaError[],\n): void {\n if (\n issues.length >= limits.maxIssues ||\n value === null ||\n typeof value !== \"object\"\n )\n return;\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n visitEmbeddedDefinitions(\n value[index],\n [...path, index],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n return;\n }\n if (Object.hasOwn(value, \"type\")) {\n visitRuntimeDefinition(\n value as GeneratorDefinition,\n path,\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n return;\n }\n for (const [key, child] of Object.entries(value)) {\n visitEmbeddedDefinitions(\n child,\n [...path, key],\n depth,\n registry,\n limits,\n visited,\n issues,\n );\n if (issues.length >= limits.maxIssues) return;\n }\n}\n\nfunction resolveParseLimits(\n options: ParseDefinitionOptions,\n): ResolvedParseLimits {\n if (\n typeof options !== \"object\" ||\n options === null ||\n typeof options.registry !== \"object\" ||\n options.registry === null ||\n typeof options.registry.lookup !== \"function\"\n ) {\n throw contextError(\n \"INVALID_PARSE_OPTIONS\",\n [],\n \"Parsing requires a registry with a lookup function.\",\n );\n }\n const supplied = options.limits ?? {};\n const resolved = {\n maxDepth: supplied.maxDepth ?? DEFAULT_PARSE_LIMITS.maxDepth,\n maxIssues: supplied.maxIssues ?? DEFAULT_PARSE_LIMITS.maxIssues,\n maxNodes: supplied.maxNodes ?? DEFAULT_PARSE_LIMITS.maxNodes,\n };\n for (const [name, value] of Object.entries(resolved)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw contextError(\n \"INVALID_PARSE_LIMITS\",\n [\"limits\", name],\n `${name} must be a positive safe integer.`,\n );\n }\n }\n return resolved;\n}\n\nfunction validateDefinitionSafely(\n value: unknown,\n path: ValidationPath,\n): readonly ValidationIssue[] {\n try {\n return validateGeneratorDefinition(value, path);\n } catch (_cause) {\n return [\n {\n code: \"invalid_json_value\",\n path,\n message: \"Definition could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validateDocumentSafely(value: unknown): readonly ValidationIssue[] {\n try {\n return validateDocument(value);\n } catch {\n return [\n {\n code: \"invalid_json_value\",\n path: [],\n message: \"Document could not be safely inspected.\",\n },\n ];\n }\n}\n\nfunction validationIssuesToErrors(\n issues: readonly ValidationIssue[],\n fallbackPath: ValidationPath,\n maxIssues = Number.POSITIVE_INFINITY,\n): ConstructaError[] {\n return issues.slice(0, maxIssues).map(\n (issue) =>\n new ConstructaError({\n kind: \"configuration\",\n code: isValidationIssue(issue)\n ? errorCodeForValidationIssue(issue.code)\n : \"INVALID_CONFIGURATION\",\n path: isValidationIssue(issue) ? issue.path : fallbackPath,\n message: isValidationIssue(issue)\n ? issue.message\n : \"Validation returned an invalid issue.\",\n details: isValidationIssue(issue)\n ? { issueCode: issue.code }\n : undefined,\n }),\n );\n}\n\nfunction errorCodeForValidationIssue(code: string): Uppercase<string> {\n const reservedCodes: Record<string, Uppercase<string>> = {\n empty_choice: \"EMPTY_CHOICE\",\n invalid_length: \"INVALID_LENGTH\",\n invalid_range: \"INVALID_RANGE\",\n };\n return reservedCodes[code] ?? \"INVALID_CONFIGURATION\";\n}\n\nfunction isValidationIssue(value: unknown): value is ValidationIssue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ValidationIssue).code === \"string\" &&\n typeof (value as ValidationIssue).message === \"string\" &&\n Array.isArray((value as ValidationIssue).path)\n );\n}\n\nfunction addParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n code: string,\n path: ValidationPath,\n message: string,\n kind: \"configuration\" | \"system\" = \"configuration\",\n): void {\n if (issues.length < limits.maxIssues)\n issues.push(\n new ConstructaError({\n kind,\n code: code as Uppercase<string>,\n path,\n message,\n }),\n );\n}\n\nfunction addExistingParseIssue(\n issues: ConstructaError[],\n limits: ResolvedParseLimits,\n error: ConstructaError,\n): void {\n if (issues.length < limits.maxIssues) issues.push(error);\n}\n\nfunction assertGeneratorImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n if (!isStableTypeId(implementation.type)) {\n throw new TypeError(\"generator type must be a stable lowercase identifier\");\n }\n if (\n !Number.isSafeInteger(implementation.version) ||\n implementation.version < 1\n ) {\n throw new TypeError(\"generator version must be a positive safe integer\");\n }\n if (typeof implementation.validateDefinition !== \"function\") {\n throw new TypeError(\"validateDefinition must be a function\");\n }\n if (typeof implementation.generate !== \"function\") {\n throw new TypeError(\"generate must be a function\");\n }\n if (\n implementation.analyzeDependencies !== undefined &&\n typeof implementation.analyzeDependencies !== \"function\"\n ) {\n throw new TypeError(\"analyzeDependencies must be a function when present\");\n }\n}\n\nfunction assertRegistryImplementation(implementation: {\n readonly type: string;\n readonly version: number;\n readonly validateDefinition: unknown;\n readonly analyzeDependencies?: unknown;\n readonly generate: unknown;\n}): void {\n try {\n assertGeneratorImplementation(implementation);\n } catch {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"implementation\"],\n \"Generator implementation is invalid.\",\n );\n }\n if (RESERVED_GENERATOR_TYPE_IDS.has(implementation.type)) {\n throw registryError(\n \"INVALID_CONFIGURATION\",\n [\"type\"],\n `Generator type \"${implementation.type}\" is reserved.`,\n );\n }\n}\n\nfunction freezeImplementation<\n Definition extends GeneratorDefinition<Output>,\n Output,\n>(\n implementation: GeneratorImplementation<Definition, Output>,\n): GeneratorImplementation<Definition, Output> {\n return Object.freeze({ ...implementation });\n}\n\nfunction createRegistrySnapshot(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n): GeneratorRegistrySnapshot {\n const snapshotImplementations = new Map(implementations);\n const generators = [...snapshotImplementations.values()]\n .map(({ type, version }) => Object.freeze({ type, version }))\n .sort((left, right) => left.type.localeCompare(right.type));\n\n return Object.freeze({\n generators: Object.freeze(generators),\n lookup(type: string, path: ValidationPath = []) {\n return lookupImplementation(snapshotImplementations, type, path);\n },\n });\n}\n\nfunction lookupImplementation(\n implementations: ReadonlyMap<\n string,\n GeneratorImplementation<GeneratorDefinition, unknown>\n >,\n type: string,\n path: ValidationPath,\n): GeneratorImplementation<GeneratorDefinition, unknown> {\n const implementation = implementations.get(type);\n if (implementation !== undefined) return implementation;\n\n const registeredTypes = [...implementations.keys()].sort((left, right) =>\n left.localeCompare(right),\n );\n throw new ConstructaError({\n kind: \"dependency\",\n code: \"UNKNOWN_GENERATOR\",\n path: [...path, \"type\"],\n message: `No generator with type \"${type}\" is registered.`,\n details: { registeredTypes },\n });\n}\n\nfunction registryError(\n code: \"DUPLICATE_GENERATOR\" | \"INVALID_CONFIGURATION\" | \"UNKNOWN_GENERATOR\",\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({ kind: \"configuration\", code, path, message });\n}\n\nfunction assertRandomSourceAdapter(adapter: RandomSourceAdapter): void {\n if (\n typeof adapter !== \"object\" ||\n adapter === null ||\n typeof adapter.float !== \"function\" ||\n typeof adapter.integer !== \"function\" ||\n typeof adapter.bytes !== \"function\"\n ) {\n throw invalidRandomSource(\n \"A random source must provide float(), integer(), and bytes() methods.\",\n );\n }\n}\n\nfunction assertRandomLength(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw invalidRandomSource(`${name} must be a positive safe integer.`);\n }\n}\n\nfunction assertByteLength(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw invalidRandomSource(\"length must be a non-negative safe integer.\");\n }\n}\n\nfunction invalidRandomSource(message: string): ConstructaError {\n return new ConstructaError({\n kind: \"system\",\n code: \"INVALID_RANDOM_SOURCE\",\n path: [\"random\"],\n message,\n });\n}\n\nfunction assertContextPath(path: ValidationPath): void {\n for (const segment of path) assertContextPathSegment(segment);\n}\n\nfunction assertContextPathSegment(\n segment: unknown,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (!Number.isSafeInteger(segment) || typeof segment !== \"number\")\n ) {\n throw contextError(\n \"INVALID_GENERATION_CONTEXT\",\n [\"path\"],\n \"Context path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction assertChildPathSegment(\n segment: unknown,\n path: ValidationPath,\n): asserts segment is ValidationPathSegment {\n if (\n typeof segment !== \"string\" &&\n (typeof segment !== \"number\" || !Number.isSafeInteger(segment))\n ) {\n throw contextError(\n \"INVALID_CHILD_PATH\",\n path,\n \"Child path segments must be strings or safe integers.\",\n );\n }\n}\n\nfunction contextError(\n code: string,\n path: ValidationPath,\n message: string,\n): ConstructaError {\n return new ConstructaError({\n kind: \"configuration\",\n code: code as Uppercase<string>,\n path,\n message,\n });\n}\n\nfunction hashSeed(seed: string): number {\n let hash = 0x811c_9dc5;\n for (const byte of new TextEncoder().encode(seed)) {\n hash = Math.imul(hash ^ byte, 0x0100_0193) >>> 0;\n }\n return hash;\n}\n\nfunction isStableTypeId(value: string): boolean {\n return /^[a-z][a-z0-9]*(?:[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AS,iBAAiB,QAAsB;CAC9C,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,SAAS,GAC5C,MAAM,oBAAoB,6CAA6C;AAE3E;AAEA,SAAS,oBAAoB,SAAkC;CAC7D,OAAO,IAAI,gBAAgB;EACzB,MAAM;EACN,MAAM;EACN,MAAM,CAAC,QAAQ;EACf;CACF,CAAC;AACH;AAEA,SAAS,kBAAkB,MAA4B;CACrD,KAAK,MAAM,WAAW,MAAM,yBAAyB,OAAO;AAC9D;AAEA,SAAS,yBACP,SAC0C;CAC1C,IACE,OAAO,YAAY,aAClB,CAAC,OAAO,cAAc,OAAO,KAAK,OAAO,YAAY,WAEtD,MAAM,aACJ,8BACA,CAAC,MAAM,GACP,yDACF;AAEJ;AAEA,SAAS,uBACP,SACA,MAC0C;CAC1C,IACE,OAAO,YAAY,aAClB,OAAO,YAAY,YAAY,CAAC,OAAO,cAAc,OAAO,IAE7D,MAAM,aACJ,sBACA,MACA,uDACF;AAEJ;AAEA,SAAS,aACP,MACA,MACA,SACiB;CACjB,OAAO,IAAI,gBAAgB;EACzB,MAAM;EACA;EACN;EACA;CACF,CAAC;AACH;AAEA,SAAS,SAAS,MAAsB;CACtC,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,GAC9C,OAAO,KAAK,KAAK,OAAO,MAAM,QAAW,MAAM;CAEjD,OAAO;AACT;AAEA,SAAS,eAAe,OAAwB;CAC9C,OAAO,uCAAuC,KAAK,KAAK;AAC1D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "constructa-core",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "The UI-agnostic Constructa generator execution engine.",
5
5
  "private": false,
6
6
  "license": "MIT",