@sensorup/sustudio 42.24.0 → 42.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/sustudio.mjs +3 -3
package/package.json
CHANGED
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.24.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.
|
|
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.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
|
|
|
@@ -265,7 +265,7 @@ Revocation is not best-effort: a sign-out that cannot revoke has not signed out,
|
|
|
265
265
|
|
|
266
266
|
Still returns \`null\` (no body), and still declares an output so the anti-mint router walk has no blind spot.`,switchTenant:`Re-mint the session for another tenant the caller is an ACTIVE member of.
|
|
267
267
|
|
|
268
|
-
Sets the session cookie for an AMBIENT caller and answers claims and label
|
|
268
|
+
Sets the session cookie for an AMBIENT caller and answers claims and label, never a token (see \`SwitchTenantOutputSchema\`). A change of tenant needs a live renewal chain of the session's subject on every transport, and a BEARER request presents none even beside a live cookie chain, so a bearer caller is refused.
|
|
269
269
|
|
|
270
270
|
The output is the NON-nullable shape: a switch either happened or refused \u2014 "no session" is not one of its answers.`,listSessionTenants:"The caller's own active memberships as switch candidates \u2014 the read surface the shell decides the switcher affordance from. Declares NO input, deliberately (the lifecycle pair's reasoning): the answer is a function of the ambient session alone, and a parameter naming another subject is exactly what this procedure must not have.",refresh:`Renew an expiring session from the renewal material the caller holds.
|
|
271
271
|
|
|
@@ -277,7 +277,7 @@ Sets the session cookie for an AMBIENT caller and answers claims; for a cookie-f
|
|
|
277
277
|
|
|
278
278
|
The renewal material ROTATES on every redemption, and the session dies at its absolute cap regardless of how many times it renewed \u2014 the cap is anchored to the original sign-in, not to the last renewal.
|
|
279
279
|
|
|
280
|
-
The output is NULLABLE like \`currentSession\`'s and unlike \`switchTenant\`'s: a caller presenting no usable renewal material is not an error, it is signed out, and answering \`null\` is what lets a client tell "renew failed, sign in" from "something broke".`,describeAuthorizationRequest:"Read the public description of a pending authorization request. Cookie-optional: it answers the same signed in or out, and returns nothing secret.",decideAuthorizationRequest:"Record the cookie-authenticated person's approve or decline on one pending request.\n\nRefuses a request that carries an `Authorization` header, a caller with no live refresh chain, and a chain that belongs to another subject than the session's: the consenting chain is the `__Host-forge_refresh` cookie's chain. One decision per request \u2014 a second call refuses. It mints nothing.",describeDeviceRequest:"Read what the device-approval panel shows for a typed user code. Requires the signed-in browser's refresh-cookie chain and refuses an `Authorization` header; rate-limited per viewer.",decideDeviceRequest:"Record the cookie-authenticated person's approve or decline on one device request, by user code. Refuses an `Authorization` header, a caller with no live refresh chain, and a chain of another subject than the session's. One decision per request. It mints nothing."},codelists:{list:"Every declared codelist, sorted by name \u2014 answers from the manifest-derived registration set (`deriveCodelists`), never the database: a codelist with zero rows still belongs on the list. Ungoverned `tenantRead`.","terms.create":"Create one term in a codelist. Refuses `CONFLICT` on a duplicate `(codelist, code)`.","terms.update":"Relabel or redescribe an existing term. Never recodes \u2014 the input carries no `newCode`. `description: undefined` leaves the stored value unchanged; `description: null` clears it. Refuses `CODELIST_TERM_UNKNOWN` on a retired term \u2014 retiring is the only lifecycle transition beyond create/relabel, and a retired term is not a live editing target.","terms.retire":"Retire a tenant-authored term. Refuses `CODELIST_TERM_SYSTEM` on a `system` term; idempotent on an already-retired one.","terms.list":"Every term in one codelist, ordered by code. Ungoverned `tenantRead` \u2014 no Record filed."},links:{forward:"The links a subject record holds, newest first (`effective_from DESC, id DESC`), active only unless `includeEnded`. Refuses `LINK_SUBJECT_UNAVAILABLE` when the caller may not read the subject \u2014 missing and invisible alike. `take` \u2264 200 and a larger one is refused, never truncated. OFFSET paging: a link drawn or ended between two page reads can repeat or skip a row, so dedupe by `id`.",reverse:"The links pointing at an object record, newest first, active only unless `includeEnded` \u2014 only rows whose SUBJECT the caller may read (a link follows its subject's access; the object's own access rules never decide the listing). Paging runs over subjects in the domains the reader reaches, so a hidden domain's links neither fill a page nor move `nextStart`; a subject deleted within a reachable domain is still dropped per row, so a page may hold fewer than `take` rows with a non-null `nextStart` \u2014 never back-filled. OFFSET paging, as for `forward`: dedupe by `id`.","linkTypes.create":"Add a display-only type to one domain's slice. The input is STRICT: `constraints`, `enforcementClass`, `pinning` and `system` are refused here \u2014 a tenant-added type is always display-only, pinned, unconstrained and `system: false`. Refuses `LINK_TYPE_EXISTS` when the slice holds the code, `LINK_TYPE_OBJECT_UNKNOWN` when an allowed object names a module or record type no manifest declares linkable, and `BAD_REQUEST` when the slice is not a registered domain or the code lacks the reserved tenant prefix `CUSTOM_` (a tenant never takes a code a domain may ship).","linkTypes.update":"Relabel a type \u2014 `name` and `inverseName` only; a code never changes. A no-op files no Record. Refuses `LINK_TYPE_RETIRED` on a retired type (not a live editing target) and `NOT_FOUND` when the slice holds no such code.","linkTypes.retire":"Retire a tenant-added type: its links stay readable and endable, new draws refuse `LINK_TYPE_RETIRED`. Refuses `LINK_TYPE_SYSTEM` on a shipped type; idempotent on an already-retired one (the retirement instant is history and is never moved).","linkTypes.list":"Every type the tenant holds \u2014 shipped and tenant-added, retired ones included \u2014 by slice, code."},bundles:{preview:"What a bundle built from this root would hold, and whether it can be built. Writes nothing. Refuses `BUNDLE_PROFILE_UNKNOWN`, `BUNDLE_ROOT_NOT_FOUND` and `BUNDLE_ITEM_REQUIRED`.",candidates:"The roots a profile can start from, newest first, each judged from relations only. Refuses `BUNDLE_PROFILE_UNKNOWN`.",build:"Seal a bundle from this root and start building its files; answers its id. Refuses `BUNDLE_PROFILE_UNKNOWN`, `BUNDLE_ROOT_NOT_FOUND`, `BUNDLE_ITEM_REQUIRED`, `BUNDLE_INELIGIBLE` (with the reasons), `BUNDLE_FORBIDDEN` (naming what the caller may not read), `BUNDLE_REFUSED`, `BUNDLE_TOO_LARGE` and `BUNDLE_STORE_UNAVAILABLE`, each before anything is written.",list:"Bundles built in this tenant, newest first, optionally of some profiles.",get:"One bundle: its state, verdict, items and, once ready, its files. Refuses `BUNDLE_NOT_FOUND`.",download:"A short-lived link to the bundle's archive, or to one entry it published; with `view`, a link the browser shows rather than saves. Refuses `BUNDLE_NOT_FOUND`, `BUNDLE_ENTRY_NOT_FOUND`, `BUNDLE_VIEW_NEEDS_ENTRY`, `BUNDLE_NOT_READY` (still building), `BUNDLE_FAILED`, `BUNDLE_FILE_CHANGED` and `BUNDLE_STORE_UNAVAILABLE`.",profiles:"The registered profiles asked for, or every one, each with its label and description."},invitations:{resolve:`Read what an invitation link refers to, before signing in.
|
|
280
|
+
The output is NULLABLE like \`currentSession\`'s and unlike \`switchTenant\`'s: a caller presenting no usable renewal material is not an error, it is signed out, and answering \`null\` is what lets a client tell "renew failed, sign in" from "something broke".`,describeAuthorizationRequest:"Read the public description of a pending authorization request. Cookie-optional: it answers the same signed in or out, and returns nothing secret.",decideAuthorizationRequest:"Record the cookie-authenticated person's approve or decline on one pending request.\n\nRefuses a request that carries an `Authorization` header, a caller with no live refresh chain, and a chain that belongs to another subject than the session's: the consenting chain is the `__Host-forge_refresh` cookie's chain. One decision per request \u2014 a second call refuses. It mints nothing.",describeDeviceRequest:"Read what the device-approval panel shows for a typed user code. Requires the signed-in browser's refresh-cookie chain and refuses an `Authorization` header; rate-limited per viewer.",decideDeviceRequest:"Record the cookie-authenticated person's approve or decline on one device request, by user code. Refuses an `Authorization` header, a caller with no live refresh chain, and a chain of another subject than the session's. One decision per request. It mints nothing.",connectProvider:"Connect the company identity provider (SAML or OIDC) for the tenant the session is pinned to, taking its display name and settings; needs a tenant administrator, and a tenant holds at most one.",changeProvider:"Change the pinned tenant's own company identity provider, taking a new display name and settings of the same standard; needs a tenant administrator, and an OIDC client secret may be left out only when the issuer, client id and scopes are unchanged, which keeps the stored one.",removeProvider:"Remove the pinned tenant's own company identity provider and its sign-in entries, taking no identifier; needs a tenant administrator.",listProviders:"List the company identity providers in effect for the pinned tenant, its own and each ancestor's, nearest first; an inherited one shows no settings; needs a tenant administrator."},codelists:{list:"Every declared codelist, sorted by name \u2014 answers from the manifest-derived registration set (`deriveCodelists`), never the database: a codelist with zero rows still belongs on the list. Ungoverned `tenantRead`.","terms.create":"Create one term in a codelist. Refuses `CONFLICT` on a duplicate `(codelist, code)`.","terms.update":"Relabel or redescribe an existing term. Never recodes \u2014 the input carries no `newCode`. `description: undefined` leaves the stored value unchanged; `description: null` clears it. Refuses `CODELIST_TERM_UNKNOWN` on a retired term \u2014 retiring is the only lifecycle transition beyond create/relabel, and a retired term is not a live editing target.","terms.retire":"Retire a tenant-authored term. Refuses `CODELIST_TERM_SYSTEM` on a `system` term; idempotent on an already-retired one.","terms.list":"Every term in one codelist, ordered by code. Ungoverned `tenantRead` \u2014 no Record filed."},links:{forward:"The links a subject record holds, newest first (`effective_from DESC, id DESC`), active only unless `includeEnded`. Refuses `LINK_SUBJECT_UNAVAILABLE` when the caller may not read the subject \u2014 missing and invisible alike. `take` \u2264 200 and a larger one is refused, never truncated. OFFSET paging: a link drawn or ended between two page reads can repeat or skip a row, so dedupe by `id`.",reverse:"The links pointing at an object record, newest first, active only unless `includeEnded` \u2014 only rows whose SUBJECT the caller may read (a link follows its subject's access; the object's own access rules never decide the listing). Paging runs over subjects in the domains the reader reaches, so a hidden domain's links neither fill a page nor move `nextStart`; a subject deleted within a reachable domain is still dropped per row, so a page may hold fewer than `take` rows with a non-null `nextStart` \u2014 never back-filled. OFFSET paging, as for `forward`: dedupe by `id`.","linkTypes.create":"Add a display-only type to one domain's slice. The input is STRICT: `constraints`, `enforcementClass`, `pinning` and `system` are refused here \u2014 a tenant-added type is always display-only, pinned, unconstrained and `system: false`. Refuses `LINK_TYPE_EXISTS` when the slice holds the code, `LINK_TYPE_OBJECT_UNKNOWN` when an allowed object names a module or record type no manifest declares linkable, and `BAD_REQUEST` when the slice is not a registered domain or the code lacks the reserved tenant prefix `CUSTOM_` (a tenant never takes a code a domain may ship).","linkTypes.update":"Relabel a type \u2014 `name` and `inverseName` only; a code never changes. A no-op files no Record. Refuses `LINK_TYPE_RETIRED` on a retired type (not a live editing target) and `NOT_FOUND` when the slice holds no such code.","linkTypes.retire":"Retire a tenant-added type: its links stay readable and endable, new draws refuse `LINK_TYPE_RETIRED`. Refuses `LINK_TYPE_SYSTEM` on a shipped type; idempotent on an already-retired one (the retirement instant is history and is never moved).","linkTypes.list":"Every type the tenant holds \u2014 shipped and tenant-added, retired ones included \u2014 by slice, code."},bundles:{preview:"What a bundle built from this root would hold, and whether it can be built. Writes nothing. Refuses `BUNDLE_PROFILE_UNKNOWN`, `BUNDLE_ROOT_NOT_FOUND` and `BUNDLE_ITEM_REQUIRED`.",candidates:"The roots a profile can start from, newest first, each judged from relations only. Refuses `BUNDLE_PROFILE_UNKNOWN`.",build:"Seal a bundle from this root and start building its files; answers its id. Refuses `BUNDLE_PROFILE_UNKNOWN`, `BUNDLE_ROOT_NOT_FOUND`, `BUNDLE_ITEM_REQUIRED`, `BUNDLE_INELIGIBLE` (with the reasons), `BUNDLE_FORBIDDEN` (naming what the caller may not read), `BUNDLE_REFUSED`, `BUNDLE_TOO_LARGE` and `BUNDLE_STORE_UNAVAILABLE`, each before anything is written.",list:"Bundles built in this tenant, newest first, optionally of some profiles.",get:"One bundle: its state, verdict, items and, once ready, its files. Refuses `BUNDLE_NOT_FOUND`.",download:"A short-lived link to the bundle's archive, or to one entry it published; with `view`, a link the browser shows rather than saves. Refuses `BUNDLE_NOT_FOUND`, `BUNDLE_ENTRY_NOT_FOUND`, `BUNDLE_VIEW_NEEDS_ENTRY`, `BUNDLE_NOT_READY` (still building), `BUNDLE_FAILED`, `BUNDLE_FILE_CHANGED` and `BUNDLE_STORE_UNAVAILABLE`.",profiles:"The registered profiles asked for, or every one, each with its label and description."},invitations:{resolve:`Read what an invitation link refers to, before signing in.
|
|
281
281
|
|
|
282
282
|
Takes the token from the acceptance URL and requires no session \u2014 a person holding an invitation link has none by construction. Answers the inviting organization, the invited email address, and whether this invitation created the account, so the acceptance page can show who invited whom and choose the right next step.
|
|
283
283
|
|