@sensorup/sustudio 42.25.2 → 42.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/sustudio.mjs +4 -2
package/sustudio.mjs CHANGED
@@ -69,7 +69,7 @@ ${code2}`:code2:"",F=Function,factoryCode=`return (input) => {
69
69
  ${code2}
70
70
  }`,fn;try{fn=new F(...constantNames,factoryCode)(...constantValues)}catch(err2){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err2.message})`)}return options?.debug&&(fn.code=fullCode),fn.definite=ctx.definite,fn}function addConstant(ctx,value2){for(let[name3,v]of ctx.constants)if(v===value2)return name3;let name2=`c${ctx.constantCounter++}`;return ctx.constants.set(name2,value2),name2}function addUserConstant(ctx,fn){return ctx.definite=!1,addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value2){let result=schema._zod.run({value:value2,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=!0){let contentLen=doc.content.length,constantCount=ctx.constants.size,constantCounter=ctx.constantCounter,varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err2){if(!(err2 instanceof ZodCompileUnsupportedError)||!err2.islandable)throw err2;if(doc.content.length=contentLen,ctx.constants.size>constantCount){let trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(let k of trailing)ctx.constants.delete(k)}return ctx.constantCounter=constantCounter,ctx.varCounter=varCounter,emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=!1;let schemaConst=addConstant(ctx,schema),runConst=addConstant(ctx,runtimeRun),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){let schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(let check2 of schemaChecks){let def=check2._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check))throw new ZodCompileUnsupportedError('check with a custom "when" condition');switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{let min=numericOperand(def.minimum,"min_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{let max2=numericOperand(def.maximum,"max_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max2}`);doc.write(`if (${len} > ${max2}) return INVALID;`);break}case"length_equals":{let exact=numericOperand(def.length,"length_equals"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check2,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{let newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor),currentAccessor=newAccessor;break}default:throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){let cpLen=addConstant(ctx,codePointLength),v=newVar(ctx);return doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`),v}function numericOperand(value2,label){if(typeof value2!="number"||!Number.isFinite(value2))throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value2}`);return`${value2}`}function comparisonOperand(ctx,value2){if(typeof value2=="bigint")return`${value2}n`;if(typeof value2=="number"){if(Number.isNaN(value2))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value2}`}if(value2 instanceof Date){if(Number.isNaN(value2.getTime()))throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound");return addConstant(ctx,value2)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value2}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){let op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){let op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value=="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{let remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){let format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`number format ${format}`)}}function generateBigIntFormatCheck(doc,def,accessor){let format=def.format;if(format)switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}function generateMimeTypeCheck(doc,ctx,def,accessor){let mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){let mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when)throw new ZodCompileUnsupportedError('check with a custom "when" condition');doc.write(`if (${accessor} == null) return INVALID;`);let shape=def.shape;for(let key of Reflect.ownKeys(shape)){let keyExpr=typeof key=="symbol"?addConstant(ctx,key):esc(key),inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`),compileChild(doc,ctx,shape[key],inputVar,!1)}}function generatePropertyCheck(doc,ctx,def,accessor){let propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor){let tx=check2._zod.def.tx;if(!tx)throw new ZodCompileUnsupportedError("overwrite check without a transform function");if(isAsyncFunction(tx))throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported");let txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue2){this.issues.push(issue2)}function generateCustomRefineCheck(doc,ctx,check2,accessor){let def=check2._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);return doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`),accessor}if(check2._zod.check){if(isAsyncFunction(check2._zod.check))throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported");let checkFn=check2._zod.check,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue};return checkFn(fakePayload)instanceof Promise&&throwAsync(),fakePayload.issues.length===0?fakePayload.value:INVALID}),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${helperConst}(${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=!0){let fmt=def.format;if(fmt==="base64"){let validator=addConstant(ctx,isValidBase64);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="base64url"){let validator=addConstant(ctx,isValidBase64URL);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="jwt"){let validator=addConstant(ctx,isValidJWT),alg=addConstant(ctx,def.alg??null);return doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`),accessor}if(fmt==="ipv6"){let validator=addConstant(ctx,isValidIPv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="cidrv6"){let validator=addConstant(ctx,isValidCIDRv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="credit_card"){let validator=addConstant(ctx,isValidCreditCard);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="iban"){let validator=addConstant(ctx,isValidIBAN);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}let formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==void 0||formatDef.protocol!==void 0){let parseConst=addConstant(ctx,validateURL),defConst=addConstant(ctx,def),trimVar=newVar(ctx),urlVar=newVar(ctx);if(doc.write(`const ${trimVar} = ${accessor}.trim();`),doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`),doc.write(`if (typeof ${urlVar} === "number") return INVALID;`),formatDef.hostname!==void 0){let hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==void 0){let protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;let outputVar=newVar(ctx),outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;return doc.write(`const ${outputVar} = ${outputExpr};`),outputVar}let customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);let fnConst=addConstant(ctx,customFn);return doc.write(`if (!${fnConst}(${accessor})) return INVALID;`),accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){let patternConst=addConstant(ctx,def.pattern);return doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`),accessor}let format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{let prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{let suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:throw new ZodCompileUnsupportedError(`string format ${format}`)}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=!0){let def=schema._zod.def,type=def.type;if(def.coerce)throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`);let buildsValue=needsValue||!!def.checks?.length,typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;"),typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{let innerOut=generateWrapperCheck(doc,ctx,schema,accessor),frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`),typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor),typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:throw new ZodCompileUnsupportedError(`schema type ${type}`)}return typeAccessor===null?null:generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=!0){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let def=schema._zod.def;return def.format===void 0?accessor:generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);let def=schema._zod.def;return def.check==="number_format"&&def.format&&generateNumberFormatCheck(doc,{format:def.format},accessor),accessor}function generateBooleanCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`),accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);let def=schema._zod.def;if(def.format)switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}return accessor}function generateSymbolCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`),accessor}function generateUndefinedCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNullCheck(doc,accessor){return doc.write(`if (${accessor} !== null) return INVALID;`),accessor}function generateVoidCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNaNCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`),accessor}function generateDateCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`),accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);let shape=def.shape,keys=Object.keys(shape),symbolKeys=Object.getOwnPropertySymbols(shape),allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys,keyExpr=k=>typeof k=="symbol"?addConstant(ctx,k):esc(k),propKey=k=>typeof k=="symbol"?`[${keyExpr(k)}]`:esc(k),propShape=shape;if(keys.includes("__proto__"))throw new ZodCompileUnsupportedError('object shape key "__proto__"');let propOutputs=new Map;for(let key of allKeys){let propSchema=propShape[key],kx=keyExpr(key),inputVar=newVar(ctx);if(doc.write(`const ${inputVar} = ${accessor}[${kx}];`),propSchema._zod.optin!==void 0){let outputVar2=newVar(ctx);doc.write(`let ${outputVar2} = (() => {`),doc.indented(d=>{let outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)}),doc.write("})();"),propSchema._zod.optout==="optional"?(doc.write(`if (${outputVar2} === INVALID) {`),doc.indented(d=>{d.write(`if (${kx} in ${accessor}) return INVALID;`),d.write(`${outputVar2} = undefined;`)}),doc.write("}")):doc.write(`if (${outputVar2} === INVALID) return INVALID;`),propOutputs.set(key,outputVar2)}else{requiresPresenceCheck(propSchema)&&doc.write(`if (!(${kx} in ${accessor})) return INVALID;`);let outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);outputAccessor!==null&&propOutputs.set(key,outputAccessor)}}let catchall=def.catchall,unknownKeysMode="none";if(catchall){let catchallType=catchall._zod.def.type;if(catchallType==="never"){let condition=keys.map(k=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write(`if (${condition}) return INVALID;`)}),doc.write("}")}else(catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length?unknownKeysMode="passthrough":unknownKeysMode="schema"}let outputVar=newVar(ctx),hasConditionalKeys=allKeys.some(k=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`);let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`),compileChild(d,ctx,catchall,valVar,!1)}),doc.write("}")}return null}if(hasConditionalKeys){doc.write(`const ${outputVar} = {};`);for(let k of allKeys){let kx=keyExpr(k),out=propOutputs.get(k);dropsWhenAbsent(propShape[k])?doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):mayOmitUndefined(propShape[k])?doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):doc.write(`${outputVar}[${kx}] = ${out};`)}}else{let propLiterals=allKeys.map(k=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}if(unknownKeysMode!=="none"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{if(d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`),unknownKeysMode==="passthrough")d.write(`${outputVar}[k] = ${accessor}[k];`);else{let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);let catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}}),doc.write("}")}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;if(isExactOptional(schema))return generateCheck(doc,ctx,def.innerType,accessor,buildsValue);if(def.innerType._zod.optin==="defaulted"){let outputVar2=newVar(ctx),branchVar=newVar(ctx);return doc.write(`let ${outputVar2};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`const ${branchVar} = (() => {`),d.indented(d2=>{let innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)}),d.write("})();"),d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar2} = ${innerOutput};`)}),doc.write("}"),outputVar2}let outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===!0}function requiresPresenceCheck(schema){return schema._zod.optin===void 0&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return!0;let def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):!0;case"catch":return!0;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):!0;case"intersection":return!def.left||!def.right?!0:fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):!0;default:return!0}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){let def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):!0;case"union":return def.options?def.options.some(mayOutputUndefined):!0;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):!0;default:return!0}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def,outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar} = null;`),doc.write(`if (${accessor} !== null) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function generateSizeGate(doc,schema,size){for(let[max2,check2]of sizeCaps(schema._zod.def.checks))doc.write(`if (${size} > ${numericOperand(max2,check2._zod.def.check)}) return INVALID;`)}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.length`);let outputVar=buildsValue?newVar(ctx):null,iVar=newVar(ctx),elemVar=newVar(ctx);return outputVar&&doc.write(`const ${outputVar} = new Array(${accessor}.length);`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);outputVar&&elemOutput!==null&&d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}"),outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){let values2=schema._zod.def.values;if(values2.length!==1){let literalSet=addConstant(ctx,new Set(values2));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}let value2=values2[0];if(typeof value2=="number"&&Number.isNaN(value2)){let literalSet=addConstant(ctx,new Set(values2));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}if(typeof value2=="string")doc.write(`if (${accessor} !== ${esc(value2)}) return INVALID;`);else if(typeof value2=="number"||typeof value2=="boolean")doc.write(`if (${accessor} !== ${value2}) return INVALID;`);else if(value2===null)doc.write(`if (${accessor} !== null) return INVALID;`);else if(value2===void 0)doc.write(`if (${accessor} !== undefined) return INVALID;`);else if(typeof value2=="bigint")doc.write(`if (${accessor} !== ${value2}n) return INVALID;`);else throw new ZodCompileUnsupportedError(`literal type ${typeof value2}`);return accessor}function generateEnumCheck(doc,ctx,schema,accessor){let values2=schema._zod.values;if(!values2)throw new ZodCompileUnsupportedError("enum schema without enumerated values");let enumSet=addConstant(ctx,values2);return doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`),accessor}function generateWrapperCheck(doc,ctx,schema,accessor){let def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){let def=schema._zod.def,defaultGetter=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue")?()=>schema._zod.def.defaultValue:void 0;if(schema._zod.def.type==="prefault"){if(!defaultGetter)return generateCheck(doc,ctx,def.innerType,accessor);let defaultFn=addConstant(ctx,defaultGetter),inputVar=newVar(ctx);return doc.write(`let ${inputVar} = ${accessor};`),doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`),generateCheck(doc,ctx,def.innerType,inputVar)}let outputVar=newVar(ctx);if(defaultGetter){let defaultFn=addConstant(ctx,defaultGetter),cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)}),doc.write("}")}else doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}");return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){let def=schema._zod.def,innerOutput=generateCheck(doc,ctx,def.innerType,accessor),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${innerOutput};`),doc.write(`if (${outputVar} === undefined) return INVALID;`),outputVar}function generateTupleCheck(doc,ctx,schema,accessor){let def=schema._zod.def,items=def.items,rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);let optinStart=getTupleOptStart2(items,"optin"),optoutStart=getTupleOptStart2(items,"optout");rest?doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`):doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`);let outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i2=0;i2<items.length;i2++){let itemSchema=items[i2];if(i2>=optoutStart)doc.write(`if (${outputVar}.length === ${i2}) {`),doc.indented(d=>{d.write(`if (${i2} < ${accessor}.length) {`),d.indented(d2=>{let elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i2}];`);let elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i2}] = ${elemOutput};`)}),d.write("} else {"),d.indented(d2=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i2};`);return}let elemVar=newVar(ctx),branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`),d2.write(`const ${branchVar} = (() => {`),d2.indented(d3=>{let elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)}),d2.write("})();"),d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i2};`),d2.write(`else ${outputVar}[${i2}] = ${branchVar};`)}),d.write("}")}),doc.write("}");else{let elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i2}];`);let elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i2}] = ${elemOutput};`)}}if(rest){let iVar=newVar(ctx),elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}")}return outputVar}function getTupleOptStart2(items,key){for(let i2=items.length-1;i2>=0;i2--)if(!(key==="optin"?items[i2]._zod.optin!==void 0:items[i2]._zod.optout==="optional"))return i2+1;return 0}function generateUnionCheck(doc,ctx,schema,accessor){let def=schema._zod.def,options=def.options;if(def.discriminator)return generateDiscriminatedUnionCheck(doc,ctx,def,accessor);if(def.inclusive===!1)throw new ZodCompileUnsupportedError("exclusive unions (z.xor)");if(options.length===0)return doc.write("return INVALID;"),accessor;if(options.length===1)return generateCheck(doc,ctx,options[0],accessor);if(options.every(opt=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length)){let values2=new Set(options.flatMap(opt=>opt._zod.def.values)),valuesConst=addConstant(ctx,values2);return doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`),accessor}let outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i2=0;i2<options.length;i2++){let opt=options[i2];i2===0?doc.write(`${outputVar} = (() => {`):doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)}),doc.write("})();")}return doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback)throw new ZodCompileUnsupportedError("discriminated union with unionFallback");if(def.options.length===0)return doc.write("return INVALID;"),accessor;let discVar=newVar(ctx),outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`),doc.write(`let ${outputVar};`);let firstBranch=!0,claimed=new Set;for(let option of def.options){let values2=option._zod.propValues?.[def.discriminator];if(!values2||values2.size===0)throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values");for(let value2 of values2){if(claimed.has(value2))throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value2)}`);claimed.add(value2)}let conditions=Array.from(values2,value2=>literalEquality(ctx,discVar,value2)),prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)}),doc.write("}"),firstBranch=!1}return doc.write("else { return INVALID; }"),outputVar}function literalEquality(ctx,accessor,value2){if(typeof value2=="string")return`${accessor} === ${esc(value2)}`;if(typeof value2=="number")return Number.isNaN(value2)?`Number.isNaN(${accessor})`:`${accessor} === ${value2}`;if(typeof value2=="boolean")return`${accessor} === ${value2}`;if(value2===null)return`${accessor} === null`;if(value2===void 0)return`${accessor} === undefined`;if(typeof value2=="bigint")return`${accessor} === ${value2}n`;if(typeof value2=="symbol"){let symbolConst=addConstant(ctx,value2);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value2)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){let def=schema._zod.def;ctx.definite=!1;let leftOutput=compileChild(doc,ctx,def.left,accessor),rightOutput=compileChild(doc,ctx,def.right,accessor),mergeConst=addConstant(ctx,mergeValues),mergedVar=newVar(ctx);return doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`),doc.write(`if (!${mergedVar}.valid) return INVALID;`),`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){let def=schema._zod.def,isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);let recordDef=def,keyValues=recordDef.partial?void 0:def.keyType._zod.values;if(keyValues){let inputKeys=[];for(let key of keyValues){if(!(typeof key=="string"||typeof key=="number"||typeof key=="symbol"))throw new ZodCompileUnsupportedError(`record key value ${String(key)}`);let inputKey=typeof key=="number"?key.toString():key;if(inputKey==="__proto__")throw new ZodCompileUnsupportedError('record key "__proto__"');inputKeys.push(inputKey);let keyConst=addConstant(ctx,key),outKey=generateCheck(doc,ctx,def.keyType,keyConst),valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);let valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}let knownKeysConst=addConstant(ctx,new Set(inputKeys));return doc.write(`for (const ${kVar} in ${accessor}) {`),doc.indented(d=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`),recordDef.mode==="loose"?d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`):d.write("return INVALID;")}),doc.write("}"),outputVar}let keyDef=def.keyType._zod.def;if(!(keyDef.type==="string"&&keyDef.format===void 0&&!keyDef.coerce&&(keyDef.checks?.length??0)===0)){let isLoose=def.mode==="loose",keyFn=compileFn(def.keyType);keyFn.definite===!1&&(ctx.definite=!1);let keyFast=addConstant(ctx,keyFn),numericConst=addConstant(ctx,number),outKeyVar=newVar(ctx);return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`),d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`),isLoose?d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`):d.write(`if (${outKeyVar} === INVALID) return INVALID;`),d.write(`if (${outKeyVar} === "__proto__") continue;`);let valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)}),outputVar}return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},"return INVALID;"),outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){let propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable),symsVar=newVar(ctx),keysVar=newVar(ctx),iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`),doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`),d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),body(d)}),doc.write("}"),doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`),d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),onSymbol?d.write(onSymbol):body(d)}),doc.write("}")}function literalPropertyKey(ctx,key){return typeof key=="string"?esc(key):addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Map();`),doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`),doc.indented(d=>{let keyOutput=generateCheck(d,ctx,def.keyType,kVar),valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)}),doc.write("}"),outputVar}function generateSetCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Set();`),doc.write(`for (const ${valVar} of ${accessor}) {`),doc.indented(d=>{let valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)}),doc.write("}"),outputVar}function generateFileCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof File)) return INVALID;`),accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let pattern=schema._zod.pattern;if(pattern){let patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){let def=schema._zod.def,getterConst=addUserConstant(ctx,def.getter),cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`),doc.indented(d=>{d.write(`const inner = ${getterConst}();`),d.write(`${cacheConst}.parser = function(input) {`),d.indented(d2=>{d2.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),d2.write("return result.issues.length === 0 ? result.value : INVALID;")}),d.write("};")}),doc.write("}");let outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generatePipeCheck(doc,ctx,schema,accessor){let def=schema._zod.def,inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue},result=transformFn(value2,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),transformedVar=newVar(ctx);return doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`),doc.write(`if (${transformedVar} === INVALID) return INVALID;`),generateCheck(doc,ctx,def.out,transformedVar)}else return generateCheck(doc,ctx,def.out,inputOutput)}function isAsyncFunction(fn){return typeof fn=="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`)}else throw new ZodCompileUnsupportedError("custom schema without a predicate function");return accessor}function runtimeCatch(innerSchema,catchValue,value2){let result=innerSchema._zod.run({value:value2,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r=result;return r.issues.length===0?r.value:catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH])throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",!1);let outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`),doc.indented(d=>{let innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)}),doc.write("})();");let innerConst=addConstant(ctx,def.innerType),catchConst=addUserConstant(ctx,def.catchValue),catchHelperConst=addConstant(ctx,runtimeCatch);return doc.write(`if (${outputVar} === INVALID) {`),doc.indented(d=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`),d.write(`if (${outputVar} === INVALID) return INVALID;`)}),doc.write("}"),outputVar}function generateTransformCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue},result=transformFn(value2,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${helperConst}(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}return accessor}function snapshotChecks(def){return def.checks&&(def.checks=[...def.checks]),def}function _string(Class2,params){return new Class2(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class2,params){return new Class2(snapshotChecks({type:"string",coerce:!0,...normalizeParams(params)}))}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _creditCard(Class2,params){return new Class2({type:"string",format:"credit_card",check:"string_format",abort:!1,...normalizeParams(params)})}function _iban(Class2,params){return new Class2({type:"string",format:"iban",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class2,params){return new Class2(snapshotChecks({type:"number",coerce:!0,checks:[],...normalizeParams(params)}))}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value2,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value:value2,inclusive:!1})}function _lte(value2,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value:value2,inclusive:!0})}function _gt(value2,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value:value2,inclusive:!1})}function _gte(value2,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value:value2,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value2,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value:value2})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input2=>input2.normalize(form))}function _trim(){return _overwrite(input2=>input2.trim())}function _toLowerCase(){return _overwrite(input2=>input2.toLowerCase())}function _toUpperCase(){return _overwrite(input2=>input2.toUpperCase())}function _slugify(){return _overwrite(input2=>slugify(input2))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new Class2({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value2,params){return new Class2({type:"literal",values:Array.isArray(value2)?value2:[value2],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn){return new Class2({type:"transform",transform:fn})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn,...norm})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch2=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch2._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=ch2),_issue.continue??(_issue.continue=!ch2._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch2}function _check(fn,params){let ch2=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch2._zod.check=fn,ch2}function describe(description){let ch2=new $ZodCheck({check:"describe"});return ch2._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch2._zod.check=()=>{},ch2}function meta(metadata){let ch2=new $ZodCheck({check:"meta"});return ch2._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch2._zod.check=()=>{},ch2}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];params.case!=="sensitive"&&(truthyArray=truthyArray.map(v=>typeof v=="string"?v.toLowerCase():v),falsyArray=falsyArray.map(v=>typeof v=="string"?v.toLowerCase():v));let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,_String=Classes.String??$ZodString,stringSchema=new _String({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec2=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:((input2,payload)=>{let data=input2;return params.case!=="sensitive"&&(data=data.toLowerCase()),truthySet.has(data)?!0:falsySet.has(data)?!1:(payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec2,continue:!1}),{})}),reverseTransform:((input2,_payload)=>input2===!0?truthyArray[0]||"true":falsyArray[0]||"false"),error:params.error});return codec2._zod.bag.truthy=truthyArray,codec2._zod.bag.falsy=falsyArray,codec2._zod.bag.case=params.case??"insensitive",codec2}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={check:"string_format",type:"string",format,fn:typeof fnOrRegex=="function"?fnOrRegex:val=>fnOrRegex.test(val),...params};return fnOrRegex instanceof RegExp&&(def.pattern=fnOrRegex),new Class2(def)}function assignProps(target,...sources){for(let source of sources)for(let key of Reflect.ownKeys(source))Object.prototype.propertyIsEnumerable.call(source,key)&&assignProp(target,key,source[key]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema,ctx,json2,params,message){let result=typeof ctx.unrepresentable=="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw new Error(message);return Object.assign(json2,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a4;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||(result.ref=parent),processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta3=ctx.metadataRegistry.get(schema);return meta3&&assignProps(result.schema,meta3),ctx.io==="input"&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a4=result.schema).default??(_a4.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
71
71
 
72
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part2=other.properties?.[key]??undeclaredConstraint(other);part2!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part2))||parts.push(part2))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded2={type:"object",properties};if(required2.size&&(folded2.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded2.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded2.additionalProperties=constraints[0]:constraints.length>1&&(folded2.additionalProperties={allOf:constraints})}return folded2}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded2=null;if(!unions.length)folded2=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded2={[keyword]:branches}}folded2&&(delete json2.allOf,assignProps(json2,folded2))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value2)=>{(agg[key]===void 0||value2>agg[key])&&(agg[key]=value2)},narrowMax=(agg,key,value2)=>{(agg[key]===void 0||value2<agg[key])&&(agg[key]=value2)},narrowBoth=(agg,value2)=>{narrowMin(agg,"minimum",value2),narrowMax(agg,"maximum",value2)},addDivisor=(agg,value2)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value2)||agg.multipleOf.push(value2)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch2 of list)contributors[ch2._zod.def.check]?.(agg,ch2._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,(format==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values2=getEnumValues(def.entries);if(values2.length===0){json2.not={};return}values2.every(v=>typeof v=="number")&&(json2.type="number"),values2.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values2},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key in shape)assignProp(json2.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i2]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,prefixPath,i2]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i2)=>branch!==branches[i2])&&(json2={...json2,[keyword]:mapped})}let types=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types.includes("string")&&types.some(t2=>t2==="number"||t2==="integer"),values2=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values2?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values2||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending2=pendingRecords.get(ctx);pending2||(pending2=[],pendingRecords.set(ctx,pending2),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending2.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value2,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value2,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2.default=value2)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value2)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input2,params){if("_idmap"in input2){let registry2=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value2){this.ctx.counter=value2}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}};var json_schema_exports={};var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value2=make(this);return Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0}),value2},set(value2){Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch2=>typeof ch2=="function"?{_zod:{check:ch2,def:{check:"custom"},onattach:[]}}:ch2)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value2){util_exports.own(this,"~standard",value2)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value2){util_exports.own(this,"spa",value2)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value2,params){return this.check(_gt(value2,params))},gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))},step(value2,params){return this.check(_multipleOf(value2,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},gt(value2,params){return this.check(_gt(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value2,params)=>inst.check(_gte(value2,params)),inst.max=(value2,params)=>inst.check(_lte(value2,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values2,params)=>{let newEntries={};for(let value2 of values2)if(keys.has(value2))newEntries[value2]=def.entries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values2,params)=>{let newEntries={...def.entries};for(let value2 of values2)if(keys.has(value2))delete newEntries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum2(values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value2,params){return new ZodLiteral({type:"literal",values:Array.isArray(value2)?value2:[value2],...util_exports.normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){let ch2=new $ZodCheck({check:"custom"});return ch2._zod.check=fn,ch2}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path3=ref.slice(1).split("/").filter(Boolean);if(path3.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path3[0]===defsKey){let key=path3[1]===void 0?void 0:decodeJSONPointerSegment(path3[1]);if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value2=>value2).check(payload=>{let value2=payload.value;if(typeof value2!="object"||value2===null||Array.isArray(value2))return;let keys=Object.getOwnPropertyNames(value2);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.keySchema)for(let key of keys){let result=guards.keySchema.safeParse(key);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value2,seen){if(value2===null)return"z";let type=typeof value2;if(type!=="object"){if(type==="number"&&Number.isNaN(value2))return null;let raw=String(value2);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value2))return null;seen.add(value2);try{if(Array.isArray(value2)){let parts2=[];for(let item of value2){let key=canonicalKey(item,seen);if(key===null)return null;parts2.push(key)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value2).sort(),parts=[];for(let k of keys){let key=canonicalKey(value2[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value2)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value2){return typeof value2!="object"||value2===null?!1:Array.isArray(value2)?value2.some(containsRef):typeof value2.$ref=="string"?!0:Object.entries(value2).some(([key,sub])=>SCHEMA_KEYWORDS.has(key)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value2=>value2).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i2=0;i2<items.length;i2++){let key=canonicalKey(items[i2],new Set);if(key===null)continue;let first=firstSeen.get(key);if(first===void 0){firstSeen.set(key,i2);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i2} duplicates the one at index ${first}`,input:items,path:[i2],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break;matches<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t2=>{let typeSchema={...schema,type:t2};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z.uuid()):format==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format==="date"?stringSchema=stringSchema.check(z.iso.date()):format==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format==="hostname"?stringSchema=stringSchema.check(z.hostname()):format==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format==="mac"?stringSchema=stringSchema.check(z.mac()):format==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z.base64()):format==="base64url"?stringSchema=stringSchema.check(z.base64url()):format==="e164"?stringSchema=stringSchema.check(z.e164()):format==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format==="iban"?stringSchema=stringSchema.check(z.iban()):format==="jwt"?stringSchema=stringSchema.check(z.jwt()):format==="emoji"?stringSchema=stringSchema.check(z.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z.ulid()):format==="xid"?stringSchema=stringSchema.check(z.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i2=2;i2<schemasToIntersect.length;i2++)result=z.intersection(result,schemasToIntersect[i2]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject(payload.value))return;let unrecognized=[];for(let key of Object.keys(payload.value))propertyKeys.includes(key)||patterns.some(regex=>regex.test(key))||unrecognized.push(key);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i2=startIdx;i2<schema.allOf.length;i2++)result=z.intersection(result,convertSchema(schema.allOf[i2],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key of["minProperties","maxProperties"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key of["uniqueItems","minContains","maxContains"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||assignProp(extraMeta,key,schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache=new Map;function run(s){let cached2=cache.get(s);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)});if(cached2!==void 0)return cached2;cache.set(s,RESOLVING);let inner=mapInner(s),mapped=fn(inner,inner!==s);return cache.set(s,mapped),mapped}function mapInner(s){let def=s._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{let mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return run(schema)}function deepPartial(schema){return visit(schema,{object:s=>s.partial(),union:s=>{let def=s._zod.def;return def.discriminator===void 0?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:s=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var UNSTAMPED_ARTIFACT_VERSION="0.0.0-unstamped",resolveArtifactVersion=stamped=>{let trimmed=stamped?.trim();return trimmed===void 0||trimmed===""?UNSTAMPED_ARTIFACT_VERSION:trimmed},FORGE_ARTIFACT_VERSION=resolveArtifactVersion("42.25.2"),UNSTAMPED_BUILD_DETAIL="this process carries no build stamp, so it is NOT a packaged extension \u2014 it is a dev checkout, or a build made without FORGE_ARTIFACT_VERSION set. An installed extension always reports a real version here; for one that does not, read it from the desktop app under Settings \u2192 Extensions \u2192 this extension \u2192 Details.",artifactBuildReport=(options={})=>{let version2=options.version??FORGE_ARTIFACT_VERSION,stamped=version2!==UNSTAMPED_ARTIFACT_VERSION;return{...options.module===void 0?{}:{module:options.module},version:version2,stamped,...stamped?{}:{detail:UNSTAMPED_BUILD_DETAIL}}};var CONTRACT_DESCRIPTIONS=Object.freeze({assets:{list:"Every asset visible to the caller's tenant as a bare `AssetRef` \u2014 an `assetId` and nothing else. This is the cross-domain reference list, the shape another domain holds to point at an asset. It takes no input, accepts no filter, and does not page. For the asset rows themselves \u2014 name, type, status, filters, paging \u2014 call `crud.list` instead.",snapshot:"The domain's snapshot mint \u2014 the ONE polymorphic mint the platform convention gives every snapshot-referable domain. An idempotent DERIVATION, not a Record-writing verb: `tenantRead`, writes nothing, never a composition step. Output is the platform kernel `EntitySnapshotRef` verbatim; an unsupported `type` refuses at parse through the ask's enum.\n\nA NOOP mint over the version row: `snapshot` := the asset's CURRENT version row id, the same value the display resolver honours on a ref's `version`. Asset version rows are append-only, so the value denotes frozen content by construction.\n\nRefuses the declared `NOT_FOUND` for an id that names no live asset \u2014 unknown, malformed, soft-deleted, or another tenant's.","crud.create":"Create an asset under a type whose template validates its properties.","crud.get":'Fetch one version of an asset by `assetId`. Optional `asOf` selects the version effective at that instant (half-open `effectiveFrom <= asOf < effectiveTo`); absent \u2192 the current version. No version effective then (pre-creation / post-soft-delete) \u2192 NOT_FOUND. As of an instant, `properties` are the merged values then: a dated value covering the instant replaces the version\'s (a dated "no value" removes the key), and `appliedDatedValueIds` names each one taken. Optional `knownAt` replays that read as known then: only dated values recorded by then and not retired by then; versions read as stored. A future `knownAt` is refused at parse; one without `asOf` is BAD_REQUEST (`data.code = KNOWN_AT_WITHOUT_AS_OF`).',"crud.list":"List assets with filters + offset/limit pagination. Optional `asOf` mirrors `get`'s point-in-time semantics: every returned row (and `total`) is the version effective at that instant, its `properties` merged with the dated values covering the instant and named in `appliedDatedValueIds`, property filters and conditions reading the merged values; absent \u2192 the CURRENT population, byte-identical to the pre-existing current-population call. `knownAt` replays an as-of page, its count and its filters as known then, as `get`'s does. Refused together with `hasGeometry` (BAD_REQUEST naming both) \u2014 a spatial capability read has no past-instant notion.\n\n`categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the temporal window applies to asset VERSIONS, not to which types currently exist. A past `asOf` naming a category whose type has SINCE been deleted silently omits assets of that type; `assetTypeIds` names concrete governed ids directly and is unaffected.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422) when the read outlived the request's transaction budget \u2014 a big selection or a busy system; a `nameContains` or `search` text reads every asset the tenant holds, and so does a property or external-ID condition alone. `data.budgetMs` is the budget. Narrow the list (an id, a type, category or lifecycle filter), or retry once the system is quieter.\n\n`conditions`: operator conditions over asset fields, properties and external IDs, combined by All or Any and ANDed with every other filter. A condition its field cannot honour is refused `INVALID_CONDITION` (400, `data.index` names the row) before anything is read. The selection-taking verbs (`count`, the bulk relationship writes) and the export do NOT take it: sending it there is refused.\n\n`search`: the search box. An asset matches when its name contains the trimmed text (any case) OR it holds a current external ID, in any system, that equals it exactly (case-sensitive, no numeric coercion, the `ext:` `is` rule); `%`, `_` and `\\` are literal in the name. ANDed with every other filter and honoured at `asOf`; `nameContains` is unchanged and name-only. Unlike `conditions`, `search` IS part of the selection, so `count`, the bulk relationship writes and the export take it and describe the set the box found. When a request carries `search`, the output's `matchedExternalIds` names, for each row on the page found by an external ID and not by its name, the binding that matched.","crud.distinctValues":"The values a condition FIELD holds on the assets a list filter selects, with the number of those assets holding each \u2014 what a person picks from instead of guessing a value. `tenantRead`: writes nothing, records nothing.\n\n`{ field, filter, prefix?, limit? }`: `field` is a condition field (`asset:status`, `prop:<code>`, `ext:<system>` / `ext:*`,...), `filter` the rest of the list filter verbatim (`asOf` included), `prefix` a case-insensitive literal prefix, `limit` 1..20 (default 20). Most common first, then by value; a response of exactly `limit` entries may have more, and there is no next page. Values `is` treats as one (case, a number and \"42\") are one entry, the most common spelling, counted over the whole group; external IDs group exactly. `count` counts assets, once each.\n\n`prefix` is REQUIRED for `asset:name` and `ext:` fields (about one value per asset): without one the read is refused `INVALID_CONDITION` (`reason: 'prefix-required'`).\n\n`values` asks instead for EXACT counts of up to 20 listed values of a `prop:` field \u2014 JSON-typed and case-exact, the `propertyFilters` equality \u2014 so one read tells a caller which values of a `oneOf` / `noneOf` list no selected asset holds (they are absent). Any other field, or a `prefix` beside it, is refused `INVALID_CONDITION` (`reason: 'values-not-allowed'`).\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the scan outlived the budget \u2014 a property or external-ID field over a whole tenant reads every asset; narrow the filter by a type or category first.","crud.index":"A LEAN sibling of `list` \u2014 the SAME filters MINUS `asOf`, plus a REQUIRED `fields` projection. Listing 129 facilities over `list` returned 92,061 characters \u2014 every property of every asset \u2014 when the caller needed only `{name, assetId}`. `locations` below was already built as exactly this lean-sibling shape for the map read; this generalizes the pattern to an arbitrary field selection.\n\nPROJECTS AFTER THE FETCH, never a second query \u2014 the `locations` precedent: `list` runs unchanged, then each row is narrowed to the requested fields in JS. `assetId` is ALWAYS present regardless of `fields` \u2014 a caller listing assets needs an id to act on any of them, the same implicit guarantee `list`/`locations` make.\n\nThe output item type is one flat object DERIVED from `AssetSchema` \u2014 every field optional except the always-present `assetId` \u2014 not a shape that varies with the selection. A per-selection output would have no single OpenAPI rendering for a non-TS consumer to code against, and a hand-authored parallel shape could drift from `AssetSchema`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list` \u2014 it IS `list` \u2014 when the read outlived the request's transaction budget. `INVALID_CONDITION`, exactly as `list`: a `conditions` row its field cannot honour is refused, naming the row, before anything is read.","crud.count":"HOW MANY assets a predicate matches, in ONE query with NO pagination \u2014 plus, optionally, a capped SAMPLE of matching ids in the same round trip. `tenantRead`: writes nothing, records nothing, stages nothing.\n\nNOT A MODE OF `list`, and the distinction is the reason it exists. `list` answers \"which slice do I show\" and carries `total` as a rider on the FIRST page only \u2014 a cursor page omits it by design \u2014 so a caller who wants only the number has to either page or reason about which page still carries it. Its first consumer did the former: the calculations authoring scope preview resolved \"resolves N assets\" by paging `list` to exhaustion at 200 ids a page over the cross-domain loopback and taking the array's LENGTH, which measured 132 s at the observed 543,391-asset estate for a number the first page had already counted.\n\n`asOf` mirrors `list`'s point-in-time semantics \u2014 the same half-open `effectiveFrom <= asOf < effectiveTo` window, applied to the same seek-free filter \u2014 so a past-instant count and a past-instant PAGE of one predicate always describe the same population. ABSENT \u2192 the CURRENT population. Refused together with `selection.hasGeometry`, exactly as `list` refuses the pair and for the same reason.\n\n`selection.categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the same caveat `list` carries, inherited rather than restated, because this IS `list`'s count.\n\nThe sample is drawn from the first page of `list`'s own default order (name ascending, `assetId`-tiebroken). It is a SAMPLE, not a page: there is no cursor and no way to ask for the next one. For rows, call `list`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the count outlived the request's transaction budget.","crud.exportEstimate":"Pre-flight an export WITHOUT authorizing one (`tenantRead`): resolve the selection, COUNT it, and report how WIDE the file would be. A count and a column count, never rows.\n\nSTAGES NOTHING, GRANTS NOTHING, RECORDS NOTHING \u2014 call it freely to refuse an over-cap or empty export BEFORE the confirm action. The authorization itself is `export`, which re-resolves on its own and does not trust this answer.\n\n`maxRows` on the answer is the deployment's EFFECTIVE row cap \u2014 the same injected policy the mint enforces. State THAT number in any copy or pre-guard; never bake the assembly default into a client, or a deployment override splits UI-refused from server-granted.\n\n`columnCount` is what makes WIDTH knowable up front \u2014 the file's column set is derived from the data in the selection, so two exports with different filters legitimately differ in width. It is SKIPPED (reported as 0) where `rowCount` already exceeds `maxRows`: an export that will be refused does not pay for column math.\n\n`maxColumns` is the WIDTH cap the mint enforces, echoed for the same reason `maxRows` is: width is the export's second scaling term (peak memory is tile rows \xD7 columns), so a selection can be refused for being too WIDE with a row count well under the cap. State that number in copy too.\n\nAnswers even where the deployment has no export store, because it touches no store.\n\nA count that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `count` is.","crud.exportStatus":"Where ONE authorized export has got to (`tenantRead`, un-recorded).\n\n `pending` \u2192 still building, with an HONEST fraction (`tilesDone` of\n `tilesTotal`) rather than a synthesized percentage, plus the\n row and column counts so a client can keep describing the\n file while it waits.\n `ready` \u2192 the GRANT: `{url, headers, expiresAt, mediaType, filename,\n rowCount}` plus `byteSize`. The URL is presigned FRESH on\n every read, so its lifetime starts when you are told about\n it rather than when the build finished.\n `failed` \u2192 why, in one sentence. A build that stopped making progress\n reports failed rather than pending forever, so a dead worker\n is legible instead of invisible.\n\nONE EXPORT, BY ID \u2014 there is deliberately no list, no paging and no filter. A read that enumerated a tenant's exports would misrepresent a transient movement artifact as a persisted published representation, so an `exportId` you no longer hold names an export you can no longer reach. Another tenant's id resolves to NOT_FOUND exactly as an id that never existed does.","crud.export":'Authorize ONE export of the assets a selection matches (`tenantWrite`, a GOVERNED verb \u2014 every mint leaves an actor-stamped Record naming the SELECTION, its ordering, its scoping and the resolved row count; the pre-flight, the build and the transfer do not).\n\nReturns a HANDLE, not the file and not yet a link: `{exportId, state, rowCount, columnCount, tilesTotal}`. Poll `crud.exportStatus` with that `exportId` for the grant. The build is ASYNCHRONOUS because it measured too slow to hold a request open \u2014 a full-estate export took ~60s unfiltered and ~200s subtree-scoped against a ~60s gateway envelope \u2014 so the mint validates, refuses, records and enqueues, and nothing more.\n\nThe response carries NO bucket, key or other storage location, and the request cannot name one \u2014 a caller-supplied `objectKey`, `bucket`, `prefix` or `tenantId` is refused at parse.\n\nThe file carries EVERYTHING the asset is known by, and the column set is derived from the DATA in the selection rather than from template declarations: the durable `assetId`, the name, resolved category and type names, lifecycle, the validity window, the location as well-known text (the column ABSENT where the deployment has no geometry \u2014 an empty cell would falsely assert "no location"), a `Parent`/`Parent ID` pair for each of the four HIERARCHY relationship types, one `prop.*` column per static property key present, and one `derived.*` column per materialized derived code present. NO column INDEX is stable across exports \u2014 read by header. A blank `derived.*` cell may mean "not rebuilt yet" rather than "no value": that table is a rebuildable projection, not governed history.\n\n`descendantOf` scopes the export to a hierarchy SUBTREE, node-inclusive and DISTINCT on asset id \u2014 the asset graph is a DAG, so one asset can be reachable from two unrelated roots. It exists on THIS input only, never on the shared bulk selection the mutating verbs take.\n\nTHE GRANT IS NOT SINGLE-USE: within its lifetime (`expiresAt`, 900s by default) it may be fetched more than once, and a transfer that begins before expiry completes even if expiry passes mid-stream. Single-use is unenforceable on a signed object-store URL. An expired grant is refused by the store; poll again for a fresh one rather than storing grant URLs. NOTHING ENUMERATES PAST EXPORTS \u2014 `exportStatus` answers about ONE id and there is no list, so a lost `exportId` is a lost export. The sealed Record is the only durable trace.\n\n`idempotencyKey` is REQUIRED, unique per (tenant, caller, key): a mint that times out may well have completed, and the SAME-KEY retry returns the one existing authorization with a FRESH usable grant. A reused key with a different selection or format is refused as `BAD_REQUEST` with `data.code = "KEY_PARAM_MISMATCH"` (another caller\'s key: `data.code = "KEY_ACTOR_MISMATCH"`); `CONFLICT` is reserved for two CONCURRENT mints racing the same key, where the loser retries into the replay.\n\nREFUSALS, declared and ordered: `SERVICE_UNAVAILABLE` with `data.code = "EXPORT_STORE_UNAVAILABLE"` (this deployment has no export store; the pre-flight still answers) \u2192 `FORMAT_UNAVAILABLE` (XLSX is a declared format this capability does not serve yet; ask for CSV) \u2192 `OVER_CAP` with `data.reason = "search-cap"` \u2192 `EMPTY_RESULT` (zero assets; nothing to stage) \u2192 `OVER_CAP` with no `data` (the selection exceeds the deployment\'s row cap; narrow it \u2014 never truncated, never queued, because a silently partial 700,000-row file is more dangerous than a refusal that names the count and the cap) \u2192 `TOO_MANY_COLUMNS` (the selection is too WIDE: the column set is derived from the data, so a selection whose assets carry thousands of distinct property keys scales the file\'s second dimension. `exportEstimate` reports both `columnCount` and `maxColumns`, so this is readable before the confirm).',"crud.locations":"The MAP's read \u2014 located assets under the same filter facets, projected to the three fields a canvas draws (`assetId`, `name`, `geometry`) and capped at a map-scale ceiling rather than the table's 200.\n\nA sibling of `list` rather than a mode of it, for two reasons: the lean projection is what makes the raised ceiling affordable (measured 248 kB vs 681 kB for the same 1,110-asset estate), and it keeps that ceiling off `crud.list`, where no caller needs a page past 200. Unpaged and unordered by construction \u2014 a map has no pager, so a page-2 pin is an invisible pin.\n\nCapability-gated like every geometry surface: a PostGIS-less deployment refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a silent empty canvas. tenantRead in the api wiring. A read that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `list` is.","crud.update":"Full-state-replace update \u2014 a new version row pinning the current template. With `effectiveFrom`, the dated values of each property it changes are replaced from that date onward. A lost race is `CONFLICT` with `data.code = DATED_VALUES_RACE`: nothing was saved, retry.","crud.delete":"Soft-delete \u2014 close the current version, no successor; returns it.\n\n`SERVICE_UNAVAILABLE` with `data.reason: 'deadlock'` is TRANSIENT: a concurrent write to the same assets deadlocked with this one and nothing was written \u2014 retry the same call.","crud.deleteImpact":"Delete-impact PREFLIGHT \u2014 a READ over a bounded batch of assetIds reporting what a delete WOULD hit (hierarchy edges, storage-only edges, live external-ID bindings) + a per-asset verdict (deletable / reparentable / reparentable-too-wide / blocked / not-found). ADVISORY: no lock between preflight and delete \u2014 the delete's own guards stay the authority (TOCTOU by design). `tenantRead`, leaves no Record.","crud.deleteMany":"GOVERNED bulk soft-delete \u2014 a bounded batch of DISTINCT assetIds with per-item success/refusal reporting, ONE actor-stamped Record for the batch (`assets.deleteMany`), and one `assets.deleted` event per deleted asset. Per-item independence: a refused item never rolls back the deleted ones. REFUSE semantics only (no reparent \u2014 that stays single `crud.delete`). `tenantWrite`. Extends the audit-receipt discipline to bulk.","crud.setLocation":'Set (or clear) the asset\'s location. A GOVERNED, version-creating verb: the successor carries the new geometry (GeoJSON in/out, native PostGIS storage); every other field copies forward. `geometry: null` clears the location. Distinct from `update` \u2014 full-state `update` carries no geometry. On a PostGIS-less deployment this refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a 500 or a silent no-op. `tenantWrite`.\n\nIT COMPARES BEFORE WRITING. A placement that would store the geometry the asset ALREADY HOLDS \u2014 including `geometry: null` over an asset with no location \u2014 creates no version, emits no `assets.location.set`, and answers with the CURRENT version. So re-sending a placement YOU JUST SENT is free, and a client may retry one without minting history.\n\n"Free" is exact equality of the stored geometry, not proximity: same coordinates in the same order, same geometry type, same SRID. A shape change at the same centre, and a different shape with the same bounding box, are both WRITES. Reading a location and sending it straight back is free too, because reads render at full stored precision \u2014 but a client that rounds, re-projects, reorders a ring, or promotes a Point to a MultiPoint is sending a different geometry and will mint a version.\n\nWHAT A CALLER CANNOT TELL, deliberately: whether this call wrote. The output is an `Asset` either way, so a caller that reports "location updated" over the response over-claims on a converged placement. Compare the returned `id` against the version you held if you need to know.\n\nA converged placement still leaves a Record, with `reads` naming the asset and `effects` EMPTY \u2014 so an automation bound to `assets.setLocation` does NOT fire for it (an empty `effects` is trigger-ineligible).\n\nNOT TRUE OF THE BULK SIBLING. `setLocationMany` writes every row it resolves, unconditionally; see its own note.',"crud.setLocationMany":`GOVERNED BULK PLACEMENT \u2014 place many assets in ONE call: the bulk sibling of \`setLocation\`, and the same operation per row (same GeoJSON surface, same PostGIS validation, its own append-only version row, its own \`assets.location.set\` event). What changes is the grain of the receipt, not the semantics.
72
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part2=other.properties?.[key]??undeclaredConstraint(other);part2!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part2))||parts.push(part2))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded2={type:"object",properties};if(required2.size&&(folded2.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded2.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded2.additionalProperties=constraints[0]:constraints.length>1&&(folded2.additionalProperties={allOf:constraints})}return folded2}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded2=null;if(!unions.length)folded2=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded2={[keyword]:branches}}folded2&&(delete json2.allOf,assignProps(json2,folded2))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value2)=>{(agg[key]===void 0||value2>agg[key])&&(agg[key]=value2)},narrowMax=(agg,key,value2)=>{(agg[key]===void 0||value2<agg[key])&&(agg[key]=value2)},narrowBoth=(agg,value2)=>{narrowMin(agg,"minimum",value2),narrowMax(agg,"maximum",value2)},addDivisor=(agg,value2)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value2)||agg.multipleOf.push(value2)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch2 of list)contributors[ch2._zod.def.check]?.(agg,ch2._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,(format==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values2=getEnumValues(def.entries);if(values2.length===0){json2.not={};return}values2.every(v=>typeof v=="number")&&(json2.type="number"),values2.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values2},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key in shape)assignProp(json2.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i2]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,prefixPath,i2]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i2)=>branch!==branches[i2])&&(json2={...json2,[keyword]:mapped})}let types=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types.includes("string")&&types.some(t2=>t2==="number"||t2==="integer"),values2=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values2?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values2||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending2=pendingRecords.get(ctx);pending2||(pending2=[],pendingRecords.set(ctx,pending2),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending2.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value2,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value2,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2.default=value2)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value2)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input2,params){if("_idmap"in input2){let registry2=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value2){this.ctx.counter=value2}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}};var json_schema_exports={};var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value2=make(this);return Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0}),value2},set(value2){Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch2=>typeof ch2=="function"?{_zod:{check:ch2,def:{check:"custom"},onattach:[]}}:ch2)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value2){util_exports.own(this,"~standard",value2)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value2){util_exports.own(this,"spa",value2)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value2,params){return this.check(_gt(value2,params))},gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))},step(value2,params){return this.check(_multipleOf(value2,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},gt(value2,params){return this.check(_gt(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value2,params)=>inst.check(_gte(value2,params)),inst.max=(value2,params)=>inst.check(_lte(value2,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values2,params)=>{let newEntries={};for(let value2 of values2)if(keys.has(value2))newEntries[value2]=def.entries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values2,params)=>{let newEntries={...def.entries};for(let value2 of values2)if(keys.has(value2))delete newEntries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum2(values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value2,params){return new ZodLiteral({type:"literal",values:Array.isArray(value2)?value2:[value2],...util_exports.normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){let ch2=new $ZodCheck({check:"custom"});return ch2._zod.check=fn,ch2}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path3=ref.slice(1).split("/").filter(Boolean);if(path3.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path3[0]===defsKey){let key=path3[1]===void 0?void 0:decodeJSONPointerSegment(path3[1]);if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value2=>value2).check(payload=>{let value2=payload.value;if(typeof value2!="object"||value2===null||Array.isArray(value2))return;let keys=Object.getOwnPropertyNames(value2);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.keySchema)for(let key of keys){let result=guards.keySchema.safeParse(key);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value2,seen){if(value2===null)return"z";let type=typeof value2;if(type!=="object"){if(type==="number"&&Number.isNaN(value2))return null;let raw=String(value2);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value2))return null;seen.add(value2);try{if(Array.isArray(value2)){let parts2=[];for(let item of value2){let key=canonicalKey(item,seen);if(key===null)return null;parts2.push(key)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value2).sort(),parts=[];for(let k of keys){let key=canonicalKey(value2[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value2)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value2){return typeof value2!="object"||value2===null?!1:Array.isArray(value2)?value2.some(containsRef):typeof value2.$ref=="string"?!0:Object.entries(value2).some(([key,sub])=>SCHEMA_KEYWORDS.has(key)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value2=>value2).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i2=0;i2<items.length;i2++){let key=canonicalKey(items[i2],new Set);if(key===null)continue;let first=firstSeen.get(key);if(first===void 0){firstSeen.set(key,i2);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i2} duplicates the one at index ${first}`,input:items,path:[i2],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break;matches<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t2=>{let typeSchema={...schema,type:t2};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z.uuid()):format==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format==="date"?stringSchema=stringSchema.check(z.iso.date()):format==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format==="hostname"?stringSchema=stringSchema.check(z.hostname()):format==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format==="mac"?stringSchema=stringSchema.check(z.mac()):format==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z.base64()):format==="base64url"?stringSchema=stringSchema.check(z.base64url()):format==="e164"?stringSchema=stringSchema.check(z.e164()):format==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format==="iban"?stringSchema=stringSchema.check(z.iban()):format==="jwt"?stringSchema=stringSchema.check(z.jwt()):format==="emoji"?stringSchema=stringSchema.check(z.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z.ulid()):format==="xid"?stringSchema=stringSchema.check(z.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i2=2;i2<schemasToIntersect.length;i2++)result=z.intersection(result,schemasToIntersect[i2]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject(payload.value))return;let unrecognized=[];for(let key of Object.keys(payload.value))propertyKeys.includes(key)||patterns.some(regex=>regex.test(key))||unrecognized.push(key);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i2=startIdx;i2<schema.allOf.length;i2++)result=z.intersection(result,convertSchema(schema.allOf[i2],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key of["minProperties","maxProperties"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key of["uniqueItems","minContains","maxContains"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||assignProp(extraMeta,key,schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache=new Map;function run(s){let cached2=cache.get(s);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)});if(cached2!==void 0)return cached2;cache.set(s,RESOLVING);let inner=mapInner(s),mapped=fn(inner,inner!==s);return cache.set(s,mapped),mapped}function mapInner(s){let def=s._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{let mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return run(schema)}function deepPartial(schema){return visit(schema,{object:s=>s.partial(),union:s=>{let def=s._zod.def;return def.discriminator===void 0?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:s=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var UNSTAMPED_ARTIFACT_VERSION="0.0.0-unstamped",resolveArtifactVersion=stamped=>{let trimmed=stamped?.trim();return trimmed===void 0||trimmed===""?UNSTAMPED_ARTIFACT_VERSION:trimmed},FORGE_ARTIFACT_VERSION=resolveArtifactVersion("42.26.0"),UNSTAMPED_BUILD_DETAIL="this process carries no build stamp, so it is NOT a packaged extension \u2014 it is a dev checkout, or a build made without FORGE_ARTIFACT_VERSION set. An installed extension always reports a real version here; for one that does not, read it from the desktop app under Settings \u2192 Extensions \u2192 this extension \u2192 Details.",artifactBuildReport=(options={})=>{let version2=options.version??FORGE_ARTIFACT_VERSION,stamped=version2!==UNSTAMPED_ARTIFACT_VERSION;return{...options.module===void 0?{}:{module:options.module},version:version2,stamped,...stamped?{}:{detail:UNSTAMPED_BUILD_DETAIL}}};var CONTRACT_DESCRIPTIONS=Object.freeze({assets:{list:"Every asset visible to the caller's tenant as a bare `AssetRef` \u2014 an `assetId` and nothing else. This is the cross-domain reference list, the shape another domain holds to point at an asset. It takes no input, accepts no filter, and does not page. For the asset rows themselves \u2014 name, type, status, filters, paging \u2014 call `crud.list` instead.",snapshot:"The domain's snapshot mint \u2014 the ONE polymorphic mint the platform convention gives every snapshot-referable domain. An idempotent DERIVATION, not a Record-writing verb: `tenantRead`, writes nothing, never a composition step. Output is the platform kernel `EntitySnapshotRef` verbatim; an unsupported `type` refuses at parse through the ask's enum.\n\nA NOOP mint over the version row: `snapshot` := the asset's CURRENT version row id, the same value the display resolver honours on a ref's `version`. Asset version rows are append-only, so the value denotes frozen content by construction.\n\nRefuses the declared `NOT_FOUND` for an id that names no live asset \u2014 unknown, malformed, soft-deleted, or another tenant's.","crud.create":"Create an asset under a type whose template validates its properties.","crud.get":'Fetch one version of an asset by `assetId`. Optional `asOf` selects the version effective at that instant (half-open `effectiveFrom <= asOf < effectiveTo`); absent \u2192 the current version. No version effective then (pre-creation / post-soft-delete) \u2192 NOT_FOUND. As of an instant, `properties` are the merged values then: a dated value covering the instant replaces the version\'s (a dated "no value" removes the key), and `appliedDatedValueIds` names each one taken. Optional `knownAt` replays that read as known then: only dated values recorded by then and not retired by then; versions read as stored. A future `knownAt` is refused at parse; one without `asOf` is BAD_REQUEST (`data.code = KNOWN_AT_WITHOUT_AS_OF`).',"crud.list":"List assets with filters + offset/limit pagination. Optional `asOf` mirrors `get`'s point-in-time semantics: every returned row (and `total`) is the version effective at that instant, its `properties` merged with the dated values covering the instant and named in `appliedDatedValueIds`, property filters and conditions reading the merged values; absent \u2192 the CURRENT population, byte-identical to the pre-existing current-population call. `knownAt` replays an as-of page, its count and its filters as known then, as `get`'s does. Refused together with `hasGeometry` (BAD_REQUEST naming both) \u2014 a spatial capability read has no past-instant notion.\n\n`categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the temporal window applies to asset VERSIONS, not to which types currently exist. A past `asOf` naming a category whose type has SINCE been deleted silently omits assets of that type; `assetTypeIds` names concrete governed ids directly and is unaffected.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422) when the read outlived the request's transaction budget \u2014 a big selection or a busy system; a `nameContains` or `search` text reads every asset the tenant holds, and so does a property or external-ID condition alone. `data.budgetMs` is the budget. Narrow the list (an id, a type, category or lifecycle filter), or retry once the system is quieter.\n\n`conditions`: operator conditions over asset fields, properties and external IDs, combined by All or Any and ANDed with every other filter. A condition its field cannot honour is refused `INVALID_CONDITION` (400, `data.index` names the row) before anything is read. The selection-taking verbs (`count`, the bulk relationship writes) and the export do NOT take it: sending it there is refused.\n\n`search`: the search box. An asset matches when its name contains the trimmed text (any case) OR it holds a current external ID, in any system, that equals it exactly (case-sensitive, no numeric coercion, the `ext:` `is` rule); `%`, `_` and `\\` are literal in the name. ANDed with every other filter and honoured at `asOf`; `nameContains` is unchanged and name-only. Unlike `conditions`, `search` IS part of the selection, so `count`, the bulk relationship writes and the export take it and describe the set the box found. When a request carries `search`, the output's `matchedExternalIds` names, for each row on the page found by an external ID and not by its name, the binding that matched.","crud.distinctValues":"The values a condition FIELD holds on the assets a list filter selects, with the number of those assets holding each \u2014 what a person picks from instead of guessing a value. `tenantRead`: writes nothing, records nothing.\n\n`{ field, filter, prefix?, limit? }`: `field` is a condition field (`asset:status`, `prop:<code>`, `ext:<system>` / `ext:*`,...), `filter` the rest of the list filter verbatim (`asOf` included), `prefix` a case-insensitive literal prefix, `limit` 1..20 (default 20). Most common first, then by value; a response of exactly `limit` entries may have more, and there is no next page. Values `is` treats as one (case, a number and \"42\") are one entry, the most common spelling, counted over the whole group; external IDs group exactly. `count` counts assets, once each.\n\n`prefix` is REQUIRED for `asset:name` and `ext:` fields (about one value per asset): without one the read is refused `INVALID_CONDITION` (`reason: 'prefix-required'`).\n\n`values` asks instead for EXACT counts of up to 20 listed values of a `prop:` field \u2014 JSON-typed and case-exact, the `propertyFilters` equality \u2014 so one read tells a caller which values of a `oneOf` / `noneOf` list no selected asset holds (they are absent). Any other field, or a `prefix` beside it, is refused `INVALID_CONDITION` (`reason: 'values-not-allowed'`).\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the scan outlived the budget \u2014 a property or external-ID field over a whole tenant reads every asset; narrow the filter by a type or category first.","crud.index":"A LEAN sibling of `list` \u2014 the SAME filters MINUS `asOf`, plus a REQUIRED `fields` projection. Listing 129 facilities over `list` returned 92,061 characters \u2014 every property of every asset \u2014 when the caller needed only `{name, assetId}`. `locations` below was already built as exactly this lean-sibling shape for the map read; this generalizes the pattern to an arbitrary field selection.\n\nPROJECTS AFTER THE FETCH, never a second query \u2014 the `locations` precedent: `list` runs unchanged, then each row is narrowed to the requested fields in JS. `assetId` is ALWAYS present regardless of `fields` \u2014 a caller listing assets needs an id to act on any of them, the same implicit guarantee `list`/`locations` make.\n\nThe output item type is one flat object DERIVED from `AssetSchema` \u2014 every field optional except the always-present `assetId` \u2014 not a shape that varies with the selection. A per-selection output would have no single OpenAPI rendering for a non-TS consumer to code against, and a hand-authored parallel shape could drift from `AssetSchema`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list` \u2014 it IS `list` \u2014 when the read outlived the request's transaction budget. `INVALID_CONDITION`, exactly as `list`: a `conditions` row its field cannot honour is refused, naming the row, before anything is read.","crud.count":"HOW MANY assets a predicate matches, in ONE query with NO pagination \u2014 plus, optionally, a capped SAMPLE of matching ids in the same round trip. `tenantRead`: writes nothing, records nothing, stages nothing.\n\nNOT A MODE OF `list`, and the distinction is the reason it exists. `list` answers \"which slice do I show\" and carries `total` as a rider on the FIRST page only \u2014 a cursor page omits it by design \u2014 so a caller who wants only the number has to either page or reason about which page still carries it. Its first consumer did the former: the calculations authoring scope preview resolved \"resolves N assets\" by paging `list` to exhaustion at 200 ids a page over the cross-domain loopback and taking the array's LENGTH, which measured 132 s at the observed 543,391-asset estate for a number the first page had already counted.\n\n`asOf` mirrors `list`'s point-in-time semantics \u2014 the same half-open `effectiveFrom <= asOf < effectiveTo` window, applied to the same seek-free filter \u2014 so a past-instant count and a past-instant PAGE of one predicate always describe the same population. ABSENT \u2192 the CURRENT population. Refused together with `selection.hasGeometry`, exactly as `list` refuses the pair and for the same reason.\n\n`selection.categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the same caveat `list` carries, inherited rather than restated, because this IS `list`'s count.\n\nThe sample is drawn from the first page of `list`'s own default order (name ascending, `assetId`-tiebroken). It is a SAMPLE, not a page: there is no cursor and no way to ask for the next one. For rows, call `list`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the count outlived the request's transaction budget.","crud.exportEstimate":"Pre-flight an export WITHOUT authorizing one (`tenantRead`): resolve the selection, COUNT it, and report how WIDE the file would be. A count and a column count, never rows.\n\nSTAGES NOTHING, GRANTS NOTHING, RECORDS NOTHING \u2014 call it freely to refuse an over-cap or empty export BEFORE the confirm action. The authorization itself is `export`, which re-resolves on its own and does not trust this answer.\n\n`maxRows` on the answer is the deployment's EFFECTIVE row cap \u2014 the same injected policy the mint enforces. State THAT number in any copy or pre-guard; never bake the assembly default into a client, or a deployment override splits UI-refused from server-granted.\n\n`columnCount` is what makes WIDTH knowable up front \u2014 the file's column set is derived from the data in the selection, so two exports with different filters legitimately differ in width. It is SKIPPED (reported as 0) where `rowCount` already exceeds `maxRows`: an export that will be refused does not pay for column math.\n\n`maxColumns` is the WIDTH cap the mint enforces, echoed for the same reason `maxRows` is: width is the export's second scaling term (peak memory is tile rows \xD7 columns), so a selection can be refused for being too WIDE with a row count well under the cap. State that number in copy too.\n\nAnswers even where the deployment has no export store, because it touches no store.\n\nA count that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `count` is.","crud.exportStatus":"Where ONE authorized export has got to (`tenantRead`, un-recorded).\n\n `pending` \u2192 still building, with an HONEST fraction (`tilesDone` of\n `tilesTotal`) rather than a synthesized percentage, plus the\n row and column counts so a client can keep describing the\n file while it waits.\n `ready` \u2192 the GRANT: `{url, headers, expiresAt, mediaType, filename,\n rowCount}` plus `byteSize`. The URL is presigned FRESH on\n every read, so its lifetime starts when you are told about\n it rather than when the build finished.\n `failed` \u2192 why, in one sentence. A build that stopped making progress\n reports failed rather than pending forever, so a dead worker\n is legible instead of invisible.\n\nONE EXPORT, BY ID \u2014 there is deliberately no list, no paging and no filter. A read that enumerated a tenant's exports would misrepresent a transient movement artifact as a persisted published representation, so an `exportId` you no longer hold names an export you can no longer reach. Another tenant's id resolves to NOT_FOUND exactly as an id that never existed does.","crud.export":'Authorize ONE export of the assets a selection matches (`tenantWrite`, a GOVERNED verb \u2014 every mint leaves an actor-stamped Record naming the SELECTION, its ordering, its scoping and the resolved row count; the pre-flight, the build and the transfer do not).\n\nReturns a HANDLE, not the file and not yet a link: `{exportId, state, rowCount, columnCount, tilesTotal}`. Poll `crud.exportStatus` with that `exportId` for the grant. The build is ASYNCHRONOUS because it measured too slow to hold a request open \u2014 a full-estate export took ~60s unfiltered and ~200s subtree-scoped against a ~60s gateway envelope \u2014 so the mint validates, refuses, records and enqueues, and nothing more.\n\nThe response carries NO bucket, key or other storage location, and the request cannot name one \u2014 a caller-supplied `objectKey`, `bucket`, `prefix` or `tenantId` is refused at parse.\n\nThe file carries EVERYTHING the asset is known by, and the column set is derived from the DATA in the selection rather than from template declarations: the durable `assetId`, the name, resolved category and type names, lifecycle, the validity window, the location as well-known text (the column ABSENT where the deployment has no geometry \u2014 an empty cell would falsely assert "no location"), a `Parent`/`Parent ID` pair for each of the four HIERARCHY relationship types, one `prop.*` column per static property key present, and one `derived.*` column per materialized derived code present. NO column INDEX is stable across exports \u2014 read by header. A blank `derived.*` cell may mean "not rebuilt yet" rather than "no value": that table is a rebuildable projection, not governed history.\n\n`descendantOf` scopes the export to a hierarchy SUBTREE, node-inclusive and DISTINCT on asset id \u2014 the asset graph is a DAG, so one asset can be reachable from two unrelated roots. It exists on THIS input only, never on the shared bulk selection the mutating verbs take.\n\nTHE GRANT IS NOT SINGLE-USE: within its lifetime (`expiresAt`, 900s by default) it may be fetched more than once, and a transfer that begins before expiry completes even if expiry passes mid-stream. Single-use is unenforceable on a signed object-store URL. An expired grant is refused by the store; poll again for a fresh one rather than storing grant URLs. NOTHING ENUMERATES PAST EXPORTS \u2014 `exportStatus` answers about ONE id and there is no list, so a lost `exportId` is a lost export. The sealed Record is the only durable trace.\n\n`idempotencyKey` is REQUIRED, unique per (tenant, caller, key): a mint that times out may well have completed, and the SAME-KEY retry returns the one existing authorization with a FRESH usable grant. A reused key with a different selection or format is refused as `BAD_REQUEST` with `data.code = "KEY_PARAM_MISMATCH"` (another caller\'s key: `data.code = "KEY_ACTOR_MISMATCH"`); `CONFLICT` is reserved for two CONCURRENT mints racing the same key, where the loser retries into the replay.\n\nREFUSALS, declared and ordered: `SERVICE_UNAVAILABLE` with `data.code = "EXPORT_STORE_UNAVAILABLE"` (this deployment has no export store; the pre-flight still answers) \u2192 `FORMAT_UNAVAILABLE` (XLSX is a declared format this capability does not serve yet; ask for CSV) \u2192 `OVER_CAP` with `data.reason = "search-cap"` \u2192 `EMPTY_RESULT` (zero assets; nothing to stage) \u2192 `OVER_CAP` with no `data` (the selection exceeds the deployment\'s row cap; narrow it \u2014 never truncated, never queued, because a silently partial 700,000-row file is more dangerous than a refusal that names the count and the cap) \u2192 `TOO_MANY_COLUMNS` (the selection is too WIDE: the column set is derived from the data, so a selection whose assets carry thousands of distinct property keys scales the file\'s second dimension. `exportEstimate` reports both `columnCount` and `maxColumns`, so this is readable before the confirm).',"crud.locations":"The MAP's read \u2014 located assets under the same filter facets, projected to the three fields a canvas draws (`assetId`, `name`, `geometry`) and capped at a map-scale ceiling rather than the table's 200.\n\nA sibling of `list` rather than a mode of it, for two reasons: the lean projection is what makes the raised ceiling affordable (measured 248 kB vs 681 kB for the same 1,110-asset estate), and it keeps that ceiling off `crud.list`, where no caller needs a page past 200. Unpaged and unordered by construction \u2014 a map has no pager, so a page-2 pin is an invisible pin.\n\nCapability-gated like every geometry surface: a PostGIS-less deployment refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a silent empty canvas. tenantRead in the api wiring. A read that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `list` is.","crud.update":"Full-state-replace update \u2014 a new version row pinning the current template. With `effectiveFrom`, the dated values of each property it changes are replaced from that date onward. A lost race is `CONFLICT` with `data.code = DATED_VALUES_RACE`: nothing was saved, retry.","crud.delete":"Soft-delete \u2014 close the current version, no successor; returns it.\n\n`SERVICE_UNAVAILABLE` with `data.reason: 'deadlock'` is TRANSIENT: a concurrent write to the same assets deadlocked with this one and nothing was written \u2014 retry the same call.","crud.deleteImpact":"Delete-impact PREFLIGHT \u2014 a READ over a bounded batch of assetIds reporting what a delete WOULD hit (hierarchy edges, storage-only edges, live external-ID bindings) + a per-asset verdict (deletable / reparentable / reparentable-too-wide / blocked / not-found). ADVISORY: no lock between preflight and delete \u2014 the delete's own guards stay the authority (TOCTOU by design). `tenantRead`, leaves no Record.","crud.deleteMany":"GOVERNED bulk soft-delete \u2014 a bounded batch of DISTINCT assetIds with per-item success/refusal reporting, ONE actor-stamped Record for the batch (`assets.deleteMany`), and one `assets.deleted` event per deleted asset. Per-item independence: a refused item never rolls back the deleted ones. REFUSE semantics only (no reparent \u2014 that stays single `crud.delete`). `tenantWrite`. Extends the audit-receipt discipline to bulk.","crud.setLocation":'Set (or clear) the asset\'s location. A GOVERNED, version-creating verb: the successor carries the new geometry (GeoJSON in/out, native PostGIS storage); every other field copies forward. `geometry: null` clears the location. Distinct from `update` \u2014 full-state `update` carries no geometry. On a PostGIS-less deployment this refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a 500 or a silent no-op. `tenantWrite`.\n\nIT COMPARES BEFORE WRITING. A placement that would store the geometry the asset ALREADY HOLDS \u2014 including `geometry: null` over an asset with no location \u2014 creates no version, emits no `assets.location.set`, and answers with the CURRENT version. So re-sending a placement YOU JUST SENT is free, and a client may retry one without minting history.\n\n"Free" is exact equality of the stored geometry, not proximity: same coordinates in the same order, same geometry type, same SRID. A shape change at the same centre, and a different shape with the same bounding box, are both WRITES. Reading a location and sending it straight back is free too, because reads render at full stored precision \u2014 but a client that rounds, re-projects, reorders a ring, or promotes a Point to a MultiPoint is sending a different geometry and will mint a version.\n\nWHAT A CALLER CANNOT TELL, deliberately: whether this call wrote. The output is an `Asset` either way, so a caller that reports "location updated" over the response over-claims on a converged placement. Compare the returned `id` against the version you held if you need to know.\n\nA converged placement still leaves a Record, with `reads` naming the asset and `effects` EMPTY \u2014 so an automation bound to `assets.setLocation` does NOT fire for it (an empty `effects` is trigger-ineligible).\n\nNOT TRUE OF THE BULK SIBLING. `setLocationMany` writes every row it resolves, unconditionally; see its own note.',"crud.setLocationMany":`GOVERNED BULK PLACEMENT \u2014 place many assets in ONE call: the bulk sibling of \`setLocation\`, and the same operation per row (same GeoJSON surface, same PostGIS validation, its own append-only version row, its own \`assets.location.set\` event). What changes is the grain of the receipt, not the semantics.
73
73
 
74
74
  ONE DIVERGENCE FROM THE SINGLE VERB: this one does NOT compare before writing. Every row it resolves takes a version row and emits an event even when the geometry it would store is already there, so re-sending a converged batch is NOT free the way re-sending a single placement is. Extending the compare into the set-based bulk interior is tracked as its own decision.
75
75
 
@@ -475,5 +475,7 @@ ${TENANCY_UPDATE_REACH_NOTE}`},"tenancy.setPackagedModulesOff":{dispatchPath:top
475
475
 
476
476
  ${TENANCY_SET_PACKAGED_MODULES_OFF_REACH_NOTE}`},"tenancy.setPreferredModulesOff":{dispatchPath:topLevel("tenancy.setPreferredModulesOff"),annotations:{destructiveHint:!0},descriptionSuffix:`${REPLAY_KEY_DISCIPLINE}
477
477
 
478
- ${TENANCY_SET_PREFERRED_MODULES_OFF_REACH_NOTE}`},"tenancy.get":{dispatchPath:topLevel("tenancy.get"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_GET_REACH_NOTE},"tenancy.list":{dispatchPath:topLevel("tenancy.list"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_LIST_REACH_NOTE},"tenancy.switchableModules":{dispatchPath:topLevel("tenancy.switchableModules"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_SWITCHABLE_MODULES_NOTE}}),iamPair=Object.freeze({manifest:iamManifest,contract:iamContract,procedures:iamProcedures});var deepFreeze=value2=>(typeof value2=="object"&&value2!==null&&(Object.values(value2).forEach(deepFreeze),Object.freeze(value2)),value2),approvalManifest=deepFreeze(JSON.parse('{"name":"approvals","plane":"resource","routerKey":"approvals","verbs":[{"name":"request"},{"name":"approve"},{"name":"reject"},{"name":"cancel"},{"name":"delegate"},{"name":"comment"},{"name":"remind"},{"name":"templateCreate"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"}]}')),assetsManifest=deepFreeze(JSON.parse('{"name":"assets","plane":"resource","routerKey":"assets","verbs":[{"name":"createMany"},{"name":"startImport"},{"name":"preflightImport"},{"name":"saveImportMapping"},{"name":"create"},{"name":"update"},{"name":"delete"},{"name":"deleteMany"},{"name":"move"},{"name":"moveMany"},{"name":"relationshipsCreateMany"},{"name":"relationshipsEndMany"},{"name":"createRelationship"},{"name":"endRelationship"},{"name":"createCategory"},{"name":"updateCategory"},{"name":"deleteCategory"},{"name":"createType"},{"name":"updateType"},{"name":"deleteType"},{"name":"setTemplate"},{"name":"createSystem"},{"name":"updateSystem"},{"name":"deleteSystem"},{"name":"createHierarchy"},{"name":"saveRules"},{"name":"savePolicy"},{"name":"setLocation"},{"name":"setLocationMany"},{"name":"setDatedValues"},{"name":"revertDatedValues"},{"name":"bindExternalId"},{"name":"bindExternalIdMany"},{"name":"unbindExternalId"},{"name":"startBindJob"},{"name":"saveNumberingConfig"},{"name":"saveNestingRules"},{"name":"saveDerivedRouting"},{"name":"applyDerivedValues"},{"name":"export"},{"name":"exportDuplicates"},{"name":"importJob"},{"name":"bindJob"},{"name":"preflightImportJob"},{"name":"landDirectory"},{"name":"publishDirectory"},{"name":"setDirectorySchedule"},{"name":"startTeardownJob"},{"name":"teardownJob"},{"name":"saveLocationPlacement"},{"name":"deleteLocationPlacement"},{"name":"startLocationPlacementJob"}]}')),bundlesManifest=deepFreeze(JSON.parse('{"name":"bundles","plane":"platform","routerKey":"bundles","verbs":[{"name":"build"},{"name":"buildCompleted"}]}')),calculationsManifest=deepFreeze(JSON.parse('{"name":"calculations","plane":"resource","routerKey":"calculations","agentGuidance":{"scheme":"calc","resources":[{"uri":"calc://declaration-format","name":"Declaration format","description":"The calculation declaration format, field by field, with worked examples \u2014 the authoring half of the engine reference.","mimeType":"text/markdown","source":{"kind":"repoFile","text":"# ECE Declaration Format (v1.0)\\n\\nThe declaration format is a JSON-based file format that fully describes an ECE workbook \u2014 sheets, columns, formulas, data, and configuration \u2014 without requiring an Excel template file.\\n\\n## When to Use\\n\\n| Approach | Use when |\\n|----------|----------|\\n| **Template + overlay** | You have an existing Excel workbook and want to make runtime modifications (formula edits, lookup data changes, new columns) |\\n| **Declaration** | You want to define a workbook from scratch in code \u2014 no Excel template needed |\\n| **Declaration + overlay** | You have a base declaration and want scenario-specific modifications without editing the declaration itself |\\n\\nBoth approaches produce the same internal manifest and feed into the same downstream pipeline (binder \u2192 DAG \u2192 SQL \u2192 executor).\\n\\n## File Structure\\n\\nDeclaration files use the `.declaration.json` extension by convention:\\n\\n```\\ncalculator.declaration.json\\npath/to/workbook.declaration.json\\n```\\n\\n## Schema Definition\\n\\n```javascript\\n{\\n \\"version\\": \\"1.0\\",\\n\\n // Sheet declarations (at least one calculator sheet required)\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Well ID\\", \\"CH4 Rate\\", \\"Total Emissions\\"],\\n\\n // Row generator columns (optional, auto-detected during extraction)\\n // \\"rowGenerators\\": [\\"Date\\"],\\n\\n // Data source (optional for calculator sheets)\\n \\"rows\\": [\\n { \\"Date\\": \\"2024-01-15\\", \\"Well ID\\": \\"W001\\", \\"CH4 Rate\\": 12.5, \\"Total Emissions\\": null }\\n ],\\n // OR: \\"source\\": \\"observations.csv\\"\\n\\n // Formulas (optional)\\n \\"columnFormulas\\": {\\n \\"Total Emissions\\": \\"=SUMIFS(Data__Obs[CH4], Data__Obs[Well], [@Well ID])\\"\\n },\\n\\n // Type hints (optional) \u2014 string or { type, format? } object\\n \\"columnTypeHints\\": {\\n \\"Date\\": \\"TIMESTAMP\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" }\\n },\\n\\n // Timezone overrides (optional)\\n \\"columnTimezones\\": {\\n \\"Date\\": \\"America/Denver\\"\\n },\\n\\n // Static cells above header row (optional, calculator only)\\n \\"staticCells\\": {\\n \\"B1\\": { \\"valueType\\": \\"number\\", \\"value\\": 0.004 }\\n },\\n\\n // Summary/aggregation rows (optional, calculator only)\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Total Emissions\\": \\"sum\\",\\n \\"Well ID\\": \\"=COUNTA(Calculator[Well ID])\\",\\n \\"CH4 Rate\\": \\"average\\"\\n }\\n }\\n ],\\n\\n // Per-row formula overrides (optional, calculator only, requires RowID column)\\n \\"literalOverrides\\": {\\n \\"CH4 Rate\\": [\\n { \\"rowId\\": \\"W001\\", \\"value\\": 0 }\\n ]\\n }\\n },\\n {\\n \\"name\\": \\"Data__Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"Date\\", \\"Well\\", \\"CH4\\", \\"CO2\\"],\\n \\"source\\": \\"observations.parquet\\",\\n\\n // Supplemental formulas (optional \u2014 any sheet can have formulas)\\n \\"columnFormulas\\": {\\n \\"CO2\\": \\"=[@CH4] * 2.75\\"\\n }\\n },\\n {\\n \\"name\\": \\"Lookup__Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"FactorID\\", \\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"FactorID\\": \\"EF001\\", \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"FactorID\\": \\"EF002\\", \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ],\\n\\n // Pivot tables (optional)\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Well ID\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Total Emissions\\", \\"name\\": \\"Sum of Emissions\\", \\"subtotal\\": \\"sum\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ],\\n\\n // Execution defaults (optional)\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP\\",\\n \\"defaultSourceTimezone\\": \\"UTC\\",\\n \\"preserveRowOrder\\": true,\\n \\"orderBy\\": [\\"phenomenonTimeBucket\\"],\\n // How *IFS criteria match: \\"excel\\" (default) or \\"exact\\". See Execution Config.\\n \\"criteriaMatching\\": \\"excel\\",\\n // Multi-calculator pipeline (optional) \u2014 run named calculators in sequence.\\n // Each stage\'s output is materialized as a DuckDB table for downstream stages.\\n // See the engine pipeline documentation.\\n \\"pipeline\\": [\\"Enrich\\", \\"CostCalc\\", \\"Compliance\\"]\\n }\\n}\\n```\\n\\n## Field Reference\\n\\n### Top-Level Metadata\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `version` | string | Yes | Schema version (currently `\\"1.0\\"`) |\\n| `sheets` | array | Yes | Sheet declarations (at least one calculator) |\\n| `pivotSheets` | array | No | Pivot table declarations |\\n| `execution` | object | No | Execution configuration defaults |\\n\\n### Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Sheet name (must be unique across all sheets) |\\n| `role` | string | Yes | Sheet role: `\\"calculator\\"`, `\\"data\\"`, `\\"lookup\\"`, or `\\"other\\"` |\\n| `columns` | string[] | Yes | Ordered column names (non-empty, no duplicates) |\\n| `rowGenerators` | string[] | No | Columns whose formulas are row generators (UNIQUE/FILTER). Auto-populated during extraction |\\n| `rows` | object[] | No | Inline data rows (mutually exclusive with `source`) |\\n| `source` | string or object | No | External file path (string), UNION definition, GROUP BY definition, or cross-join definition. See below |\\n| `columnFormulas` | object | No | Map of column name to Excel formula string |\\n| `formulaSourceRow` | number | No | The Excel row number where cell-address formulas (A1-style) originate \u2014 used to compute cross-row offsets for LAG/LEAD. See the Cross-Row References section of the engine specification. Defaults to `headerRowNumber + 1` if omitted (`2` for a sheet with a single header row), so a relative formula written against row 3 resolves as same-row only when the sheet declares `formulaSourceRow: 3` \u2014 which every example declaration this server publishes does. Omitting it is only soft-warned at validate. A `# ECE Declaration Format (v1.0)\\n\\nThe declaration format is a JSON-based file format that fully describes an ECE workbook \u2014 sheets, columns, formulas, data, and configuration \u2014 without requiring an Excel template file.\\n\\n## When to Use\\n\\n| Approach | Use when |\\n|----------|----------|\\n| **Template + overlay** | You have an existing Excel workbook and want to make runtime modifications (formula edits, lookup data changes, new columns) |\\n| **Declaration** | You want to define a workbook from scratch in code \u2014 no Excel template needed |\\n| **Declaration + overlay** | You have a base declaration and want scenario-specific modifications without editing the declaration itself |\\n\\nBoth approaches produce the same internal manifest and feed into the same downstream pipeline (binder \u2192 DAG \u2192 SQL \u2192 executor).\\n\\n## File Structure\\n\\nDeclaration files use the `.declaration.json` extension by convention:\\n\\n```\\ncalculator.declaration.json\\npath/to/workbook.declaration.json\\n```\\n\\n## Schema Definition\\n\\n```javascript\\n{\\n \\"version\\": \\"1.0\\",\\n\\n // Sheet declarations (at least one calculator sheet required)\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Well ID\\", \\"CH4 Rate\\", \\"Total Emissions\\"],\\n\\n // Row generator columns (optional, auto-detected during extraction)\\n // \\"rowGenerators\\": [\\"Date\\"],\\n\\n // Data source (optional for calculator sheets)\\n \\"rows\\": [\\n { \\"Date\\": \\"2024-01-15\\", \\"Well ID\\": \\"W001\\", \\"CH4 Rate\\": 12.5, \\"Total Emissions\\": null }\\n ],\\n // OR: \\"source\\": \\"observations.csv\\"\\n\\n // Formulas (optional)\\n \\"columnFormulas\\": {\\n \\"Total Emissions\\": \\"=SUMIFS(Data__Obs[CH4], Data__Obs[Well], [@Well ID])\\"\\n },\\n\\n // Type hints (optional) \u2014 string or { type, format? } object\\n \\"columnTypeHints\\": {\\n \\"Date\\": \\"TIMESTAMP\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" }\\n },\\n\\n // Timezone overrides (optional)\\n \\"columnTimezones\\": {\\n \\"Date\\": \\"America/Denver\\"\\n },\\n\\n // Static cells above header row (optional, calculator only)\\n \\"staticCells\\": {\\n \\"B1\\": { \\"valueType\\": \\"number\\", \\"value\\": 0.004 }\\n },\\n\\n // Summary/aggregation rows (optional, calculator only)\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Total Emissions\\": \\"sum\\",\\n \\"Well ID\\": \\"=COUNTA(Calculator[Well ID])\\",\\n \\"CH4 Rate\\": \\"average\\"\\n }\\n }\\n ],\\n\\n // Per-row formula overrides (optional, calculator only, requires RowID column)\\n \\"literalOverrides\\": {\\n \\"CH4 Rate\\": [\\n { \\"rowId\\": \\"W001\\", \\"value\\": 0 }\\n ]\\n }\\n },\\n {\\n \\"name\\": \\"Data__Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"Date\\", \\"Well\\", \\"CH4\\", \\"CO2\\"],\\n \\"source\\": \\"observations.parquet\\",\\n\\n // Supplemental formulas (optional \u2014 any sheet can have formulas)\\n \\"columnFormulas\\": {\\n \\"CO2\\": \\"=[@CH4] * 2.75\\"\\n }\\n },\\n {\\n \\"name\\": \\"Lookup__Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"FactorID\\", \\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"FactorID\\": \\"EF001\\", \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"FactorID\\": \\"EF002\\", \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ],\\n\\n // Pivot tables (optional)\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Well ID\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Total Emissions\\", \\"name\\": \\"Sum of Emissions\\", \\"subtotal\\": \\"sum\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ],\\n\\n // Execution defaults (optional)\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP\\",\\n \\"defaultSourceTimezone\\": \\"UTC\\",\\n \\"preserveRowOrder\\": true,\\n \\"orderBy\\": [\\"phenomenonTimeBucket\\"],\\n // How *IFS criteria match: \\"excel\\" (default) or \\"exact\\". See Execution Config.\\n \\"criteriaMatching\\": \\"excel\\",\\n // Multi-calculator pipeline (optional) \u2014 run named calculators in sequence.\\n // Each stage\'s output is materialized as a DuckDB table for downstream stages.\\n // See the engine pipeline documentation.\\n \\"pipeline\\": [\\"Enrich\\", \\"CostCalc\\", \\"Compliance\\"]\\n }\\n}\\n```\\n\\n## Field Reference\\n\\n### Top-Level Metadata\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `version` | string | Yes | Schema version (currently `\\"1.0\\"`) |\\n| `sheets` | array | Yes | Sheet declarations (at least one calculator) |\\n| `pivotSheets` | array | No | Pivot table declarations |\\n| `execution` | object | No | Execution configuration defaults |\\n\\n### Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Sheet name (must be unique across all sheets) |\\n| `role` | string | Yes | Sheet role: `\\"calculator\\"`, `\\"data\\"`, `\\"lookup\\"`, or `\\"other\\"` |\\n| `columns` | string[] | Yes | Ordered column names (non-empty, no duplicates) |\\n| `rowGenerators` | string[] | No | Columns whose formulas are row generators (UNIQUE/FILTER). Auto-populated during extraction |\\n| `rows` | object[] | No | Inline data rows (mutually exclusive with `source`) |\\n| `source` | string or object | No | External file path (string), UNION definition, GROUP BY definition, or cross-join definition. See below |\\n| `columnFormulas` | object | No | Map of column name to Excel formula string |\\n| `formulaSourceRow` | number | No | The Excel row number where cell-address formulas (A1-style) originate \u2014 used to compute cross-row offsets for LAG/LEAD. See the Cross-Row References section of the engine specification. -anchored row, `$B$2`, reads that row on every row (see the Absolute-Row Cell References section of the engine specification) |\\n| `columnTypeHints` | object | No | Map of column name to type hint |\\n| `columnTimezones` | object | No | Map of column name to IANA timezone |\\n| `staticCells` | object | No | Map of cell reference (e.g., `\\"B1\\"`) to value object. Calculator only |\\n| `summaryRows` | array | No | Summary/aggregation rows below data. Calculator only |\\n| `literalOverrides` | object | No | Per-row formula overrides. Calculator only; requires a `RowID` column |\\n\\n**Data source rules:**\\n- **Calculator sheets** can omit both `rows` and `source` (e.g., when using UNIQUE/FILTER row generators)\\n- **Data and lookup sheets** must specify either `rows` or `source`\\n- **Other sheets** can omit both `rows` and `source` (they are inert during execution)\\n- `rows` and `source` cannot both be specified on the same sheet \u2014 except for UNION sources, which require `rows: []` (empty) alongside the `source` definition\\n\\n**Source types:**\\n- **String** \u2014 external file path: `\\"source\\": \\"observations.csv\\"` (CSV, Parquet, JSON, or JSONL)\\n- **UNION object** \u2014 virtual table composed from other sheets:\\n ```json\\n \\"source\\": {\\n \\"union\\": [\\n { \\"sheet\\": \\"Data__Wells\\", \\"columns\\": { \\"AssetID\\": \\"WellID\\", \\"Type\\": { \\"literal\\": \\"WELL\\" } } },\\n { \\"sheet\\": \\"Data__Facs\\", \\"columns\\": { \\"AssetID\\": \\"FacID\\", \\"Type\\": { \\"literal\\": \\"FAC\\" } } }\\n ],\\n \\"distinct\\": false\\n }\\n ```\\n Each member maps output columns to source columns (string = rename, `{ \\"literal\\": value }` = constant). Optional `filter` applies a WHERE clause. Optional `distinct: true` uses `UNION` instead of `UNION ALL`. A member may not map a `columnFormulas` column of its source sheet (unions are built before those formulas run); that is refused.\\n\\n- **GROUP BY object** \u2014 calculator rows from aggregation (calculator sheets only):\\n ```json\\n \\"source\\": {\\n \\"groupBy\\": {\\n \\"sheet\\": \\"Data__Production\\",\\n \\"keys\\": [\\"FacilityID\\", \\"Year\\"],\\n \\"aggregations\\": {\\n \\"TotalOil\\": { \\"function\\": \\"SUM\\", \\"column\\": \\"OIL_PROD_BBL\\" },\\n \\"RecordCount\\": { \\"function\\": \\"COUNT\\", \\"column\\": \\"*\\" }\\n }\\n }\\n }\\n ```\\n Generates one row per unique combination of key columns. `aggregations` maps output column names to `{ function, column }` pairs. Supported functions: `SUM`, `AVG`, `COUNT`, `MAX`, `MIN`. Formula columns in the calculator then compute on top of these aggregated seed rows.\\n\\n- **Cross-join object** \u2014 calculator rows from Cartesian product (calculator sheets only):\\n ```json\\n \\"source\\": {\\n \\"crossJoin\\": {\\n \\"left\\": \\"Data__Years\\",\\n \\"right\\": \\"Data__Sites\\",\\n \\"filter\\": \\"__cj_right.\\\\\\"SiteType\\\\\\" = \'Active\'\\"\\n }\\n }\\n ```\\n Generates every combination of rows from `left` and `right` tables. Optional `filter` is a SQL WHERE clause using `__cj_left` / `__cj_right` aliases. Both tables must be registered data sheets or materialized UNION sheets.\\n\\n### Static Cell Value Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `valueType` | string | No | Type of the value: `\\"string\\"`, `\\"number\\"`, `\\"boolean\\"`, or `\\"date\\"` |\\n| `value` | any | Yes | The cell value |\\n\\n### Summary Row Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `label` | string | No | Row label (e.g., `\\"TOTALS\\"`) |\\n| `aggregations` | object | Yes | Map of column name to aggregation value |\\n\\n**Aggregation values** can be any of:\\n\\n| Form | Example | Description |\\n|------|---------|-------------|\\n| Simple type | `\\"sum\\"` | One of `\\"sum\\"`, `\\"average\\"`, `\\"count\\"`, `\\"max\\"`, `\\"min\\"` |\\n| Formula | `\\"=COUNTA(Calculator[Well ID])\\"` | Arbitrary Excel formula (must start with `=`) |\\n| Value object | `{ \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" }` | Static value (label, constant) |\\n| `null` | `null` | Skip this column in the aggregation row |\\n\\n`\\"avg\\"` is accepted as a synonym for `\\"average\\"`.\\n\\n### Literal Override Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `rowId` | any | Yes | Value of the `RowID` column for the target row |\\n| `value` | any | Yes | Literal value to use instead of the column formula |\\n\\nWhen a column has literal overrides, the SQL generator produces a `CASE WHEN` expression:\\n```sql\\nCASE WHEN \\"RowID\\" = \'W001\' THEN 0 ELSE <formula> END\\n```\\n\\n### Pivot Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Pivot sheet name |\\n| `source` | object | Yes | Source sheet reference |\\n| `dataFields` | array | Yes | Aggregated value columns (at least one) |\\n| `rowFields` | array | No | Row grouping fields |\\n| `colFields` | array | No | Column grouping fields |\\n| `pageFields` | array | No | Filter/page fields |\\n| `calculatedFields` | array | No | Computed pivot fields |\\n| `dataOnRows` | boolean | No | Transpose summary layout (default: `false`) |\\n| `rowGrandTotals` | boolean | No | Include row grand totals (default: `true`) |\\n| `colGrandTotals` | boolean | No | Include column grand totals (default: `true`) |\\n\\n#### Pivot Source Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `sheetName` | string | One of the two | Source sheet name |\\n| `tableName` | string | One of the two | Source table name |\\n\\n#### Pivot Data Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `sourceField` | string | Yes | Column to aggregate |\\n| `subtotal` | string | No | Aggregation type: `\\"sum\\"`, `\\"count\\"`, `\\"average\\"`, `\\"min\\"`, `\\"max\\"` (default: `\\"sum\\"`) |\\n| `name` | string | No | Display name (default: `\\"<subtotal> of <sourceField>\\"`) |\\n\\n`\\"avg\\"` is accepted as a synonym for `\\"average\\"`.\\n\\n#### Pivot Row/Column Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Column name to group by |\\n| `items` | array | No | Pre-defined unique values for the field (preserved from manifest `sharedItems` for round-trip fidelity when source columns have empty cached values) |\\n\\n#### Pivot Page Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Column name to filter on |\\n| `selectedItem` | any | No | Selected filter value |\\n\\n#### Pivot Calculated Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Calculated field name |\\n| `formula` | string | Yes | Pivot formula expression |\\n\\n### Execution Config\\n\\n| Field | Type | Default | Description |\\n|-------|------|---------|-------------|\\n| `defaultTimestampType` | string | `\\"TIMESTAMP\\"` | Default temporal type for date/time columns |\\n| `defaultSourceTimezone` | string | *(none)* | Default source timezone for timestamp parsing |\\n| `preserveRowOrder` | boolean | `true` | `false` stops a workbook\'s loader numbering rows, which leaves LAG/LEAD unavailable. Outputs are written in source row order either way: later stages, summary rows and pivots read them back |\\n| `orderBy` | string or string[] | *(none)* | Column name(s) to sort output by. Overrides `preserveRowOrder` when set. |\\n| `pipeline` | string[] | *(none)* | Calculator sheet names to run in sequence. Each stage\'s output is materialized as a DuckDB table for downstream reference. See the engine pipeline documentation. |\\n| `criteriaMatching` | `\\"excel\\"` or `\\"exact\\"` | `\\"excel\\"` | Rules for the criteria of `SUMIFS`, `COUNTIFS`, `MAXIFS` and the other criteria functions. See below. |\\n\\nExecution config values act as defaults. Runtime parameters passed to `runEce()` or CLI flags (`--pipeline`) take precedence. A runtime `pipeline` does not rescue an invalid declared one: a declaration whose `execution.pipeline` names a missing sheet (or is not an array of strings) fails validation when loaded, whatever pipeline the run passes.\\n\\n#### `criteriaMatching`\\n\\nPicks the rules that every criteria function uses to match cells. It applies to literal criteria (`\\"oil\\"`), reference criteria (`[@Kind]`) and criteria built at run time (`\\"<>\\"&[@Kind]`).\\n\\n| Value | Rules |\\n|-------|-------|\\n| `\\"excel\\"` (default) | Microsoft Excel\'s rules, for literal, reference and runtime-built criteria alike. Text matches without regard to case. `*` and `?` are wildcards and `~` escapes them. `\\"\\"` matches empty cells and cells holding `\\"\\"`, while `\\"=\\"` matches only empty cells. Numbers also match text that reads as the same number. `<`/`>` order number and date cells only; ordering text (`\\">abc\\"`) is refused. With no matching rows, `AVERAGEIFS`/`MEDIANIFS` return NULL. The full rules are in the Criteria Semantics section of the engine specification. |\\n| `\\"exact\\"` | Text matches only when the case is the same. `*` and `?` are ordinary characters. `\\"\\"` and `\\"=\\"` match only empty (NULL) cells, and `\\"<>\\"` matches every cell that is not empty. Plain references (`[@Key]`) are a SQL `=` join, and equality on numbers and dates uses the comparison of 1.3.x. It is not 1.3.x, though: blanks, `\\"=\\"&x`/`\\"<>\\"&x` with text, dates or booleans, numeric criteria on text columns and `<`/`>` (now Excel\'s ordering, with text operands compared case-sensitively) changed (see the `\\"exact\\"` mode section of the engine specification). Use this for ID-style joins where `ab-1` and `AB-1` are different keys. |\\n\\nOnly the declaration (or an overlay\'s `execution` section) can set this, not `runEce()` options or CLI flags. That way a published number can be reproduced from the declaration alone. Absent or `null` means `\\"excel\\"`. Any other value fails validation, and `runEce()` refuses it with `ECE_INVALID_CRITERIA_MATCHING`, also from an overlay run with `onOverlayError: \\"warn\\"` (that option skips other overlay errors, but skipping this one would silently change the rule set). `runEce()` records the rules it used as `criteriaMatching` on its result and on the manifest it writes.\\n\\n### Resolved Declarations\\n\\nA **resolved declaration** is a self-contained declaration where all runtime data sources (e.g., `\\"source\\": \\"runtime\\"`) have been replaced with actual inlined `rows`. This is produced by running `runEce` with `resolveOverrides: true` and then calling `manifestToDeclaration(manifest)`.\\n\\nResolved declarations are useful for:\\n- **Reproducibility** \u2014 re-executing produces identical results with no external dependencies\\n- **Auditing** \u2014 captures the exact inputs used for a calculation run\\n- **Archival** \u2014 all data frozen in a single artifact\\n- **Workbook generation** \u2014 with `populateCalculatorRows: true`, the declaration contains the row count and seed data needed by `declarationToWorkbook` / `ece build` to produce a complete Excel workbook\\n\\nWhen converting a resolved declaration to an Excel workbook, formula cells always use `result: 0` (no pre-computed cached values). The workbook sets `fullCalcOnLoad=\\"1\\"`, so Excel recalculates all formulas on open. This ensures that any discrepancy between Excel\'s results and the Parquet output is immediately visible during inspection.\\n\\nSee the Resolved Declarations section of the engine specification for API and CLI usage.\\n\\n### Column Type Hints\\n\\nSupported type hints (same as the overlay format):\\n\\n`INTEGER`, `BIGINT`, `DOUBLE`, `DECIMAL`, `STRING`, `VARCHAR`, `BOOLEAN`, `DATE`, `TIMESTAMP`, `TIMESTAMP_TZ`, `TIME`, `INTERVAL`\\n\\nType hints can be specified as a plain string or as an object with an optional `format` field:\\n\\n```json\\n\\"columnTypeHints\\": {\\n \\"Value\\": \\"DOUBLE\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" },\\n \\"CreatedAt\\": { \\"type\\": \\"TIMESTAMP\\", \\"format\\": \\"%Y-%m-%dT%H:%M:%S.%gZ\\" }\\n}\\n```\\n\\nThe `CreatedAt` example produces JavaScript-style ISO-8601 UTC strings (`\\"2024-01-15T00:00:00.000Z\\"`), where `Z` is a literal suffix and `%g` is DuckDB\'s millisecond format code.\\n\\nWhen `format` is provided, the column is output as a formatted `VARCHAR` string using DuckDB\'s `STRFTIME` function. This works with all temporal types (`DATE`, `TIMESTAMP`, `TIMESTAMPTZ`) and is useful when downstream consumers expect a specific string representation rather than a native temporal type.\\n\\nThe `format` field survives round-trips through Excel workbooks using the `TYPE:FMT:format` convention in the type hint row (e.g., `DATE:FMT:%Y-%m-%d` or `TIMESTAMP:FMT:%Y-%m-%dT%H:%M:%S`). Colons within the format string are safe \u2014 the `:FMT:` marker delimits the type from the format. For `TIMESTAMPTZ` with both timezone and format, use `TIMESTAMPTZ:timezone:FMT:format` (e.g., `TIMESTAMPTZ:America/New_York:FMT:%Y-%m-%d %H:%M:%S%z`).\\n\\n## What Studio runs\\n\\nThis document describes the calculation engine\u2019s whole format. A calculation runs a subset\\nof it. A declaration that asks for something outside the subset is refused when it is\\nvalidated, saved, imported, activated or run, with the code below, instead of failing at\\nits first run or filing a wrong number.\\n\\n### Supported\\n\\n- One calculator sheet \u2014 the first sheet with `role: \\"calculator\\"` \u2014 whose rows are the\\n project\u2019s assets, or the rows of a table the project connects as a \\"Data table\\" binding.\\n- Data and lookup sheets with typed-in `rows`, or with rows a project binding delivers.\\n- Formulas on a data or lookup sheet, and extra calculator sheets, as long as they do not\\n read the main calculator sheet. Each is checked at validate like the main sheet.\\n- A `union` `source` on a data sheet or an extra calculator sheet, with no `filter`.\\n- A `groupBy` or `crossJoin` `source` on the calculator sheet, with no `filter`, in a project\\n whose rows come from a \\"Data table\\" binding or that is set to No specific assets.\\n- Pivot sheets that total one value per data field with `sum` and no grouping: each is\\n filed as a grand total.\\n- `summaryRows` are accepted, but their values are not filed. Declare a total as a pivot.\\n\\n### Refused\\n\\n- Running sheets as a pipeline (`execution.pipeline`) \u2192 `CALC_PIPELINE_UNSUPPORTED`.\\n- A sheet that reads its rows from a file \u2014 a text `source`, or an object `source` with a\\n `path` \u2014 \u2192 `CALC_FILE_SOURCE_UNSUPPORTED`.\\n- A raw database `filter` on a `union` member or a `crossJoin` `source`, on any sheet\\n \u2192 `CALC_SOURCE_FILTER_UNSUPPORTED`. Filter the data before it is delivered, or write the\\n condition as a formula column.\\n- A `union` `source` on the calculator sheet \u2192 `CALC_CALCULATOR_SOURCE_UNSUPPORTED`.\\n- A `groupBy` or `crossJoin` `source` on any sheet but the calculator, or a `union` `source`\\n on a lookup sheet \u2192 `CALC_SHEET_SOURCE_UNSUPPORTED`. Those rows are never built there, so\\n the sheet would be empty.\\n- A `groupBy` or `crossJoin` `source` on the calculator sheet of a project whose rows are its\\n assets \u2192 `CALC_CALCULATOR_SOURCE_PER_ASSET`.\\n- A formula on a data, lookup or extra calculator sheet that reads the main calculator sheet\\n \u2192 `CALC_SHEET_READS_CALCULATOR`. Such a sheet is computed before the calculator, so the\\n run would fail, or skip its formulas and read their typed-in values instead.\\n- A same-row reference to ANOTHER table, `Factors[@EF]` or `Factors[[#This Row],[EF]]`\\n \u2192 `CALC_SAME_ROW_OTHER_TABLE`. The calculation would read the formula sheet\u2019s own `EF`,\\n not the Factors row; look the value up by a key instead. `[@EF]` and the sheet\u2019s own\\n name or table alias (`Calculator[@EF]` on Calculator) are fine.\\n- A pivot that groups or filters its total, uses a calculated field, totals with anything\\n but `sum`, or lists its values down the rows \u2192 `CALC_PIVOT_GROUPING_UNSUPPORTED`,\\n `CALC_PIVOT_CALCULATED_FIELD_UNSUPPORTED`, `CALC_PIVOT_SUBTOTAL_UNSUPPORTED`,\\n `CALC_PIVOT_DATA_ON_ROWS_UNSUPPORTED`.\\n- A formula function outside the supported list \u2192 `ECE_UNSUPPORTED_FUNCTION`.\\n- A sheet with no text `name`, a `sheets` entry that is not an object, or a sheet whose\\n `role`, `source`, `columnFormulas` or `tableNames` has the wrong shape\\n \u2192 `CALC_SHEET_UNREADABLE`: the calculation cannot be checked, so it is refused.\\n- A formula longer than 16,384 characters \u2192 `CALC_FORMULA_TOO_LONG`. Split it across helper\\n columns.\\n\\n## Validation\\n\\nDeclarations go through two validation stages:\\n\\n### 1. Structural Schema Validation\\n\\nChecks types, required fields, and enum values. Run via `validateDeclarationSchema()`.\\n\\n**Errors** (invalid declaration):\\n- Missing `version` or `sheets`\\n- Empty `sheets` array\\n- Missing or invalid sheet `name`, `role`, or `columns`\\n- Duplicate sheet names or column names within a sheet\\n- Both `rows` and `source` on the same sheet\\n- Data/lookup sheet missing both `rows` and `source` (does not apply to `\\"other\\"` sheets)\\n- No calculator sheet\\n- Invalid `columnFormulas`, `columnTypeHints`, `columnTimezones`, `staticCells`, `summaryRows`, or `literalOverrides` structure\\n- Invalid pivot sheet structure\\n\\n**Warnings** (allowed but flagged):\\n- Version mismatch\\n- `staticCells`, `summaryRows`, or `literalOverrides` on a non-calculator sheet\\n- `literalOverrides` without a `RowID` column\\n- Unknown `columnTypeHints` values\\n\\n### 2. Cross-Reference Validation\\n\\nChecks that references between sheets and columns are consistent. Run via `validateDeclaration()` (which includes structural validation).\\n\\n- Column formula references to non-existent sheets or columns\\n- Summary row formula references to non-existent sheets or columns\\n- `literalOverrides` on a column not in `columnFormulas`\\n- Pivot source sheet not found in declaration\\n- Pivot field references to non-existent source columns\\n\\nCross-reference issues are reported as **warnings** (not errors) to allow forward-looking declarations where external sources may provide columns at runtime.\\n\\n### 3. Strict Validation Mode\\n\\nPass `{ strict: true }` to enable strict validation, which reports additional errors:\\n\\n- **Unknown fields** at any level (top-level, sheet, pivot, execution, etc.) become errors. This catches typos like `\\"columnFormula\\"` instead of `\\"columnFormulas\\"`.\\n- **Version mismatch** becomes an error (instead of a warning in default mode).\\n\\n```javascript\\n// Default mode \u2014 unknown fields silently ignored\\nvalidateDeclarationSchema(declaration); // { valid: true, ... }\\n\\n// Strict mode \u2014 unknown fields become errors\\nvalidateDeclarationSchema(declaration, { strict: true }); // { valid: false, errors: [\'...unknown field \\"columnFormula\\"\'] }\\n```\\n\\nThe `--strict` CLI flag enables strict validation for `ece run` and `ece extract`.\\n\\n## Examples\\n\\n### Simple Calculator\\n\\nA calculator with two formula columns and a summary row:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Site\\", \\"Rate\\", \\"Volume\\", \\"Emissions\\"],\\n \\"rows\\": [\\n { \\"Site\\": \\"Plant A\\", \\"Rate\\": 1.25, \\"Volume\\": 100, \\"Emissions\\": null },\\n { \\"Site\\": \\"Plant B\\", \\"Rate\\": 0.80, \\"Volume\\": 250, \\"Emissions\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Emissions\\": \\"=[@Rate] * [@Volume]\\"\\n },\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Site\\": { \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" },\\n \\"Emissions\\": \\"sum\\"\\n }\\n }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Calculator with Cross-Sheet Formulas\\n\\nA calculator that references a lookup table:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Well ID\\", \\"Region\\", \\"Emissions\\", \\"Factor\\", \\"Adjusted\\"],\\n \\"rows\\": [\\n { \\"Well ID\\": \\"W001\\", \\"Region\\": \\"West\\", \\"Emissions\\": 150, \\"Factor\\": null, \\"Adjusted\\": null },\\n { \\"Well ID\\": \\"W002\\", \\"Region\\": \\"East\\", \\"Emissions\\": 200, \\"Factor\\": null, \\"Adjusted\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Factor\\": \\"=XLOOKUP([@Region], Factors[Region], Factors[Rate])\\",\\n \\"Adjusted\\": \\"=[@Emissions] * [@Factor]\\"\\n }\\n },\\n {\\n \\"name\\": \\"Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### External Data Sources\\n\\nA calculator driven by an external CSV, with a lookup loaded from Parquet:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Timestamp\\", \\"SiteID\\", \\"Reading\\", \\"SiteName\\"],\\n \\"source\\": \\"readings.csv\\",\\n \\"columnFormulas\\": {\\n \\"SiteName\\": \\"=XLOOKUP([@SiteID], Sites[SiteID], Sites[Name])\\"\\n },\\n \\"columnTypeHints\\": {\\n \\"Timestamp\\": \\"TIMESTAMP_TZ\\"\\n },\\n \\"columnTimezones\\": {\\n \\"Timestamp\\": \\"America/Denver\\"\\n }\\n },\\n {\\n \\"name\\": \\"Sites\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"SiteID\\", \\"Name\\", \\"Region\\"],\\n \\"source\\": \\"sites.parquet\\"\\n }\\n ]\\n}\\n```\\n\\n### Summary Rows with Formulas and Value Objects\\n\\nMultiple aggregation types in a single summary row:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Site\\", \\"Status\\", \\"Emissions\\", \\"Intensity\\"],\\n \\"rows\\": [\\n { \\"Site\\": \\"A\\", \\"Status\\": \\"Pass\\", \\"Emissions\\": 100, \\"Intensity\\": null },\\n { \\"Site\\": \\"B\\", \\"Status\\": \\"Fail\\", \\"Emissions\\": 200, \\"Intensity\\": null },\\n { \\"Site\\": \\"C\\", \\"Status\\": \\"Pass\\", \\"Emissions\\": 150, \\"Intensity\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Intensity\\": \\"=[@Emissions] / 1000\\"\\n },\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Site\\": { \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" },\\n \\"Status\\": \\"=COUNTIF(Calculator[Status],\\\\\\"Pass\\\\\\") & \\\\\\"/\\\\\\" & COUNTA(Calculator[Status])\\",\\n \\"Emissions\\": \\"sum\\",\\n \\"Intensity\\": \\"average\\"\\n }\\n }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Pivot Tables\\n\\nA pivot table summarizing calculator output by region:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Region\\", \\"Site\\", \\"Emissions\\", \\"Cost\\"],\\n \\"source\\": \\"site-data.csv\\",\\n \\"columnFormulas\\": {\\n \\"Cost\\": \\"=[@Emissions] * 25\\"\\n }\\n }\\n ],\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Regional Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Region\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"sum\\" },\\n { \\"sourceField\\": \\"Cost\\", \\"subtotal\\": \\"sum\\" },\\n { \\"sourceField\\": \\"Site\\", \\"subtotal\\": \\"count\\", \\"name\\": \\"Site Count\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ]\\n}\\n```\\n\\nA transposed pivot (`dataOnRows`) where values appear as rows:\\n\\n```json\\n{\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"KPI Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"sum\\", \\"name\\": \\"Total Emissions\\" },\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"average\\", \\"name\\": \\"Avg Emissions\\" },\\n { \\"sourceField\\": \\"Site\\", \\"subtotal\\": \\"count\\", \\"name\\": \\"Site Count\\" }\\n ],\\n \\"dataOnRows\\": true,\\n \\"rowGrandTotals\\": false\\n }\\n ]\\n}\\n```\\n\\n### Literal Overrides\\n\\nOverride a formula for specific rows:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"RowID\\", \\"Site\\", \\"CH4 Rate\\", \\"Emissions\\"],\\n \\"rows\\": [\\n { \\"RowID\\": \\"R001\\", \\"Site\\": \\"A\\", \\"CH4 Rate\\": 12.5, \\"Emissions\\": null },\\n { \\"RowID\\": \\"R002\\", \\"Site\\": \\"B\\", \\"CH4 Rate\\": 8.0, \\"Emissions\\": null },\\n { \\"RowID\\": \\"R003\\", \\"Site\\": \\"C\\", \\"CH4 Rate\\": 0, \\"Emissions\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Emissions\\": \\"=[@CH4 Rate] * 100\\"\\n },\\n \\"literalOverrides\\": {\\n \\"Emissions\\": [\\n { \\"rowId\\": \\"R003\\", \\"value\\": 0 }\\n ]\\n }\\n }\\n ]\\n}\\n```\\n\\nRow `R003` uses the literal value `0` instead of the formula. Other rows use the formula as normal.\\n\\n### Execution Config\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Timestamp\\", \\"Value\\"],\\n \\"source\\": \\"timeseries.csv\\",\\n \\"columnTypeHints\\": {\\n \\"Timestamp\\": \\"TIMESTAMP_TZ\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP_TZ\\",\\n \\"defaultSourceTimezone\\": \\"America/New_York\\",\\n \\"preserveRowOrder\\": false\\n }\\n}\\n```\\n\\n### Extra Sheets (role: \\"other\\")\\n\\nWhen a workbook hosts multiple ECE configurations sharing a single `.xlsx`, some sheets may not belong to the current configuration. For example, the facility-emissions-calculator workbook has:\\n\\n- **Config 1**: Calculator + Observations + Constants + ElementMetadata\\n- **Config 2**: Summary (as calculator) + DailyResults + Observations\\n\\nWhen extracting a declaration for Config 1, `extractDeclaration()` captures DailyResults and Summary as `role: \\"other\\"` sheets. These are **inert during ECE execution** \u2014 they are not registered in DuckDB and don\'t participate in the DAG. They exist purely for workbook fidelity so that `declarationToWorkbook()` produces an `.xlsx` with all original sheets intact.\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Emissions\\"],\\n \\"columnFormulas\\": { \\"Emissions\\": \\"=SUMIFS(Obs[value], Obs[date], [@Date])\\" }\\n },\\n {\\n \\"name\\": \\"Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"date\\", \\"value\\"],\\n \\"source\\": \\"observations.csv\\"\\n },\\n {\\n \\"name\\": \\"DailyResults\\",\\n \\"role\\": \\"other\\",\\n \\"columns\\": [\\"Date\\", \\"Total\\"],\\n \\"rows\\": [\\n { \\"Date\\": \\"2025-01-01\\", \\"Total\\": 42 }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Multiple Calculator Sheets\\n\\nA declaration can contain multiple calculator sheets when a single workbook hosts several independent calculation configurations. At runtime, `calculatorSheetName` selects which sheet acts as the calculator \u2014 non-selected calculator sheets become data sheets:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"DailyCalculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Site\\", \\"DailyEmissions\\"],\\n \\"columnFormulas\\": {\\n \\"DailyEmissions\\": \\"=SUMIFS(Obs[value], Obs[date], [@Date], Obs[site], [@Site])\\"\\n }\\n },\\n {\\n \\"name\\": \\"MonthlyCalculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Month\\", \\"Site\\", \\"MonthlyTotal\\"],\\n \\"columnFormulas\\": {\\n \\"MonthlyTotal\\": \\"=SUMIFS(DailyCalculator[DailyEmissions], DailyCalculator[Site], [@Site])\\"\\n }\\n },\\n {\\n \\"name\\": \\"Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"date\\", \\"site\\", \\"value\\"],\\n \\"source\\": \\"observations.parquet\\"\\n }\\n ]\\n}\\n```\\n\\n```javascript\\n// Run the daily calculator \u2014 MonthlyCalculator becomes a data sheet\\nawait runEce({\\n declarationPath: \'./multi-calc.declaration.json\',\\n calculatorSheetName: \'DailyCalculator\',\\n output: \'./daily.parquet\'\\n});\\n\\n// Run the monthly calculator \u2014 DailyCalculator becomes a data sheet\\nawait runEce({\\n declarationPath: \'./multi-calc.declaration.json\',\\n calculatorSheetName: \'MonthlyCalculator\',\\n output: \'./monthly.parquet\'\\n});\\n```\\n\\nWhen `calculatorSheetName` is omitted, the first calculator sheet in the `sheets` array is used.\\n\\n## Design Decisions\\n\\n### Warnings vs. Errors\\n\\nStructural problems (missing fields, wrong types, duplicate names) are **errors** that prevent loading. Cross-reference problems (formula references non-existent columns) are **warnings** that allow the declaration to load. This accommodates declarations where external data sources provide columns at runtime that aren\'t known at validation time.\\n\\n### Case-Insensitive Matching\\n\\nColumn and sheet name matching during cross-reference validation is case-insensitive, consistent with the overlay format and Excel\'s behavior. A formula referencing `\\"emissions\\"` will match a column declared as `\\"Emissions\\"`.\\n\\n### Relationship to Overlay Format\\n\\nThe declaration and overlay formats serve complementary purposes:\\n\\n- **Declaration** is a standalone format: it defines a workbook from scratch\\n- **Overlay** is a delta format: it captures modifications on top of a base (Excel workbook or declaration)\\n\\nOverlays can be applied to declarations at runtime, just like they can be applied to Excel templates. This enables scenarios like a shared base declaration with per-customer or per-scenario overlays that swap lookup data, modify formulas, or add columns \u2014 without duplicating the entire declaration.\\n\\nThey share many of the same field shapes (`columnFormulas`, `columnTypeHints`, `columnTimezones`, `staticCells`, type hints) and both produce the same manifest structure that the downstream pipeline consumes.\\n\\n### Excel Interop\\n\\nDeclarations can be converted to and from Excel workbooks:\\n\\n- **Workbook \u2192 Declaration**: `extractDeclaration()` loads an `.xlsx` (with optional overlay) and produces a declaration capturing all functionally significant information. Visual formatting is intentionally dropped.\\n- **Declaration \u2192 Workbook**: `declarationToWorkbook()` builds a minimal `.xlsx` using `WorkbookBuilder`, producing a template that can be opened in Excel and round-tripped through the overlay system.\\n\\nThis enables workflows like: extract a declaration from an existing workbook, edit the JSON, then optionally convert back to Excel for review.\\n\\n### Calculator Data is Optional\\n\\nA calculator sheet can omit both `rows` and `source`. This supports UNIQUE/FILTER-driven calculators where the data comes from row generator formulas that pull from data sheets at execution time.\\n\\n## Best Practices\\n\\n1. **Declare all columns explicitly** \u2014 The `columns` array defines the canonical column order and is required even when data comes from an external `source`\\n\\n2. **Use `source` for large datasets** \u2014 Inline `rows` are convenient for small lookup tables; use `source` with CSV, Parquet, JSON, or JSONL files for large data sheets\\n\\n3. **Use ISO-8601 for dates** \u2014 Always use `YYYY-MM-DD` format for dates in inline rows. This ensures correct sorting, unambiguous interpretation, and proper type detection\\n\\n4. **Validate before executing** \u2014 Use `validateDeclaration()` to catch problems early. It checks both structural integrity and cross-reference consistency\\n\\n5. **Use type hints for ambiguous columns** \u2014 When a column could be interpreted as multiple types (e.g., a date stored as a string), add a `columnTypeHints` entry to make the intent explicit\\n\\n6. **Keep execution config in the declaration** \u2014 If your declaration always needs specific timezone or timestamp settings, include them in the `execution` section rather than relying on runtime parameters\\n\\n7. **Prefer one calculator sheet per declaration** \u2014 Most declarations need only one calculator sheet. When a workbook hosts multiple calculator configurations, a single declaration can include multiple `role: \\"calculator\\"` sheets. Use `calculatorSheetName` at runtime to select which one to execute \u2014 non-selected calculator sheets become data sheets, available for cross-sheet references\\n"}},{"uri":"calc://functions","name":"Supported formula functions","description":"Every spreadsheet function the engine accepts, plus the documented rewrite for each commonly-attempted function it does not.","mimeType":"text/markdown","source":{"kind":"generated","text":"# Formula functions the calculation engine accepts\\n\\nA formula using anything outside this list is refused at validate with\\n`ECE_UNSUPPORTED_FUNCTION`. The list is the engine registry itself, so it is exactly\\nwhat the validator checks against.\\n\\n## Supported (73)\\n\\n- `LET`\\n- `IF`\\n- `IFS`\\n- `IFERROR`\\n- `SUM`\\n- `SUMIFS`\\n- `COUNTIFS`\\n- `SUMIF`\\n- `COUNT`\\n- `COUNTIF`\\n- `COUNTA`\\n- `AVERAGEIF`\\n- `MAXIFS`\\n- `MINIFS`\\n- `AVERAGEIFS`\\n- `MEDIAN`\\n- `MEDIANIFS`\\n- `XLOOKUP`\\n- `AND`\\n- `OR`\\n- `NOT`\\n- `MAX`\\n- `MIN`\\n- `ABS`\\n- `ROUND`\\n- `AVERAGE`\\n- `SUMPRODUCT`\\n- `UNIQUE`\\n- `FILTER`\\n- `SINGLE`\\n- `SWITCH`\\n- `SQRT`\\n- `POWER`\\n- `LOG`\\n- `LOG10`\\n- `LN`\\n- `EXP`\\n- `MOD`\\n- `CEILING`\\n- `FLOOR`\\n- `SIGN`\\n- `INT`\\n- `TRUNC`\\n- `PI`\\n- `RAND`\\n- `LEN`\\n- `TRIM`\\n- `UPPER`\\n- `LOWER`\\n- `CONCAT`\\n- `TEXTJOIN`\\n- `LEFT`\\n- `RIGHT`\\n- `MID`\\n- `REPT`\\n- `SUBSTITUTE`\\n- `FIND`\\n- `SEARCH`\\n- `TEXT`\\n- `TODAY`\\n- `NOW`\\n- `DATE`\\n- `YEAR`\\n- `MONTH`\\n- `DAY`\\n- `DATEDIFF`\\n- `ECE.ROWNUM`\\n- `ECE.RANK`\\n- `COUNTDISTINCT`\\n- `ECE.LOOKUPWHERE`\\n- `ISBLANK`\\n- `ISNUMBER`\\n- `ISTEXT`\\n\\n## Not supported, and what to write instead (9)\\n\\nThese are the functions authors reach for most often that the engine does not\\nimplement. Each carries the rewrite that expresses the same intent.\\n\\n- **`OFFSET`** \u2014 OFFSET is incompatible with the ECE static-analysis model. For cross-row references (period-over-period, previous row), use a relative reference like `=B2` from row 3 \u2014 it compiles to LAG/LEAD window functions.\\n- **`INDIRECT`** \u2014 INDIRECT is incompatible with the ECE static-analysis model \u2014 references must be resolvable statically. Build the reference directly, or for cross-row use a relative reference (e.g. `=B2` from row 3, which compiles to LAG/LEAD).\\n- **`INDEX`** \u2014 INDEX/MATCH is not implemented. Use XLOOKUP \u2014 it covers the same exact-match and table-lookup cases.\\n- **`MATCH`** \u2014 INDEX/MATCH is not implemented. Use XLOOKUP \u2014 it covers the same exact-match and table-lookup cases.\\n- **`VLOOKUP`** \u2014 VLOOKUP is not implemented. Use XLOOKUP \u2014 it supports the same lookup semantics and is column-order-independent.\\n- **`HLOOKUP`** \u2014 HLOOKUP is not implemented. Transpose the lookup table to be row-oriented and use XLOOKUP.\\n- **`CHOOSE`** \u2014 CHOOSE is not implemented. Use SWITCH or IFS for positional / conditional selection.\\n- **`ISERROR`** \u2014 ISERROR is not implemented. Wrap the inner expression in IFERROR(expr, fallback) to express the same intent.\\n- **`VALUE`** \u2014 VALUE is not implemented. Coerce the column type via columnTypeHints, or use arithmetic (e.g. `col * 1`) to force numeric context.\\n\\n## Referring to the current row inside a calculator formula\\n\\nA `columnFormulas` entry is authored once and evaluated for every generated row, so a\\nreference to the row the formula is on has three written forms. They mean the same\\nthing, and the served examples use all three:\\n\\n- `[@Column]` \u2014 Excel\u2019s own display form, and the one the format reference uses\\n throughout.\\n- `Calculator[[#This Row],[Column]]` \u2014 the identical structured reference in the form a\\n programmatic writer emits; Excel renders it back as `[@[Column]]`.\\n- `$A3` \u2014 an A1-style cell address, and the ONLY one of the three with a precondition.\\n A cell address resolves by OFFSET from the sheet\u2019s `formulaSourceRow`, so `$A3` means\\n THIS row only when the sheet declares `formulaSourceRow: 3`. Both example\\n declarations do, and so does every seeded methodology \u2014 3 is the first data row of\\n the workbook convention they all follow (row 1 the column type hints, row 2 the\\n headers). Copy the anchor with the formula: without it the same text means a\\n different row or refuses at RUN time, and validate only soft-warns. It also names its\\n column by POSITION, so a column inserted ahead of it repoints the formula silently \u2014\\n prefer a named form where you have the choice.\\n\\nThe table name in the two structured forms must be the formula\u2019s OWN sheet (or one of\\nits `tableNames`). Naming another table \u2014 `Factors[@EF]` on the Calculator sheet \u2014 is\\nrefused with `CALC_SAME_ROW_OTHER_TABLE`: the calculation would read the Calculator\u2019s own\\n`EF`, not the Factors row Excel means. Look another table\u2019s value up by a key instead,\\nfor example `XLOOKUP([@Gas], Factors[Gas], Factors[EF])`.\\n"}},{"uri":"calc://diagnostics","name":"Validation diagnostics","description":"What each validation diagnostic code means in author-facing terms, and how to recover from it.","mimeType":"text/markdown","source":{"kind":"generated","text":"# Validation diagnostics: what each code means and how to recover\\n\\nEvery code the validator, the import inspection and a run can report, with the\\nauthor-facing meaning and the recovery. `ECE_*` codes come from the calculation\\nengine; `CALC_*` codes from this domain.\\n\\n## Codes (183)\\n\\n### `ECE_UNSUPPORTED_FUNCTION`\\n\\n**Means.** A formula uses a function outside the supported engine registry.\\n\\n**Recover.** Rewrite the formula with a supported function.\\n\\n### `ECE_FORMULA_PARSE_ERROR`\\n\\n**Means.** A formula could not be parsed. Its syntax is malformed.\\n\\n**Recover.** Fix the syntax: unmatched brackets, stray operators, or unsupported reference styles.\\n\\n### `ECE_FORMULA_TRANSLATE_ERROR`\\n\\n**Means.** A formula parsed but could not be translated to the engine SQL plan.\\n\\n**Recover.** Verify argument types and that every referenced column exists.\\n\\n### `ECE_INTERNAL`\\n\\n**Means.** An internal engine error. It is not a problem with the declaration itself.\\n\\n**Recover.** Report it with the formula and the details of this finding.\\n\\n### `ECE_UNRESOLVED_SHEET`\\n\\n**Means.** A formula references a sheet that is not present in the declaration.\\n\\n**Recover.** Add the missing sheet, or correct the reference.\\n\\n### `ECE_UNRESOLVED_COLUMN`\\n\\n**Means.** A formula references a column that is not present on the target sheet.\\n\\n**Recover.** Add the missing column, or correct the reference.\\n\\n### `ECE_UNCLASSIFIED_SHEET_REFERENCE`\\n\\n**Means.** A referenced sheet exists but is not classified as a data or lookup sheet.\\n\\n**Recover.** Set the sheet\u2019s role to data or lookup, or rename it to start with Data__ or Lookup__.\\n\\n### `ECE_MULTIPLE_UNIQUE`\\n\\n**Means.** A calculator has more than one row generator. UNIQUE and FILTER both count, and only one is supported.\\n\\n**Recover.** Combine the row generators, or split the logic into separate calculators.\\n\\n### `ECE_UNIQUE_NOT_STANDALONE`\\n\\n**Means.** UNIQUE/FILTER is nested inside a larger expression; it must be the whole column formula.\\n\\n**Recover.** Move the wrapping logic into a downstream column.\\n\\n### `ECE_CIRCULAR_DEPENDENCY`\\n\\n**Means.** The formula dependency graph contains a cycle.\\n\\n**Recover.** Introduce an intermediate column, or use a LAG/LEAD relative reference.\\n\\n### `ECE_TABLE_SPILL_CONFLICT`\\n\\n**Means.** A spill column coexists with a conflicting fixed-row-count construct (reserved: no check reports it yet).\\n\\n**Recover.** Move one construct onto a separate sheet.\\n\\n### `ECE_MISSING_TYPE_HINT`\\n\\n**Means.** A column has no explicit type hint; the engine inferred one.\\n\\n**Recover.** Give the column a type, so its values are not converted in ways you don\u2019t expect (API: a `columnTypeHints` entry).\\n\\n### `ECE_AMBIGUOUS_SHEET_ROLE`\\n\\n**Means.** A sheet role is ambiguous (reserved: no check reports it yet).\\n\\n**Recover.** Start the sheet\u2019s name with Data__ or Lookup__, or set its role when you import the file.\\n\\n### `ECE_NO_CALCULATOR`\\n\\n**Means.** The declaration has no calculator sheet.\\n\\n**Recover.** Add at least one sheet whose role is \\"calculator\\".\\n\\n### `ECE_LITERAL_OVERRIDE_NO_EFFECT`\\n\\n**Means.** A literal override targets a column that has no formula, so it does nothing.\\n\\n**Recover.** Remove the override, or give the column a formula (API: add it to `columnFormulas`).\\n\\n### `ECE_AMBIGUOUS_COLUMN_REFERENCE`\\n\\n**Means.** Two columns on a sheet have names that differ only in letter case, so a reference to either cannot tell them apart (Excel matches column names without regard to case).\\n\\n**Recover.** Rename one of the two columns (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DUPLICATE_COLUMN_NAME`\\n\\n**Means.** A sheet has two columns whose names differ only in letter case. Excel treats them as one name, so the calculation cannot tell which a formula reads.\\n\\n**Recover.** Rename one of the two columns so the names differ by more than letter case (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DUPLICATE_TABLE_NAME`\\n\\n**Means.** Two sheets answer to the same table name up to letter case. A sheet answers to its name, its table names, and the name the workbook gives its table. A table reference cannot tell them apart.\\n\\n**Recover.** Rename one of the sheets, or change its table names, so no two sheets share one (API: `name` / `tableNames`).\\n\\n### `ECE_RESERVED_COLUMN_NAME`\\n\\n**Means.** A column is named like one the engine adds to its own tables (`__row_num__`, `__generator_order__`, `__union_order__`, or a name starting with `__ece_` or `__calc_`, in any letter case).\\n\\n**Recover.** Rename the column (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DATE_PART_OUT_OF_RANGE`\\n\\n**Means.** DATE was given a year below -32768. Excel\u2019s answer for such a year has not been checked, so the calculation refuses it rather than file a date that may be wrong.\\n\\n**Recover.** Check the year the formula passes to DATE; a real year is 1900\u20139999 (0\u20131899 reads as 1900 plus the year, as in Excel).\\n\\n### `ECE_DATE_SERIAL_OUT_OF_RANGE`\\n\\n**Means.** A number in a date column, or in a date-formatted cell, is no date Excel can show (below 0, or after 9999-12-31 23:59:59). Excel shows such a cell as #####.\\n\\n**Recover.** Check the formula\u2019s arithmetic or the source value, or make the column a number column (API: a `DOUBLE` entry in `columnTypeHints`). In a workbook, correct the cell or give it a number format.\\n\\n### `ECE_CRITERIA_TEXT_ORDERING`\\n\\n**Means.** A SUMIFS-style criterion orders text by a text value (\\">abc\\"). Excel orders text by the computer\u2019s language settings, which the calculation does not reproduce, so it refuses rather than match different rows.\\n\\n**Recover.** Compare numbers or dates instead, or switch the calculation to exact matching for case-sensitive ordering (API: `execution.criteriaMatching: \\"exact\\"`).\\n\\n### `ECE_CRITERIA_AMBIGUOUS_COLUMN`\\n\\n**Means.** A criteria range, an XLOOKUP range or a lookup value holds cells whose kind (number or text) the calculation cannot tell before the run. Excel knows each cell\u2019s kind; the calculation needs it up front to match as Excel does.\\n\\n**Recover.** Give the column a type (API: a `columnTypeHints` entry), or compute it without mixing number and text results.\\n\\n### `ECE_MIXED_VALUE_COLUMN`\\n\\n**Means.** A SUMIFS-style, COUNTDISTINCT or LOOKUPWHERE value range mixes numbers with text or TRUE/FALSE cells. Excel leaves the text and TRUE/FALSE cells out; the calculation reads the column as one kind and cannot.\\n\\n**Recover.** Make the column\u2019s values numbers, leaving missing values blank.\\n\\n### `ECE_IFERROR_TEXT_VALUE`\\n\\n**Means.** IFERROR with a number fallback met a text value that is not a number or a date. Excel returns the text; the calculation\u2019s column holds numbers and would have filed 0, so it refuses.\\n\\n**Recover.** Use a text fallback such as \\"\\" (IFERROR(x, \\"\\")), or look up a numeric column.\\n\\n### `ECE_FORMULA_NOT_IN_COLUMNS`\\n\\n**Means.** A sheet has a formula for a column it does not list, so the formula would be dropped from the results without a word.\\n\\n**Recover.** Add the column to the sheet, or remove the formula (API: list it in `columns`, or delete it from `columnFormulas`). From a workbook this usually means an Excel table column whose name no longer matches its header cell.\\n\\n### `ECE_SELF_AGGREGATE_COMPUTED_COLUMN`\\n\\n**Means.** A formula totals or looks up a computed column of its own sheet. That column is not computed yet when the formula runs, so the result would not be Excel\u2019s.\\n\\n**Recover.** Use [@Column] for the same row\u2019s value. A whole-column total or lookup over a computed column needs a calculation that computes it in an earlier step.\\n\\n### `ECE_WHOLE_COLUMN_SELF_RANGE`\\n\\n**Means.** A formula reads its own sheet\u2019s whole column (SUM(X:X)), which includes its own cell. Excel calls that a circular reference.\\n\\n**Recover.** For a column total, use a summary row (API: `summaryRows`).\\n\\n### `ECE_BOUNDED_RANGE_PARTIAL`\\n\\n**Means.** A range with fixed rows (C2:C6) misses some data rows, starts on the header, or ends below the data where a blank would change the result. The calculation does not read a part of a table by row position.\\n\\n**Recover.** Use a whole-column reference (Sheet!C:C) or a table column (Table[Column]); to use only some rows, choose them with SUMIFS-style criteria on a key or date column.\\n\\n### `ECE_BOUNDED_RANGE_RUNTIME_ROWS`\\n\\n**Means.** A range with fixed rows covers the rows typed into the sheet, but the run may deliver more rows, which would fall outside it.\\n\\n**Recover.** Use a whole-column reference (Sheet!C:C), a table column (Table[Column]), or a range ending at row 1048576.\\n\\n### `ECE_RELATIVE_ROW_RANGE`\\n\\n**Means.** A range with relative rows (SUM(C2:C6)) moves down one row on every row in Excel. The calculation reads one range for every row, so it refuses rather than file different values.\\n\\n**Recover.** Anchor both rows with $ ($C$2:$C$6) so every row reads the same rows, or use a table column (Table[Column]) or a whole column (Sheet!C:C).\\n\\n### `ECE_PARTIAL_RUNNING_RANGE`\\n\\n**Means.** A running range (SUM($B$2:B2)) does not start on the sheet\u2019s first data row, ends on another row than the formula\u2019s own, or is used where the calculation cannot keep a running total.\\n\\n**Recover.** For a running total, anchor the start on the first data row and end on the formula\u2019s own row (SUM($B$2:B2) when data starts on row 2), in SUM, AVERAGE, MAX, MIN or COUNTA. For a fixed set of rows, anchor both rows ($B$2:$B$6).\\n\\n### `ECE_ABSOLUTE_ROW_UNRESOLVED`\\n\\n**Means.** A cell reference anchors its row with $ ($B$2) on a row the calculation cannot place: not a data row of the sheet, or a sheet whose rows it does not keep in order.\\n\\n**Recover.** Anchor the row on a data row of the sheet, put the constant in a cell above the header (API: `staticCells`), or look the value up by a key with XLOOKUP or SUMIFS.\\n\\n### `ECE_RANGE_NOT_NUMERIC`\\n\\n**Means.** SUM, AVERAGE, MAX, MIN, MEDIAN, SUMPRODUCT or COUNT reads a column holding text or TRUE/FALSE. Excel skips those cells; the calculation reads the column as one kind and cannot, so it refuses rather than file a different number.\\n\\n**Recover.** Make every cell of the column a number or blank and give it a number type (API: a `DOUBLE` entry in `columnTypeHints`), or total a numeric column.\\n\\n### `ECE_SOURCE_COLUMNS_MISMATCH`\\n\\n**Means.** The rows a sheet was given at run time carry other columns than the sheet declares (a missing one, or extra ones).\\n\\n**Recover.** Give the sheet exactly its declared columns, with the same names (letter case may differ) and no others. For a connected dataset, its columns must match the sheet\u2019s.\\n\\n**Next.** open-bindings\\n\\n### `ECE_SUMMARY_ROW_UNTRANSLATED`\\n\\n**Means.** A summary-row formula is not one the calculation can compute: it must be a single total over its own column\u2019s data rows, or over another column of the sheet.\\n\\n**Recover.** Write the summary as one total over the column (SUM(B2:B6), SUM(B:B) or SUM(Calculator[col])) (API: `summaryRows`).\\n\\n### `ECE_SUMMARY_ROW_FAILED`\\n\\n**Means.** A summary-row formula failed on the run\u2019s values. The run is refused rather than filing the summary row empty.\\n\\n**Recover.** Read the message for the failing formula and fix it, or the values it totals (API: `summaryRows`).\\n\\n### `ECE_EXPLAIN_REQUEST`\\n\\n**Means.** The request to explain a figure is not one the engine can answer: no such column or row, a row key compared with a column of another type, or the run\u2019s input types given without its row counts (or the other way round).\\n\\n**Recover.** Ask again for a column and row the calculation has, giving the run\u2019s input types and row counts together. (API: `inputTypes` with `runRowCounts`.)\\n\\n### `ECE_EXPLAIN_ROW_NOT_FOUND`\\n\\n**Means.** No row of the calculation matches the row asked for, so there is nothing to explain.\\n\\n**Recover.** Ask for a row the run computed (for an asset, one in the run\u2019s asset selection).\\n\\n### `ECE_EXPLAIN_ROW_NOT_UNIQUE`\\n\\n**Means.** Several rows of the calculation match the row asked for, so it is not one figure.\\n\\n**Recover.** Name the row by a key that picks exactly one row, or by its row number.\\n\\n### `ECE_EXPLAIN_WINDOW_FUNCTION`\\n\\n**Means.** The formula ranks or numbers rows (ECE.RANK, ECE.ROWNUM), so its value depends on the order of every row and cannot be explained from one.\\n\\n**Recover.** Explain a column that reads the ranked column instead; the rank appears there as one piece.\\n\\n### `ECE_EXPLAIN_RUNNING_RANGE`\\n\\n**Means.** The formula reads a running range (SUM($B$2:B2)), whose value is every row so far, so it cannot be explained from one row.\\n\\n**Recover.** Explain a column that reads the running total instead.\\n\\n### `ECE_EXPLAIN_PIVOT_CELL`\\n\\n**Means.** A pivot cell totals many rows, so it is not explained piece by piece.\\n\\n**Recover.** Explain the calculator rows the pivot totals.\\n\\n### `ECE_EXPLAIN_GROUPED_SOURCE`\\n\\n**Means.** The column is an input of a grouped or joined calculator source: its value comes from another sheet\u2019s rows, not from a formula.\\n\\n**Recover.** Explain one of the calculator\u2019s formula columns instead.\\n\\n### `ECE_EXPLAIN_INPUT_TYPES`\\n\\n**Means.** The input column types given for the explanation do not match the calculator\u2019s inputs as the run registered them, so it would not reproduce the run.\\n\\n**Recover.** Explain with the run\u2019s own input types, unchanged, covering every input column (API: `inputTypes`).\\n\\n### `ECE_EXPLAIN_NEEDS_RUN_ROWS`\\n\\n**Means.** The explanation was given a different number of rows of a sheet than the run had, so a lookup or total would read other rows than the run did.\\n\\n**Recover.** Explain with every row of that sheet the run had (API: `runRowCounts`).\\n\\n### `ECE_EXPLAIN_VOLATILE`\\n\\n**Means.** The column, or a column it reads, uses RAND, NOW or TODAY, whose value changes every time it is computed, so no explanation reproduces it.\\n\\n**Recover.** Replace the volatile function with a fixed value or an input, then re-run.\\n\\n### `ECE_EXPLAIN_PIPELINE`\\n\\n**Means.** The calculation runs as a pipeline of stages; only a single calculator is explained.\\n\\n**Recover.** Explain a calculation without a pipeline (API: `execution.pipeline`).\\n\\n### `ECE_PIPELINE_STAGE_NOT_FOUND`\\n\\n**Means.** The pipeline names a sheet the calculation does not have (API: `execution.pipeline`).\\n\\n**Recover.** Correct the stage name or add the sheet. A calculation does not run pipelines yet, so removing the pipeline is the usual fix.\\n\\n### `ECE_PIPELINE_STAGE_ORDER`\\n\\n**Means.** A pipeline stage reads a stage that runs after it (API: `execution.pipeline`).\\n\\n**Recover.** Reorder the stages, or remove the read. A calculation does not run pipelines yet.\\n\\n### `ECE_SUPPLEMENTAL_SHEET_SKIPPED`\\n\\n**Means.** A data or lookup sheet\u2019s formulas read the main calculator sheet, so the run skips that sheet and its formulas are never computed.\\n\\n**Recover.** Move those formulas onto the calculator sheet, or rewrite them so they do not read it (API: the sheet\u2019s `columnFormulas`).\\n\\n### `ECE_SKIPPED_SHEET_READ`\\n\\n**Means.** A formula reads a computed column of a sheet the run skips (because that sheet reads the main calculator), so the value would never be computed.\\n\\n**Recover.** Move the skipped sheet\u2019s formulas onto the calculator sheet, or stop reading them, so every value read is computed.\\n\\n### `ECE_CRITERIA_INTERVAL`\\n\\n**Means.** A SUMIFS-style criteria range holds time spans (an INTERVAL column). Excel has no such cell, so the calculation cannot match criteria against it as Excel would.\\n\\n**Recover.** Give the column a number type holding the span as a fraction of a day, or a text type (API: `columnTypeHints`).\\n\\n### `ECE_CRITERIA_1900_LEAP_DAY`\\n\\n**Means.** A criterion or a text cell names a time on 1900-02-29, a day Excel shows that never existed. The calculation cannot hold it as a date, so it refuses rather than match the wrong day.\\n\\n**Recover.** Correct the date in the criterion or the cell.\\n\\n### `ECE_INVALID_CRITERIA_MATCHING`\\n\\n**Means.** The calculation\u2019s matching setting is neither excel nor exact (API: `execution.criteriaMatching`).\\n\\n**Recover.** Use \\"excel\\" (the default, Excel\u2019s rules) or \\"exact\\" (plain equality), or remove the setting (API: `execution.criteriaMatching`).\\n\\n### `ECE_SQL_GEN_SKIPPED`\\n\\n**Means.** SQL generation was skipped because bind-time errors were present.\\n\\n**Recover.** Fix the other errors first, then check again to see any findings that remain.\\n\\n### `ECE_EXTRACTION_WARNING`\\n\\n**Means.** A loader heuristic flagged a structure (sparse formulas, summary rows, inconsistent source rows).\\n\\n**Recover.** Check the flagged part of the workbook. The calculation still runs, but it may not read the workbook the way you meant.\\n\\n### `CALC_UNRESOLVED_VARIABLE`\\n\\n**Means.** A formula reads a sheet the calculation does not have, or a sheet that ships no rows with nothing connected to supply them. At import this holds the import; on a project it refuses activation, because a run would read nothing for the formula and an empty read adds up to 0, a made-up figure filed as a governed number.\\n\\n**Recover.** At import, add the missing sheet to the file (or stop ignoring it (API: drop it from `sheetRoles`)) or correct the formula, then read the file again. On a project, connect the sheet as a Data table under Connect inputs (API: `kind: \\"dataTable\\"`), or connect the value itself as an Observation or an Asset property (API: `kind: \\"observation\\"` or `kind: \\"assetProperty\\"`). A value that really is fixed can be a Constant (API: `kind: \\"constant\\"`). If a formula names a sheet the calculation does not have, the name is a typo: correct it and use the new version on the project.\\n\\n**Next.** open-mapping\\n\\n### `CALC_DATA_SHEET_UNBOUND`\\n\\n**Means.** A `role: \\"data\\"` sheet ships its own rows inside the pinned declaration, the calculator reads it, and no binding on the project delivers it, so every run computes over the rows the methodology shipped, which are usually the vendor\u2019s samples rather than the tenant\u2019s activity data, and files them as governed numbers. An ACTIVATION rule: import and the library report the same condition as a warning, because a methodology being stored or browsed files nothing.\\n\\n**Recover.** Under Connect inputs, connect the sheet to a dataset as a Data table, so its rows come from the dataset. If the rows in the file are the real data, add them to Data as a dataset and connect that, so they have version history. (API: `kind: \\"dataTable\\"`)\\n\\n### `CALC_DATA_TABLE_BINDING_LIMIT`\\n\\n**Means.** The composition carries more than one \\"Data table\\" binding, or a \\"Data table\\" binding beside an \\"Observation\\", \\"Asset property\\", \\"Asset aggregate\\" or \\"Asset count\\" binding. A row-generated calculator derives its own row set from one delivered table, so a second table has no row spine to land on and a per-asset value has no row to land on; every run of such a project refuses. An ACTIVATION rule: the same limit refuses at run time, and activation reports it before the project goes ACTIVE.\\n\\n**Recover.** Keep one Data table connection and remove the others. To combine several tables, add them to Data as one dataset and connect that. To feed a value per asset, remove the Data table connection, or add the value to the connected table as a column.\\n\\n### `CALC_CONSTANT_MISSING`\\n\\n**Means.** A constant the calculation uses has no value that covers this period.\\n\\n**Recover.** Add a value for the constant that covers this period to its reference data, or connect the input to reference data that has one, or correct the project\u2019s reporting window. Then run the period again.\\n\\n### `CALC_CONSTANT_CHANGES_IN_PERIOD`\\n\\n**Means.** A constant the calculation uses has a value that changes during this period: at least one row of its reference data starts or ends partway through the period (its validFrom or validTo date falls inside it), so no single value covers the whole period. The run stopped rather than pick one.\\n\\n**Recover.** Line the change up with a period boundary: end the old row on the last day of a period and start the new row on the first day of the next one, so one row covers each whole period. Write each end as a date: a date covers that whole day, while a date with a time covers only up to that instant, so a time even a second before the period ends does not cover it. Or connect the input to reference data with one row for the whole period. Then run the period again.\\n\\n### `CALC_LOOKUP_FACTOR_CHANGES_IN_PERIOD`\\n\\n**Means.** A value in a Lookup table changes during this period: at least one of its rows starts or ends partway through the period (its validFrom or validTo date falls inside it), so no single value covers the whole period. The run stopped rather than read the value as 0.\\n\\n**Recover.** Line the change up with a period boundary: end the old row on the last day of a period and start the new row on the first day of the next one, so one row covers each whole period. A value that stops applying partway through must end at a period boundary too. Write each end as a date: a date covers that whole day, while a date with a time covers only up to that instant, so a time even a second before the period ends does not cover it. Then run the period again.\\n\\n### `CALC_REFERENCE_VALIDITY_COLUMN_NEAR_MISS`\\n\\n**Means.** A Lookup table or constant\u2019s dataset has a column that looks like a validity date (such as ValidFrom, valid from or VALID-TO) but is not named exactly validFrom or validTo. Only those exact names date a table\u2019s rows, so the rows were not dated by that column: a row with no exactly named date on that side is read as open there, valid however far the period reaches. The run still completes.\\n\\n**Recover.** Rename the column to validFrom or validTo, exactly as written here, publish the dataset, and run the period again. If the rows are meant to apply to every period, nothing needs fixing. A dataset from SDP also carries its own valid_from and valid_to columns beside record_id and manifest_id: those are system dates and never count.\\n\\n### `CALC_EMPTY_COVERAGE`\\n\\n**Means.** No observation data covers the selected assets for the run period.\\n\\n**Recover.** Confirm the observation source has rows for these assets and this period.\\n\\n### `CALC_SCOPE_EMPTY_AT_PERIOD_END`\\n\\n**Means.** No assets were in the project\u2019s asset selection at the end of this period, although the same asset selection matches assets today. The run stopped rather than replace the period\u2019s published results with an empty one.\\n\\n**Recover.** Check the project\u2019s reporting window against when these assets were added: a window that starts before them has nothing to run over. Correct the window or the asset selection, then run the period again. An asset selection that is empty at both times still publishes, with a warning.\\n\\n### `CALC_DATA_TABLE_TARGET_NOT_DATA_SHEET`\\n\\n**Means.** The Data table connection points at a sheet of the calculation that isn\u2019t a data sheet. Your table would be ignored, and every run would calculate over the sample rows the calculation ships with.\\n\\n**Recover.** Point the connection at one of the calculation\u2019s data sheets (the refusal names them). If the calculation should read a new table, add a data sheet for it, publish the calculation again, and connect that sheet.\\n\\n### `CALC_DATA_TABLE_CONTRIBUTED_NOTHING`\\n\\n**Means.** The bound dataTable delivered no rows to ANY subject in the run, yet the run still produced results. The bound source cannot have supplied them, so they came from the declaration\u2019s own rows. The run is FAILED and promotes nothing. Partial coverage is not this: a run whose table covers some of the run\u2019s subjects and not others still completes.\\n\\n**Recover.** Check that the binding names the right data sheet and the right dataset, that the promoted version carries rows for this period, and that the assetColumn values match the selected assets.\\n\\n### `CALC_DATA_TABLE_RESULT_OUTSIDE_SCOPE`\\n\\n**Means.** A run with a Data table connection keyed its results to ids that are not assets in the project\u2019s asset selection. The Calculator\u2019s asset column holds rows typed into the workbook rather than values taken from the connected data, so the results would be filed under subjects that are not your assets, and a formula that looks data up by that column matches nothing, so every value would be 0. The run is FAILED and files nothing.\\n\\n**Recover.** Make the Calculator\u2019s asset column a formula over the connected data sheet \u2014 the message names both, for example =UNIQUE(Data__Readings[AssetId]) \u2014 so its rows are the assets the data carries. Pin the corrected version on the project and run the period again. (API: the column is the `dataTable` binding\u2019s `assetColumn`)\\n\\n### `CALC_NARROW_SCOPE`\\n\\n**Means.** The asset selection is unusually narrow, possibly from an over-restrictive selector.\\n\\n**Recover.** Review the selector; proceed if the narrow asset selection is intended.\\n\\n### `CALC_VOLATILE_FUNCTION`\\n\\n**Means.** A formula uses a volatile function (RAND/NOW/TODAY); its value is non-reproducible.\\n\\n**Recover.** Replace it with an input for the period or a fixed value.\\n\\n### `CALC_SHADOWED_CONSTANT`\\n\\n**Means.** A project-local reference dataset shadows a shared constant of the same code.\\n\\n**Recover.** Confirm the shadow is intended; the project\u2019s own value takes precedence.\\n\\n### `CALC_EMPTY_RESULT_PROMOTED`\\n\\n**Means.** A COMPLETED run produced zero result cells; the empty result set was promoted and supersedes this period\u2019s previous Tier-2 publish under the warn-and-promote policy.\\n\\n**Recover.** If the empty result is not the truth, fix the asset selection or the observation data and re-run the period \u2014 the re-run\u2019s promotion supersedes the empty publish (version history keeps both).\\n\\n### `CALC_PIVOT_GROUPING_UNSUPPORTED`\\n\\n**Means.** A pivot table breaks down or filters its total (API: `rowFields` / `colFields` / `pageFields`). A calculation files one grand total only; a total broken down or filtered belongs in Reports.\\n\\n**Recover.** Remove the grouping to file the grand total here, or build the breakdown as a report over the published results.\\n\\n### `CALC_PIVOT_CALCULATED_FIELD_UNSUPPORTED`\\n\\n**Means.** A pivot table uses a calculated field: a formula over its totals, such as a ratio of two sums. A calculation cannot file a total like that yet.\\n\\n**Recover.** Compute each part as its own output on the Calculator sheet and total those with a sum; the calculation files each sum as its own total.\\n\\n### `CALC_PIVOT_DATA_FIELD_COLLISION`\\n\\n**Means.** More than one declared data field aggregates the same calculator column. A harvested total is filed under its source element, so the two would collide on one cell.\\n\\n**Recover.** Give each aggregate its own calculator column.\\n\\n### `CALC_PIVOT_SUBTOTAL_UNSUPPORTED`\\n\\n**Means.** A pivot table totals a column with something other than a sum: a count, average, minimum or maximum. A filed total is kept under its column alone, with that column\u2019s unit, so any other figure would read as the sum.\\n\\n**Recover.** Change the pivot to a sum, or compute the other figure as its own column on the Calculator sheet, with its own unit.\\n\\n### `CALC_PIVOT_DATA_ON_ROWS_UNSUPPORTED`\\n\\n**Means.** A pivot table lists its values down the rows (API: `dataOnRows: true`). A total the calculation can file needs one row, with a column per value.\\n\\n**Recover.** Show the pivot\u2019s values in columns instead of rows (API: `dataOnRows: false`).\\n\\n### `CALC_PIVOT_RESERVED_COLUMN`\\n\\n**Means.** A pivot data field aggregates a reserved keying column (__name__). Reserved columns carry row identity, not a measured quantity.\\n\\n**Recover.** Aggregate a measured calculator column instead.\\n\\n### `CALC_PIVOT_OUTPUT_MISSING`\\n\\n**Means.** A declared pivot produced no engine output, or declares no readable data field, so its declared total would silently vanish.\\n\\n**Recover.** Check the pivot\u2019s name and that each data field names a source field, then import the calculation again.\\n\\n### `CALC_PIVOT_OUTPUT_UNHARVESTED`\\n\\n**Means.** The engine computed a pivot output that no declared pivot claims, so its total would be discarded. The declaration reader and the engine disagree about what is declared.\\n\\n**Recover.** Report this with the calculation: it is a fault in the app, not in the calculation. Don\u2019t rely on this run\u2019s totals until it is fixed.\\n\\n### `CALC_PIVOT_TOTAL_CELL_MISSING`\\n\\n**Means.** A declared pivot produced output, but its grand-total cell could not be read (wrong row count, or a non-scalar value).\\n\\n**Recover.** Check that the pivot is not grouped and that its data fields use number columns on the calculator sheet.\\n\\n### `CALC_AGGREGATE_PERIOD_UNRESOLVED`\\n\\n**Means.** A declared aggregate must be keyed to the run\u2019s single period, but the period could not be resolved unambiguously from the calculator source.\\n\\n**Recover.** Check that the calculator sheet\u2019s source has one period per run. A total dated to the wrong period files a wrong number.\\n\\n### `CALC_RUN_CANCELLED`\\n\\n**Means.** An operator cancelled this run while it was still in flight; the note names who cancelled it and, when given, why. The run sealed CANCELLED before its results were written, so it filed no numbers and promoted nothing.\\n\\n**Recover.** Nothing to fix \u2014 a cancel is a deliberate stop. Re-run the period from the Runs tab when the asset selection, bindings or data are right; the new run supersedes the cancelled one. NOTE: an automated (scheduled) project does NOT re-file a cancelled period on its own \u2014 the re-run is the operator\u2019s, or the bulk backfill action\u2019s.\\n\\n### `CALC_ENGINE_VERSION_MISMATCH`\\n\\n**Means.** A run sealed before engine stamping was refused because its calculation version had been saved on a different engine than the one the app ran. Runs no longer refuse on this: each run executes on the app\u2019s engine and records it.\\n\\n**Recover.** Re-run the period: it now runs on the app\u2019s engine. The run\u2019s checks say whether the engine changed since the project\u2019s previous run.\\n\\n### `CALC_SCOPE_NONE_REQUIRES_DATA_TABLE`\\n\\n**Means.** A project set to No specific assets carries no dataTable binding. Every run needs a row spine, and with no assets the delivered table is the only one available.\\n\\n**Recover.** Connect exactly one dataset as a Data table, or choose Specific assets or a filter for the project. A calculation over constants and lookups alone has no rows to file. (API: one `kind: \\"dataTable\\"`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_SCOPE_NONE_ASSET_BINDING`\\n\\n**Means.** A project set to No specific assets carries a per-asset binding (observation, assetProperty, assetAggregate, or assetCount). Each of those is ABOUT the selected assets, and none are selected by design here.\\n\\n**Recover.** Remove the per-asset connection, or choose Specific assets or a filter for the project. Constant, Table lookup and Output connections work without assets. (API: `constant`, `tableLookup` and `node`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSET_COLUMN_FORBIDDEN`\\n\\n**Means.** The Data table connection names an asset column, but this project is set to No specific assets, so there is no asset to match it against.\\n\\n**Recover.** Clear the asset column. To identify the result rows by another column, choose it as the identity column instead.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_IDENTITY_COLUMN_FORBIDDEN`\\n\\n**Means.** A dataTable binding on a project with assets selected declares an identityColumn. On that path the asset column is what keys each result row, so a second keying column would be ambiguous.\\n\\n**Recover.** Clear the identity column; it applies only to a project set to No specific assets.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSET_COLUMN_REQUIRED`\\n\\n**Means.** The Data table connection doesn\u2019t say which column holds the asset. This project has assets selected, so every result has to belong to an asset.\\n\\n**Recover.** Choose the column that holds the asset, or set the project to No specific assets.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_COLUMN_UNKNOWN`\\n\\n**Means.** A data sheet declares one or more columns the BOUND dataset version does not carry. Nothing refuses this: every read of a missing column resolves to 0 (the documented absent-input\u21920 contract), so a run over this binding COMPLETES and files zeros instead of failing.\\n\\n**Recover.** Rename the column to match the dataset\u2019s, connect a dataset that has it, or add a dataset version that has it. If the column is really missing for this period, nothing needs fixing: a missing value reads as zero, and this warning only makes that visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_NO_MATCH`\\n\\n**Means.** The bound observation source carries rows, but none of them matched this property for one or more selected assets in the run period. Nothing refuses this: each unmatched value resolves to 0 (the documented absent-input\u21920 contract), so the run COMPLETES and files zeros for those assets. The diagnostic counts the DISTINCT assets affected and names a few of them.\\n\\n**Recover.** Check the grain and period of the bound dataset against the run: a monthly-landed source matches a monthly period, an annual row does not roll into a month, and the rows must carry this property code. If those assets genuinely had no readings this period, no action is needed \u2014 zero is the contract, and this warning only makes it visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_BLANK_CELLS`\\n\\n**Means.** A dataset bound one column per input has blank cells in a value column, on rows that were otherwise read for this period. Each blank counts as no reading, so the period\u2019s total for those assets leaves it out: a year with one blank month sums eleven months. The run still completes. The diagnostic counts the blank cells and names a few (asset @ period).\\n\\n**Recover.** Fill the blank cells in the dataset if those readings exist, then rerun the period. If those assets genuinely had no reading then, nothing needs fixing \u2014 this warning only makes the gap visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_SOURCE_EMPTY`\\n\\n**Means.** The version of the observation dataset this run read has no rows at all, so every input it feeds resolved to 0 for every selected asset. Nothing refuses it and the run completes, but the observations check fails, because no asset had a reading to match. The number affected counts the selected assets, which is all of them, and the diagnostic names a few.\\n\\n**Recover.** Check that the bound dataset version carries rows, and that the version the run read is the one you expect. If the source genuinely has no data, nothing needs fixing: zero is what the calculation reads when an input is absent.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_ROWS_OUT_OF_SCOPE`\\n\\n**Means.** Rows in the bound observation dataset name an asset that is not in this run\u2019s asset selection, so the run did not read them. That covers an ID that matches no asset at all, and an asset left out at the period end (divested, or not yet acquired). A dataset shared across projects usually carries other assets\u2019 rows, so this is often expected. Nothing refuses it and the run completes. The number affected counts ROWS, not assets: an asset with twelve monthly rows counts twelve. The diagnostic names a few of the asset IDs, each once.\\n\\n**Recover.** If a named ID belongs to an asset this calculation should cover, check that ID in the dataset against the asset, then check the project\u2019s asset selection and reporting window. If those rows belong to assets the calculation does not cover, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ROWS_OUT_OF_SCOPE`\\n\\n**Means.** Rows in the dataset connected as a Data table name an asset that is not in this run\u2019s asset selection, so they were left out of the table the calculation read. That covers an ID that matches no asset at all, and an asset left out at the period end (divested, or not yet acquired). A dataset shared across projects usually carries other assets\u2019 rows, so this is often expected. Nothing refuses it and the run completes. The number affected counts ROWS, not assets: an asset with twelve monthly rows counts twelve. The diagnostic names a few of the asset IDs, each once.\\n\\n**Recover.** If a named ID belongs to an asset this calculation should cover, check that ID in the dataset against the asset, then check the project\u2019s asset selection and reporting window. If those rows belong to assets the calculation does not cover, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSETS_WITHOUT_ROWS`\\n\\n**Means.** Some selected assets got no row from the dataset connected as a Data table for this period, so the calculation has no row for them and files no result for them. When the dataset delivered no rows at all, every selected asset is counted. The run still completes. The diagnostic counts the assets and names a few.\\n\\n**Recover.** Check that the dataset carries rows for these assets in this period, and that the version the run read is the one you expect. If those assets had no activity in the period, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_NAME_NO_ROWS`\\n\\n**Means.** A formula reads a name from the dataset connected as a Data table (for example SUMIFS(Observations[value], Observations[elementId], \\"SUBW-Z-ZNA\\", \u2026)), and the dataset has rows for this period but none for that name, for any unit. No formula gives a fallback for it, so every unit would read it as 0, which looks exactly like a real reading of 0. The run stopped rather than file that number.\\n\\n**Recover.** Check that the dataset carries rows for this name in this period, and that the name in the formula matches the one in the data. If a missing value should fall back to a default, write the fallback in the formula, for example IF(x = 0, default, x) or IF(COUNTIFS(<same criteria>) = 0, default, SUMIFS(\u2026)). Then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_NAME_ROWS_MISSING`\\n\\n**Means.** A formula reads a name from the dataset connected as a Data table, and some units (possibly all of them) have no rows for that name in this period, so each of them reads it as 0. Where the formula gives a fallback (for example IF(x = 0, default, x)), the fallback applies instead. A row whose value is 0 is a real reading and is not counted. No rows for any unit can be a missing measurement, or a quiet period or a period mismatch, so the run completes and says so rather than stopping. The diagnostic counts the units and names a few.\\n\\n**Recover.** Check that the dataset carries rows for this name for these units in this period, and that the name in the formula matches the one in the data. If those units genuinely had no reading, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_IFERROR_SUMIFS_NOOP`\\n\\n**Means.** A formula wraps SUMIFS in IFERROR to supply a default, but the default can never apply. SUMIFS already returns 0 when nothing matches (it never errors on an empty match), so IFERROR(SUMIFS(\u2026), d) computes exactly what SUMIFS(\u2026) computes and d is never used. The run completes and the value is unchanged. What is lost is the default you believed you had expressed. Two independent choices are in play: HOW a value is read (an activity quantity SUMS matching rows via SUMIFS; a parameter is a SINGLE value via XLOOKUP) and WHAT absence means (0, or a default), and only some read forms can carry a default.\\n\\n**Recover.** Write the default so it applies. For a sum: IF(COUNTIFS(<same criteria>)=0, <default>, SUMIFS(<range>, <same criteria>)). COUNTIFS is 0 only when nothing matched, so the default applies exactly then. For a single value: XLOOKUP(<key>, <keys>, <values>, <default>), where the fourth argument is the default. If 0 is the right value when nothing matches, remove the IFERROR: it adds nothing.\\n\\n### `CALC_CROSS_ROW_FORMULA_PER_ASSET`\\n\\n**Means.** A formula on a per-asset project reads other assets\u2019 rows: it ranks rows (ECE.RANK), numbers rows (ECE.ROWNUM), reads a previous or following row, or reads the whole calculator column (for example COUNTIFS(Calculator[X], \u2026) or [@Gas] / SUM(Calculator[Gas])). A per-asset run evaluates its assets in fixed-size batches, so the formula sees only the assets in its own batch, and once more assets are selected than one batch holds, the value it files differs from the answer over all of them while the run still completes. Every calculator sheet is checked, including extra sheets and pipeline stages; a sheet whose formulas cannot be checked at all (it will not bind on its own) is refused the same way, as unchecked rather than as clean. Refused at activation and, for a project activated before this rule, at the run that would batch. On activation the draft stays as saved; on a revise of an ACTIVE project the change is not applied and the project keeps its current version.\\n\\n**Recover.** Rewrite the formula to read only its own row. If the figure really spans assets, compute it where every asset is in view: as a total, or in a project whose rows come from a Data table or that is set to No specific assets.\\n\\n### `CALC_ELEMENT_FORMULA_SHADOWS_BINDING`\\n\\n**Means.** An element carries both a formula (`columnFormulas` entry) and a binding targeting it. The formula OVERRIDES the value the binding injects. The run COMPLETES with zeros, and because the methodology now has no input columns, the \\"Calculation inputs\\" checklist never renders to warn about it.\\n\\n**Recover.** Remove the column\u2019s formula from the calculation and use the column\u2019s name in another formula instead. On save it becomes an input, and Connect inputs lets you connect it.\\n\\n**Next.** open-bindings\\n\\n### `CALC_ROW_IDENTITY_UNRESOLVED`\\n\\n**Means.** The Data table connection doesn\u2019t say which column identifies each result row, and the calculation doesn\u2019t generate its rows either, so nothing says what the result rows are.\\n\\n**Recover.** Choose an identity column on the connection, or use a calculation version that generates its rows.\\n\\n**Next.** open-bindings\\n\\n### `CALC_SCOPE_ARM_LOCKED_BY_RUNS`\\n\\n**Means.** A revise tried to move a project between selecting assets (explicit/filter) and No specific assets after the project had already run. The two produce different Tier-2 dataset families, so the one already published would stay live and never be superseded: a receipted, permanently stale answer with nothing marking it stale.\\n\\n**Recover.** Clone the project instead. The clone starts as a draft with nothing published, and its asset selection can change freely. You can still switch between a list of assets and a filter, or edit the filter, and a project that has never run can change freely.\\n\\n**Next.** clone-project\\n\\n### `CALC_ROW_IDENTITY_AMBIGUOUS`\\n\\n**Means.** The Data table connection doesn\u2019t say which column identifies each result row, and the calculation generates its rows from more than one column. Guessing would file results against the wrong column.\\n\\n**Recover.** Choose one of those columns as the connection\u2019s identity column.\\n\\n**Next.** open-bindings\\n\\n### `CALC_LOOKUP_SHEET_FROM_FILE`\\n\\n**Means.** A lookup sheet\u2019s rows (factors or reference rows) are saved in the calculation, so runs read them as they are. This is the normal setup for factors and needs no dataset. Only a dataset named exactly like the sheet can replace those rows.\\n\\n**Recover.** Optional: to keep the values in Data with version history, add a dataset with the sheet\u2019s name and connect it to the project.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_SHEET_FROM_FILE`\\n\\n**Means.** A data sheet\u2019s rows in the imported file are examples. A project that uses the calculation can\u2019t be activated until it connects a dataset to that sheet; the dataset\u2019s rows then replace the file\u2019s.\\n\\n**Recover.** Under Connect inputs, connect the sheet as a Data table. To file results per asset, pick the dataset column that holds each row\u2019s asset (its values must be Studio asset IDs) and the column that holds the period. Without a period column, a run reads the rows of every period. If the rows in the file are the real data, add them to Data as a dataset and connect that. (API: a `dataTable` binding with `assetColumn` and `timeColumn`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_MULTIPLE_DATA_SHEETS`\\n\\n**Means.** The formulas read two or more data sheets. A project can connect only one data sheet for now, and it cannot be activated while a data sheet that ships rows is unconnected, so no project can run this calculation yet. Advisory: it never blocks the import.\\n\\n**Recover.** Combine the activity data into one data sheet, or set a sheet that holds factors to Lookup table. (API: at most one `dataTable` binding per project)\\n\\n**Next.** open-mapping\\n\\n### `CALC_RESULT_NOT_FINITE`\\n\\n**Means.** A result came out as Infinity or NaN (not a number) for one or more assets or rows, usually because its formula divided by zero. A filed result must be a finite number, so the run fails and nothing is published. One finding per result counts the assets or rows and names a few (asset @ period, or row @ period). It says the result divided by zero, and which input was 0, when the formula is one division and that input was 0 for every one of them. Otherwise it says the result is not a finite number: an overflow, MOD by zero, LOG of base 1, CEILING to a multiple of 0, or 0 raised to a negative power give the same value.\\n\\n**Recover.** Guard the division in that result\u2019s formula. Where the formula is one division and it divided by zero, the finding writes the guard out with the formula\u2019s own names, for example IF([@Production]=0, 0, [@Emissions]/[@Production]); otherwise guard each division the same way, IF(denominator=0, 0, numerator/denominator). Choose the value that a zero denominator should give. IFERROR(numerator/denominator, fallback) catches it too (since ECE 1.4.1), and also files the fallback where an input is blank or not a number. Then rerun the period.\\n\\n### `CALC_ROW_KEY_TYPED_IN`\\n\\n**Means.** The Calculator sheet names its rows by typing them into its key column (`unitId`, or else a first column that holds text) with no formula that generates them, and a formula reads that column, typically a SUMIFS or XLOOKUP that matches each row\u2019s asset. In a project run the key column holds each asset\u2019s Studio asset ID, not the names typed into the file, so a formula that looks data up by it finds only rows keyed by Studio asset ID. Rows keyed by the file\u2019s names match nothing and file 0. Advisory: it never blocks the import.\\n\\n**Recover.** Look up the rows by Studio asset ID, in the sheet the formula reads or in the dataset a project connects to that sheet. Or, to take the rows from a data sheet, make the ID column a formula over it, for example =UNIQUE(Data__Readings[AssetId]) (the finding names your workbook\u2019s own data sheet when it has one), and connect a dataset to that sheet on the project. Or connect the formula\u2019s inputs on the project as an Observation or an Asset property instead of looking them up. (API: a `tableLookup` binding whose rows are keyed by asset id, or `kind: \\"observation\\"` / `kind: \\"assetProperty\\"` on each input column)\\n\\n**Next.** open-bindings\\n\\n### `CALC_BINDING_NEEDS_LANDED_DATASET`\\n\\n**Means.** A sheet the formulas read declares its columns but ships no rows, so nothing supplies its data until it is connected to a dataset that exists and is promoted. A run with the sheet unconnected does not refuse. It reads nothing for it, which is how a run can complete with numbers quietly missing.\\n\\n**Recover.** Add the data to Data as a dataset, approve it, then connect the sheet on the project. For a lookup sheet, the dataset must have exactly the sheet\u2019s name (API: `kind: \\"tableLookup\\"`, its `source.code` the sheet name). For a data sheet, a Data table connection names the sheet and the dataset can have any name (API: `kind: \\"dataTable\\"`). Once connected, a run stops until the dataset exists and has an approved version: a lookup table stays on the version approved when it was connected (or follows approved versions, if it was set to), and a data sheet reads its current version, which must be approved (API: `SOURCE_NOT_FOUND` for a dataset that does not exist, `SOURCE_NOT_PROMOTED` when the version a run reads is not promoted).\\n\\n**Next.** open-bindings\\n\\n### `CALC_PIPELINE_UNSUPPORTED`\\n\\n**Means.** The calculation runs its sheets as a pipeline, one stage after another (API: `execution.pipeline`). A calculation cannot run a pipeline yet: every run would fail without filing anything, and the pipeline produces no declared totals.\\n\\n**Recover.** Compute everything on one calculator sheet, reading the other sheets as tables, and remove the pipeline (API: delete `execution.pipeline`, or set it to `[]`).\\n\\n### `CALC_FILE_SOURCE_UNSUPPORTED`\\n\\n**Means.** A sheet reads its rows from a file named in the calculation (API: a text `source` such as `\\"observations.csv\\"`). A calculation cannot read files: a run would fail, or read a file nobody meant.\\n\\n**Recover.** Type the rows into the sheet, or connect the sheet\u2019s data as a Data table under Connect inputs, and remove the file name (API: delete the sheet\u2019s `source`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_CALCULATOR_SOURCE_UNSUPPORTED`\\n\\n**Means.** The calculator sheet builds its rows by combining other sheets (API: a `union` `source` on the calculator sheet). A calculation cannot run a calculator built that way: every run would fail without filing anything.\\n\\n**Recover.** Combine the rows on a data sheet and read it from the calculator sheet, or connect the combined data as a Data table (API: delete the calculator sheet\u2019s `source`).\\n\\n### `CALC_CALCULATOR_SOURCE_PER_ASSET`\\n\\n**Means.** The calculator sheet builds its rows by grouping another sheet or by pairing two sheets (API: a `groupBy` or `crossJoin` `source` on the calculator sheet), but the project gives it one row per asset. Those two ways of building rows conflict: the run would fail, or complete with rows that are not the project\u2019s assets. A project whose rows come from a \\"Data table\\" binding, or that is set to No specific assets, runs it.\\n\\n**Recover.** Use the calculation in a project that connects its data as a Data table or is set to No specific assets. Or remove the calculator sheet\u2019s source so it computes one row per asset (API: delete the calculator sheet\u2019s `source`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_SHEET_READS_CALCULATOR`\\n\\n**Means.** A data, lookup or extra calculator sheet has formulas that read the main calculator sheet. Sheets like that are computed before the calculator, so the run would fail, or skip those formulas and file the values typed into the sheet instead of computed ones.\\n\\n**Recover.** Move those formulas onto the calculator sheet, or rewrite them so they do not read it (API: the sheet\u2019s `columnFormulas`).\\n\\n### `CALC_SAME_ROW_OTHER_TABLE`\\n\\n**Means.** A formula reads the same row of another table, for example Factors[@EF] or Factors[[#This Row],[EF]] on the Calculator sheet. In Excel that is the Factors row level with the formula; the calculation reads it as the formula sheet\u2019s own EF column instead, so the value it files would be wrong.\\n\\n**Recover.** Look the value up by a key, for example XLOOKUP([@Gas], Factors[Gas], Factors[EF]), or, if the sheet\u2019s own column is meant, write [@EF] (API: `columnFormulas`).\\n\\n### `CALC_SOURCE_FILTER_UNSUPPORTED`\\n\\n**Means.** A sheet\u2019s source combines or pairs other sheets and filters the result with a condition written as database code: a `filter` on a `union` member or on a `crossJoin` source. A calculation cannot run a raw database filter safely, so it is refused.\\n\\n**Recover.** Filter the data before it is delivered to the calculation, or express the condition as a formula column on the sheet (API: remove `filter` from the `source`).\\n\\n### `CALC_FORMULA_TOO_LONG`\\n\\n**Means.** A formula is longer than a calculation reads: 16,384 characters, twice the longest formula Excel itself allows. A formula that long is refused rather than checked.\\n\\n**Recover.** Split the formula across helper columns, each computing one part, and combine them in a shorter formula (API: `columnFormulas`).\\n\\n### `CALC_SHEET_SOURCE_UNSUPPORTED`\\n\\n**Means.** A sheet other than the calculator builds its rows in a way a calculation only runs elsewhere: by grouping another sheet or pairing two sheets (only the calculator sheet runs those), or by combining other sheets on a lookup sheet (only a data sheet runs that) (API: a `groupBy`, `crossJoin` or `union` `source`). The sheet would have no rows, and the run would complete and file a wrong number.\\n\\n**Recover.** Build grouped or paired rows on the calculator sheet, make a combined lookup sheet a data sheet, or connect the data as a Data table (API: remove the sheet\u2019s `source`, or set `role: \\"data\\"` for a `union`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_SHEET_UNREADABLE`\\n\\n**Means.** A sheet in the calculation cannot be read (API: a `sheets` entry that is not an object, whose `name` or `role` is not text, whose `source` is neither text nor an object, whose `columnFormulas` are not an object, or whose `tableNames` are not a list). The calculation cannot be checked for engine features it cannot run, so it is refused rather than run unchecked.\\n\\n**Recover.** Give every sheet a text name and role, its formulas as named entries, its table names as a list, and a source that is text or an object, or remove the sheet (API: the field the message names).\\n\\n### `CALC_LOOKUP_TARGET_NOT_LOOKUP_SHEET`\\n\\n**Means.** A Table lookup, or a constant with a Lookup table chosen, fills a table that is not one of the calculation\u2019s lookup tables. With a Lookup table chosen it fills that table; a Table lookup with none chosen fills the table named like its dataset. If the calculation has no lookup table by that name, the dataset\u2019s rows fill nothing and the formulas read the tables\u2019 own rows; if the name belongs to a data table, its rows replace that table\u2019s. Either way a run would complete with numbers the dataset did not supply. (API: a `tableLookup` binding\u2019s `targetSheet`, or its `source.code` when `targetSheet` is absent, and a `constant` binding\u2019s `targetSheet` when set, must name a sheet whose role is lookup.)\\n\\n**Recover.** Connect a dataset named like one of the calculation\u2019s lookup tables (the message names them), or remove the Table lookup. To fill a data sheet, connect it as a Data table instead. (API: set `targetSheet` and `targetElement` to the lookup table it fills; for a data sheet use `kind: \\"dataTable\\"`.)\\n\\n### `CALC_SHEET_FILLED_TWICE`\\n\\n**Means.** One table of the calculation is filled more than one way: from more than one dataset, by more than one Table lookup that names it, or by a Data table and another connection. A run keeps one of them and drops the others without a word, so its numbers could come from any of them. (API: bindings deliver the same sheet with different `source.code` values, or more than one sets it as `targetSheet`, or one of them is a `dataTable`.)\\n\\n**Recover.** Keep one connection for the table (the message names the table and what fills it) and remove the rest. Several Table lookups and constants reading the same dataset into one table are fine. (API: one `source.code` per delivered sheet.)\\n\\n### `CALC_LOOKUP_TARGET_ELEMENT_MISMATCH`\\n\\n**Means.** A Table lookup that names its Lookup table carries a different name of its own. The two must match: whatever reads the name, a scenario for one, takes it as the table the rows fill. The binder always gives them the same name, so this comes from a request that set them apart. (API: a `tableLookup` binding sets `targetSheet` and a different `targetElement`.)\\n\\n**Recover.** Open the Table lookup and save it again to fix the name. (API: set `targetElement` to the same value as `targetSheet`.)\\n\\n### `CALC_LOOKUP_FILLS_NO_LOOKUP_TABLE`\\n\\n**Means.** A Table lookup with no Lookup table chosen fills the table named like its dataset, and the calculation has no lookup table by that name. Its rows fill nothing, or, when the name belongs to another kind of table, replace that table\u2019s rows. Nothing refuses it: the run lets it through as runs always have, so the dataset may not be supplying the numbers you expect. It is not raised for a table the run refuses for another reason, since that refusal says what to fix. (API: a `tableLookup` binding without `targetSheet` whose `source.code` names no sheet whose role is lookup.)\\n\\n**Recover.** Connect a dataset named like one of the calculation\u2019s lookup tables (the message names them), or remove the Table lookup. To fill a data sheet, connect it as a Data table instead. (API: on one `tableLookup` for the dataset, set `targetSheet` and `targetElement` to the lookup table it should fill; for a data sheet use `kind: \\"dataTable\\"`.)\\n\\n### `CALC_LOOKUP_FALLBACK_USED`\\n\\n**Means.** A formula looks a value up in a Lookup table with a fallback written in (for example XLOOKUP([@Gas], Factors[Gas], Factors[GWP], 0)), and the table has no row for the key some rows look up. Those rows filed the fallback, usually 0, which looks exactly like a real value. The run completes and says so: the diagnostic counts the rows and names a few, and the keys the table lacks. A lookup inside a branch only some rows take (an IF, IFS or SWITCH branch, the fallback of IFERROR, of another XLOOKUP or of ECE.LOOKUPWHERE, or a LET binding) is not counted, since a row that skips the branch never takes its figure from the table, and a lookup bound by LET is not counted even when every row reads it; that includes a COUNTIFS guard written to mark the fallback intended.\\n\\n**Recover.** Check that the dataset connected to the Lookup table carries a row for each key named. If the fallback is the value you intend for a missing key, say so in the formula: IF(COUNTIFS(Factors[Gas], [@Gas]) = 0, 0, XLOOKUP([@Gas], Factors[Gas], Factors[GWP], 0)).\\n\\n**Next.** open-bindings\\n\\n### `CALC_ASSET_PROPERTY_CURRENT_VALUE_USED`\\n\\n**Means.** A selected asset had no value for a bound property at the end of the period, so the run used the asset\u2019s value today for that property and completed. Every other value is the one in force at the period end. A property with a value set from a past date is never filled from today, even when that value is blank. The warning names the property and the date, counts the assets and names the first few.\\n\\n**Recover.** Check that today\u2019s value also held during the period. If it did, nothing needs fixing. If it did not, set the property\u2019s value from the date it took effect in Assets, then run the period again. The run then reads that value, and this warning stops.\\n\\n### `CALC_LOOKUP_PIN_DATASET_MISMATCH`\\n\\n**Means.** A constant or Table lookup is pinned to a version of a different dataset from the one it reads, or the dataset it reads does not exist or is not visible to you. Its runs would read rows the dataset never held, so the save is refused. (API: a `constant` or `tableLookup` binding\u2019s `pin.datasetId` is not the dataset its `source.code` names.)\\n\\n**Recover.** Open the input and pick its version again from the dataset it reads. (API: send `pin` with the `datasetId` and an approved `versionId` of the dataset `source.code` names, or send `follow: true` to follow its approved versions.)\\n\\n### `CALC_LOOKUP_PIN_NOT_PROMOTED`\\n\\n**Means.** A constant or Table lookup is pinned to a version that is not approved, or that the dataset does not have. A run reads only approved versions and never falls back to another one, so every run of the project would be refused. (API: a `constant` or `tableLookup` binding\u2019s `pin.versionId` is unknown or not promoted.)\\n\\n**Recover.** Pick an approved version of the dataset, or approve this one in Datasets first and save again. When the message names a second input, the version was that input\u2019s choice: one still on it, which the new input joined (move that input to an approved version), or one this save removes, whose version was kept so the constants and Table lookups reading the dataset stay on it (pick an approved version for the first input). (API: promote the version, or send a `pin.versionId` that is promoted. `data.heldBy` names an untouched binding holding the pin an added binding joined; `data.carriedFrom` a binding the save removes whose pin was carried so the `constant` and `tableLookup` bindings left on `source.code` keep reading it.)\\n\\n### `CALC_SOURCE_PINNED_TWICE`\\n\\n**Means.** Two inputs read the same dataset and are pinned to different versions of it. A project reads one version of a dataset per run, so it cannot tell which one the numbers should come from. (API: two `constant` or `tableLookup` bindings with the same `source.code` carry different `pin` values.)\\n\\n**Recover.** Set every input reading the dataset to the same approved version. The message names the dataset and the inputs pinning it. (API: one `pin` per `source.code`; a refused save or run carries the versions in `data.versionIds`.)\\n\\n### `CALC_SOURCE_PIN_AND_FOLLOW`\\n\\n**Means.** An input reading a dataset is set to follow its approved versions while another input reading the same dataset stays on one version of it, or one input is set both ways. A project reads one version of a dataset per run, so the dataset either stays on a version or follows approved versions, for every input reading it. (API: a `constant` or `tableLookup` binding carries `pin` and `follow`, or carries `follow` on a `source.code` another binding pins.)\\n\\n**Recover.** Choose one for the dataset: keep every input reading it on the same approved version, or set them all to follow approved versions. The message names the inputs. (API: send `pin` or `follow` on a binding, never both, and `follow` only on a `source.code` no binding pins.)\\n\\n### `CALC_SOURCE_NEWER_VERSION_WAITING`\\n\\n**Means.** A constant or Table lookup read the newest approved version of its dataset, and the dataset has a newer version that is not approved: one waiting for approval, held by its checks or rejected. The run completed on the approved values; runs read only approved versions. (API: every input reading the dataset is a `constant` or `tableLookup` with no `pin`, so runs read its newest promoted version.)\\n\\n**Recover.** If the newer values are the ones to report, approve, in Datasets, a version that holds them, then run the period again. If the approved values are right, nothing needs doing.\\n\\n### `CALC_SOURCE_NEWER_DATA_BLOCKED`\\n\\n**Means.** A dataset this run read has newer data that is not used: its newest delivery is held back from publishing (blocked) and adds, changes or removes rows dated in this period, or has problem rows dated in it, or a reason that holds every period, or rows sent to the source and dated in this period wait on a fix. The run completed on the last published delivery and names it, the delivery that waits, and why, in the words Datasets uses. (API: an unpinned `observation`, `dataTable` or Category map input reads its current load, and reads the newest published version whose source delivery is published only while the current load is held.)\\n\\n**Recover.** Open the dataset at the delivery that waits and resolve its rows, or publish it, then run the period again. If the published data is right, nothing needs doing: the period can still be sent unless its approval setup requires \\"Input data up to date\\".\\n\\n### `CALC_CATEGORY_ELEMENT_NOT_SPLITTABLE`\\n\\n**Means.** A result listed under Results broken down by Emission category (API: `categoryBreakdown.splitElements`) cannot be split into category parts. Only a mass or CO2e result is broken down: one whose unit is a mass such as t, kg, lb, tCH4 or tCO2e, or a mass per unit of time such as t/yr, because only then do the parts add up to the whole. A ratio (an intensity such as tCO2e/boe, a control efficiency), a result with another unit or none, a result holding text, and a name the calculation has no result for are refused.\\n\\n**Recover.** Remove the result from Results broken down by Emission category, or, if it really is a mass, give it a mass unit in the calculation and pin that version. To stop breaking results down at all, clear the breakdown (API: `categoryBreakdown: null`).\\n\\n### `CALC_CATEGORY_READS_OTHER_ROWS`\\n\\n**Means.** A result listed under Results broken down by Emission category (API: `categoryBreakdown.splitElements`) takes in other rows of the calculation: its formula, or a column it uses, reads the whole calculator column, ranks or numbers rows, or reads a previous or following row. Those are other assets\u2019 rows, so its value carries rows whose source types were never judged for it, and a category part could be filed under the wrong category. It is also refused when another calculator sheet reads other rows, or could not be checked, since what that sheet feeds is not traced. Refused when the project is saved, and again by the run against the version it pinned.\\n\\n**Recover.** Remove the result from Results broken down by Emission category, or rewrite it (and the columns it uses) to read only its own row. For example, break down the per-asset result a roll-up adds up, not the roll-up itself.\\n\\n### `CALC_CATEGORY_GRAIN_UNSUPPORTED`\\n\\n**Means.** The Emission category breakdown is supported only for results filed per asset: Observation inputs on a project with assets selected. It is refused on a project set to No specific assets, whose results are filed per row of a Data table or as totals (API: `assetScope: { kind: \\"none\\" }`), and for a Data table feeding a broken-down result on assets selected (API: `kind: \\"dataTable\\"`). Runs of those shapes could not file category parts. Refused when the project is saved, and again by the run against the versions it pinned.\\n\\n**Recover.** Feed the broken-down results from Observation inputs on a project with assets selected. Otherwise clear the breakdown (API: `categoryBreakdown: null`).\\n\\n### `CALC_CATEGORY_MAP_UNRESOLVED`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) names a dataset that does not exist or is not visible to you, so no source type could be given a family.\\n\\n**Recover.** Check the Category map\u2019s dataset name, or add the map to Data as a dataset with the columns sourceType and family (program is optional), and name that one.\\n\\n### `CALC_CATEGORY_MAP_SHAPE`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) lacks a column every map needs: sourceType (each source type, once) and family (the group it adds up into). program (a reporting program the family belongs to) is optional, and so are validFrom and validTo, which date a row the way a constant\u2019s are. Any other column is ignored, except one that reads as program misnamed (Program, or program with spaces around it) on a map with no program column, which is refused so its programs are not dropped.\\n\\n**Recover.** Add a version of the map with the sourceType and family columns (and a program column spelled exactly program, if it has one), or name a dataset that has them.\\n\\n### `CALC_CATEGORY_COLUMN_MISSING`\\n\\n**Means.** A source that feeds a result broken down by Emission category has no Emission category column (API: `categoryBreakdown.sourceTypeColumn`), so a run could not tell which category each of its rows belongs to. Only sources feeding a broken-down result need the column: a production source feeding only an intensity does not.\\n\\n**Recover.** Add the column to the dataset (the message names the dataset and its columns), or name the column it does carry as the Emission category column. If the source should not feed a broken-down result, remove that result from Results broken down by Emission category.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CATEGORY_CHECKS_SKIPPED`\\n\\n**Means.** Validate could not read the datasets the Emission category breakdown names, so it skipped checking the Category map (API: `categoryBreakdown.map`) and each source\u2019s Emission category column. The other checks ran. This is not a pass: saving checks the datasets again and refuses if Datasets cannot be read.\\n\\n**Recover.** Validate again once Datasets can be read. Nothing in the project needs to change for this warning alone.\\n\\n### `CALC_CATEGORY_UNMAPPED`\\n\\n**Means.** Readings feeding a result broken down by Emission category carry source types the Category map (API: `categoryBreakdown.map`) gives no family for, in the version the run read and for the whole of the run\u2019s period (a row dated to cover only part of the period does not count). The run cannot say which family those readings belong to, so it files nothing. The message names up to 20 of the source types, each with how many readings carry it. A column carrying more than 10,000 distinct values is refused the same way, as a guardrail: it is almost certainly not the column holding the source type.\\n\\n**Recover.** Add a row for each named source type to the Category map (sourceType and family, and program if the map has that column), dated to cover the whole period, and land that version; or correct the source type in the input data, or name the right column as the Emission category column. Then run the period again.\\n\\n### `CALC_CATEGORY_SOURCE_TYPE_BLANK`\\n\\n**Means.** A result broken down by Emission category has value with no source type: readings feeding it leave the Emission category column (API: `categoryBreakdown.sourceTypeColumn`) blank or hold something other than text or a number in it, or no Observation input feeds the result at all, so none of its value comes from a reading that carries a source type. The run files nothing rather than leave part of a result without a category.\\n\\n**Recover.** Fill the Emission category column on the rows the message counts, or connect an Observation input whose dataset carries it to the result. If the result should not be broken down, remove it from Results broken down by Emission category.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CATEGORY_MIXED_SUBJECT`\\n\\n**Means.** A run sealed before results could be split between categories was refused because an asset\u2019s rows feeding a result broken down by Emission category carried more than one source type. Runs no longer refuse on this: such an asset\u2019s result is split into one part per source type, each computed over that source type\u2019s rows.\\n\\n**Recover.** Run the period again: the asset\u2019s result is now split between its categories. If its parts do not add up to the result, the run says so (CALC_CATEGORY_TOTALS_DO_NOT_RECONCILE).\\n\\n### `CALC_CATEGORY_MAP_ROWS_INVALID`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) has rows a run cannot read for its period: a source type listed in more than one row, a row with no sourceType or family (or no program, in a map with a program column), a sourceType longer than 500 characters, a sourceType, family or program holding a NUL character (U+0000, which cannot be stored), a validFrom or validTo that is not a date, or a row whose validFrom is after its validTo (refused wherever the row sits, even outside the period). Each source type must name exactly one family (and program, when the map has that column) for any one period.\\n\\n**Recover.** Correct the rows the message names in the Category map and land that version, then run the period again.\\n\\n### `CALC_CATEGORY_TOTALS_DO_NOT_RECONCILE`\\n\\n**Means.** A result broken down by Emission category (API: `categoryBreakdown.splitElements`) does not add up across its category parts: on at least one asset, its value differs from the sum of that asset\u2019s category parts. Every asset\u2019s value must add up on its own (a negative value too), so a subtotal filtered to any asset matches it. Usually some assets have value that no reading with a source type carries, such as a constant added to the result on an asset with no readings, so that value could not be given a category. The run fails and publishes nothing, so no category subtotal can disagree with the run\u2019s total.\\n\\n**Recover.** Check the assets the message names. Feed their value from readings that carry the Emission category column, or remove the result from Results broken down by Emission category. Then run the period again.\\n\\n### `CALC_ROLLUP_SCOPE_NOT_A_TREE`\\n\\n**Means.** Roll-up levels (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list) total results at levels of a named hierarchy, under a root: the selection\u2019s own root, or the root a fixed asset list names to total under (API: `assetScope.rootAssetId`). This asset selection has no root, or reads the unassigned bucket, where an asset can sit under two parents and a total would count it twice.\\n\\n**Recover.** Select the project\u2019s assets Under the asset at the top of the levels to total, by its id or its name, in a named hierarchy. On a fixed asset list, pick that asset as the root to total under, and its hierarchy. Or remove the roll-up levels.\\n\\n### `CALC_ROLLUP_LEVEL_REPEATED`\\n\\n**Means.** A level is listed twice under the roll-up levels (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list): the same asset type, or the same property. Each level is listed once, top level first.\\n\\n**Recover.** List each asset type and each property once.\\n\\n### `CALC_ROLLUP_LEVEL_UNKNOWN_TYPE`\\n\\n**Means.** A roll-up level (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list) names an asset type Assets does not govern, or a property no asset template defines, so nothing could ever be one of its nodes.\\n\\n**Recover.** Pick the level from the asset types or the template properties in Assets, or remove it.\\n\\n### `CALC_RESULT_BEHAVIOUR_INVALID`\\n\\n**Means.** A result\u2019s behaviour at a total, as confirmed (API: `resultBehaviours`), cannot be honoured: the result is not a numeric result of the calculation, or is confirmed twice; a ratio is confirmed as adding up (a ratio never adds up, whether it is one by its unit or by its formula); or a ratio\u2019s numerator or denominator is not a numeric result or does not add up, or its unit is not the result\u2019s own; or a ratio disagrees with the result\u2019s formula: another numerator or denominator than the one division the formula is, the two swapped, another scale than the formula\u2019s constant factors, or a formula that adds or subtracts and divides nothing.\\n\\n**Recover.** Leave the result to its detected behaviour, or confirm a ratio over two results that add up (a mass, a volume, a count), in the result\u2019s own unit, dividing what its formula divides by the formula\u2019s own scale.\\n\\n### `CALC_ROLLUP_LEVEL_PARTIAL`\\n\\n**Means.** A roll-up level was not totalled for this run, so its total would be partial or missing: no asset of the level\u2019s type under the project\u2019s selection root holds a selected asset at the period end (a node holding some assets that are not selected still totals the selected ones it holds), the asset selection has no root to walk the tree from, the level\u2019s nodes could not be read, the level has more nodes than a run reads one by one (the message gives the count), or the run was posted by an outside engine, which files no node results. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Widen the asset selection to the level\u2019s nodes, total a coarser level, or remove the level from the roll-up; for a posted run, run the period in Studio. Then run the period again.\\n\\n### `CALC_ROLLUP_LEVEL_OVERLAP`\\n\\n**Means.** A roll-up level was not totalled for this run: two of its nodes hold the same asset at the period end (a node nested under another node of its own type), so that asset would be counted twice. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Give the nested node its own asset type in Assets, or keep only one of the two types as a level. Then run the period again.\\n\\n### `CALC_ROLLUP_LEVEL_UNASSIGNED`\\n\\n**Means.** Some selected assets sit under no node of a roll-up level at the period end and hold a non-zero amount of a result that adds up. They are shown in a row of their own (\u201CNot in any \u2026\u201D, or \u201CNo \u2026\u201D for a field), so the level still adds up to the level above. Only such an asset is counted: one under no node that holds only zeros leaves every total unchanged. The warning is per run, so an asset can appear in a month it files a non-zero amount and not in others. The level is still totalled for the assets its nodes hold; the message names how many assets are left out and their total. A level no selected asset can be placed in at all (a property none of them holds) is not totalled. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Place those assets under a node of the level in Assets (or give them the property the level groups by), or remove the level. Then run the period again.\\n\\n### `CALC_ROLLUP_BEHAVIOUR_UNREADABLE`\\n\\n**Means.** The calculation version stores a behaviour at a total for one of its results (API: `resultBehaviours`) that this engine cannot read (a kind, a source or a field inside the behaviour it does not know, or a value it refuses), so whether that result adds up at a node of the roll-up is read from its unit alone (unless another stored entry for it can be read), as the Ledger reads it: a unit that is a ratio (a share, a quotient, a rate) is not totalled, any other is summed. An entry that names no result gives none a behaviour and is passed over. When the stored behaviours are not a list at all, none can be read and every result is judged by its unit. The asset results are unaffected either way.\\n\\n**Recover.** Run the period again: one cause is a version written by a newer release while a deploy was part-way, which the engine reads once every server runs that release. A re-run does not heal a stored behaviour that this release reads more strictly than the release that wrote it, or one that is itself bad: if the warning comes back, save a new calculation version that confirms that result as adding up, a ratio or per asset only, point the project at it, and run the period again.\\n\\n### `CALC_NUMERIC_VALUE_UNTYPED`\\n\\n**Means.** Some numbers this run published could not be copied into the numericValue column of the published datasets, so that column is empty for them. Datasets can only store a number there when it can hold it exactly, and a number too large to hold exactly (past 2^53 \u2212 1) cannot be held. The exact number is still in the value column and in the run\u2019s own results, so nothing is lost and sign-off is unaffected. Only a sum or total built over numericValue (an Insights metric, an aggregate read) leaves these numbers out. The diagnostic names the result and the published dataset, and counts the values left out of that one dataset, so a result and its category breakdown are counted separately, each against its own dataset.\\n\\n**Recover.** Nothing needs fixing in the calculation. Where a total must include these numbers, total the value column instead of numericValue.\\n\\n### `CALC_NODE_LEVEL_UNNAMED`\\n\\n**Means.** A roll-up level has no name in Assets any more, so its totals were published under its ID instead of a name. The totals themselves are unchanged.\\n\\n**Recover.** Name the level in Assets, then re-run the period to publish its name.\\n\\n### `CALC_RUN_INPUT_TOO_LARGE`\\n\\n**Means.** This run\u2019s input is larger than a run can store, so it was stopped and nothing was published; the period\u2019s earlier results are unchanged. The message gives the size and the limit, and says what made the input large. A run over assets: the selected assets and the reference tables, checked before anything is computed (the rows of each asset are stored batch by batch and are not counted). A table-driven run: it may keep up to 2,000,000 rows from its connected Data table (those in its period and asset selection where the connection filters by them, every row where it filters by neither) and up to 28,000,000 values (those rows \xD7 the columns each carries), both counted as the table is read, so a run that keeps more is refused there, before the rest is read; the table is stored in parts, up to 640 MiB across them, checked while the table is read so a table past it is refused before the rest is read, and a single row too large to store as one part on its own is refused as the parts are written; its reference tables are checked before anything is computed. One batch of a run over assets: that batch\u2019s rows, checked when the batch is computed, so the run stopped at that batch. (API: the run-wide engine input plus the asset selection snapshot is over `RUN_INPUT_STORE_MAX_BYTES`, or a Data table is over `RUN_INPUT_TABLE_MAX_BYTES`, named as the `estimate` or `exact` layer; or a Data table delivered more rows than `DATA_TABLE_SUPPORTED_ROWS`, or more rows \xD7 delivered columns than `DATA_TABLE_SUPPORTED_VALUES`, after its `timeColumn` and `assetColumn` filters, named by that limit; or one `run_input_chunk` is over the chunk limit, named as the `chunk` layer for a batch of a run over assets and as the `exact` layer\'s `run_input_chunk` for one part of a Data table.)\\n\\n**Recover.** A run over assets: narrow the project\u2019s asset selection, or reduce the reference tables. A table-driven run whose Data table stores too much: keep fewer of its rows or columns \u2014 where the connection filters the table by period or asset, a run that keeps fewer rows stores less; drop the columns your formulas do not read from the table \u2014 or split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs; one row too large to store on its own: connect a table whose rows carry smaller values, or drop the columns your formulas do not read. A run that keeps more rows or values from its Data table than a run supports: where the connection filters the table by period or asset, a run that keeps fewer rows is not refused; fewer columns allow more rows, so drop the columns your formulas do not read from the table (any columns the platform adds to every row stay; the message counts them); otherwise split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs. One batch too large: split the calculation into calculations with fewer connected inputs, or connect inputs with smaller values. Then re-run the period; re-running unchanged is refused the same way. (API: trigger it with a new `idempotencyKey` once the asset selection, tables or bindings change.)\\n\\n### `CALC_DATA_TABLE_ROWS_PAST_SUPPORTED`\\n\\n**Means.** A connected Data table holds more rows in total than a run supports (2,000,000), or more values (its rows \xD7 the columns each carries) than the 28,000,000 a run supports. A run that keeps more than either will be refused as too large (CALC_RUN_INPUT_TOO_LARGE). A run keeps the rows in its period and asset selection where the connection filters by them; where it filters by neither, a run keeps every row, so every run of a table this large is refused. The warning names the sheet, the dataset and its row count, and says which applies. (API: the bound version\'s `rowCount` is past `DATA_TABLE_SUPPORTED_ROWS`, or its `rowCount` \xD7 its delivered columns past `DATA_TABLE_SUPPORTED_VALUES`.)\\n\\n**Recover.** Where the connection filters by period or asset, a run that keeps fewer rows is not refused. Fewer columns allow more rows: drop the columns your formulas do not read from the table (any columns the platform adds to every row stay; the message counts them). Otherwise split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_CHANGED_DURING_READ`\\n\\n**Means.** The Data table connected to this calculation kept changing while the run read it: the run read a different number of rows than the table held when it started, several times in a row, as happens while new data is still being loaded into it. Rather than file a figure that might count a row twice, the run was stopped: it is FAILED and nothing was published; the period\u2019s earlier results are unchanged. (API: one task\u2019s reads in a row of a Data table returned a row count other than the one their open counted; a single such read is retried, and the run is refused at the limit on that task.)\\n\\n**Recover.** Re-run the period once the table has finished loading. If it keeps happening, check what is still writing to the table. (API: trigger it with a new `idempotencyKey`.)\\n\\n### `CALC_ADDED_UNIT_MISMATCH`\\n\\n**Means.** A formula adds or subtracts two values whose units differ, for example a result in t and one in kg, or a reading in mcf and a constant in m\xB3. The calculation adds the numbers as plain numbers, with no conversion, so the result is wrong unless the two are the same unit written two ways. Units are compared as typed: t and tonne are different units here. Only formulas, constants and connected readings with a unit are compared; a value whose unit is known only when a run reads it is not. A warning: it never holds Next or Publish.\\n\\n**Recover.** Convert one value in the formula so both are in the same unit (for example [@Recovered] / 1000 to turn kg into t), or correct a Unit that was typed wrong. If the two really are the same unit written two ways, write them the same way.\\n\\n### `CALC_OBSERVATION_COARSER_THAN_PERIOD`\\n\\n**Means.** Rows of an observation input cover a span longer than the calculation period (annual data in a monthly calculation, for example), so none of them fits inside the period. The input is set to leave such rows out, so the run did not use them, and an asset with no other reading for the period read 0. The run completes. The number affected counts the rows, and the diagnostic names a few (asset @ period).\\n\\n**Recover.** Choose how the input handles longer data: Spread by days shares each value across the periods it covers in proportion to their days (for amounts that add up), and Value in effect uses the whole value in every period it covers (for rates and factors). If the rows belong to another calculation, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_CROSSES_PERIOD`\\n\\n**Means.** Rows of an observation input cover a span that crosses the edge of the calculation period (a calendar month in a weekly calculation, or calendar-year data in a fiscal year), so they fit inside no period. The input is set to leave such rows out, so the run did not use them. The run completes. The number affected counts the rows, and the diagnostic names a few (asset @ period).\\n\\n**Recover.** Choose Spread by days on the input to share each such row between the periods it touches in proportion to their days, or Value in effect to use its whole value. Otherwise report the data on the calculation\u2019s own period boundaries.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_MIXED_FREQUENCY`\\n\\n**Means.** The rows an observation input read for this period mix spans (some daily and some monthly, for example), so the dataset does not report at one frequency. Each row is still handled by the input\u2019s choices: rows inside the period are combined as chosen, and longer rows as chosen for those. The run completes; the warning makes the mix visible, since mixed data often means a value is counted twice.\\n\\n**Recover.** Check the dataset for overlapping rows, such as a monthly total beside the daily readings it was made from. If the mix is intended, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_VALUE_CHANGED_IN_PERIOD`\\n\\n**Means.** A value this calculation reads changed part-way through the period: an asset property, a constant or a lookup factor. The input is set to use the value at the period end, so the run used that value for the whole period, including the days before the change. The run completes. The diagnostic names the input and counts what changed: the assets whose property changed, or the rows of the reference table whose validity starts or ends inside the period.\\n\\n**Recover.** If the period should be calculated in parts at the change, set the input to Split the period at the change. If the period-end value is right for the whole period, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_PERIOD_SPLIT`\\n\\n**Means.** A value this calculation reads changed part-way through the period, and the input is set to split the period at the change. The run calculated each part with the value in force during it and its own share of the activity data (readings inside a part go to it, and a reading spanning the change is shared by days), then combined the parts by what each result is calculated from: a result from readings is added up across the parts, a result only from values in force (a property such as a device count or capacity, a constant, a factor) is averaged over the days, so 10 devices then 12 is about 11, not 22, and a ratio is recomputed from its combined parts. The diagnostic names the parts.\\n\\n**Recover.** Nothing needs fixing. A result combined by a day-weighted average is an estimate. The diagnostic names each part and its days.\\n\\n### `CALC_PERIOD_SPLIT_UNSUPPORTED`\\n\\n**Means.** An input is set to split the period when its value changes, but this calculation cannot be calculated in parts: it reads a whole Data table (rows the run cannot share between parts), breaks results down by emission category, a row of a Data table with a time column crosses the change, the value changes too many times inside the period to calculate it in parts, or a result cannot be put back together from its parts (it is calculated from readings but is neither added up nor a ratio of totals, or it reads data used whole in every period it overlaps). The run stopped rather than use one value for the whole period.\\n\\n**Recover.** Set the input to stop the run or use the value at the period end, or report the data on the change\u2019s boundaries. A Data table needs a time column before its period can be split.\\n\\n**Next.** open-bindings\\n\\n### `CALC_ASSET_PROPERTY_CHANGES_IN_PERIOD`\\n\\n**Means.** An asset property this calculation reads changed part-way through the period on at least one asset, and the input is set to stop the run when its value changes, so no single value covers the period. The run stopped rather than pick one. The diagnostic counts the assets and names a few, with the value at the period start and at its end.\\n\\n**Recover.** Choose what the input does when the value changes: use the value at the period end, or split the period at the change. Or, if the change was entered on the wrong date, correct it on the asset. Then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_PERIOD_FIT_INVALID`\\n\\n**Means.** An input\u2019s choices for data reported at a different frequency than the calculation runs cannot be honoured together, so the save was refused. Spread by days works only with Added up; a Data table cannot spread its rows, and needs a time column before it has rows longer than the period; a period cannot be split at a change while a Data table with no time column is connected; and inputs filling one sheet must choose the same thing to do when a value changes inside the period.\\n\\n**Recover.** Change the named input\u2019s choice as the message says, then save again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_INPUT_ASSET_TYPES_MATCH_NONE`\\n\\n**Means.** An input of the calculation lists the asset types that need it, and no selected asset is of any of those types. The list still applies, so no selected asset whose type was read was checked for the input: right for an asset selection with none of those types, and a sign of a stale list otherwise (a type renamed or replaced in Assets).\\n\\n**Recover.** Check the asset types the input applies to on the calculation. If an asset type was renamed or replaced in Assets, pick the new one and publish again.\\n\\n### `CALC_INPUT_ASSET_TYPE_GONE`\\n\\n**Means.** An input of the calculation lists an asset type that is no longer in Assets. The list still applies as written: an asset that was of the removed type at the period end is checked against it, as when the type existed.\\n\\n**Recover.** Remove the asset type from the input on the calculation, or pick the type that replaced it, and publish again.\\n\\n### `CALC_UNKNOWN_PROPERTY_KEY`\\n\\n**Means.** An input reads an asset property that no asset template defines. The project was saved when the property existed; it has since been renamed or removed, so the run stopped before calculating rather than reading nothing.\\n\\n**Recover.** Open the input\u2019s connection and pick a property that exists today, then run the period again. (API: the binding\u2019s `propertyKey`)\\n\\n### `CALC_PROPERTY_TYPE_UNBINDABLE`\\n\\n**Means.** An input reads an asset property whose type a calculation cannot read as a number. Only number and measurement properties can feed a formula; the property\u2019s type was changed after the project was saved, so the run stopped before calculating.\\n\\n**Recover.** Open the input\u2019s connection and pick a number or measurement property, or change the property back to one of those types, then run the period again. (API: the binding\u2019s `propertyKey`)\\n\\n### `CALC_ASSET_PROPERTY_MISSING`\\n\\n**Means.** A bound asset property has no value on at least one selected asset, neither at the end of the period nor today. A missing property is a data fault, never read as 0, so the run stopped before calculating.\\n\\n**Recover.** Connect the input to a property every selected asset carries, or give the assets that lack it a value in Assets. You can also narrow the project\u2019s asset selection to assets that carry it. Then run the period again.\\n\\n### `CALC_DATA_TABLE_KEY_COLUMN_UNCOMPUTED`\\n\\n**Means.** The Data table connection names a key column (the asset column or the identity column) that the pinned calculation\u2019s calculator does not compute. Results are keyed by that column, so every delivered row would key to nothing and the run would complete with nothing filed. The run stopped before calculating instead.\\n\\n**Recover.** Point the connection at a column the calculator computes (the refusal lists them), or pin a calculation whose calculator computes the named column. (API: the `dataTable` binding\u2019s `assetColumn` or `identityColumn`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_COLUMN_MISSING`\\n\\n**Means.** An observation source the run reads lacks a column the connection needs. The version the run read carries different columns than the one the project was saved against, so the run stopped before calculating.\\n\\n**Recover.** Connect a dataset version that carries the column, or change the connection to a column that version has, then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CROSS_ROW_CHECK_FAULT`\\n\\n**Means.** The run was refused before any batch filed because the check for formulas that read other assets\u2019 rows could not finish on this calculation, so its results could not be trusted to be complete.\\n\\n**Recover.** Run the period again. If it keeps failing, report it with the run\u2019s id and the calculation version.\\n\\n### `RUN_BATCH_DUPLICATE_CELL`\\n\\n**Means.** One batch of assets produced two results with the same key, which a correct calculation never does, so the run stopped and filed nothing.\\n\\n**Recover.** Check the calculation for outputs that repeat a key within one asset, then run the period again. The batch number is in the run\u2019s message.\\n\\n### `RUN_BATCH_LEDGER_INCOMPLETE`\\n\\n**Means.** The run finished its batches, but the batch record does not confirm that every batch was filed, so it was sealed as failed rather than filing a partial result.\\n\\n**Recover.** Run the period again. The batches the record could not confirm are named in the run\u2019s message.\\n\\n### `RUN_INERT_BINDING_REFUSED`\\n\\n**Means.** The connected data table reached none of the selected assets, yet the calculation produced figures, so those figures came from the sample rows the calculation ships with and not from your data. Nothing was filed.\\n\\n**Recover.** Check that the data table\u2019s asset column holds ids or names that match the selected assets, then run the period again.\\n\\n### `RUN_RESULT_OUTSIDE_SCOPE`\\n\\n**Means.** The calculation produced results keyed to assets that are not in this run\u2019s asset selection, so they were not filed.\\n\\n**Recover.** Check the asset column of the calculation\u2019s own table: it should be generated from the connected data rather than typed in. Then run the period again.\\n\\n### `RUN_REAPED`\\n\\n**Means.** The run could not finish within its attempts: the worker running it stopped, its input could not be read in time on some of its attempts (the run\u2019s message says on how many), or its last attempt made no progress for the stall threshold and was handed on. It was sealed as failed. Nothing was filed.\\n\\n**Recover.** Run the period again. If its input could not be read in time, or it made no progress, the system was likely busy; a quieter time usually works. If it keeps failing, the asset selection may be too large to finish in one attempt; report it with the run\u2019s id.\\n\\n### `SEAL_ROLLBACK`\\n\\n**Means.** The run\u2019s results could not be filed, or the run was too large to file. Nothing was published, and the period\u2019s earlier results are unchanged. Results its batches had already stored stay on the failed run; the message says when there are any. The message names the cause: two results with the same key, or an asset selection too large to file (more results than one run can file, or more than filing can finish within its time budget). A per-asset run that is already too large is stopped before it calculates. (API: `context.cause` is `duplicate-result-cell` or `transaction-budget`. `transaction-budget` names both size causes. The cell ceiling `CALC_RUN_SEAL_MAX_CELLS` is judged before the filing opens, or before the run reads anything for a per-asset run, so it runs no transaction.)\\n\\n**Recover.** For a duplicate key, fix the calculation or its data so no two results share a key. For an asset selection too large to file, narrow the project\u2019s asset selection, or split the calculation into calculations that produce fewer results, and run the period again.\\n\\n### `UNCLASSIFIED`\\n\\n**Means.** The run failed for a reason this version does not classify. The run\u2019s message holds the full account.\\n\\n**Recover.** Read the run\u2019s message and correct what it names, then run the period again. Nothing was filed.\\n\\n### `CALC_RUN_ENGINE_CHANGED_MID_RUN`\\n\\n**Means.** This run had already computed part of its work on one engine when the app was upgraded to another. A run is computed on one engine only, so it stopped before computing anything on the new one and filed nothing from it. (A run that had computed nothing yet simply runs on the new engine.) The period\u2019s earlier results and any sign-off are unchanged. (API: the run\u2019s `engineVersion` is not the engine the app now runs.)\\n\\n**Recover.** Re-run the period: the new run is computed on the app\u2019s current engine and records it. (API: trigger it with a new `idempotencyKey`.)\\n"}},{"uri":"calc://example/simple-total","name":"Example declaration: simple-total","description":"The smallest useful shape: one data sheet, one calculator. Row generation with UNIQUE, a SUMIFS pull-down keyed on the generated row, and an arithmetic product across two columns of the same row. Fully synthetic example data \u2014 not a methodology.","mimeType":"application/json","source":{"kind":"generated","text":"{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Observations\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"elementId\\",\\n \\"value\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"elementId\\": \\"VARCHAR\\",\\n \\"value\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 120\\n },\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"elementId\\": \\"EMISSION_FACTOR\\",\\n \\"value\\": 2.5\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 80\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"elementId\\": \\"EMISSION_FACTOR\\",\\n \\"value\\": 2.5\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"FUEL_VOLUME\\",\\n \\"EMISSION_FACTOR\\",\\n \\"EMISSIONS_T\\"\\n ],\\n \\"rowGenerators\\": [\\n \\"siteId\\"\\n ],\\n \\"rows\\": [],\\n \\"columnFormulas\\": {\\n \\"siteId\\": \\"UNIQUE(Observations[siteId])\\",\\n \\"FUEL_VOLUME\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"FUEL_VOLUME\\\\\\",Observations[siteId],$A3)\\",\\n \\"EMISSION_FACTOR\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"EMISSION_FACTOR\\\\\\",Observations[siteId],$A3)\\",\\n \\"EMISSIONS_T\\": \\"Calculator[[#This Row],[FUEL_VOLUME]] * Calculator[[#This Row],[EMISSION_FACTOR]]\\"\\n },\\n \\"formulaSourceRow\\": 3,\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"FUEL_VOLUME\\": \\"DOUBLE\\",\\n \\"EMISSION_FACTOR\\": \\"DOUBLE\\",\\n \\"EMISSIONS_T\\": \\"DOUBLE\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"orderBy\\": [\\n \\"siteId\\"\\n ]\\n }\\n}\\n"}},{"uri":"calc://example/lookup-factor","name":"Example declaration: lookup-factor","description":"Adds a lookup sheet: XLOOKUP against a factor table keyed on a value the calculator itself derived, with IFERROR around the product so a missing factor yields a value rather than an error. Fully synthetic example data \u2014 not a methodology.","mimeType":"application/json","source":{"kind":"generated","text":"{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Observations\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"fuelType\\",\\n \\"elementId\\",\\n \\"value\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"fuelType\\": \\"VARCHAR\\",\\n \\"elementId\\": \\"VARCHAR\\",\\n \\"value\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"fuelType\\": \\"DIESEL\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 120\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"fuelType\\": \\"GAS\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 80\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\n \\"fuelType\\",\\n \\"factor\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"fuelType\\": \\"VARCHAR\\",\\n \\"factor\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"fuelType\\": \\"DIESEL\\",\\n \\"factor\\": 2.68\\n },\\n {\\n \\"fuelType\\": \\"GAS\\",\\n \\"factor\\": 1.88\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"FUEL_TYPE\\",\\n \\"FUEL_VOLUME\\",\\n \\"FACTOR\\",\\n \\"EMISSIONS_T\\"\\n ],\\n \\"rowGenerators\\": [\\n \\"siteId\\"\\n ],\\n \\"rows\\": [],\\n \\"columnFormulas\\": {\\n \\"siteId\\": \\"UNIQUE(Observations[siteId])\\",\\n \\"FUEL_TYPE\\": \\"XLOOKUP($A3,Observations[siteId],Observations[fuelType])\\",\\n \\"FUEL_VOLUME\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"FUEL_VOLUME\\\\\\",Observations[siteId],$A3)\\",\\n \\"FACTOR\\": \\"XLOOKUP(Calculator[[#This Row],[FUEL_TYPE]],Factors[fuelType],Factors[factor])\\",\\n \\"EMISSIONS_T\\": \\"IFERROR(Calculator[[#This Row],[FUEL_VOLUME]] * Calculator[[#This Row],[FACTOR]], 0)\\"\\n },\\n \\"formulaSourceRow\\": 3,\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"FUEL_TYPE\\": \\"VARCHAR\\",\\n \\"FUEL_VOLUME\\": \\"DOUBLE\\",\\n \\"FACTOR\\": \\"DOUBLE\\",\\n \\"EMISSIONS_T\\": \\"DOUBLE\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"orderBy\\": [\\n \\"siteId\\"\\n ]\\n }\\n}\\n"}}],"prompts":[{"name":"author-declaration","description":"Author a calculation methodology end to end: preview, validate, create, attach to a project, activate, run. Reads the format, function and diagnostics resources as it goes.","arguments":[{"name":"methodology","description":"What to build, in the words of whoever asked for it \u2014 a standard, a spreadsheet description, or the calculation in prose.","required":true},{"name":"projectName","description":"An existing project to attach the declaration to, if one was named.","required":false}],"template":"Author a calculation methodology in Studio for the following request.\\n\\nREQUEST\\n{{methodology}}\\n\\nTARGET PROJECT (may be empty \u2014 create one if so, or ask which to use)\\n{{projectName}}\\n\\nRead these before writing any formula. They are served as resources on this server;\\nif your client does not support resources, `calculations_describe` returns the same\\ntext.\\n\\n- `calc://declaration-format` \u2014 the artifact format, field by field.\\n- `calc://functions` \u2014 the functions the engine accepts, and the rewrite for each one\\n it does not. Checking here first is cheaper than a failed validate.\\n- `calc://example/simple-total` \u2014 the smallest complete declaration.\\n- `calc://example/lookup-factor` \u2014 the same, with a lookup table.\\n- `calc://diagnostics` \u2014 what a validation code means and how to recover. Read the\\n entry for a code you hit rather than guessing at the message.\\n\\nORDER OF OPERATIONS. Do not skip ahead: each step is cheap and the next one is not.\\n\\n1. PREVIEW \u2014 `calculations_declarations_preview`. Evaluates the declaration without\\n writing anything, so iterating costs no rows. Stay here until the shape is right.\\n2. VALIDATE \u2014 `calculations_declarations_validate`. Reports diagnostics against the\\n full engine, including the cross-reference errors a preview cannot see. Resolve\\n every `error`; read `calc://diagnostics` for any code you do not recognise.\\n3. CREATE \u2014 `calculations_declarations_create`. Writes the declaration.\\n4. PROJECT \u2014 attach it to a project, creating one first if none was named.\\n5. ACTIVATE \u2014 `calculations_activateProject`. A project must be active before it runs.\\n A refusal here needs a person with tenant-admin authority to activate the project;\\n an unattended agent cannot do it, whatever its role.\\n6. RUN \u2014 `calculations_run`, then read the result.\\n\\nIDEMPOTENCY KEYS \u2014 the rule, stated once, because getting it wrong is silent.\\n\\nEvery keyed write takes an `idempotencyKey` and there is no minting helper, on\\npurpose: a key minted by the shell would regenerate on retry, which destroys the\\nreplay protection the key exists for. Only you know you are retrying. So mint a fresh\\nUUID per logical operation, and reuse a key ONLY to retry that same call after a\\nfailure you did not get an answer to. A key reused against a different target is\\nrefused rather than answered. Individual tools state their own additional semantics in\\ntheir descriptions \u2014 several differ deliberately, so read the one you are calling.\\n\\nReport back with the declaration you created, the diagnostics you resolved along the\\nway, and the run result. If you could not reach a clean validate, say which diagnostic\\nblocked you rather than creating anyway."}]},"verbs":[{"name":"run"},{"name":"startRun"},{"name":"startPublishedRun"},{"name":"postRun"},{"name":"promoteResults"},{"name":"rebuildResultsWindow"},{"name":"publishNodeResults"},{"name":"createProject"},{"name":"cloneProject"},{"name":"reviseProject"},{"name":"activateProject"},{"name":"archiveProject"},{"name":"createDeclarationVersion"},{"name":"archiveDeclaration"},{"name":"unarchiveDeclaration"},{"name":"moveDeclarations"},{"name":"createNamespace"},{"name":"updateNamespace"},{"name":"deleteNamespace"},{"name":"generatePeriods"},{"name":"closePeriod"},{"name":"reopenPeriod"},{"name":"assertPeriodSignable"},{"name":"rerunReopenedParents"},{"name":"recordReviewDecision"},{"name":"recordVarianceDecision"},{"name":"captureParityBaseline"},{"name":"cancelRun"},{"name":"createProjectRelationship"},{"name":"endProjectRelationship"},{"name":"rewireProjectRelationship"},{"name":"createProjectRelationshipKind"},{"name":"exportResults"}]}')),codelistsManifest=deepFreeze(JSON.parse('{"name":"codelists","plane":"platform","routerKey":"codelists","verbs":[{"name":"create"},{"name":"update"},{"name":"retire"}]}')),compositionsManifest=deepFreeze(JSON.parse('{"name":"compositions","plane":"resource","routerKey":"compositions","verbs":[{"name":"create"},{"name":"publish"},{"name":"saveManifest"},{"name":"unpublish"},{"name":"update"},{"name":"delete"},{"name":"saveDefinitionVersion"},{"name":"saveAutomation"},{"name":"saveAutomationGroup"},{"name":"saveTriggerBindingVersion"},{"name":"retireDefinition"},{"name":"retireTriggerBinding"},{"name":"saveApprovalUse"},{"name":"markAutomationDue"},{"name":"setTriggerBindingOwner"}]}')),datasetsManifest=deepFreeze(JSON.parse('{"name":"datasets","plane":"resource","routerKey":"datasets","verbs":[{"name":"promote"},{"name":"land"},{"name":"declareReplica"},{"name":"observeReplicaDataset"},{"name":"retireReplica"},{"name":"registerSourceArtifact"},{"name":"createSourceTransformation"},{"name":"runTransformation"},{"name":"saveLiveDefinition"},{"name":"saveTransformSpec"},{"name":"saveValidationRuleset"},{"name":"changeStatus"},{"name":"changeMaturity"},{"name":"rename"},{"name":"describe"},{"name":"setColumnEntities"},{"name":"describeColumns"},{"name":"proposeDescription"},{"name":"decideDescriptionProposal"},{"name":"flagRecords"},{"name":"commentRecords"},{"name":"dismissFinding"},{"name":"requestCorrection"},{"name":"withdrawReviewAct"},{"name":"markDeliveryReviewed"},{"name":"correctRecords"},{"name":"correctCells"},{"name":"applyCorrections"},{"name":"saveCorrectionSettings"},{"name":"setReviewEnabled"},{"name":"setHoistedColumns"},{"name":"retryReviewCarry"},{"name":"retryCorrectedCopy"},{"name":"decideRuleResult"},{"name":"saveReviewSettings"},{"name":"setKeyColumn"},{"name":"setCatalogDetails"},{"name":"setKeyFields"},{"name":"export"},{"name":"runQualityCheck"},{"name":"startImportJob"},{"name":"startQualityRun"},{"name":"resolvePromotedVersions"},{"name":"resolveLatestVersions"},{"name":"checkInputsChanged"},{"name":"markInputsProcessed"},{"name":"startQualityChecks"},{"name":"promoteIfReady"},{"name":"reapplyCorrections"},{"name":"requestReland"},{"name":"observeReplicaDelivery"},{"name":"observeVersionLanded"},{"name":"runQualityChecks"},{"name":"seedCorrectedCopyFault"},{"name":"relandCurrentLoad"},{"name":"observeReferenceVersion"},{"name":"markReferenceValues"},{"name":"saveReferenceVersion"},{"name":"createReferenceTable"},{"name":"setReferenceSource"},{"name":"setReferenceKeyCodelists"},{"name":"assertReferenceVersionSignable"},{"name":"activateReferenceVersion"}]}')),eventsManifest=deepFreeze(JSON.parse('{"name":"events","plane":"resource","routerKey":"events","verbs":[{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"categoryRetire"},{"name":"typeCreate"},{"name":"typeUpdate"},{"name":"typeRetire"},{"name":"templateCreate"},{"name":"templateUpdate"},{"name":"templateRetire"},{"name":"statusCreate"},{"name":"statusUpdate"},{"name":"statusRetire"},{"name":"severityCreate"},{"name":"severityUpdate"},{"name":"severityRetire"},{"name":"numberingConfigSet"},{"name":"create"},{"name":"update"},{"name":"transition"},{"name":"accept"},{"name":"dismiss"},{"name":"reopen"},{"name":"linkDraw"},{"name":"linkEnd"},{"name":"merge"},{"name":"citeReadings"},{"name":"citationRemove"},{"name":"propose"},{"name":"commentAdd"}]}')),insightsManifest=deepFreeze(JSON.parse('{"name":"insights","plane":"resource","routerKey":"insights","verbs":[{"name":"metricCreate"},{"name":"metricRevise"},{"name":"metricDescribe"},{"name":"metricPublish"},{"name":"metricRetire"},{"name":"thresholdRuleCreate"},{"name":"thresholdRuleRevise"},{"name":"thresholdRuleDelete"},{"name":"createSavedView"},{"name":"updateSavedView"},{"name":"deleteSavedView"},{"name":"ruleBreach"},{"name":"ruleRecovery"},{"name":"ruleMissingData"}]}')),integrationsManifest=deepFreeze(JSON.parse('{"name":"integrations","plane":"resource","routerKey":"integrations","verbs":[{"name":"beginCapture"},{"name":"completeCapture"},{"name":"registerSource"},{"name":"createConnection"},{"name":"configureConnection"},{"name":"retireConnection"},{"name":"setSnowflakeKey"}]}')),mediaManifest=deepFreeze(JSON.parse('{"name":"media","plane":"resource","routerKey":"media","verbs":[{"name":"requestUpload"},{"name":"confirmUpload"},{"name":"block"},{"name":"unblock"},{"name":"attach"},{"name":"detach"},{"name":"setCaption"},{"name":"hide"},{"name":"unhide"},{"name":"createWebLink"},{"name":"requestUploads"},{"name":"confirmUploads"}]}')),notificationsManifest=deepFreeze(JSON.parse('{"name":"notifications","plane":"resource","routerKey":"notifications","verbs":[{"name":"send"},{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"definitionCreate"},{"name":"definitionUpdate"},{"name":"versionCreate"},{"name":"templateCreate"},{"name":"contactPointCreate"},{"name":"contactPointConsent"},{"name":"contactPointVerify"},{"name":"preferenceSet"},{"name":"feedMarkRead"}]}')),obligationsManifest=deepFreeze(JSON.parse('{"name":"obligations","plane":"resource","routerKey":"obligations","verbs":[{"name":"frameworkCreate"},{"name":"frameworkVersionCreate"},{"name":"frameworkVersionSetSuggestedPlans"},{"name":"frameworkVersionSetContentBasis"},{"name":"requirementCreate"},{"name":"requirementUpdate"},{"name":"frameworkPublish"},{"name":"frameworkImport"},{"name":"frameworkDraftFromDocument"},{"name":"programCreate"},{"name":"programUpdate"},{"name":"programArchive"},{"name":"programPinVersion"},{"name":"changeReviewDecide"},{"name":"enrollmentCreate"},{"name":"enrollmentRemove"},{"name":"enrollmentReplace"},{"name":"enrollmentSetZoneOverride"},{"name":"planCreate"},{"name":"planRevise"},{"name":"planEnable"},{"name":"planDisable"},{"name":"planCloneFromLibrary"},{"name":"determinationOverride"},{"name":"determinationRevokeOverride"},{"name":"planApply"},{"name":"applicationCancel"},{"name":"applicationRegenerate"},{"name":"applicationConfirmScope"},{"name":"applicationRecordEvent"},{"name":"obligationCreate"},{"name":"obligationUpdate"},{"name":"obligationSatisfy"},{"name":"obligationSatisfyFromWork"},{"name":"obligationCancel"},{"name":"obligationExempt"},{"name":"obligationMarkNotApplicable"},{"name":"obligationExtend"},{"name":"satisfactionAccept"},{"name":"satisfactionReject"},{"name":"creditOverride"},{"name":"deviationValidate"},{"name":"deviationVoid"},{"name":"deviationUpdate"},{"name":"deviationReport"},{"name":"deviationClose"},{"name":"deviationDraft"},{"name":"deviationRecord"},{"name":"deviationMarkUnderReview"},{"name":"workLinkKindSet"},{"name":"obligationBecameOverdue"},{"name":"obligationNonconformity"},{"name":"obligationDueSoon"},{"name":"determinationChanged"},{"name":"obligationMaterialized"},{"name":"obligationRedated"},{"name":"obligationAnchorCorrected"},{"name":"occurrenceDeferred"}]}')),observationsManifest=deepFreeze(JSON.parse('{"name":"observations","plane":"resource","routerKey":"observations","verbs":[{"name":"declare"},{"name":"rederive"},{"name":"retire"},{"name":"trippedReadings"},{"name":"createReference"},{"name":"confirmReference"},{"name":"endReference"},{"name":"derivationSealed"}]}')),reportsManifest=deepFreeze(JSON.parse('{"name":"reports","plane":"resource","routerKey":"reports","verbs":[{"name":"templateCreate"},{"name":"templateCustomize"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"},{"name":"generate"},{"name":"override"},{"name":"lock"},{"name":"promote"}]}')),scenariosManifest=deepFreeze(JSON.parse('{"name":"scenarios","plane":"resource","routerKey":"scenarios","verbs":[{"name":"create"},{"name":"update"},{"name":"commit"},{"name":"derive"},{"name":"duplicate"},{"name":"import"},{"name":"archive"},{"name":"unarchive"},{"name":"forecastsCreate"},{"name":"forecastsUpdate"},{"name":"forecastsDelete"},{"name":"fleetEventsCreate"},{"name":"fleetEventsUpdate"},{"name":"fleetEventsDelete"},{"name":"namedProceduresCreate"},{"name":"namedProceduresUpdate"},{"name":"namedProceduresDelete"},{"name":"namedProceduresApply"},{"name":"variablesCreate"},{"name":"variablesUpdate"},{"name":"variablesDelete"},{"name":"qualifiersCreate"},{"name":"qualifiersUpdate"},{"name":"qualifiersDelete"},{"name":"adjustmentsCreate"},{"name":"adjustmentsUpdate"},{"name":"adjustmentsDelete"},{"name":"initiativesCreate"},{"name":"initiativesUpdate"},{"name":"initiativesDelete"},{"name":"targetsCreate"},{"name":"targetsUpdate"},{"name":"targetsDelete"},{"name":"targetsTransition"},{"name":"runsStart"},{"name":"runsCancel"},{"name":"runsPublish"},{"name":"publishInitiatives"}]}')),workManifest=deepFreeze(JSON.parse('{"name":"work","plane":"resource","routerKey":"work","verbs":[{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"categoryDelete"},{"name":"typeCreate"},{"name":"typeUpdate"},{"name":"typeDelete"},{"name":"typeVersionPublish"},{"name":"typeVersionRetire"},{"name":"templateCreate"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"},{"name":"statusCreate"},{"name":"statusUpdate"},{"name":"statusRetire"},{"name":"categoryStatusesReplace"},{"name":"priorityRanksReplace"},{"name":"linkKindCreate"},{"name":"linkKindUpdate"},{"name":"linkKindRetire"},{"name":"numberingConfigSet"},{"name":"statusSettingSet"},{"name":"workCreate"},{"name":"workUpdate"},{"name":"workDelete"},{"name":"workTransition"},{"name":"workAssign"},{"name":"linkCreate"},{"name":"linkEnsure"},{"name":"linkRemove"},{"name":"subjectChange"},{"name":"responseSubmit"},{"name":"draftUpdate"},{"name":"draftDiscard"},{"name":"workRefile"},{"name":"commentCreate"},{"name":"commentUpdate"},{"name":"commentDelete"},{"name":"bulkCreate"},{"name":"bulkTransition"},{"name":"bulkAssign"},{"name":"bulkDelete"},{"name":"bulkSetBatch"},{"name":"bulkJobCancel"},{"name":"batchCreate"},{"name":"batchUpdate"},{"name":"batchDelete"},{"name":"scheduleCreate"},{"name":"scheduleUpdate"},{"name":"scheduleRetire"},{"name":"scheduleRefreshSubjects"},{"name":"optionSetCreate"},{"name":"optionSetUpdate"},{"name":"optionSetRetire"},{"name":"externalIdBind"},{"name":"externalIdUnbind"},{"name":"workExport"},{"name":"tenantConfigSet"},{"name":"executeFollowUpRules"},{"name":"fireSchedules"},{"name":"bulkJob"},{"name":"bulkCreateTile"},{"name":"bulkTransitionTile"},{"name":"bulkAssignTile"},{"name":"bulkDeleteTile"},{"name":"bulkSetBatchTile"},{"name":"notificationDefaultInstall"},{"name":"workDueSoon"},{"name":"workOverdue"},{"name":"workExportCompleted"}]}'));var mediaProcedures=Object.freeze({lookup:{annotations:{readOnlyHint:!0}},imageLinks:{annotations:{readOnlyHint:!0}},downloadLink:{annotations:{readOnlyHint:!0}},recentUploads:{annotations:{readOnlyHint:!0}}});var obligationsProcedures=Object.freeze({frameworkPublish:{annotations:{destructiveHint:!0}}});var DESTRUCTIVE_WORK_VERB=/delete|retire|remove|discard|replace/i,WORK_VERB_NAMES=new Set((workManifest.verbs??[]).map(verb=>verb.name)),workProcedures=Object.freeze(Object.fromEntries(listContractProcedures(workContract).map(entry=>{let path3=entry.path.join(".");return WORK_VERB_NAMES.has(path3)?[path3,{annotations:{destructiveHint:DESTRUCTIVE_WORK_VERB.test(path3)}}]:[path3,{annotations:{readOnlyHint:!0}}]})));var compositionsDomainContract={solutions:solutionsContract,workingCopies:workingCopiesContract,automations:compositionsContract},notificationsDomainContract={...notificationsContract,...notificationSendContract},interfacePairs=Object.freeze([{manifest:assetsManifest,contract:assetsContract,procedures:assetsProcedures},{manifest:calculationsManifest,contract:calculationsContract,procedures:calculationsProcedures},{manifest:datasetsManifest,contract:datasetsContract},{manifest:reportsManifest,contract:reportsContract},{manifest:insightsManifest,contract:insightsContract},{manifest:workManifest,contract:workContract,procedures:workProcedures},{manifest:eventsManifest,contract:eventsContract},{manifest:approvalManifest,contract:approvalContract},{manifest:observationsManifest,contract:observationsContract},{manifest:integrationsManifest,contract:integrationsContract},{manifest:obligationsManifest,contract:obligationsContract,procedures:obligationsProcedures},{manifest:scenariosManifest,contract:scenariosContract},{manifest:mediaManifest,contract:mediaContract,procedures:mediaProcedures},{manifest:notificationsManifest,contract:notificationsDomainContract},{manifest:compositionsManifest,contract:compositionsDomainContract,procedures:compositionsProcedures},iamPair,{manifest:codelistsManifest,contract:codelistsContract},{manifest:bundlesManifest,contract:bundlesContract}]);var program2=buildForgeCli({pairs:interfacePairs});try{await runForgeCli(program2,process.argv,fileURLToPath2(import.meta.url))}catch(error62){process.exitCode===void 0&&(process.stderr.write(`${error62 instanceof Error?error62.message:String(error62)}
478
+ ${TENANCY_SET_PREFERRED_MODULES_OFF_REACH_NOTE}`},"tenancy.get":{dispatchPath:topLevel("tenancy.get"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_GET_REACH_NOTE},"tenancy.list":{dispatchPath:topLevel("tenancy.list"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_LIST_REACH_NOTE},"tenancy.switchableModules":{dispatchPath:topLevel("tenancy.switchableModules"),annotations:{readOnlyHint:!0},descriptionSuffix:TENANCY_SWITCHABLE_MODULES_NOTE}}),iamPair=Object.freeze({manifest:iamManifest,contract:iamContract,procedures:iamProcedures});var deepFreeze=value2=>(typeof value2=="object"&&value2!==null&&(Object.values(value2).forEach(deepFreeze),Object.freeze(value2)),value2),approvalManifest=deepFreeze(JSON.parse('{"name":"approvals","plane":"resource","routerKey":"approvals","verbs":[{"name":"request"},{"name":"approve"},{"name":"reject"},{"name":"cancel"},{"name":"delegate"},{"name":"comment"},{"name":"remind"},{"name":"templateCreate"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"}]}')),assetsManifest=deepFreeze(JSON.parse('{"name":"assets","plane":"resource","routerKey":"assets","verbs":[{"name":"createMany"},{"name":"startImport"},{"name":"preflightImport"},{"name":"saveImportMapping"},{"name":"create"},{"name":"update"},{"name":"delete"},{"name":"deleteMany"},{"name":"move"},{"name":"moveMany"},{"name":"relationshipsCreateMany"},{"name":"relationshipsEndMany"},{"name":"createRelationship"},{"name":"endRelationship"},{"name":"createCategory"},{"name":"updateCategory"},{"name":"deleteCategory"},{"name":"createType"},{"name":"updateType"},{"name":"deleteType"},{"name":"setTemplate"},{"name":"createSystem"},{"name":"updateSystem"},{"name":"deleteSystem"},{"name":"createHierarchy"},{"name":"saveRules"},{"name":"savePolicy"},{"name":"setLocation"},{"name":"setLocationMany"},{"name":"setDatedValues"},{"name":"revertDatedValues"},{"name":"bindExternalId"},{"name":"bindExternalIdMany"},{"name":"unbindExternalId"},{"name":"startBindJob"},{"name":"saveNumberingConfig"},{"name":"saveNestingRules"},{"name":"saveDerivedRouting"},{"name":"applyDerivedValues"},{"name":"export"},{"name":"exportDuplicates"},{"name":"importJob"},{"name":"bindJob"},{"name":"preflightImportJob"},{"name":"landDirectory"},{"name":"publishDirectory"},{"name":"setDirectorySchedule"},{"name":"startTeardownJob"},{"name":"teardownJob"},{"name":"saveLocationPlacement"},{"name":"deleteLocationPlacement"},{"name":"startLocationPlacementJob"}]}')),bundlesManifest=deepFreeze(JSON.parse('{"name":"bundles","plane":"platform","routerKey":"bundles","verbs":[{"name":"build"},{"name":"buildCompleted"}]}')),calculationsManifest=deepFreeze(JSON.parse('{"name":"calculations","plane":"resource","routerKey":"calculations","agentGuidance":{"scheme":"calc","resources":[{"uri":"calc://declaration-format","name":"Declaration format","description":"The calculation declaration format, field by field, with worked examples \u2014 the authoring half of the engine reference.","mimeType":"text/markdown","source":{"kind":"repoFile","text":"# ECE Declaration Format (v1.0)\\n\\nThe declaration format is a JSON-based file format that fully describes an ECE workbook \u2014 sheets, columns, formulas, data, and configuration \u2014 without requiring an Excel template file.\\n\\n## When to Use\\n\\n| Approach | Use when |\\n|----------|----------|\\n| **Template + overlay** | You have an existing Excel workbook and want to make runtime modifications (formula edits, lookup data changes, new columns) |\\n| **Declaration** | You want to define a workbook from scratch in code \u2014 no Excel template needed |\\n| **Declaration + overlay** | You have a base declaration and want scenario-specific modifications without editing the declaration itself |\\n\\nBoth approaches produce the same internal manifest and feed into the same downstream pipeline (binder \u2192 DAG \u2192 SQL \u2192 executor).\\n\\n## File Structure\\n\\nDeclaration files use the `.declaration.json` extension by convention:\\n\\n```\\ncalculator.declaration.json\\npath/to/workbook.declaration.json\\n```\\n\\n## Schema Definition\\n\\n```javascript\\n{\\n \\"version\\": \\"1.0\\",\\n\\n // Sheet declarations (at least one calculator sheet required)\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Well ID\\", \\"CH4 Rate\\", \\"Total Emissions\\"],\\n\\n // Row generator columns (optional, auto-detected during extraction)\\n // \\"rowGenerators\\": [\\"Date\\"],\\n\\n // Data source (optional for calculator sheets)\\n \\"rows\\": [\\n { \\"Date\\": \\"2024-01-15\\", \\"Well ID\\": \\"W001\\", \\"CH4 Rate\\": 12.5, \\"Total Emissions\\": null }\\n ],\\n // OR: \\"source\\": \\"observations.csv\\"\\n\\n // Formulas (optional)\\n \\"columnFormulas\\": {\\n \\"Total Emissions\\": \\"=SUMIFS(Data__Obs[CH4], Data__Obs[Well], [@Well ID])\\"\\n },\\n\\n // Type hints (optional) \u2014 string or { type, format? } object\\n \\"columnTypeHints\\": {\\n \\"Date\\": \\"TIMESTAMP\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" }\\n },\\n\\n // Timezone overrides (optional)\\n \\"columnTimezones\\": {\\n \\"Date\\": \\"America/Denver\\"\\n },\\n\\n // Static cells above header row (optional, calculator only)\\n \\"staticCells\\": {\\n \\"B1\\": { \\"valueType\\": \\"number\\", \\"value\\": 0.004 }\\n },\\n\\n // Summary/aggregation rows (optional, calculator only)\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Total Emissions\\": \\"sum\\",\\n \\"Well ID\\": \\"=COUNTA(Calculator[Well ID])\\",\\n \\"CH4 Rate\\": \\"average\\"\\n }\\n }\\n ],\\n\\n // Per-row formula overrides (optional, calculator only, requires RowID column)\\n \\"literalOverrides\\": {\\n \\"CH4 Rate\\": [\\n { \\"rowId\\": \\"W001\\", \\"value\\": 0 }\\n ]\\n }\\n },\\n {\\n \\"name\\": \\"Data__Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"Date\\", \\"Well\\", \\"CH4\\", \\"CO2\\"],\\n \\"source\\": \\"observations.parquet\\",\\n\\n // Supplemental formulas (optional \u2014 any sheet can have formulas)\\n \\"columnFormulas\\": {\\n \\"CO2\\": \\"=[@CH4] * 2.75\\"\\n }\\n },\\n {\\n \\"name\\": \\"Lookup__Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"FactorID\\", \\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"FactorID\\": \\"EF001\\", \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"FactorID\\": \\"EF002\\", \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ],\\n\\n // Pivot tables (optional)\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Well ID\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Total Emissions\\", \\"name\\": \\"Sum of Emissions\\", \\"subtotal\\": \\"sum\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ],\\n\\n // Execution defaults (optional)\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP\\",\\n \\"defaultSourceTimezone\\": \\"UTC\\",\\n \\"preserveRowOrder\\": true,\\n \\"orderBy\\": [\\"phenomenonTimeBucket\\"],\\n // How *IFS criteria match: \\"excel\\" (default) or \\"exact\\". See Execution Config.\\n \\"criteriaMatching\\": \\"excel\\",\\n // Multi-calculator pipeline (optional) \u2014 run named calculators in sequence.\\n // Each stage\'s output is materialized as a DuckDB table for downstream stages.\\n // See the engine pipeline documentation.\\n \\"pipeline\\": [\\"Enrich\\", \\"CostCalc\\", \\"Compliance\\"]\\n }\\n}\\n```\\n\\n## Field Reference\\n\\n### Top-Level Metadata\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `version` | string | Yes | Schema version (currently `\\"1.0\\"`) |\\n| `sheets` | array | Yes | Sheet declarations (at least one calculator) |\\n| `pivotSheets` | array | No | Pivot table declarations |\\n| `execution` | object | No | Execution configuration defaults |\\n\\n### Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Sheet name (must be unique across all sheets) |\\n| `role` | string | Yes | Sheet role: `\\"calculator\\"`, `\\"data\\"`, `\\"lookup\\"`, or `\\"other\\"` |\\n| `columns` | string[] | Yes | Ordered column names (non-empty, no duplicates) |\\n| `rowGenerators` | string[] | No | Columns whose formulas are row generators (UNIQUE/FILTER). Auto-populated during extraction |\\n| `rows` | object[] | No | Inline data rows (mutually exclusive with `source`) |\\n| `source` | string or object | No | External file path (string), UNION definition, GROUP BY definition, or cross-join definition. See below |\\n| `columnFormulas` | object | No | Map of column name to Excel formula string |\\n| `formulaSourceRow` | number | No | The Excel row number where cell-address formulas (A1-style) originate \u2014 used to compute cross-row offsets for LAG/LEAD. See the Cross-Row References section of the engine specification. Defaults to `headerRowNumber + 1` if omitted (`2` for a sheet with a single header row), so a relative formula written against row 3 resolves as same-row only when the sheet declares `formulaSourceRow: 3` \u2014 which every example declaration this server publishes does. Omitting it is only soft-warned at validate. A `# ECE Declaration Format (v1.0)\\n\\nThe declaration format is a JSON-based file format that fully describes an ECE workbook \u2014 sheets, columns, formulas, data, and configuration \u2014 without requiring an Excel template file.\\n\\n## When to Use\\n\\n| Approach | Use when |\\n|----------|----------|\\n| **Template + overlay** | You have an existing Excel workbook and want to make runtime modifications (formula edits, lookup data changes, new columns) |\\n| **Declaration** | You want to define a workbook from scratch in code \u2014 no Excel template needed |\\n| **Declaration + overlay** | You have a base declaration and want scenario-specific modifications without editing the declaration itself |\\n\\nBoth approaches produce the same internal manifest and feed into the same downstream pipeline (binder \u2192 DAG \u2192 SQL \u2192 executor).\\n\\n## File Structure\\n\\nDeclaration files use the `.declaration.json` extension by convention:\\n\\n```\\ncalculator.declaration.json\\npath/to/workbook.declaration.json\\n```\\n\\n## Schema Definition\\n\\n```javascript\\n{\\n \\"version\\": \\"1.0\\",\\n\\n // Sheet declarations (at least one calculator sheet required)\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Well ID\\", \\"CH4 Rate\\", \\"Total Emissions\\"],\\n\\n // Row generator columns (optional, auto-detected during extraction)\\n // \\"rowGenerators\\": [\\"Date\\"],\\n\\n // Data source (optional for calculator sheets)\\n \\"rows\\": [\\n { \\"Date\\": \\"2024-01-15\\", \\"Well ID\\": \\"W001\\", \\"CH4 Rate\\": 12.5, \\"Total Emissions\\": null }\\n ],\\n // OR: \\"source\\": \\"observations.csv\\"\\n\\n // Formulas (optional)\\n \\"columnFormulas\\": {\\n \\"Total Emissions\\": \\"=SUMIFS(Data__Obs[CH4], Data__Obs[Well], [@Well ID])\\"\\n },\\n\\n // Type hints (optional) \u2014 string or { type, format? } object\\n \\"columnTypeHints\\": {\\n \\"Date\\": \\"TIMESTAMP\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" }\\n },\\n\\n // Timezone overrides (optional)\\n \\"columnTimezones\\": {\\n \\"Date\\": \\"America/Denver\\"\\n },\\n\\n // Static cells above header row (optional, calculator only)\\n \\"staticCells\\": {\\n \\"B1\\": { \\"valueType\\": \\"number\\", \\"value\\": 0.004 }\\n },\\n\\n // Summary/aggregation rows (optional, calculator only)\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Total Emissions\\": \\"sum\\",\\n \\"Well ID\\": \\"=COUNTA(Calculator[Well ID])\\",\\n \\"CH4 Rate\\": \\"average\\"\\n }\\n }\\n ],\\n\\n // Per-row formula overrides (optional, calculator only, requires RowID column)\\n \\"literalOverrides\\": {\\n \\"CH4 Rate\\": [\\n { \\"rowId\\": \\"W001\\", \\"value\\": 0 }\\n ]\\n }\\n },\\n {\\n \\"name\\": \\"Data__Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"Date\\", \\"Well\\", \\"CH4\\", \\"CO2\\"],\\n \\"source\\": \\"observations.parquet\\",\\n\\n // Supplemental formulas (optional \u2014 any sheet can have formulas)\\n \\"columnFormulas\\": {\\n \\"CO2\\": \\"=[@CH4] * 2.75\\"\\n }\\n },\\n {\\n \\"name\\": \\"Lookup__Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"FactorID\\", \\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"FactorID\\": \\"EF001\\", \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"FactorID\\": \\"EF002\\", \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ],\\n\\n // Pivot tables (optional)\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Well ID\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Total Emissions\\", \\"name\\": \\"Sum of Emissions\\", \\"subtotal\\": \\"sum\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ],\\n\\n // Execution defaults (optional)\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP\\",\\n \\"defaultSourceTimezone\\": \\"UTC\\",\\n \\"preserveRowOrder\\": true,\\n \\"orderBy\\": [\\"phenomenonTimeBucket\\"],\\n // How *IFS criteria match: \\"excel\\" (default) or \\"exact\\". See Execution Config.\\n \\"criteriaMatching\\": \\"excel\\",\\n // Multi-calculator pipeline (optional) \u2014 run named calculators in sequence.\\n // Each stage\'s output is materialized as a DuckDB table for downstream stages.\\n // See the engine pipeline documentation.\\n \\"pipeline\\": [\\"Enrich\\", \\"CostCalc\\", \\"Compliance\\"]\\n }\\n}\\n```\\n\\n## Field Reference\\n\\n### Top-Level Metadata\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `version` | string | Yes | Schema version (currently `\\"1.0\\"`) |\\n| `sheets` | array | Yes | Sheet declarations (at least one calculator) |\\n| `pivotSheets` | array | No | Pivot table declarations |\\n| `execution` | object | No | Execution configuration defaults |\\n\\n### Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Sheet name (must be unique across all sheets) |\\n| `role` | string | Yes | Sheet role: `\\"calculator\\"`, `\\"data\\"`, `\\"lookup\\"`, or `\\"other\\"` |\\n| `columns` | string[] | Yes | Ordered column names (non-empty, no duplicates) |\\n| `rowGenerators` | string[] | No | Columns whose formulas are row generators (UNIQUE/FILTER). Auto-populated during extraction |\\n| `rows` | object[] | No | Inline data rows (mutually exclusive with `source`) |\\n| `source` | string or object | No | External file path (string), UNION definition, GROUP BY definition, or cross-join definition. See below |\\n| `columnFormulas` | object | No | Map of column name to Excel formula string |\\n| `formulaSourceRow` | number | No | The Excel row number where cell-address formulas (A1-style) originate \u2014 used to compute cross-row offsets for LAG/LEAD. See the Cross-Row References section of the engine specification. -anchored row, `$B$2`, reads that row on every row (see the Absolute-Row Cell References section of the engine specification) |\\n| `columnTypeHints` | object | No | Map of column name to type hint |\\n| `columnTimezones` | object | No | Map of column name to IANA timezone |\\n| `staticCells` | object | No | Map of cell reference (e.g., `\\"B1\\"`) to value object. Calculator only |\\n| `summaryRows` | array | No | Summary/aggregation rows below data. Calculator only |\\n| `literalOverrides` | object | No | Per-row formula overrides. Calculator only; requires a `RowID` column |\\n\\n**Data source rules:**\\n- **Calculator sheets** can omit both `rows` and `source` (e.g., when using UNIQUE/FILTER row generators)\\n- **Data and lookup sheets** must specify either `rows` or `source`\\n- **Other sheets** can omit both `rows` and `source` (they are inert during execution)\\n- `rows` and `source` cannot both be specified on the same sheet \u2014 except for UNION sources, which require `rows: []` (empty) alongside the `source` definition\\n\\n**Source types:**\\n- **String** \u2014 external file path: `\\"source\\": \\"observations.csv\\"` (CSV, Parquet, JSON, or JSONL)\\n- **UNION object** \u2014 virtual table composed from other sheets:\\n ```json\\n \\"source\\": {\\n \\"union\\": [\\n { \\"sheet\\": \\"Data__Wells\\", \\"columns\\": { \\"AssetID\\": \\"WellID\\", \\"Type\\": { \\"literal\\": \\"WELL\\" } } },\\n { \\"sheet\\": \\"Data__Facs\\", \\"columns\\": { \\"AssetID\\": \\"FacID\\", \\"Type\\": { \\"literal\\": \\"FAC\\" } } }\\n ],\\n \\"distinct\\": false\\n }\\n ```\\n Each member maps output columns to source columns (string = rename, `{ \\"literal\\": value }` = constant). Optional `filter` applies a WHERE clause. Optional `distinct: true` uses `UNION` instead of `UNION ALL`. A member may not map a `columnFormulas` column of its source sheet (unions are built before those formulas run); that is refused.\\n\\n- **GROUP BY object** \u2014 calculator rows from aggregation (calculator sheets only):\\n ```json\\n \\"source\\": {\\n \\"groupBy\\": {\\n \\"sheet\\": \\"Data__Production\\",\\n \\"keys\\": [\\"FacilityID\\", \\"Year\\"],\\n \\"aggregations\\": {\\n \\"TotalOil\\": { \\"function\\": \\"SUM\\", \\"column\\": \\"OIL_PROD_BBL\\" },\\n \\"RecordCount\\": { \\"function\\": \\"COUNT\\", \\"column\\": \\"*\\" }\\n }\\n }\\n }\\n ```\\n Generates one row per unique combination of key columns. `aggregations` maps output column names to `{ function, column }` pairs. Supported functions: `SUM`, `AVG`, `COUNT`, `MAX`, `MIN`. Formula columns in the calculator then compute on top of these aggregated seed rows.\\n\\n- **Cross-join object** \u2014 calculator rows from Cartesian product (calculator sheets only):\\n ```json\\n \\"source\\": {\\n \\"crossJoin\\": {\\n \\"left\\": \\"Data__Years\\",\\n \\"right\\": \\"Data__Sites\\",\\n \\"filter\\": \\"__cj_right.\\\\\\"SiteType\\\\\\" = \'Active\'\\"\\n }\\n }\\n ```\\n Generates every combination of rows from `left` and `right` tables. Optional `filter` is a SQL WHERE clause using `__cj_left` / `__cj_right` aliases. Both tables must be registered data sheets or materialized UNION sheets.\\n\\n### Static Cell Value Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `valueType` | string | No | Type of the value: `\\"string\\"`, `\\"number\\"`, `\\"boolean\\"`, or `\\"date\\"` |\\n| `value` | any | Yes | The cell value |\\n\\n### Summary Row Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `label` | string | No | Row label (e.g., `\\"TOTALS\\"`) |\\n| `aggregations` | object | Yes | Map of column name to aggregation value |\\n\\n**Aggregation values** can be any of:\\n\\n| Form | Example | Description |\\n|------|---------|-------------|\\n| Simple type | `\\"sum\\"` | One of `\\"sum\\"`, `\\"average\\"`, `\\"count\\"`, `\\"max\\"`, `\\"min\\"` |\\n| Formula | `\\"=COUNTA(Calculator[Well ID])\\"` | Arbitrary Excel formula (must start with `=`) |\\n| Value object | `{ \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" }` | Static value (label, constant) |\\n| `null` | `null` | Skip this column in the aggregation row |\\n\\n`\\"avg\\"` is accepted as a synonym for `\\"average\\"`.\\n\\n### Literal Override Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `rowId` | any | Yes | Value of the `RowID` column for the target row |\\n| `value` | any | Yes | Literal value to use instead of the column formula |\\n\\nWhen a column has literal overrides, the SQL generator produces a `CASE WHEN` expression:\\n```sql\\nCASE WHEN \\"RowID\\" = \'W001\' THEN 0 ELSE <formula> END\\n```\\n\\n### Pivot Sheet Declaration\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Pivot sheet name |\\n| `source` | object | Yes | Source sheet reference |\\n| `dataFields` | array | Yes | Aggregated value columns (at least one) |\\n| `rowFields` | array | No | Row grouping fields |\\n| `colFields` | array | No | Column grouping fields |\\n| `pageFields` | array | No | Filter/page fields |\\n| `calculatedFields` | array | No | Computed pivot fields |\\n| `dataOnRows` | boolean | No | Transpose summary layout (default: `false`) |\\n| `rowGrandTotals` | boolean | No | Include row grand totals (default: `true`) |\\n| `colGrandTotals` | boolean | No | Include column grand totals (default: `true`) |\\n\\n#### Pivot Source Object\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `sheetName` | string | One of the two | Source sheet name |\\n| `tableName` | string | One of the two | Source table name |\\n\\n#### Pivot Data Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `sourceField` | string | Yes | Column to aggregate |\\n| `subtotal` | string | No | Aggregation type: `\\"sum\\"`, `\\"count\\"`, `\\"average\\"`, `\\"min\\"`, `\\"max\\"` (default: `\\"sum\\"`) |\\n| `name` | string | No | Display name (default: `\\"<subtotal> of <sourceField>\\"`) |\\n\\n`\\"avg\\"` is accepted as a synonym for `\\"average\\"`.\\n\\n#### Pivot Row/Column Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Column name to group by |\\n| `items` | array | No | Pre-defined unique values for the field (preserved from manifest `sharedItems` for round-trip fidelity when source columns have empty cached values) |\\n\\n#### Pivot Page Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Column name to filter on |\\n| `selectedItem` | any | No | Selected filter value |\\n\\n#### Pivot Calculated Field\\n\\n| Field | Type | Required | Description |\\n|-------|------|----------|-------------|\\n| `name` | string | Yes | Calculated field name |\\n| `formula` | string | Yes | Pivot formula expression |\\n\\n### Execution Config\\n\\n| Field | Type | Default | Description |\\n|-------|------|---------|-------------|\\n| `defaultTimestampType` | string | `\\"TIMESTAMP\\"` | Default temporal type for date/time columns |\\n| `defaultSourceTimezone` | string | *(none)* | Default source timezone for timestamp parsing |\\n| `preserveRowOrder` | boolean | `true` | `false` stops a workbook\'s loader numbering rows, which leaves LAG/LEAD unavailable. Outputs are written in source row order either way: later stages, summary rows and pivots read them back |\\n| `orderBy` | string or string[] | *(none)* | Column name(s) to sort output by. Overrides `preserveRowOrder` when set. |\\n| `pipeline` | string[] | *(none)* | Calculator sheet names to run in sequence. Each stage\'s output is materialized as a DuckDB table for downstream reference. See the engine pipeline documentation. |\\n| `criteriaMatching` | `\\"excel\\"` or `\\"exact\\"` | `\\"excel\\"` | Rules for the criteria of `SUMIFS`, `COUNTIFS`, `MAXIFS` and the other criteria functions. See below. |\\n\\nExecution config values act as defaults. Runtime parameters passed to `runEce()` or CLI flags (`--pipeline`) take precedence. A runtime `pipeline` does not rescue an invalid declared one: a declaration whose `execution.pipeline` names a missing sheet (or is not an array of strings) fails validation when loaded, whatever pipeline the run passes.\\n\\n#### `criteriaMatching`\\n\\nPicks the rules that every criteria function uses to match cells. It applies to literal criteria (`\\"oil\\"`), reference criteria (`[@Kind]`) and criteria built at run time (`\\"<>\\"&[@Kind]`).\\n\\n| Value | Rules |\\n|-------|-------|\\n| `\\"excel\\"` (default) | Microsoft Excel\'s rules, for literal, reference and runtime-built criteria alike. Text matches without regard to case. `*` and `?` are wildcards and `~` escapes them. `\\"\\"` matches empty cells and cells holding `\\"\\"`, while `\\"=\\"` matches only empty cells. Numbers also match text that reads as the same number. `<`/`>` order number and date cells only; ordering text (`\\">abc\\"`) is refused. With no matching rows, `AVERAGEIFS`/`MEDIANIFS` return NULL. The full rules are in the Criteria Semantics section of the engine specification. |\\n| `\\"exact\\"` | Text matches only when the case is the same. `*` and `?` are ordinary characters. `\\"\\"` and `\\"=\\"` match only empty (NULL) cells, and `\\"<>\\"` matches every cell that is not empty. Plain references (`[@Key]`) are a SQL `=` join, and equality on numbers and dates uses the comparison of 1.3.x. It is not 1.3.x, though: blanks, `\\"=\\"&x`/`\\"<>\\"&x` with text, dates or booleans, numeric criteria on text columns and `<`/`>` (now Excel\'s ordering, with text operands compared case-sensitively) changed (see the `\\"exact\\"` mode section of the engine specification). Use this for ID-style joins where `ab-1` and `AB-1` are different keys. |\\n\\nOnly the declaration (or an overlay\'s `execution` section) can set this, not `runEce()` options or CLI flags. That way a published number can be reproduced from the declaration alone. Absent or `null` means `\\"excel\\"`. Any other value fails validation, and `runEce()` refuses it with `ECE_INVALID_CRITERIA_MATCHING`, also from an overlay run with `onOverlayError: \\"warn\\"` (that option skips other overlay errors, but skipping this one would silently change the rule set). `runEce()` records the rules it used as `criteriaMatching` on its result and on the manifest it writes.\\n\\n### Resolved Declarations\\n\\nA **resolved declaration** is a self-contained declaration where all runtime data sources (e.g., `\\"source\\": \\"runtime\\"`) have been replaced with actual inlined `rows`. This is produced by running `runEce` with `resolveOverrides: true` and then calling `manifestToDeclaration(manifest)`.\\n\\nResolved declarations are useful for:\\n- **Reproducibility** \u2014 re-executing produces identical results with no external dependencies\\n- **Auditing** \u2014 captures the exact inputs used for a calculation run\\n- **Archival** \u2014 all data frozen in a single artifact\\n- **Workbook generation** \u2014 with `populateCalculatorRows: true`, the declaration contains the row count and seed data needed by `declarationToWorkbook` / `ece build` to produce a complete Excel workbook\\n\\nWhen converting a resolved declaration to an Excel workbook, formula cells always use `result: 0` (no pre-computed cached values). The workbook sets `fullCalcOnLoad=\\"1\\"`, so Excel recalculates all formulas on open. This ensures that any discrepancy between Excel\'s results and the Parquet output is immediately visible during inspection.\\n\\nSee the Resolved Declarations section of the engine specification for API and CLI usage.\\n\\n### Column Type Hints\\n\\nSupported type hints (same as the overlay format):\\n\\n`INTEGER`, `BIGINT`, `DOUBLE`, `DECIMAL`, `STRING`, `VARCHAR`, `BOOLEAN`, `DATE`, `TIMESTAMP`, `TIMESTAMP_TZ`, `TIME`, `INTERVAL`\\n\\nType hints can be specified as a plain string or as an object with an optional `format` field:\\n\\n```json\\n\\"columnTypeHints\\": {\\n \\"Value\\": \\"DOUBLE\\",\\n \\"ReportDate\\": { \\"type\\": \\"DATE\\", \\"format\\": \\"%Y-%m-%d\\" },\\n \\"CreatedAt\\": { \\"type\\": \\"TIMESTAMP\\", \\"format\\": \\"%Y-%m-%dT%H:%M:%S.%gZ\\" }\\n}\\n```\\n\\nThe `CreatedAt` example produces JavaScript-style ISO-8601 UTC strings (`\\"2024-01-15T00:00:00.000Z\\"`), where `Z` is a literal suffix and `%g` is DuckDB\'s millisecond format code.\\n\\nWhen `format` is provided, the column is output as a formatted `VARCHAR` string using DuckDB\'s `STRFTIME` function. This works with all temporal types (`DATE`, `TIMESTAMP`, `TIMESTAMPTZ`) and is useful when downstream consumers expect a specific string representation rather than a native temporal type.\\n\\nThe `format` field survives round-trips through Excel workbooks using the `TYPE:FMT:format` convention in the type hint row (e.g., `DATE:FMT:%Y-%m-%d` or `TIMESTAMP:FMT:%Y-%m-%dT%H:%M:%S`). Colons within the format string are safe \u2014 the `:FMT:` marker delimits the type from the format. For `TIMESTAMPTZ` with both timezone and format, use `TIMESTAMPTZ:timezone:FMT:format` (e.g., `TIMESTAMPTZ:America/New_York:FMT:%Y-%m-%d %H:%M:%S%z`).\\n\\n## What Studio runs\\n\\nThis document describes the calculation engine\u2019s whole format. A calculation runs a subset\\nof it. A declaration that asks for something outside the subset is refused when it is\\nvalidated, saved, imported, activated or run, with the code below, instead of failing at\\nits first run or filing a wrong number.\\n\\n### Supported\\n\\n- One calculator sheet \u2014 the first sheet with `role: \\"calculator\\"` \u2014 whose rows are the\\n project\u2019s assets, or the rows of a table the project connects as a \\"Data table\\" binding.\\n- Data and lookup sheets with typed-in `rows`, or with rows a project binding delivers.\\n- Formulas on a data or lookup sheet, and extra calculator sheets, as long as they do not\\n read the main calculator sheet. Each is checked at validate like the main sheet.\\n- A `union` `source` on a data sheet or an extra calculator sheet, with no `filter`.\\n- A `groupBy` or `crossJoin` `source` on the calculator sheet, with no `filter`, in a project\\n whose rows come from a \\"Data table\\" binding or that is set to No specific assets.\\n- Pivot sheets that total one value per data field with `sum` and no grouping: each is\\n filed as a grand total.\\n- `summaryRows` are accepted, but their values are not filed. Declare a total as a pivot.\\n\\n### Refused\\n\\n- Running sheets as a pipeline (`execution.pipeline`) \u2192 `CALC_PIPELINE_UNSUPPORTED`.\\n- A sheet that reads its rows from a file \u2014 a text `source`, or an object `source` with a\\n `path` \u2014 \u2192 `CALC_FILE_SOURCE_UNSUPPORTED`.\\n- A raw database `filter` on a `union` member or a `crossJoin` `source`, on any sheet\\n \u2192 `CALC_SOURCE_FILTER_UNSUPPORTED`. Filter the data before it is delivered, or write the\\n condition as a formula column.\\n- A `union` `source` on the calculator sheet \u2192 `CALC_CALCULATOR_SOURCE_UNSUPPORTED`.\\n- A `groupBy` or `crossJoin` `source` on any sheet but the calculator, or a `union` `source`\\n on a lookup sheet \u2192 `CALC_SHEET_SOURCE_UNSUPPORTED`. Those rows are never built there, so\\n the sheet would be empty.\\n- A `groupBy` or `crossJoin` `source` on the calculator sheet of a project whose rows are its\\n assets \u2192 `CALC_CALCULATOR_SOURCE_PER_ASSET`.\\n- A formula on a data, lookup or extra calculator sheet that reads the main calculator sheet\\n \u2192 `CALC_SHEET_READS_CALCULATOR`. Such a sheet is computed before the calculator, so the\\n run would fail, or skip its formulas and read their typed-in values instead.\\n- A same-row reference to ANOTHER table, `Factors[@EF]` or `Factors[[#This Row],[EF]]`\\n \u2192 `CALC_SAME_ROW_OTHER_TABLE`. The calculation would read the formula sheet\u2019s own `EF`,\\n not the Factors row; look the value up by a key instead. `[@EF]` and the sheet\u2019s own\\n name or table alias (`Calculator[@EF]` on Calculator) are fine.\\n- A pivot that groups or filters its total, uses a calculated field, totals with anything\\n but `sum`, or lists its values down the rows \u2192 `CALC_PIVOT_GROUPING_UNSUPPORTED`,\\n `CALC_PIVOT_CALCULATED_FIELD_UNSUPPORTED`, `CALC_PIVOT_SUBTOTAL_UNSUPPORTED`,\\n `CALC_PIVOT_DATA_ON_ROWS_UNSUPPORTED`.\\n- A formula function outside the supported list \u2192 `ECE_UNSUPPORTED_FUNCTION`.\\n- A sheet with no text `name`, a `sheets` entry that is not an object, or a sheet whose\\n `role`, `source`, `columnFormulas` or `tableNames` has the wrong shape\\n \u2192 `CALC_SHEET_UNREADABLE`: the calculation cannot be checked, so it is refused.\\n- A formula longer than 16,384 characters \u2192 `CALC_FORMULA_TOO_LONG`. Split it across helper\\n columns.\\n\\n## Validation\\n\\nDeclarations go through two validation stages:\\n\\n### 1. Structural Schema Validation\\n\\nChecks types, required fields, and enum values. Run via `validateDeclarationSchema()`.\\n\\n**Errors** (invalid declaration):\\n- Missing `version` or `sheets`\\n- Empty `sheets` array\\n- Missing or invalid sheet `name`, `role`, or `columns`\\n- Duplicate sheet names or column names within a sheet\\n- Both `rows` and `source` on the same sheet\\n- Data/lookup sheet missing both `rows` and `source` (does not apply to `\\"other\\"` sheets)\\n- No calculator sheet\\n- Invalid `columnFormulas`, `columnTypeHints`, `columnTimezones`, `staticCells`, `summaryRows`, or `literalOverrides` structure\\n- Invalid pivot sheet structure\\n\\n**Warnings** (allowed but flagged):\\n- Version mismatch\\n- `staticCells`, `summaryRows`, or `literalOverrides` on a non-calculator sheet\\n- `literalOverrides` without a `RowID` column\\n- Unknown `columnTypeHints` values\\n\\n### 2. Cross-Reference Validation\\n\\nChecks that references between sheets and columns are consistent. Run via `validateDeclaration()` (which includes structural validation).\\n\\n- Column formula references to non-existent sheets or columns\\n- Summary row formula references to non-existent sheets or columns\\n- `literalOverrides` on a column not in `columnFormulas`\\n- Pivot source sheet not found in declaration\\n- Pivot field references to non-existent source columns\\n\\nCross-reference issues are reported as **warnings** (not errors) to allow forward-looking declarations where external sources may provide columns at runtime.\\n\\n### 3. Strict Validation Mode\\n\\nPass `{ strict: true }` to enable strict validation, which reports additional errors:\\n\\n- **Unknown fields** at any level (top-level, sheet, pivot, execution, etc.) become errors. This catches typos like `\\"columnFormula\\"` instead of `\\"columnFormulas\\"`.\\n- **Version mismatch** becomes an error (instead of a warning in default mode).\\n\\n```javascript\\n// Default mode \u2014 unknown fields silently ignored\\nvalidateDeclarationSchema(declaration); // { valid: true, ... }\\n\\n// Strict mode \u2014 unknown fields become errors\\nvalidateDeclarationSchema(declaration, { strict: true }); // { valid: false, errors: [\'...unknown field \\"columnFormula\\"\'] }\\n```\\n\\nThe `--strict` CLI flag enables strict validation for `ece run` and `ece extract`.\\n\\n## Examples\\n\\n### Simple Calculator\\n\\nA calculator with two formula columns and a summary row:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Site\\", \\"Rate\\", \\"Volume\\", \\"Emissions\\"],\\n \\"rows\\": [\\n { \\"Site\\": \\"Plant A\\", \\"Rate\\": 1.25, \\"Volume\\": 100, \\"Emissions\\": null },\\n { \\"Site\\": \\"Plant B\\", \\"Rate\\": 0.80, \\"Volume\\": 250, \\"Emissions\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Emissions\\": \\"=[@Rate] * [@Volume]\\"\\n },\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Site\\": { \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" },\\n \\"Emissions\\": \\"sum\\"\\n }\\n }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Calculator with Cross-Sheet Formulas\\n\\nA calculator that references a lookup table:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Well ID\\", \\"Region\\", \\"Emissions\\", \\"Factor\\", \\"Adjusted\\"],\\n \\"rows\\": [\\n { \\"Well ID\\": \\"W001\\", \\"Region\\": \\"West\\", \\"Emissions\\": 150, \\"Factor\\": null, \\"Adjusted\\": null },\\n { \\"Well ID\\": \\"W002\\", \\"Region\\": \\"East\\", \\"Emissions\\": 200, \\"Factor\\": null, \\"Adjusted\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Factor\\": \\"=XLOOKUP([@Region], Factors[Region], Factors[Rate])\\",\\n \\"Adjusted\\": \\"=[@Emissions] * [@Factor]\\"\\n }\\n },\\n {\\n \\"name\\": \\"Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"Region\\", \\"Rate\\"],\\n \\"rows\\": [\\n { \\"Region\\": \\"West\\", \\"Rate\\": 1.25 },\\n { \\"Region\\": \\"East\\", \\"Rate\\": 1.50 }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### External Data Sources\\n\\nA calculator driven by an external CSV, with a lookup loaded from Parquet:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Timestamp\\", \\"SiteID\\", \\"Reading\\", \\"SiteName\\"],\\n \\"source\\": \\"readings.csv\\",\\n \\"columnFormulas\\": {\\n \\"SiteName\\": \\"=XLOOKUP([@SiteID], Sites[SiteID], Sites[Name])\\"\\n },\\n \\"columnTypeHints\\": {\\n \\"Timestamp\\": \\"TIMESTAMP_TZ\\"\\n },\\n \\"columnTimezones\\": {\\n \\"Timestamp\\": \\"America/Denver\\"\\n }\\n },\\n {\\n \\"name\\": \\"Sites\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\"SiteID\\", \\"Name\\", \\"Region\\"],\\n \\"source\\": \\"sites.parquet\\"\\n }\\n ]\\n}\\n```\\n\\n### Summary Rows with Formulas and Value Objects\\n\\nMultiple aggregation types in a single summary row:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Site\\", \\"Status\\", \\"Emissions\\", \\"Intensity\\"],\\n \\"rows\\": [\\n { \\"Site\\": \\"A\\", \\"Status\\": \\"Pass\\", \\"Emissions\\": 100, \\"Intensity\\": null },\\n { \\"Site\\": \\"B\\", \\"Status\\": \\"Fail\\", \\"Emissions\\": 200, \\"Intensity\\": null },\\n { \\"Site\\": \\"C\\", \\"Status\\": \\"Pass\\", \\"Emissions\\": 150, \\"Intensity\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Intensity\\": \\"=[@Emissions] / 1000\\"\\n },\\n \\"summaryRows\\": [\\n {\\n \\"label\\": \\"TOTALS\\",\\n \\"aggregations\\": {\\n \\"Site\\": { \\"type\\": \\"value\\", \\"value\\": \\"All Sites\\" },\\n \\"Status\\": \\"=COUNTIF(Calculator[Status],\\\\\\"Pass\\\\\\") & \\\\\\"/\\\\\\" & COUNTA(Calculator[Status])\\",\\n \\"Emissions\\": \\"sum\\",\\n \\"Intensity\\": \\"average\\"\\n }\\n }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Pivot Tables\\n\\nA pivot table summarizing calculator output by region:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Region\\", \\"Site\\", \\"Emissions\\", \\"Cost\\"],\\n \\"source\\": \\"site-data.csv\\",\\n \\"columnFormulas\\": {\\n \\"Cost\\": \\"=[@Emissions] * 25\\"\\n }\\n }\\n ],\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"Regional Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"rowFields\\": [{ \\"name\\": \\"Region\\" }],\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"sum\\" },\\n { \\"sourceField\\": \\"Cost\\", \\"subtotal\\": \\"sum\\" },\\n { \\"sourceField\\": \\"Site\\", \\"subtotal\\": \\"count\\", \\"name\\": \\"Site Count\\" }\\n ],\\n \\"rowGrandTotals\\": true,\\n \\"colGrandTotals\\": true\\n }\\n ]\\n}\\n```\\n\\nA transposed pivot (`dataOnRows`) where values appear as rows:\\n\\n```json\\n{\\n \\"pivotSheets\\": [\\n {\\n \\"name\\": \\"KPI Summary\\",\\n \\"source\\": { \\"sheetName\\": \\"Calculator\\" },\\n \\"dataFields\\": [\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"sum\\", \\"name\\": \\"Total Emissions\\" },\\n { \\"sourceField\\": \\"Emissions\\", \\"subtotal\\": \\"average\\", \\"name\\": \\"Avg Emissions\\" },\\n { \\"sourceField\\": \\"Site\\", \\"subtotal\\": \\"count\\", \\"name\\": \\"Site Count\\" }\\n ],\\n \\"dataOnRows\\": true,\\n \\"rowGrandTotals\\": false\\n }\\n ]\\n}\\n```\\n\\n### Literal Overrides\\n\\nOverride a formula for specific rows:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"RowID\\", \\"Site\\", \\"CH4 Rate\\", \\"Emissions\\"],\\n \\"rows\\": [\\n { \\"RowID\\": \\"R001\\", \\"Site\\": \\"A\\", \\"CH4 Rate\\": 12.5, \\"Emissions\\": null },\\n { \\"RowID\\": \\"R002\\", \\"Site\\": \\"B\\", \\"CH4 Rate\\": 8.0, \\"Emissions\\": null },\\n { \\"RowID\\": \\"R003\\", \\"Site\\": \\"C\\", \\"CH4 Rate\\": 0, \\"Emissions\\": null }\\n ],\\n \\"columnFormulas\\": {\\n \\"Emissions\\": \\"=[@CH4 Rate] * 100\\"\\n },\\n \\"literalOverrides\\": {\\n \\"Emissions\\": [\\n { \\"rowId\\": \\"R003\\", \\"value\\": 0 }\\n ]\\n }\\n }\\n ]\\n}\\n```\\n\\nRow `R003` uses the literal value `0` instead of the formula. Other rows use the formula as normal.\\n\\n### Execution Config\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Timestamp\\", \\"Value\\"],\\n \\"source\\": \\"timeseries.csv\\",\\n \\"columnTypeHints\\": {\\n \\"Timestamp\\": \\"TIMESTAMP_TZ\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"defaultTimestampType\\": \\"TIMESTAMP_TZ\\",\\n \\"defaultSourceTimezone\\": \\"America/New_York\\",\\n \\"preserveRowOrder\\": false\\n }\\n}\\n```\\n\\n### Extra Sheets (role: \\"other\\")\\n\\nWhen a workbook hosts multiple ECE configurations sharing a single `.xlsx`, some sheets may not belong to the current configuration. For example, the facility-emissions-calculator workbook has:\\n\\n- **Config 1**: Calculator + Observations + Constants + ElementMetadata\\n- **Config 2**: Summary (as calculator) + DailyResults + Observations\\n\\nWhen extracting a declaration for Config 1, `extractDeclaration()` captures DailyResults and Summary as `role: \\"other\\"` sheets. These are **inert during ECE execution** \u2014 they are not registered in DuckDB and don\'t participate in the DAG. They exist purely for workbook fidelity so that `declarationToWorkbook()` produces an `.xlsx` with all original sheets intact.\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Emissions\\"],\\n \\"columnFormulas\\": { \\"Emissions\\": \\"=SUMIFS(Obs[value], Obs[date], [@Date])\\" }\\n },\\n {\\n \\"name\\": \\"Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"date\\", \\"value\\"],\\n \\"source\\": \\"observations.csv\\"\\n },\\n {\\n \\"name\\": \\"DailyResults\\",\\n \\"role\\": \\"other\\",\\n \\"columns\\": [\\"Date\\", \\"Total\\"],\\n \\"rows\\": [\\n { \\"Date\\": \\"2025-01-01\\", \\"Total\\": 42 }\\n ]\\n }\\n ]\\n}\\n```\\n\\n### Multiple Calculator Sheets\\n\\nA declaration can contain multiple calculator sheets when a single workbook hosts several independent calculation configurations. At runtime, `calculatorSheetName` selects which sheet acts as the calculator \u2014 non-selected calculator sheets become data sheets:\\n\\n```json\\n{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"DailyCalculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Date\\", \\"Site\\", \\"DailyEmissions\\"],\\n \\"columnFormulas\\": {\\n \\"DailyEmissions\\": \\"=SUMIFS(Obs[value], Obs[date], [@Date], Obs[site], [@Site])\\"\\n }\\n },\\n {\\n \\"name\\": \\"MonthlyCalculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\"Month\\", \\"Site\\", \\"MonthlyTotal\\"],\\n \\"columnFormulas\\": {\\n \\"MonthlyTotal\\": \\"=SUMIFS(DailyCalculator[DailyEmissions], DailyCalculator[Site], [@Site])\\"\\n }\\n },\\n {\\n \\"name\\": \\"Obs\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\"date\\", \\"site\\", \\"value\\"],\\n \\"source\\": \\"observations.parquet\\"\\n }\\n ]\\n}\\n```\\n\\n```javascript\\n// Run the daily calculator \u2014 MonthlyCalculator becomes a data sheet\\nawait runEce({\\n declarationPath: \'./multi-calc.declaration.json\',\\n calculatorSheetName: \'DailyCalculator\',\\n output: \'./daily.parquet\'\\n});\\n\\n// Run the monthly calculator \u2014 DailyCalculator becomes a data sheet\\nawait runEce({\\n declarationPath: \'./multi-calc.declaration.json\',\\n calculatorSheetName: \'MonthlyCalculator\',\\n output: \'./monthly.parquet\'\\n});\\n```\\n\\nWhen `calculatorSheetName` is omitted, the first calculator sheet in the `sheets` array is used.\\n\\n## Design Decisions\\n\\n### Warnings vs. Errors\\n\\nStructural problems (missing fields, wrong types, duplicate names) are **errors** that prevent loading. Cross-reference problems (formula references non-existent columns) are **warnings** that allow the declaration to load. This accommodates declarations where external data sources provide columns at runtime that aren\'t known at validation time.\\n\\n### Case-Insensitive Matching\\n\\nColumn and sheet name matching during cross-reference validation is case-insensitive, consistent with the overlay format and Excel\'s behavior. A formula referencing `\\"emissions\\"` will match a column declared as `\\"Emissions\\"`.\\n\\n### Relationship to Overlay Format\\n\\nThe declaration and overlay formats serve complementary purposes:\\n\\n- **Declaration** is a standalone format: it defines a workbook from scratch\\n- **Overlay** is a delta format: it captures modifications on top of a base (Excel workbook or declaration)\\n\\nOverlays can be applied to declarations at runtime, just like they can be applied to Excel templates. This enables scenarios like a shared base declaration with per-customer or per-scenario overlays that swap lookup data, modify formulas, or add columns \u2014 without duplicating the entire declaration.\\n\\nThey share many of the same field shapes (`columnFormulas`, `columnTypeHints`, `columnTimezones`, `staticCells`, type hints) and both produce the same manifest structure that the downstream pipeline consumes.\\n\\n### Excel Interop\\n\\nDeclarations can be converted to and from Excel workbooks:\\n\\n- **Workbook \u2192 Declaration**: `extractDeclaration()` loads an `.xlsx` (with optional overlay) and produces a declaration capturing all functionally significant information. Visual formatting is intentionally dropped.\\n- **Declaration \u2192 Workbook**: `declarationToWorkbook()` builds a minimal `.xlsx` using `WorkbookBuilder`, producing a template that can be opened in Excel and round-tripped through the overlay system.\\n\\nThis enables workflows like: extract a declaration from an existing workbook, edit the JSON, then optionally convert back to Excel for review.\\n\\n### Calculator Data is Optional\\n\\nA calculator sheet can omit both `rows` and `source`. This supports UNIQUE/FILTER-driven calculators where the data comes from row generator formulas that pull from data sheets at execution time.\\n\\n## Best Practices\\n\\n1. **Declare all columns explicitly** \u2014 The `columns` array defines the canonical column order and is required even when data comes from an external `source`\\n\\n2. **Use `source` for large datasets** \u2014 Inline `rows` are convenient for small lookup tables; use `source` with CSV, Parquet, JSON, or JSONL files for large data sheets\\n\\n3. **Use ISO-8601 for dates** \u2014 Always use `YYYY-MM-DD` format for dates in inline rows. This ensures correct sorting, unambiguous interpretation, and proper type detection\\n\\n4. **Validate before executing** \u2014 Use `validateDeclaration()` to catch problems early. It checks both structural integrity and cross-reference consistency\\n\\n5. **Use type hints for ambiguous columns** \u2014 When a column could be interpreted as multiple types (e.g., a date stored as a string), add a `columnTypeHints` entry to make the intent explicit\\n\\n6. **Keep execution config in the declaration** \u2014 If your declaration always needs specific timezone or timestamp settings, include them in the `execution` section rather than relying on runtime parameters\\n\\n7. **Prefer one calculator sheet per declaration** \u2014 Most declarations need only one calculator sheet. When a workbook hosts multiple calculator configurations, a single declaration can include multiple `role: \\"calculator\\"` sheets. Use `calculatorSheetName` at runtime to select which one to execute \u2014 non-selected calculator sheets become data sheets, available for cross-sheet references\\n"}},{"uri":"calc://functions","name":"Supported formula functions","description":"Every spreadsheet function the engine accepts, plus the documented rewrite for each commonly-attempted function it does not.","mimeType":"text/markdown","source":{"kind":"generated","text":"# Formula functions the calculation engine accepts\\n\\nA formula using anything outside this list is refused at validate with\\n`ECE_UNSUPPORTED_FUNCTION`. The list is the engine registry itself, so it is exactly\\nwhat the validator checks against.\\n\\n## Supported (73)\\n\\n- `LET`\\n- `IF`\\n- `IFS`\\n- `IFERROR`\\n- `SUM`\\n- `SUMIFS`\\n- `COUNTIFS`\\n- `SUMIF`\\n- `COUNT`\\n- `COUNTIF`\\n- `COUNTA`\\n- `AVERAGEIF`\\n- `MAXIFS`\\n- `MINIFS`\\n- `AVERAGEIFS`\\n- `MEDIAN`\\n- `MEDIANIFS`\\n- `XLOOKUP`\\n- `AND`\\n- `OR`\\n- `NOT`\\n- `MAX`\\n- `MIN`\\n- `ABS`\\n- `ROUND`\\n- `AVERAGE`\\n- `SUMPRODUCT`\\n- `UNIQUE`\\n- `FILTER`\\n- `SINGLE`\\n- `SWITCH`\\n- `SQRT`\\n- `POWER`\\n- `LOG`\\n- `LOG10`\\n- `LN`\\n- `EXP`\\n- `MOD`\\n- `CEILING`\\n- `FLOOR`\\n- `SIGN`\\n- `INT`\\n- `TRUNC`\\n- `PI`\\n- `RAND`\\n- `LEN`\\n- `TRIM`\\n- `UPPER`\\n- `LOWER`\\n- `CONCAT`\\n- `TEXTJOIN`\\n- `LEFT`\\n- `RIGHT`\\n- `MID`\\n- `REPT`\\n- `SUBSTITUTE`\\n- `FIND`\\n- `SEARCH`\\n- `TEXT`\\n- `TODAY`\\n- `NOW`\\n- `DATE`\\n- `YEAR`\\n- `MONTH`\\n- `DAY`\\n- `DATEDIFF`\\n- `ECE.ROWNUM`\\n- `ECE.RANK`\\n- `COUNTDISTINCT`\\n- `ECE.LOOKUPWHERE`\\n- `ISBLANK`\\n- `ISNUMBER`\\n- `ISTEXT`\\n\\n## Not supported, and what to write instead (9)\\n\\nThese are the functions authors reach for most often that the engine does not\\nimplement. Each carries the rewrite that expresses the same intent.\\n\\n- **`OFFSET`** \u2014 OFFSET is incompatible with the ECE static-analysis model. For cross-row references (period-over-period, previous row), use a relative reference like `=B2` from row 3 \u2014 it compiles to LAG/LEAD window functions.\\n- **`INDIRECT`** \u2014 INDIRECT is incompatible with the ECE static-analysis model \u2014 references must be resolvable statically. Build the reference directly, or for cross-row use a relative reference (e.g. `=B2` from row 3, which compiles to LAG/LEAD).\\n- **`INDEX`** \u2014 INDEX/MATCH is not implemented. Use XLOOKUP \u2014 it covers the same exact-match and table-lookup cases.\\n- **`MATCH`** \u2014 INDEX/MATCH is not implemented. Use XLOOKUP \u2014 it covers the same exact-match and table-lookup cases.\\n- **`VLOOKUP`** \u2014 VLOOKUP is not implemented. Use XLOOKUP \u2014 it supports the same lookup semantics and is column-order-independent.\\n- **`HLOOKUP`** \u2014 HLOOKUP is not implemented. Transpose the lookup table to be row-oriented and use XLOOKUP.\\n- **`CHOOSE`** \u2014 CHOOSE is not implemented. Use SWITCH or IFS for positional / conditional selection.\\n- **`ISERROR`** \u2014 ISERROR is not implemented. Wrap the inner expression in IFERROR(expr, fallback) to express the same intent.\\n- **`VALUE`** \u2014 VALUE is not implemented. Coerce the column type via columnTypeHints, or use arithmetic (e.g. `col * 1`) to force numeric context.\\n\\n## Referring to the current row inside a calculator formula\\n\\nA `columnFormulas` entry is authored once and evaluated for every generated row, so a\\nreference to the row the formula is on has three written forms. They mean the same\\nthing, and the served examples use all three:\\n\\n- `[@Column]` \u2014 Excel\u2019s own display form, and the one the format reference uses\\n throughout.\\n- `Calculator[[#This Row],[Column]]` \u2014 the identical structured reference in the form a\\n programmatic writer emits; Excel renders it back as `[@[Column]]`.\\n- `$A3` \u2014 an A1-style cell address, and the ONLY one of the three with a precondition.\\n A cell address resolves by OFFSET from the sheet\u2019s `formulaSourceRow`, so `$A3` means\\n THIS row only when the sheet declares `formulaSourceRow: 3`. Both example\\n declarations do, and so does every seeded methodology \u2014 3 is the first data row of\\n the workbook convention they all follow (row 1 the column type hints, row 2 the\\n headers). Copy the anchor with the formula: without it the same text means a\\n different row or refuses at RUN time, and validate only soft-warns. It also names its\\n column by POSITION, so a column inserted ahead of it repoints the formula silently \u2014\\n prefer a named form where you have the choice.\\n\\nThe table name in the two structured forms must be the formula\u2019s OWN sheet (or one of\\nits `tableNames`). Naming another table \u2014 `Factors[@EF]` on the Calculator sheet \u2014 is\\nrefused with `CALC_SAME_ROW_OTHER_TABLE`: the calculation would read the Calculator\u2019s own\\n`EF`, not the Factors row Excel means. Look another table\u2019s value up by a key instead,\\nfor example `XLOOKUP([@Gas], Factors[Gas], Factors[EF])`.\\n"}},{"uri":"calc://diagnostics","name":"Validation diagnostics","description":"What each validation diagnostic code means in author-facing terms, and how to recover from it.","mimeType":"text/markdown","source":{"kind":"generated","text":"# Validation diagnostics: what each code means and how to recover\\n\\nEvery code the validator, the import inspection and a run can report, with the\\nauthor-facing meaning and the recovery. `ECE_*` codes come from the calculation\\nengine; `CALC_*` codes from this domain.\\n\\n## Codes (183)\\n\\n### `ECE_UNSUPPORTED_FUNCTION`\\n\\n**Means.** A formula uses a function outside the supported engine registry.\\n\\n**Recover.** Rewrite the formula with a supported function.\\n\\n### `ECE_FORMULA_PARSE_ERROR`\\n\\n**Means.** A formula could not be parsed. Its syntax is malformed.\\n\\n**Recover.** Fix the syntax: unmatched brackets, stray operators, or unsupported reference styles.\\n\\n### `ECE_FORMULA_TRANSLATE_ERROR`\\n\\n**Means.** A formula parsed but could not be translated to the engine SQL plan.\\n\\n**Recover.** Verify argument types and that every referenced column exists.\\n\\n### `ECE_INTERNAL`\\n\\n**Means.** An internal engine error. It is not a problem with the declaration itself.\\n\\n**Recover.** Report it with the formula and the details of this finding.\\n\\n### `ECE_UNRESOLVED_SHEET`\\n\\n**Means.** A formula references a sheet that is not present in the declaration.\\n\\n**Recover.** Add the missing sheet, or correct the reference.\\n\\n### `ECE_UNRESOLVED_COLUMN`\\n\\n**Means.** A formula references a column that is not present on the target sheet.\\n\\n**Recover.** Add the missing column, or correct the reference.\\n\\n### `ECE_UNCLASSIFIED_SHEET_REFERENCE`\\n\\n**Means.** A referenced sheet exists but is not classified as a data or lookup sheet.\\n\\n**Recover.** Set the sheet\u2019s role to data or lookup, or rename it to start with Data__ or Lookup__.\\n\\n### `ECE_MULTIPLE_UNIQUE`\\n\\n**Means.** A calculator has more than one row generator. UNIQUE and FILTER both count, and only one is supported.\\n\\n**Recover.** Combine the row generators, or split the logic into separate calculators.\\n\\n### `ECE_UNIQUE_NOT_STANDALONE`\\n\\n**Means.** UNIQUE/FILTER is nested inside a larger expression; it must be the whole column formula.\\n\\n**Recover.** Move the wrapping logic into a downstream column.\\n\\n### `ECE_CIRCULAR_DEPENDENCY`\\n\\n**Means.** The formula dependency graph contains a cycle.\\n\\n**Recover.** Introduce an intermediate column, or use a LAG/LEAD relative reference.\\n\\n### `ECE_TABLE_SPILL_CONFLICT`\\n\\n**Means.** A spill column coexists with a conflicting fixed-row-count construct (reserved: no check reports it yet).\\n\\n**Recover.** Move one construct onto a separate sheet.\\n\\n### `ECE_MISSING_TYPE_HINT`\\n\\n**Means.** A column has no explicit type hint; the engine inferred one.\\n\\n**Recover.** Give the column a type, so its values are not converted in ways you don\u2019t expect (API: a `columnTypeHints` entry).\\n\\n### `ECE_AMBIGUOUS_SHEET_ROLE`\\n\\n**Means.** A sheet role is ambiguous (reserved: no check reports it yet).\\n\\n**Recover.** Start the sheet\u2019s name with Data__ or Lookup__, or set its role when you import the file.\\n\\n### `ECE_NO_CALCULATOR`\\n\\n**Means.** The declaration has no calculator sheet.\\n\\n**Recover.** Add at least one sheet whose role is \\"calculator\\".\\n\\n### `ECE_LITERAL_OVERRIDE_NO_EFFECT`\\n\\n**Means.** A literal override targets a column that has no formula, so it does nothing.\\n\\n**Recover.** Remove the override, or give the column a formula (API: add it to `columnFormulas`).\\n\\n### `ECE_AMBIGUOUS_COLUMN_REFERENCE`\\n\\n**Means.** Two columns on a sheet have names that differ only in letter case, so a reference to either cannot tell them apart (Excel matches column names without regard to case).\\n\\n**Recover.** Rename one of the two columns (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DUPLICATE_COLUMN_NAME`\\n\\n**Means.** A sheet has two columns whose names differ only in letter case. Excel treats them as one name, so the calculation cannot tell which a formula reads.\\n\\n**Recover.** Rename one of the two columns so the names differ by more than letter case (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DUPLICATE_TABLE_NAME`\\n\\n**Means.** Two sheets answer to the same table name up to letter case. A sheet answers to its name, its table names, and the name the workbook gives its table. A table reference cannot tell them apart.\\n\\n**Recover.** Rename one of the sheets, or change its table names, so no two sheets share one (API: `name` / `tableNames`).\\n\\n### `ECE_RESERVED_COLUMN_NAME`\\n\\n**Means.** A column is named like one the engine adds to its own tables (`__row_num__`, `__generator_order__`, `__union_order__`, or a name starting with `__ece_` or `__calc_`, in any letter case).\\n\\n**Recover.** Rename the column (API: the sheet\u2019s `columns`).\\n\\n### `ECE_DATE_PART_OUT_OF_RANGE`\\n\\n**Means.** DATE was given a year below -32768. Excel\u2019s answer for such a year has not been checked, so the calculation refuses it rather than file a date that may be wrong.\\n\\n**Recover.** Check the year the formula passes to DATE; a real year is 1900\u20139999 (0\u20131899 reads as 1900 plus the year, as in Excel).\\n\\n### `ECE_DATE_SERIAL_OUT_OF_RANGE`\\n\\n**Means.** A number in a date column, or in a date-formatted cell, is no date Excel can show (below 0, or after 9999-12-31 23:59:59). Excel shows such a cell as #####.\\n\\n**Recover.** Check the formula\u2019s arithmetic or the source value, or make the column a number column (API: a `DOUBLE` entry in `columnTypeHints`). In a workbook, correct the cell or give it a number format.\\n\\n### `ECE_CRITERIA_TEXT_ORDERING`\\n\\n**Means.** A SUMIFS-style criterion orders text by a text value (\\">abc\\"). Excel orders text by the computer\u2019s language settings, which the calculation does not reproduce, so it refuses rather than match different rows.\\n\\n**Recover.** Compare numbers or dates instead, or switch the calculation to exact matching for case-sensitive ordering (API: `execution.criteriaMatching: \\"exact\\"`).\\n\\n### `ECE_CRITERIA_AMBIGUOUS_COLUMN`\\n\\n**Means.** A criteria range, an XLOOKUP range or a lookup value holds cells whose kind (number or text) the calculation cannot tell before the run. Excel knows each cell\u2019s kind; the calculation needs it up front to match as Excel does.\\n\\n**Recover.** Give the column a type (API: a `columnTypeHints` entry), or compute it without mixing number and text results.\\n\\n### `ECE_MIXED_VALUE_COLUMN`\\n\\n**Means.** A SUMIFS-style, COUNTDISTINCT or LOOKUPWHERE value range mixes numbers with text or TRUE/FALSE cells. Excel leaves the text and TRUE/FALSE cells out; the calculation reads the column as one kind and cannot.\\n\\n**Recover.** Make the column\u2019s values numbers, leaving missing values blank.\\n\\n### `ECE_IFERROR_TEXT_VALUE`\\n\\n**Means.** IFERROR with a number fallback met a text value that is not a number or a date. Excel returns the text; the calculation\u2019s column holds numbers and would have filed 0, so it refuses.\\n\\n**Recover.** Use a text fallback such as \\"\\" (IFERROR(x, \\"\\")), or look up a numeric column.\\n\\n### `ECE_FORMULA_NOT_IN_COLUMNS`\\n\\n**Means.** A sheet has a formula for a column it does not list, so the formula would be dropped from the results without a word.\\n\\n**Recover.** Add the column to the sheet, or remove the formula (API: list it in `columns`, or delete it from `columnFormulas`). From a workbook this usually means an Excel table column whose name no longer matches its header cell.\\n\\n### `ECE_SELF_AGGREGATE_COMPUTED_COLUMN`\\n\\n**Means.** A formula totals or looks up a computed column of its own sheet. That column is not computed yet when the formula runs, so the result would not be Excel\u2019s.\\n\\n**Recover.** Use [@Column] for the same row\u2019s value. A whole-column total or lookup over a computed column needs a calculation that computes it in an earlier step.\\n\\n### `ECE_WHOLE_COLUMN_SELF_RANGE`\\n\\n**Means.** A formula reads its own sheet\u2019s whole column (SUM(X:X)), which includes its own cell. Excel calls that a circular reference.\\n\\n**Recover.** For a column total, use a summary row (API: `summaryRows`).\\n\\n### `ECE_BOUNDED_RANGE_PARTIAL`\\n\\n**Means.** A range with fixed rows (C2:C6) misses some data rows, starts on the header, or ends below the data where a blank would change the result. The calculation does not read a part of a table by row position.\\n\\n**Recover.** Use a whole-column reference (Sheet!C:C) or a table column (Table[Column]); to use only some rows, choose them with SUMIFS-style criteria on a key or date column.\\n\\n### `ECE_BOUNDED_RANGE_RUNTIME_ROWS`\\n\\n**Means.** A range with fixed rows covers the rows typed into the sheet, but the run may deliver more rows, which would fall outside it.\\n\\n**Recover.** Use a whole-column reference (Sheet!C:C), a table column (Table[Column]), or a range ending at row 1048576.\\n\\n### `ECE_RELATIVE_ROW_RANGE`\\n\\n**Means.** A range with relative rows (SUM(C2:C6)) moves down one row on every row in Excel. The calculation reads one range for every row, so it refuses rather than file different values.\\n\\n**Recover.** Anchor both rows with $ ($C$2:$C$6) so every row reads the same rows, or use a table column (Table[Column]) or a whole column (Sheet!C:C).\\n\\n### `ECE_PARTIAL_RUNNING_RANGE`\\n\\n**Means.** A running range (SUM($B$2:B2)) does not start on the sheet\u2019s first data row, ends on another row than the formula\u2019s own, or is used where the calculation cannot keep a running total.\\n\\n**Recover.** For a running total, anchor the start on the first data row and end on the formula\u2019s own row (SUM($B$2:B2) when data starts on row 2), in SUM, AVERAGE, MAX, MIN or COUNTA. For a fixed set of rows, anchor both rows ($B$2:$B$6).\\n\\n### `ECE_ABSOLUTE_ROW_UNRESOLVED`\\n\\n**Means.** A cell reference anchors its row with $ ($B$2) on a row the calculation cannot place: not a data row of the sheet, or a sheet whose rows it does not keep in order.\\n\\n**Recover.** Anchor the row on a data row of the sheet, put the constant in a cell above the header (API: `staticCells`), or look the value up by a key with XLOOKUP or SUMIFS.\\n\\n### `ECE_RANGE_NOT_NUMERIC`\\n\\n**Means.** SUM, AVERAGE, MAX, MIN, MEDIAN, SUMPRODUCT or COUNT reads a column holding text or TRUE/FALSE. Excel skips those cells; the calculation reads the column as one kind and cannot, so it refuses rather than file a different number.\\n\\n**Recover.** Make every cell of the column a number or blank and give it a number type (API: a `DOUBLE` entry in `columnTypeHints`), or total a numeric column.\\n\\n### `ECE_SOURCE_COLUMNS_MISMATCH`\\n\\n**Means.** The rows a sheet was given at run time carry other columns than the sheet declares (a missing one, or extra ones).\\n\\n**Recover.** Give the sheet exactly its declared columns, with the same names (letter case may differ) and no others. For a connected dataset, its columns must match the sheet\u2019s.\\n\\n**Next.** open-bindings\\n\\n### `ECE_SUMMARY_ROW_UNTRANSLATED`\\n\\n**Means.** A summary-row formula is not one the calculation can compute: it must be a single total over its own column\u2019s data rows, or over another column of the sheet.\\n\\n**Recover.** Write the summary as one total over the column (SUM(B2:B6), SUM(B:B) or SUM(Calculator[col])) (API: `summaryRows`).\\n\\n### `ECE_SUMMARY_ROW_FAILED`\\n\\n**Means.** A summary-row formula failed on the run\u2019s values. The run is refused rather than filing the summary row empty.\\n\\n**Recover.** Read the message for the failing formula and fix it, or the values it totals (API: `summaryRows`).\\n\\n### `ECE_EXPLAIN_REQUEST`\\n\\n**Means.** The request to explain a figure is not one the engine can answer: no such column or row, a row key compared with a column of another type, or the run\u2019s input types given without its row counts (or the other way round).\\n\\n**Recover.** Ask again for a column and row the calculation has, giving the run\u2019s input types and row counts together. (API: `inputTypes` with `runRowCounts`.)\\n\\n### `ECE_EXPLAIN_ROW_NOT_FOUND`\\n\\n**Means.** No row of the calculation matches the row asked for, so there is nothing to explain.\\n\\n**Recover.** Ask for a row the run computed (for an asset, one in the run\u2019s asset selection).\\n\\n### `ECE_EXPLAIN_ROW_NOT_UNIQUE`\\n\\n**Means.** Several rows of the calculation match the row asked for, so it is not one figure.\\n\\n**Recover.** Name the row by a key that picks exactly one row, or by its row number.\\n\\n### `ECE_EXPLAIN_WINDOW_FUNCTION`\\n\\n**Means.** The formula ranks or numbers rows (ECE.RANK, ECE.ROWNUM), so its value depends on the order of every row and cannot be explained from one.\\n\\n**Recover.** Explain a column that reads the ranked column instead; the rank appears there as one piece.\\n\\n### `ECE_EXPLAIN_RUNNING_RANGE`\\n\\n**Means.** The formula reads a running range (SUM($B$2:B2)), whose value is every row so far, so it cannot be explained from one row.\\n\\n**Recover.** Explain a column that reads the running total instead.\\n\\n### `ECE_EXPLAIN_PIVOT_CELL`\\n\\n**Means.** A pivot cell totals many rows, so it is not explained piece by piece.\\n\\n**Recover.** Explain the calculator rows the pivot totals.\\n\\n### `ECE_EXPLAIN_GROUPED_SOURCE`\\n\\n**Means.** The column is an input of a grouped or joined calculator source: its value comes from another sheet\u2019s rows, not from a formula.\\n\\n**Recover.** Explain one of the calculator\u2019s formula columns instead.\\n\\n### `ECE_EXPLAIN_INPUT_TYPES`\\n\\n**Means.** The input column types given for the explanation do not match the calculator\u2019s inputs as the run registered them, so it would not reproduce the run.\\n\\n**Recover.** Explain with the run\u2019s own input types, unchanged, covering every input column (API: `inputTypes`).\\n\\n### `ECE_EXPLAIN_NEEDS_RUN_ROWS`\\n\\n**Means.** The explanation was given a different number of rows of a sheet than the run had, so a lookup or total would read other rows than the run did.\\n\\n**Recover.** Explain with every row of that sheet the run had (API: `runRowCounts`).\\n\\n### `ECE_EXPLAIN_VOLATILE`\\n\\n**Means.** The column, or a column it reads, uses RAND, NOW or TODAY, whose value changes every time it is computed, so no explanation reproduces it.\\n\\n**Recover.** Replace the volatile function with a fixed value or an input, then re-run.\\n\\n### `ECE_EXPLAIN_PIPELINE`\\n\\n**Means.** The calculation runs as a pipeline of stages; only a single calculator is explained.\\n\\n**Recover.** Explain a calculation without a pipeline (API: `execution.pipeline`).\\n\\n### `ECE_PIPELINE_STAGE_NOT_FOUND`\\n\\n**Means.** The pipeline names a sheet the calculation does not have (API: `execution.pipeline`).\\n\\n**Recover.** Correct the stage name or add the sheet. A calculation does not run pipelines yet, so removing the pipeline is the usual fix.\\n\\n### `ECE_PIPELINE_STAGE_ORDER`\\n\\n**Means.** A pipeline stage reads a stage that runs after it (API: `execution.pipeline`).\\n\\n**Recover.** Reorder the stages, or remove the read. A calculation does not run pipelines yet.\\n\\n### `ECE_SUPPLEMENTAL_SHEET_SKIPPED`\\n\\n**Means.** A data or lookup sheet\u2019s formulas read the main calculator sheet, so the run skips that sheet and its formulas are never computed.\\n\\n**Recover.** Move those formulas onto the calculator sheet, or rewrite them so they do not read it (API: the sheet\u2019s `columnFormulas`).\\n\\n### `ECE_SKIPPED_SHEET_READ`\\n\\n**Means.** A formula reads a computed column of a sheet the run skips (because that sheet reads the main calculator), so the value would never be computed.\\n\\n**Recover.** Move the skipped sheet\u2019s formulas onto the calculator sheet, or stop reading them, so every value read is computed.\\n\\n### `ECE_CRITERIA_INTERVAL`\\n\\n**Means.** A SUMIFS-style criteria range holds time spans (an INTERVAL column). Excel has no such cell, so the calculation cannot match criteria against it as Excel would.\\n\\n**Recover.** Give the column a number type holding the span as a fraction of a day, or a text type (API: `columnTypeHints`).\\n\\n### `ECE_CRITERIA_1900_LEAP_DAY`\\n\\n**Means.** A criterion or a text cell names a time on 1900-02-29, a day Excel shows that never existed. The calculation cannot hold it as a date, so it refuses rather than match the wrong day.\\n\\n**Recover.** Correct the date in the criterion or the cell.\\n\\n### `ECE_INVALID_CRITERIA_MATCHING`\\n\\n**Means.** The calculation\u2019s matching setting is neither excel nor exact (API: `execution.criteriaMatching`).\\n\\n**Recover.** Use \\"excel\\" (the default, Excel\u2019s rules) or \\"exact\\" (plain equality), or remove the setting (API: `execution.criteriaMatching`).\\n\\n### `ECE_SQL_GEN_SKIPPED`\\n\\n**Means.** SQL generation was skipped because bind-time errors were present.\\n\\n**Recover.** Fix the other errors first, then check again to see any findings that remain.\\n\\n### `ECE_EXTRACTION_WARNING`\\n\\n**Means.** A loader heuristic flagged a structure (sparse formulas, summary rows, inconsistent source rows).\\n\\n**Recover.** Check the flagged part of the workbook. The calculation still runs, but it may not read the workbook the way you meant.\\n\\n### `CALC_UNRESOLVED_VARIABLE`\\n\\n**Means.** A formula reads a sheet the calculation does not have, or a sheet that ships no rows with nothing connected to supply them. At import this holds the import; on a project it refuses activation, because a run would read nothing for the formula and an empty read adds up to 0, a made-up figure filed as a governed number.\\n\\n**Recover.** At import, add the missing sheet to the file (or stop ignoring it (API: drop it from `sheetRoles`)) or correct the formula, then read the file again. On a project, connect the sheet as a Data table under Connect inputs (API: `kind: \\"dataTable\\"`), or connect the value itself as an Observation or an Asset property (API: `kind: \\"observation\\"` or `kind: \\"assetProperty\\"`). A value that really is fixed can be a Constant (API: `kind: \\"constant\\"`). If a formula names a sheet the calculation does not have, the name is a typo: correct it and use the new version on the project.\\n\\n**Next.** open-mapping\\n\\n### `CALC_DATA_SHEET_UNBOUND`\\n\\n**Means.** A `role: \\"data\\"` sheet ships its own rows inside the pinned declaration, the calculator reads it, and no binding on the project delivers it, so every run computes over the rows the methodology shipped, which are usually the vendor\u2019s samples rather than the tenant\u2019s activity data, and files them as governed numbers. An ACTIVATION rule: import and the library report the same condition as a warning, because a methodology being stored or browsed files nothing.\\n\\n**Recover.** Under Connect inputs, connect the sheet to a dataset as a Data table, so its rows come from the dataset. If the rows in the file are the real data, add them to Data as a dataset and connect that, so they have version history. (API: `kind: \\"dataTable\\"`)\\n\\n### `CALC_DATA_TABLE_BINDING_LIMIT`\\n\\n**Means.** The composition carries more than one \\"Data table\\" binding, or a \\"Data table\\" binding beside an \\"Observation\\", \\"Asset property\\", \\"Asset aggregate\\" or \\"Asset count\\" binding. A row-generated calculator derives its own row set from one delivered table, so a second table has no row spine to land on and a per-asset value has no row to land on; every run of such a project refuses. An ACTIVATION rule: the same limit refuses at run time, and activation reports it before the project goes ACTIVE.\\n\\n**Recover.** Keep one Data table connection and remove the others. To combine several tables, add them to Data as one dataset and connect that. To feed a value per asset, remove the Data table connection, or add the value to the connected table as a column.\\n\\n### `CALC_CONSTANT_MISSING`\\n\\n**Means.** A constant the calculation uses has no value that covers this period.\\n\\n**Recover.** Add a value for the constant that covers this period to its reference data, or connect the input to reference data that has one, or correct the project\u2019s reporting window. Then run the period again.\\n\\n### `CALC_CONSTANT_CHANGES_IN_PERIOD`\\n\\n**Means.** A constant the calculation uses has a value that changes during this period: at least one row of its reference data starts or ends partway through the period (its validFrom or validTo date falls inside it), so no single value covers the whole period. The run stopped rather than pick one.\\n\\n**Recover.** Line the change up with a period boundary: end the old row on the last day of a period and start the new row on the first day of the next one, so one row covers each whole period. Write each end as a date: a date covers that whole day, while a date with a time covers only up to that instant, so a time even a second before the period ends does not cover it. Or connect the input to reference data with one row for the whole period. Then run the period again.\\n\\n### `CALC_LOOKUP_FACTOR_CHANGES_IN_PERIOD`\\n\\n**Means.** A value in a Lookup table changes during this period: at least one of its rows starts or ends partway through the period (its validFrom or validTo date falls inside it), so no single value covers the whole period. The run stopped rather than read the value as 0.\\n\\n**Recover.** Line the change up with a period boundary: end the old row on the last day of a period and start the new row on the first day of the next one, so one row covers each whole period. A value that stops applying partway through must end at a period boundary too. Write each end as a date: a date covers that whole day, while a date with a time covers only up to that instant, so a time even a second before the period ends does not cover it. Then run the period again.\\n\\n### `CALC_REFERENCE_VALIDITY_COLUMN_NEAR_MISS`\\n\\n**Means.** A Lookup table or constant\u2019s dataset has a column that looks like a validity date (such as ValidFrom, valid from or VALID-TO) but is not named exactly validFrom or validTo. Only those exact names date a table\u2019s rows, so the rows were not dated by that column: a row with no exactly named date on that side is read as open there, valid however far the period reaches. The run still completes.\\n\\n**Recover.** Rename the column to validFrom or validTo, exactly as written here, publish the dataset, and run the period again. If the rows are meant to apply to every period, nothing needs fixing. A dataset from SDP also carries its own valid_from and valid_to columns beside record_id and manifest_id: those are system dates and never count.\\n\\n### `CALC_EMPTY_COVERAGE`\\n\\n**Means.** No observation data covers the selected assets for the run period.\\n\\n**Recover.** Confirm the observation source has rows for these assets and this period.\\n\\n### `CALC_SCOPE_EMPTY_AT_PERIOD_END`\\n\\n**Means.** No assets were in the project\u2019s asset selection at the end of this period, although the same asset selection matches assets today. The run stopped rather than replace the period\u2019s published results with an empty one.\\n\\n**Recover.** Check the project\u2019s reporting window against when these assets were added: a window that starts before them has nothing to run over. Correct the window or the asset selection, then run the period again. An asset selection that is empty at both times still publishes, with a warning.\\n\\n### `CALC_DATA_TABLE_TARGET_NOT_DATA_SHEET`\\n\\n**Means.** The Data table connection points at a sheet of the calculation that isn\u2019t a data sheet. Your table would be ignored, and every run would calculate over the sample rows the calculation ships with.\\n\\n**Recover.** Point the connection at one of the calculation\u2019s data sheets (the refusal names them). If the calculation should read a new table, add a data sheet for it, publish the calculation again, and connect that sheet.\\n\\n### `CALC_DATA_TABLE_CONTRIBUTED_NOTHING`\\n\\n**Means.** The bound dataTable delivered no rows to ANY subject in the run, yet the run still produced results. The bound source cannot have supplied them, so they came from the declaration\u2019s own rows. The run is FAILED and promotes nothing. Partial coverage is not this: a run whose table covers some of the run\u2019s subjects and not others still completes.\\n\\n**Recover.** Check that the binding names the right data sheet and the right dataset, that the promoted version carries rows for this period, and that the assetColumn values match the selected assets.\\n\\n### `CALC_DATA_TABLE_RESULT_OUTSIDE_SCOPE`\\n\\n**Means.** A run with a Data table connection keyed its results to ids that are not assets in the project\u2019s asset selection. The Calculator\u2019s asset column holds rows typed into the workbook rather than values taken from the connected data, so the results would be filed under subjects that are not your assets, and a formula that looks data up by that column matches nothing, so every value would be 0. The run is FAILED and files nothing.\\n\\n**Recover.** Make the Calculator\u2019s asset column a formula over the connected data sheet \u2014 the message names both, for example =UNIQUE(Data__Readings[AssetId]) \u2014 so its rows are the assets the data carries. Pin the corrected version on the project and run the period again. (API: the column is the `dataTable` binding\u2019s `assetColumn`)\\n\\n### `CALC_NARROW_SCOPE`\\n\\n**Means.** The asset selection is unusually narrow, possibly from an over-restrictive selector.\\n\\n**Recover.** Review the selector; proceed if the narrow asset selection is intended.\\n\\n### `CALC_VOLATILE_FUNCTION`\\n\\n**Means.** A formula uses a volatile function (RAND/NOW/TODAY); its value is non-reproducible.\\n\\n**Recover.** Replace it with an input for the period or a fixed value.\\n\\n### `CALC_SHADOWED_CONSTANT`\\n\\n**Means.** A project-local reference dataset shadows a shared constant of the same code.\\n\\n**Recover.** Confirm the shadow is intended; the project\u2019s own value takes precedence.\\n\\n### `CALC_EMPTY_RESULT_PROMOTED`\\n\\n**Means.** A COMPLETED run produced zero result cells; the empty result set was promoted and supersedes this period\u2019s previous Tier-2 publish under the warn-and-promote policy.\\n\\n**Recover.** If the empty result is not the truth, fix the asset selection or the observation data and re-run the period \u2014 the re-run\u2019s promotion supersedes the empty publish (version history keeps both).\\n\\n### `CALC_PIVOT_GROUPING_UNSUPPORTED`\\n\\n**Means.** A pivot table breaks down or filters its total (API: `rowFields` / `colFields` / `pageFields`). A calculation files one grand total only; a total broken down or filtered belongs in Reports.\\n\\n**Recover.** Remove the grouping to file the grand total here, or build the breakdown as a report over the published results.\\n\\n### `CALC_PIVOT_CALCULATED_FIELD_UNSUPPORTED`\\n\\n**Means.** A pivot table uses a calculated field: a formula over its totals, such as a ratio of two sums. A calculation cannot file a total like that yet.\\n\\n**Recover.** Compute each part as its own output on the Calculator sheet and total those with a sum; the calculation files each sum as its own total.\\n\\n### `CALC_PIVOT_DATA_FIELD_COLLISION`\\n\\n**Means.** More than one declared data field aggregates the same calculator column. A harvested total is filed under its source element, so the two would collide on one cell.\\n\\n**Recover.** Give each aggregate its own calculator column.\\n\\n### `CALC_PIVOT_SUBTOTAL_UNSUPPORTED`\\n\\n**Means.** A pivot table totals a column with something other than a sum: a count, average, minimum or maximum. A filed total is kept under its column alone, with that column\u2019s unit, so any other figure would read as the sum.\\n\\n**Recover.** Change the pivot to a sum, or compute the other figure as its own column on the Calculator sheet, with its own unit.\\n\\n### `CALC_PIVOT_DATA_ON_ROWS_UNSUPPORTED`\\n\\n**Means.** A pivot table lists its values down the rows (API: `dataOnRows: true`). A total the calculation can file needs one row, with a column per value.\\n\\n**Recover.** Show the pivot\u2019s values in columns instead of rows (API: `dataOnRows: false`).\\n\\n### `CALC_PIVOT_RESERVED_COLUMN`\\n\\n**Means.** A pivot data field aggregates a reserved keying column (__name__). Reserved columns carry row identity, not a measured quantity.\\n\\n**Recover.** Aggregate a measured calculator column instead.\\n\\n### `CALC_PIVOT_OUTPUT_MISSING`\\n\\n**Means.** A declared pivot produced no engine output, or declares no readable data field, so its declared total would silently vanish.\\n\\n**Recover.** Check the pivot\u2019s name and that each data field names a source field, then import the calculation again.\\n\\n### `CALC_PIVOT_OUTPUT_UNHARVESTED`\\n\\n**Means.** The engine computed a pivot output that no declared pivot claims, so its total would be discarded. The declaration reader and the engine disagree about what is declared.\\n\\n**Recover.** Report this with the calculation: it is a fault in the app, not in the calculation. Don\u2019t rely on this run\u2019s totals until it is fixed.\\n\\n### `CALC_PIVOT_TOTAL_CELL_MISSING`\\n\\n**Means.** A declared pivot produced output, but its grand-total cell could not be read (wrong row count, or a non-scalar value).\\n\\n**Recover.** Check that the pivot is not grouped and that its data fields use number columns on the calculator sheet.\\n\\n### `CALC_AGGREGATE_PERIOD_UNRESOLVED`\\n\\n**Means.** A declared aggregate must be keyed to the run\u2019s single period, but the period could not be resolved unambiguously from the calculator source.\\n\\n**Recover.** Check that the calculator sheet\u2019s source has one period per run. A total dated to the wrong period files a wrong number.\\n\\n### `CALC_RUN_CANCELLED`\\n\\n**Means.** An operator cancelled this run while it was still in flight; the note names who cancelled it and, when given, why. The run sealed CANCELLED before its results were written, so it filed no numbers and promoted nothing.\\n\\n**Recover.** Nothing to fix \u2014 a cancel is a deliberate stop. Re-run the period from the Runs tab when the asset selection, bindings or data are right; the new run supersedes the cancelled one. NOTE: an automated (scheduled) project does NOT re-file a cancelled period on its own \u2014 the re-run is the operator\u2019s, or the bulk backfill action\u2019s.\\n\\n### `CALC_ENGINE_VERSION_MISMATCH`\\n\\n**Means.** A run sealed before engine stamping was refused because its calculation version had been saved on a different engine than the one the app ran. Runs no longer refuse on this: each run executes on the app\u2019s engine and records it.\\n\\n**Recover.** Re-run the period: it now runs on the app\u2019s engine. The run\u2019s checks say whether the engine changed since the project\u2019s previous run.\\n\\n### `CALC_SCOPE_NONE_REQUIRES_DATA_TABLE`\\n\\n**Means.** A project set to No specific assets carries no dataTable binding. Every run needs a row spine, and with no assets the delivered table is the only one available.\\n\\n**Recover.** Connect exactly one dataset as a Data table, or choose Specific assets or a filter for the project. A calculation over constants and lookups alone has no rows to file. (API: one `kind: \\"dataTable\\"`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_SCOPE_NONE_ASSET_BINDING`\\n\\n**Means.** A project set to No specific assets carries a per-asset binding (observation, assetProperty, assetAggregate, or assetCount). Each of those is ABOUT the selected assets, and none are selected by design here.\\n\\n**Recover.** Remove the per-asset connection, or choose Specific assets or a filter for the project. Constant, Table lookup and Output connections work without assets. (API: `constant`, `tableLookup` and `node`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSET_COLUMN_FORBIDDEN`\\n\\n**Means.** The Data table connection names an asset column, but this project is set to No specific assets, so there is no asset to match it against.\\n\\n**Recover.** Clear the asset column. To identify the result rows by another column, choose it as the identity column instead.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_IDENTITY_COLUMN_FORBIDDEN`\\n\\n**Means.** A dataTable binding on a project with assets selected declares an identityColumn. On that path the asset column is what keys each result row, so a second keying column would be ambiguous.\\n\\n**Recover.** Clear the identity column; it applies only to a project set to No specific assets.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSET_COLUMN_REQUIRED`\\n\\n**Means.** The Data table connection doesn\u2019t say which column holds the asset. This project has assets selected, so every result has to belong to an asset.\\n\\n**Recover.** Choose the column that holds the asset, or set the project to No specific assets.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_COLUMN_UNKNOWN`\\n\\n**Means.** A data sheet declares one or more columns the BOUND dataset version does not carry. Nothing refuses this: every read of a missing column resolves to 0 (the documented absent-input\u21920 contract), so a run over this binding COMPLETES and files zeros instead of failing.\\n\\n**Recover.** Rename the column to match the dataset\u2019s, connect a dataset that has it, or add a dataset version that has it. If the column is really missing for this period, nothing needs fixing: a missing value reads as zero, and this warning only makes that visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_NO_MATCH`\\n\\n**Means.** The bound observation source carries rows, but none of them matched this property for one or more selected assets in the run period. Nothing refuses this: each unmatched value resolves to 0 (the documented absent-input\u21920 contract), so the run COMPLETES and files zeros for those assets. The diagnostic counts the DISTINCT assets affected and names a few of them.\\n\\n**Recover.** Check the grain and period of the bound dataset against the run: a monthly-landed source matches a monthly period, an annual row does not roll into a month, and the rows must carry this property code. If those assets genuinely had no readings this period, no action is needed \u2014 zero is the contract, and this warning only makes it visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_BLANK_CELLS`\\n\\n**Means.** A dataset bound one column per input has blank cells in a value column, on rows that were otherwise read for this period. Each blank counts as no reading, so the period\u2019s total for those assets leaves it out: a year with one blank month sums eleven months. The run still completes. The diagnostic counts the blank cells and names a few (asset @ period).\\n\\n**Recover.** Fill the blank cells in the dataset if those readings exist, then rerun the period. If those assets genuinely had no reading then, nothing needs fixing \u2014 this warning only makes the gap visible.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_SOURCE_EMPTY`\\n\\n**Means.** The version of the observation dataset this run read has no rows at all, so every input it feeds resolved to 0 for every selected asset. Nothing refuses it and the run completes, but the observations check fails, because no asset had a reading to match. The number affected counts the selected assets, which is all of them, and the diagnostic names a few.\\n\\n**Recover.** Check that the bound dataset version carries rows, and that the version the run read is the one you expect. If the source genuinely has no data, nothing needs fixing: zero is what the calculation reads when an input is absent.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_ROWS_OUT_OF_SCOPE`\\n\\n**Means.** Rows in the bound observation dataset name an asset that is not in this run\u2019s asset selection, so the run did not read them. That covers an ID that matches no asset at all, and an asset left out at the period end (divested, or not yet acquired). A dataset shared across projects usually carries other assets\u2019 rows, so this is often expected. Nothing refuses it and the run completes. The number affected counts ROWS, not assets: an asset with twelve monthly rows counts twelve. The diagnostic names a few of the asset IDs, each once.\\n\\n**Recover.** If a named ID belongs to an asset this calculation should cover, check that ID in the dataset against the asset, then check the project\u2019s asset selection and reporting window. If those rows belong to assets the calculation does not cover, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ROWS_OUT_OF_SCOPE`\\n\\n**Means.** Rows in the dataset connected as a Data table name an asset that is not in this run\u2019s asset selection, so they were left out of the table the calculation read. That covers an ID that matches no asset at all, and an asset left out at the period end (divested, or not yet acquired). A dataset shared across projects usually carries other assets\u2019 rows, so this is often expected. Nothing refuses it and the run completes. The number affected counts ROWS, not assets: an asset with twelve monthly rows counts twelve. The diagnostic names a few of the asset IDs, each once.\\n\\n**Recover.** If a named ID belongs to an asset this calculation should cover, check that ID in the dataset against the asset, then check the project\u2019s asset selection and reporting window. If those rows belong to assets the calculation does not cover, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_ASSETS_WITHOUT_ROWS`\\n\\n**Means.** Some selected assets got no row from the dataset connected as a Data table for this period, so the calculation has no row for them and files no result for them. When the dataset delivered no rows at all, every selected asset is counted. The run still completes. The diagnostic counts the assets and names a few.\\n\\n**Recover.** Check that the dataset carries rows for these assets in this period, and that the version the run read is the one you expect. If those assets had no activity in the period, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_NAME_NO_ROWS`\\n\\n**Means.** A formula reads a name from the dataset connected as a Data table (for example SUMIFS(Observations[value], Observations[elementId], \\"SUBW-Z-ZNA\\", \u2026)), and the dataset has rows for this period but none for that name, for any unit. No formula gives a fallback for it, so every unit would read it as 0, which looks exactly like a real reading of 0. The run stopped rather than file that number.\\n\\n**Recover.** Check that the dataset carries rows for this name in this period, and that the name in the formula matches the one in the data. If a missing value should fall back to a default, write the fallback in the formula, for example IF(x = 0, default, x) or IF(COUNTIFS(<same criteria>) = 0, default, SUMIFS(\u2026)). Then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_NAME_ROWS_MISSING`\\n\\n**Means.** A formula reads a name from the dataset connected as a Data table, and some units (possibly all of them) have no rows for that name in this period, so each of them reads it as 0. Where the formula gives a fallback (for example IF(x = 0, default, x)), the fallback applies instead. A row whose value is 0 is a real reading and is not counted. No rows for any unit can be a missing measurement, or a quiet period or a period mismatch, so the run completes and says so rather than stopping. The diagnostic counts the units and names a few.\\n\\n**Recover.** Check that the dataset carries rows for this name for these units in this period, and that the name in the formula matches the one in the data. If those units genuinely had no reading, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_IFERROR_SUMIFS_NOOP`\\n\\n**Means.** A formula wraps SUMIFS in IFERROR to supply a default, but the default can never apply. SUMIFS already returns 0 when nothing matches (it never errors on an empty match), so IFERROR(SUMIFS(\u2026), d) computes exactly what SUMIFS(\u2026) computes and d is never used. The run completes and the value is unchanged. What is lost is the default you believed you had expressed. Two independent choices are in play: HOW a value is read (an activity quantity SUMS matching rows via SUMIFS; a parameter is a SINGLE value via XLOOKUP) and WHAT absence means (0, or a default), and only some read forms can carry a default.\\n\\n**Recover.** Write the default so it applies. For a sum: IF(COUNTIFS(<same criteria>)=0, <default>, SUMIFS(<range>, <same criteria>)). COUNTIFS is 0 only when nothing matched, so the default applies exactly then. For a single value: XLOOKUP(<key>, <keys>, <values>, <default>), where the fourth argument is the default. If 0 is the right value when nothing matches, remove the IFERROR: it adds nothing.\\n\\n### `CALC_CROSS_ROW_FORMULA_PER_ASSET`\\n\\n**Means.** A formula on a per-asset project reads other assets\u2019 rows: it ranks rows (ECE.RANK), numbers rows (ECE.ROWNUM), reads a previous or following row, or reads the whole calculator column (for example COUNTIFS(Calculator[X], \u2026) or [@Gas] / SUM(Calculator[Gas])). A per-asset run evaluates its assets in fixed-size batches, so the formula sees only the assets in its own batch, and once more assets are selected than one batch holds, the value it files differs from the answer over all of them while the run still completes. Every calculator sheet is checked, including extra sheets and pipeline stages; a sheet whose formulas cannot be checked at all (it will not bind on its own) is refused the same way, as unchecked rather than as clean. Refused at activation and, for a project activated before this rule, at the run that would batch. On activation the draft stays as saved; on a revise of an ACTIVE project the change is not applied and the project keeps its current version.\\n\\n**Recover.** Rewrite the formula to read only its own row. If the figure really spans assets, compute it where every asset is in view: as a total, or in a project whose rows come from a Data table or that is set to No specific assets.\\n\\n### `CALC_ELEMENT_FORMULA_SHADOWS_BINDING`\\n\\n**Means.** An element carries both a formula (`columnFormulas` entry) and a binding targeting it. The formula OVERRIDES the value the binding injects. The run COMPLETES with zeros, and because the methodology now has no input columns, the \\"Calculation inputs\\" checklist never renders to warn about it.\\n\\n**Recover.** Remove the column\u2019s formula from the calculation and use the column\u2019s name in another formula instead. On save it becomes an input, and Connect inputs lets you connect it.\\n\\n**Next.** open-bindings\\n\\n### `CALC_ROW_IDENTITY_UNRESOLVED`\\n\\n**Means.** The Data table connection doesn\u2019t say which column identifies each result row, and the calculation doesn\u2019t generate its rows either, so nothing says what the result rows are.\\n\\n**Recover.** Choose an identity column on the connection, or use a calculation version that generates its rows.\\n\\n**Next.** open-bindings\\n\\n### `CALC_SCOPE_ARM_LOCKED_BY_RUNS`\\n\\n**Means.** A revise tried to move a project between selecting assets (explicit/filter) and No specific assets after the project had already run. The two produce different Tier-2 dataset families, so the one already published would stay live and never be superseded: a receipted, permanently stale answer with nothing marking it stale.\\n\\n**Recover.** Clone the project instead. The clone starts as a draft with nothing published, and its asset selection can change freely. You can still switch between a list of assets and a filter, or edit the filter, and a project that has never run can change freely.\\n\\n**Next.** clone-project\\n\\n### `CALC_ROW_IDENTITY_AMBIGUOUS`\\n\\n**Means.** The Data table connection doesn\u2019t say which column identifies each result row, and the calculation generates its rows from more than one column. Guessing would file results against the wrong column.\\n\\n**Recover.** Choose one of those columns as the connection\u2019s identity column.\\n\\n**Next.** open-bindings\\n\\n### `CALC_LOOKUP_SHEET_FROM_FILE`\\n\\n**Means.** A lookup sheet\u2019s rows (factors or reference rows) are saved in the calculation, so runs read them as they are. This is the normal setup for factors and needs no dataset. Only a dataset named exactly like the sheet can replace those rows.\\n\\n**Recover.** Optional: to keep the values in Data with version history, add a dataset with the sheet\u2019s name and connect it to the project.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_SHEET_FROM_FILE`\\n\\n**Means.** A data sheet\u2019s rows in the imported file are examples. A project that uses the calculation can\u2019t be activated until it connects a dataset to that sheet; the dataset\u2019s rows then replace the file\u2019s.\\n\\n**Recover.** Under Connect inputs, connect the sheet as a Data table. To file results per asset, pick the dataset column that holds each row\u2019s asset (its values must be Studio asset IDs) and the column that holds the period. Without a period column, a run reads the rows of every period. If the rows in the file are the real data, add them to Data as a dataset and connect that. (API: a `dataTable` binding with `assetColumn` and `timeColumn`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_MULTIPLE_DATA_SHEETS`\\n\\n**Means.** The formulas read two or more data sheets. A project can connect only one data sheet for now, and it cannot be activated while a data sheet that ships rows is unconnected, so no project can run this calculation yet. Advisory: it never blocks the import.\\n\\n**Recover.** Combine the activity data into one data sheet, or set a sheet that holds factors to Lookup table. (API: at most one `dataTable` binding per project)\\n\\n**Next.** open-mapping\\n\\n### `CALC_RESULT_NOT_FINITE`\\n\\n**Means.** A result came out as Infinity or NaN (not a number) for one or more assets or rows, usually because its formula divided by zero. A filed result must be a finite number, so the run fails and nothing is published. One finding per result counts the assets or rows and names a few (asset @ period, or row @ period). It says the result divided by zero, and which input was 0, when the formula is one division and that input was 0 for every one of them. Otherwise it says the result is not a finite number: an overflow, MOD by zero, LOG of base 1, CEILING to a multiple of 0, or 0 raised to a negative power give the same value.\\n\\n**Recover.** Guard the division in that result\u2019s formula. Where the formula is one division and it divided by zero, the finding writes the guard out with the formula\u2019s own names, for example IF([@Production]=0, 0, [@Emissions]/[@Production]); otherwise guard each division the same way, IF(denominator=0, 0, numerator/denominator). Choose the value that a zero denominator should give. IFERROR(numerator/denominator, fallback) catches it too (since ECE 1.4.1), and also files the fallback where an input is blank or not a number. Then rerun the period.\\n\\n### `CALC_ROW_KEY_TYPED_IN`\\n\\n**Means.** The Calculator sheet names its rows by typing them into its key column (`unitId`, or else a first column that holds text) with no formula that generates them, and a formula reads that column, typically a SUMIFS or XLOOKUP that matches each row\u2019s asset. In a project run the key column holds each asset\u2019s Studio asset ID, not the names typed into the file, so a formula that looks data up by it finds only rows keyed by Studio asset ID. Rows keyed by the file\u2019s names match nothing and file 0. Advisory: it never blocks the import.\\n\\n**Recover.** Look up the rows by Studio asset ID, in the sheet the formula reads or in the dataset a project connects to that sheet. Or, to take the rows from a data sheet, make the ID column a formula over it, for example =UNIQUE(Data__Readings[AssetId]) (the finding names your workbook\u2019s own data sheet when it has one), and connect a dataset to that sheet on the project. Or connect the formula\u2019s inputs on the project as an Observation or an Asset property instead of looking them up. (API: a `tableLookup` binding whose rows are keyed by asset id, or `kind: \\"observation\\"` / `kind: \\"assetProperty\\"` on each input column)\\n\\n**Next.** open-bindings\\n\\n### `CALC_BINDING_NEEDS_LANDED_DATASET`\\n\\n**Means.** A sheet the formulas read declares its columns but ships no rows, so nothing supplies its data until it is connected to a dataset that exists and is promoted. A run with the sheet unconnected does not refuse. It reads nothing for it, which is how a run can complete with numbers quietly missing.\\n\\n**Recover.** Add the data to Data as a dataset, approve it, then connect the sheet on the project. For a lookup sheet, the dataset must have exactly the sheet\u2019s name (API: `kind: \\"tableLookup\\"`, its `source.code` the sheet name). For a data sheet, a Data table connection names the sheet and the dataset can have any name (API: `kind: \\"dataTable\\"`). Once connected, a run stops until the dataset exists and has an approved version: a lookup table stays on the version approved when it was connected (or follows approved versions, if it was set to), and a data sheet reads its current version, which must be approved (API: `SOURCE_NOT_FOUND` for a dataset that does not exist, `SOURCE_NOT_PROMOTED` when the version a run reads is not promoted).\\n\\n**Next.** open-bindings\\n\\n### `CALC_PIPELINE_UNSUPPORTED`\\n\\n**Means.** The calculation runs its sheets as a pipeline, one stage after another (API: `execution.pipeline`). A calculation cannot run a pipeline yet: every run would fail without filing anything, and the pipeline produces no declared totals.\\n\\n**Recover.** Compute everything on one calculator sheet, reading the other sheets as tables, and remove the pipeline (API: delete `execution.pipeline`, or set it to `[]`).\\n\\n### `CALC_FILE_SOURCE_UNSUPPORTED`\\n\\n**Means.** A sheet reads its rows from a file named in the calculation (API: a text `source` such as `\\"observations.csv\\"`). A calculation cannot read files: a run would fail, or read a file nobody meant.\\n\\n**Recover.** Type the rows into the sheet, or connect the sheet\u2019s data as a Data table under Connect inputs, and remove the file name (API: delete the sheet\u2019s `source`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_CALCULATOR_SOURCE_UNSUPPORTED`\\n\\n**Means.** The calculator sheet builds its rows by combining other sheets (API: a `union` `source` on the calculator sheet). A calculation cannot run a calculator built that way: every run would fail without filing anything.\\n\\n**Recover.** Combine the rows on a data sheet and read it from the calculator sheet, or connect the combined data as a Data table (API: delete the calculator sheet\u2019s `source`).\\n\\n### `CALC_CALCULATOR_SOURCE_PER_ASSET`\\n\\n**Means.** The calculator sheet builds its rows by grouping another sheet or by pairing two sheets (API: a `groupBy` or `crossJoin` `source` on the calculator sheet), but the project gives it one row per asset. Those two ways of building rows conflict: the run would fail, or complete with rows that are not the project\u2019s assets. A project whose rows come from a \\"Data table\\" binding, or that is set to No specific assets, runs it.\\n\\n**Recover.** Use the calculation in a project that connects its data as a Data table or is set to No specific assets. Or remove the calculator sheet\u2019s source so it computes one row per asset (API: delete the calculator sheet\u2019s `source`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_SHEET_READS_CALCULATOR`\\n\\n**Means.** A data, lookup or extra calculator sheet has formulas that read the main calculator sheet. Sheets like that are computed before the calculator, so the run would fail, or skip those formulas and file the values typed into the sheet instead of computed ones.\\n\\n**Recover.** Move those formulas onto the calculator sheet, or rewrite them so they do not read it (API: the sheet\u2019s `columnFormulas`).\\n\\n### `CALC_SAME_ROW_OTHER_TABLE`\\n\\n**Means.** A formula reads the same row of another table, for example Factors[@EF] or Factors[[#This Row],[EF]] on the Calculator sheet. In Excel that is the Factors row level with the formula; the calculation reads it as the formula sheet\u2019s own EF column instead, so the value it files would be wrong.\\n\\n**Recover.** Look the value up by a key, for example XLOOKUP([@Gas], Factors[Gas], Factors[EF]), or, if the sheet\u2019s own column is meant, write [@EF] (API: `columnFormulas`).\\n\\n### `CALC_SOURCE_FILTER_UNSUPPORTED`\\n\\n**Means.** A sheet\u2019s source combines or pairs other sheets and filters the result with a condition written as database code: a `filter` on a `union` member or on a `crossJoin` source. A calculation cannot run a raw database filter safely, so it is refused.\\n\\n**Recover.** Filter the data before it is delivered to the calculation, or express the condition as a formula column on the sheet (API: remove `filter` from the `source`).\\n\\n### `CALC_FORMULA_TOO_LONG`\\n\\n**Means.** A formula is longer than a calculation reads: 16,384 characters, twice the longest formula Excel itself allows. A formula that long is refused rather than checked.\\n\\n**Recover.** Split the formula across helper columns, each computing one part, and combine them in a shorter formula (API: `columnFormulas`).\\n\\n### `CALC_SHEET_SOURCE_UNSUPPORTED`\\n\\n**Means.** A sheet other than the calculator builds its rows in a way a calculation only runs elsewhere: by grouping another sheet or pairing two sheets (only the calculator sheet runs those), or by combining other sheets on a lookup sheet (only a data sheet runs that) (API: a `groupBy`, `crossJoin` or `union` `source`). The sheet would have no rows, and the run would complete and file a wrong number.\\n\\n**Recover.** Build grouped or paired rows on the calculator sheet, make a combined lookup sheet a data sheet, or connect the data as a Data table (API: remove the sheet\u2019s `source`, or set `role: \\"data\\"` for a `union`).\\n\\n**Next.** open-bindings\\n\\n### `CALC_SHEET_UNREADABLE`\\n\\n**Means.** A sheet in the calculation cannot be read (API: a `sheets` entry that is not an object, whose `name` or `role` is not text, whose `source` is neither text nor an object, whose `columnFormulas` are not an object, or whose `tableNames` are not a list). The calculation cannot be checked for engine features it cannot run, so it is refused rather than run unchecked.\\n\\n**Recover.** Give every sheet a text name and role, its formulas as named entries, its table names as a list, and a source that is text or an object, or remove the sheet (API: the field the message names).\\n\\n### `CALC_LOOKUP_TARGET_NOT_LOOKUP_SHEET`\\n\\n**Means.** A Table lookup, or a constant with a Lookup table chosen, fills a table that is not one of the calculation\u2019s lookup tables. With a Lookup table chosen it fills that table; a Table lookup with none chosen fills the table named like its dataset. If the calculation has no lookup table by that name, the dataset\u2019s rows fill nothing and the formulas read the tables\u2019 own rows; if the name belongs to a data table, its rows replace that table\u2019s. Either way a run would complete with numbers the dataset did not supply. (API: a `tableLookup` binding\u2019s `targetSheet`, or its `source.code` when `targetSheet` is absent, and a `constant` binding\u2019s `targetSheet` when set, must name a sheet whose role is lookup.)\\n\\n**Recover.** Connect a dataset named like one of the calculation\u2019s lookup tables (the message names them), or remove the Table lookup. To fill a data sheet, connect it as a Data table instead. (API: set `targetSheet` and `targetElement` to the lookup table it fills; for a data sheet use `kind: \\"dataTable\\"`.)\\n\\n### `CALC_SHEET_FILLED_TWICE`\\n\\n**Means.** One table of the calculation is filled more than one way: from more than one dataset, by more than one Table lookup that names it, or by a Data table and another connection. A run keeps one of them and drops the others without a word, so its numbers could come from any of them. (API: bindings deliver the same sheet with different `source.code` values, or more than one sets it as `targetSheet`, or one of them is a `dataTable`.)\\n\\n**Recover.** Keep one connection for the table (the message names the table and what fills it) and remove the rest. Several Table lookups and constants reading the same dataset into one table are fine. (API: one `source.code` per delivered sheet.)\\n\\n### `CALC_LOOKUP_TARGET_ELEMENT_MISMATCH`\\n\\n**Means.** A Table lookup that names its Lookup table carries a different name of its own. The two must match: whatever reads the name, a scenario for one, takes it as the table the rows fill. The binder always gives them the same name, so this comes from a request that set them apart. (API: a `tableLookup` binding sets `targetSheet` and a different `targetElement`.)\\n\\n**Recover.** Open the Table lookup and save it again to fix the name. (API: set `targetElement` to the same value as `targetSheet`.)\\n\\n### `CALC_LOOKUP_FILLS_NO_LOOKUP_TABLE`\\n\\n**Means.** A Table lookup with no Lookup table chosen fills the table named like its dataset, and the calculation has no lookup table by that name. Its rows fill nothing, or, when the name belongs to another kind of table, replace that table\u2019s rows. Nothing refuses it: the run lets it through as runs always have, so the dataset may not be supplying the numbers you expect. It is not raised for a table the run refuses for another reason, since that refusal says what to fix. (API: a `tableLookup` binding without `targetSheet` whose `source.code` names no sheet whose role is lookup.)\\n\\n**Recover.** Connect a dataset named like one of the calculation\u2019s lookup tables (the message names them), or remove the Table lookup. To fill a data sheet, connect it as a Data table instead. (API: on one `tableLookup` for the dataset, set `targetSheet` and `targetElement` to the lookup table it should fill; for a data sheet use `kind: \\"dataTable\\"`.)\\n\\n### `CALC_LOOKUP_FALLBACK_USED`\\n\\n**Means.** A formula looks a value up in a Lookup table with a fallback written in (for example XLOOKUP([@Gas], Factors[Gas], Factors[GWP], 0)), and the table has no row for the key some rows look up. Those rows filed the fallback, usually 0, which looks exactly like a real value. The run completes and says so: the diagnostic counts the rows and names a few, and the keys the table lacks. A lookup inside a branch only some rows take (an IF, IFS or SWITCH branch, the fallback of IFERROR, of another XLOOKUP or of ECE.LOOKUPWHERE, or a LET binding) is not counted, since a row that skips the branch never takes its figure from the table, and a lookup bound by LET is not counted even when every row reads it; that includes a COUNTIFS guard written to mark the fallback intended.\\n\\n**Recover.** Check that the dataset connected to the Lookup table carries a row for each key named. If the fallback is the value you intend for a missing key, say so in the formula: IF(COUNTIFS(Factors[Gas], [@Gas]) = 0, 0, XLOOKUP([@Gas], Factors[Gas], Factors[GWP], 0)).\\n\\n**Next.** open-bindings\\n\\n### `CALC_ASSET_PROPERTY_CURRENT_VALUE_USED`\\n\\n**Means.** A selected asset had no value for a bound property at the end of the period, so the run used the asset\u2019s value today for that property and completed. Every other value is the one in force at the period end. A property with a value set from a past date is never filled from today, even when that value is blank. The warning names the property and the date, counts the assets and names the first few.\\n\\n**Recover.** Check that today\u2019s value also held during the period. If it did, nothing needs fixing. If it did not, set the property\u2019s value from the date it took effect in Assets, then run the period again. The run then reads that value, and this warning stops.\\n\\n### `CALC_LOOKUP_PIN_DATASET_MISMATCH`\\n\\n**Means.** A constant or Table lookup is pinned to a version of a different dataset from the one it reads, or the dataset it reads does not exist or is not visible to you. Its runs would read rows the dataset never held, so the save is refused. (API: a `constant` or `tableLookup` binding\u2019s `pin.datasetId` is not the dataset its `source.code` names.)\\n\\n**Recover.** Open the input and pick its version again from the dataset it reads. (API: send `pin` with the `datasetId` and an approved `versionId` of the dataset `source.code` names, or send `follow: true` to follow its approved versions.)\\n\\n### `CALC_LOOKUP_PIN_NOT_PROMOTED`\\n\\n**Means.** A constant or Table lookup is pinned to a version that is not approved, or that the dataset does not have. A run reads only approved versions and never falls back to another one, so every run of the project would be refused. (API: a `constant` or `tableLookup` binding\u2019s `pin.versionId` is unknown or not promoted.)\\n\\n**Recover.** Pick an approved version of the dataset, or approve this one in Datasets first and save again. When the message names a second input, the version was that input\u2019s choice: one still on it, which the new input joined (move that input to an approved version), or one this save removes, whose version was kept so the constants and Table lookups reading the dataset stay on it (pick an approved version for the first input). (API: promote the version, or send a `pin.versionId` that is promoted. `data.heldBy` names an untouched binding holding the pin an added binding joined; `data.carriedFrom` a binding the save removes whose pin was carried so the `constant` and `tableLookup` bindings left on `source.code` keep reading it.)\\n\\n### `CALC_SOURCE_PINNED_TWICE`\\n\\n**Means.** Two inputs read the same dataset and are pinned to different versions of it. A project reads one version of a dataset per run, so it cannot tell which one the numbers should come from. (API: two `constant` or `tableLookup` bindings with the same `source.code` carry different `pin` values.)\\n\\n**Recover.** Set every input reading the dataset to the same approved version. The message names the dataset and the inputs pinning it. (API: one `pin` per `source.code`; a refused save or run carries the versions in `data.versionIds`.)\\n\\n### `CALC_SOURCE_PIN_AND_FOLLOW`\\n\\n**Means.** An input reading a dataset is set to follow its approved versions while another input reading the same dataset stays on one version of it, or one input is set both ways. A project reads one version of a dataset per run, so the dataset either stays on a version or follows approved versions, for every input reading it. (API: a `constant` or `tableLookup` binding carries `pin` and `follow`, or carries `follow` on a `source.code` another binding pins.)\\n\\n**Recover.** Choose one for the dataset: keep every input reading it on the same approved version, or set them all to follow approved versions. The message names the inputs. (API: send `pin` or `follow` on a binding, never both, and `follow` only on a `source.code` no binding pins.)\\n\\n### `CALC_SOURCE_NEWER_VERSION_WAITING`\\n\\n**Means.** A constant or Table lookup read the newest approved version of its dataset, and the dataset has a newer version that is not approved: one waiting for approval, held by its checks or rejected. The run completed on the approved values; runs read only approved versions. (API: every input reading the dataset is a `constant` or `tableLookup` with no `pin`, so runs read its newest promoted version.)\\n\\n**Recover.** If the newer values are the ones to report, approve, in Datasets, a version that holds them, then run the period again. If the approved values are right, nothing needs doing.\\n\\n### `CALC_SOURCE_NEWER_DATA_BLOCKED`\\n\\n**Means.** A dataset this run read has newer data that is not used: its newest delivery is held back from publishing (blocked) and adds, changes or removes rows dated in this period, or has problem rows dated in it, or a reason that holds every period, or rows sent to the source and dated in this period wait on a fix. The run completed on the last published delivery and names it, the delivery that waits, and why, in the words Datasets uses. (API: an unpinned `observation`, `dataTable` or Category map input reads its current load, and reads the newest published version whose source delivery is published only while the current load is held.)\\n\\n**Recover.** Open the dataset at the delivery that waits and resolve its rows, or publish it, then run the period again. If the published data is right, nothing needs doing: the period can still be sent unless its approval setup requires \\"Input data up to date\\".\\n\\n### `CALC_CATEGORY_ELEMENT_NOT_SPLITTABLE`\\n\\n**Means.** A result listed under Results broken down by Emission category (API: `categoryBreakdown.splitElements`) cannot be split into category parts. Only a mass or CO2e result is broken down: one whose unit is a mass such as t, kg, lb, tCH4 or tCO2e, or a mass per unit of time such as t/yr, because only then do the parts add up to the whole. A ratio (an intensity such as tCO2e/boe, a control efficiency), a result with another unit or none, a result holding text, and a name the calculation has no result for are refused.\\n\\n**Recover.** Remove the result from Results broken down by Emission category, or, if it really is a mass, give it a mass unit in the calculation and pin that version. To stop breaking results down at all, clear the breakdown (API: `categoryBreakdown: null`).\\n\\n### `CALC_CATEGORY_READS_OTHER_ROWS`\\n\\n**Means.** A result listed under Results broken down by Emission category (API: `categoryBreakdown.splitElements`) takes in other rows of the calculation: its formula, or a column it uses, reads the whole calculator column, ranks or numbers rows, or reads a previous or following row. Those are other assets\u2019 rows, so its value carries rows whose source types were never judged for it, and a category part could be filed under the wrong category. It is also refused when another calculator sheet reads other rows, or could not be checked, since what that sheet feeds is not traced. Refused when the project is saved, and again by the run against the version it pinned.\\n\\n**Recover.** Remove the result from Results broken down by Emission category, or rewrite it (and the columns it uses) to read only its own row. For example, break down the per-asset result a roll-up adds up, not the roll-up itself.\\n\\n### `CALC_CATEGORY_GRAIN_UNSUPPORTED`\\n\\n**Means.** The Emission category breakdown is supported only for results filed per asset: Observation inputs on a project with assets selected. It is refused on a project set to No specific assets, whose results are filed per row of a Data table or as totals (API: `assetScope: { kind: \\"none\\" }`), and for a Data table feeding a broken-down result on assets selected (API: `kind: \\"dataTable\\"`). Runs of those shapes could not file category parts. Refused when the project is saved, and again by the run against the versions it pinned.\\n\\n**Recover.** Feed the broken-down results from Observation inputs on a project with assets selected. Otherwise clear the breakdown (API: `categoryBreakdown: null`).\\n\\n### `CALC_CATEGORY_MAP_UNRESOLVED`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) names a dataset that does not exist or is not visible to you, so no source type could be given a family.\\n\\n**Recover.** Check the Category map\u2019s dataset name, or add the map to Data as a dataset with the columns sourceType and family (program is optional), and name that one.\\n\\n### `CALC_CATEGORY_MAP_SHAPE`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) lacks a column every map needs: sourceType (each source type, once) and family (the group it adds up into). program (a reporting program the family belongs to) is optional, and so are validFrom and validTo, which date a row the way a constant\u2019s are. Any other column is ignored, except one that reads as program misnamed (Program, or program with spaces around it) on a map with no program column, which is refused so its programs are not dropped.\\n\\n**Recover.** Add a version of the map with the sourceType and family columns (and a program column spelled exactly program, if it has one), or name a dataset that has them.\\n\\n### `CALC_CATEGORY_COLUMN_MISSING`\\n\\n**Means.** A source that feeds a result broken down by Emission category has no Emission category column (API: `categoryBreakdown.sourceTypeColumn`), so a run could not tell which category each of its rows belongs to. Only sources feeding a broken-down result need the column: a production source feeding only an intensity does not.\\n\\n**Recover.** Add the column to the dataset (the message names the dataset and its columns), or name the column it does carry as the Emission category column. If the source should not feed a broken-down result, remove that result from Results broken down by Emission category.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CATEGORY_CHECKS_SKIPPED`\\n\\n**Means.** Validate could not read the datasets the Emission category breakdown names, so it skipped checking the Category map (API: `categoryBreakdown.map`) and each source\u2019s Emission category column. The other checks ran. This is not a pass: saving checks the datasets again and refuses if Datasets cannot be read.\\n\\n**Recover.** Validate again once Datasets can be read. Nothing in the project needs to change for this warning alone.\\n\\n### `CALC_CATEGORY_UNMAPPED`\\n\\n**Means.** Readings feeding a result broken down by Emission category carry source types the Category map (API: `categoryBreakdown.map`) gives no family for, in the version the run read and for the whole of the run\u2019s period (a row dated to cover only part of the period does not count). The run cannot say which family those readings belong to, so it files nothing. The message names up to 20 of the source types, each with how many readings carry it. A column carrying more than 10,000 distinct values is refused the same way, as a guardrail: it is almost certainly not the column holding the source type.\\n\\n**Recover.** Add a row for each named source type to the Category map (sourceType and family, and program if the map has that column), dated to cover the whole period, and land that version; or correct the source type in the input data, or name the right column as the Emission category column. Then run the period again.\\n\\n### `CALC_CATEGORY_SOURCE_TYPE_BLANK`\\n\\n**Means.** A result broken down by Emission category has value with no source type: readings feeding it leave the Emission category column (API: `categoryBreakdown.sourceTypeColumn`) blank or hold something other than text or a number in it, or no Observation input feeds the result at all, so none of its value comes from a reading that carries a source type. The run files nothing rather than leave part of a result without a category.\\n\\n**Recover.** Fill the Emission category column on the rows the message counts, or connect an Observation input whose dataset carries it to the result. If the result should not be broken down, remove it from Results broken down by Emission category.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CATEGORY_MIXED_SUBJECT`\\n\\n**Means.** A run sealed before results could be split between categories was refused because an asset\u2019s rows feeding a result broken down by Emission category carried more than one source type. Runs no longer refuse on this: such an asset\u2019s result is split into one part per source type, each computed over that source type\u2019s rows.\\n\\n**Recover.** Run the period again: the asset\u2019s result is now split between its categories. If its parts do not add up to the result, the run says so (CALC_CATEGORY_TOTALS_DO_NOT_RECONCILE).\\n\\n### `CALC_CATEGORY_MAP_ROWS_INVALID`\\n\\n**Means.** The Category map (API: `categoryBreakdown.map`) has rows a run cannot read for its period: a source type listed in more than one row, a row with no sourceType or family (or no program, in a map with a program column), a sourceType longer than 500 characters, a sourceType, family or program holding a NUL character (U+0000, which cannot be stored), a validFrom or validTo that is not a date, or a row whose validFrom is after its validTo (refused wherever the row sits, even outside the period). Each source type must name exactly one family (and program, when the map has that column) for any one period.\\n\\n**Recover.** Correct the rows the message names in the Category map and land that version, then run the period again.\\n\\n### `CALC_CATEGORY_TOTALS_DO_NOT_RECONCILE`\\n\\n**Means.** A result broken down by Emission category (API: `categoryBreakdown.splitElements`) does not add up across its category parts: on at least one asset, its value differs from the sum of that asset\u2019s category parts. Every asset\u2019s value must add up on its own (a negative value too), so a subtotal filtered to any asset matches it. Usually some assets have value that no reading with a source type carries, such as a constant added to the result on an asset with no readings, so that value could not be given a category. The run fails and publishes nothing, so no category subtotal can disagree with the run\u2019s total.\\n\\n**Recover.** Check the assets the message names. Feed their value from readings that carry the Emission category column, or remove the result from Results broken down by Emission category. Then run the period again.\\n\\n### `CALC_ROLLUP_SCOPE_NOT_A_TREE`\\n\\n**Means.** Roll-up levels (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list) total results at levels of a named hierarchy, under a root: the selection\u2019s own root, or the root a fixed asset list names to total under (API: `assetScope.rootAssetId`). This asset selection has no root, or reads the unassigned bucket, where an asset can sit under two parents and a total would count it twice.\\n\\n**Recover.** Select the project\u2019s assets Under the asset at the top of the levels to total, by its id or its name, in a named hierarchy. On a fixed asset list, pick that asset as the root to total under, and its hierarchy. Or remove the roll-up levels.\\n\\n### `CALC_ROLLUP_LEVEL_REPEATED`\\n\\n**Means.** A level is listed twice under the roll-up levels (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list): the same asset type, or the same property. Each level is listed once, top level first.\\n\\n**Recover.** List each asset type and each property once.\\n\\n### `CALC_ROLLUP_LEVEL_UNKNOWN_TYPE`\\n\\n**Means.** A roll-up level (API: `assetScope.filter.rollupLevels`, or `assetScope.rollupLevels` on a fixed asset list) names an asset type Assets does not govern, or a property no asset template defines, so nothing could ever be one of its nodes.\\n\\n**Recover.** Pick the level from the asset types or the template properties in Assets, or remove it.\\n\\n### `CALC_RESULT_BEHAVIOUR_INVALID`\\n\\n**Means.** A result\u2019s behaviour at a total, as confirmed (API: `resultBehaviours`), cannot be honoured: the result is not a numeric result of the calculation, or is confirmed twice; a ratio is confirmed as adding up (a ratio never adds up, whether it is one by its unit or by its formula); or a ratio\u2019s numerator or denominator is not a numeric result or does not add up, or its unit is not the result\u2019s own; or a ratio disagrees with the result\u2019s formula: another numerator or denominator than the one division the formula is, the two swapped, another scale than the formula\u2019s constant factors, or a formula that adds or subtracts and divides nothing.\\n\\n**Recover.** Leave the result to its detected behaviour, or confirm a ratio over two results that add up (a mass, a volume, a count), in the result\u2019s own unit, dividing what its formula divides by the formula\u2019s own scale.\\n\\n### `CALC_ROLLUP_LEVEL_PARTIAL`\\n\\n**Means.** A roll-up level was not totalled for this run, so its total would be partial or missing: no asset of the level\u2019s type under the project\u2019s selection root holds a selected asset at the period end (a node holding some assets that are not selected still totals the selected ones it holds), the asset selection has no root to walk the tree from, the level\u2019s nodes could not be read, the level has more nodes than a run reads one by one (the message gives the count), or the run was posted by an outside engine, which files no node results. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Widen the asset selection to the level\u2019s nodes, total a coarser level, or remove the level from the roll-up; for a posted run, run the period in Studio. Then run the period again.\\n\\n### `CALC_ROLLUP_LEVEL_OVERLAP`\\n\\n**Means.** A roll-up level was not totalled for this run: two of its nodes hold the same asset at the period end (a node nested under another node of its own type), so that asset would be counted twice. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Give the nested node its own asset type in Assets, or keep only one of the two types as a level. Then run the period again.\\n\\n### `CALC_ROLLUP_LEVEL_UNASSIGNED`\\n\\n**Means.** Some selected assets sit under no node of a roll-up level at the period end and hold a non-zero amount of a result that adds up. They are shown in a row of their own (\u201CNot in any \u2026\u201D, or \u201CNo \u2026\u201D for a field), so the level still adds up to the level above. Only such an asset is counted: one under no node that holds only zeros leaves every total unchanged. The warning is per run, so an asset can appear in a month it files a non-zero amount and not in others. The level is still totalled for the assets its nodes hold; the message names how many assets are left out and their total. A level no selected asset can be placed in at all (a property none of them holds) is not totalled. The other levels, and the asset results, are unaffected.\\n\\n**Recover.** Place those assets under a node of the level in Assets (or give them the property the level groups by), or remove the level. Then run the period again.\\n\\n### `CALC_ROLLUP_BEHAVIOUR_UNREADABLE`\\n\\n**Means.** The calculation version stores a behaviour at a total for one of its results (API: `resultBehaviours`) that this engine cannot read (a kind, a source or a field inside the behaviour it does not know, or a value it refuses), so whether that result adds up at a node of the roll-up is read from its unit alone (unless another stored entry for it can be read), as the Ledger reads it: a unit that is a ratio (a share, a quotient, a rate) is not totalled, any other is summed. An entry that names no result gives none a behaviour and is passed over. When the stored behaviours are not a list at all, none can be read and every result is judged by its unit. The asset results are unaffected either way.\\n\\n**Recover.** Run the period again: one cause is a version written by a newer release while a deploy was part-way, which the engine reads once every server runs that release. A re-run does not heal a stored behaviour that this release reads more strictly than the release that wrote it, or one that is itself bad: if the warning comes back, save a new calculation version that confirms that result as adding up, a ratio or per asset only, point the project at it, and run the period again.\\n\\n### `CALC_NUMERIC_VALUE_UNTYPED`\\n\\n**Means.** Some numbers this run published could not be copied into the numericValue column of the published datasets, so that column is empty for them. Datasets can only store a number there when it can hold it exactly, and a number too large to hold exactly (past 2^53 \u2212 1) cannot be held. The exact number is still in the value column and in the run\u2019s own results, so nothing is lost and sign-off is unaffected. Only a sum or total built over numericValue (an Insights metric, an aggregate read) leaves these numbers out. The diagnostic names the result and the published dataset, and counts the values left out of that one dataset, so a result and its category breakdown are counted separately, each against its own dataset.\\n\\n**Recover.** Nothing needs fixing in the calculation. Where a total must include these numbers, total the value column instead of numericValue.\\n\\n### `CALC_NODE_LEVEL_UNNAMED`\\n\\n**Means.** A roll-up level has no name in Assets any more, so its totals were published under its ID instead of a name. The totals themselves are unchanged.\\n\\n**Recover.** Name the level in Assets, then re-run the period to publish its name.\\n\\n### `CALC_RUN_INPUT_TOO_LARGE`\\n\\n**Means.** This run\u2019s input is larger than a run can store, so it was stopped and nothing was published; the period\u2019s earlier results are unchanged. The message gives the size and the limit, and says what made the input large. A run over assets: the selected assets and the reference tables, checked before anything is computed (the rows of each asset are stored batch by batch and are not counted). A table-driven run: it may keep up to 2,000,000 rows from its connected Data table (those in its period and asset selection where the connection filters by them, every row where it filters by neither) and up to 28,000,000 values (those rows \xD7 the columns each carries), both counted as the table is read, so a run that keeps more is refused there, before the rest is read; the table is stored in parts, up to 640 MiB across them, checked while the table is read so a table past it is refused before the rest is read, and a single row too large to store as one part on its own is refused as the parts are written; its reference tables are checked before anything is computed. One batch of a run over assets: that batch\u2019s rows, checked when the batch is computed, so the run stopped at that batch. (API: the run-wide engine input plus the asset selection snapshot is over `RUN_INPUT_STORE_MAX_BYTES`, or a Data table is over `RUN_INPUT_TABLE_MAX_BYTES`, named as the `estimate` or `exact` layer; or a Data table delivered more rows than `DATA_TABLE_SUPPORTED_ROWS`, or more rows \xD7 delivered columns than `DATA_TABLE_SUPPORTED_VALUES`, after its `timeColumn` and `assetColumn` filters, named by that limit; or one `run_input_chunk` is over the chunk limit, named as the `chunk` layer for a batch of a run over assets and as the `exact` layer\'s `run_input_chunk` for one part of a Data table.)\\n\\n**Recover.** A run over assets: narrow the project\u2019s asset selection, or reduce the reference tables. A table-driven run whose Data table stores too much: keep fewer of its rows or columns \u2014 where the connection filters the table by period or asset, a run that keeps fewer rows stores less; drop the columns your formulas do not read from the table \u2014 or split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs; one row too large to store on its own: connect a table whose rows carry smaller values, or drop the columns your formulas do not read. A run that keeps more rows or values from its Data table than a run supports: where the connection filters the table by period or asset, a run that keeps fewer rows is not refused; fewer columns allow more rows, so drop the columns your formulas do not read from the table (any columns the platform adds to every row stay; the message counts them); otherwise split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs. One batch too large: split the calculation into calculations with fewer connected inputs, or connect inputs with smaller values. Then re-run the period; re-running unchanged is refused the same way. (API: trigger it with a new `idempotencyKey` once the asset selection, tables or bindings change.)\\n\\n### `CALC_DATA_TABLE_ROWS_PAST_SUPPORTED`\\n\\n**Means.** A connected Data table holds more rows in total than a run supports (2,000,000), or more values (its rows \xD7 the columns each carries) than the 28,000,000 a run supports. A run that keeps more than either will be refused as too large (CALC_RUN_INPUT_TOO_LARGE). A run keeps the rows in its period and asset selection where the connection filters by them; where it filters by neither, a run keeps every row, so every run of a table this large is refused. The warning names the sheet, the dataset and its row count, and says which applies. (API: the bound version\'s `rowCount` is past `DATA_TABLE_SUPPORTED_ROWS`, or its `rowCount` \xD7 its delivered columns past `DATA_TABLE_SUPPORTED_VALUES`.)\\n\\n**Recover.** Where the connection filters by period or asset, a run that keeps fewer rows is not refused. Fewer columns allow more rows: drop the columns your formulas do not read from the table (any columns the platform adds to every row stay; the message counts them). Otherwise split the table (a calculation reads one Data table, so connect each part to its own project), or connect the readings as Observation inputs.\\n\\n**Next.** open-bindings\\n\\n### `CALC_DATA_TABLE_CHANGED_DURING_READ`\\n\\n**Means.** The Data table connected to this calculation kept changing while the run read it: the run read a different number of rows than the table held when it started, several times in a row, as happens while new data is still being loaded into it. Rather than file a figure that might count a row twice, the run was stopped: it is FAILED and nothing was published; the period\u2019s earlier results are unchanged. (API: one task\u2019s reads in a row of a Data table returned a row count other than the one their open counted; a single such read is retried, and the run is refused at the limit on that task.)\\n\\n**Recover.** Re-run the period once the table has finished loading. If it keeps happening, check what is still writing to the table. (API: trigger it with a new `idempotencyKey`.)\\n\\n### `CALC_ADDED_UNIT_MISMATCH`\\n\\n**Means.** A formula adds or subtracts two values whose units differ, for example a result in t and one in kg, or a reading in mcf and a constant in m\xB3. The calculation adds the numbers as plain numbers, with no conversion, so the result is wrong unless the two are the same unit written two ways. Units are compared as typed: t and tonne are different units here. Only formulas, constants and connected readings with a unit are compared; a value whose unit is known only when a run reads it is not. A warning: it never holds Next or Publish.\\n\\n**Recover.** Convert one value in the formula so both are in the same unit (for example [@Recovered] / 1000 to turn kg into t), or correct a Unit that was typed wrong. If the two really are the same unit written two ways, write them the same way.\\n\\n### `CALC_OBSERVATION_COARSER_THAN_PERIOD`\\n\\n**Means.** Rows of an observation input cover a span longer than the calculation period (annual data in a monthly calculation, for example), so none of them fits inside the period. The input is set to leave such rows out, so the run did not use them, and an asset with no other reading for the period read 0. The run completes. The number affected counts the rows, and the diagnostic names a few (asset @ period).\\n\\n**Recover.** Choose how the input handles longer data: Spread by days shares each value across the periods it covers in proportion to their days (for amounts that add up), and Value in effect uses the whole value in every period it covers (for rates and factors). If the rows belong to another calculation, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_CROSSES_PERIOD`\\n\\n**Means.** Rows of an observation input cover a span that crosses the edge of the calculation period (a calendar month in a weekly calculation, or calendar-year data in a fiscal year), so they fit inside no period. The input is set to leave such rows out, so the run did not use them. The run completes. The number affected counts the rows, and the diagnostic names a few (asset @ period).\\n\\n**Recover.** Choose Spread by days on the input to share each such row between the periods it touches in proportion to their days, or Value in effect to use its whole value. Otherwise report the data on the calculation\u2019s own period boundaries.\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_MIXED_FREQUENCY`\\n\\n**Means.** The rows an observation input read for this period mix spans (some daily and some monthly, for example), so the dataset does not report at one frequency. Each row is still handled by the input\u2019s choices: rows inside the period are combined as chosen, and longer rows as chosen for those. The run completes; the warning makes the mix visible, since mixed data often means a value is counted twice.\\n\\n**Recover.** Check the dataset for overlapping rows, such as a monthly total beside the daily readings it was made from. If the mix is intended, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_VALUE_CHANGED_IN_PERIOD`\\n\\n**Means.** A value this calculation reads changed part-way through the period: an asset property, a constant or a lookup factor. The input is set to use the value at the period end, so the run used that value for the whole period, including the days before the change. The run completes. The diagnostic names the input and counts what changed: the assets whose property changed, or the rows of the reference table whose validity starts or ends inside the period.\\n\\n**Recover.** If the period should be calculated in parts at the change, set the input to Split the period at the change. If the period-end value is right for the whole period, nothing needs fixing.\\n\\n**Next.** open-bindings\\n\\n### `CALC_PERIOD_SPLIT`\\n\\n**Means.** A value this calculation reads changed part-way through the period, and the input is set to split the period at the change. The run calculated each part with the value in force during it and its own share of the activity data (readings inside a part go to it, and a reading spanning the change is shared by days), then combined the parts by what each result is calculated from: a result from readings is added up across the parts, a result only from values in force (a property such as a device count or capacity, a constant, a factor) is averaged over the days, so 10 devices then 12 is about 11, not 22, and a ratio is recomputed from its combined parts. The diagnostic names the parts.\\n\\n**Recover.** Nothing needs fixing. A result combined by a day-weighted average is an estimate. The diagnostic names each part and its days.\\n\\n### `CALC_PERIOD_SPLIT_UNSUPPORTED`\\n\\n**Means.** An input is set to split the period when its value changes, but this calculation cannot be calculated in parts: it reads a whole Data table (rows the run cannot share between parts), breaks results down by emission category, a row of a Data table with a time column crosses the change, the value changes too many times inside the period to calculate it in parts, or a result cannot be put back together from its parts (it is calculated from readings but is neither added up nor a ratio of totals, or it reads data used whole in every period it overlaps). The run stopped rather than use one value for the whole period.\\n\\n**Recover.** Set the input to stop the run or use the value at the period end, or report the data on the change\u2019s boundaries. A Data table needs a time column before its period can be split.\\n\\n**Next.** open-bindings\\n\\n### `CALC_ASSET_PROPERTY_CHANGES_IN_PERIOD`\\n\\n**Means.** An asset property this calculation reads changed part-way through the period on at least one asset, and the input is set to stop the run when its value changes, so no single value covers the period. The run stopped rather than pick one. The diagnostic counts the assets and names a few, with the value at the period start and at its end.\\n\\n**Recover.** Choose what the input does when the value changes: use the value at the period end, or split the period at the change. Or, if the change was entered on the wrong date, correct it on the asset. Then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_PERIOD_FIT_INVALID`\\n\\n**Means.** An input\u2019s choices for data reported at a different frequency than the calculation runs cannot be honoured together, so the save was refused. Spread by days works only with Added up; a Data table cannot spread its rows, and needs a time column before it has rows longer than the period; a period cannot be split at a change while a Data table with no time column is connected; and inputs filling one sheet must choose the same thing to do when a value changes inside the period.\\n\\n**Recover.** Change the named input\u2019s choice as the message says, then save again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_INPUT_ASSET_TYPES_MATCH_NONE`\\n\\n**Means.** An input of the calculation lists the asset types that need it, and no selected asset is of any of those types. The list still applies, so no selected asset whose type was read was checked for the input: right for an asset selection with none of those types, and a sign of a stale list otherwise (a type renamed or replaced in Assets).\\n\\n**Recover.** Check the asset types the input applies to on the calculation. If an asset type was renamed or replaced in Assets, pick the new one and publish again.\\n\\n### `CALC_INPUT_ASSET_TYPE_GONE`\\n\\n**Means.** An input of the calculation lists an asset type that is no longer in Assets. The list still applies as written: an asset that was of the removed type at the period end is checked against it, as when the type existed.\\n\\n**Recover.** Remove the asset type from the input on the calculation, or pick the type that replaced it, and publish again.\\n\\n### `CALC_UNKNOWN_PROPERTY_KEY`\\n\\n**Means.** An input reads an asset property that no asset template defines. The project was saved when the property existed; it has since been renamed or removed, so the run stopped before calculating rather than reading nothing.\\n\\n**Recover.** Open the input\u2019s connection and pick a property that exists today, then run the period again. (API: the binding\u2019s `propertyKey`)\\n\\n### `CALC_PROPERTY_TYPE_UNBINDABLE`\\n\\n**Means.** An input reads an asset property whose type a calculation cannot read as a number. Only number and measurement properties can feed a formula; the property\u2019s type was changed after the project was saved, so the run stopped before calculating.\\n\\n**Recover.** Open the input\u2019s connection and pick a number or measurement property, or change the property back to one of those types, then run the period again. (API: the binding\u2019s `propertyKey`)\\n\\n### `CALC_ASSET_PROPERTY_MISSING`\\n\\n**Means.** A bound asset property has no value on at least one selected asset, neither at the end of the period nor today. A missing property is a data fault, never read as 0, so the run stopped before calculating.\\n\\n**Recover.** Connect the input to a property every selected asset carries, or give the assets that lack it a value in Assets. You can also narrow the project\u2019s asset selection to assets that carry it. Then run the period again.\\n\\n### `CALC_DATA_TABLE_KEY_COLUMN_UNCOMPUTED`\\n\\n**Means.** The Data table connection names a key column (the asset column or the identity column) that the pinned calculation\u2019s calculator does not compute. Results are keyed by that column, so every delivered row would key to nothing and the run would complete with nothing filed. The run stopped before calculating instead.\\n\\n**Recover.** Point the connection at a column the calculator computes (the refusal lists them), or pin a calculation whose calculator computes the named column. (API: the `dataTable` binding\u2019s `assetColumn` or `identityColumn`)\\n\\n**Next.** open-bindings\\n\\n### `CALC_OBSERVATION_COLUMN_MISSING`\\n\\n**Means.** An observation source the run reads lacks a column the connection needs. The version the run read carries different columns than the one the project was saved against, so the run stopped before calculating.\\n\\n**Recover.** Connect a dataset version that carries the column, or change the connection to a column that version has, then run the period again.\\n\\n**Next.** open-bindings\\n\\n### `CALC_CROSS_ROW_CHECK_FAULT`\\n\\n**Means.** The run was refused before any batch filed because the check for formulas that read other assets\u2019 rows could not finish on this calculation, so its results could not be trusted to be complete.\\n\\n**Recover.** Run the period again. If it keeps failing, report it with the run\u2019s id and the calculation version.\\n\\n### `RUN_BATCH_DUPLICATE_CELL`\\n\\n**Means.** One batch of assets produced two results with the same key, which a correct calculation never does, so the run stopped and filed nothing.\\n\\n**Recover.** Check the calculation for outputs that repeat a key within one asset, then run the period again. The batch number is in the run\u2019s message.\\n\\n### `RUN_BATCH_LEDGER_INCOMPLETE`\\n\\n**Means.** The run finished its batches, but the batch record does not confirm that every batch was filed, so it was sealed as failed rather than filing a partial result.\\n\\n**Recover.** Run the period again. The batches the record could not confirm are named in the run\u2019s message.\\n\\n### `RUN_INERT_BINDING_REFUSED`\\n\\n**Means.** The connected data table reached none of the selected assets, yet the calculation produced figures, so those figures came from the sample rows the calculation ships with and not from your data. Nothing was filed.\\n\\n**Recover.** Check that the data table\u2019s asset column holds ids or names that match the selected assets, then run the period again.\\n\\n### `RUN_RESULT_OUTSIDE_SCOPE`\\n\\n**Means.** The calculation produced results keyed to assets that are not in this run\u2019s asset selection, so they were not filed.\\n\\n**Recover.** Check the asset column of the calculation\u2019s own table: it should be generated from the connected data rather than typed in. Then run the period again.\\n\\n### `RUN_REAPED`\\n\\n**Means.** The run could not finish within its attempts: the worker running it stopped, its input could not be read in time on some of its attempts (the run\u2019s message says on how many), or its last attempt made no progress for the stall threshold and was handed on. It was sealed as failed. Nothing was filed.\\n\\n**Recover.** Run the period again. If its input could not be read in time, or it made no progress, the system was likely busy; a quieter time usually works. If it keeps failing, the asset selection may be too large to finish in one attempt; report it with the run\u2019s id.\\n\\n### `SEAL_ROLLBACK`\\n\\n**Means.** The run\u2019s results could not be filed, or the run was too large to file. Nothing was published, and the period\u2019s earlier results are unchanged. Results its batches had already stored stay on the failed run; the message says when there are any. The message names the cause: two results with the same key, or an asset selection too large to file (more results than one run can file, or more than filing can finish within its time budget). A per-asset run that is already too large is stopped before it calculates. (API: `context.cause` is `duplicate-result-cell` or `transaction-budget`. `transaction-budget` names both size causes. The cell ceiling `CALC_RUN_SEAL_MAX_CELLS` is judged before the filing opens, or before the run reads anything for a per-asset run, so it runs no transaction.)\\n\\n**Recover.** For a duplicate key, fix the calculation or its data so no two results share a key. For an asset selection too large to file, narrow the project\u2019s asset selection, or split the calculation into calculations that produce fewer results, and run the period again.\\n\\n### `UNCLASSIFIED`\\n\\n**Means.** The run failed for a reason this version does not classify. The run\u2019s message holds the full account.\\n\\n**Recover.** Read the run\u2019s message and correct what it names, then run the period again. Nothing was filed.\\n\\n### `CALC_RUN_ENGINE_CHANGED_MID_RUN`\\n\\n**Means.** This run had already computed part of its work on one engine when the app was upgraded to another. A run is computed on one engine only, so it stopped before computing anything on the new one and filed nothing from it. (A run that had computed nothing yet simply runs on the new engine.) The period\u2019s earlier results and any sign-off are unchanged. (API: the run\u2019s `engineVersion` is not the engine the app now runs.)\\n\\n**Recover.** Re-run the period: the new run is computed on the app\u2019s current engine and records it. (API: trigger it with a new `idempotencyKey`.)\\n"}},{"uri":"calc://example/simple-total","name":"Example declaration: simple-total","description":"The smallest useful shape: one data sheet, one calculator. Row generation with UNIQUE, a SUMIFS pull-down keyed on the generated row, and an arithmetic product across two columns of the same row. Fully synthetic example data \u2014 not a methodology.","mimeType":"application/json","source":{"kind":"generated","text":"{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Observations\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"elementId\\",\\n \\"value\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"elementId\\": \\"VARCHAR\\",\\n \\"value\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 120\\n },\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"elementId\\": \\"EMISSION_FACTOR\\",\\n \\"value\\": 2.5\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 80\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"elementId\\": \\"EMISSION_FACTOR\\",\\n \\"value\\": 2.5\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"FUEL_VOLUME\\",\\n \\"EMISSION_FACTOR\\",\\n \\"EMISSIONS_T\\"\\n ],\\n \\"rowGenerators\\": [\\n \\"siteId\\"\\n ],\\n \\"rows\\": [],\\n \\"columnFormulas\\": {\\n \\"siteId\\": \\"UNIQUE(Observations[siteId])\\",\\n \\"FUEL_VOLUME\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"FUEL_VOLUME\\\\\\",Observations[siteId],$A3)\\",\\n \\"EMISSION_FACTOR\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"EMISSION_FACTOR\\\\\\",Observations[siteId],$A3)\\",\\n \\"EMISSIONS_T\\": \\"Calculator[[#This Row],[FUEL_VOLUME]] * Calculator[[#This Row],[EMISSION_FACTOR]]\\"\\n },\\n \\"formulaSourceRow\\": 3,\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"FUEL_VOLUME\\": \\"DOUBLE\\",\\n \\"EMISSION_FACTOR\\": \\"DOUBLE\\",\\n \\"EMISSIONS_T\\": \\"DOUBLE\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"orderBy\\": [\\n \\"siteId\\"\\n ]\\n }\\n}\\n"}},{"uri":"calc://example/lookup-factor","name":"Example declaration: lookup-factor","description":"Adds a lookup sheet: XLOOKUP against a factor table keyed on a value the calculator itself derived, with IFERROR around the product so a missing factor yields a value rather than an error. Fully synthetic example data \u2014 not a methodology.","mimeType":"application/json","source":{"kind":"generated","text":"{\\n \\"version\\": \\"1.0\\",\\n \\"sheets\\": [\\n {\\n \\"name\\": \\"Observations\\",\\n \\"role\\": \\"data\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"fuelType\\",\\n \\"elementId\\",\\n \\"value\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"fuelType\\": \\"VARCHAR\\",\\n \\"elementId\\": \\"VARCHAR\\",\\n \\"value\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"siteId\\": \\"SITE-1\\",\\n \\"fuelType\\": \\"DIESEL\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 120\\n },\\n {\\n \\"siteId\\": \\"SITE-2\\",\\n \\"fuelType\\": \\"GAS\\",\\n \\"elementId\\": \\"FUEL_VOLUME\\",\\n \\"value\\": 80\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Factors\\",\\n \\"role\\": \\"lookup\\",\\n \\"columns\\": [\\n \\"fuelType\\",\\n \\"factor\\"\\n ],\\n \\"columnTypeHints\\": {\\n \\"fuelType\\": \\"VARCHAR\\",\\n \\"factor\\": \\"DOUBLE\\"\\n },\\n \\"rows\\": [\\n {\\n \\"fuelType\\": \\"DIESEL\\",\\n \\"factor\\": 2.68\\n },\\n {\\n \\"fuelType\\": \\"GAS\\",\\n \\"factor\\": 1.88\\n }\\n ]\\n },\\n {\\n \\"name\\": \\"Calculator\\",\\n \\"role\\": \\"calculator\\",\\n \\"columns\\": [\\n \\"siteId\\",\\n \\"FUEL_TYPE\\",\\n \\"FUEL_VOLUME\\",\\n \\"FACTOR\\",\\n \\"EMISSIONS_T\\"\\n ],\\n \\"rowGenerators\\": [\\n \\"siteId\\"\\n ],\\n \\"rows\\": [],\\n \\"columnFormulas\\": {\\n \\"siteId\\": \\"UNIQUE(Observations[siteId])\\",\\n \\"FUEL_TYPE\\": \\"XLOOKUP($A3,Observations[siteId],Observations[fuelType])\\",\\n \\"FUEL_VOLUME\\": \\"SUMIFS(Observations[value],Observations[elementId],\\\\\\"FUEL_VOLUME\\\\\\",Observations[siteId],$A3)\\",\\n \\"FACTOR\\": \\"XLOOKUP(Calculator[[#This Row],[FUEL_TYPE]],Factors[fuelType],Factors[factor])\\",\\n \\"EMISSIONS_T\\": \\"IFERROR(Calculator[[#This Row],[FUEL_VOLUME]] * Calculator[[#This Row],[FACTOR]], 0)\\"\\n },\\n \\"formulaSourceRow\\": 3,\\n \\"columnTypeHints\\": {\\n \\"siteId\\": \\"VARCHAR\\",\\n \\"FUEL_TYPE\\": \\"VARCHAR\\",\\n \\"FUEL_VOLUME\\": \\"DOUBLE\\",\\n \\"FACTOR\\": \\"DOUBLE\\",\\n \\"EMISSIONS_T\\": \\"DOUBLE\\"\\n }\\n }\\n ],\\n \\"execution\\": {\\n \\"orderBy\\": [\\n \\"siteId\\"\\n ]\\n }\\n}\\n"}}],"prompts":[{"name":"author-declaration","description":"Author a calculation methodology end to end: preview, validate, create, attach to a project, activate, run. Reads the format, function and diagnostics resources as it goes.","arguments":[{"name":"methodology","description":"What to build, in the words of whoever asked for it \u2014 a standard, a spreadsheet description, or the calculation in prose.","required":true},{"name":"projectName","description":"An existing project to attach the declaration to, if one was named.","required":false}],"template":"Author a calculation methodology in Studio for the following request.\\n\\nREQUEST\\n{{methodology}}\\n\\nTARGET PROJECT (may be empty \u2014 create one if so, or ask which to use)\\n{{projectName}}\\n\\nRead these before writing any formula. They are served as resources on this server;\\nif your client does not support resources, `calculations_describe` returns the same\\ntext.\\n\\n- `calc://declaration-format` \u2014 the artifact format, field by field.\\n- `calc://functions` \u2014 the functions the engine accepts, and the rewrite for each one\\n it does not. Checking here first is cheaper than a failed validate.\\n- `calc://example/simple-total` \u2014 the smallest complete declaration.\\n- `calc://example/lookup-factor` \u2014 the same, with a lookup table.\\n- `calc://diagnostics` \u2014 what a validation code means and how to recover. Read the\\n entry for a code you hit rather than guessing at the message.\\n\\nORDER OF OPERATIONS. Do not skip ahead: each step is cheap and the next one is not.\\n\\n1. PREVIEW \u2014 `calculations_declarations_preview`. Evaluates the declaration without\\n writing anything, so iterating costs no rows. Stay here until the shape is right.\\n2. VALIDATE \u2014 `calculations_declarations_validate`. Reports diagnostics against the\\n full engine, including the cross-reference errors a preview cannot see. Resolve\\n every `error`; read `calc://diagnostics` for any code you do not recognise.\\n3. CREATE \u2014 `calculations_declarations_create`. Writes the declaration.\\n4. PROJECT \u2014 attach it to a project, creating one first if none was named.\\n5. ACTIVATE \u2014 `calculations_activateProject`. A project must be active before it runs.\\n A refusal here needs a person with tenant-admin authority to activate the project;\\n an unattended agent cannot do it, whatever its role.\\n6. RUN \u2014 `calculations_run`, then read the result.\\n\\nIDEMPOTENCY KEYS \u2014 the rule, stated once, because getting it wrong is silent.\\n\\nEvery keyed write takes an `idempotencyKey` and there is no minting helper, on\\npurpose: a key minted by the shell would regenerate on retry, which destroys the\\nreplay protection the key exists for. Only you know you are retrying. So mint a fresh\\nUUID per logical operation, and reuse a key ONLY to retry that same call after a\\nfailure you did not get an answer to. A key reused against a different target is\\nrefused rather than answered. Individual tools state their own additional semantics in\\ntheir descriptions \u2014 several differ deliberately, so read the one you are calling.\\n\\nReport back with the declaration you created, the diagnostics you resolved along the\\nway, and the run result. If you could not reach a clean validate, say which diagnostic\\nblocked you rather than creating anyway."}]},"verbs":[{"name":"run"},{"name":"startRun"},{"name":"startPublishedRun"},{"name":"postRun"},{"name":"promoteResults"},{"name":"rebuildResultsWindow"},{"name":"publishNodeResults"},{"name":"createProject"},{"name":"cloneProject"},{"name":"reviseProject"},{"name":"activateProject"},{"name":"archiveProject"},{"name":"createDeclarationVersion"},{"name":"archiveDeclaration"},{"name":"unarchiveDeclaration"},{"name":"moveDeclarations"},{"name":"createNamespace"},{"name":"updateNamespace"},{"name":"deleteNamespace"},{"name":"generatePeriods"},{"name":"closePeriod"},{"name":"reopenPeriod"},{"name":"assertPeriodSignable"},{"name":"rerunReopenedParents"},{"name":"recordReviewDecision"},{"name":"recordVarianceDecision"},{"name":"captureParityBaseline"},{"name":"cancelRun"},{"name":"createProjectRelationship"},{"name":"endProjectRelationship"},{"name":"rewireProjectRelationship"},{"name":"createProjectRelationshipKind"},{"name":"exportResults"}]}')),codelistsManifest=deepFreeze(JSON.parse('{"name":"codelists","plane":"platform","routerKey":"codelists","verbs":[{"name":"create"},{"name":"update"},{"name":"retire"}]}')),compositionsManifest=deepFreeze(JSON.parse('{"name":"compositions","plane":"resource","routerKey":"compositions","verbs":[{"name":"create"},{"name":"publish"},{"name":"saveManifest"},{"name":"unpublish"},{"name":"update"},{"name":"delete"},{"name":"saveDefinitionVersion"},{"name":"saveAutomation"},{"name":"saveAutomationGroup"},{"name":"saveTriggerBindingVersion"},{"name":"retireDefinition"},{"name":"retireTriggerBinding"},{"name":"saveApprovalUse"},{"name":"markAutomationDue"},{"name":"setTriggerBindingOwner"}]}')),datasetsManifest=deepFreeze(JSON.parse('{"name":"datasets","plane":"resource","routerKey":"datasets","verbs":[{"name":"promote"},{"name":"land"},{"name":"declareReplica"},{"name":"observeReplicaDataset"},{"name":"retireReplica"},{"name":"registerSourceArtifact"},{"name":"createSourceTransformation"},{"name":"runTransformation"},{"name":"saveLiveDefinition"},{"name":"saveTransformSpec"},{"name":"saveValidationRuleset"},{"name":"changeStatus"},{"name":"changeMaturity"},{"name":"rename"},{"name":"describe"},{"name":"setColumnEntities"},{"name":"describeColumns"},{"name":"proposeDescription"},{"name":"decideDescriptionProposal"},{"name":"flagRecords"},{"name":"commentRecords"},{"name":"dismissFinding"},{"name":"requestCorrection"},{"name":"withdrawReviewAct"},{"name":"markDeliveryReviewed"},{"name":"correctRecords"},{"name":"correctCells"},{"name":"applyCorrections"},{"name":"saveCorrectionSettings"},{"name":"setReviewEnabled"},{"name":"setHoistedColumns"},{"name":"retryReviewCarry"},{"name":"retryCorrectedCopy"},{"name":"decideRuleResult"},{"name":"saveReviewSettings"},{"name":"setKeyColumn"},{"name":"setCatalogDetails"},{"name":"setKeyFields"},{"name":"export"},{"name":"runQualityCheck"},{"name":"startImportJob"},{"name":"startQualityRun"},{"name":"resolvePromotedVersions"},{"name":"resolveLatestVersions"},{"name":"checkInputsChanged"},{"name":"markInputsProcessed"},{"name":"startQualityChecks"},{"name":"promoteIfReady"},{"name":"reapplyCorrections"},{"name":"requestReland"},{"name":"observeReplicaDelivery"},{"name":"observeVersionLanded"},{"name":"runQualityChecks"},{"name":"seedCorrectedCopyFault"},{"name":"relandCurrentLoad"},{"name":"observeReferenceVersion"},{"name":"markReferenceValues"},{"name":"saveReferenceVersion"},{"name":"createReferenceTable"},{"name":"setReferenceSource"},{"name":"setReferenceKeyCodelists"},{"name":"assertReferenceVersionSignable"},{"name":"activateReferenceVersion"}]}')),eventsManifest=deepFreeze(JSON.parse('{"name":"events","plane":"resource","routerKey":"events","verbs":[{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"categoryRetire"},{"name":"typeCreate"},{"name":"typeUpdate"},{"name":"typeRetire"},{"name":"templateCreate"},{"name":"templateUpdate"},{"name":"templateRetire"},{"name":"statusCreate"},{"name":"statusUpdate"},{"name":"statusRetire"},{"name":"severityCreate"},{"name":"severityUpdate"},{"name":"severityRetire"},{"name":"numberingConfigSet"},{"name":"create"},{"name":"update"},{"name":"transition"},{"name":"accept"},{"name":"dismiss"},{"name":"reopen"},{"name":"linkDraw"},{"name":"linkEnd"},{"name":"merge"},{"name":"citeReadings"},{"name":"citationRemove"},{"name":"propose"},{"name":"commentAdd"}]}')),insightsManifest=deepFreeze(JSON.parse('{"name":"insights","plane":"resource","routerKey":"insights","verbs":[{"name":"metricCreate"},{"name":"metricRevise"},{"name":"metricDescribe"},{"name":"metricPublish"},{"name":"metricRetire"},{"name":"thresholdRuleCreate"},{"name":"thresholdRuleRevise"},{"name":"thresholdRuleDelete"},{"name":"createSavedView"},{"name":"updateSavedView"},{"name":"deleteSavedView"},{"name":"ruleBreach"},{"name":"ruleRecovery"},{"name":"ruleMissingData"}]}')),integrationsManifest=deepFreeze(JSON.parse('{"name":"integrations","plane":"resource","routerKey":"integrations","verbs":[{"name":"beginCapture"},{"name":"completeCapture"},{"name":"registerSource"},{"name":"createConnection"},{"name":"configureConnection"},{"name":"retireConnection"},{"name":"setSnowflakeKey"}]}')),mediaManifest=deepFreeze(JSON.parse('{"name":"media","plane":"resource","routerKey":"media","verbs":[{"name":"requestUpload"},{"name":"confirmUpload"},{"name":"block"},{"name":"unblock"},{"name":"attach"},{"name":"detach"},{"name":"setCaption"},{"name":"hide"},{"name":"unhide"},{"name":"createWebLink"},{"name":"requestUploads"},{"name":"confirmUploads"}]}')),notificationsManifest=deepFreeze(JSON.parse('{"name":"notifications","plane":"resource","routerKey":"notifications","verbs":[{"name":"send"},{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"definitionCreate"},{"name":"definitionUpdate"},{"name":"versionCreate"},{"name":"templateCreate"},{"name":"contactPointCreate"},{"name":"contactPointConsent"},{"name":"contactPointVerify"},{"name":"preferenceSet"},{"name":"feedMarkRead"}]}')),obligationsManifest=deepFreeze(JSON.parse('{"name":"obligations","plane":"resource","routerKey":"obligations","verbs":[{"name":"frameworkCreate"},{"name":"frameworkVersionCreate"},{"name":"frameworkVersionSetSuggestedPlans"},{"name":"frameworkVersionSetContentBasis"},{"name":"requirementCreate"},{"name":"requirementUpdate"},{"name":"frameworkPublish"},{"name":"frameworkImport"},{"name":"frameworkDraftFromDocument"},{"name":"programCreate"},{"name":"programUpdate"},{"name":"programArchive"},{"name":"programPinVersion"},{"name":"changeReviewDecide"},{"name":"enrollmentCreate"},{"name":"enrollmentRemove"},{"name":"enrollmentReplace"},{"name":"enrollmentSetZoneOverride"},{"name":"planCreate"},{"name":"planRevise"},{"name":"planEnable"},{"name":"planDisable"},{"name":"planCloneFromLibrary"},{"name":"determinationOverride"},{"name":"determinationRevokeOverride"},{"name":"planApply"},{"name":"applicationCancel"},{"name":"applicationRegenerate"},{"name":"applicationConfirmScope"},{"name":"applicationRecordEvent"},{"name":"obligationCreate"},{"name":"obligationUpdate"},{"name":"obligationSatisfy"},{"name":"obligationSatisfyFromWork"},{"name":"obligationCancel"},{"name":"obligationExempt"},{"name":"obligationMarkNotApplicable"},{"name":"obligationExtend"},{"name":"satisfactionAccept"},{"name":"satisfactionReject"},{"name":"creditOverride"},{"name":"deviationValidate"},{"name":"deviationVoid"},{"name":"deviationUpdate"},{"name":"deviationReport"},{"name":"deviationClose"},{"name":"deviationDraft"},{"name":"deviationRecord"},{"name":"deviationMarkUnderReview"},{"name":"workLinkKindSet"},{"name":"obligationBecameOverdue"},{"name":"obligationNonconformity"},{"name":"obligationDueSoon"},{"name":"determinationChanged"},{"name":"obligationMaterialized"},{"name":"obligationRedated"},{"name":"obligationAnchorCorrected"},{"name":"occurrenceDeferred"}]}')),observationsManifest=deepFreeze(JSON.parse('{"name":"observations","plane":"resource","routerKey":"observations","verbs":[{"name":"declare"},{"name":"rederive"},{"name":"retire"},{"name":"trippedReadings"},{"name":"createReference"},{"name":"confirmReference"},{"name":"endReference"},{"name":"derivationSealed"}]}')),reportsManifest=deepFreeze(JSON.parse('{"name":"reports","plane":"resource","routerKey":"reports","verbs":[{"name":"templateCreate"},{"name":"templateCustomize"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"},{"name":"generate"},{"name":"override"},{"name":"lock"},{"name":"promote"}]}')),scenariosManifest=deepFreeze(JSON.parse('{"name":"scenarios","plane":"resource","routerKey":"scenarios","verbs":[{"name":"create"},{"name":"update"},{"name":"commit"},{"name":"derive"},{"name":"duplicate"},{"name":"import"},{"name":"archive"},{"name":"unarchive"},{"name":"forecastsCreate"},{"name":"forecastsUpdate"},{"name":"forecastsDelete"},{"name":"fleetEventsCreate"},{"name":"fleetEventsUpdate"},{"name":"fleetEventsDelete"},{"name":"namedProceduresCreate"},{"name":"namedProceduresUpdate"},{"name":"namedProceduresDelete"},{"name":"namedProceduresApply"},{"name":"variablesCreate"},{"name":"variablesUpdate"},{"name":"variablesDelete"},{"name":"qualifiersCreate"},{"name":"qualifiersUpdate"},{"name":"qualifiersDelete"},{"name":"adjustmentsCreate"},{"name":"adjustmentsUpdate"},{"name":"adjustmentsDelete"},{"name":"initiativesCreate"},{"name":"initiativesUpdate"},{"name":"initiativesDelete"},{"name":"targetsCreate"},{"name":"targetsUpdate"},{"name":"targetsDelete"},{"name":"targetsTransition"},{"name":"runsStart"},{"name":"runsCancel"},{"name":"runsPublish"},{"name":"publishInitiatives"}]}')),workManifest=deepFreeze(JSON.parse('{"name":"work","plane":"resource","routerKey":"work","verbs":[{"name":"categoryCreate"},{"name":"categoryUpdate"},{"name":"categoryDelete"},{"name":"typeCreate"},{"name":"typeUpdate"},{"name":"typeDelete"},{"name":"typeVersionPublish"},{"name":"typeVersionRetire"},{"name":"templateCreate"},{"name":"templateRevise"},{"name":"templatePublish"},{"name":"templateRetire"},{"name":"statusCreate"},{"name":"statusUpdate"},{"name":"statusRetire"},{"name":"categoryStatusesReplace"},{"name":"priorityRanksReplace"},{"name":"linkKindCreate"},{"name":"linkKindUpdate"},{"name":"linkKindRetire"},{"name":"numberingConfigSet"},{"name":"statusSettingSet"},{"name":"workCreate"},{"name":"workUpdate"},{"name":"workDelete"},{"name":"workTransition"},{"name":"workAssign"},{"name":"linkCreate"},{"name":"linkEnsure"},{"name":"linkRemove"},{"name":"subjectChange"},{"name":"responseSubmit"},{"name":"draftUpdate"},{"name":"draftDiscard"},{"name":"workRefile"},{"name":"commentCreate"},{"name":"commentUpdate"},{"name":"commentDelete"},{"name":"bulkCreate"},{"name":"bulkTransition"},{"name":"bulkAssign"},{"name":"bulkDelete"},{"name":"bulkSetBatch"},{"name":"bulkJobCancel"},{"name":"batchCreate"},{"name":"batchUpdate"},{"name":"batchDelete"},{"name":"scheduleCreate"},{"name":"scheduleUpdate"},{"name":"scheduleRetire"},{"name":"scheduleRefreshSubjects"},{"name":"optionSetCreate"},{"name":"optionSetUpdate"},{"name":"optionSetRetire"},{"name":"externalIdBind"},{"name":"externalIdUnbind"},{"name":"workExport"},{"name":"tenantConfigSet"},{"name":"executeFollowUpRules"},{"name":"fireSchedules"},{"name":"bulkJob"},{"name":"bulkCreateTile"},{"name":"bulkTransitionTile"},{"name":"bulkAssignTile"},{"name":"bulkDeleteTile"},{"name":"bulkSetBatchTile"},{"name":"notificationDefaultInstall"},{"name":"workDueSoon"},{"name":"workOverdue"},{"name":"workExportCompleted"}]}'));var mediaProcedures=Object.freeze({lookup:{annotations:{readOnlyHint:!0}},imageLinks:{annotations:{readOnlyHint:!0}},downloadLink:{annotations:{readOnlyHint:!0}},recentUploads:{annotations:{readOnlyHint:!0}}});var obligationsProcedures=Object.freeze({frameworkPublish:{annotations:{destructiveHint:!0}}});var DESTRUCTIVE_WORK_VERB=/delete|retire|remove|discard|replace/i,WORK_VERB_NAMES=new Set((workManifest.verbs??[]).map(verb=>verb.name)),workProcedures=Object.freeze(Object.fromEntries(listContractProcedures(workContract).map(entry=>{let path3=entry.path.join(".");return WORK_VERB_NAMES.has(path3)?[path3,{annotations:{destructiveHint:DESTRUCTIVE_WORK_VERB.test(path3)}}]:[path3,{annotations:{readOnlyHint:!0}}]})));var compositionsDomainContract={solutions:solutionsContract,workingCopies:workingCopiesContract,automations:compositionsContract},notificationsDomainContract={...notificationsContract,...notificationSendContract},interfacePairs=Object.freeze([{manifest:assetsManifest,contract:assetsContract,procedures:assetsProcedures},{manifest:calculationsManifest,contract:calculationsContract,procedures:calculationsProcedures},{manifest:datasetsManifest,contract:datasetsContract},{manifest:reportsManifest,contract:reportsContract},{manifest:insightsManifest,contract:insightsContract},{manifest:workManifest,contract:workContract,procedures:workProcedures},{manifest:eventsManifest,contract:eventsContract},{manifest:approvalManifest,contract:approvalContract},{manifest:observationsManifest,contract:observationsContract},{manifest:integrationsManifest,contract:integrationsContract},{manifest:obligationsManifest,contract:obligationsContract,procedures:obligationsProcedures},{manifest:scenariosManifest,contract:scenariosContract},{manifest:mediaManifest,contract:mediaContract,procedures:mediaProcedures},{manifest:notificationsManifest,contract:notificationsDomainContract},{manifest:compositionsManifest,contract:compositionsDomainContract,procedures:compositionsProcedures},iamPair,{manifest:codelistsManifest,contract:codelistsContract},{manifest:bundlesManifest,contract:bundlesContract}]);var getPath=()=>{let dispatchPath=iamProcedures["tenancy.get"]?.dispatchPath;if(dispatchPath===void 0)throw new Error("provisioning wait: iam has no tenancy.get dispatch path");return dispatchPath},WAITING_COMMANDS=["tenancy.create","tenancy.retryProvisioning"],PROVISIONING_WAIT_DEFAULT_TIMEOUT_SECONDS=600,PROVISIONING_WAIT_POLL_MS=2e3,WAIT_WORDING={waitOption:"wait until the tenant has finished setting up or its setup fails (exits non-zero, naming the failed step, on a failure)",timeoutOption:`give up waiting after this many seconds (default ${String(PROVISIONING_WAIT_DEFAULT_TIMEOUT_SECONDS)}; the setup carries on without you)`,timeoutNeedsWait:"input: --wait-timeout only applies together with --wait",timeoutNotPositive:"input: --wait-timeout must be a positive number of seconds",failed:(tenantId,step,reason)=>`server: PROVISIONING_FAILED: tenant ${tenantId} stopped at step "${step}" (reason: ${reason}). Retry with tenancy.retryProvisioning.`,failedUnreported:tenantId=>`server: PROVISIONING_FAILED: tenant ${tenantId} failed, and the server named no step or reason. Retry with tenancy.retryProvisioning.`,interrupted:tenantId=>`transport: interrupted while waiting. Tenant ${tenantId} may still be being set up; read it with tenancy.get.`,timedOut:(tenantId,step,seconds)=>`transport: gave up waiting after ${String(seconds)} s. Tenant ${tenantId} is still being set up${step===void 0?"":` (at step "${step}")`}. It carries on without you; read it with tenancy.get.`},EXIT_FLUSH_FALLBACK_MS=1e3;function exitAfterFlush(code2,io={stdout:process.stdout,stderr:process.stderr,exit:c2=>process.exit(c2)}){let state={remaining:2,exited:!1},fallback=setTimeout(()=>exitOnce(),EXIT_FLUSH_FALLBACK_MS),exitOnce=()=>{state.exited||(state.exited=!0,clearTimeout(fallback),io.exit(code2))},done=()=>{state.remaining-=1,state.remaining===0&&exitOnce()};io.stdout.write("",done),io.stderr.write("",done),fallback.unref()}var defaultSetDeadline=milliseconds=>{let handle={timer:void 0};return{expired:new Promise(resolve=>{handle.timer=setTimeout(resolve,milliseconds)}),cancel:()=>clearTimeout(handle.timer)}},ContractMismatchError=class extends Error{},defaultOnInterrupt=handler=>(process.once("SIGINT",handler),process.once("SIGTERM",handler),()=>{process.off("SIGINT",handler),process.off("SIGTERM",handler)}),recordOf=value2=>typeof value2=="object"&&value2!==null?Object.fromEntries(Object.entries(value2)):void 0,asTenant=value2=>{let fields=recordOf(value2);if(fields===void 0)return;let{id,status}=fields;if(typeof id!="string"||typeof status!="string")return;let provisioning=recordOf(fields.provisioning),failure2=recordOf(provisioning?.failure);return{id,status,provisioning:provisioning===void 0?null:{state:typeof provisioning.state=="string"?provisioning.state:"",currentStep:typeof provisioning.currentStep=="string"?provisioning.currentStep:void 0,failure:typeof failure2?.step=="string"&&typeof failure2.reason=="string"?{step:failure2.step,reason:failure2.reason}:null}}};async function waitForProvisioned(invoke,tenantId,timeoutMs,options,onRead=()=>{},initial){let deadline=options.now()+timeoutMs,last=initial,readMade=!1;for(;;){if(readMade&&last!==void 0&&deadline-options.now()<=0)return{kind:"timeout",abandoned:!1,tenant:last.tenant,raw:last.raw,step:last.tenant.provisioning?.currentStep};let attempt=Promise.resolve(invoke(getPath(),{id:tenantId})),bound=options.setDeadline(Math.max(deadline-options.now(),1)),answered=await Promise.race([attempt.then(value2=>({value:value2})),bound.expired.then(()=>{})]).finally(bound.cancel);if(readMade=!0,answered===void 0){if(last===void 0)throw new ContractMismatchError(`tenancy.get gave no answer for ${tenantId} in time`);return{kind:"timeout",abandoned:!0,tenant:last.tenant,raw:last.raw,step:last.tenant.provisioning?.currentStep}}let raw=answered.value,tenant=asTenant(raw);if(tenant===void 0)throw new ContractMismatchError(`tenancy.get answered no tenant for ${tenantId}`);if(onRead(raw),last={tenant,raw},tenant.status!=="provisioning")return{kind:"settled",tenant,raw};if(tenant.provisioning?.state==="failed"){let failure2=tenant.provisioning.failure;return{kind:"failed",tenant,raw,step:failure2?.step,reason:failure2?.reason}}let remaining=deadline-options.now();if(remaining<=0)return{kind:"timeout",abandoned:!1,tenant,raw,step:tenant.provisioning?.currentStep};await options.sleep(Math.min(options.pollMs,remaining))}}function buildStudioCli(options){let write=options.stdout??(line=>process.stdout.write(`${line}
479
+ `)),writeError=options.stderr??(line=>process.stderr.write(`${line}
480
+ `)),wait={sleep:options.sleep??(ms=>new Promise(resolve=>setTimeout(resolve,ms))),now:options.now??Date.now,pollMs:options.pollMs??PROVISIONING_WAIT_POLL_MS,setDeadline:options.setDeadline??defaultSetDeadline},waiting,held,program3=buildForgeCli({...options,stdout:line=>{waiting===void 0?write(line):held=line}}),emit=value2=>write(stringifyRedacted(value2,2)),emitError=payload=>writeError(stringifyRedacted(payload)),endProcess=options.exit??(code2=>exitAfterFlush(code2)),fail2=(code2,payload,failOptions)=>{throw emitError(payload),process.exitCode=code2,failOptions?.endProcess===!0&&endProcess(code2),new Error(payload.error)},invoke=options.invoke??((path3,input2)=>invokeProcedure(resolveProfile({flag:program3.opts().profile,env:selectedProfileFromEnv()}),path3,input2)),iam=program3.commands.find(command=>command.name()===iamManifest.routerKey);for(let name2 of WAITING_COMMANDS){let command=iam?.commands.find(candidate=>candidate.name()===name2);if(command===void 0)throw new Error(`buildStudioCli: no derived command iam ${name2} to add --wait to`);command.option("--wait",WAIT_WORDING.waitOption).option("--wait-timeout <seconds>",WAIT_WORDING.timeoutOption).hook("preAction",(_command,action)=>{let{wait:requested,waitTimeout}=action.opts();if(requested!==!0){waitTimeout!==void 0&&fail2(EXIT.INPUT,{error:WAIT_WORDING.timeoutNeedsWait});return}let seconds=waitTimeout===void 0?PROVISIONING_WAIT_DEFAULT_TIMEOUT_SECONDS:Number(waitTimeout);(!Number.isFinite(seconds)||seconds<=0)&&fail2(EXIT.INPUT,{error:WAIT_WORDING.timeoutNotPositive}),waiting={timeoutMs:seconds*1e3}}).hook("postAction",async()=>{if(waiting===void 0)return;let{timeoutMs}=waiting,answered=held===void 0?void 0:asTenant(JSON.parse(held));waiting=void 0,answered===void 0&&fail2(EXIT.CONTRACT_MISMATCH,{error:"contract mismatch: the command answered no tenant to wait for"});let lastRaw=held===void 0?null:JSON.parse(held),lastId=answered.id,interrupted=!1,unhook=(options.onInterrupt??defaultOnInterrupt)(()=>{interrupted||(interrupted=!0,emit(lastRaw),emitError({error:WAIT_WORDING.interrupted(lastId)}),process.exitCode=EXIT.TRANSPORT,endProcess(EXIT.TRANSPORT))}),outcome;try{outcome=await waitForProvisioned(invoke,answered.id,timeoutMs,wait,raw=>{lastRaw=raw,lastId=asTenant(raw)?.id??lastId},{tenant:answered,raw:lastRaw})}catch(error62){if(interrupted)return;emit(lastRaw),error62 instanceof ContractMismatchError&&fail2(EXIT.CONTRACT_MISMATCH,{error:`contract mismatch: ${error62.message}`});let{code:code2,payload}=mapErrorToExit(error62);fail2(code2,payload)}finally{unhook()}interrupted||(emit(outcome.raw),outcome.kind==="failed"&&fail2(EXIT.SERVER,{error:outcome.step===void 0||outcome.reason===void 0?WAIT_WORDING.failedUnreported(outcome.tenant.id):WAIT_WORDING.failed(outcome.tenant.id,outcome.step,outcome.reason),detail:{tenantId:outcome.tenant.id,step:outcome.step??null,reason:outcome.reason??null}}),outcome.kind==="timeout"&&fail2(EXIT.TRANSPORT,{error:WAIT_WORDING.timedOut(outcome.tenant.id,outcome.step,timeoutMs/1e3),detail:{tenantId:outcome.tenant.id,step:outcome.step}},{endProcess:outcome.abandoned}))})}return program3}var program2=buildStudioCli({pairs:interfacePairs});try{await runForgeCli(program2,process.argv,fileURLToPath2(import.meta.url))}catch(error62){process.exitCode===void 0&&(process.stderr.write(`${error62 instanceof Error?error62.message:String(error62)}
479
481
  `),process.exitCode=1)}