@kubohiroya/turbowarp-named-functions 0.1.2 → 0.2.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.
@@ -1,3 +1,4 @@
1
+ import {readLiteralInput, readOptionalLiteralInput} from './block-literals.js';
1
2
  import type {RuntimeTarget, SerializedBlock} from './runtime-types.js';
2
3
  import {validateSchemaDefinition} from './schema-validator.js';
3
4
 
@@ -28,11 +29,23 @@ export interface FunctionScan {
28
29
  errors: string[];
29
30
  }
30
31
 
32
+ export interface FunctionScanOptions {
33
+ /**
34
+ * Resolves a schema name typed into SCHEMA or RETURNS instead of JSON text, such as a
35
+ * `define schema` hat's name. Without it, those inputs must be JSON.
36
+ */
37
+ resolveSchema?: (reference: string, label: string) => Record<string, unknown>;
38
+ }
39
+
31
40
  /**
32
41
  * Reads every `define function` hat in the project. NAME, DESCRIPTION, and SCHEMA are part of the
33
42
  * tool contract sent to the model before any script runs, so they must be literal text.
34
43
  */
35
- export function scanFunctionDefinitions(targets: readonly RuntimeTarget[], hatOpcode: string): FunctionScan {
44
+ export function scanFunctionDefinitions(
45
+ targets: readonly RuntimeTarget[],
46
+ hatOpcode: string,
47
+ options: FunctionScanOptions = {}
48
+ ): FunctionScan {
36
49
  const functions: FunctionDefinition[] = [];
37
50
  const errors: string[] = [];
38
51
  const seen = new Map<string, string>();
@@ -45,7 +58,7 @@ export function scanFunctionDefinitions(targets: readonly RuntimeTarget[], hatOp
45
58
  if (block.opcode !== hatOpcode || block.topLevel === false) continue;
46
59
  const where = `${targetName} (block ${block.id})`;
47
60
  try {
48
- const definition = readDefinition(block, blocks, targetName);
61
+ const definition = readDefinition(block, blocks, targetName, options);
49
62
  const previous = seen.get(definition.name);
50
63
  if (previous !== undefined) {
51
64
  throw new Error(`function "${definition.name}" is already defined in ${previous}`);
@@ -75,7 +88,8 @@ export function toFunctionTools(functions: readonly FunctionDefinition[]): Funct
75
88
  function readDefinition(
76
89
  block: SerializedBlock,
77
90
  blocks: Record<string, SerializedBlock>,
78
- targetName: string
91
+ targetName: string,
92
+ options: FunctionScanOptions
79
93
  ): FunctionDefinition {
80
94
  const name = readLiteralInput(block, blocks, 'NAME').trim();
81
95
  if (!FUNCTION_NAME_PATTERN.test(name)) {
@@ -85,11 +99,11 @@ function readDefinition(
85
99
  if (description.length > MAX_DESCRIPTION_LENGTH) {
86
100
  throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
87
101
  }
88
- const parameters = parseSchema(readLiteralInput(block, blocks, 'SCHEMA'), 'args schema', true);
102
+ const parameters = parseSchema(readLiteralInput(block, blocks, 'SCHEMA'), 'args schema', true, options);
89
103
  const returnsText = readOptionalLiteralInput(block, blocks, 'RETURNS');
90
104
  const returns = returnsText === undefined || returnsText.trim() === ''
91
105
  ? undefined
92
- : parseSchema(returnsText, 'returns schema', false);
106
+ : parseSchema(returnsText, 'returns schema', false, options);
93
107
  const exportValue = String(block.fields?.EXPORT?.value ?? 'none');
94
108
  const exportAs = exportValue === 'tool' ? 'tool' : 'none';
95
109
  if (exportAs === 'tool' && description.length === 0) {
@@ -98,37 +112,22 @@ function readDefinition(
98
112
  return {name, description, parameters, ...(returns ? {returns} : {}), exportAs, targetName, blockId: block.id};
99
113
  }
100
114
 
101
- function readOptionalLiteralInput(
102
- block: SerializedBlock,
103
- blocks: Record<string, SerializedBlock>,
104
- inputName: string
105
- ): string | undefined {
106
- if (!block.inputs?.[inputName]) return undefined;
107
- return readLiteralInput(block, blocks, inputName);
108
- }
109
-
110
- function readLiteralInput(
111
- block: SerializedBlock,
112
- blocks: Record<string, SerializedBlock>,
113
- inputName: string
114
- ): string {
115
- const input = block.inputs?.[inputName];
116
- if (!input) throw new Error(`${inputName} is missing`);
117
- if (input.block && input.block !== input.shadow) {
118
- throw new Error(`${inputName} must be literal text, not a reporter block`);
119
- }
120
- const shadowId = input.shadow ?? input.block;
121
- const shadow = shadowId ? blocks[shadowId] : undefined;
122
- const field = shadow?.fields ? Object.values(shadow.fields)[0] : undefined;
123
- if (!field) throw new Error(`${inputName} is missing`);
124
- return String(field.value ?? '');
125
- }
126
-
127
- function parseSchema(text: string, label: string, requireObjectType: boolean): Record<string, unknown> {
115
+ /**
116
+ * SCHEMA and RETURNS hold either JSON Schema text or, when the consumer supports it, the name of a
117
+ * `define schema` hat. Text that is not JSON is treated as a name, so existing JSON projects are
118
+ * unaffected.
119
+ */
120
+ function parseSchema(
121
+ text: string,
122
+ label: string,
123
+ requireObjectType: boolean,
124
+ options: FunctionScanOptions
125
+ ): Record<string, unknown> {
128
126
  let value: unknown;
129
127
  try {
130
128
  value = JSON.parse(text) as unknown;
131
129
  } catch {
130
+ if (options.resolveSchema) return resolveNamed(text, label, requireObjectType, options.resolveSchema);
132
131
  throw new Error(`${label} must be valid JSON`);
133
132
  }
134
133
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
@@ -139,3 +138,15 @@ function parseSchema(text: string, label: string, requireObjectType: boolean): R
139
138
  validateSchemaDefinition(schema, label);
140
139
  return schema;
141
140
  }
141
+
142
+ function resolveNamed(
143
+ text: string,
144
+ label: string,
145
+ requireObjectType: boolean,
146
+ resolveSchema: (reference: string, label: string) => Record<string, unknown>
147
+ ): Record<string, unknown> {
148
+ const schema = resolveSchema(text, label);
149
+ if (requireObjectType && schema.type !== 'object') throw new Error('args schema must have "type": "object"');
150
+ validateSchemaDefinition(schema, label);
151
+ return schema;
152
+ }
@@ -14,6 +14,8 @@ export interface SerializedBlock {
14
14
  opcode: string;
15
15
  topLevel?: boolean;
16
16
  shadow?: boolean;
17
+ /** Id of the next block in the same stack, as the VM serializes a script. */
18
+ next?: string | null;
17
19
  inputs?: Record<string, SerializedInput>;
18
20
  fields?: Record<string, SerializedField>;
19
21
  }
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Lowers `define schema` block stacks into the canonical JSON Schema objects consumed by
3
+ * `validateAgainstSchema`.
4
+ *
5
+ * The builder is declarative: it reads literal block fields before any script runs and never
6
+ * executes the blocks it reads. Every schema it produces is checked with `validateSchemaDefinition`,
7
+ * so a block-built schema and a hand-written JSON one go through one validator and one diagnostic
8
+ * format.
9
+ */
10
+ import {readLiteralInput, readMenuField, stackBelow} from './block-literals.js';
11
+ import type {RuntimeTarget, SerializedBlock} from './runtime-types.js';
12
+ import {validateAgainstSchema, validateSchemaDefinition} from './schema-validator.js';
13
+
14
+ export const SCHEMA_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/u;
15
+
16
+ /** Complete SemVer, as the named-data schema identity contract requires. */
17
+ export const SCHEMA_VERSION_PATTERN =
18
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
19
+
20
+ /** How deep a chain of schema references may nest before it is reported as too deep. */
21
+ export const MAX_SCHEMA_REFERENCE_DEPTH = 16;
22
+
23
+ /** Opcodes of the consumer extension's schema-builder blocks. */
24
+ export interface SchemaBlockOpcodes {
25
+ /** `define schema [NAME] version [VERSION]` */
26
+ hat: string;
27
+ /** `property [NAME] type [TYPE] [PRESENCE]` */
28
+ property: string;
29
+ /** `property [NAME] schema [SCHEMA] [PRESENCE]` */
30
+ propertySchema: string;
31
+ /** `property [NAME] array of schema [SCHEMA] [PRESENCE]` */
32
+ propertyArraySchema: string;
33
+ /** `limit [KEYWORD] to (VALUE)` */
34
+ constraint: string;
35
+ /** `allowed values [VALUES]` */
36
+ allowedValues: string;
37
+ /** `allow undeclared properties [ALLOW]` */
38
+ additionalProperties: string;
39
+ }
40
+
41
+ export interface SchemaDefinition {
42
+ name: string;
43
+ version: string;
44
+ /** Canonical JSON Schema with every schema reference already inlined. */
45
+ schema: Record<string, unknown>;
46
+ targetName: string;
47
+ blockId: string;
48
+ }
49
+
50
+ export interface SchemaScan {
51
+ schemas: SchemaDefinition[];
52
+ errors: string[];
53
+ }
54
+
55
+ /** A `Name` or `Name@1.2.3` reference typed into a block field. */
56
+ export interface SchemaReference {
57
+ name: string;
58
+ version?: string;
59
+ }
60
+
61
+ const PROPERTY_TYPES: Record<string, () => Record<string, unknown>> = {
62
+ string: () => ({type: 'string'}),
63
+ number: () => ({type: 'number'}),
64
+ integer: () => ({type: 'integer'}),
65
+ boolean: () => ({type: 'boolean'}),
66
+ null: () => ({type: 'null'}),
67
+ object: () => ({type: 'object'}),
68
+ array: () => ({type: 'array'}),
69
+ 'array of string': () => ({type: 'array', items: {type: 'string'}}),
70
+ 'array of number': () => ({type: 'array', items: {type: 'number'}}),
71
+ 'array of integer': () => ({type: 'array', items: {type: 'integer'}}),
72
+ 'array of boolean': () => ({type: 'array', items: {type: 'boolean'}}),
73
+ 'array of object': () => ({type: 'array', items: {type: 'object'}})
74
+ };
75
+
76
+ const CONSTRAINT_KEYWORDS = new Set(['minimum', 'maximum', 'minLength', 'maxLength', 'minItems', 'maxItems']);
77
+
78
+ /** Keywords that describe the array itself rather than each of its items. */
79
+ const ARRAY_LEVEL_KEYWORDS = new Set(['minItems', 'maxItems']);
80
+
81
+ interface DraftProperty {
82
+ name: string;
83
+ required: boolean;
84
+ /** Set unless the property points at another named schema. */
85
+ schema?: Record<string, unknown>;
86
+ reference?: SchemaReference;
87
+ /** True when the reference stands for an array of the referenced schema. */
88
+ referenceIsArray?: boolean;
89
+ }
90
+
91
+ interface DraftSchema {
92
+ name: string;
93
+ version: string;
94
+ properties: DraftProperty[];
95
+ additionalProperties?: boolean;
96
+ targetName: string;
97
+ blockId: string;
98
+ }
99
+
100
+ /**
101
+ * Reads every `define schema` hat in the project and lowers it to a canonical JSON Schema.
102
+ * A hat that cannot be read is reported in `errors` and left out of `schemas`.
103
+ */
104
+ export function scanSchemaDefinitions(
105
+ targets: readonly RuntimeTarget[],
106
+ opcodes: SchemaBlockOpcodes
107
+ ): SchemaScan {
108
+ const drafts: DraftSchema[] = [];
109
+ const errors: string[] = [];
110
+ const seen = new Map<string, string>();
111
+
112
+ for (const target of targets) {
113
+ if (target.isOriginal === false) continue;
114
+ const targetName = target.getName?.() ?? (target.isStage ? 'Stage' : 'sprite');
115
+ const blocks = target.blocks._blocks;
116
+ for (const block of Object.values(blocks)) {
117
+ if (block.opcode !== opcodes.hat || block.topLevel === false) continue;
118
+ const where = `${targetName} (block ${block.id})`;
119
+ try {
120
+ const draft = readDraft(block, blocks, opcodes, targetName);
121
+ const key = `${draft.name}@${draft.version}`;
122
+ const previous = seen.get(key);
123
+ if (previous !== undefined) {
124
+ throw new Error(`schema "${key}" is already defined in ${previous}`);
125
+ }
126
+ seen.set(key, where);
127
+ drafts.push(draft);
128
+ } catch (error) {
129
+ errors.push(`${where}: ${messageOf(error)}`);
130
+ }
131
+ }
132
+ }
133
+
134
+ const byKey = new Map(drafts.map((draft) => [`${draft.name}@${draft.version}`, draft]));
135
+ const schemas: SchemaDefinition[] = [];
136
+ for (const draft of drafts) {
137
+ try {
138
+ const schema = lowerDraft(draft, byKey, []);
139
+ validateSchemaDefinition(schema, `schema ${draft.name}`);
140
+ schemas.push({
141
+ name: draft.name,
142
+ version: draft.version,
143
+ schema,
144
+ targetName: draft.targetName,
145
+ blockId: draft.blockId
146
+ });
147
+ } catch (error) {
148
+ errors.push(`${draft.targetName} (block ${draft.blockId}): ${messageOf(error)}`);
149
+ }
150
+ }
151
+
152
+ schemas.sort((left, right) => compare(`${left.name}@${left.version}`, `${right.name}@${right.version}`));
153
+ return {schemas, errors};
154
+ }
155
+
156
+ /** Parses `Name` or `Name@1.2.3`. */
157
+ export function parseSchemaReference(text: string, label: string): SchemaReference {
158
+ const trimmed = text.trim();
159
+ const at = trimmed.lastIndexOf('@');
160
+ const name = at > 0 ? trimmed.slice(0, at) : trimmed;
161
+ const version = at > 0 ? trimmed.slice(at + 1) : undefined;
162
+ if (!SCHEMA_NAME_PATTERN.test(name)) {
163
+ throw new Error(`${label} must be 1-128 letters, digits, ".", "_" or "-"`);
164
+ }
165
+ if (version !== undefined && !SCHEMA_VERSION_PATTERN.test(version)) {
166
+ throw new Error(`${label} version "${version}" must be a complete SemVer value such as 1.0.0`);
167
+ }
168
+ return version === undefined ? {name} : {name, version};
169
+ }
170
+
171
+ /**
172
+ * Resolves a `Name` or `Name@1.2.3` reference against scanned schemas. An unknown name or version
173
+ * fails; a name with several versions and no pinned version is ambiguous rather than guessed.
174
+ */
175
+ export function resolveSchemaReference(
176
+ schemas: readonly SchemaDefinition[],
177
+ text: string,
178
+ label: string
179
+ ): Record<string, unknown> {
180
+ const reference = parseSchemaReference(text, label);
181
+ const matches = schemas.filter((candidate) => candidate.name === reference.name);
182
+ if (matches.length === 0) {
183
+ throw new Error(`${label} refers to unknown schema "${reference.name}"`);
184
+ }
185
+ if (reference.version !== undefined) {
186
+ const exact = matches.find((candidate) => candidate.version === reference.version);
187
+ if (!exact) {
188
+ const available = matches.map((candidate) => candidate.version).join(', ');
189
+ throw new Error(
190
+ `${label} refers to unknown version "${reference.version}" of schema "${reference.name}" (defined: ${available})`
191
+ );
192
+ }
193
+ return exact.schema;
194
+ }
195
+ if (matches.length > 1) {
196
+ const available = matches.map((candidate) => candidate.version).join(', ');
197
+ throw new Error(
198
+ `${label} refers to schema "${reference.name}", which has several versions (${available}); pin one as "${reference.name}@${matches[0]?.version}"`
199
+ );
200
+ }
201
+ return (matches[0] as SchemaDefinition).schema;
202
+ }
203
+
204
+ function readDraft(
205
+ hat: SerializedBlock,
206
+ blocks: Record<string, SerializedBlock>,
207
+ opcodes: SchemaBlockOpcodes,
208
+ targetName: string
209
+ ): DraftSchema {
210
+ const name = readLiteralInput(hat, blocks, 'NAME').trim();
211
+ if (!SCHEMA_NAME_PATTERN.test(name)) {
212
+ throw new Error('schema name must be 1-128 letters, digits, ".", "_" or "-"');
213
+ }
214
+ const version = readLiteralInput(hat, blocks, 'VERSION').trim();
215
+ if (!SCHEMA_VERSION_PATTERN.test(version)) {
216
+ throw new Error(`schema version "${version}" must be a complete SemVer value such as 1.0.0`);
217
+ }
218
+
219
+ const draft: DraftSchema = {name, version, properties: [], targetName, blockId: hat.id};
220
+ const declared = new Set<string>();
221
+
222
+ for (const block of stackBelow(hat, blocks)) {
223
+ if (block.opcode === opcodes.property) {
224
+ draft.properties.push(readProperty(block, blocks, declared));
225
+ } else if (block.opcode === opcodes.propertySchema || block.opcode === opcodes.propertyArraySchema) {
226
+ draft.properties.push(
227
+ readReferenceProperty(block, blocks, declared, block.opcode === opcodes.propertyArraySchema)
228
+ );
229
+ } else if (block.opcode === opcodes.constraint) {
230
+ applyConstraint(block, blocks, draft);
231
+ } else if (block.opcode === opcodes.allowedValues) {
232
+ applyAllowedValues(block, blocks, draft);
233
+ } else if (block.opcode === opcodes.additionalProperties) {
234
+ if (draft.additionalProperties !== undefined) {
235
+ throw new Error('"allow undeclared properties" is used more than once in this schema');
236
+ }
237
+ draft.additionalProperties = readMenuField(block, 'ALLOW') === 'yes';
238
+ } else {
239
+ throw new Error(`${block.opcode} cannot be used inside a "define schema" stack`);
240
+ }
241
+ }
242
+ return draft;
243
+ }
244
+
245
+ function readProperty(
246
+ block: SerializedBlock,
247
+ blocks: Record<string, SerializedBlock>,
248
+ declared: Set<string>
249
+ ): DraftProperty {
250
+ const name = readPropertyName(block, blocks, declared);
251
+ const typeName = readMenuField(block, 'TYPE');
252
+ const build = PROPERTY_TYPES[typeName];
253
+ if (!build) throw new Error(`property "${name}" has unsupported type "${typeName}"`);
254
+ return {name, required: readPresence(block), schema: build()};
255
+ }
256
+
257
+ function readReferenceProperty(
258
+ block: SerializedBlock,
259
+ blocks: Record<string, SerializedBlock>,
260
+ declared: Set<string>,
261
+ asArray: boolean
262
+ ): DraftProperty {
263
+ const name = readPropertyName(block, blocks, declared);
264
+ const reference = parseSchemaReference(
265
+ readLiteralInput(block, blocks, 'SCHEMA'),
266
+ `property "${name}" schema`
267
+ );
268
+ return {name, required: readPresence(block), reference, referenceIsArray: asArray};
269
+ }
270
+
271
+ function readPropertyName(
272
+ block: SerializedBlock,
273
+ blocks: Record<string, SerializedBlock>,
274
+ declared: Set<string>
275
+ ): string {
276
+ const name = readLiteralInput(block, blocks, 'NAME').trim();
277
+ if (name.length === 0) throw new Error('a property needs a name');
278
+ if (declared.has(name)) throw new Error(`property "${name}" is declared more than once`);
279
+ declared.add(name);
280
+ return name;
281
+ }
282
+
283
+ function readPresence(block: SerializedBlock): boolean {
284
+ return readMenuField(block, 'PRESENCE') === 'required';
285
+ }
286
+
287
+ function applyConstraint(
288
+ block: SerializedBlock,
289
+ blocks: Record<string, SerializedBlock>,
290
+ draft: DraftSchema
291
+ ): void {
292
+ const keyword = readMenuField(block, 'KEYWORD');
293
+ if (!CONSTRAINT_KEYWORDS.has(keyword)) throw new Error(`unsupported limit "${keyword}"`);
294
+ const target = constraintTarget(draft, `limit "${keyword}"`, keyword);
295
+ const raw = readLiteralInput(block, blocks, 'VALUE').trim();
296
+ const value = Number(raw);
297
+ if (raw.length === 0 || !Number.isFinite(value)) {
298
+ throw new Error(`limit "${keyword}" needs a number, not "${raw}"`);
299
+ }
300
+ if (target[keyword] !== undefined) {
301
+ throw new Error(`limit "${keyword}" is set more than once on property "${lastProperty(draft).name}"`);
302
+ }
303
+ target[keyword] = value;
304
+ }
305
+
306
+ function applyAllowedValues(
307
+ block: SerializedBlock,
308
+ blocks: Record<string, SerializedBlock>,
309
+ draft: DraftSchema
310
+ ): void {
311
+ const target = constraintTarget(draft, '"allowed values"', 'enum');
312
+ const property = lastProperty(draft);
313
+ if (target.enum !== undefined) {
314
+ throw new Error(`"allowed values" is set more than once on property "${property.name}"`);
315
+ }
316
+ const values = parseAllowedValues(readLiteralInput(block, blocks, 'VALUES'), property.name);
317
+ // The declared type and the allowed values must agree, or every value would fail at call time.
318
+ const type = target.type;
319
+ if (type !== undefined) {
320
+ for (const value of values) {
321
+ const errors = validateAgainstSchema(value, {type});
322
+ if (errors.length > 0) {
323
+ throw new Error(
324
+ `allowed value ${JSON.stringify(value)} does not match the declared type of property "${property.name}"`
325
+ );
326
+ }
327
+ }
328
+ }
329
+ target.enum = values;
330
+ }
331
+
332
+ /**
333
+ * Where a limit or an allowed-values list belongs. For an array property the item keywords describe
334
+ * each item, while `minItems`/`maxItems` describe the array.
335
+ */
336
+ function constraintTarget(draft: DraftSchema, label: string, keyword: string): Record<string, unknown> {
337
+ const property = lastProperty(draft, label);
338
+ if (!property.schema) {
339
+ throw new Error(`${label} cannot be used on property "${property.name}", which uses another schema`);
340
+ }
341
+ const isArray = property.schema.type === 'array';
342
+ if (!isArray) {
343
+ if (ARRAY_LEVEL_KEYWORDS.has(keyword)) {
344
+ throw new Error(`${label} can only be used on an array property, not "${property.name}"`);
345
+ }
346
+ return property.schema;
347
+ }
348
+ if (ARRAY_LEVEL_KEYWORDS.has(keyword)) return property.schema;
349
+ const items = property.schema.items;
350
+ if (items === undefined || typeof items !== 'object' || items === null || Array.isArray(items)) {
351
+ throw new Error(
352
+ `${label} needs property "${property.name}" to declare an item type, such as "array of number"`
353
+ );
354
+ }
355
+ return items as Record<string, unknown>;
356
+ }
357
+
358
+ function lastProperty(draft: DraftSchema, label = 'this block'): DraftProperty {
359
+ const property = draft.properties.at(-1);
360
+ if (!property) throw new Error(`${label} must come after a property block`);
361
+ return property;
362
+ }
363
+
364
+ /** JSON array text, or a comma-separated list of strings. */
365
+ function parseAllowedValues(text: string, propertyName: string): unknown[] {
366
+ const trimmed = text.trim();
367
+ if (trimmed.length === 0) throw new Error(`"allowed values" for property "${propertyName}" is empty`);
368
+ if (trimmed.startsWith('[')) {
369
+ let parsed: unknown;
370
+ try {
371
+ parsed = JSON.parse(trimmed) as unknown;
372
+ } catch {
373
+ throw new Error(`"allowed values" for property "${propertyName}" must be valid JSON`);
374
+ }
375
+ if (!Array.isArray(parsed) || parsed.length === 0) {
376
+ throw new Error(`"allowed values" for property "${propertyName}" must be a non-empty JSON array`);
377
+ }
378
+ return parsed;
379
+ }
380
+ const values = trimmed.split(',').map((value) => value.trim()).filter((value) => value.length > 0);
381
+ if (values.length === 0) throw new Error(`"allowed values" for property "${propertyName}" is empty`);
382
+ return values;
383
+ }
384
+
385
+ function lowerDraft(
386
+ draft: DraftSchema,
387
+ byKey: ReadonlyMap<string, DraftSchema>,
388
+ stack: readonly string[]
389
+ ): Record<string, unknown> {
390
+ const key = `${draft.name}@${draft.version}`;
391
+ if (stack.includes(key)) {
392
+ throw new Error(`schema reference cycle: ${[...stack, key].join(' -> ')}`);
393
+ }
394
+ if (stack.length >= MAX_SCHEMA_REFERENCE_DEPTH) {
395
+ throw new Error(`schema references nest deeper than ${MAX_SCHEMA_REFERENCE_DEPTH} levels`);
396
+ }
397
+ const nextStack = [...stack, key];
398
+
399
+ const properties: Record<string, unknown> = {};
400
+ const required: string[] = [];
401
+ for (const property of draft.properties) {
402
+ properties[property.name] = property.reference
403
+ ? lowerReference(property, draft, byKey, nextStack)
404
+ : (property.schema as Record<string, unknown>);
405
+ if (property.required) required.push(property.name);
406
+ }
407
+
408
+ return {
409
+ type: 'object',
410
+ properties,
411
+ ...(required.length > 0 ? {required} : {}),
412
+ ...(draft.additionalProperties === undefined ? {} : {additionalProperties: draft.additionalProperties})
413
+ };
414
+ }
415
+
416
+ function lowerReference(
417
+ property: DraftProperty,
418
+ draft: DraftSchema,
419
+ byKey: ReadonlyMap<string, DraftSchema>,
420
+ stack: readonly string[]
421
+ ): Record<string, unknown> {
422
+ const reference = property.reference as SchemaReference;
423
+ const label = `property "${property.name}" of schema ${draft.name}`;
424
+ const target = findDraft(byKey, reference, label);
425
+ const lowered = lowerDraft(target, byKey, stack);
426
+ return property.referenceIsArray ? {type: 'array', items: lowered} : lowered;
427
+ }
428
+
429
+ function findDraft(
430
+ byKey: ReadonlyMap<string, DraftSchema>,
431
+ reference: SchemaReference,
432
+ label: string
433
+ ): DraftSchema {
434
+ if (reference.version !== undefined) {
435
+ const exact = byKey.get(`${reference.name}@${reference.version}`);
436
+ if (!exact) {
437
+ throw new Error(`${label} refers to unknown schema "${reference.name}@${reference.version}"`);
438
+ }
439
+ return exact;
440
+ }
441
+ const matches = [...byKey.values()].filter((candidate) => candidate.name === reference.name);
442
+ if (matches.length === 0) throw new Error(`${label} refers to unknown schema "${reference.name}"`);
443
+ if (matches.length > 1) {
444
+ const available = matches.map((candidate) => candidate.version).join(', ');
445
+ throw new Error(
446
+ `${label} refers to schema "${reference.name}", which has several versions (${available}); pin one as "${reference.name}@${matches[0]?.version}"`
447
+ );
448
+ }
449
+ return matches[0] as DraftSchema;
450
+ }
451
+
452
+ function compare(left: string, right: string): number {
453
+ return left < right ? -1 : left > right ? 1 : 0;
454
+ }
455
+
456
+ function messageOf(error: unknown): string {
457
+ return error instanceof Error ? error.message : String(error);
458
+ }