typebars 1.0.21 → 1.0.22

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,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get assertNoConditionalSchema(){return assertNoConditionalSchema},get findConditionalSchemaLocations(){return findConditionalSchemaLocations},get resolveArrayItems(){return resolveArrayItems},get resolveRef(){return resolveRef},get resolveSchemaPath(){return resolveSchemaPath},get simplifySchema(){return simplifySchema}});const _errorsts=require("./errors.js");const _utilsts=require("./utils.js");function findConditionalSchemaLocations(schema,path="",visited=new Set){const locations=[];if(visited.has(schema))return locations;visited.add(schema);for(const kw of["if","then","else"]){if(schema[kw]!==undefined){locations.push({keyword:"if/then/else",schemaPath:path||"/"});break}}if(schema.properties){for(const[key,prop]of Object.entries(schema.properties)){if(prop&&typeof prop!=="boolean"){locations.push(...findConditionalSchemaLocations(prop,`${path}/properties/${key}`,visited))}}}if(schema.additionalProperties&&typeof schema.additionalProperties==="object"){locations.push(...findConditionalSchemaLocations(schema.additionalProperties,`${path}/additionalProperties`,visited))}if(schema.items){if(Array.isArray(schema.items)){for(let i=0;i<schema.items.length;i++){const item=schema.items[i];if(item&&typeof item!=="boolean"){locations.push(...findConditionalSchemaLocations(item,`${path}/items/${i}`,visited))}}}else if(typeof schema.items!=="boolean"){locations.push(...findConditionalSchemaLocations(schema.items,`${path}/items`,visited))}}for(const keyword of["allOf","anyOf","oneOf"]){const branches=schema[keyword];if(branches){for(let i=0;i<branches.length;i++){const branch=branches[i];if(branch&&typeof branch!=="boolean"){locations.push(...findConditionalSchemaLocations(branch,`${path}/${keyword}/${i}`,visited))}}}}if(schema.not&&typeof schema.not!=="boolean"){locations.push(...findConditionalSchemaLocations(schema.not,`${path}/not`,visited))}for(const defsKey of["definitions","$defs"]){const defs=schema[defsKey];if(defs){for(const[name,def]of Object.entries(defs)){if(def&&typeof def!=="boolean"){locations.push(...findConditionalSchemaLocations(def,`${path}/${defsKey}/${name}`,visited))}}}}return locations}function assertNoConditionalSchema(schema,path="",visited=new Set){const locations=findConditionalSchemaLocations(schema,path,visited);if(locations.length>0){const first=locations[0];throw new _errorsts.UnsupportedSchemaError(first.keyword,first.schemaPath)}}function resolveRef(schema,root){if(!schema.$ref)return schema;const ref=schema.$ref;const match=ref.match(/^#\/(definitions|\$defs)\/(.+)$/);if(!match){throw new Error(`Unsupported $ref format: "${ref}". Only internal #/definitions/ references are supported.`)}const defsKey=match[1];const name=match[2]??"";const defs=defsKey==="definitions"?root.definitions:root.$defs;if(!defs||!(name in defs)){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}const def=defs[name];if(!def||typeof def==="boolean"){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}return resolveRef(def,root)}function resolveSegment(schema,segment,root){const resolved=resolveRef(schema,root);if(resolved.properties&&segment in resolved.properties){const prop=resolved.properties[segment];if(prop&&typeof prop!=="boolean")return resolveRef(prop,root);if(prop===true)return{}}if(resolved.additionalProperties!==undefined&&resolved.additionalProperties!==false){if(resolved.additionalProperties===true){return{}}return resolveRef(resolved.additionalProperties,root)}const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(isArray&&segment==="length"){return{type:"integer"}}if(isArray&&/^\d+$/.test(segment)){if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const idx=Number.parseInt(segment,10);const item=resolved.items[idx];if(item!==undefined&&typeof item!=="boolean"){return resolveRef(item,root)}if(item!==undefined&&typeof item==="boolean"){return{}}if(resolved.additionalItems===false){return undefined}if(resolved.additionalItems!==undefined&&resolved.additionalItems!==true&&typeof resolved.additionalItems==="object"){return resolveRef(resolved.additionalItems,root)}return{}}return resolveRef(resolved.items,root)}const combinatorResult=resolveInCombinators(resolved,segment,root);if(combinatorResult)return combinatorResult;return undefined}function resolveInCombinators(schema,segment,root){if(schema.allOf){const matches=schema.allOf.filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{allOf:matches}}for(const key of["anyOf","oneOf"]){if(!schema[key])continue;const matches=schema[key].filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{[key]:matches}}return undefined}function resolveSchemaPath(schema,path){if(path.length===0)return resolveRef(schema,schema);let current=resolveRef(schema,schema);const root=schema;for(const segment of path){const next=resolveSegment(current,segment,root);if(next===undefined)return undefined;current=next}return current}function resolveArrayItems(schema,root){const resolved=resolveRef(schema,root);const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(!isArray&&resolved.items===undefined){return undefined}if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const schemas=resolved.items.filter(item=>typeof item!=="boolean").map(item=>resolveRef(item,root));if(schemas.length===0)return{};return{oneOf:schemas}}return resolveRef(resolved.items,root)}function simplifySchema(schema){for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length===1){const first=arr[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}}if(schema.allOf&&schema.allOf.length===1){const first=schema.allOf[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length>1){const unique=[];for(const entry of arr){if(typeof entry==="boolean")continue;const isDuplicate=unique.some(existing=>(0,_utilsts.deepEqual)(existing,entry));if(!isDuplicate){unique.push(simplifySchema(entry))}}if(unique.length===1)return unique[0];return{...schema,[key]:unique}}}return schema}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get assertNoConditionalSchema(){return assertNoConditionalSchema},get findConditionalSchemaLocations(){return findConditionalSchemaLocations},get resolveArrayItems(){return resolveArrayItems},get resolveRef(){return resolveRef},get resolveSchemaPath(){return resolveSchemaPath},get simplifySchema(){return simplifySchema}});const _errorsts=require("./errors.js");const _utilsts=require("./utils.js");function findConditionalSchemaLocations(schema,path="",visited=new Set){const locations=[];if(visited.has(schema))return locations;visited.add(schema);for(const kw of["if","then","else"]){if(schema[kw]!==undefined){locations.push({keyword:"if/then/else",schemaPath:path||"/"});break}}if(schema.properties){for(const[key,prop]of Object.entries(schema.properties)){if(prop&&typeof prop!=="boolean"){locations.push(...findConditionalSchemaLocations(prop,`${path}/properties/${key}`,visited))}}}if(schema.additionalProperties&&typeof schema.additionalProperties==="object"){locations.push(...findConditionalSchemaLocations(schema.additionalProperties,`${path}/additionalProperties`,visited))}if(schema.items){if(Array.isArray(schema.items)){for(let i=0;i<schema.items.length;i++){const item=schema.items[i];if(item&&typeof item!=="boolean"){locations.push(...findConditionalSchemaLocations(item,`${path}/items/${i}`,visited))}}}else if(typeof schema.items!=="boolean"){locations.push(...findConditionalSchemaLocations(schema.items,`${path}/items`,visited))}}for(const keyword of["allOf","anyOf","oneOf"]){const branches=schema[keyword];if(branches){for(let i=0;i<branches.length;i++){const branch=branches[i];if(branch&&typeof branch!=="boolean"){locations.push(...findConditionalSchemaLocations(branch,`${path}/${keyword}/${i}`,visited))}}}}if(schema.not&&typeof schema.not!=="boolean"){locations.push(...findConditionalSchemaLocations(schema.not,`${path}/not`,visited))}for(const defsKey of["definitions","$defs"]){const defs=schema[defsKey];if(defs){for(const[name,def]of Object.entries(defs)){if(def&&typeof def!=="boolean"){locations.push(...findConditionalSchemaLocations(def,`${path}/${defsKey}/${name}`,visited))}}}}return locations}function assertNoConditionalSchema(schema,path="",visited=new Set){const locations=findConditionalSchemaLocations(schema,path,visited);if(locations.length>0){const first=locations[0];throw new _errorsts.UnsupportedSchemaError(first.keyword,first.schemaPath)}}function resolveRef(schema,root){if(!schema.$ref)return schema;const ref=schema.$ref;const match=ref.match(/^#\/(definitions|\$defs)\/(.+)$/);if(!match){throw new Error(`Unsupported $ref format: "${ref}". Only internal #/definitions/ references are supported.`)}const defsKey=match[1];const name=match[2]??"";const defs=defsKey==="definitions"?root.definitions:root.$defs;if(!defs||!(name in defs)){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}const def=defs[name];if(!def||typeof def==="boolean"){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}return resolveRef(def,root)}function resolveSegment(schema,segment,root){const resolved=resolveRef(schema,root);if(resolved.properties&&segment in resolved.properties){const prop=resolved.properties[segment];if(prop&&typeof prop!=="boolean")return resolveRef(prop,root);if(prop===true)return{}}if(resolved.additionalProperties!==undefined&&resolved.additionalProperties!==false){if(resolved.additionalProperties===true){return{}}return resolveRef(resolved.additionalProperties,root)}const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(isArray&&segment==="length"){return{type:"integer"}}if(isArray&&/^\d+$/.test(segment)){if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const idx=Number.parseInt(segment,10);const item=resolved.items[idx];if(item!==undefined&&typeof item!=="boolean"){return resolveRef(item,root)}if(item!==undefined&&typeof item==="boolean"){return{}}if(resolved.additionalItems===false){return undefined}if(resolved.additionalItems!==undefined&&resolved.additionalItems!==true&&typeof resolved.additionalItems==="object"){return resolveRef(resolved.additionalItems,root)}return{}}return resolveRef(resolved.items,root)}const combinatorResult=resolveInCombinators(resolved,segment,root);if(combinatorResult)return combinatorResult;return undefined}function resolveInCombinators(schema,segment,root){if(schema.allOf){const matches=schema.allOf.filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{allOf:matches}}for(const key of["anyOf","oneOf"]){if(!schema[key])continue;const matches=schema[key].filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{[key]:matches}}return undefined}function resolveSchemaPath(schema,path){if(path.length===0)return resolveRef(schema,schema);let current=resolveRef(schema,schema);const root=schema;for(const segment of path){const next=resolveSegment(current,segment,root);if(next===undefined)return undefined;current=next}return current}function resolveArrayItems(schema,root){const resolved=resolveRef(schema,root);const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(!isArray&&resolved.items===undefined){return undefined}if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const schemas=resolved.items.filter(item=>typeof item!=="boolean").map(item=>resolveRef(item,root));if(schemas.length===0)return{};return{oneOf:schemas}}return resolveRef(resolved.items,root)}function simplifySchema(schema){for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length===1){const first=arr[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}}if(schema.allOf&&schema.allOf.length===1){const first=schema.allOf[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}let result=schema;for(const key of["oneOf","anyOf"]){const arr=result[key];if(arr&&arr.length>1){const unique=[];for(const entry of arr){if(typeof entry==="boolean")continue;const simplified=simplifySchema(entry);const isDuplicate=unique.some(existing=>(0,_utilsts.deepEqual)(existing,simplified));if(!isDuplicate){unique.push(simplified)}}if(unique.length===1)return unique[0];result={...result,[key]:unique}}}if(result.allOf&&result.allOf.length>1){const simplifiedBranches=result.allOf.map(branch=>{if(typeof branch==="boolean"||branch===undefined)return branch;return simplifySchema(branch)});result={...result,allOf:simplifiedBranches}}if(result.properties){const simplifiedProps={};let changed=false;for(const[key,prop]of Object.entries(result.properties)){if(prop&&typeof prop!=="boolean"){const simplified=simplifySchema(prop);simplifiedProps[key]=simplified;if(simplified!==prop)changed=true}else{simplifiedProps[key]=prop}}if(changed){result={...result,properties:simplifiedProps}}}if(result.items){if(Array.isArray(result.items)){let itemsChanged=false;const simplifiedItems=result.items.map(item=>{if(item&&typeof item!=="boolean"){const simplified=simplifySchema(item);if(simplified!==item)itemsChanged=true;return simplified}return item});if(itemsChanged){result={...result,items:simplifiedItems}}}else if(typeof result.items!=="boolean"){const simplified=simplifySchema(result.items);if(simplified!==result.items){result={...result,items:simplified}}}}if(result.additionalProperties&&typeof result.additionalProperties==="object"){const simplified=simplifySchema(result.additionalProperties);if(simplified!==result.additionalProperties){result={...result,additionalProperties:simplified}}}return result}
2
2
  //# sourceMappingURL=schema-resolver.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema-resolver.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { UnsupportedSchemaError } from \"./errors.ts\";\nimport { deepEqual } from \"./utils.ts\";\n\n// ─── JSON Schema Resolver ────────────────────────────────────────────────────\n// Utility for navigating a JSON Schema Draft v7 by following a property path\n// (e.g. [\"user\", \"address\", \"city\"]).\n//\n// Handles:\n// - `$ref` resolution (internal references #/definitions/...)\n// - Navigation through `properties`\n// - Navigation through `items` (array elements)\n// - Combinators `allOf`, `anyOf`, `oneOf` (searches each branch)\n// - `additionalProperties` when the property is not explicitly declared\n//\n// Rejects:\n// - Conditional schemas (`if/then/else`) — non-resolvable without runtime data\n\n// ─── Conditional Schema Detection ────────────────────────────────────────────\n// JSON Schema Draft v7 introduced `if/then/else` conditional schemas.\n// These are fundamentally non-resolvable during static analysis because\n// they depend on runtime data values. Rather than silently ignoring them\n// (which would produce incorrect results — missing properties, wrong types),\n// we fail fast with a clear error pointing to the exact location in the schema.\n\n/**\n * Recursively scans a JSON Schema tree for `if/then/else` conditional keywords\n * and returns their locations as an array of `{ keyword, schemaPath }` objects.\n *\n * This is the non-throwing counterpart of `assertNoConditionalSchema`.\n * It traverses the entire schema tree, including:\n * - `properties` values\n * - `additionalProperties` (when it's a schema)\n * - `items` (single schema or tuple)\n * - `allOf`, `anyOf`, `oneOf` branches\n * - `not`\n * - `definitions` / `$defs` values\n *\n * A `Set<object>` is used to track visited schemas and prevent infinite loops\n * from circular structures.\n *\n * @param schema - The JSON Schema to scan\n * @param path - The current JSON pointer path (for location reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n * @returns Array of locations where `if/then/else` keywords were found\n *\n * @example\n * ```\n * // Returns [{ keyword: \"if/then/else\", schemaPath: \"/\" }]:\n * findConditionalSchemaLocations({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // Returns []:\n * findConditionalSchemaLocations({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function findConditionalSchemaLocations(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): Array<{ keyword: string; schemaPath: string }> {\n\tconst locations: Array<{ keyword: string; schemaPath: string }> = [];\n\n\t// Cycle protection — avoid infinite loops on circular schema structures\n\tif (visited.has(schema)) return locations;\n\tvisited.add(schema);\n\n\t// ── Detect if/then/else at the current level ─────────────────────────\n\t// One diagnostic per schema node is enough — no need to report `then`\n\t// and `else` separately if `if` is already present.\n\tfor (const kw of [\"if\", \"then\", \"else\"] as const) {\n\t\tif (schema[kw] !== undefined) {\n\t\t\tlocations.push({ keyword: \"if/then/else\", schemaPath: path || \"/\" });\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// ── Recurse into properties ──────────────────────────────────────────\n\tif (schema.properties) {\n\t\tfor (const [key, prop] of Object.entries(schema.properties)) {\n\t\t\tif (prop && typeof prop !== \"boolean\") {\n\t\t\t\tlocations.push(\n\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\tprop,\n\t\t\t\t\t\t`${path}/properties/${key}`,\n\t\t\t\t\t\tvisited,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into additionalProperties ────────────────────────────────\n\tif (\n\t\tschema.additionalProperties &&\n\t\ttypeof schema.additionalProperties === \"object\"\n\t) {\n\t\tlocations.push(\n\t\t\t...findConditionalSchemaLocations(\n\t\t\t\tschema.additionalProperties,\n\t\t\t\t`${path}/additionalProperties`,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t}\n\n\t// ── Recurse into items ───────────────────────────────────────────────\n\tif (schema.items) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let i = 0; i < schema.items.length; i++) {\n\t\t\t\tconst item = schema.items[i];\n\t\t\t\tif (item && typeof item !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t`${path}/items/${i}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof schema.items !== \"boolean\") {\n\t\t\tlocations.push(\n\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\tschema.items,\n\t\t\t\t\t`${path}/items`,\n\t\t\t\t\tvisited,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Recurse into combinators ─────────────────────────────────────────\n\tfor (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n\t\tconst branches = schema[keyword];\n\t\tif (branches) {\n\t\t\tfor (let i = 0; i < branches.length; i++) {\n\t\t\t\tconst branch = branches[i];\n\t\t\t\tif (branch && typeof branch !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\tbranch,\n\t\t\t\t\t\t\t`${path}/${keyword}/${i}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into not ─────────────────────────────────────────────────\n\tif (schema.not && typeof schema.not !== \"boolean\") {\n\t\tlocations.push(\n\t\t\t...findConditionalSchemaLocations(schema.not, `${path}/not`, visited),\n\t\t);\n\t}\n\n\t// ── Recurse into definitions / $defs ─────────────────────────────────\n\tfor (const defsKey of [\"definitions\", \"$defs\"] as const) {\n\t\tconst defs = schema[defsKey];\n\t\tif (defs) {\n\t\t\tfor (const [name, def] of Object.entries(defs)) {\n\t\t\t\tif (def && typeof def !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\tdef,\n\t\t\t\t\t\t\t`${path}/${defsKey}/${name}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn locations;\n}\n\n/**\n * Recursively validates that a JSON Schema does not contain `if/then/else`\n * conditional keywords. Throws an `UnsupportedSchemaError` if any are found.\n *\n * @deprecated Use `findConditionalSchemaLocations` for diagnostic-based reporting.\n * This function is preserved for backward compatibility.\n *\n * @param schema - The JSON Schema to validate\n * @param path - The current JSON pointer path (for error reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n *\n * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found\n *\n * @example\n * ```\n * // Throws UnsupportedSchemaError:\n * assertNoConditionalSchema({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // OK — no conditional keywords:\n * assertNoConditionalSchema({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function assertNoConditionalSchema(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): void {\n\tconst locations = findConditionalSchemaLocations(schema, path, visited);\n\tif (locations.length > 0) {\n\t\t// biome-ignore lint: length check guarantees defined\n\t\tconst first = locations[0]!;\n\t\tthrow new UnsupportedSchemaError(first.keyword, first.schemaPath);\n\t}\n}\n\n// ─── $ref Resolution ─────────────────────────────────────────────────────────\n// Only supports internal references in the format `#/definitions/Foo`\n// or `#/$defs/Foo` (JSON Schema Draft 2019+). Remote $refs (URLs) are\n// not supported — that is outside the scope of a template engine.\n\n/**\n * Recursively resolves `$ref` in a schema using the root schema as the\n * source of definitions.\n */\nexport function resolveRef(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 {\n\tif (!schema.$ref) return schema;\n\n\tconst ref = schema.$ref;\n\n\t// Expected format: #/definitions/Name or #/$defs/Name\n\tconst match = ref.match(/^#\\/(definitions|\\$defs)\\/(.+)$/);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Unsupported $ref format: \"${ref}\". Only internal #/definitions/ references are supported.`,\n\t\t);\n\t}\n\n\tconst defsKey = match[1] as \"definitions\" | \"$defs\";\n\tconst name = match[2] ?? \"\";\n\n\tconst defs = defsKey === \"definitions\" ? root.definitions : root.$defs;\n\n\tif (!defs || !(name in defs)) {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\n\t// Recursive resolution in case the definition itself contains a $ref\n\tconst def = defs[name];\n\tif (!def || typeof def === \"boolean\") {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\treturn resolveRef(def, root);\n}\n\n// ─── Single-Segment Path Navigation ─────────────────────────────────────────\n\n/**\n * Resolves a single path segment (a property name) within a schema.\n * Returns the corresponding sub-schema, or `undefined` if the path is invalid.\n *\n * @param schema - The current schema (already resolved, no $ref)\n * @param segment - The property name to resolve\n * @param root - The root schema (for resolving any internal $refs)\n */\nfunction resolveSegment(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// 1. Explicit properties\n\tif (resolved.properties && segment in resolved.properties) {\n\t\tconst prop = resolved.properties[segment];\n\t\tif (prop && typeof prop !== \"boolean\") return resolveRef(prop, root);\n\t\tif (prop === true) return {};\n\t}\n\n\t// 2. additionalProperties (when the property is not declared)\n\tif (\n\t\tresolved.additionalProperties !== undefined &&\n\t\tresolved.additionalProperties !== false\n\t) {\n\t\tif (resolved.additionalProperties === true) {\n\t\t\t// additionalProperties: true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\treturn resolveRef(resolved.additionalProperties, root);\n\t}\n\n\t// 3. Intrinsic array properties (e.g. `.length`)\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (isArray && segment === \"length\") {\n\t\treturn { type: \"integer\" };\n\t}\n\n\t// 3b. Numeric index access on arrays (e.g. `users.[0]` → items schema)\n\tif (isArray && /^\\d+$/.test(segment)) {\n\t\tif (resolved.items === undefined) {\n\t\t\t// array without items → element type is unknown\n\t\t\treturn {};\n\t\t}\n\t\tif (typeof resolved.items === \"boolean\") {\n\t\t\treturn {};\n\t\t}\n\t\t// Tuple: items is an array of schemas — resolve by index if possible\n\t\tif (Array.isArray(resolved.items)) {\n\t\t\tconst idx = Number.parseInt(segment, 10);\n\t\t\tconst item = resolved.items[idx];\n\t\t\tif (item !== undefined && typeof item !== \"boolean\") {\n\t\t\t\treturn resolveRef(item, root);\n\t\t\t}\n\t\t\tif (item !== undefined && typeof item === \"boolean\") {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t\t// Index out of bounds for tuple → check additionalItems (Draft 7)\n\t\t\t// additionalItems: false → no additional elements allowed\n\t\t\tif (resolved.additionalItems === false) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// additionalItems: schema → additional elements have this type\n\t\t\tif (\n\t\t\t\tresolved.additionalItems !== undefined &&\n\t\t\t\tresolved.additionalItems !== true &&\n\t\t\t\ttypeof resolved.additionalItems === \"object\"\n\t\t\t) {\n\t\t\t\treturn resolveRef(resolved.additionalItems, root);\n\t\t\t}\n\t\t\t// additionalItems absent or true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\t// Single items schema — all elements share the same type\n\t\treturn resolveRef(resolved.items, root);\n\t}\n\n\t// 4. Combinators — search within each branch\n\tconst combinatorResult = resolveInCombinators(resolved, segment, root);\n\tif (combinatorResult) return combinatorResult;\n\n\treturn undefined;\n}\n\n/**\n * Searches for a segment within `allOf`, `anyOf`, `oneOf` branches.\n * Returns the first matching sub-schema, or `undefined`.\n * For `allOf`, found results are merged into a single `allOf`.\n */\nfunction resolveInCombinators(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\t// allOf: the property can be defined in any branch, and all constraints\n\t// apply simultaneously.\n\tif (schema.allOf) {\n\t\tconst matches = schema.allOf\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { allOf: matches };\n\t}\n\n\t// anyOf / oneOf: the property can come from any branch.\n\tfor (const key of [\"anyOf\", \"oneOf\"] as const) {\n\t\tif (!schema[key]) continue;\n\t\tconst matches = schema[key]\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { [key]: matches };\n\t}\n\n\treturn undefined;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Resolves a full path (e.g. [\"user\", \"address\", \"city\"]) within a JSON\n * Schema and returns the corresponding sub-schema.\n *\n * @param schema - The root schema describing the template context\n * @param path - Array of segments (property names)\n * @returns The sub-schema at the end of the path, or `undefined` if the path\n * cannot be resolved.\n *\n * @example\n * ```\n * const schema = {\n * type: \"object\",\n * properties: {\n * user: {\n * type: \"object\",\n * properties: {\n * name: { type: \"string\" }\n * }\n * }\n * }\n * };\n * resolveSchemaPath(schema, [\"user\", \"name\"]);\n * // → { type: \"string\" }\n * ```\n */\nexport function resolveSchemaPath(\n\tschema: JSONSchema7,\n\tpath: string[],\n): JSONSchema7 | undefined {\n\tif (path.length === 0) return resolveRef(schema, schema);\n\n\tlet current: JSONSchema7 = resolveRef(schema, schema);\n\tconst root = schema;\n\n\tfor (const segment of path) {\n\t\tconst next = resolveSegment(current, segment, root);\n\t\tif (next === undefined) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the item schema of an array.\n * If the schema is not of type `array` or has no `items`, returns `undefined`.\n *\n * @param schema - The array schema\n * @param root - The root schema (for resolving $refs)\n */\nexport function resolveArrayItems(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// Verify that it's actually an array\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (!isArray && resolved.items === undefined) {\n\t\treturn undefined;\n\t}\n\n\tif (resolved.items === undefined) {\n\t\t// array without items → element type is unknown\n\t\treturn {};\n\t}\n\n\t// items can be a boolean (true = anything, false = nothing)\n\tif (typeof resolved.items === \"boolean\") {\n\t\treturn {};\n\t}\n\n\t// items can be a single schema or a tuple (array of schemas).\n\t// For template loops, we handle the single-schema case.\n\tif (Array.isArray(resolved.items)) {\n\t\t// Tuple: create a oneOf of all possible types\n\t\tconst schemas = resolved.items\n\t\t\t.filter((item): item is JSONSchema7 => typeof item !== \"boolean\")\n\t\t\t.map((item) => resolveRef(item, root));\n\t\tif (schemas.length === 0) return {};\n\t\treturn { oneOf: schemas };\n\t}\n\n\treturn resolveRef(resolved.items, root);\n}\n\n/**\n * Simplifies an output schema to avoid unnecessarily complex constructs\n * (e.g. `oneOf` with a single element, duplicates, etc.).\n *\n * Uses `deepEqual` for deduplication — more robust and performant than\n * `JSON.stringify` (independent of key order, no intermediate string\n * allocations).\n */\nexport function simplifySchema(schema: JSONSchema7): JSONSchema7 {\n\t// oneOf / anyOf with a single element → unwrap\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length === 1) {\n\t\t\tconst first = arr[0];\n\t\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\t\treturn simplifySchema(first);\n\t\t}\n\t}\n\n\t// allOf with a single element → unwrap\n\tif (schema.allOf && schema.allOf.length === 1) {\n\t\tconst first = schema.allOf[0];\n\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\treturn simplifySchema(first);\n\t}\n\n\t// Deduplicate identical entries in oneOf/anyOf\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length > 1) {\n\t\t\tconst unique: JSONSchema7[] = [];\n\t\t\tfor (const entry of arr) {\n\t\t\t\tif (typeof entry === \"boolean\") continue;\n\t\t\t\t// Use deepEqual instead of JSON.stringify for structural\n\t\t\t\t// comparison — more robust (key order independent) and\n\t\t\t\t// more performant (no string allocations).\n\t\t\t\tconst isDuplicate = unique.some((existing) =>\n\t\t\t\t\tdeepEqual(existing, entry),\n\t\t\t\t);\n\t\t\t\tif (!isDuplicate) {\n\t\t\t\t\tunique.push(simplifySchema(entry));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unique.length === 1) return unique[0] as JSONSchema7;\n\t\t\treturn { ...schema, [key]: unique };\n\t\t}\n\t}\n\n\treturn schema;\n}\n"],"names":["assertNoConditionalSchema","findConditionalSchemaLocations","resolveArrayItems","resolveRef","resolveSchemaPath","simplifySchema","schema","path","visited","Set","locations","has","add","kw","undefined","push","keyword","schemaPath","properties","key","prop","Object","entries","additionalProperties","items","Array","isArray","i","length","item","branches","branch","not","defsKey","defs","name","def","first","UnsupportedSchemaError","root","$ref","ref","match","Error","definitions","$defs","resolveSegment","segment","resolved","schemaType","type","includes","test","idx","Number","parseInt","additionalItems","combinatorResult","resolveInCombinators","allOf","matches","filter","b","map","s","current","next","schemas","oneOf","arr","unique","entry","isDuplicate","some","existing","deepEqual"],"mappings":"mPAsNgBA,mCAAAA,+BAxJAC,wCAAAA,oCAyYAC,2BAAAA,uBA3NAC,oBAAAA,gBAkMAC,2BAAAA,uBAyEAC,wBAAAA,0CAtfuB,sCACb,cA4DnB,SAASJ,+BACfK,MAAmB,CACnBC,KAAO,EAAE,CACTC,QAAuB,IAAIC,GAAK,EAEhC,MAAMC,UAA4D,EAAE,CAGpE,GAAIF,QAAQG,GAAG,CAACL,QAAS,OAAOI,UAChCF,QAAQI,GAAG,CAACN,QAKZ,IAAK,MAAMO,KAAM,CAAC,KAAM,OAAQ,OAAO,CAAW,CACjD,GAAIP,MAAM,CAACO,GAAG,GAAKC,UAAW,CAC7BJ,UAAUK,IAAI,CAAC,CAAEC,QAAS,eAAgBC,WAAYV,MAAQ,GAAI,GAClE,KACD,CACD,CAGA,GAAID,OAAOY,UAAU,CAAE,CACtB,IAAK,KAAM,CAACC,IAAKC,KAAK,GAAIC,OAAOC,OAAO,CAAChB,OAAOY,UAAU,EAAG,CAC5D,GAAIE,MAAQ,OAAOA,OAAS,UAAW,CACtCV,UAAUK,IAAI,IACVd,+BACFmB,KACA,CAAC,EAAEb,KAAK,YAAY,EAAEY,IAAI,CAAC,CAC3BX,SAGH,CACD,CACD,CAGA,GACCF,OAAOiB,oBAAoB,EAC3B,OAAOjB,OAAOiB,oBAAoB,GAAK,SACtC,CACDb,UAAUK,IAAI,IACVd,+BACFK,OAAOiB,oBAAoB,CAC3B,CAAC,EAAEhB,KAAK,qBAAqB,CAAC,CAC9BC,SAGH,CAGA,GAAIF,OAAOkB,KAAK,CAAE,CACjB,GAAIC,MAAMC,OAAO,CAACpB,OAAOkB,KAAK,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B,GAAIhC,QAAUvB,WAAa,OAAOuB,QAAU,UAC3C,OAAOhC,eAAegC,MACxB,CACD,CAGA,GAAI/B,OAAOqD,KAAK,EAAIrD,OAAOqD,KAAK,CAAC/B,MAAM,GAAK,EAAG,CAC9C,MAAMS,MAAQ/B,OAAOqD,KAAK,CAAC,EAAE,CAC7B,GAAItB,QAAUvB,WAAa,OAAOuB,QAAU,UAC3C,OAAOhC,eAAegC,MACxB,CAGA,IAAK,MAAMlB,MAAO,CAAC,QAAS,QAAQ,CAAW,CAC9C,MAAMkD,IAAM/D,MAAM,CAACa,IAAI,CACvB,GAAIkD,KAAOA,IAAIzC,MAAM,CAAG,EAAG,CAC1B,MAAM0C,OAAwB,EAAE,CAChC,IAAK,MAAMC,SAASF,IAAK,CACxB,GAAI,OAAOE,QAAU,UAAW,SAIhC,MAAMC,YAAcF,OAAOG,IAAI,CAAC,AAACC,UAChCC,GAAAA,kBAAS,EAACD,SAAUH,QAErB,GAAI,CAACC,YAAa,CACjBF,OAAOvD,IAAI,CAACV,eAAekE,OAC5B,CACD,CACA,GAAID,OAAO1C,MAAM,GAAK,EAAG,OAAO0C,MAAM,CAAC,EAAE,CACzC,MAAO,CAAE,GAAGhE,MAAM,CAAE,CAACa,IAAI,CAAEmD,MAAO,CACnC,CACD,CAEA,OAAOhE,MACR"}
1
+ {"version":3,"sources":["../../src/schema-resolver.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { UnsupportedSchemaError } from \"./errors.ts\";\nimport { deepEqual } from \"./utils.ts\";\n\n// ─── JSON Schema Resolver ────────────────────────────────────────────────────\n// Utility for navigating a JSON Schema Draft v7 by following a property path\n// (e.g. [\"user\", \"address\", \"city\"]).\n//\n// Handles:\n// - `$ref` resolution (internal references #/definitions/...)\n// - Navigation through `properties`\n// - Navigation through `items` (array elements)\n// - Combinators `allOf`, `anyOf`, `oneOf` (searches each branch)\n// - `additionalProperties` when the property is not explicitly declared\n//\n// Rejects:\n// - Conditional schemas (`if/then/else`) — non-resolvable without runtime data\n\n// ─── Conditional Schema Detection ────────────────────────────────────────────\n// JSON Schema Draft v7 introduced `if/then/else` conditional schemas.\n// These are fundamentally non-resolvable during static analysis because\n// they depend on runtime data values. Rather than silently ignoring them\n// (which would produce incorrect results — missing properties, wrong types),\n// we fail fast with a clear error pointing to the exact location in the schema.\n\n/**\n * Recursively scans a JSON Schema tree for `if/then/else` conditional keywords\n * and returns their locations as an array of `{ keyword, schemaPath }` objects.\n *\n * This is the non-throwing counterpart of `assertNoConditionalSchema`.\n * It traverses the entire schema tree, including:\n * - `properties` values\n * - `additionalProperties` (when it's a schema)\n * - `items` (single schema or tuple)\n * - `allOf`, `anyOf`, `oneOf` branches\n * - `not`\n * - `definitions` / `$defs` values\n *\n * A `Set<object>` is used to track visited schemas and prevent infinite loops\n * from circular structures.\n *\n * @param schema - The JSON Schema to scan\n * @param path - The current JSON pointer path (for location reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n * @returns Array of locations where `if/then/else` keywords were found\n *\n * @example\n * ```\n * // Returns [{ keyword: \"if/then/else\", schemaPath: \"/\" }]:\n * findConditionalSchemaLocations({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // Returns []:\n * findConditionalSchemaLocations({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function findConditionalSchemaLocations(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): Array<{ keyword: string; schemaPath: string }> {\n\tconst locations: Array<{ keyword: string; schemaPath: string }> = [];\n\n\t// Cycle protection — avoid infinite loops on circular schema structures\n\tif (visited.has(schema)) return locations;\n\tvisited.add(schema);\n\n\t// ── Detect if/then/else at the current level ─────────────────────────\n\t// One diagnostic per schema node is enough — no need to report `then`\n\t// and `else` separately if `if` is already present.\n\tfor (const kw of [\"if\", \"then\", \"else\"] as const) {\n\t\tif (schema[kw] !== undefined) {\n\t\t\tlocations.push({ keyword: \"if/then/else\", schemaPath: path || \"/\" });\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// ── Recurse into properties ──────────────────────────────────────────\n\tif (schema.properties) {\n\t\tfor (const [key, prop] of Object.entries(schema.properties)) {\n\t\t\tif (prop && typeof prop !== \"boolean\") {\n\t\t\t\tlocations.push(\n\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\tprop,\n\t\t\t\t\t\t`${path}/properties/${key}`,\n\t\t\t\t\t\tvisited,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into additionalProperties ────────────────────────────────\n\tif (\n\t\tschema.additionalProperties &&\n\t\ttypeof schema.additionalProperties === \"object\"\n\t) {\n\t\tlocations.push(\n\t\t\t...findConditionalSchemaLocations(\n\t\t\t\tschema.additionalProperties,\n\t\t\t\t`${path}/additionalProperties`,\n\t\t\t\tvisited,\n\t\t\t),\n\t\t);\n\t}\n\n\t// ── Recurse into items ───────────────────────────────────────────────\n\tif (schema.items) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let i = 0; i < schema.items.length; i++) {\n\t\t\t\tconst item = schema.items[i];\n\t\t\t\tif (item && typeof item !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t\t`${path}/items/${i}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof schema.items !== \"boolean\") {\n\t\t\tlocations.push(\n\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\tschema.items,\n\t\t\t\t\t`${path}/items`,\n\t\t\t\t\tvisited,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Recurse into combinators ─────────────────────────────────────────\n\tfor (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n\t\tconst branches = schema[keyword];\n\t\tif (branches) {\n\t\t\tfor (let i = 0; i < branches.length; i++) {\n\t\t\t\tconst branch = branches[i];\n\t\t\t\tif (branch && typeof branch !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\tbranch,\n\t\t\t\t\t\t\t`${path}/${keyword}/${i}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into not ─────────────────────────────────────────────────\n\tif (schema.not && typeof schema.not !== \"boolean\") {\n\t\tlocations.push(\n\t\t\t...findConditionalSchemaLocations(schema.not, `${path}/not`, visited),\n\t\t);\n\t}\n\n\t// ── Recurse into definitions / $defs ─────────────────────────────────\n\tfor (const defsKey of [\"definitions\", \"$defs\"] as const) {\n\t\tconst defs = schema[defsKey];\n\t\tif (defs) {\n\t\t\tfor (const [name, def] of Object.entries(defs)) {\n\t\t\t\tif (def && typeof def !== \"boolean\") {\n\t\t\t\t\tlocations.push(\n\t\t\t\t\t\t...findConditionalSchemaLocations(\n\t\t\t\t\t\t\tdef,\n\t\t\t\t\t\t\t`${path}/${defsKey}/${name}`,\n\t\t\t\t\t\t\tvisited,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn locations;\n}\n\n/**\n * Recursively validates that a JSON Schema does not contain `if/then/else`\n * conditional keywords. Throws an `UnsupportedSchemaError` if any are found.\n *\n * @deprecated Use `findConditionalSchemaLocations` for diagnostic-based reporting.\n * This function is preserved for backward compatibility.\n *\n * @param schema - The JSON Schema to validate\n * @param path - The current JSON pointer path (for error reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n *\n * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found\n *\n * @example\n * ```\n * // Throws UnsupportedSchemaError:\n * assertNoConditionalSchema({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // OK — no conditional keywords:\n * assertNoConditionalSchema({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function assertNoConditionalSchema(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): void {\n\tconst locations = findConditionalSchemaLocations(schema, path, visited);\n\tif (locations.length > 0) {\n\t\t// biome-ignore lint: length check guarantees defined\n\t\tconst first = locations[0]!;\n\t\tthrow new UnsupportedSchemaError(first.keyword, first.schemaPath);\n\t}\n}\n\n// ─── $ref Resolution ─────────────────────────────────────────────────────────\n// Only supports internal references in the format `#/definitions/Foo`\n// or `#/$defs/Foo` (JSON Schema Draft 2019+). Remote $refs (URLs) are\n// not supported — that is outside the scope of a template engine.\n\n/**\n * Recursively resolves `$ref` in a schema using the root schema as the\n * source of definitions.\n */\nexport function resolveRef(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 {\n\tif (!schema.$ref) return schema;\n\n\tconst ref = schema.$ref;\n\n\t// Expected format: #/definitions/Name or #/$defs/Name\n\tconst match = ref.match(/^#\\/(definitions|\\$defs)\\/(.+)$/);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Unsupported $ref format: \"${ref}\". Only internal #/definitions/ references are supported.`,\n\t\t);\n\t}\n\n\tconst defsKey = match[1] as \"definitions\" | \"$defs\";\n\tconst name = match[2] ?? \"\";\n\n\tconst defs = defsKey === \"definitions\" ? root.definitions : root.$defs;\n\n\tif (!defs || !(name in defs)) {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\n\t// Recursive resolution in case the definition itself contains a $ref\n\tconst def = defs[name];\n\tif (!def || typeof def === \"boolean\") {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\treturn resolveRef(def, root);\n}\n\n// ─── Single-Segment Path Navigation ─────────────────────────────────────────\n\n/**\n * Resolves a single path segment (a property name) within a schema.\n * Returns the corresponding sub-schema, or `undefined` if the path is invalid.\n *\n * @param schema - The current schema (already resolved, no $ref)\n * @param segment - The property name to resolve\n * @param root - The root schema (for resolving any internal $refs)\n */\nfunction resolveSegment(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// 1. Explicit properties\n\tif (resolved.properties && segment in resolved.properties) {\n\t\tconst prop = resolved.properties[segment];\n\t\tif (prop && typeof prop !== \"boolean\") return resolveRef(prop, root);\n\t\tif (prop === true) return {};\n\t}\n\n\t// 2. additionalProperties (when the property is not declared)\n\tif (\n\t\tresolved.additionalProperties !== undefined &&\n\t\tresolved.additionalProperties !== false\n\t) {\n\t\tif (resolved.additionalProperties === true) {\n\t\t\t// additionalProperties: true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\treturn resolveRef(resolved.additionalProperties, root);\n\t}\n\n\t// 3. Intrinsic array properties (e.g. `.length`)\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (isArray && segment === \"length\") {\n\t\treturn { type: \"integer\" };\n\t}\n\n\t// 3b. Numeric index access on arrays (e.g. `users.[0]` → items schema)\n\tif (isArray && /^\\d+$/.test(segment)) {\n\t\tif (resolved.items === undefined) {\n\t\t\t// array without items → element type is unknown\n\t\t\treturn {};\n\t\t}\n\t\tif (typeof resolved.items === \"boolean\") {\n\t\t\treturn {};\n\t\t}\n\t\t// Tuple: items is an array of schemas — resolve by index if possible\n\t\tif (Array.isArray(resolved.items)) {\n\t\t\tconst idx = Number.parseInt(segment, 10);\n\t\t\tconst item = resolved.items[idx];\n\t\t\tif (item !== undefined && typeof item !== \"boolean\") {\n\t\t\t\treturn resolveRef(item, root);\n\t\t\t}\n\t\t\tif (item !== undefined && typeof item === \"boolean\") {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t\t// Index out of bounds for tuple → check additionalItems (Draft 7)\n\t\t\t// additionalItems: false → no additional elements allowed\n\t\t\tif (resolved.additionalItems === false) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// additionalItems: schema → additional elements have this type\n\t\t\tif (\n\t\t\t\tresolved.additionalItems !== undefined &&\n\t\t\t\tresolved.additionalItems !== true &&\n\t\t\t\ttypeof resolved.additionalItems === \"object\"\n\t\t\t) {\n\t\t\t\treturn resolveRef(resolved.additionalItems, root);\n\t\t\t}\n\t\t\t// additionalItems absent or true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\t// Single items schema — all elements share the same type\n\t\treturn resolveRef(resolved.items, root);\n\t}\n\n\t// 4. Combinators — search within each branch\n\tconst combinatorResult = resolveInCombinators(resolved, segment, root);\n\tif (combinatorResult) return combinatorResult;\n\n\treturn undefined;\n}\n\n/**\n * Searches for a segment within `allOf`, `anyOf`, `oneOf` branches.\n * Returns the first matching sub-schema, or `undefined`.\n * For `allOf`, found results are merged into a single `allOf`.\n */\nfunction resolveInCombinators(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\t// allOf: the property can be defined in any branch, and all constraints\n\t// apply simultaneously.\n\tif (schema.allOf) {\n\t\tconst matches = schema.allOf\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { allOf: matches };\n\t}\n\n\t// anyOf / oneOf: the property can come from any branch.\n\tfor (const key of [\"anyOf\", \"oneOf\"] as const) {\n\t\tif (!schema[key]) continue;\n\t\tconst matches = schema[key]\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { [key]: matches };\n\t}\n\n\treturn undefined;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Resolves a full path (e.g. [\"user\", \"address\", \"city\"]) within a JSON\n * Schema and returns the corresponding sub-schema.\n *\n * @param schema - The root schema describing the template context\n * @param path - Array of segments (property names)\n * @returns The sub-schema at the end of the path, or `undefined` if the path\n * cannot be resolved.\n *\n * @example\n * ```\n * const schema = {\n * type: \"object\",\n * properties: {\n * user: {\n * type: \"object\",\n * properties: {\n * name: { type: \"string\" }\n * }\n * }\n * }\n * };\n * resolveSchemaPath(schema, [\"user\", \"name\"]);\n * // → { type: \"string\" }\n * ```\n */\nexport function resolveSchemaPath(\n\tschema: JSONSchema7,\n\tpath: string[],\n): JSONSchema7 | undefined {\n\tif (path.length === 0) return resolveRef(schema, schema);\n\n\tlet current: JSONSchema7 = resolveRef(schema, schema);\n\tconst root = schema;\n\n\tfor (const segment of path) {\n\t\tconst next = resolveSegment(current, segment, root);\n\t\tif (next === undefined) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the item schema of an array.\n * If the schema is not of type `array` or has no `items`, returns `undefined`.\n *\n * @param schema - The array schema\n * @param root - The root schema (for resolving $refs)\n */\nexport function resolveArrayItems(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// Verify that it's actually an array\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (!isArray && resolved.items === undefined) {\n\t\treturn undefined;\n\t}\n\n\tif (resolved.items === undefined) {\n\t\t// array without items → element type is unknown\n\t\treturn {};\n\t}\n\n\t// items can be a boolean (true = anything, false = nothing)\n\tif (typeof resolved.items === \"boolean\") {\n\t\treturn {};\n\t}\n\n\t// items can be a single schema or a tuple (array of schemas).\n\t// For template loops, we handle the single-schema case.\n\tif (Array.isArray(resolved.items)) {\n\t\t// Tuple: create a oneOf of all possible types\n\t\tconst schemas = resolved.items\n\t\t\t.filter((item): item is JSONSchema7 => typeof item !== \"boolean\")\n\t\t\t.map((item) => resolveRef(item, root));\n\t\tif (schemas.length === 0) return {};\n\t\treturn { oneOf: schemas };\n\t}\n\n\treturn resolveRef(resolved.items, root);\n}\n\n/**\n * Simplifies an output schema to avoid unnecessarily complex constructs\n * (e.g. `oneOf` with a single element, duplicates, etc.).\n *\n * Uses `deepEqual` for deduplication — more robust and performant than\n * `JSON.stringify` (independent of key order, no intermediate string\n * allocations).\n */\nexport function simplifySchema(schema: JSONSchema7): JSONSchema7 {\n\t// ── Phase 1 : Unwrap single-branch combinators ──────────────────────\n\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length === 1) {\n\t\t\tconst first = arr[0];\n\t\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\t\treturn simplifySchema(first);\n\t\t}\n\t}\n\n\tif (schema.allOf && schema.allOf.length === 1) {\n\t\tconst first = schema.allOf[0];\n\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\treturn simplifySchema(first);\n\t}\n\n\t// ── Phase 2 : Deduplicate multi-branch oneOf/anyOf ──────────────────\n\n\tlet result: JSONSchema7 = schema;\n\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = result[key];\n\t\tif (arr && arr.length > 1) {\n\t\t\tconst unique: JSONSchema7[] = [];\n\t\t\tfor (const entry of arr) {\n\t\t\t\tif (typeof entry === \"boolean\") continue;\n\t\t\t\t// Use deepEqual instead of JSON.stringify for structural\n\t\t\t\t// comparison — more robust (key order independent) and\n\t\t\t\t// more performant (no string allocations).\n\t\t\t\tconst simplified = simplifySchema(entry);\n\t\t\t\tconst isDuplicate = unique.some((existing) =>\n\t\t\t\t\tdeepEqual(existing, simplified),\n\t\t\t\t);\n\t\t\t\tif (!isDuplicate) {\n\t\t\t\t\tunique.push(simplified);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unique.length === 1) return unique[0] as JSONSchema7;\n\t\t\tresult = { ...result, [key]: unique };\n\t\t}\n\t}\n\n\t// ── Phase 3 : Recurse into allOf branches (multi-branch) ────────────\n\n\tif (result.allOf && result.allOf.length > 1) {\n\t\tconst simplifiedBranches = result.allOf.map((branch) => {\n\t\t\tif (typeof branch === \"boolean\" || branch === undefined) return branch;\n\t\t\treturn simplifySchema(branch);\n\t\t});\n\t\tresult = { ...result, allOf: simplifiedBranches };\n\t}\n\n\t// ── Phase 4 : Recurse into properties ───────────────────────────────\n\n\tif (result.properties) {\n\t\tconst simplifiedProps: Record<string, JSONSchema7> = {};\n\t\tlet changed = false;\n\t\tfor (const [key, prop] of Object.entries(result.properties)) {\n\t\t\tif (prop && typeof prop !== \"boolean\") {\n\t\t\t\tconst simplified = simplifySchema(prop);\n\t\t\t\tsimplifiedProps[key] = simplified;\n\t\t\t\tif (simplified !== prop) changed = true;\n\t\t\t} else {\n\t\t\t\tsimplifiedProps[key] = prop as unknown as JSONSchema7;\n\t\t\t}\n\t\t}\n\t\tif (changed) {\n\t\t\tresult = { ...result, properties: simplifiedProps };\n\t\t}\n\t}\n\n\t// ── Phase 5 : Recurse into items ────────────────────────────────────\n\n\tif (result.items) {\n\t\tif (Array.isArray(result.items)) {\n\t\t\t// Tuple items\n\t\t\tlet itemsChanged = false;\n\t\t\tconst simplifiedItems = result.items.map((item) => {\n\t\t\t\tif (item && typeof item !== \"boolean\") {\n\t\t\t\t\tconst simplified = simplifySchema(item);\n\t\t\t\t\tif (simplified !== item) itemsChanged = true;\n\t\t\t\t\treturn simplified;\n\t\t\t\t}\n\t\t\t\treturn item;\n\t\t\t});\n\t\t\tif (itemsChanged) {\n\t\t\t\tresult = { ...result, items: simplifiedItems };\n\t\t\t}\n\t\t} else if (typeof result.items !== \"boolean\") {\n\t\t\t// Single items schema\n\t\t\tconst simplified = simplifySchema(result.items);\n\t\t\tif (simplified !== result.items) {\n\t\t\t\tresult = { ...result, items: simplified };\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Phase 6 : Recurse into additionalProperties ─────────────────────\n\n\tif (\n\t\tresult.additionalProperties &&\n\t\ttypeof result.additionalProperties === \"object\"\n\t) {\n\t\tconst simplified = simplifySchema(result.additionalProperties);\n\t\tif (simplified !== result.additionalProperties) {\n\t\t\tresult = { ...result, additionalProperties: simplified };\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"names":["assertNoConditionalSchema","findConditionalSchemaLocations","resolveArrayItems","resolveRef","resolveSchemaPath","simplifySchema","schema","path","visited","Set","locations","has","add","kw","undefined","push","keyword","schemaPath","properties","key","prop","Object","entries","additionalProperties","items","Array","isArray","i","length","item","branches","branch","not","defsKey","defs","name","def","first","UnsupportedSchemaError","root","$ref","ref","match","Error","definitions","$defs","resolveSegment","segment","resolved","schemaType","type","includes","test","idx","Number","parseInt","additionalItems","combinatorResult","resolveInCombinators","allOf","matches","filter","b","map","s","current","next","schemas","oneOf","arr","result","unique","entry","simplified","isDuplicate","some","existing","deepEqual","simplifiedBranches","simplifiedProps","changed","itemsChanged","simplifiedItems"],"mappings":"mPAsNgBA,mCAAAA,+BAxJAC,wCAAAA,oCAyYAC,2BAAAA,uBA3NAC,oBAAAA,gBAkMAC,2BAAAA,uBAyEAC,wBAAAA,0CAtfuB,sCACb,cA4DnB,SAASJ,+BACfK,MAAmB,CACnBC,KAAO,EAAE,CACTC,QAAuB,IAAIC,GAAK,EAEhC,MAAMC,UAA4D,EAAE,CAGpE,GAAIF,QAAQG,GAAG,CAACL,QAAS,OAAOI,UAChCF,QAAQI,GAAG,CAACN,QAKZ,IAAK,MAAMO,KAAM,CAAC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,OAAOA,OAAS,UAAW,CACtC,MAAM4C,WAAapE,eAAewB,MAClC,GAAI4C,aAAe5C,KAAMoD,aAAe,KACxC,OAAOR,UACR,CACA,OAAO5C,IACR,GACA,GAAIoD,aAAc,CACjBX,OAAS,CAAE,GAAGA,MAAM,CAAE9C,MAAO0D,eAAgB,CAC9C,CACD,MAAO,GAAI,OAAOZ,OAAO9C,KAAK,GAAK,UAAW,CAE7C,MAAMiD,WAAapE,eAAeiE,OAAO9C,KAAK,EAC9C,GAAIiD,aAAeH,OAAO9C,KAAK,CAAE,CAChC8C,OAAS,CAAE,GAAGA,MAAM,CAAE9C,MAAOiD,UAAW,CACzC,CACD,CACD,CAIA,GACCH,OAAO/C,oBAAoB,EAC3B,OAAO+C,OAAO/C,oBAAoB,GAAK,SACtC,CACD,MAAMkD,WAAapE,eAAeiE,OAAO/C,oBAAoB,EAC7D,GAAIkD,aAAeH,OAAO/C,oBAAoB,CAAE,CAC/C+C,OAAS,CAAE,GAAGA,MAAM,CAAE/C,qBAAsBkD,UAAW,CACxD,CACD,CAEA,OAAOH,MACR"}
@@ -104,7 +104,9 @@ export type DiagnosticCode =
104
104
  /** The $root token is used with path traversal (e.g. $root.name) */
105
105
  | "ROOT_PATH_TRAVERSAL"
106
106
  /** Unsupported JSON Schema feature (e.g. if/then/else conditional schemas) */
107
- | "UNSUPPORTED_SCHEMA";
107
+ | "UNSUPPORTED_SCHEMA"
108
+ /** The map helper implicitly flattens the input array one level before mapping */
109
+ | "MAP_IMPLICIT_FLATTEN";
108
110
  export interface DiagnosticDetails {
109
111
  /** Path of the expression that caused the error (e.g. `"user.name.foo"`) */
110
112
  path?: string;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport type { FromSchema, JSONSchema } from \"json-schema-to-ts\";\n\n// ─── Template Input ──────────────────────────────────────────────────────────\n// The engine accepts primitive values in addition to template strings.\n// When a non-string value is passed, it is treated as a literal passthrough:\n// analysis returns the inferred type, and execution returns the value as-is.\n\n/**\n * Object where each property is a `TemplateInput` (recursive).\n *\n * Allows passing an entire structure as a template:\n * ```\n * engine.analyze({\n * userName: \"{{name}}\",\n * userAge: \"{{age}}\",\n * nested: { x: \"{{foo}}\" },\n * }, inputSchema);\n * ```\n */\nexport interface TemplateInputObject {\n\t[key: string]: TemplateInput;\n}\n\n/**\n * Array where each element is a `TemplateInput` (recursive).\n *\n * Allows passing an array as a template:\n * ```\n * engine.analyze([\"{{name}}\", \"{{age}}\"], inputSchema);\n * engine.execute([\"{{name}}\", 42], data);\n * ```\n */\nexport type TemplateInputArray = TemplateInput[];\n\n/**\n * Input type accepted by the template engine.\n *\n * - `string` → standard Handlebars template (parsed and executed)\n * - `number` → numeric literal (passthrough)\n * - `boolean` → boolean literal (passthrough)\n * - `null` → null literal (passthrough)\n * - `TemplateInputArray` → array where each element is a `TemplateInput`\n * - `TemplateInputObject` → object where each property is a `TemplateInput`\n */\nexport type TemplateInput =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| TemplateInputArray\n\t| TemplateInputObject;\n\n// ─── Template Data ───────────────────────────────────────────────────────────\n// The data parameter accepted by `execute()` and `analyzeAndExecute()`.\n// In most cases this is a `Record<string, unknown>` (object context), but\n// primitives are also allowed — for example when using `{{$root}}` to\n// reference the entire data value directly.\n\n/**\n * Data type accepted by the template engine's execution methods.\n *\n * - `Record<string, unknown>` → standard object context (most common)\n * - `string` → primitive value (e.g. for `{{$root}}`)\n * - `number` → primitive value\n * - `boolean` → primitive value\n * - `null` → null value\n * - `unknown[]` → array value\n */\nexport type TemplateData =\n\t| Record<string, unknown>\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| unknown[];\n\n/**\n * Checks whether a value is a non-string primitive literal (number, boolean, null).\n * These values are treated as passthrough by the engine.\n *\n * Note: objects (`TemplateInputObject`) and arrays (`TemplateInputArray`) are NOT literals.\n */\nexport function isLiteralInput(\n\tinput: TemplateInput,\n): input is number | boolean | null {\n\treturn (\n\t\tinput === null || (typeof input !== \"string\" && typeof input !== \"object\")\n\t);\n}\n\n/**\n * Checks whether a value is a template array (`TemplateInputArray`).\n * Template arrays are processed recursively by the engine:\n * each element is analyzed/executed individually and the result is an array.\n */\nexport function isArrayInput(\n\tinput: TemplateInput,\n): input is TemplateInputArray {\n\treturn Array.isArray(input);\n}\n\n/**\n * Checks whether a value is a template object (`TemplateInputObject`).\n * Template objects are processed recursively by the engine:\n * each property is analyzed/executed individually.\n *\n * Note: arrays are excluded — use `isArrayInput()` first.\n */\nexport function isObjectInput(\n\tinput: TemplateInput,\n): input is TemplateInputObject {\n\treturn input !== null && typeof input === \"object\" && !Array.isArray(input);\n}\n\n/**\n * Infers the JSON Schema of a non-string primitive value.\n *\n * @param value - The primitive value (number, boolean, null)\n * @returns The corresponding JSON Schema\n *\n * @example\n * ```\n * inferPrimitiveSchema(42) // → { type: \"number\" }\n * inferPrimitiveSchema(true) // → { type: \"boolean\" }\n * inferPrimitiveSchema(null) // → { type: \"null\" }\n * ```\n */\nexport function inferPrimitiveSchema(\n\tvalue: number | boolean | null,\n): JSONSchema7 {\n\tif (value === null) return { type: \"null\" };\n\tif (typeof value === \"boolean\") return { type: \"boolean\" };\n\tif (typeof value === \"number\") {\n\t\treturn Number.isInteger(value) ? { type: \"integer\" } : { type: \"number\" };\n\t}\n\t// Exhaustiveness check — all branches are covered above.\n\t// If the type of `value` changes, TypeScript will raise an error here.\n\tvalue satisfies never;\n\treturn { type: \"null\" };\n}\n\n// ─── Diagnostic Codes ────────────────────────────────────────────────────────\n// Machine-readable codes for each error/warning type, enabling the frontend\n// to react programmatically without parsing the human-readable message.\n\nexport type DiagnosticCode =\n\t/** The referenced property does not exist in the context schema */\n\t| \"UNKNOWN_PROPERTY\"\n\t/** Type mismatch (e.g. #each on a non-array) */\n\t| \"TYPE_MISMATCH\"\n\t/** A block helper is used without a required argument */\n\t| \"MISSING_ARGUMENT\"\n\t/** Unknown block helper (neither built-in nor registered) */\n\t| \"UNKNOWN_HELPER\"\n\t/** The expression cannot be statically analyzed */\n\t| \"UNANALYZABLE\"\n\t/** The {{key:N}} syntax is used but no identifierSchemas were provided */\n\t| \"MISSING_IDENTIFIER_SCHEMAS\"\n\t/** The identifier N does not exist in the provided identifierSchemas */\n\t| \"UNKNOWN_IDENTIFIER\"\n\t/** The property does not exist in the identifier's schema */\n\t| \"IDENTIFIER_PROPERTY_NOT_FOUND\"\n\t/** Syntax error in the template */\n\t| \"PARSE_ERROR\"\n\t/** The $root token is used with path traversal (e.g. $root.name) */\n\t| \"ROOT_PATH_TRAVERSAL\"\n\t/** Unsupported JSON Schema feature (e.g. if/then/else conditional schemas) */\n\t| \"UNSUPPORTED_SCHEMA\";\n\n// ─── Diagnostic Details ──────────────────────────────────────────────────────\n// Supplementary information to understand the exact cause of the error.\n// Designed to be easily JSON-serializable and consumable by a frontend.\n\nexport interface DiagnosticDetails {\n\t/** Path of the expression that caused the error (e.g. `\"user.name.foo\"`) */\n\tpath?: string;\n\t/** Name of the helper involved (for helper-related errors) */\n\thelperName?: string;\n\t/** What was expected (e.g. `\"array\"`, `\"property to exist\"`) */\n\texpected?: string;\n\t/** What was found (e.g. `\"string\"`, `\"undefined\"`) */\n\tactual?: string;\n\t/** Available properties in the current schema (for suggestions) */\n\tavailableProperties?: string[];\n\t/** Template identifier number (for `{{key:N}}` errors) */\n\tidentifier?: number;\n}\n\n// ─── Static Analysis Result ──────────────────────────────────────────────────\n\n/** Diagnostic produced by the static analyzer */\nexport interface TemplateDiagnostic {\n\t/** \"error\" blocks execution, \"warning\" is informational */\n\tseverity: \"error\" | \"warning\";\n\n\t/** Machine-readable code identifying the error type */\n\tcode: DiagnosticCode;\n\n\t/** Human-readable message describing the problem */\n\tmessage: string;\n\n\t/** Position in the template source (if available from the AST) */\n\tloc?: {\n\t\tstart: { line: number; column: number };\n\t\tend: { line: number; column: number };\n\t};\n\n\t/** Fragment of the template source around the error */\n\tsource?: string;\n\n\t/** Structured information for debugging and frontend display */\n\tdetails?: DiagnosticDetails;\n}\n\n/** Complete result of the static analysis */\nexport interface AnalysisResult {\n\t/** true if no errors (warnings are tolerated) */\n\tvalid: boolean;\n\t/** List of diagnostics (errors + warnings) */\n\tdiagnostics: TemplateDiagnostic[];\n\t/** JSON Schema describing the template's return type */\n\toutputSchema: JSONSchema7;\n}\n\n/** Lightweight validation result (without output type inference) */\nexport interface ValidationResult {\n\t/** true if no errors (warnings are tolerated) */\n\tvalid: boolean;\n\t/** List of diagnostics (errors + warnings) */\n\tdiagnostics: TemplateDiagnostic[];\n}\n\n// ─── Public Engine Options ───────────────────────────────────────────────────\n\nexport interface TemplateEngineOptions {\n\t/**\n\t * Capacity of the parsed AST cache. Each parsed template is cached\n\t * to avoid costly re-parsing on repeated calls.\n\t * @default 256\n\t */\n\tastCacheSize?: number;\n\n\t/**\n\t * Capacity of the compiled Handlebars template cache.\n\t * @default 256\n\t */\n\tcompilationCacheSize?: number;\n\n\t/**\n\t * Custom helpers to register during engine construction.\n\t *\n\t * Each entry describes a helper with its name, implementation,\n\t * expected parameters, and return type.\n\t *\n\t * @example\n\t * ```\n\t * const engine = new Typebars({\n\t * helpers: [\n\t * {\n\t * name: \"uppercase\",\n\t * description: \"Converts a string to uppercase\",\n\t * fn: (value: string) => String(value).toUpperCase(),\n\t * params: [\n\t * { name: \"value\", type: { type: \"string\" }, description: \"The string to convert\" },\n\t * ],\n\t * returnType: { type: \"string\" },\n\t * },\n\t * ],\n\t * });\n\t * ```\n\t */\n\thelpers?: HelperConfig[];\n}\n\nexport interface CommonTypebarsOptions {\n\t/**\n\t * Explicit coercion schema for the output value.\n\t * When provided with a primitive type, the execution result will be\n\t * coerced to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/**\n\t * When `true`, properties whose values contain Handlebars expressions\n\t * (i.e. any `{{…}}` syntax) are excluded from the execution result.\n\t *\n\t * - **Object**: properties with template expressions are omitted from\n\t * the resulting object.\n\t * - **Array**: elements with template expressions are omitted from\n\t * the resulting array.\n\t * - **Root string** with expressions: returns `null` (there is no\n\t * parent to exclude from).\n\t * - **Literals** (number, boolean, null): unaffected.\n\t *\n\t * This mirrors the analysis-side `excludeTemplateExpression` option\n\t * but applied at runtime.\n\t *\n\t * @default false\n\t */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Execution Options ───────────────────────────────────────────────────────\n// Optional options object for `execute()`, replacing multiple positional\n// parameters for better ergonomics.\n\nexport interface ExecuteOptions extends CommonTypebarsOptions {\n\t/** JSON Schema for pre-execution static validation */\n\tschema?: JSONSchema7;\n\t/** Data by identifier `{ [id]: { key: value } }` */\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\t/** Schemas by identifier (for static validation with identifiers) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n}\n\n// ─── Combined Analyze-and-Execute Options ────────────────────────────────────\n// Optional options object for `analyzeAndExecute()`, grouping parameters\n// related to template identifiers.\n\nexport interface AnalyzeAndExecuteOptions extends CommonTypebarsOptions {\n\t/** Schemas by identifier `{ [id]: JSONSchema7 }` for static analysis */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Data by identifier `{ [id]: { key: value } }` for execution */\n\tidentifierData?: Record<number, Record<string, unknown>>;\n}\n\n// ─── Custom Helpers ──────────────────────────────────────────────────────────\n// Allows registering custom helpers with their type signature for static\n// analysis support.\n\n/** Describes a parameter expected by a helper */\nexport interface HelperParam {\n\t/** Parameter name (for documentation / introspection) */\n\tname: string;\n\n\t/**\n\t * JSON Schema describing the expected type for this parameter.\n\t * Used for documentation and static validation.\n\t */\n\ttype?: JSONSchema7;\n\n\t/** Human-readable description of the parameter */\n\tdescription?: string;\n\n\t/**\n\t * Whether the parameter is optional.\n\t * @default false\n\t */\n\toptional?: boolean;\n}\n\n/**\n * Definition of a helper registerable via `registerHelper()`.\n *\n * Contains the runtime implementation and typing metadata\n * for static analysis.\n */\nexport interface HelperDefinition {\n\t/**\n\t * Runtime implementation of the helper — will be registered with Handlebars.\n\t *\n\t * For an inline helper `{{uppercase name}}`:\n\t * `(value: string) => string`\n\t *\n\t * For a block helper `{{#repeat count}}...{{/repeat}}`:\n\t * `function(this: any, count: number, options: Handlebars.HelperOptions) { ... }`\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: Handlebars helper signatures are inherently dynamic\n\tfn: (...args: any[]) => unknown;\n\n\t/**\n\t * Parameters expected by the helper (for documentation and analysis).\n\t *\n\t * @example\n\t * ```\n\t * params: [\n\t * { name: \"value\", type: { type: \"number\" }, description: \"The value to round\" },\n\t * { name: \"precision\", type: { type: \"number\" }, description: \"Decimal places\", optional: true },\n\t * ]\n\t * ```\n\t */\n\tparams?: HelperParam[];\n\n\t/**\n\t * JSON Schema describing the helper's return type for static analysis.\n\t * @default { type: \"string\" }\n\t */\n\treturnType?: JSONSchema7;\n\n\t/** Human-readable description of the helper */\n\tdescription?: string;\n}\n\n/**\n * Full helper configuration for registration via the `Typebars({ helpers: [...] })`\n * constructor options.\n *\n * Extends `HelperDefinition` with a required `name`.\n *\n * @example\n * ```\n * const config: HelperConfig = {\n * name: \"round\",\n * description: \"Rounds a number to a given precision\",\n * fn: (value: number, precision?: number) => { ... },\n * params: [\n * { name: \"value\", type: { type: \"number\" } },\n * { name: \"precision\", type: { type: \"number\" }, optional: true },\n * ],\n * returnType: { type: \"number\" },\n * };\n * ```\n */\nexport interface HelperConfig extends HelperDefinition {\n\t/** Name of the helper as used in templates (e.g. `\"uppercase\"`) */\n\tname: string;\n}\n\n// ─── Automatic Type Inference via json-schema-to-ts ──────────────────────────\n// Allows `defineHelper()` to infer TypeScript types for `fn` arguments\n// from the JSON Schemas declared in `params`.\n\n/**\n * Param definition used for type inference.\n * Accepts `JSONSchema` from `json-schema-to-ts` to allow `FromSchema`\n * to resolve literal types.\n */\ntype TypedHelperParam = {\n\treadonly name: string;\n\treadonly type?: JSONSchema;\n\treadonly description?: string;\n\treadonly optional?: boolean;\n};\n\n/**\n * Infers the TypeScript type of a single parameter from its JSON Schema.\n * - If `optional: true`, the resolved type is unioned with `undefined`.\n * - If `type` is not provided, the type is `unknown`.\n */\ntype InferParamType<P> = P extends {\n\treadonly type: infer S extends JSONSchema;\n\treadonly optional: true;\n}\n\t? FromSchema<S> | undefined\n\t: P extends { readonly type: infer S extends JSONSchema }\n\t\t? FromSchema<S>\n\t\t: unknown;\n\n/**\n * Maps a tuple of `TypedHelperParam` to a tuple of inferred TypeScript types,\n * usable as the `fn` signature.\n *\n * @example\n * ```\n * type Args = InferArgs<readonly [\n * { name: \"a\"; type: { type: \"string\" } },\n * { name: \"b\"; type: { type: \"number\" }; optional: true },\n * ]>;\n * // => [string, number | undefined]\n * ```\n */\ntype InferArgs<P extends readonly TypedHelperParam[]> = {\n\t[K in keyof P]: InferParamType<P[K]>;\n};\n\n/**\n * Helper configuration with generic parameter inference.\n * Used exclusively by `defineHelper()`.\n */\ninterface TypedHelperConfig<P extends readonly TypedHelperParam[]> {\n\tname: string;\n\tdescription?: string;\n\tparams: P;\n\tfn: (...args: InferArgs<P>) => unknown;\n\treturnType?: JSONSchema;\n}\n\n/**\n * Creates a `HelperConfig` with automatic type inference for `fn` arguments\n * based on the JSON Schemas declared in `params`.\n *\n * The generic parameter `const P` preserves schema literal types\n * (equivalent of `as const`), enabling `FromSchema` to resolve the\n * corresponding TypeScript types.\n *\n * @example\n * ```\n * const helper = defineHelper({\n * name: \"concat\",\n * description: \"Concatenates two strings\",\n * params: [\n * { name: \"a\", type: { type: \"string\" }, description: \"First string\" },\n * { name: \"b\", type: { type: \"string\" }, description: \"Second string\" },\n * { name: \"sep\", type: { type: \"string\" }, description: \"Separator\", optional: true },\n * ],\n * fn: (a, b, sep) => {\n * // a: string, b: string, sep: string | undefined\n * const separator = sep ?? \"\";\n * return `${a}${separator}${b}`;\n * },\n * returnType: { type: \"string\" },\n * });\n * ```\n */\nexport function defineHelper<const P extends readonly TypedHelperParam[]>(\n\tconfig: TypedHelperConfig<P>,\n): HelperConfig {\n\treturn config as unknown as HelperConfig;\n}\n"],"names":["defineHelper","inferPrimitiveSchema","isArrayInput","isLiteralInput","isObjectInput","input","Array","isArray","value","type","Number","isInteger","config"],"mappings":"mPAwfgBA,sBAAAA,kBAxXAC,8BAAAA,0BAhCAC,sBAAAA,kBAbAC,wBAAAA,oBA0BAC,uBAAAA,iBA1BT,SAASD,eACfE,KAAoB,EAEpB,OACCA,QAAU,MAAS,OAAOA,QAAU,UAAY,OAAOA,QAAU,QAEnE,CAOO,SAASH,aACfG,KAAoB,EAEpB,OAAOC,MAAMC,OAAO,CAACF,MACtB,CASO,SAASD,cACfC,KAAoB,EAEpB,OAAOA,QAAU,MAAQ,OAAOA,QAAU,UAAY,CAACC,MAAMC,OAAO,CAACF,MACtE,CAeO,SAASJ,qBACfO,KAA8B,EAE9B,GAAIA,QAAU,KAAM,MAAO,CAAEC,KAAM,MAAO,EAC1C,GAAI,OAAOD,QAAU,UAAW,MAAO,CAAEC,KAAM,SAAU,EACzD,GAAI,OAAOD,QAAU,SAAU,CAC9B,OAAOE,OAAOC,SAAS,CAACH,OAAS,CAAEC,KAAM,SAAU,EAAI,CAAEA,KAAM,QAAS,CACzE,CAGAD,MACA,MAAO,CAAEC,KAAM,MAAO,CACvB,CA4WO,SAAST,aACfY,MAA4B,EAE5B,OAAOA,MACR"}
1
+ {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport type { FromSchema, JSONSchema } from \"json-schema-to-ts\";\n\n// ─── Template Input ──────────────────────────────────────────────────────────\n// The engine accepts primitive values in addition to template strings.\n// When a non-string value is passed, it is treated as a literal passthrough:\n// analysis returns the inferred type, and execution returns the value as-is.\n\n/**\n * Object where each property is a `TemplateInput` (recursive).\n *\n * Allows passing an entire structure as a template:\n * ```\n * engine.analyze({\n * userName: \"{{name}}\",\n * userAge: \"{{age}}\",\n * nested: { x: \"{{foo}}\" },\n * }, inputSchema);\n * ```\n */\nexport interface TemplateInputObject {\n\t[key: string]: TemplateInput;\n}\n\n/**\n * Array where each element is a `TemplateInput` (recursive).\n *\n * Allows passing an array as a template:\n * ```\n * engine.analyze([\"{{name}}\", \"{{age}}\"], inputSchema);\n * engine.execute([\"{{name}}\", 42], data);\n * ```\n */\nexport type TemplateInputArray = TemplateInput[];\n\n/**\n * Input type accepted by the template engine.\n *\n * - `string` → standard Handlebars template (parsed and executed)\n * - `number` → numeric literal (passthrough)\n * - `boolean` → boolean literal (passthrough)\n * - `null` → null literal (passthrough)\n * - `TemplateInputArray` → array where each element is a `TemplateInput`\n * - `TemplateInputObject` → object where each property is a `TemplateInput`\n */\nexport type TemplateInput =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| TemplateInputArray\n\t| TemplateInputObject;\n\n// ─── Template Data ───────────────────────────────────────────────────────────\n// The data parameter accepted by `execute()` and `analyzeAndExecute()`.\n// In most cases this is a `Record<string, unknown>` (object context), but\n// primitives are also allowed — for example when using `{{$root}}` to\n// reference the entire data value directly.\n\n/**\n * Data type accepted by the template engine's execution methods.\n *\n * - `Record<string, unknown>` → standard object context (most common)\n * - `string` → primitive value (e.g. for `{{$root}}`)\n * - `number` → primitive value\n * - `boolean` → primitive value\n * - `null` → null value\n * - `unknown[]` → array value\n */\nexport type TemplateData =\n\t| Record<string, unknown>\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| unknown[];\n\n/**\n * Checks whether a value is a non-string primitive literal (number, boolean, null).\n * These values are treated as passthrough by the engine.\n *\n * Note: objects (`TemplateInputObject`) and arrays (`TemplateInputArray`) are NOT literals.\n */\nexport function isLiteralInput(\n\tinput: TemplateInput,\n): input is number | boolean | null {\n\treturn (\n\t\tinput === null || (typeof input !== \"string\" && typeof input !== \"object\")\n\t);\n}\n\n/**\n * Checks whether a value is a template array (`TemplateInputArray`).\n * Template arrays are processed recursively by the engine:\n * each element is analyzed/executed individually and the result is an array.\n */\nexport function isArrayInput(\n\tinput: TemplateInput,\n): input is TemplateInputArray {\n\treturn Array.isArray(input);\n}\n\n/**\n * Checks whether a value is a template object (`TemplateInputObject`).\n * Template objects are processed recursively by the engine:\n * each property is analyzed/executed individually.\n *\n * Note: arrays are excluded — use `isArrayInput()` first.\n */\nexport function isObjectInput(\n\tinput: TemplateInput,\n): input is TemplateInputObject {\n\treturn input !== null && typeof input === \"object\" && !Array.isArray(input);\n}\n\n/**\n * Infers the JSON Schema of a non-string primitive value.\n *\n * @param value - The primitive value (number, boolean, null)\n * @returns The corresponding JSON Schema\n *\n * @example\n * ```\n * inferPrimitiveSchema(42) // → { type: \"number\" }\n * inferPrimitiveSchema(true) // → { type: \"boolean\" }\n * inferPrimitiveSchema(null) // → { type: \"null\" }\n * ```\n */\nexport function inferPrimitiveSchema(\n\tvalue: number | boolean | null,\n): JSONSchema7 {\n\tif (value === null) return { type: \"null\" };\n\tif (typeof value === \"boolean\") return { type: \"boolean\" };\n\tif (typeof value === \"number\") {\n\t\treturn Number.isInteger(value) ? { type: \"integer\" } : { type: \"number\" };\n\t}\n\t// Exhaustiveness check — all branches are covered above.\n\t// If the type of `value` changes, TypeScript will raise an error here.\n\tvalue satisfies never;\n\treturn { type: \"null\" };\n}\n\n// ─── Diagnostic Codes ────────────────────────────────────────────────────────\n// Machine-readable codes for each error/warning type, enabling the frontend\n// to react programmatically without parsing the human-readable message.\n\nexport type DiagnosticCode =\n\t/** The referenced property does not exist in the context schema */\n\t| \"UNKNOWN_PROPERTY\"\n\t/** Type mismatch (e.g. #each on a non-array) */\n\t| \"TYPE_MISMATCH\"\n\t/** A block helper is used without a required argument */\n\t| \"MISSING_ARGUMENT\"\n\t/** Unknown block helper (neither built-in nor registered) */\n\t| \"UNKNOWN_HELPER\"\n\t/** The expression cannot be statically analyzed */\n\t| \"UNANALYZABLE\"\n\t/** The {{key:N}} syntax is used but no identifierSchemas were provided */\n\t| \"MISSING_IDENTIFIER_SCHEMAS\"\n\t/** The identifier N does not exist in the provided identifierSchemas */\n\t| \"UNKNOWN_IDENTIFIER\"\n\t/** The property does not exist in the identifier's schema */\n\t| \"IDENTIFIER_PROPERTY_NOT_FOUND\"\n\t/** Syntax error in the template */\n\t| \"PARSE_ERROR\"\n\t/** The $root token is used with path traversal (e.g. $root.name) */\n\t| \"ROOT_PATH_TRAVERSAL\"\n\t/** Unsupported JSON Schema feature (e.g. if/then/else conditional schemas) */\n\t| \"UNSUPPORTED_SCHEMA\"\n\t/** The map helper implicitly flattens the input array one level before mapping */\n\t| \"MAP_IMPLICIT_FLATTEN\";\n\n// ─── Diagnostic Details ──────────────────────────────────────────────────────\n// Supplementary information to understand the exact cause of the error.\n// Designed to be easily JSON-serializable and consumable by a frontend.\n\nexport interface DiagnosticDetails {\n\t/** Path of the expression that caused the error (e.g. `\"user.name.foo\"`) */\n\tpath?: string;\n\t/** Name of the helper involved (for helper-related errors) */\n\thelperName?: string;\n\t/** What was expected (e.g. `\"array\"`, `\"property to exist\"`) */\n\texpected?: string;\n\t/** What was found (e.g. `\"string\"`, `\"undefined\"`) */\n\tactual?: string;\n\t/** Available properties in the current schema (for suggestions) */\n\tavailableProperties?: string[];\n\t/** Template identifier number (for `{{key:N}}` errors) */\n\tidentifier?: number;\n}\n\n// ─── Static Analysis Result ──────────────────────────────────────────────────\n\n/** Diagnostic produced by the static analyzer */\nexport interface TemplateDiagnostic {\n\t/** \"error\" blocks execution, \"warning\" is informational */\n\tseverity: \"error\" | \"warning\";\n\n\t/** Machine-readable code identifying the error type */\n\tcode: DiagnosticCode;\n\n\t/** Human-readable message describing the problem */\n\tmessage: string;\n\n\t/** Position in the template source (if available from the AST) */\n\tloc?: {\n\t\tstart: { line: number; column: number };\n\t\tend: { line: number; column: number };\n\t};\n\n\t/** Fragment of the template source around the error */\n\tsource?: string;\n\n\t/** Structured information for debugging and frontend display */\n\tdetails?: DiagnosticDetails;\n}\n\n/** Complete result of the static analysis */\nexport interface AnalysisResult {\n\t/** true if no errors (warnings are tolerated) */\n\tvalid: boolean;\n\t/** List of diagnostics (errors + warnings) */\n\tdiagnostics: TemplateDiagnostic[];\n\t/** JSON Schema describing the template's return type */\n\toutputSchema: JSONSchema7;\n}\n\n/** Lightweight validation result (without output type inference) */\nexport interface ValidationResult {\n\t/** true if no errors (warnings are tolerated) */\n\tvalid: boolean;\n\t/** List of diagnostics (errors + warnings) */\n\tdiagnostics: TemplateDiagnostic[];\n}\n\n// ─── Public Engine Options ───────────────────────────────────────────────────\n\nexport interface TemplateEngineOptions {\n\t/**\n\t * Capacity of the parsed AST cache. Each parsed template is cached\n\t * to avoid costly re-parsing on repeated calls.\n\t * @default 256\n\t */\n\tastCacheSize?: number;\n\n\t/**\n\t * Capacity of the compiled Handlebars template cache.\n\t * @default 256\n\t */\n\tcompilationCacheSize?: number;\n\n\t/**\n\t * Custom helpers to register during engine construction.\n\t *\n\t * Each entry describes a helper with its name, implementation,\n\t * expected parameters, and return type.\n\t *\n\t * @example\n\t * ```\n\t * const engine = new Typebars({\n\t * helpers: [\n\t * {\n\t * name: \"uppercase\",\n\t * description: \"Converts a string to uppercase\",\n\t * fn: (value: string) => String(value).toUpperCase(),\n\t * params: [\n\t * { name: \"value\", type: { type: \"string\" }, description: \"The string to convert\" },\n\t * ],\n\t * returnType: { type: \"string\" },\n\t * },\n\t * ],\n\t * });\n\t * ```\n\t */\n\thelpers?: HelperConfig[];\n}\n\nexport interface CommonTypebarsOptions {\n\t/**\n\t * Explicit coercion schema for the output value.\n\t * When provided with a primitive type, the execution result will be\n\t * coerced to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/**\n\t * When `true`, properties whose values contain Handlebars expressions\n\t * (i.e. any `{{…}}` syntax) are excluded from the execution result.\n\t *\n\t * - **Object**: properties with template expressions are omitted from\n\t * the resulting object.\n\t * - **Array**: elements with template expressions are omitted from\n\t * the resulting array.\n\t * - **Root string** with expressions: returns `null` (there is no\n\t * parent to exclude from).\n\t * - **Literals** (number, boolean, null): unaffected.\n\t *\n\t * This mirrors the analysis-side `excludeTemplateExpression` option\n\t * but applied at runtime.\n\t *\n\t * @default false\n\t */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Execution Options ───────────────────────────────────────────────────────\n// Optional options object for `execute()`, replacing multiple positional\n// parameters for better ergonomics.\n\nexport interface ExecuteOptions extends CommonTypebarsOptions {\n\t/** JSON Schema for pre-execution static validation */\n\tschema?: JSONSchema7;\n\t/** Data by identifier `{ [id]: { key: value } }` */\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\t/** Schemas by identifier (for static validation with identifiers) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n}\n\n// ─── Combined Analyze-and-Execute Options ────────────────────────────────────\n// Optional options object for `analyzeAndExecute()`, grouping parameters\n// related to template identifiers.\n\nexport interface AnalyzeAndExecuteOptions extends CommonTypebarsOptions {\n\t/** Schemas by identifier `{ [id]: JSONSchema7 }` for static analysis */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Data by identifier `{ [id]: { key: value } }` for execution */\n\tidentifierData?: Record<number, Record<string, unknown>>;\n}\n\n// ─── Custom Helpers ──────────────────────────────────────────────────────────\n// Allows registering custom helpers with their type signature for static\n// analysis support.\n\n/** Describes a parameter expected by a helper */\nexport interface HelperParam {\n\t/** Parameter name (for documentation / introspection) */\n\tname: string;\n\n\t/**\n\t * JSON Schema describing the expected type for this parameter.\n\t * Used for documentation and static validation.\n\t */\n\ttype?: JSONSchema7;\n\n\t/** Human-readable description of the parameter */\n\tdescription?: string;\n\n\t/**\n\t * Whether the parameter is optional.\n\t * @default false\n\t */\n\toptional?: boolean;\n}\n\n/**\n * Definition of a helper registerable via `registerHelper()`.\n *\n * Contains the runtime implementation and typing metadata\n * for static analysis.\n */\nexport interface HelperDefinition {\n\t/**\n\t * Runtime implementation of the helper — will be registered with Handlebars.\n\t *\n\t * For an inline helper `{{uppercase name}}`:\n\t * `(value: string) => string`\n\t *\n\t * For a block helper `{{#repeat count}}...{{/repeat}}`:\n\t * `function(this: any, count: number, options: Handlebars.HelperOptions) { ... }`\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: Handlebars helper signatures are inherently dynamic\n\tfn: (...args: any[]) => unknown;\n\n\t/**\n\t * Parameters expected by the helper (for documentation and analysis).\n\t *\n\t * @example\n\t * ```\n\t * params: [\n\t * { name: \"value\", type: { type: \"number\" }, description: \"The value to round\" },\n\t * { name: \"precision\", type: { type: \"number\" }, description: \"Decimal places\", optional: true },\n\t * ]\n\t * ```\n\t */\n\tparams?: HelperParam[];\n\n\t/**\n\t * JSON Schema describing the helper's return type for static analysis.\n\t * @default { type: \"string\" }\n\t */\n\treturnType?: JSONSchema7;\n\n\t/** Human-readable description of the helper */\n\tdescription?: string;\n}\n\n/**\n * Full helper configuration for registration via the `Typebars({ helpers: [...] })`\n * constructor options.\n *\n * Extends `HelperDefinition` with a required `name`.\n *\n * @example\n * ```\n * const config: HelperConfig = {\n * name: \"round\",\n * description: \"Rounds a number to a given precision\",\n * fn: (value: number, precision?: number) => { ... },\n * params: [\n * { name: \"value\", type: { type: \"number\" } },\n * { name: \"precision\", type: { type: \"number\" }, optional: true },\n * ],\n * returnType: { type: \"number\" },\n * };\n * ```\n */\nexport interface HelperConfig extends HelperDefinition {\n\t/** Name of the helper as used in templates (e.g. `\"uppercase\"`) */\n\tname: string;\n}\n\n// ─── Automatic Type Inference via json-schema-to-ts ──────────────────────────\n// Allows `defineHelper()` to infer TypeScript types for `fn` arguments\n// from the JSON Schemas declared in `params`.\n\n/**\n * Param definition used for type inference.\n * Accepts `JSONSchema` from `json-schema-to-ts` to allow `FromSchema`\n * to resolve literal types.\n */\ntype TypedHelperParam = {\n\treadonly name: string;\n\treadonly type?: JSONSchema;\n\treadonly description?: string;\n\treadonly optional?: boolean;\n};\n\n/**\n * Infers the TypeScript type of a single parameter from its JSON Schema.\n * - If `optional: true`, the resolved type is unioned with `undefined`.\n * - If `type` is not provided, the type is `unknown`.\n */\ntype InferParamType<P> = P extends {\n\treadonly type: infer S extends JSONSchema;\n\treadonly optional: true;\n}\n\t? FromSchema<S> | undefined\n\t: P extends { readonly type: infer S extends JSONSchema }\n\t\t? FromSchema<S>\n\t\t: unknown;\n\n/**\n * Maps a tuple of `TypedHelperParam` to a tuple of inferred TypeScript types,\n * usable as the `fn` signature.\n *\n * @example\n * ```\n * type Args = InferArgs<readonly [\n * { name: \"a\"; type: { type: \"string\" } },\n * { name: \"b\"; type: { type: \"number\" }; optional: true },\n * ]>;\n * // => [string, number | undefined]\n * ```\n */\ntype InferArgs<P extends readonly TypedHelperParam[]> = {\n\t[K in keyof P]: InferParamType<P[K]>;\n};\n\n/**\n * Helper configuration with generic parameter inference.\n * Used exclusively by `defineHelper()`.\n */\ninterface TypedHelperConfig<P extends readonly TypedHelperParam[]> {\n\tname: string;\n\tdescription?: string;\n\tparams: P;\n\tfn: (...args: InferArgs<P>) => unknown;\n\treturnType?: JSONSchema;\n}\n\n/**\n * Creates a `HelperConfig` with automatic type inference for `fn` arguments\n * based on the JSON Schemas declared in `params`.\n *\n * The generic parameter `const P` preserves schema literal types\n * (equivalent of `as const`), enabling `FromSchema` to resolve the\n * corresponding TypeScript types.\n *\n * @example\n * ```\n * const helper = defineHelper({\n * name: \"concat\",\n * description: \"Concatenates two strings\",\n * params: [\n * { name: \"a\", type: { type: \"string\" }, description: \"First string\" },\n * { name: \"b\", type: { type: \"string\" }, description: \"Second string\" },\n * { name: \"sep\", type: { type: \"string\" }, description: \"Separator\", optional: true },\n * ],\n * fn: (a, b, sep) => {\n * // a: string, b: string, sep: string | undefined\n * const separator = sep ?? \"\";\n * return `${a}${separator}${b}`;\n * },\n * returnType: { type: \"string\" },\n * });\n * ```\n */\nexport function defineHelper<const P extends readonly TypedHelperParam[]>(\n\tconfig: TypedHelperConfig<P>,\n): HelperConfig {\n\treturn config as unknown as HelperConfig;\n}\n"],"names":["defineHelper","inferPrimitiveSchema","isArrayInput","isLiteralInput","isObjectInput","input","Array","isArray","value","type","Number","isInteger","config"],"mappings":"mPA0fgBA,sBAAAA,kBA1XAC,8BAAAA,0BAhCAC,sBAAAA,kBAbAC,wBAAAA,oBA0BAC,uBAAAA,iBA1BT,SAASD,eACfE,KAAoB,EAEpB,OACCA,QAAU,MAAS,OAAOA,QAAU,UAAY,OAAOA,QAAU,QAEnE,CAOO,SAASH,aACfG,KAAoB,EAEpB,OAAOC,MAAMC,OAAO,CAACF,MACtB,CASO,SAASD,cACfC,KAAoB,EAEpB,OAAOA,QAAU,MAAQ,OAAOA,QAAU,UAAY,CAACC,MAAMC,OAAO,CAACF,MACtE,CAeO,SAASJ,qBACfO,KAA8B,EAE9B,GAAIA,QAAU,KAAM,MAAO,CAAEC,KAAM,MAAO,EAC1C,GAAI,OAAOD,QAAU,UAAW,MAAO,CAAEC,KAAM,SAAU,EACzD,GAAI,OAAOD,QAAU,SAAU,CAC9B,OAAOE,OAAOC,SAAS,CAACH,OAAS,CAAEC,KAAM,SAAU,EAAI,CAAEA,KAAM,QAAS,CACzE,CAGAD,MACA,MAAO,CAAEC,KAAM,MAAO,CACvB,CA8WO,SAAST,aACfY,MAA4B,EAE5B,OAAOA,MACR"}
@@ -1,2 +1,2 @@
1
- import{dispatchAnalyze}from"./dispatch.js";import{createMissingArgumentMessage,createPropertyNotFoundMessage,createRootPathTraversalMessage,createTypeMismatchMessage,createUnanalyzableMessage,createUnknownHelperMessage}from"./errors.js";import{MapHelpers}from"./helpers/map-helpers.js";import{detectLiteralType,extractExpressionIdentifier,extractPathSegments,getEffectiveBody,getEffectivelySingleBlock,getEffectivelySingleExpression,isRootPathTraversal,isRootSegments,isThisExpression,parse}from"./parser.js";import{findConditionalSchemaLocations,resolveArrayItems,resolveSchemaPath,simplifySchema}from"./schema-resolver.js";import{deepEqual,extractSourceSnippet,getSchemaPropertyNames}from"./utils.js";function coerceTextValue(text,targetType){switch(targetType){case"number":case"integer":{if(text==="")return undefined;const num=Number(text);if(Number.isNaN(num))return undefined;if(targetType==="integer"&&!Number.isInteger(num))return undefined;return num}case"boolean":{const lower=text.toLowerCase();if(lower==="true")return true;if(lower==="false")return false;return undefined}case"null":return null;default:return text}}export function analyze(template,inputSchema={},options){return dispatchAnalyze(template,options,(tpl,coerceSchema)=>{const ast=parse(tpl);return analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,coerceSchema})},(child,childOptions)=>analyze(child,inputSchema,childOptions))}export function analyzeFromAst(ast,template,inputSchema={},options){const ctx={root:inputSchema,current:inputSchema,diagnostics:[],template,identifierSchemas:options?.identifierSchemas,helpers:options?.helpers,coerceSchema:options?.coerceSchema};const conditionalLocations=findConditionalSchemaLocations(inputSchema);for(const loc of conditionalLocations){addDiagnostic(ctx,"UNSUPPORTED_SCHEMA","error",`Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". `+"Conditional schemas (if/then/else) cannot be resolved during static analysis "+"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.",undefined,{path:loc.schemaPath})}if(options?.identifierSchemas){for(const[id,idSchema]of Object.entries(options.identifierSchemas)){const idLocations=findConditionalSchemaLocations(idSchema,`/identifierSchemas/${id}`);for(const loc of idLocations){addDiagnostic(ctx,"UNSUPPORTED_SCHEMA","error",`Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". `+"Conditional schemas (if/then/else) cannot be resolved during static analysis "+"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.",undefined,{path:loc.schemaPath})}}}if(ctx.diagnostics.length>0){return{valid:false,diagnostics:ctx.diagnostics,outputSchema:{}}}const outputSchema=inferProgramType(ast,ctx);const hasErrors=ctx.diagnostics.some(d=>d.severity==="error");return{valid:!hasErrors,diagnostics:ctx.diagnostics,outputSchema:simplifySchema(outputSchema)}}function processStatement(stmt,ctx){switch(stmt.type){case"ContentStatement":case"CommentStatement":return undefined;case"MustacheStatement":return processMustache(stmt,ctx);case"BlockStatement":return inferBlockType(stmt,ctx);default:addDiagnostic(ctx,"UNANALYZABLE","warning",`Unsupported AST node type: "${stmt.type}"`,stmt);return undefined}}function processMustache(stmt,ctx){if(stmt.path.type==="SubExpression"){addDiagnostic(ctx,"UNANALYZABLE","warning","Sub-expressions are not statically analyzable",stmt);return{}}if(stmt.params.length>0||stmt.hash){const helperName=getExpressionName(stmt.path);if(helperName===MapHelpers.MAP_HELPER_NAME){return processMapHelper(stmt,ctx)}const helper=ctx.helpers?.get(helperName);if(helper){const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(stmt.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${stmt.params.length}`,stmt,{helperName,expected:`${requiredCount} argument(s)`,actual:`${stmt.params.length} argument(s)`})}}for(let i=0;i<stmt.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(stmt.params[i],ctx,stmt);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,stmt,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown inline helper "${helperName}" — cannot analyze statically`,stmt,{helperName});return{type:"string"}}return resolveExpressionWithDiagnostics(stmt.path,ctx,stmt)??{}}function processMapHelper(stmt,ctx){const helperName=MapHelpers.MAP_HELPER_NAME;if(stmt.params.length<2){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least 2 argument(s), but got ${stmt.params.length}`,stmt,{helperName,expected:"2 argument(s)",actual:`${stmt.params.length} argument(s)`});return{type:"array"}}const collectionExpr=stmt.params[0];const collectionSchema=resolveExpressionWithDiagnostics(collectionExpr,ctx,stmt);if(!collectionSchema){return{type:"array"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "collection" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,stmt,{helperName,expected:"array",actual:schemaTypeLabel(collectionSchema)});return{type:"array"}}let effectiveItemSchema=itemSchema;const itemType=effectiveItemSchema.type;if(itemType==="array"||Array.isArray(itemType)&&itemType.includes("array")){const innerItems=resolveArrayItems(effectiveItemSchema,ctx.root);if(innerItems){effectiveItemSchema=innerItems}}const effectiveItemType=effectiveItemSchema.type;const isObject=effectiveItemType==="object"||Array.isArray(effectiveItemType)&&effectiveItemType.includes("object")||!effectiveItemType&&effectiveItemSchema.properties!==undefined;if(!isObject&&effectiveItemType!==undefined){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" expects an array of objects, but the array items have type "${schemaTypeLabel(effectiveItemSchema)}"`,stmt,{helperName,expected:"object",actual:schemaTypeLabel(effectiveItemSchema)});return{type:"array"}}const propertyExpr=stmt.params[1];let propertyName;if(propertyExpr.type==="PathExpression"){const bare=propertyExpr.original;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" must be a quoted string. `+`Use {{ ${helperName} … "${bare}" }} instead of {{ ${helperName} … ${bare} }}`,stmt,{helperName,expected:'StringLiteral (e.g. "property")',actual:`PathExpression (${bare})`});return{type:"array"}}if(propertyExpr.type==="StringLiteral"){propertyName=propertyExpr.value}if(!propertyName){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" expects a quoted string literal, but got ${propertyExpr.type}`,stmt,{helperName,expected:'StringLiteral (e.g. "property")',actual:propertyExpr.type});return{type:"array"}}const propertySchema=resolveSchemaPath(effectiveItemSchema,[propertyName]);if(!propertySchema){const availableProperties=getSchemaPropertyNames(effectiveItemSchema);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(propertyName,availableProperties),stmt,{path:propertyName,availableProperties});return{type:"array"}}return{type:"array",items:propertySchema}}function isParamTypeCompatible(resolved,expected){if(!expected.type||!resolved.type)return true;const expectedTypes=Array.isArray(expected.type)?expected.type:[expected.type];const resolvedTypes=Array.isArray(resolved.type)?resolved.type:[resolved.type];return resolvedTypes.some(rt=>expectedTypes.some(et=>rt===et||et==="number"&&rt==="integer"||et==="integer"&&rt==="number"))}function inferProgramType(program,ctx){const effective=getEffectiveBody(program);if(effective.length===0){return{type:"string"}}const singleExpr=getEffectivelySingleExpression(program);if(singleExpr){return processMustache(singleExpr,ctx)}const singleBlock=getEffectivelySingleBlock(program);if(singleBlock){return inferBlockType(singleBlock,ctx)}const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){const text=effective.map(s=>s.value).join("").trim();if(text==="")return{type:"string"};const coercedType=ctx.coerceSchema?.type;if(typeof coercedType==="string"&&(coercedType==="string"||coercedType==="number"||coercedType==="integer"||coercedType==="boolean"||coercedType==="null")){const coercedValue=coerceTextValue(text,coercedType);return{type:coercedType,const:coercedValue}}const literalType=detectLiteralType(text);if(literalType)return{type:literalType}}const allBlocks=effective.every(s=>s.type==="BlockStatement");if(allBlocks){const types=[];for(const stmt of effective){const t=inferBlockType(stmt,ctx);if(t)types.push(t)}if(types.length===1)return types[0];if(types.length>1)return simplifySchema({oneOf:types});return{type:"string"}}for(const stmt of program.body){processStatement(stmt,ctx)}return{type:"string"}}function inferBlockType(stmt,ctx){const helperName=getBlockHelperName(stmt);switch(helperName){case"if":case"unless":{const arg=getBlockArgument(stmt);if(arg){resolveExpressionWithDiagnostics(arg,ctx,stmt)}else{addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage(helperName),stmt,{helperName})}const thenType=inferProgramType(stmt.program,ctx);if(stmt.inverse){const elseType=inferProgramType(stmt.inverse,ctx);if(deepEqual(thenType,elseType))return thenType;return simplifySchema({oneOf:[thenType,elseType]})}return thenType}case"each":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage("each"),stmt,{helperName:"each"});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const collectionSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);if(!collectionSchema){const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",createTypeMismatchMessage("each","an array",schemaTypeLabel(collectionSchema)),stmt,{helperName:"each",expected:"array",actual:schemaTypeLabel(collectionSchema)});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const saved=ctx.current;ctx.current=itemSchema;inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}case"with":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage("with"),stmt,{helperName:"with"});const saved=ctx.current;ctx.current={};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}const innerSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);const saved=ctx.current;ctx.current=innerSchema??{};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}default:{const helper=ctx.helpers?.get(helperName);if(helper){for(const param of stmt.params){resolveExpressionWithDiagnostics(param,ctx,stmt)}inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",createUnknownHelperMessage(helperName),stmt,{helperName});inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}}}function resolveExpressionWithDiagnostics(expr,ctx,parentNode){if(isThisExpression(expr)){return ctx.current}if(expr.type==="SubExpression"){return resolveSubExpression(expr,ctx,parentNode)}const segments=extractPathSegments(expr);if(segments.length===0){if(expr.type==="StringLiteral")return{type:"string"};if(expr.type==="NumberLiteral")return{type:"number"};if(expr.type==="BooleanLiteral")return{type:"boolean"};if(expr.type==="NullLiteral")return{type:"null"};if(expr.type==="UndefinedLiteral")return{};addDiagnostic(ctx,"UNANALYZABLE","warning",createUnanalyzableMessage(expr.type),parentNode??expr);return undefined}const{cleanSegments,identifier}=extractExpressionIdentifier(segments);if(isRootPathTraversal(cleanSegments)){const fullPath=cleanSegments.join(".");addDiagnostic(ctx,"ROOT_PATH_TRAVERSAL","error",createRootPathTraversalMessage(fullPath),parentNode??expr,{path:fullPath});return undefined}if(isRootSegments(cleanSegments)){if(identifier!==null){return resolveRootWithIdentifier(identifier,ctx,parentNode??expr)}return ctx.current}if(identifier!==null){return resolveWithIdentifier(cleanSegments,identifier,ctx,parentNode??expr)}const resolved=resolveSchemaPath(ctx.current,cleanSegments);if(resolved===undefined){const fullPath=cleanSegments.join(".");const availableProperties=getSchemaPropertyNames(ctx.current);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(fullPath,availableProperties),parentNode??expr,{path:fullPath,availableProperties});return undefined}return resolved}function resolveRootWithIdentifier(identifier,ctx,node){if(!ctx.identifierSchemas){addDiagnostic(ctx,"MISSING_IDENTIFIER_SCHEMAS","error",`Property "$root:${identifier}" uses an identifier but no identifier schemas were provided`,node,{path:`$root:${identifier}`,identifier});return undefined}const idSchema=ctx.identifierSchemas[identifier];if(!idSchema){addDiagnostic(ctx,"UNKNOWN_IDENTIFIER","error",`Property "$root:${identifier}" references identifier ${identifier} but no schema exists for this identifier`,node,{path:`$root:${identifier}`,identifier});return undefined}return idSchema}function resolveWithIdentifier(cleanSegments,identifier,ctx,node){const fullPath=cleanSegments.join(".");if(!ctx.identifierSchemas){addDiagnostic(ctx,"MISSING_IDENTIFIER_SCHEMAS","error",`Property "${fullPath}:${identifier}" uses an identifier but no identifier schemas were provided`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const idSchema=ctx.identifierSchemas[identifier];if(!idSchema){addDiagnostic(ctx,"UNKNOWN_IDENTIFIER","error",`Property "${fullPath}:${identifier}" references identifier ${identifier} but no schema exists for this identifier`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const resolved=resolveSchemaPath(idSchema,cleanSegments);if(resolved===undefined){const availableProperties=getSchemaPropertyNames(idSchema);addDiagnostic(ctx,"IDENTIFIER_PROPERTY_NOT_FOUND","error",`Property "${fullPath}" does not exist in the schema for identifier ${identifier}`,node,{path:fullPath,identifier,availableProperties});return undefined}return resolved}function resolveSubExpression(expr,ctx,parentNode){const helperName=getExpressionName(expr.path);if(helperName===MapHelpers.MAP_HELPER_NAME){return processMapSubExpression(expr,ctx,parentNode)}const helper=ctx.helpers?.get(helperName);if(!helper){addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown sub-expression helper "${helperName}" — cannot analyze statically`,parentNode??expr,{helperName});return{type:"string"}}const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(expr.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${expr.params.length}`,parentNode??expr,{helperName,expected:`${requiredCount} argument(s)`,actual:`${expr.params.length} argument(s)`})}}for(let i=0;i<expr.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(expr.params[i],ctx,parentNode??expr);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,parentNode??expr,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}function processMapSubExpression(expr,ctx,parentNode){const helperName=MapHelpers.MAP_HELPER_NAME;const node=parentNode??expr;if(expr.params.length<2){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least 2 argument(s), but got ${expr.params.length}`,node,{helperName,expected:"2 argument(s)",actual:`${expr.params.length} argument(s)`});return{type:"array"}}const collectionExpr=expr.params[0];const collectionSchema=resolveExpressionWithDiagnostics(collectionExpr,ctx,node);if(!collectionSchema){return{type:"array"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "collection" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,node,{helperName,expected:"array",actual:schemaTypeLabel(collectionSchema)});return{type:"array"}}let effectiveItemSchema=itemSchema;const itemType=effectiveItemSchema.type;if(itemType==="array"||Array.isArray(itemType)&&itemType.includes("array")){const innerItems=resolveArrayItems(effectiveItemSchema,ctx.root);if(innerItems){effectiveItemSchema=innerItems}}const effectiveItemType=effectiveItemSchema.type;const isObject=effectiveItemType==="object"||Array.isArray(effectiveItemType)&&effectiveItemType.includes("object")||!effectiveItemType&&effectiveItemSchema.properties!==undefined;if(!isObject&&effectiveItemType!==undefined){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" expects an array of objects, but the array items have type "${schemaTypeLabel(effectiveItemSchema)}"`,node,{helperName,expected:"object",actual:schemaTypeLabel(effectiveItemSchema)});return{type:"array"}}const propertyExpr=expr.params[1];let propertyName;if(propertyExpr.type==="PathExpression"){const bare=propertyExpr.original;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" must be a quoted string. `+`Use (${helperName} … "${bare}") instead of (${helperName} … ${bare})`,node,{helperName,expected:'StringLiteral (e.g. "property")',actual:`PathExpression (${bare})`});return{type:"array"}}if(propertyExpr.type==="StringLiteral"){propertyName=propertyExpr.value}if(!propertyName){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" expects a quoted string literal, but got ${propertyExpr.type}`,node,{helperName,expected:'StringLiteral (e.g. "property")',actual:propertyExpr.type});return{type:"array"}}const propertySchema=resolveSchemaPath(effectiveItemSchema,[propertyName]);if(!propertySchema){const availableProperties=getSchemaPropertyNames(effectiveItemSchema);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(propertyName,availableProperties),node,{path:propertyName,availableProperties});return{type:"array"}}return{type:"array",items:propertySchema}}function getBlockArgument(stmt){return stmt.params[0]}function getBlockHelperName(stmt){if(stmt.path.type==="PathExpression"){return stmt.path.original}return""}function getExpressionName(expr){if(expr.type==="PathExpression"){return expr.original}return""}function addDiagnostic(ctx,code,severity,message,node,details){const diagnostic={severity,code,message};if(node&&"loc"in node&&node.loc){diagnostic.loc={start:{line:node.loc.start.line,column:node.loc.start.column},end:{line:node.loc.end.line,column:node.loc.end.column}};diagnostic.source=extractSourceSnippet(ctx.template,diagnostic.loc)}if(details){diagnostic.details=details}ctx.diagnostics.push(diagnostic)}function schemaTypeLabel(schema){if(schema.type){return Array.isArray(schema.type)?schema.type.join(" | "):schema.type}if(schema.oneOf)return"oneOf(...)";if(schema.anyOf)return"anyOf(...)";if(schema.allOf)return"allOf(...)";if(schema.enum)return"enum";return"unknown"}export{inferBlockType};
1
+ import{dispatchAnalyze}from"./dispatch.js";import{createMissingArgumentMessage,createPropertyNotFoundMessage,createRootPathTraversalMessage,createTypeMismatchMessage,createUnanalyzableMessage,createUnknownHelperMessage}from"./errors.js";import{MapHelpers}from"./helpers/map-helpers.js";import{detectLiteralType,extractExpressionIdentifier,extractPathSegments,getEffectiveBody,getEffectivelySingleBlock,getEffectivelySingleExpression,isRootPathTraversal,isRootSegments,isThisExpression,parse}from"./parser.js";import{findConditionalSchemaLocations,resolveArrayItems,resolveSchemaPath,simplifySchema}from"./schema-resolver.js";import{deepEqual,extractSourceSnippet,getSchemaPropertyNames}from"./utils.js";function coerceTextValue(text,targetType){switch(targetType){case"number":case"integer":{if(text==="")return undefined;const num=Number(text);if(Number.isNaN(num))return undefined;if(targetType==="integer"&&!Number.isInteger(num))return undefined;return num}case"boolean":{const lower=text.toLowerCase();if(lower==="true")return true;if(lower==="false")return false;return undefined}case"null":return null;default:return text}}export function analyze(template,inputSchema={},options){return dispatchAnalyze(template,options,(tpl,coerceSchema)=>{const ast=parse(tpl);return analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,coerceSchema})},(child,childOptions)=>analyze(child,inputSchema,childOptions))}export function analyzeFromAst(ast,template,inputSchema={},options){const ctx={root:inputSchema,current:inputSchema,diagnostics:[],template,identifierSchemas:options?.identifierSchemas,helpers:options?.helpers,coerceSchema:options?.coerceSchema};const conditionalLocations=findConditionalSchemaLocations(inputSchema);for(const loc of conditionalLocations){addDiagnostic(ctx,"UNSUPPORTED_SCHEMA","error",`Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". `+"Conditional schemas (if/then/else) cannot be resolved during static analysis "+"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.",undefined,{path:loc.schemaPath})}if(options?.identifierSchemas){for(const[id,idSchema]of Object.entries(options.identifierSchemas)){const idLocations=findConditionalSchemaLocations(idSchema,`/identifierSchemas/${id}`);for(const loc of idLocations){addDiagnostic(ctx,"UNSUPPORTED_SCHEMA","error",`Unsupported JSON Schema feature: "${loc.keyword}" at "${loc.schemaPath}". `+"Conditional schemas (if/then/else) cannot be resolved during static analysis "+"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.",undefined,{path:loc.schemaPath})}}}if(ctx.diagnostics.length>0){return{valid:false,diagnostics:ctx.diagnostics,outputSchema:{}}}const outputSchema=inferProgramType(ast,ctx);const hasErrors=ctx.diagnostics.some(d=>d.severity==="error");return{valid:!hasErrors,diagnostics:ctx.diagnostics,outputSchema:simplifySchema(outputSchema)}}function processStatement(stmt,ctx){switch(stmt.type){case"ContentStatement":case"CommentStatement":return undefined;case"MustacheStatement":return processMustache(stmt,ctx);case"BlockStatement":return inferBlockType(stmt,ctx);default:addDiagnostic(ctx,"UNANALYZABLE","warning",`Unsupported AST node type: "${stmt.type}"`,stmt);return undefined}}function processMustache(stmt,ctx){if(stmt.path.type==="SubExpression"){addDiagnostic(ctx,"UNANALYZABLE","warning","Sub-expressions are not statically analyzable",stmt);return{}}if(stmt.params.length>0||stmt.hash){const helperName=getExpressionName(stmt.path);if(helperName===MapHelpers.MAP_HELPER_NAME){return processMapHelper(stmt,ctx)}const helper=ctx.helpers?.get(helperName);if(helper){const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(stmt.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${stmt.params.length}`,stmt,{helperName,expected:`${requiredCount} argument(s)`,actual:`${stmt.params.length} argument(s)`})}}for(let i=0;i<stmt.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(stmt.params[i],ctx,stmt);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,stmt,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown inline helper "${helperName}" — cannot analyze statically`,stmt,{helperName});return{type:"string"}}return resolveExpressionWithDiagnostics(stmt.path,ctx,stmt)??{}}function processMapHelper(stmt,ctx){const helperName=MapHelpers.MAP_HELPER_NAME;if(stmt.params.length<2){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least 2 argument(s), but got ${stmt.params.length}`,stmt,{helperName,expected:"2 argument(s)",actual:`${stmt.params.length} argument(s)`});return{type:"array"}}const collectionExpr=stmt.params[0];const collectionSchema=resolveExpressionWithDiagnostics(collectionExpr,ctx,stmt);if(!collectionSchema){return{type:"array"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "collection" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,stmt,{helperName,expected:"array",actual:schemaTypeLabel(collectionSchema)});return{type:"array"}}let effectiveItemSchema=itemSchema;const itemType=effectiveItemSchema.type;if(itemType==="array"||Array.isArray(itemType)&&itemType.includes("array")){const innerItems=resolveArrayItems(effectiveItemSchema,ctx.root);if(innerItems){effectiveItemSchema=innerItems;addDiagnostic(ctx,"MAP_IMPLICIT_FLATTEN","warning",`The "${helperName}" helper will automatically flatten the input array one level before mapping. `+`The item type "${Array.isArray(itemType)?itemType.join(" | "):itemType}" was unwrapped to its inner items schema.`,stmt,{helperName,expected:"object",actual:schemaTypeLabel(effectiveItemSchema)})}}const effectiveItemType=effectiveItemSchema.type;const isObject=effectiveItemType==="object"||Array.isArray(effectiveItemType)&&effectiveItemType.includes("object")||!effectiveItemType&&effectiveItemSchema.properties!==undefined;if(!isObject&&effectiveItemType!==undefined){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" expects an array of objects, but the array items have type "${schemaTypeLabel(effectiveItemSchema)}"`,stmt,{helperName,expected:"object",actual:schemaTypeLabel(effectiveItemSchema)});return{type:"array"}}const propertyExpr=stmt.params[1];let propertyName;if(propertyExpr.type==="PathExpression"){const bare=propertyExpr.original;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" must be a quoted string. `+`Use {{ ${helperName} … "${bare}" }} instead of {{ ${helperName} … ${bare} }}`,stmt,{helperName,expected:'StringLiteral (e.g. "property")',actual:`PathExpression (${bare})`});return{type:"array"}}if(propertyExpr.type==="StringLiteral"){propertyName=propertyExpr.value}if(!propertyName){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" expects a quoted string literal, but got ${propertyExpr.type}`,stmt,{helperName,expected:'StringLiteral (e.g. "property")',actual:propertyExpr.type});return{type:"array"}}const propertySchema=resolveSchemaPath(effectiveItemSchema,[propertyName]);if(!propertySchema){const availableProperties=getSchemaPropertyNames(effectiveItemSchema);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(propertyName,availableProperties),stmt,{path:propertyName,availableProperties});return{type:"array"}}return{type:"array",items:propertySchema}}function isParamTypeCompatible(resolved,expected){if(!expected.type||!resolved.type)return true;const expectedTypes=Array.isArray(expected.type)?expected.type:[expected.type];const resolvedTypes=Array.isArray(resolved.type)?resolved.type:[resolved.type];return resolvedTypes.some(rt=>expectedTypes.some(et=>rt===et||et==="number"&&rt==="integer"||et==="integer"&&rt==="number"))}function inferProgramType(program,ctx){const effective=getEffectiveBody(program);if(effective.length===0){return{type:"string"}}const singleExpr=getEffectivelySingleExpression(program);if(singleExpr){return processMustache(singleExpr,ctx)}const singleBlock=getEffectivelySingleBlock(program);if(singleBlock){return inferBlockType(singleBlock,ctx)}const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){const text=effective.map(s=>s.value).join("").trim();if(text==="")return{type:"string"};const coercedType=ctx.coerceSchema?.type;if(typeof coercedType==="string"&&(coercedType==="string"||coercedType==="number"||coercedType==="integer"||coercedType==="boolean"||coercedType==="null")){const coercedValue=coerceTextValue(text,coercedType);return{type:coercedType,const:coercedValue}}const literalType=detectLiteralType(text);if(literalType)return{type:literalType}}const allBlocks=effective.every(s=>s.type==="BlockStatement");if(allBlocks){const types=[];for(const stmt of effective){const t=inferBlockType(stmt,ctx);if(t)types.push(t)}if(types.length===1)return types[0];if(types.length>1)return simplifySchema({oneOf:types});return{type:"string"}}for(const stmt of program.body){processStatement(stmt,ctx)}return{type:"string"}}function inferBlockType(stmt,ctx){const helperName=getBlockHelperName(stmt);switch(helperName){case"if":case"unless":{const arg=getBlockArgument(stmt);if(arg){resolveExpressionWithDiagnostics(arg,ctx,stmt)}else{addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage(helperName),stmt,{helperName})}const thenType=inferProgramType(stmt.program,ctx);if(stmt.inverse){const elseType=inferProgramType(stmt.inverse,ctx);if(deepEqual(thenType,elseType))return thenType;return simplifySchema({oneOf:[thenType,elseType]})}return thenType}case"each":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage("each"),stmt,{helperName:"each"});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const collectionSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);if(!collectionSchema){const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",createTypeMismatchMessage("each","an array",schemaTypeLabel(collectionSchema)),stmt,{helperName:"each",expected:"array",actual:schemaTypeLabel(collectionSchema)});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const saved=ctx.current;ctx.current=itemSchema;inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}case"with":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",createMissingArgumentMessage("with"),stmt,{helperName:"with"});const saved=ctx.current;ctx.current={};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}const innerSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);const saved=ctx.current;ctx.current=innerSchema??{};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}default:{const helper=ctx.helpers?.get(helperName);if(helper){for(const param of stmt.params){resolveExpressionWithDiagnostics(param,ctx,stmt)}inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",createUnknownHelperMessage(helperName),stmt,{helperName});inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}}}function resolveExpressionWithDiagnostics(expr,ctx,parentNode){if(isThisExpression(expr)){return ctx.current}if(expr.type==="SubExpression"){return resolveSubExpression(expr,ctx,parentNode)}const segments=extractPathSegments(expr);if(segments.length===0){if(expr.type==="StringLiteral")return{type:"string"};if(expr.type==="NumberLiteral")return{type:"number"};if(expr.type==="BooleanLiteral")return{type:"boolean"};if(expr.type==="NullLiteral")return{type:"null"};if(expr.type==="UndefinedLiteral")return{};addDiagnostic(ctx,"UNANALYZABLE","warning",createUnanalyzableMessage(expr.type),parentNode??expr);return undefined}const{cleanSegments,identifier}=extractExpressionIdentifier(segments);if(isRootPathTraversal(cleanSegments)){const fullPath=cleanSegments.join(".");addDiagnostic(ctx,"ROOT_PATH_TRAVERSAL","error",createRootPathTraversalMessage(fullPath),parentNode??expr,{path:fullPath});return undefined}if(isRootSegments(cleanSegments)){if(identifier!==null){return resolveRootWithIdentifier(identifier,ctx,parentNode??expr)}return ctx.current}if(identifier!==null){return resolveWithIdentifier(cleanSegments,identifier,ctx,parentNode??expr)}const resolved=resolveSchemaPath(ctx.current,cleanSegments);if(resolved===undefined){const fullPath=cleanSegments.join(".");const availableProperties=getSchemaPropertyNames(ctx.current);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(fullPath,availableProperties),parentNode??expr,{path:fullPath,availableProperties});return undefined}return resolved}function resolveRootWithIdentifier(identifier,ctx,node){if(!ctx.identifierSchemas){addDiagnostic(ctx,"MISSING_IDENTIFIER_SCHEMAS","error",`Property "$root:${identifier}" uses an identifier but no identifier schemas were provided`,node,{path:`$root:${identifier}`,identifier});return undefined}const idSchema=ctx.identifierSchemas[identifier];if(!idSchema){addDiagnostic(ctx,"UNKNOWN_IDENTIFIER","error",`Property "$root:${identifier}" references identifier ${identifier} but no schema exists for this identifier`,node,{path:`$root:${identifier}`,identifier});return undefined}return idSchema}function resolveWithIdentifier(cleanSegments,identifier,ctx,node){const fullPath=cleanSegments.join(".");if(!ctx.identifierSchemas){addDiagnostic(ctx,"MISSING_IDENTIFIER_SCHEMAS","error",`Property "${fullPath}:${identifier}" uses an identifier but no identifier schemas were provided`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const idSchema=ctx.identifierSchemas[identifier];if(!idSchema){addDiagnostic(ctx,"UNKNOWN_IDENTIFIER","error",`Property "${fullPath}:${identifier}" references identifier ${identifier} but no schema exists for this identifier`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const resolved=resolveSchemaPath(idSchema,cleanSegments);if(resolved===undefined){const availableProperties=getSchemaPropertyNames(idSchema);addDiagnostic(ctx,"IDENTIFIER_PROPERTY_NOT_FOUND","error",`Property "${fullPath}" does not exist in the schema for identifier ${identifier}`,node,{path:fullPath,identifier,availableProperties});return undefined}return resolved}function resolveSubExpression(expr,ctx,parentNode){const helperName=getExpressionName(expr.path);if(helperName===MapHelpers.MAP_HELPER_NAME){return processMapSubExpression(expr,ctx,parentNode)}const helper=ctx.helpers?.get(helperName);if(!helper){addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown sub-expression helper "${helperName}" — cannot analyze statically`,parentNode??expr,{helperName});return{type:"string"}}const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(expr.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${expr.params.length}`,parentNode??expr,{helperName,expected:`${requiredCount} argument(s)`,actual:`${expr.params.length} argument(s)`})}}for(let i=0;i<expr.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(expr.params[i],ctx,parentNode??expr);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,parentNode??expr,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}function processMapSubExpression(expr,ctx,parentNode){const helperName=MapHelpers.MAP_HELPER_NAME;const node=parentNode??expr;if(expr.params.length<2){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least 2 argument(s), but got ${expr.params.length}`,node,{helperName,expected:"2 argument(s)",actual:`${expr.params.length} argument(s)`});return{type:"array"}}const collectionExpr=expr.params[0];const collectionSchema=resolveExpressionWithDiagnostics(collectionExpr,ctx,node);if(!collectionSchema){return{type:"array"}}const itemSchema=resolveArrayItems(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "collection" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,node,{helperName,expected:"array",actual:schemaTypeLabel(collectionSchema)});return{type:"array"}}let effectiveItemSchema=itemSchema;const itemType=effectiveItemSchema.type;if(itemType==="array"||Array.isArray(itemType)&&itemType.includes("array")){const innerItems=resolveArrayItems(effectiveItemSchema,ctx.root);if(innerItems){effectiveItemSchema=innerItems}}const effectiveItemType=effectiveItemSchema.type;const isObject=effectiveItemType==="object"||Array.isArray(effectiveItemType)&&effectiveItemType.includes("object")||!effectiveItemType&&effectiveItemSchema.properties!==undefined;if(!isObject&&effectiveItemType!==undefined){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" expects an array of objects, but the array items have type "${schemaTypeLabel(effectiveItemSchema)}"`,node,{helperName,expected:"object",actual:schemaTypeLabel(effectiveItemSchema)});return{type:"array"}}const propertyExpr=expr.params[1];let propertyName;if(propertyExpr.type==="PathExpression"){const bare=propertyExpr.original;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" must be a quoted string. `+`Use (${helperName} … "${bare}") instead of (${helperName} … ${bare})`,node,{helperName,expected:'StringLiteral (e.g. "property")',actual:`PathExpression (${bare})`});return{type:"array"}}if(propertyExpr.type==="StringLiteral"){propertyName=propertyExpr.value}if(!propertyName){addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "property" expects a quoted string literal, but got ${propertyExpr.type}`,node,{helperName,expected:'StringLiteral (e.g. "property")',actual:propertyExpr.type});return{type:"array"}}const propertySchema=resolveSchemaPath(effectiveItemSchema,[propertyName]);if(!propertySchema){const availableProperties=getSchemaPropertyNames(effectiveItemSchema);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",createPropertyNotFoundMessage(propertyName,availableProperties),node,{path:propertyName,availableProperties});return{type:"array"}}return{type:"array",items:propertySchema}}function getBlockArgument(stmt){return stmt.params[0]}function getBlockHelperName(stmt){if(stmt.path.type==="PathExpression"){return stmt.path.original}return""}function getExpressionName(expr){if(expr.type==="PathExpression"){return expr.original}return""}function addDiagnostic(ctx,code,severity,message,node,details){const diagnostic={severity,code,message};if(node&&"loc"in node&&node.loc){diagnostic.loc={start:{line:node.loc.start.line,column:node.loc.start.column},end:{line:node.loc.end.line,column:node.loc.end.column}};diagnostic.source=extractSourceSnippet(ctx.template,diagnostic.loc)}if(details){diagnostic.details=details}ctx.diagnostics.push(diagnostic)}function schemaTypeLabel(schema){if(schema.type){return Array.isArray(schema.type)?schema.type.join(" | "):schema.type}if(schema.oneOf)return"oneOf(...)";if(schema.anyOf)return"anyOf(...)";if(schema.allOf)return"allOf(...)";if(schema.enum)return"enum";return"unknown"}export{inferBlockType};
2
2
  //# sourceMappingURL=analyzer.js.map