omo-ai 5.1.2 → 5.1.4

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.
@@ -291,7 +291,7 @@ You are working on tasks that don't fit specific categories but require moderate
291
291
  </Category_Context>`,UNSPECIFIED_LOW_CATEGORY_CALLER_GUIDANCE=`<Selection_Gate>Use only when no specialist category fits, effort is moderate, and scope stays within a few files/modules. Prefer any matching specialist category.</Selection_Gate>
292
292
  <Caller_Warning>Provide explicit must-do steps, forbidden scope, and concrete success criteria.</Caller_Warning>`,UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND=`<Category_Context>
293
293
  You are working on tasks that don't fit specific categories but require substantial effort.
294
- </Category_Context>`,UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Use only when no specialist category fits and substantial effort spans systems/modules with broad impact. Use unspecified-low for contained moderate work.</Selection_Gate>",DEEP_LOW_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here when one subsystem plus its callers holds the mechanism and the evidence, once read, leaves one right answer. Wide but mechanical work belongs here or in a quick batch. When unsure, choose deep-low: a misrouted child returns `ESCALATE: deep-high` after one cheap attempt; re-spawn the same brief as deep-high with its findings.</Selection_Gate>",DEEP_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here only when you can name the decision evidence cannot settle: a trade-off with no single right answer, a contract change crossing a package or process boundary, a mechanism with no in-repo pattern to copy, or correctness argued from invariants rather than observed in a test. Wide scope with easy decisions is deep-low or unspecified-high; reasoning as the deliverable is ultrabrain.</Selection_Gate>",GPT_FLAGSHIP_GATE_MODELS=["gpt-6-astra","gpt-5.6-sol"],DEEP_LOW_GATE_MODELS=["gpt-5.6-sol-fast","gpt-5.6-sol"],DEEP_HIGH_GATE_MODEL="gpt-6-astra",OPENAI_CATEGORIES=[{name:"ultrabrain",config:{model:"chatgpt-subscription/gpt-6-astra",variant:"max"},description:"Use ONLY for genuinely hard, logic-heavy tasks. Give clear goals only, not step-by-step instructions.",promptAppend:`<Category_Context>
294
+ </Category_Context>`,UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Use only when no specialist category fits and substantial effort spans systems/modules with broad impact. Use unspecified-low for contained moderate work.</Selection_Gate>",DEEP_LOW_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here when one subsystem plus its callers holds the mechanism and the evidence, once read, leaves one right answer. Wide but mechanical work belongs here or in a quick batch. When unsure, choose deep-low: a misrouted child returns `ESCALATE: deep-high` after one cheap attempt; re-spawn the same brief as deep-high with its findings.</Selection_Gate>",DEEP_HIGH_CATEGORY_CALLER_GUIDANCE="<Selection_Gate>Route here only when you can name the decision evidence cannot settle: a trade-off with no single right answer, a contract change crossing a package or process boundary, a mechanism with no in-repo pattern to copy, or correctness argued from invariants rather than observed in a test. Wide scope with easy decisions is deep-low or unspecified-high; reasoning as the deliverable is ultrabrain.</Selection_Gate>",GPT_FLAGSHIP_GATE_MODELS=["gpt-6-astra","gpt-5.6-sol"],DEEP_LOW_GATE_MODELS=["gpt-6.1-sol","gpt-6.1-sol-fast","gpt-5.6-sol-fast","gpt-5.6-sol"],DEEP_HIGH_GATE_MODEL="gpt-6-astra",OPENAI_CATEGORIES=[{name:"ultrabrain",config:{model:"chatgpt-subscription/gpt-6-astra",variant:"max"},description:"Use ONLY for genuinely hard, logic-heavy tasks. Give clear goals only, not step-by-step instructions.",promptAppend:`<Category_Context>
295
295
  You are working on DEEP LOGICAL REASONING / COMPLEX ARCHITECTURE tasks.
296
296
 
297
297
  **CRITICAL - CODE STYLE REQUIREMENTS (NON-NEGOTIABLE)**:
@@ -311,7 +311,7 @@ Response format:
311
311
  - Bottom line (2-3 sentences)
312
312
  - Action plan (numbered steps)
313
313
  - Risks and mitigations (if relevant)
314
- </Category_Context>`,resolvePromptAppend:resolveUltrabrainCategoryPromptAppend,requiresModel:GPT_FLAGSHIP_GATE_MODELS},{name:"deep-low",config:{model:"chatgpt-subscription/gpt-5.6-sol",variant:"medium"},description:"Default deep lane: one goal, one deliverable, decisions the child can settle from what it reads. **3D graphics, computer/browser use, CAPTCHA, multimodal, backend, logic, and algorithm work is routed here.** Multiple goals fan out as parallel calls.",callerGuidance:DEEP_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:`<Category_Context name="deep-low">
314
+ </Category_Context>`,resolvePromptAppend:resolveUltrabrainCategoryPromptAppend,requiresModel:GPT_FLAGSHIP_GATE_MODELS},{name:"deep-low",config:{model:"chatgpt-subscription/gpt-6.1-sol",variant:"medium"},description:"Default deep lane: one goal, one deliverable, decisions the child can settle from what it reads. **3D graphics, computer/browser use, CAPTCHA, multimodal, backend, logic, and algorithm work is routed here.** Multiple goals fan out as parallel calls.",callerGuidance:DEEP_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:`<Category_Context name="deep-low">
315
315
  You are working on a GOAL-ORIENTED AUTONOMOUS task: one goal, one deliverable, decisions the codebase can settle.
316
316
 
317
317
  Before any change, read the files involved and trace their dependencies until you can explain the mechanism you are about to modify. The goal is already defined: do not ask clarifying questions; make reasonable assumptions, record them in the final message, and proceed.
@@ -329,7 +329,7 @@ Before any change, read the files involved and trace their dependencies until yo
329
329
  When the goal lists numbered steps or phases, execute all of them in this turn as one atomic task. Genuinely independent tasks bundled into one goal: flag them and do only the one the goal centers on.
330
330
 
331
331
  Prefer the fix that removes the cause over the patch that hides the symptom. Report completion with the changes made, the evidence they work, and the decision you settled with the alternative you rejected.
332
- </Category_Context>`,resolvePromptAppend:resolveDeepHighCategoryPromptAppend,requiresModel:DEEP_HIGH_GATE_MODEL},{name:"quick",config:{model:"chatgpt-subscription/gpt-6-luna-fast",variant:"low"},description:"Trivial tasks - single file changes, typo fixes, simple modifications",callerGuidance:QUICK_CATEGORY_CALLER_GUIDANCE,promptAppend:QUICK_CATEGORY_PROMPT_APPEND},{name:"unspecified-low",config:{model:"anthropic/claude-sonnet-5-5",variant:"medium"},description:"Tasks that don't fit other categories, low effort required",callerGuidance:UNSPECIFIED_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:UNSPECIFIED_LOW_CATEGORY_PROMPT_APPEND},{name:"unspecified-high",config:{model:"anthropic/claude-opus-5-5",variant:"medium"},description:"Tasks that don't fit other categories, high effort required",callerGuidance:UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE,promptAppend:UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND,resolvePromptAppend:resolveUnspecifiedHighCategoryPromptAppend}];var CATEGORY_FALLBACK_CHAINS={"visual-engineering":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],architect:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"}],ultrabrain:[{providers:["chatgpt-subscription","openai"],model:"gpt-6-astra",variant:"max"},{providers:["github-copilot"],model:"gpt-6-astra",variant:"max"},{providers:["chatgpt-subscription","openai","opencode"],model:"gpt-6-astra",variant:"max"},{providers:["chatgpt-subscription","openai"],model:"gpt-5.6-sol",variant:"max"},{providers:["github-copilot"],model:"gpt-5.6-sol",variant:"max"},{providers:["chatgpt-subscription","openai","opencode"],model:"gpt-5.6-sol",variant:"max"}],"deep-low":[{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-5.6-sol",variant:"medium"},{providers:["chatgpt-subscription","openai"],model:"gpt-5.6-sol-fast",variant:"medium"}],"deep-high":[{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-6-astra",variant:"xhigh"}],artistry:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],quick:[{providers:["chatgpt-subscription","openai"],model:"gpt-6-luna-fast",variant:"low"},{providers:["deepseek"],model:"deepseek-flash",variant:"off"},{providers:["qwen-token-plan","alibaba-token-plan","bailian-coding-plan"],model:"qwen3.6-flash",variant:"low"},{providers:["opencode-go"],model:"minimax-m3",variant:"max"},{providers:["opencode-go"],model:"minimax-m2.7",variant:"max"},{providers:["xai"],model:"grok-4.20-0309-non-reasoning"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot"],model:"claude-haiku-4-5",variant:"off"}],"unspecified-low":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-sonnet-5-5",variant:"medium"},{providers:["xiaomi","opencode-go"],model:"mimo-v2.6-pro",variant:"max"},{providers:["xai","github-copilot","opencode-go"],model:"grok-4.7",variant:"xhigh"},{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-5.6-terra",variant:"high"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-sonnet-5",variant:"low"},{providers:["qwen-token-plan","alibaba-token-plan","qwen-token-plan-cn","alibaba-token-plan-cn"],model:"qwen3.8-max-preview",variant:"max"},{providers:["deepseek","opencode-go"],model:"deepseek-v4-pro",variant:"max"},{providers:["xiaomi","opencode-go"],model:"mimo-v2.5-pro",variant:"max"}],"unspecified-high":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"medium"},{providers:["zai","zai-coding-cn","opencode-go"],model:"glm-5.3",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],writing:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"low"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-4-6",variant:"max"}]};var BUILTIN_CATEGORY_DEFAULTS=[...GOOGLE_CATEGORIES,...OPENAI_CATEGORIES,...ANTHROPIC_CATEGORIES,...KIMI_CATEGORIES],DEFAULT_CATEGORIES=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.config])),CATEGORY_DESCRIPTIONS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.description])),CATEGORY_CALLER_GUIDANCE=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.callerGuidance])),CATEGORY_PROMPT_APPENDS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.promptAppend]));function hasRequiresModel(definition){return definition.requiresModel!==void 0}var BUILTIN_CATEGORY_REQUIRES_MODEL=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.filter(hasRequiresModel).map((definition)=>[definition.name,typeof definition.requiresModel==="string"?[definition.requiresModel]:definition.requiresModel]));function categoryGateModels(categoryName){return Object.hasOwn(BUILTIN_CATEGORY_REQUIRES_MODEL,categoryName)?BUILTIN_CATEGORY_REQUIRES_MODEL[categoryName]:void 0}function categoryChainProviders(categoryName){return(Object.hasOwn(CATEGORY_FALLBACK_CHAINS,categoryName)?CATEGORY_FALLBACK_CHAINS[categoryName]:[]).flatMap((rung)=>rung.providers)}function providerServesModel(provider,model,availableModels){return availableModels.has(`${provider}/${model}`)||availableModels.has(`${provider}/${transformModelForProvider(provider,model)}`)}function isCategoryGateSatisfied(categoryName,hasExplicitUserConfig,availableModels){let gateModels=categoryGateModels(categoryName);if(gateModels===void 0||hasExplicitUserConfig)return!0;let chainProviders=categoryChainProviders(categoryName);return gateModels.some((gateModel)=>chainProviders.some((provider)=>providerServesModel(provider,gateModel,availableModels)))}function isCategoryChainRungResolvable(entry,availableModels){return entry.providers.some((provider)=>providerServesModel(provider,entry.model,availableModels))}function isCategoryChainViable(categoryName,hasExplicitUserConfig,availableModels){if(hasExplicitUserConfig)return!0;let chain=Object.hasOwn(CATEGORY_FALLBACK_CHAINS,categoryName)?CATEGORY_FALLBACK_CHAINS[categoryName]:void 0;if(chain===void 0||chain.length===0)return!0;return chain.some((rung)=>isCategoryChainRungResolvable(rung,availableModels))}var CATEGORY_PROMPT_APPEND_RESOLVERS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.filter(hasPromptAppendResolver).map((definition)=>[definition.name,definition.resolvePromptAppend]));function hasPromptAppendResolver(definition){return definition.resolvePromptAppend!==void 0}var SECRET_LIKE_MODEL_FIELD_NAMES=new Set(["accesstoken","apikey","auth","authorization","bearertoken","clientsecret","password","privatekey","privatetoken","secret","secretkey","token"]);function formatModel(model){return`${model.provider}/${model.modelId}`}function normalizeModelFieldName(key){return key.replaceAll(/[^a-zA-Z0-9]/g,"").toLowerCase()}function hasSecretLikeModelField(model){return Object.getOwnPropertyNames(model).some((key)=>SECRET_LIKE_MODEL_FIELD_NAMES.has(normalizeModelFieldName(key)))}function ownStringDataProperty(model,key){let descriptor=Object.getOwnPropertyDescriptor(model,key);return descriptor&&"value"in descriptor&&typeof descriptor.value==="string"?descriptor.value:void 0}function isSenpiModelPort(model){if(typeof model!=="object"||model===null||hasSecretLikeModelField(model))return!1;return ownStringDataProperty(model,"provider")!==void 0&&ownStringDataProperty(model,"id")!==void 0}function parseRegistryModel(model,expected){if(!isSenpiModelPort(model))return;let provider=ownStringDataProperty(model,"provider"),modelId=ownStringDataProperty(model,"id"),displayName=ownStringDataProperty(model,"name");if(!provider||!modelId||expected!==void 0&&(provider!==expected.provider||modelId!==expected.modelId))return;return{model,provider,modelId,...displayName!==void 0&&displayName.trim().length>0&&displayName.length<=120&&!/[\u0000-\u001f\u007f-\u009f]/u.test(displayName)?{displayName}:{}}}function availableCategoryNames(config,availableModels){let names=Array.from(new Set([...Object.keys(DEFAULT_CATEGORIES),...Object.keys(config.categories??{})])).sort();if(availableModels===void 0)return names;let userCategories=config.categories??{};return names.filter((name)=>{let hasExplicitUserConfig=getOwnRecordValue(userCategories,name)!==void 0;return isCategoryGateSatisfied(name,hasExplicitUserConfig,availableModels)&&isCategoryChainViable(name,hasExplicitUserConfig,availableModels)})}function gatedAvailableCategories(config,senpiModelRegistry){try{let parsed=parseAvailableModels(senpiModelRegistry.getAvailable());if(!parsed.validContainer)return availableCategoryNames(config);return availableCategoryNames(config,new Set(parsed.models))}catch{return availableCategoryNames(config)}}function resolveAvailableCategoryNames(config,senpiModelRegistry){return gatedAvailableCategories(config,senpiModelRegistry)}function missingChainProviders(chain,availableModels){let connected=new Set(availableModels.map((model)=>model.slice(0,model.indexOf("/")))),missing=[];for(let rung of chain)for(let provider of rung.providers)if(!connected.has(provider)&&!missing.includes(provider))missing.push(provider);return missing}function unlistedProviderModel(chain,availableModels){let available=new Set(availableModels);for(let rung of chain){let match=resolveModelForDelegateTask({fallbackChain:[rung],allowUnlistedProviders:!0,availableModels:available},{connectedProviders:null,hasProviderModelsCache:!0,hasConnectedProvidersCache:!0});if(match!==void 0&&"model"in match)return match.model}return}function getOwnRecordValue(record,key){return Object.hasOwn(record,key)?record[key]:void 0}function parseAvailableModels(models){if(!Array.isArray(models))return{models:[],validContainer:!1};return{models:models.map((model)=>parseRegistryModel(model)).filter((model)=>model!==void 0).map(formatModel).sort(),validContainer:!0}}function resolveCategoryCoverage(config,registry){let available=parseAvailableModels(registry.getAvailable());if(!available.validContainer)throw Error("the model registry did not return a model list");let userCategories=config.categories??{},enabled=(name)=>!Object.hasOwn(userCategories,name)||userCategories[name]?.disable!==!0,usable=new Set(resolveAvailableCategoryNames(config,registry)),names=Array.from(new Set([...Object.keys(DEFAULT_CATEGORIES),...Object.keys(userCategories)])).sort().filter(enabled);return{usable:names.filter((name)=>usable.has(name)),unusable:names.filter((name)=>!usable.has(name)).map((name)=>{let chain=Object.hasOwn(CATEGORY_FALLBACK_CHAINS,name)?CATEGORY_FALLBACK_CHAINS[name]:[],optIn=unlistedProviderModel(chain,available.models);return{name,providers:missingChainProviders(chain,available.models),...optIn!==void 0?{unlistedProviderModel:optIn}:{}}})}}import{accessSync as accessSync2,constants as constants2,existsSync as existsSync3}from"node:fs";import{dirname as dirname4,resolve as resolve3}from"node:path";var PROTOCOL_VERSION="1",ENGINE_ABI="senpi-desktop/1",ENGINE_METHODS=["engine.hello","session.open","session.close","capabilities","displays","windows","capture","click","moveMouse","drag","scroll","typeText","keyChord","raiseWindow","clipboard.read","clipboard.write","ax.snapshot","ax.query","ax.elementAt","ax.focused","ax.node","ax.attributes","ax.children","ax.parent","ax.perform","ax.setValue","ax.focus","ax.click","stopPath.start","stopPath.status","stopPath.heartbeat","stopPath.stop","stopPath.resume","$/cancel","$/test.advanceClock"];var ERROR_CODES=["PermissionDenied","CaptureFailed","InputFailed","BackgroundUnavailable","WindowNotFound","InvalidTarget","InvalidKey","InvalidCoordinateFrame","StaleRef","AxUnsupported","AxFailed","Timeout","Closed","Internal","StopPathUnavailable","Suspended","ScreenLocked","Cancelled","CursorRestoreFailed","FocusRestoreFailed","TransactionFailed"];import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var DESKTOP_ENGINE_BINARY="senpi-desktop-engine",QUARANTINE_ATTRIBUTE="com.apple.quarantine",defaultPackageDir=join2(dirname2(fileURLToPath(import.meta.url)),"..");function getDesktopEngineHost(platform=process.platform,arch=process.arch,libc=platform==="linux"&&platform===process.platform?runningLibc():void 0){return platform==="linux"&&libc==="musl"?`${platform}-${arch}-musl`:`${platform}-${arch}`}var detectedLibc;function runningLibc(){return detectedLibc??=libcFromSignals(process.report?.getReport(),readProcessMaps),detectedLibc}function libcFromSignals(report,readMaps){let header=typeof report==="object"&&report!==null?Reflect.get(report,"header"):void 0,glibc=typeof header==="object"&&header!==null?Reflect.get(header,"glibcVersionRuntime"):void 0;if(typeof glibc==="string"&&glibc.length>0)return"glibc";return/\/ld-musl-[^/\s]+\.so\.1$/m.test(readMaps()??"")?"musl":"glibc"}function readProcessMaps(){try{return readFileSync2("/proc/self/maps","utf8")}catch(error){if(error instanceof Error&&"code"in error)return;throw error}}function getDesktopEngineFileName(platform=process.platform){return platform==="win32"?`${DESKTOP_ENGINE_BINARY}.exe`:DESKTOP_ENGINE_BINARY}function getDesktopEngineCandidatePaths(options={}){let host=getDesktopEngineHost(options.platform,options.arch,options.libc),file=getDesktopEngineFileName(options.platform),packageDir=options.packageDir??defaultPackageDir,execDir=options.execDir??dirname2(process.execPath),repoRoot=options.repoRoot??join2(packageDir,"..",".."),prebuild=join2("native","prebuilds",host,file),runtimeDir=options.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...runtimeDir?[join2(runtimeDir,prebuild)]:[],join2(execDir,prebuild),join2(packageDir,prebuild),join2(repoRoot,"target","release",file)]}function locateDesktopEngine(options={}){let platform=options.platform??process.platform,host=getDesktopEngineHost(platform,options.arch,options.libc),attemptedPaths=getDesktopEngineCandidatePaths(options),isQuarantined=options.isQuarantined??((enginePath)=>isQuarantinedFile(enginePath,platform)),causes=[],quarantinedPaths=[];for(let enginePath of attemptedPaths){if(!existsSync2(enginePath)){causes.push(`${enginePath}: missing`);continue}if(isQuarantined(enginePath)){quarantinedPaths.push(enginePath),causes.push(`${enginePath}: blocked because ${QUARANTINE_ATTRIBUTE} is present (macOS Gatekeeper)`);continue}if(!isExecutable(enginePath)){causes.push(`${enginePath}: not executable (chmod +x)`);continue}return{path:enginePath,diagnostic:null}}let code=quarantinedPaths.length>0?"quarantined":"native-unavailable",message=code==="quarantined"?`The ${DESKTOP_ENGINE_BINARY} binary for ${host} is quarantined by macOS Gatekeeper: ${quarantinedPaths.join(", ")}.`:`No ${DESKTOP_ENGINE_BINARY} binary is available for ${host}.`;return{path:null,diagnostic:{code,host,attemptedPaths,message,cause:causes.join("; ")}}}function isQuarantinedFile(enginePath,platform=process.platform){if(platform!=="darwin")return!1;let probe=spawnSync("/usr/bin/xattr",["-p",QUARANTINE_ATTRIBUTE,enginePath],{stdio:["ignore","ignore","ignore"],timeout:2000});return probe.error===void 0&&probe.status===0}function isExecutable(enginePath){try{return accessSync(enginePath,constants.X_OK),!0}catch(error){if(error instanceof Error&&"code"in error)return!1;throw error}}var GC_NEVER_STALE_MS=Number.MAX_SAFE_INTEGER;function Match(args,match){return match[args.length]?.(...args)??(()=>{throw Error("Invalid Arguments")})()}function CodePointCount(value){let result=0,index=0,prev=0;while(index<value.length){let next=value.charCodeAt(index++)>>10;result+=+((prev<<8|next)!==13879),prev=next}return result}function IsMaxLength(value,maxLength){return value.length<=maxLength||value.length<=maxLength<<1&&CodePointCount(value)<=maxLength}function IsMinLength(value,minLength){return value.length>=minLength<<1||value.length>=minLength&&CodePointCount(value)>=minLength}function IsArray(value){return Array.isArray(value)}function IsBigInt(value){return IsEqual(typeof value,"bigint")}function IsBoolean(value){return IsEqual(typeof value,"boolean")}function IsConstructor(value){if(IsUndefined(value)||!IsFunction(value))return!1;let result=Function.prototype.toString.call(value);if(/^class\s/.test(result))return!0;if(/\[native code\]/.test(result))return!0;return!1}function IsFunction(value){return IsEqual(typeof value,"function")}function IsInteger(value){return Number.isInteger(value)}function IsNull(value){return IsEqual(value,null)}function IsNumber(value){return Number.isFinite(value)}function IsObjectNotArray(value){return IsObject(value)&&!IsArray(value)}function IsObject(value){return IsEqual(typeof value,"object")&&!IsNull(value)}function IsString(value){return IsEqual(typeof value,"string")}function IsSymbol(value){return IsEqual(typeof value,"symbol")}function IsUndefined(value){return IsEqual(value,void 0)}function IsEqual(left,right){return left===right}function IsGreaterThan(left,right){return left>right}function IsLessThan(left,right){return left<right}function IsLessEqualThan(left,right){return left<=right}function IsGreaterEqualThan(left,right){return left>=right}function IsMultipleOf(dividend,divisor){if(IsBigInt(dividend)||IsBigInt(divisor))return BigInt(dividend)%BigInt(divisor)===0n;let tolerance=0.0000000001;if(!IsNumber(dividend))return!0;if(IsInteger(dividend)&&1/divisor%1===0)return!0;let mod=dividend%divisor;return Math.min(Math.abs(mod),Math.abs(mod-divisor),Math.abs(mod+divisor))<tolerance}function IsClassInstance(value){if(!IsObject(value))return!1;let proto=globalThis.Object.getPrototypeOf(value);if(IsNull(proto))return!1;return IsEqual(typeof proto.constructor,"function")&&!(IsEqual(proto.constructor,globalThis.Object)||IsEqual(proto.constructor.name,"Object"))}function IsValueLike(value){return IsBigInt(value)||IsBoolean(value)||IsNull(value)||IsNumber(value)||IsString(value)||IsUndefined(value)}function IsMaxLength2(value,maxLength){return IsMaxLength(value,maxLength)}function IsMinLength2(value,minLength){return IsMinLength(value,minLength)}function Every(value,offset,callback){return value.every((item,index)=>index<offset||callback(item,index))}function EveryAll(value,offset,callback){let result=!0;return value.forEach((item,index)=>{if(index>=offset&&!callback(item,index))result=!1}),result}function Some(value,callback){return value.some((value,index)=>callback(value,index))}function SomeAll(value,callback){let result=!1;return value.forEach((item,index)=>{if(callback(item,index))result=!0}),result}function Counted(value,callback){return value.reduce((result,value,index)=>callback(value,index)?++result:result,0)}function ShiftLeft(array,true_,false_){return IsEqual(array.length,0)?false_():true_(array[0],array.slice(1))}function IsUnsafePropertyKey(key){return IsEqual(key,"__proto__")||IsEqual(key,"constructor")||IsEqual(key,"prototype")}function HasPropertyKey(value,key){return IsUnsafePropertyKey(key)?Object.prototype.hasOwnProperty.call(value,key):(key in value)}function EntriesRegExp(value){return Keys(value).map((key)=>[new RegExp(`^${key}$`),value[key]])}function Entries(value){return Object.entries(value)}function Keys(value){return Object.getOwnPropertyNames(value)}function Symbols(value){return Object.getOwnPropertySymbols(value)}function Values(value){return Object.values(value)}function DeepEqualObject(left,right){if(!IsObject(right))return!1;let keys=Keys(left);return IsEqual(keys.length,Keys(right).length)&&keys.every((key)=>IsDeepEqual(left[key],right[key]))}function DeepEqualArray(left,right){return IsArray(right)&&IsEqual(left.length,right.length)&&left.every((_,index)=>IsDeepEqual(left[index],right[index]))}function IsDeepEqual(left,right){return IsArray(left)?DeepEqualArray(left,right):IsObject(left)?DeepEqualObject(left,right):IsEqual(left,right)}function IsBoolean2(value){return value instanceof Boolean}function IsNumber2(value){return value instanceof Number}function IsString2(value){return value instanceof String}function IsTypeArray(value){return globalThis.ArrayBuffer.isView(value)}function IsRegExp(value){return value instanceof globalThis.RegExp}function IsDate(value){return value instanceof globalThis.Date}function IsSet(value){return value instanceof globalThis.Set}function IsMap(value){return value instanceof globalThis.Map}var settings={immutableTypes:!1,maxErrors:8,maxParseErrors:1,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Get(){return settings}function IsRefine(value){return HasPropertyKey(value,"~refine")&&IsArray(value["~refine"])&&Every(value["~refine"],0,(value)=>IsObject(value)&&HasPropertyKey(value,"check")&&HasPropertyKey(value,"error")&&IsFunction(value.check)&&IsFunction(value.error))}function IsSchemaObject(value){return IsObject(value)&&!IsArray(value)}function IsSchemaBoolean(value){return IsBoolean(value)}function IsSchema(value){return IsSchemaObject(value)||IsSchemaBoolean(value)}function IsAdditionalItems(schema){return HasPropertyKey(schema,"additionalItems")&&IsSchema(schema.additionalItems)}function IsAdditionalProperties(schema){return HasPropertyKey(schema,"additionalProperties")&&IsSchema(schema.additionalProperties)}function IsAllOf(schema){return HasPropertyKey(schema,"allOf")&&IsArray(schema.allOf)&&schema.allOf.every((value)=>IsSchema(value))}function IsAnchor(schema){return HasPropertyKey(schema,"$anchor")&&IsString(schema.$anchor)}function IsAnyOf(schema){return HasPropertyKey(schema,"anyOf")&&IsArray(schema.anyOf)&&schema.anyOf.every((value)=>IsSchema(value))}function IsConst(value){return HasPropertyKey(value,"const")}function IsContains(schema){return HasPropertyKey(schema,"contains")&&IsSchema(schema.contains)}function IsDefault(schema){return HasPropertyKey(schema,"default")}function IsDependencies(schema){return HasPropertyKey(schema,"dependencies")&&IsObject(schema.dependencies)&&Object.values(schema.dependencies).every((value)=>IsSchema(value)||IsArray(value)&&value.every((value)=>IsString(value)))}function IsDependentRequired(schema){return HasPropertyKey(schema,"dependentRequired")&&IsObject(schema.dependentRequired)&&Object.values(schema.dependentRequired).every((value)=>IsArray(value)&&value.every((value)=>IsString(value)))}function IsDependentSchemas(schema){return HasPropertyKey(schema,"dependentSchemas")&&IsObject(schema.dependentSchemas)&&Object.values(schema.dependentSchemas).every((value)=>IsSchema(value))}function IsDynamicAnchor(schema){return HasPropertyKey(schema,"$dynamicAnchor")&&IsString(schema.$dynamicAnchor)}function IsDynamicRef(schema){return HasPropertyKey(schema,"$dynamicRef")&&IsString(schema.$dynamicRef)}function IsElse(schema){return HasPropertyKey(schema,"else")&&IsSchema(schema.else)}function IsEnum(schema){return HasPropertyKey(schema,"enum")&&IsArray(schema.enum)}function IsExclusiveMaximum(schema){return HasPropertyKey(schema,"exclusiveMaximum")&&(IsNumber(schema.exclusiveMaximum)||IsBigInt(schema.exclusiveMaximum))}function IsExclusiveMinimum(schema){return HasPropertyKey(schema,"exclusiveMinimum")&&(IsNumber(schema.exclusiveMinimum)||IsBigInt(schema.exclusiveMinimum))}function IsFormat(schema){return HasPropertyKey(schema,"format")&&IsString(schema.format)}function IsId(schema){return HasPropertyKey(schema,"$id")&&IsString(schema.$id)}function IsIf(schema){return HasPropertyKey(schema,"if")&&IsSchema(schema.if)}function IsItems(schema){return HasPropertyKey(schema,"items")&&(IsSchema(schema.items)||IsArray(schema.items)&&schema.items.every((value)=>IsSchema(value)))}function IsItemsSized(schema){return IsItems(schema)&&IsArray(schema.items)}function IsMaximum(schema){return HasPropertyKey(schema,"maximum")&&(IsNumber(schema.maximum)||IsBigInt(schema.maximum))}function IsMaxContains(schema){return HasPropertyKey(schema,"maxContains")&&IsNumber(schema.maxContains)}function IsMaxItems(schema){return HasPropertyKey(schema,"maxItems")&&IsNumber(schema.maxItems)}function IsMaxLength3(schema){return HasPropertyKey(schema,"maxLength")&&IsNumber(schema.maxLength)}function IsMaxProperties(schema){return HasPropertyKey(schema,"maxProperties")&&IsNumber(schema.maxProperties)}function IsMinimum(schema){return HasPropertyKey(schema,"minimum")&&(IsNumber(schema.minimum)||IsBigInt(schema.minimum))}function IsMinContains(schema){return HasPropertyKey(schema,"minContains")&&IsNumber(schema.minContains)}function IsMinItems(schema){return HasPropertyKey(schema,"minItems")&&IsNumber(schema.minItems)}function IsMinLength3(schema){return HasPropertyKey(schema,"minLength")&&IsNumber(schema.minLength)}function IsMinProperties(schema){return HasPropertyKey(schema,"minProperties")&&IsNumber(schema.minProperties)}function IsMultipleOf2(schema){return HasPropertyKey(schema,"multipleOf")&&(IsNumber(schema.multipleOf)||IsBigInt(schema.multipleOf))}function IsNot(schema){return HasPropertyKey(schema,"not")&&IsSchema(schema.not)}function IsOneOf(schema){return HasPropertyKey(schema,"oneOf")&&IsArray(schema.oneOf)&&schema.oneOf.every((value)=>IsSchema(value))}function IsPattern(schema){return HasPropertyKey(schema,"pattern")&&(IsString(schema.pattern)||schema.pattern instanceof RegExp)}function IsPatternProperties(schema){return HasPropertyKey(schema,"patternProperties")&&IsObject(schema.patternProperties)&&Object.values(schema.patternProperties).every((value)=>IsSchema(value))}function IsPrefixItems(schema){return HasPropertyKey(schema,"prefixItems")&&IsArray(schema.prefixItems)&&schema.prefixItems.every((schema)=>IsSchema(schema))}function IsProperties(schema){return HasPropertyKey(schema,"properties")&&IsObject(schema.properties)&&Object.values(schema.properties).every((value)=>IsSchema(value))}function IsPropertyNames(schema){return HasPropertyKey(schema,"propertyNames")&&(IsObject(schema.propertyNames)||IsSchema(schema.propertyNames))}function IsRecursiveAnchor(schema){return HasPropertyKey(schema,"$recursiveAnchor")&&IsBoolean(schema.$recursiveAnchor)}function IsRecursiveAnchorTrue(schema){return IsRecursiveAnchor(schema)&&IsEqual(schema.$recursiveAnchor,!0)}function IsRecursiveRef(schema){return HasPropertyKey(schema,"$recursiveRef")&&IsString(schema.$recursiveRef)}function IsRef(schema){return HasPropertyKey(schema,"$ref")&&IsString(schema.$ref)}function IsRequired(schema){return HasPropertyKey(schema,"required")&&IsArray(schema.required)&&schema.required.every((value)=>IsString(value))}function IsThen(schema){return HasPropertyKey(schema,"then")&&IsSchema(schema.then)}function IsType(schema){return HasPropertyKey(schema,"type")&&(IsString(schema.type)||IsArray(schema.type)&&schema.type.every((value)=>IsString(value)))}function IsUniqueItems(schema){return HasPropertyKey(schema,"uniqueItems")&&IsBoolean(schema.uniqueItems)}function IsUnevaluatedItems(schema){return HasPropertyKey(schema,"unevaluatedItems")&&IsSchema(schema.unevaluatedItems)}function IsUnevaluatedProperties(schema){return HasPropertyKey(schema,"unevaluatedProperties")&&IsSchema(schema.unevaluatedProperties)}class CheckContext{constructor(){let indices=new Set,keys=new Set;this.stack=[{indices,keys}]}Push(){let indices=new Set,keys=new Set;return this.stack.push({indices,keys}),!0}Pop(){return this.stack.pop(),!0}AddIndex(index){return this.GetIndices().add(index),!0}AddKey(key){return this.GetKeys().add(key),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(results){for(let context of results)context.GetIndices().forEach((value)=>this.GetIndices().add(value)),context.GetKeys().forEach((value)=>this.GetKeys().add(value));return!0}}class ErrorContext extends CheckContext{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Get().maxErrors}AddError(keyword,schemaPath,instancePath,params){return this.AddErrorObject({keyword,schemaPath,instancePath,params})}AddErrors(error){return error.forEach((error)=>this.AddErrorObject(error)),!1}GetErrors(){return this.errors}AddErrorObject(error){if(!this.AtCapacity())this.errors.push(error);return!1}}function CheckRefine(_stack,_context,schema,value){return Every(schema["~refine"],0,(refinement,_)=>refinement.check(value))}function ErrorRefine(_stack,context,schemaPath,instancePath,schema,value){return EveryAll(schema["~refine"],0,(refinement,index)=>refinement.check(value)||context.AddError("~refine",schemaPath,instancePath,{index,message:refinement.error(value)}))}var DefaultUri="urn:typebox:root";function NextUri(ref,base){return URL.canParse(ref,base)?new URL(ref,base):IsEqual(base,DefaultUri)?new URL(`${base}:${ref}`):new URL(`${base.slice(0,base.lastIndexOf(":"))}:${ref}`)}function Stack(context,schema){let base=IsSchemaObject(schema)&&IsId(schema)?NextUri(schema.$id,DefaultUri).href:DefaultUri;return{context,schema,lexicalSchema:schema,lexicalBase:base,resourceBase:base,referenceBase:base,ids:[],useResourceBaseForReference:!0,recursiveAnchor:void 0,dynamicAnchors:[],resourceEntries:new Map,pendingResource:!0,enteredResource:!1}}function RegisterResourceAnchors(anchors,schema,isRoot=!0){if(IsSchemaBoolean(schema))return anchors;if(Array.isArray(schema))return schema.reduce((result,item)=>RegisterResourceAnchors(result,item,!1),anchors);if(!IsSchemaObject(schema))return anchors;if(!isRoot&&IsId(schema))return anchors;let next=!isRoot&&IsDynamicAnchor(schema)?[...anchors,schema]:anchors;return Object.keys(schema).reduce((result,key)=>RegisterResourceAnchors(result,schema[key],!1),next)}function ResourceEntry(stack,schema){return stack.resourceEntries.get(schema)}function NextEnteredResource(stack,schema){return stack.enteredResource||ResourceEntry(stack,schema)!==void 0}function IsRelativeId(schema){return!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(schema.$id)}function NextIds(stack,schema){return IsId(schema)?[...stack.ids,schema]:stack.ids}function NextRecursiveAnchor(stack,schema){return stack.recursiveAnchor??(IsRecursiveAnchorTrue(schema)?schema:void 0)}function NextDynamicAnchors(stack,schema){let registered=IsId(schema)?RegisterResourceAnchors(stack.dynamicAnchors,schema):stack.dynamicAnchors;return IsDynamicAnchor(schema)?[...registered,schema]:registered}function NextPendingResource(stack,schema){return IsId(schema)?!1:stack.pendingResource}function NextLexicalBase(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.base;return IsId(schema)?NextUri(schema.$id,stack.lexicalBase).href:stack.lexicalBase}function NextResourceBase(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.base;return IsId(schema)&&stack.pendingResource?NextUri(schema.$id,stack.resourceBase).href:stack.resourceBase}function NextUseResourceBaseForReference(stack,schema){return IsId(schema)?!IsRelativeId(schema):stack.useResourceBaseForReference}function NextReferenceBase(stack,schema){let isRetrieved=NextEnteredResource(stack,schema),useResourceBaseForReference=NextUseResourceBaseForReference(stack,schema);return isRetrieved||useResourceBaseForReference?NextResourceBase(stack,schema):NextLexicalBase(stack,schema)}function NextLexicalSchema(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.root;return IsId(schema)?schema:stack.lexicalSchema}function HasStackKeywords(stack,schema){return IsSchemaObject(schema)&&(IsId(schema)||IsDynamicAnchor(schema)||IsUndefined(stack.recursiveAnchor)&&IsRecursiveAnchorTrue(schema)||!IsUndefined(ResourceEntry(stack,schema)))}function NextStack(stack,schema){return HasStackKeywords(stack,schema)?{...stack,ids:NextIds(stack,schema),dynamicAnchors:NextDynamicAnchors(stack,schema),recursiveAnchor:NextRecursiveAnchor(stack,schema),pendingResource:NextPendingResource(stack,schema),lexicalBase:NextLexicalBase(stack,schema),resourceBase:NextResourceBase(stack,schema),useResourceBaseForReference:NextUseResourceBaseForReference(stack,schema),referenceBase:NextReferenceBase(stack,schema),lexicalSchema:NextLexicalSchema(stack,schema),enteredResource:NextEnteredResource(stack,schema)}:stack}function IsValid(schema){return IsItems(schema)&&IsArray(schema.items)}function CheckAdditionalItems(stack,context,schema,value){if(!IsValid(schema))return!0;return Every(value,0,(item,index)=>IsLessThan(index,schema.items.length)||CheckSchemaPushStack(stack,context,schema.additionalItems,item)&&context.AddIndex(index))}function ErrorAdditionalItems(stack,context,schemaPath,instancePath,schema,value){if(!IsValid(schema))return!0;return Every(value,0,(item,index)=>{let nextSchemaPath=`${schemaPath}/additionalItems`,nextInstancePath=`${instancePath}/${index}`;return IsLessThan(index,schema.items.length)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.additionalItems,item)&&context.AddIndex(index)})}function EncodeFragment(fragment){return fragment.replace(/~/g,"~0").replace(/\//g,"~1")}function UnicodeRegExp(pattern){return new RegExp(pattern,"u")}function GetPropertyKeyAsPattern(key){return`^${key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function GetPropertiesPattern(schema){let patterns=[];if(IsPatternProperties(schema))patterns.push(...Keys(schema.patternProperties));if(IsProperties(schema))patterns.push(...Keys(schema.properties).map(GetPropertyKeyAsPattern));return IsEqual(patterns.length,0)?"(?!)":`(${patterns.join("|")})`}function CheckAdditionalProperties(stack,context,schema,value){let regexp=UnicodeRegExp(GetPropertiesPattern(schema));return Every(Keys(value),0,(key,_index)=>regexp.test(key)||CheckSchemaPushStack(stack,context,schema.additionalProperties,value[key])&&context.AddKey(key))}function ErrorAdditionalProperties(stack,context,schemaPath,instancePath,schema,value){let regexp=UnicodeRegExp(GetPropertiesPattern(schema)),additionalProperties=[];return EveryAll(Keys(value),0,(key,_index)=>{let nextSchemaPath=`${schemaPath}/additionalProperties`,nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,isAdditionalProperty=regexp.test(key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.additionalProperties,value[key])&&context.AddKey(key);if(!isAdditionalProperty)additionalProperties.push(key);return isAdditionalProperty})||context.AddError("additionalProperties",schemaPath,instancePath,{additionalProperties})}function CheckAllOf(stack,context,schema,value){let results=schema.allOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsEqual(results.length,schema.allOf.length)&&context.Merge(results)}function ErrorAllOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],results=schema.allOf.reduce((result,schema,index)=>{let nextSchemaPath=`${schemaPath}/allOf/${index}`,nextContext=new ErrorContext,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isAllOf=IsEqual(results.length,schema.allOf.length)&&context.Merge(results);if(!isAllOf)failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isAllOf}function CheckAnyOf(stack,context,schema,value){let results=schema.anyOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsGreaterThan(results.length,0)&&context.Merge(results)}function ErrorAnyOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],results=schema.anyOf.reduce((result,schema,index)=>{let nextContext=new ErrorContext,nextSchemaPath=`${schemaPath}/anyOf/${index}`,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isAnyOf=IsGreaterThan(results.length,0)&&context.Merge(results);if(!isAnyOf)failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isAnyOf||context.AddError("anyOf",schemaPath,instancePath,{})}function CheckSchemaBoolean(_stack,_context,schema,_value){return schema}function ErrorSchemaBoolean(stack,context,schemaPath,instancePath,schema,value){return CheckSchemaBoolean(stack,context,schema,value)||context.AddError("boolean",schemaPath,instancePath,{})}function CheckConst(_stack,_context,schema,value){return IsValueLike(schema.const)?IsEqual(value,schema.const):IsDeepEqual(value,schema.const)}function ErrorConst(stack,context,schemaPath,instancePath,schema,value){return CheckConst(stack,context,schema,value)||context.AddError("const",schemaPath,instancePath,{allowedValue:schema.const})}function IsValid2(schema){return!(IsMinContains(schema)&&IsEqual(schema.minContains,0))}function CheckContains(stack,context,schema,value){if(!IsValid2(schema))return!0;return!IsEqual(value.length,0)&&SomeAll(value,(item,index)=>CheckSchema(stack,context,schema.contains,item)&&context.AddIndex(index))}function ErrorContains(stack,context,schemaPath,instancePath,schema,value){return CheckContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains:1})}function CheckDependencies(stack,context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependencies),0,([key,schema])=>!HasPropertyKey(value,key)||(IsArray(schema)?schema.every((key)=>HasPropertyKey(value,key)):CheckSchema(stack,context,schema,value)));return isLength||isEvery}function ErrorDependencies(stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=EveryAll(Entries(schema.dependencies),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/dependencies/${EncodeFragment(key)}`;return!HasPropertyKey(value,key)||(IsArray(schema)?schema.every((dependency)=>HasPropertyKey(value,dependency)||context.AddError("dependencies",schemaPath,instancePath,{property:key,dependencies:schema})):ErrorSchema(stack,context,nextSchemaPath,instancePath,schema,value))});return isLength||isEvery}function CheckDependentRequired(_stack,_context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependentRequired),0,([key,keys])=>!HasPropertyKey(value,key)||keys.every((key)=>HasPropertyKey(value,key)));return isLength||isEvery}function ErrorDependentRequired(_stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEveryEntry=EveryAll(Entries(schema.dependentRequired),0,([key,keys])=>!HasPropertyKey(value,key)||EveryAll(keys,0,(dependency)=>HasPropertyKey(value,dependency)||context.AddError("dependentRequired",schemaPath,instancePath,{property:key,dependencies:keys})));return isLength||isEveryEntry}function CheckDependentSchemas(stack,context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependentSchemas),0,([key,schema])=>!HasPropertyKey(value,key)||CheckSchema(stack,context,schema,value));return isLength||isEvery}function ErrorDependentSchemas(stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=EveryAll(Entries(schema.dependentSchemas),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/dependentSchemas/${EncodeFragment(key)}`;return!HasPropertyKey(value,key)||ErrorSchema(stack,context,nextSchemaPath,instancePath,schema,value)});return isLength||isEvery}function Indices(pointer){let indices=pointer.split("/").map((index)=>index.replace(/~1/g,"/").replace(/~0/g,"~"));return indices[0]===""?indices.slice(1):indices}function Get2(value,pointer){let current=value;for(let index of Indices(pointer)){if(!IsObject(current)||IsUnsafePropertyKey(index))return;current=current[index]}return current}function RelativeBase(schema,base){return IsSchemaObject(schema)&&IsId(schema)?NextUri(schema.$id,base.href):base}function AbsoluteBase(base){return NextUri(base,DefaultUri)}function CanonicalHref(url){return url.href.split("#")[0]}function Base(schema,base,target){return SearchBase(schema,AbsoluteBase(base),target)}function RefRoot(stack,ref){return ref.$ref.startsWith("#")||stack.enteredResource?stack.lexicalSchema:stack.schema}function IsPointerFragment(fragment){return fragment.startsWith("#/")}function SearchDynamicAnchor(schema,name){if(IsObject(schema)&&IsDynamicAnchor(schema)&&IsEqual(schema.$dynamicAnchor,name))return schema;if(IsObject(schema))for(let key of Keys(schema)){let result=SearchDynamicAnchor(schema[key],name);if(result)return result}return}function SearchBase(schema,base,target){if(IsEqual(schema,target))return base.href;let nextBase=RelativeBase(schema,base);if(IsArray(schema))for(let item of schema){let result=SearchBase(item,nextBase,target);if(!IsUndefined(result))return result}else if(IsObject(schema))for(let key of Keys(schema)){let result=SearchBase(schema[key],nextBase,target);if(!IsUndefined(result))return result}return}function MatchWithHash(schema,ref){if(ref.href.endsWith("#"))return schema;if(!ref.hash.startsWith("#"))return;let fragment=decodeURIComponent(ref.hash.slice(1));if(!fragment.startsWith("/"))return;return Get2(schema,fragment)}function MatchWithId(schema,base,ref){if(!IsId(schema))return;if(IsEqual(schema.$id,ref.hash))return schema;let absoluteRef=new URL(ref.href,base.href);if(IsEqual(base.pathname,absoluteRef.pathname))return ref.hash.startsWith("#")?MatchWithHash(schema,ref):schema;return}function MatchWithAnchor(schema,base,ref){if(!IsAnchor(schema))return;let absoluteAnchor=new URL(`#${schema.$anchor}`,base.href),absoluteRef=new URL(ref.href,base.href);return IsEqual(absoluteAnchor.href,absoluteRef.href)?schema:void 0}function MatchWithDynamicAnchor(schema,base,ref){if(!IsDynamicAnchor(schema))return;let absoluteAnchor=new URL(`#${schema.$dynamicAnchor}`,base.href),absoluteRef=new URL(ref.href,base.href);return IsEqual(absoluteAnchor.href,absoluteRef.href)?schema:void 0}function MatchSchemaObject(schema,base,ref){if(!IsSchemaObject(schema))return;return MatchWithId(schema,base,ref)??MatchWithAnchor(schema,base,ref)??MatchWithDynamicAnchor(schema,base,ref)??MatchWithHash(schema,ref)}function MatchFromArray(schema,base,ref){if(!IsArray(schema))return;return schema.reduce((result,item)=>{let match=Match2(item,base,ref);return!IsUndefined(match)?match:result},void 0)}function MatchFromObject(schema,base,ref){if(!IsObject(schema))return;return Keys(schema).reduce((result,key)=>{if(IsEqual(key,"const")||IsEqual(key,"enum"))return result;let match=Match2(schema[key],base,ref);return!IsUndefined(match)?match:result},void 0)}function Match2(schema,base,ref){let relativeBase=RelativeBase(schema,base);return MatchSchemaObject(schema,relativeBase,ref)??MatchFromArray(schema,relativeBase,ref)??MatchFromObject(schema,relativeBase,ref)}function Resource(context,schema,base,ref){let result=RefInternal(context,schema,base,ref);return IsSchemaObject(result)&&IsId(result)?result:void 0}function FindDeferredResourceLegacy(stack,ref,schema){if(!ref.$ref.startsWith("#"))return;if(!IsSchemaObject(stack.schema)||HasPropertyKey(stack.schema,"$schema"))return;let targetBase=Base(stack.lexicalSchema,stack.referenceBase,schema);if(IsUndefined(targetBase)||IsEqual(targetBase,stack.referenceBase))return;return{target:schema,base:targetBase,root:stack.lexicalSchema}}function FindDeferredResourceModern(stack,canonical,schema){let remoteRoot=stack.context[canonical];if(!IsSchemaObject(remoteRoot))return;return{target:schema,base:canonical,root:remoteRoot}}function FindDeferredResource(stack,ref,schema,canonical,isRemote){let remote=isRemote?FindDeferredResourceModern(stack,canonical,schema):void 0;return IsUndefined(remote)?FindDeferredResourceLegacy(stack,ref,schema):remote}function FindResolvedResource(stack,canonical,schema){if(IsId(schema))return;let resource=Resource(stack.context,stack.schema,stack.referenceBase,canonical);if(!resource||stack.ids.includes(resource))return;return{resource}}function RefInternalWithContext(context,ref){return HasPropertyKey(context,ref)?context[ref]:void 0}function RefInternalWithLocal(schema,base,ref){return Match2(schema,base,ref)}function RefInternalWithRemote(context,base,ref){let canonicalHref=CanonicalHref(ref);if(!HasPropertyKey(context,canonicalHref)||IsEqual(canonicalHref,CanonicalHref(base)))return;let remoteSchema=context[canonicalHref],remoteBase=RelativeBase(remoteSchema,new URL(canonicalHref));return IsEqual(ref.hash,"")?remoteSchema:Match2(remoteSchema,remoteBase,ref)}function RefInternal(context,schema,base,ref){let absoluteBase=AbsoluteBase(base),target=NextUri(ref,absoluteBase.href);return RefInternalWithContext(context,ref)??RefInternalWithLocal(schema,absoluteBase,target)??RefInternalWithRemote(context,absoluteBase,target)}function RefNextStackDeferred(stack,deferredResource){if(!deferredResource)return stack;let resourceEntries=new Map(stack.resourceEntries);return resourceEntries.set(deferredResource.target,{base:deferredResource.base,root:deferredResource.root}),{...stack,resourceEntries}}function RefNextStackResolved(stack,resolvedResource){return resolvedResource?NextStack(stack,resolvedResource.resource):stack}function RefNextStack(stack,pendingResource,deferredResource,resolvedResource){let withDeferred=RefNextStackDeferred({...stack,pendingResource},deferredResource);return RefNextStackResolved(withDeferred,resolvedResource)}function RefResultFound(stack,ref,schema){let canonical=CanonicalHref(NextUri(ref.$ref,stack.referenceBase)),isRemote=!IsEqual(canonical,stack.resourceBase),deferredResource=FindDeferredResource(stack,ref,schema,canonical,isRemote),resolvedResource=isRemote?FindResolvedResource(stack,canonical,schema):void 0;return{schema,stack:RefNextStack(stack,!0,deferredResource,resolvedResource)}}function RefResultNotFound(stack,schema){return{schema,stack:RefNextStack(stack,!IsUndefined(schema))}}function Ref(stack,ref){let schema=RefInternal(stack.context,RefRoot(stack,ref),stack.referenceBase,ref.$ref);return IsSchemaObject(schema)?RefResultFound(stack,ref,schema):RefResultNotFound(stack,schema)}function IsRecursiveAnchorInScope(stack){return IsSchemaObject(stack.lexicalSchema)&&IsRecursiveAnchorTrue(stack.lexicalSchema)}function RecursiveRef(stack,recursiveRef){let schema=IsRecursiveAnchorInScope(stack)?stack.recursiveAnchor:stack.lexicalSchema;return RefInternal(stack.context,schema,stack.lexicalBase,recursiveRef.$recursiveRef)}function DynamicRefFragment(stack,dynamicRef){return NextUri(dynamicRef.$dynamicRef,AbsoluteBase(stack.lexicalBase).href).hash}function FindScopedDynamicAnchor(stack,name){return stack.dynamicAnchors.find((anchor)=>IsEqual(anchor.$dynamicAnchor,name))??SearchDynamicAnchor(stack.schema,name)}function DynamicRefWhenFound(stack,dynamicRef,fragmentTarget){if(!IsSchemaObject(fragmentTarget)||!IsDynamicAnchor(fragmentTarget))return fragmentTarget;let fragment=DynamicRefFragment(stack,dynamicRef);return IsPointerFragment(fragment)?fragmentTarget:FindScopedDynamicAnchor(stack,fragmentTarget.$dynamicAnchor)}function DynamicRefWhenNotFound(stack,dynamicRef){let fragment=DynamicRefFragment(stack,dynamicRef);return FindScopedDynamicAnchor(stack,decodeURIComponent(fragment.slice(1)))}function DynamicRef(stack,dynamicRef){let fragmentRoot=dynamicRef.$dynamicRef.startsWith("#")?stack.lexicalSchema:stack.schema,fragmentTarget=RefInternal(stack.context,fragmentRoot,stack.lexicalBase,dynamicRef.$dynamicRef);return IsUndefined(fragmentTarget)?DynamicRefWhenNotFound(stack,dynamicRef):DynamicRefWhenFound(stack,dynamicRef,fragmentTarget)}function CheckDynamicRef(stack,context,schema,value){let target=DynamicRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&CheckSchema(nextStack,context,target,value)}function ErrorDynamicRef(stack,context,schemaPath,instancePath,schema,value){let target=DynamicRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&ErrorSchema(nextStack,context,schemaPath,instancePath,target,value)}function CheckEnum(_stack,_context,schema,value){return Some(schema.enum,(option)=>IsValueLike(option)?IsEqual(value,option):IsDeepEqual(value,option))}function ErrorEnum(stack,context,schemaPath,instancePath,schema,value){return CheckEnum(stack,context,schema,value)||context.AddError("enum",schemaPath,instancePath,{allowedValues:schema.enum})}function CheckExclusiveMaximum(_stack,_context,schema,value){return IsLessThan(value,schema.exclusiveMaximum)}function ErrorExclusiveMaximum(stack,context,schemaPath,instancePath,schema,value){return CheckExclusiveMaximum(stack,context,schema,value)||context.AddError("exclusiveMaximum",schemaPath,instancePath,{comparison:"<",limit:schema.exclusiveMaximum})}function CheckExclusiveMinimum(_stack,_context,schema,value){return IsGreaterThan(value,schema.exclusiveMinimum)}function ErrorExclusiveMinimum(stack,context,schemaPath,instancePath,schema,value){return CheckExclusiveMinimum(stack,context,schema,value)||context.AddError("exclusiveMinimum",schemaPath,instancePath,{comparison:">",limit:schema.exclusiveMinimum})}var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function IsLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function IsDate2(value){let matches=DATE.exec(value);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&IsLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function IsTime(value,strictTimeZone=!0){let matches=TIME.exec(value);if(!matches)return!1;if(strictTimeZone&&!matches[4]&&!matches[5])return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3];if(hr>23||min>59||sec>60)return!1;if(matches[5]){let tzH=+matches[6],tzM=+matches[7];if(tzH>23||tzM>59)return!1}if(sec<60)return!0;let tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);return((hr*60+min-tzSign*(tzH*60+tzM))%1440+1440)%1440===1439}function IsDateTime(value){let dateTime=value.split(/T/i);return dateTime.length===2&&IsDate2(dateTime[0])&&IsTime(dateTime[1])}var Duration=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function IsDuration(value){return Duration.test(value)}var Email=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function IsEmail(value){return Email.test(value)}var RE_RULE_HYPHEN_PLACEMENT=/^(?!-).*(?<!-)$/,RE_RULE_NOT_RESERVED_ACE=/^(?!..--)/,RE_ASCII_LDH=/^[a-zA-Z0-9-]*$/;var RE_NON_ASCII=/[^\p{ASCII}]/u;var RE_ASCII_DIGIT=/[0-9]/,RE_ARABIC_INDIC_DIGIT=/[\u{0660}-\u{0669}]/u,RE_EXT_ARABIC_INDIC_DIGIT=/[\u{06f0}-\u{06f9}]/u,RE_COMMON_SEPARATOR=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,RE_EUROPEAN_SEPARATOR=/[\u{002d}\u{002b}]/u,RE_MARK_NONSPACING=/\p{Mn}/u,RE_MARK_SPACING_COMBINING=/\p{Mc}/u;var RE_COMBINING_MARK=/[\p{Mn}\p{Mc}\p{Me}]/u,RE_LETTER=/\p{L}/u,RE_NUMBER_DECIMAL=/\p{Nd}/u,RE_SCRIPT_GREEK=/\p{Script=Greek}/u,RE_SCRIPT_HEBREW=/\p{Script=Hebrew}/u,RE_SCRIPT_JAPANESE=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,RE_SCRIPT_ARABIC_LETTER=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,RE_VIRAMA=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,RE_RFC5892_DISALLOWED=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,RE_CONTEXTO_EXCEPTIONS=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,RE_PVALID_EXCEPTIONS=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,RE_EUROPEAN_NUMBER=new RegExp([RE_ASCII_DIGIT,RE_EXT_ARABIC_INDIC_DIGIT].map((regexp)=>regexp.source).join("|"),"u"),RE_PERMITTED_CATEGORY=new RegExp([RE_LETTER,RE_EUROPEAN_SEPARATOR,RE_COMMON_SEPARATOR,RE_NUMBER_DECIMAL,RE_MARK_NONSPACING,RE_MARK_SPACING_COMBINING,RE_CONTEXTO_EXCEPTIONS,RE_PVALID_EXCEPTIONS].map((regexp)=>regexp.source).join("|"),"u");function IsAsciiLabel(value){return RE_RULE_HYPHEN_PLACEMENT.test(value)&&RE_RULE_NOT_RESERVED_ACE.test(value)&&RE_ASCII_LDH.test(value)}var PUNYCODE_BASE=36,PUNYCODE_TMIN=1,PUNYCODE_TMAX=26,PUNYCODE_SKEW=38,PUNYCODE_DAMP=700,PUNYCODE_INITIAL_BIAS=72,PUNYCODE_INITIAL_N=128;function ThrowDontCare(){throw null}function IsAcePrefixed(value){return value.toLowerCase().startsWith("xn--")}function Adapt(delta,numPoints,firstTime){delta=firstTime?Math.floor(delta/PUNYCODE_DAMP):delta>>1,delta+=Math.floor(delta/numPoints);let k=0;while(delta>(PUNYCODE_BASE-PUNYCODE_TMIN)*PUNYCODE_TMAX>>1)delta=Math.floor(delta/(PUNYCODE_BASE-PUNYCODE_TMIN)),k+=PUNYCODE_BASE;return k+Math.floor((PUNYCODE_BASE-PUNYCODE_TMIN+1)*delta/(delta+PUNYCODE_SKEW))}function Decode(value){let output=[],n=PUNYCODE_INITIAL_N,i=0,bias=PUNYCODE_INITIAL_BIAS,delimIdx=value.lastIndexOf("-");if(delimIdx>0)for(let j=0;j<delimIdx;j++){let cp=value.charCodeAt(j);if(cp>=128)ThrowDontCare();output.push(cp)}let inIdx=delimIdx<0?0:delimIdx+1;while(inIdx<value.length){let oldi=i,w=1,k=PUNYCODE_BASE;while(!0){if(inIdx>=value.length)ThrowDontCare();let ch=value.charCodeAt(inIdx++),digit;if(ch>=97&&ch<=122)digit=ch-97;else if(ch>=48&&ch<=57)digit=ch-48+26;else ThrowDontCare();i+=digit*w;let t=k<=bias?PUNYCODE_TMIN:k>=bias+PUNYCODE_TMAX?PUNYCODE_TMAX:k-bias;if(digit<t)break;w*=PUNYCODE_BASE-t,k+=PUNYCODE_BASE}let outLen=output.length+1;bias=Adapt(i-oldi,outLen,oldi===0),n+=Math.floor(i/outLen),i%=outLen,output.splice(i,0,n),i++}return String.fromCodePoint(...output)}function DigitToChar(digit){return digit<26?String.fromCharCode(digit+97):String.fromCharCode(digit-26+48)}var RE_REPLACE_NON_ASCII=new RegExp(RE_NON_ASCII.source,"gu");function Encode(input){let basic=input.replace(RE_REPLACE_NON_ASCII,""),basicLength=basic.length,result=basicLength>0?[basic,"-"]:[],codePoints=Array.from(input,(char)=>char.codePointAt(0)),n=PUNYCODE_INITIAL_N,delta=0,bias=PUNYCODE_INITIAL_BIAS,handledCPCount=basicLength;while(handledCPCount<codePoints.length){let m=1/0;for(let cp of codePoints)if(cp>=n&&cp<m)m=cp;delta+=(m-n)*(handledCPCount+1),n=m;for(let cp of codePoints){if(cp<n)delta++;if(cp===n){let q=delta;for(let k=PUNYCODE_BASE;;k+=PUNYCODE_BASE){let t=k<=bias?PUNYCODE_TMIN:k>=bias+PUNYCODE_TMAX?PUNYCODE_TMAX:k-bias;if(q<t)break;let digit=t+(q-t)%(PUNYCODE_BASE-t);result.push(DigitToChar(digit)),q=Math.floor((q-t)/(PUNYCODE_BASE-t))}result.push(DigitToChar(q)),bias=Adapt(delta,handledCPCount+1,handledCPCount===basicLength),delta=0,handledCPCount++}}delta++,n++}return result.join("")}var RE_RTL_ALLOWED=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,RE_LTR_ALLOWED=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,RE_RTL_CLASSES=/^(?:R|AL|AN)$/;function HasBidiChars(value){if(IsAcePrefixed(value))try{return HasRightToLeftCharacters(Decode(value.slice(4).toLowerCase()))}catch{return!1}return HasRightToLeftCharacters(value)}function GetBidiClass(codePoint){let char=String.fromCodePoint(codePoint);return RE_EUROPEAN_NUMBER.test(char)?"EN":RE_ARABIC_INDIC_DIGIT.test(char)?"AN":RE_MARK_NONSPACING.test(char)?"NSM":RE_SCRIPT_HEBREW.test(char)?"R":RE_SCRIPT_ARABIC_LETTER.test(char)?"AL":RE_LETTER.test(char)?"L":"ON"}function HasRightToLeftCharacters(value){for(let ch of value)if(RE_RTL_CLASSES.test(GetBidiClass(ch.codePointAt(0))))return!0;return!1}function SatisfiesBidiRule(value){let isRtl=!1,allowed=RE_LTR_ALLOWED,sawEN=!1,sawAN=!1,isFirst=!0;for(let ch of value){let bidiClass=GetBidiClass(ch.codePointAt(0));if(isFirst){if(bidiClass!=="L"&&bidiClass!=="R"&&bidiClass!=="AL")return!1;isRtl=bidiClass==="R"||bidiClass==="AL",allowed=isRtl?RE_RTL_ALLOWED:RE_LTR_ALLOWED,isFirst=!1}if(!allowed.test(bidiClass))return!1;if(bidiClass==="EN")sawEN=!0;else if(bidiClass==="AN")sawAN=!0}if(isRtl&&sawEN&&sawAN)return!1;return!0}function ExceedsMaxALabelLength(value){return RE_NON_ASCII.test(value)&&Encode(value).length+4>63}function HasInvalidHyphens(chars){if(chars[0]==="-"||chars[chars.length-1]==="-")return!0;return chars.slice(2).join("").startsWith("--")}function IsUnicodeLabel(value){if(ExceedsMaxALabelLength(value))return!1;if(HasRightToLeftCharacters(value)&&!SatisfiesBidiRule(value))return!1;let chars=[...value],codePoints=chars.map((c)=>c.codePointAt(0)),length=codePoints.length;if(HasInvalidHyphens(chars))return!1;if(RE_COMBINING_MARK.test(chars[0]))return!1;let hasJapanese=!1;for(let i=0;i<length;i++){let codePoint=codePoints[i],char=chars[i];if(RE_RFC5892_DISALLOWED.test(char))return!1;if(!RE_PERMITTED_CATEGORY.test(char))return!1;if(RE_SCRIPT_JAPANESE.test(char))hasJapanese=!0;let prev=codePoints[i-1],next=codePoints[i+1];switch(codePoint){case 183:if(prev!==108||next!==108)return!1;break;case 885:if(!next||!RE_SCRIPT_GREEK.test(chars[i+1]))return!1;break;case 1523:case 1524:if(!prev||!RE_SCRIPT_HEBREW.test(chars[i-1]))return!1;break;case 8204:if(!prev||prev<128&&!RE_VIRAMA.test(chars[i-1]))return!1;break;case 8205:if(!prev||!RE_VIRAMA.test(chars[i-1]))return!1;break;case 12539:break}}if(value.includes("・")&&!hasJapanese)return!1;return!0}function IsPunyLabel(value){if(!IsAcePrefixed(value))return!1;try{let body=value.slice(4).toLowerCase();if(body.lastIndexOf("-")===0)return!1;let decoded=Decode(body);if(!RE_NON_ASCII.test(decoded))return!1;return IsUnicodeLabel(decoded)}catch{return!1}}function IsValidLabelLength(value){return value.length>0&&value.length<=63}function IsLabel(value){return IsValidLabelLength(value)&&(IsPunyLabel(value)||IsAsciiLabel(value))}function IsHostname(value){if(value.length===0||value.length>253)return!1;if(value.charCodeAt(value.length-1)===46)return!1;return value.split(".").every((label)=>IsLabel(label))}function IsValidLabelLength2(value){return value.length>0&&value.length<=63}function IsLabel2(value){return IsValidLabelLength2(value)&&(IsPunyLabel(value)||IsUnicodeLabel(value))}function NormalizeHostname(value){return value.replace(/[\uff01-\uff5e]/g,(char)=>String.fromCharCode(char.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function IsIdnHostname(value){if(value.length===0||value.includes(" "))return!1;let normalized=NormalizeHostname(value);if(normalized.length>253)return!1;let labels=normalized.split("."),hasBidiChars=labels.some((label)=>HasBidiChars(label));return labels.every((label)=>IsLabel2(label)&&(!hasBidiChars||SatisfiesBidiRule(label)))}function IsHostname2(value){return IsHostname(value)}var IdnEmail=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function IsIdnEmail(value){return IdnEmail.test(value.normalize("NFC"))}function IsIdnHostname2(value){return IsIdnHostname(value)}var IPv4=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function IsIPv4(value){return IPv4.test(value)}var IPv6=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function IsIPv6(value){return IPv6.test(value)}var InvalidIriChars=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,MalformedScheme=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function IsIriReference(value){return!InvalidIriChars.test(value)&&!MalformedScheme.test(value)&&URL.canParse(value,"http://example.com")}var InvalidIriChars2=/[\x00-\x20<>\^`{|}\\]/,InvalidPercentEncoding=/%(?![0-9a-fA-F]{2})/;function IsIri(value){if(InvalidIriChars2.test(value))return!1;if(InvalidPercentEncoding.test(value))return!1;return URL.canParse(value)}var JsonPointerUriFragment=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function IsJsonPointerUriFragment(value){return JsonPointerUriFragment.test(value)}var JsonPointer=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function IsJsonPointer(value){return JsonPointer.test(value)}function IsRegex(value){try{return new RegExp(value,"u"),!0}catch{return!1}}var RelativeJsonPointer=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function IsRelativeJsonPointer(value){return RelativeJsonPointer.test(value)}var UriReference=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function IsUriReference(value){return UriReference.test(value)}var UriTemplate=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function IsUriTemplate(value){return UriTemplate.test(value)}var Uri=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function IsUri(value){return Uri.test(value)}function IsUrl(value){return URL.canParse(value)}var Uuid=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function IsUuid(value){return Uuid.test(value)}var formats=new Map;function Clear(){formats.clear()}function Test(format,value){return formats.get(format)?.(value)??!0}function Reset(){Clear(),formats.set("date-time",IsDateTime),formats.set("date",IsDate2),formats.set("duration",IsDuration),formats.set("email",IsEmail),formats.set("hostname",IsHostname2),formats.set("idn-email",IsIdnEmail),formats.set("idn-hostname",IsIdnHostname2),formats.set("ipv4",IsIPv4),formats.set("ipv6",IsIPv6),formats.set("iri-reference",IsIriReference),formats.set("iri",IsIri),formats.set("json-pointer-uri-fragment",IsJsonPointerUriFragment),formats.set("json-pointer",IsJsonPointer),formats.set("regex",IsRegex),formats.set("relative-json-pointer",IsRelativeJsonPointer),formats.set("time",IsTime),formats.set("uri-reference",IsUriReference),formats.set("uri-template",IsUriTemplate),formats.set("uri",IsUri),formats.set("url",IsUrl),formats.set("uuid",IsUuid)}Reset();function CheckFormat(_stack,_context,schema,value){return Test(schema.format,value)}function ErrorFormat(stack,context,schemaPath,instancePath,schema,value){return CheckFormat(stack,context,schema,value)||context.AddError("format",schemaPath,instancePath,{format:schema.format})}function CheckIf(stack,context,schema,value){let thenSchema=IsThen(schema)?schema.then:!0,elseSchema=IsElse(schema)?schema.else:!0;return CheckSchema(stack,context,schema.if,value)?CheckSchema(stack,context,thenSchema,value):CheckSchema(stack,context,elseSchema,value)}function ErrorIf(stack,context,schemaPath,instancePath,schema,value){let thenSchema=IsThen(schema)?schema.then:!0,elseSchema=IsElse(schema)?schema.else:!0,trueContext=new ErrorContext,isIf=ErrorSchema(stack,trueContext,`${schemaPath}/if`,instancePath,schema.if,value)?ErrorSchema(stack,trueContext,`${schemaPath}/then`,instancePath,thenSchema,value)||context.AddError("if",schemaPath,instancePath,{failingKeyword:"then"}):ErrorSchema(stack,context,`${schemaPath}/else`,instancePath,elseSchema,value)||context.AddError("if",schemaPath,instancePath,{failingKeyword:"else"});if(isIf)context.Merge([trueContext]);return isIf}function CheckItemsSized(stack,context,schema,value){return Every(schema.items,0,(schema,index)=>IsLessEqualThan(value.length,index)||CheckSchemaPushStack(stack,context,schema,value[index])&&context.AddIndex(index))}function ErrorItemsSized(stack,context,schemaPath,instancePath,schema,value){return EveryAll(schema.items,0,(schema,index)=>{let nextSchemaPath=`${schemaPath}/items/${index}`,nextInstancePath=`${instancePath}/${index}`;return IsLessEqualThan(value.length,index)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[index])&&context.AddIndex(index)})}function CheckItemsUnsized(stack,context,schema,value){let offset=IsPrefixItems(schema)?schema.prefixItems.length:0;return Every(value,offset,(element,index)=>CheckSchemaPushStack(stack,context,schema.items,element)&&context.AddIndex(index))}function ErrorItemsUnsized(stack,context,schemaPath,instancePath,schema,value){let offset=IsPrefixItems(schema)?schema.prefixItems.length:0;return EveryAll(value,offset,(element,index)=>{let nextSchemaPath=`${schemaPath}/items`,nextInstancePath=`${instancePath}/${index}`;return ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.items,element)&&context.AddIndex(index)})}function CheckItems(stack,context,schema,value){return IsItemsSized(schema)?CheckItemsSized(stack,context,schema,value):CheckItemsUnsized(stack,context,schema,value)}function ErrorItems(stack,context,schemaPath,instancePath,schema,value){return IsItemsSized(schema)?ErrorItemsSized(stack,context,schemaPath,instancePath,schema,value):ErrorItemsUnsized(stack,context,schemaPath,instancePath,schema,value)}function IsValid3(schema){return IsContains(schema)}function CheckMaxContains(stack,context,schema,value){if(!IsValid3(schema))return!0;let count=Counted(value,(item)=>CheckSchema(stack,context,schema.contains,item));return IsLessEqualThan(count,schema.maxContains)}function ErrorMaxContains(stack,context,schemaPath,instancePath,schema,value){let minContains=IsMinContains(schema)?schema.minContains:1;return CheckMaxContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains,maxContains:schema.maxContains})}function CheckMaximum(_stack,_context,schema,value){return IsLessEqualThan(value,schema.maximum)}function ErrorMaximum(stack,context,schemaPath,instancePath,schema,value){return CheckMaximum(stack,context,schema,value)||context.AddError("maximum",schemaPath,instancePath,{comparison:"<=",limit:schema.maximum})}function CheckMaxItems(_stack,_context,schema,value){return IsLessEqualThan(value.length,schema.maxItems)}function ErrorMaxItems(stack,context,schemaPath,instancePath,schema,value){return CheckMaxItems(stack,context,schema,value)||context.AddError("maxItems",schemaPath,instancePath,{limit:schema.maxItems})}function CheckMaxLength(_stack,_context,schema,value){return IsMaxLength2(value,schema.maxLength)}function ErrorMaxLength(stack,context,schemaPath,instancePath,schema,value){return CheckMaxLength(stack,context,schema,value)||context.AddError("maxLength",schemaPath,instancePath,{limit:schema.maxLength})}function CheckMaxProperties(_stack,_context,schema,value){return IsLessEqualThan(Keys(value).length,schema.maxProperties)}function ErrorMaxProperties(stack,context,schemaPath,instancePath,schema,value){return CheckMaxProperties(stack,context,schema,value)||context.AddError("maxProperties",schemaPath,instancePath,{limit:schema.maxProperties})}function IsValid4(schema){return IsContains(schema)}function CheckMinContains(stack,context,schema,value){if(!IsValid4(schema))return!0;let count=Counted(value,(item,index)=>CheckSchema(stack,context,schema.contains,item)&&context.AddIndex(index));return IsGreaterEqualThan(count,schema.minContains)}function ErrorMinContains(stack,context,schemaPath,instancePath,schema,value){return CheckMinContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains:schema.minContains})}function CheckMinimum(_stack,_context,schema,value){return IsGreaterEqualThan(value,schema.minimum)}function ErrorMinimum(stack,context,schemaPath,instancePath,schema,value){return CheckMinimum(stack,context,schema,value)||context.AddError("minimum",schemaPath,instancePath,{comparison:">=",limit:schema.minimum})}function CheckMinItems(_stack,_context,schema,value){return IsGreaterEqualThan(value.length,schema.minItems)}function ErrorMinItems(stack,context,schemaPath,instancePath,schema,value){return CheckMinItems(stack,context,schema,value)||context.AddError("minItems",schemaPath,instancePath,{limit:schema.minItems})}function CheckMinLength(_stack,_context,schema,value){return IsMinLength2(value,schema.minLength)}function ErrorMinLength(stack,context,schemaPath,instancePath,schema,value){return CheckMinLength(stack,context,schema,value)||context.AddError("minLength",schemaPath,instancePath,{limit:schema.minLength})}function CheckMinProperties(_stack,_context,schema,value){return IsGreaterEqualThan(Keys(value).length,schema.minProperties)}function ErrorMinProperties(stack,context,schemaPath,instancePath,schema,value){return CheckMinProperties(stack,context,schema,value)||context.AddError("minProperties",schemaPath,instancePath,{limit:schema.minProperties})}function CheckMultipleOf(_stack,_context,schema,value){return IsMultipleOf(value,schema.multipleOf)}function ErrorMultipleOf(stack,context,schemaPath,instancePath,schema,value){return CheckMultipleOf(stack,context,schema,value)||context.AddError("multipleOf",schemaPath,instancePath,{multipleOf:schema.multipleOf})}function CheckNot(stack,context,schema,value){let nextContext=new CheckContext;return!CheckSchema(stack,nextContext,schema.not,value)&&context.Merge([nextContext])}function ErrorNot(stack,context,schemaPath,instancePath,schema,value){return CheckNot(stack,context,schema,value)||context.AddError("not",schemaPath,instancePath,{})}function CheckOneOf(stack,context,schema,value){let passedContexts=schema.oneOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsEqual(passedContexts.length,1)&&context.Merge(passedContexts)}function ErrorOneOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],passingSchemas=[],passedContexts=schema.oneOf.reduce((result,schema,index)=>{let nextContext=new ErrorContext,nextSchemaPath=`${schemaPath}/oneOf/${index}`,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(isSchema)passingSchemas.push(index);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isOneOf=IsEqual(passedContexts.length,1)&&context.Merge(passedContexts);if(!isOneOf&&IsEqual(passingSchemas.length,0))failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isOneOf||context.AddError("oneOf",schemaPath,instancePath,{passingSchemas})}function CheckPattern(_stack,_context,schema,value){return(IsString(schema.pattern)?UnicodeRegExp(schema.pattern):schema.pattern).test(value)}function ErrorPattern(stack,context,schemaPath,instancePath,schema,value){return CheckPattern(stack,context,schema,value)||context.AddError("pattern",schemaPath,instancePath,{pattern:schema.pattern})}function CheckPatternProperties(stack,context,schema,value){return Every(Entries(schema.patternProperties),0,([pattern,schema])=>{let regexp=UnicodeRegExp(pattern);return Every(Entries(value),0,([key,prop])=>!regexp.test(key)||CheckSchemaPushStack(stack,context,schema,prop)&&context.AddKey(key))})}function ErrorPatternProperties(stack,context,schemaPath,instancePath,schema,value){return EveryAll(Entries(schema.patternProperties),0,([pattern,schema])=>{let nextSchemaPath=`${schemaPath}/patternProperties/${EncodeFragment(pattern)}`,regexp=UnicodeRegExp(pattern);return EveryAll(Entries(value),0,([key,value])=>{let nextInstancePath=`${instancePath}/${EncodeFragment(key)}`;return!regexp.test(key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value)&&context.AddKey(key)})})}function CheckPrefixItems(stack,context,schema,value){return IsEqual(value.length,0)||Every(schema.prefixItems,0,(schema,index)=>IsLessEqualThan(value.length,index)||CheckSchemaPushStack(stack,context,schema,value[index])&&context.AddIndex(index))}function ErrorPrefixItems(stack,context,schemaPath,instancePath,schema,value){return IsEqual(value.length,0)||EveryAll(schema.prefixItems,0,(schema,index)=>{let nextSchemaPath=`${schemaPath}/prefixItems/${index}`,nextInstancePath=`${instancePath}/${index}`;return IsLessEqualThan(value.length,index)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[index])&&context.AddIndex(index)})}function IsExactOptional(required,key){return required.includes(key)||Get().exactOptionalPropertyTypes}function InexactOptionalCheck(value,key){return IsUndefined(value[key])}function CheckProperties(stack,context,schema,value){let required=IsRequired(schema)?schema.required:[];return Every(Entries(schema.properties),0,([key,schema])=>{let isProperty=!HasPropertyKey(value,key)||CheckSchemaPushStack(stack,context,schema,value[key])&&context.AddKey(key);return IsExactOptional(required,key)?isProperty:InexactOptionalCheck(value,key)||isProperty})}function ErrorProperties(stack,context,schemaPath,instancePath,schema,value){let required=IsRequired(schema)?schema.required:[];return EveryAll(Entries(schema.properties),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/properties/${EncodeFragment(key)}`,nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,isProperty=()=>!HasPropertyKey(value,key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[key])&&context.AddKey(key);return IsExactOptional(required,key)?isProperty():InexactOptionalCheck(value,key)||isProperty()})}function CheckPropertyNames(stack,context,schema,value){return Every(Keys(value),0,(key,_index)=>CheckSchema(stack,context,schema.propertyNames,key))}function ErrorPropertyNames(stack,context,schemaPath,instancePath,schema,value){let propertyNames=[];return EveryAll(Keys(value),0,(key,_index)=>{let nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,nextSchemaPath=`${schemaPath}/propertyNames`,isPropertyName=ErrorSchema(stack,context,nextSchemaPath,nextInstancePath,schema.propertyNames,key);if(!isPropertyName)propertyNames.push(key);return isPropertyName})||context.AddError("propertyNames",schemaPath,instancePath,{propertyNames})}function CheckRecursiveRef(stack,context,schema,value){let target=RecursiveRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&CheckSchema(nextStack,context,target,value)}function ErrorRecursiveRef(stack,context,schemaPath,instancePath,schema,value){let target=RecursiveRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&ErrorSchema(nextStack,context,schemaPath,instancePath,target,value)}function CheckRef(stack,context,schema,value){let result=Ref(stack,schema),target=result.schema??!1,nextContext=new CheckContext,valid=IsSchema(target)&&CheckSchema(result.stack,nextContext,target,value);if(valid)context.Merge([nextContext]);return valid}function ErrorRef(stack,context,schemaPath,instancePath,schema,value){let result=Ref(stack,schema),target=result.schema??!1,nextContext=new ErrorContext,valid=IsSchema(target)&&ErrorSchema(result.stack,nextContext,schemaPath,instancePath,target,value);if(valid)context.Merge([nextContext]);if(!valid)context.AddErrors(nextContext.GetErrors());return valid}function CheckRequired(_stack,_context,schema,value){return Every(schema.required,0,(key)=>HasPropertyKey(value,key))}function ErrorRequired(_stack,context,schemaPath,instancePath,schema,value){let requiredProperties=[];return EveryAll(schema.required,0,(key)=>{let hasKey=HasPropertyKey(value,key);if(!hasKey)requiredProperties.push(key);return hasKey})||context.AddError("required",schemaPath,instancePath,{requiredProperties})}function CheckTypeName(_stack,_context,type,_schema,value){return IsEqual(type,"object")?IsObjectNotArray(value):IsEqual(type,"array")?IsArray(value):IsEqual(type,"boolean")?IsBoolean(value):IsEqual(type,"integer")?IsInteger(value):IsEqual(type,"number")?IsNumber(value):IsEqual(type,"null")?IsNull(value):IsEqual(type,"string")?IsString(value):IsEqual(type,"bigint")?IsBigInt(value):IsEqual(type,"constructor")?IsConstructor(value):IsEqual(type,"function")?IsFunction(value):IsEqual(type,"symbol")?IsSymbol(value):IsEqual(type,"undefined")?IsUndefined(value):IsEqual(type,"void")?IsUndefined(value):!0}function CheckTypeNames(stack,context,types,schema,value){return Some(types,(type)=>CheckTypeName(stack,context,type,schema,value))}function CheckType(stack,context,schema,value){return IsArray(schema.type)?CheckTypeNames(stack,context,schema.type,schema,value):CheckTypeName(stack,context,schema.type,schema,value)}function ErrorType(stack,context,schemaPath,instancePath,schema,value){return(IsArray(schema.type)?CheckTypeNames(stack,context,schema.type,schema,value):CheckTypeName(stack,context,schema.type,schema,value))||context.AddError("type",schemaPath,instancePath,{type:schema.type})}function CheckUnevaluatedItems(stack,context,schema,value){let indices=context.GetIndices();return Every(value,0,(item,index)=>(indices.has(index)||CheckSchema(stack,context,schema.unevaluatedItems,item))&&context.AddIndex(index))}function ErrorUnevaluatedItems(stack,context,schemaPath,instancePath,schema,value){let indices=context.GetIndices(),unevaluatedItems=[];return EveryAll(value,0,(item,index)=>{let nextContext=new ErrorContext,isEvaluatedItem=(indices.has(index)||ErrorSchema(stack,nextContext,schemaPath,instancePath,schema.unevaluatedItems,item))&&context.AddIndex(index);if(!isEvaluatedItem)unevaluatedItems.push(index);return isEvaluatedItem})||context.AddError("unevaluatedItems",schemaPath,instancePath,{unevaluatedItems})}function CheckUnevaluatedProperties(stack,context,schema,value){let keys=context.GetKeys();return Every(Entries(value),0,([key,prop])=>keys.has(key)||CheckSchema(stack,context,schema.unevaluatedProperties,prop)&&context.AddKey(key))}function ErrorUnevaluatedProperties(stack,context,schemaPath,instancePath,schema,value){let keys=context.GetKeys(),unevaluatedProperties=[];return EveryAll(Entries(value),0,([key,prop])=>{let nextContext=new ErrorContext,isEvaluatedProperty=keys.has(key)||ErrorSchema(stack,nextContext,schemaPath,instancePath,schema.unevaluatedProperties,prop)&&context.AddKey(key);if(!isEvaluatedProperty)unevaluatedProperties.push(key);return isEvaluatedProperty})||context.AddError("unevaluatedProperties",schemaPath,instancePath,{unevaluatedProperties})}function Unreachable(){throw Error("Unreachable")}function InstanceKeys(value){let propertyKeys=new Set,current=value;while(current&&current!==Object.prototype){for(let key of Reflect.ownKeys(current))if(key!=="constructor"&&typeof key!=="symbol")propertyKeys.add(key);current=Object.getPrototypeOf(current)}return[...propertyKeys]}function IsIEEE754(value){return typeof value==="number"}var ByteMarker;(function(ByteMarker){ByteMarker[ByteMarker.Array=0]="Array",ByteMarker[ByteMarker.BigInt=1]="BigInt",ByteMarker[ByteMarker.Boolean=2]="Boolean",ByteMarker[ByteMarker.Date=3]="Date",ByteMarker[ByteMarker.Constructor=4]="Constructor",ByteMarker[ByteMarker.Function=5]="Function",ByteMarker[ByteMarker.Null=6]="Null",ByteMarker[ByteMarker.Number=7]="Number",ByteMarker[ByteMarker.Object=8]="Object",ByteMarker[ByteMarker.RegExp=9]="RegExp",ByteMarker[ByteMarker.String=10]="String",ByteMarker[ByteMarker.Symbol=11]="Symbol",ByteMarker[ByteMarker.TypeArray=12]="TypeArray",ByteMarker[ByteMarker.Undefined=13]="Undefined"})(ByteMarker||(ByteMarker={}));var Accumulator=BigInt("14695981039346656037"),[Prime,Size]=[BigInt("1099511628211"),BigInt("18446744073709551616")],Bytes=Array.from({length:256}).map((_,i)=>BigInt(i)),F64=new Float64Array(1),F64In=new DataView(F64.buffer),F64Out=new Uint8Array(F64.buffer);function FNV1A64_OP(byte){Accumulator=Accumulator^Bytes[byte],Accumulator=Accumulator*Prime%Size}function FromArray(value){FNV1A64_OP(ByteMarker.Array);for(let item of value)FromValue(item)}function FromBigInt(value){FNV1A64_OP(ByteMarker.BigInt),F64In.setBigInt64(0,value);for(let byte of F64Out)FNV1A64_OP(byte)}function FromBoolean(value){FNV1A64_OP(ByteMarker.Boolean),FNV1A64_OP(value?1:0)}function FromConstructor(value){FNV1A64_OP(ByteMarker.Constructor),FromValue(value.toString())}function FromDate(value){FNV1A64_OP(ByteMarker.Date),FromValue(value.getTime())}function FromFunction(value){FNV1A64_OP(ByteMarker.Function),FromValue(value.toString())}function FromNull(_value){FNV1A64_OP(ByteMarker.Null)}function FromNumber(value){FNV1A64_OP(ByteMarker.Number),F64In.setFloat64(0,value,!0);for(let byte of F64Out)FNV1A64_OP(byte)}function FromObject(value){FNV1A64_OP(ByteMarker.Object);for(let key of InstanceKeys(value).sort())FromValue(key),FromValue(value[key])}function FromRegExp(value){FNV1A64_OP(ByteMarker.RegExp),FromString(value.toString())}var encoder=new TextEncoder;function FromString(value){FNV1A64_OP(ByteMarker.String);for(let byte of encoder.encode(value))FNV1A64_OP(byte)}function FromSymbol(value){FNV1A64_OP(ByteMarker.Symbol),FromValue(value.toString())}function FromTypeArray(value){FNV1A64_OP(ByteMarker.TypeArray);let buffer=new Uint8Array(value.buffer);for(let i=0;i<buffer.length;i++)FNV1A64_OP(buffer[i])}function FromUndefined(_value){return FNV1A64_OP(ByteMarker.Undefined)}function FromValue(value){return IsTypeArray(value)?FromTypeArray(value):IsDate(value)?FromDate(value):IsRegExp(value)?FromRegExp(value):IsBoolean2(value)?FromBoolean(value.valueOf()):IsString2(value)?FromString(value.valueOf()):IsNumber2(value)?FromNumber(value.valueOf()):IsIEEE754(value)?FromNumber(value):IsArray(value)?FromArray(value):IsBoolean(value)?FromBoolean(value):IsBigInt(value)?FromBigInt(value):IsConstructor(value)?FromConstructor(value):IsNull(value)?FromNull(value):IsObject(value)?FromObject(value):IsString(value)?FromString(value):IsSymbol(value)?FromSymbol(value):IsUndefined(value)?FromUndefined(value):IsFunction(value)?FromFunction(value):Unreachable()}function HashCode(value){return Accumulator=BigInt("14695981039346656037"),FromValue(value),Accumulator}function Hash(value){return HashCode(value).toString(16).padStart(16,"0")}function IsValid5(schema){return!IsEqual(schema.uniqueItems,!1)}function CheckUniqueItems(_stack,_context,schema,value){if(!IsValid5(schema))return!0;let set=new Set(value.map(Hash)).size,isLength=value.length;return IsEqual(set,isLength)}function ErrorUniqueItems(_stack,context,schemaPath,instancePath,schema,value){if(!IsValid5(schema))return!0;let set=new Set,duplicateItems=value.reduce((result,value,index)=>{let hash=Hash(value);if(set.has(hash))return[...result,index];return set.add(hash),result},[]);return IsEqual(duplicateItems.length,0)||context.AddError("uniqueItems",schemaPath,instancePath,{duplicateItems})}function CheckSchemaPushStack(stack,context,schema,value){return context.Push()&&CheckSchema(stack,context,schema,value)&&context.Pop()}function CheckSchema(stack,context,schema,value){let current=NextStack(stack,schema);return IsSchemaBoolean(schema)?CheckSchemaBoolean(current,context,schema,value):(!IsType(schema)||CheckType(current,context,schema,value))&&(!(IsObject(value)&&!IsArray(value))||(!IsRequired(schema)||CheckRequired(current,context,schema,value))&&(!IsAdditionalProperties(schema)||CheckAdditionalProperties(current,context,schema,value))&&(!IsDependencies(schema)||CheckDependencies(current,context,schema,value))&&(!IsDependentRequired(schema)||CheckDependentRequired(current,context,schema,value))&&(!IsDependentSchemas(schema)||CheckDependentSchemas(current,context,schema,value))&&(!IsPatternProperties(schema)||CheckPatternProperties(current,context,schema,value))&&(!IsProperties(schema)||CheckProperties(current,context,schema,value))&&(!IsPropertyNames(schema)||CheckPropertyNames(current,context,schema,value))&&(!IsMinProperties(schema)||CheckMinProperties(current,context,schema,value))&&(!IsMaxProperties(schema)||CheckMaxProperties(current,context,schema,value)))&&(!IsArray(value)||(!IsAdditionalItems(schema)||CheckAdditionalItems(current,context,schema,value))&&(!IsContains(schema)||CheckContains(current,context,schema,value))&&(!IsItems(schema)||CheckItems(current,context,schema,value))&&(!IsMinContains(schema)||CheckMinContains(current,context,schema,value))&&(!IsMaxContains(schema)||CheckMaxContains(current,context,schema,value))&&(!IsMinItems(schema)||CheckMinItems(current,context,schema,value))&&(!IsMaxItems(schema)||CheckMaxItems(current,context,schema,value))&&(!IsPrefixItems(schema)||CheckPrefixItems(current,context,schema,value))&&(!IsUniqueItems(schema)||CheckUniqueItems(current,context,schema,value)))&&(!IsString(value)||(!IsMinLength3(schema)||CheckMinLength(current,context,schema,value))&&(!IsMaxLength3(schema)||CheckMaxLength(current,context,schema,value))&&(!IsFormat(schema)||CheckFormat(current,context,schema,value))&&(!IsPattern(schema)||CheckPattern(current,context,schema,value)))&&(!(IsNumber(value)||IsBigInt(value))||(!IsExclusiveMinimum(schema)||CheckExclusiveMinimum(current,context,schema,value))&&(!IsExclusiveMaximum(schema)||CheckExclusiveMaximum(current,context,schema,value))&&(!IsMinimum(schema)||CheckMinimum(current,context,schema,value))&&(!IsMaximum(schema)||CheckMaximum(current,context,schema,value))&&(!IsMultipleOf2(schema)||CheckMultipleOf(current,context,schema,value)))&&(!IsRef(schema)||CheckRef(current,context,schema,value))&&(!IsRecursiveRef(schema)||CheckRecursiveRef(current,context,schema,value))&&(!IsDynamicRef(schema)||CheckDynamicRef(current,context,schema,value))&&(!IsConst(schema)||CheckConst(current,context,schema,value))&&(!IsEnum(schema)||CheckEnum(current,context,schema,value))&&(!IsIf(schema)||CheckIf(current,context,schema,value))&&(!IsNot(schema)||CheckNot(current,context,schema,value))&&(!IsAllOf(schema)||CheckAllOf(current,context,schema,value))&&(!IsAnyOf(schema)||CheckAnyOf(current,context,schema,value))&&(!IsOneOf(schema)||CheckOneOf(current,context,schema,value))&&(!IsUnevaluatedItems(schema)||(!IsArray(value)||CheckUnevaluatedItems(current,context,schema,value)))&&(!IsUnevaluatedProperties(schema)||(!IsObject(value)||CheckUnevaluatedProperties(current,context,schema,value)))&&(!IsRefine(schema)||CheckRefine(current,context,schema,value))}function ErrorSchemaPushStack(stack,context,schemaPath,instancePath,schema,value){return context.Push()&&ErrorSchema(stack,context,schemaPath,instancePath,schema,value)&&context.Pop()}function ErrorSchema(stack,context,schemaPath,instancePath,schema,value){if(context.AtCapacity())return!1;let current=NextStack(stack,schema);return IsSchemaBoolean(schema)?ErrorSchemaBoolean(current,context,schemaPath,instancePath,schema,value):!!(+(!IsType(schema)||ErrorType(current,context,schemaPath,instancePath,schema,value))&+(!(IsObject(value)&&!IsArray(value))||!!(+(!IsRequired(schema)||ErrorRequired(current,context,schemaPath,instancePath,schema,value))&+(!IsAdditionalProperties(schema)||ErrorAdditionalProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsDependencies(schema)||ErrorDependencies(current,context,schemaPath,instancePath,schema,value))&+(!IsDependentRequired(schema)||ErrorDependentRequired(current,context,schemaPath,instancePath,schema,value))&+(!IsDependentSchemas(schema)||ErrorDependentSchemas(current,context,schemaPath,instancePath,schema,value))&+(!IsPatternProperties(schema)||ErrorPatternProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsProperties(schema)||ErrorProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsPropertyNames(schema)||ErrorPropertyNames(current,context,schemaPath,instancePath,schema,value))&+(!IsMinProperties(schema)||ErrorMinProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxProperties(schema)||ErrorMaxProperties(current,context,schemaPath,instancePath,schema,value))))&+(!IsArray(value)||!!(+(!IsAdditionalItems(schema)||ErrorAdditionalItems(current,context,schemaPath,instancePath,schema,value))&+(!IsContains(schema)||ErrorContains(current,context,schemaPath,instancePath,schema,value))&+(!IsItems(schema)||ErrorItems(current,context,schemaPath,instancePath,schema,value))&+(!IsMinContains(schema)||ErrorMinContains(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxContains(schema)||ErrorMaxContains(current,context,schemaPath,instancePath,schema,value))&+(!IsMinItems(schema)||ErrorMinItems(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxItems(schema)||ErrorMaxItems(current,context,schemaPath,instancePath,schema,value))&+(!IsPrefixItems(schema)||ErrorPrefixItems(current,context,schemaPath,instancePath,schema,value))&+(!IsUniqueItems(schema)||ErrorUniqueItems(current,context,schemaPath,instancePath,schema,value))))&+(!IsString(value)||!!(+(!IsMinLength3(schema)||ErrorMinLength(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxLength3(schema)||ErrorMaxLength(current,context,schemaPath,instancePath,schema,value))&+(!IsFormat(schema)||ErrorFormat(current,context,schemaPath,instancePath,schema,value))&+(!IsPattern(schema)||ErrorPattern(current,context,schemaPath,instancePath,schema,value))))&+(!(IsNumber(value)||IsBigInt(value))||!!(+(!IsExclusiveMinimum(schema)||ErrorExclusiveMinimum(current,context,schemaPath,instancePath,schema,value))&+(!IsExclusiveMaximum(schema)||ErrorExclusiveMaximum(current,context,schemaPath,instancePath,schema,value))&+(!IsMinimum(schema)||ErrorMinimum(current,context,schemaPath,instancePath,schema,value))&+(!IsMaximum(schema)||ErrorMaximum(current,context,schemaPath,instancePath,schema,value))&+(!IsMultipleOf2(schema)||ErrorMultipleOf(current,context,schemaPath,instancePath,schema,value))))&+(!IsRef(schema)||ErrorRef(current,context,schemaPath,instancePath,schema,value))&+(!IsRecursiveRef(schema)||ErrorRecursiveRef(current,context,schemaPath,instancePath,schema,value))&+(!IsDynamicRef(schema)||ErrorDynamicRef(current,context,schemaPath,instancePath,schema,value))&+(!IsConst(schema)||ErrorConst(current,context,schemaPath,instancePath,schema,value))&+(!IsEnum(schema)||ErrorEnum(current,context,schemaPath,instancePath,schema,value))&+(!IsIf(schema)||ErrorIf(current,context,schemaPath,instancePath,schema,value))&+(!IsNot(schema)||ErrorNot(current,context,schemaPath,instancePath,schema,value))&+(!IsAllOf(schema)||ErrorAllOf(current,context,schemaPath,instancePath,schema,value))&+(!IsAnyOf(schema)||ErrorAnyOf(current,context,schemaPath,instancePath,schema,value))&+(!IsOneOf(schema)||ErrorOneOf(current,context,schemaPath,instancePath,schema,value))&+(!IsUnevaluatedItems(schema)||(!IsArray(value)||ErrorUnevaluatedItems(current,context,schemaPath,instancePath,schema,value)))&+(!IsUnevaluatedProperties(schema)||(!IsObject(value)||ErrorUnevaluatedProperties(current,context,schemaPath,instancePath,schema,value))))&&(!IsRefine(schema)||ErrorRefine(current,context,schemaPath,instancePath,schema,value))}function en_US(error){switch(error.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"dependentRequired":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"exclusiveMinimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"format":return`must match format "${error.params.format}"`;case"if":return`must match "${error.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${error.params.limit} items`;case"maxLength":return`must not have more than ${error.params.limit} characters`;case"maxProperties":return`must not have more than ${error.params.limit} properties`;case"maximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"minItems":return`must not have fewer than ${error.params.limit} items`;case"minLength":return`must not have fewer than ${error.params.limit} characters`;case"minProperties":return`must not have fewer than ${error.params.limit} properties`;case"minimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"multipleOf":return`must be multiple of ${error.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${error.params.pattern}"`;case"propertyNames":return`property names ${error.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${error.params.requiredProperties.join(", ")}`;case"type":return typeof error.params.type==="string"?`must be ${error.params.type}`:`must be either ${error.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return error.params.message;default:return"an unknown validation error occurred"}}var locale=en_US;function Get3(){return locale}var Metrics={assign:0,create:0,clone:0,discard:0,update:0};function Freeze(value){return Get().immutableTypes?Object.freeze(value):value}function Assign(left,right){return Metrics.assign+=1,Freeze({...left,...right})}function FromClassInstance(value){return value}function IsSchemaObject2(value){return HasPropertyKey(value,"~kind")||HasPropertyKey(value,"~unsafe")}function FromSchemaObject(value){let result={};for(let key of Keys(value)){if(IsUnsafePropertyKey(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor.value=FromValue2(descriptor.value),IsEqual(descriptor.enumerable,!0))result[key]=descriptor.value;else Object.defineProperty(result,key,descriptor)}return result}function FromPlainObject(value){let result={};for(let key of Keys(value)){if(IsUnsafePropertyKey(key))continue;result[key]=FromValue2(value[key])}for(let key of Symbols(value))result[key]=FromValue2(value[key]);return result}function FromObject2(value){return IsClassInstance(value)?FromClassInstance(value):IsSchemaObject2(value)?FromSchemaObject(value):FromPlainObject(value)}function FromArray2(value){return value.map((element)=>FromValue2(element))}function FromTypedArray(value){return value.slice()}function FromRegExp2(value){return new RegExp(value.source,value.flags)}function FromMap(value){return new Map(FromValue2([...value.entries()]))}function FromSet(value){return new Set(FromValue2([...value.values()]))}function FromValue2(value){return IsTypeArray(value)?FromTypedArray(value):IsRegExp(value)?FromRegExp2(value):IsMap(value)?FromMap(value):IsSet(value)?FromSet(value):IsArray(value)?FromArray2(value):IsObject(value)?FromObject2(value):value}function Clone(value){return Metrics.clone+=1,FromValue2(value)}function MergeHidden(left,right){for(let key of Object.keys(right))Object.defineProperty(left,key,{configurable:!0,writable:!0,enumerable:!1,value:right[key]});return left}function Merge(left,right){return{...left,...right}}function Create(hidden,enumerable,options={}){Metrics.create+=1;let withOptions=Merge(enumerable,options),withHidden=Get().enumerableKind?Merge(withOptions,hidden):MergeHidden(withOptions,hidden);return Freeze(withHidden)}function Discard(value,propertyKeys){Metrics.discard+=1;let result={};for(let key of Keys(value)){if(propertyKeys.includes(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);descriptor.value=Clone(descriptor.value),Object.defineProperty(result,key,descriptor)}return Freeze(result)}function Update(current,hidden,enumerable){Metrics.update+=1;let settings=Get(),result=Clone(current);for(let key of Object.keys(hidden))Object.defineProperty(result,key,{configurable:!0,writable:!0,enumerable:settings.enumerableKind,value:hidden[key]});for(let key of Object.keys(enumerable))Object.defineProperty(result,key,{configurable:!0,enumerable:!0,writable:!0,value:enumerable[key]});return Freeze(result)}function Errors(...args){let[context,schema,value]=Match(args,{3:(context,schema,value)=>[context,schema,value],2:(schema,value)=>[{},schema,value]}),stack=Stack(context,schema),errorContext=new ErrorContext,result=ErrorSchema(stack,errorContext,"#","",schema,value),errors=errorContext.GetErrors(),locale=Get3(),localized=errors.map((error)=>({...error,message:locale(error)}));return[result,localized]}var TempMaxErrors=0;function EnableParseErrors(){let settings=Get();TempMaxErrors=settings.maxErrors,settings.maxErrors=settings.maxParseErrors}function DisableParseErrors(){let settings=Get();settings.maxErrors=TempMaxErrors}function Check(...args){let[context,schema,value]=Match(args,{3:(context,schema,value)=>[context,schema,value],2:(schema,value)=>[{},schema,value]}),stack=Stack(context,schema),checkContext=new CheckContext;return CheckSchema(stack,checkContext,schema,value)}function Check2(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return Check(context,type,value)}function Errors2(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]}),[_,errors]=Errors(context,type,value);return errors}class AssertError extends Error{constructor(source,value,errors){super(source);Object.defineProperty(this,"cause",{value:{source,errors,value},writable:!1,configurable:!1,enumerable:!1})}}function IsKind(value,kind){return IsObject(value)&&HasPropertyKey(value,"~kind")&&IsEqual(value["~kind"],kind)}function IsSchema2(value){return IsObject(value)}function Deferred(action,parameters,options){return Create({"~kind":"Deferred"},{type:"deferred",action,parameters,options},{})}function IsDeferred(value){return IsKind(value,"Deferred")}function AddReadonlyOperation(type){return Update(type,{"~readonly":!0},{})}function AddReadonlyAction(type,options){return Update(AddReadonlyOperation(type),{},options)}function AddReadonlyInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddReadonlyAction(instantiatedType,options)}function AddOptionalOperation(type){return Update(type,{"~optional":!0},{})}function AddOptionalAction(type,options){return Update(AddOptionalOperation(type),{},options)}function AddOptionalInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddOptionalAction(instantiatedType,options)}function _Array_(items,options){return Create({"~kind":"Array"},{type:"array",items},options)}function IsArray2(value){return IsKind(value,"Array")}function ArrayOptions(type){return Discard(type,["~kind","type","items"])}function Constructor(parameters,instanceType,options={}){return Create({"~kind":"Constructor"},{type:"constructor",parameters,instanceType},options)}function IsConstructor2(value){return IsKind(value,"Constructor")}function ConstructorOptions(type){return Discard(type,["~kind","type","parameters","instanceType"])}function _Function_(parameters,returnType,options={}){return Create({["~kind"]:"Function"},{type:"function",parameters,returnType},options)}function IsFunction2(value){return IsKind(value,"Function")}function FunctionOptions(type){return Discard(type,["~kind","type","parameters","returnType"])}function Ref2(ref,options){return Create({["~kind"]:"Ref"},{$ref:ref},options)}function IsRef2(value){return IsKind(value,"Ref")}function Generic(parameters,expression){return Create({"~kind":"Generic"},{type:"generic",parameters,expression})}function IsGeneric(value){return IsKind(value,"Generic")}function Any(options){return Create({["~kind"]:"Any"},{},options)}function IsAny(value){return IsKind(value,"Any")}var NeverPattern="(?!)";function Never(options){return Create({"~kind":"Never"},{not:{}},options)}function IsNever(value){return IsKind(value,"Never")}function AddOptional(type,options={}){return AddOptionalAction(type,options)}function Optional(type){return AddOptional(type)}function IsOptional(value){return IsSchema2(value)&&HasPropertyKey(value,"~optional")}function RequiredArray(properties){return Keys(properties).filter((key)=>!IsOptional(properties[key]))}function PropertyKeys(properties){return Keys(properties)}function PropertyValues(properties){return Values(properties)}function _Object_(properties,options={}){let requiredKeys=RequiredArray(properties),required=requiredKeys.length>0?{required:requiredKeys}:{};return Create({"~kind":"Object"},{type:"object",...required,properties},options)}function IsObject2(value){return IsKind(value,"Object")}function ObjectOptions(type){return Discard(type,["~kind","type","properties","required"])}function Unknown(options){return Create({["~kind"]:"Unknown"},{},options)}function IsUnknown(value){return IsKind(value,"Unknown")}function Cyclic($defs,$ref,options){let defs=Keys($defs).reduce((result,key)=>({...result,[key]:Update($defs[key],{},{$id:key})}),{});return Create({["~kind"]:"Cyclic"},{$defs:defs,$ref},options)}function IsCyclic(value){return IsKind(value,"Cyclic")}function IsUnsafe(value){return IsObjectNotArray(value)&&HasPropertyKey(value,"~unsafe")&&IsNull(value["~unsafe"])}function IsInfer(value){return IsKind(value,"Infer")}function Dependent(if_,then_,else_,options={}){return Create({"~kind":"Dependent"},{if:if_,then:then_,else:else_},options)}function IsDependent(value){return IsKind(value,"Dependent")}function DependentOptions(type){return Discard(type,["~kind","if","then","else"])}function IsTypeScriptEnumLike(value){return IsObjectNotArray(value)}function TypeScriptEnumToEnumValues(type){return Keys(type).filter((key)=>isNaN(key)).reduce((result,key)=>[...result,type[key]],[])}function Enum(value,options){let values=IsTypeScriptEnumLike(value)?TypeScriptEnumToEnumValues(value):value;return Create({"~kind":"Enum"},{enum:values},options)}function IsEnum2(value){return IsKind(value,"Enum")}function Intersect(types,options={}){return Create({"~kind":"Intersect"},{allOf:types},options)}function IsIntersect(value){return IsKind(value,"Intersect")}function IntersectOptions(type){return Discard(type,["~kind","allOf"])}function IsCodec(value){return IsSchema2(value)&&HasPropertyKey(value,"~codec")&&IsObject(value["~codec"])&&HasPropertyKey(value["~codec"],"encode")&&HasPropertyKey(value["~codec"],"decode")}function IsImmutable(value){return IsSchema2(value)&&HasPropertyKey(value,"~immutable")}function AddReadonly(type,options={}){return AddReadonlyAction(type,options)}function IsReadonly(value){return IsSchema2(value)&&HasPropertyKey(value,"~readonly")}var BigIntPattern="-?(?:0|[1-9][0-9]*)n";function BigInt2(options){return Create({"~kind":"BigInt"},{type:"bigint"},options)}function IsBigInt2(value){return IsKind(value,"BigInt")}function Boolean2(options){return Create({"~kind":"Boolean"},{type:"boolean"},options)}function IsBoolean3(value){return IsKind(value,"Boolean")}var IntegerPattern="-?(?:0|[1-9][0-9]*)";function Integer(options){return Create({"~kind":"Integer"},{type:"integer"},options)}function IsInteger2(value){return IsKind(value,"Integer")}class InvalidLiteralValue extends Error{constructor(value){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value},writable:!1,configurable:!1,enumerable:!1})}}function LiteralTypeName(value){return IsBigInt(value)?"bigint":IsBoolean(value)?"boolean":IsNumber(value)?"number":IsString(value)?"string":(()=>{throw new InvalidLiteralValue(value)})()}function Literal(value,options){return Create({"~kind":"Literal"},{type:LiteralTypeName(value),const:value},options)}function IsLiteralValue(value){return IsBigInt(value)||IsBoolean(value)||IsNumber(value)||IsString(value)}function IsLiteralBigInt(value){return IsLiteral(value)&&IsBigInt(value.const)}function IsLiteralBoolean(value){return IsLiteral(value)&&IsBoolean(value.const)}function IsLiteralNumber(value){return IsLiteral(value)&&IsNumber(value.const)}function IsLiteralString(value){return IsLiteral(value)&&IsString(value.const)}function IsLiteral(value){return IsKind(value,"Literal")}function Null(options){return Create({"~kind":"Null"},{type:"null"},options)}function IsNull2(value){return IsKind(value,"Null")}var NumberPattern="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Number2(options){return Create({"~kind":"Number"},{type:"number"},options)}function IsNumber3(value){return IsKind(value,"Number")}function Symbol2(options){return Create({"~kind":"Symbol"},{type:"symbol"},options)}function IsSymbol2(value){return IsKind(value,"Symbol")}var StringPattern=".*";function String2(options){return Create({"~kind":"String"},{type:"string"},options)}function IsString3(value){return IsKind(value,"String")}function Union(anyOf,options={}){return Create({"~kind":"Union"},{anyOf},options)}function IsUnion(value){return IsKind(value,"Union")}function UnionOptions(type){return Discard(type,["~kind","anyOf"])}function ParsePatternIntoTypes(pattern){let parsed=Pattern(pattern);return IsEqual(parsed.length,2)?parsed[0]:[]}function FromLiteral(_value){return!0}function FromTypesReduce(types){return ShiftLeft(types,(left,right)=>FromType(left)?FromTypesReduce(right):!1,()=>!0)}function FromTypes(types){return IsEqual(types.length,0)?!1:FromTypesReduce(types)}function FromType(type){return IsUnion(type)?FromTypes(type.anyOf):IsLiteral(type)?FromLiteral(type.const):!1}function IsTemplateLiteralFinite(types){return FromTypes(types)}function TemplateLiteralCreate(pattern){return Create({["~kind"]:"TemplateLiteral"},{type:"string",pattern},{})}function FromLiteralPush(variants,value,result=[]){return ShiftLeft(variants,(left,right)=>FromLiteralPush(right,value,[...result,`${left}${value}`]),()=>result)}function FromLiteral2(variants,value){return IsEqual(variants.length,0)?[`${value}`]:FromLiteralPush(variants,value)}function FromUnion(variants,types,result=[]){return ShiftLeft(types,(left,right)=>FromUnion(variants,right,[...result,...FromType2(variants,left)]),()=>result)}function FromType2(variants,type){return IsUnion(type)?FromUnion(variants,type.anyOf):IsLiteral(type)?FromLiteral2(variants,type.const):Unreachable()}function DecodeFromSpan(variants,types){return ShiftLeft(types,(left,right)=>DecodeFromSpan(FromType2(variants,left),right),()=>variants)}function VariantsToLiterals(variants){return variants.map((variant)=>Literal(variant))}function DecodeTypesAsUnion(types){let variants=DecodeFromSpan([],types),literals=VariantsToLiterals(variants);return Union(literals)}function DecodeTypes(types){return IsEqual(types.length,0)?Unreachable():IsEqual(types.length,1)&&IsLiteral(types[0])?types[0]:DecodeTypesAsUnion(types)}function TemplateLiteralDecodeUnsafe(pattern){let types=ParsePatternIntoTypes(pattern);return IsEqual(types.length,0)?String2():IsTemplateLiteralFinite(types)?DecodeTypes(types):TemplateLiteralCreate(pattern)}function TemplateLiteralDecode(pattern){let decoded=TemplateLiteralDecodeUnsafe(pattern);return IsTemplateLiteral(decoded)?String2():decoded}function CreateRecord(key,value){let patternProperties={[key]:value};return Create({["~kind"]:"Record"},{type:"object",patternProperties})}function FromAnyKey(value){return CreateRecord(StringKey,value)}function FromBooleanKey(value){return _Object_({true:value,false:value})}function Tuple(types,options={}){let[items,minItems,additionalItems]=[types,types.length,!1];return Create({["~kind"]:"Tuple"},{type:"array",additionalItems,items,minItems},options)}function IsTuple(value){return IsKind(value,"Tuple")}function TupleOptions(type){return Discard(type,["~kind","type","items","minItems","additionalItems"])}function RemoveReadonlyOperation(type){return Discard(type,["~readonly"])}function RemoveReadonlyAction(type,options){return Update(RemoveReadonlyOperation(type),{},options)}function RemoveReadonlyInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveReadonlyAction(instantiatedType,options)}function RemoveReadonly(type,options={}){return RemoveReadonlyAction(type,options)}function RemoveOptionalOperation(type){return Discard(type,["~optional"])}function RemoveOptionalAction(type,options){return Update(RemoveOptionalOperation(type),{},options)}function RemoveOptionalInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveOptionalAction(instantiatedType,options)}function RemoveOptional(type,options={}){return RemoveOptionalAction(type,options)}function TupleElementsToProperties(types){return types.reduceRight((result,right,index)=>({[index]:right,...result}),{})}function TupleToObject(type){let properties=TupleElementsToProperties(type.items);return _Object_(properties)}function CanComposite(type){return IsObject2(type)||IsTuple(type)}function IsReadonlyProperty(left,right){return IsReadonly(left)?IsReadonly(right)?!0:!1:!1}function IsOptionalProperty(left,right){return IsOptional(left)?IsOptional(right)?!0:!1:!1}function CompositeProperty(left,right){let isReadonly=IsReadonlyProperty(left,right),isOptional=IsOptionalProperty(left,right),evaluated=EvaluateIntersect([left,right]),property=RemoveReadonly(RemoveOptional(evaluated));return isReadonly&&isOptional?AddReadonly(AddOptional(property)):isReadonly&&!isOptional?AddReadonly(property):!isReadonly&&isOptional?AddOptional(property):property}function CompositePropertyKey(left,right,key){return key in left?key in right?CompositeProperty(left[key],right[key]):left[key]:(key in right)?right[key]:Never()}function CompositeProperties(left,right){return[...new Set([...Keys(left),...Keys(right)])].reduce((result,key)=>({...result,[key]:CompositePropertyKey(left,right,key)}),{})}function GetProperties(type){return IsObject2(type)?type.properties:IsTuple(type)?TupleElementsToProperties(type.items):{}}function Composite(left,right){let leftProperties=GetProperties(left),rightProperties=GetProperties(right),properties=CompositeProperties(leftProperties,rightProperties);return _Object_(properties)}function NarrowCompareRule(left,right){let result=Compare(left,right);return IsEqual(result,CompareResultLeftInside)?left:IsEqual(result,CompareResultRightInside)?right:IsEqual(result,CompareResultEqual)?right:Never()}function NarrowCompositeRule(left,right){let canCompositeLeft=CanComposite(left),canCompositeRight=CanComposite(right);return canCompositeLeft&&canCompositeRight?Composite(left,right):canCompositeLeft&&!canCompositeRight?left:!canCompositeLeft&&canCompositeRight?right:NarrowCompareRule(left,right)}function Narrow(left,right){return IsNever(left)?left:IsAny(left)?left:IsUnknown(left)?right:IsNever(right)?right:IsAny(right)?right:IsUnknown(right)?left:NarrowCompositeRule(left,right)}function ShouldEvaluate(left,right){return IsUnion(left)||IsUnion(right)}function DistributeOperation(left,right){let evaluatedLeft=EvaluateType(left),evaluatedRight=EvaluateType(right);return ShouldEvaluate(evaluatedLeft,evaluatedRight)?EvaluateIntersect([evaluatedLeft,evaluatedRight]):Narrow(evaluatedLeft,evaluatedRight)}function DistributeType(type,types,result=[]){return ShiftLeft(types,(left,right)=>DistributeType(type,right,[...result,DistributeOperation(left,type)]),()=>IsEqual(result.length,0)?[type]:result)}function DistributeUnion(types,distribution,result=[]){return ShiftLeft(types,(left,right)=>DistributeUnion(right,distribution,[...result,...Distribute([left],distribution)]),()=>result)}function Distribute(types,result=[]){return ShiftLeft(types,(left,right)=>IsUnion(left)?Distribute(right,DistributeUnion(left.anyOf,result)):Distribute(right,DistributeType(left,result)),()=>result)}function ExcludeType(left,right){let check=Extends({},left,right);return IsExtendsTrueLike(check)?[]:[left]}function ExcludeUnion(left,right,result=[]){return ShiftLeft(left,(head,tail)=>ExcludeUnion(tail,right,[...result,...ExcludeType(head,right)]),()=>result)}function ExcludeOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExcludeUnion(canonical,right);return EvaluateUnion(remaining)}function EvaluateDependent(if_,then_,else_){let intersected=EvaluateIntersect([if_,then_]),excluded=ExcludeOperation(else_,if_);return EvaluateUnion([intersected,excluded])}function EvaluateEnum(values,result=[]){return ShiftLeft(values,(left,right)=>EvaluateEnum(right,[...result,Literal(left)]),()=>EvaluateUnion(result))}function EvaluateIntersect(types){let distribution=Distribute(types),broadend=Broaden(distribution);return EvaluateUnion(broadend)}function EvaluateTemplateLiteral(pattern){let evaluated=TemplateLiteralDecode(pattern);return EvaluateType(evaluated)}function EvaluateUnion(types){let broadend=Broaden(types);return EvaluateUnionFast(broadend)}function EvaluateType(type){return IsDependent(type)?EvaluateDependent(type.if,type.then,type.else):IsEnum2(type)?EvaluateEnum(type.enum):IsIntersect(type)?EvaluateIntersect(type.allOf):IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsUnion(type)?EvaluateUnion(type.anyOf):type}function EvaluateUnionFast(types){return IsEqual(types.length,1)?types[0]:IsEqual(types.length,0)?Never():Union(types)}function FromEnumKey(values,value){let unionKey=EvaluateEnum(values);return FromKey(unionKey,value)}function FromIntegerKey(_key,value){return CreateRecord(IntegerKey,value)}function FromIntersectKey(types,value){let evaluatedKey=EvaluateIntersect(types);return FromKey(evaluatedKey,value)}function FromLiteralKey(key,value){return IsString(key)||IsNumber(key)?_Object_({[key]:value}):IsEqual(key,!1)?_Object_({false:value}):IsEqual(key,!0)?_Object_({true:value}):_Object_({})}function FromNumberKey(_key,value){return CreateRecord(NumberKey,value)}function FromStringKey(key,value){return HasPropertyKey(key,"pattern")&&(IsString(key.pattern)||key.pattern instanceof RegExp)?CreateRecord(key.pattern.toString(),value):CreateRecord(StringKey,value)}function FromTemplateKey(pattern,value){let types=ParsePatternIntoTypes(pattern);return IsTemplateLiteralFinite(types)?FromKey(EvaluateTemplateLiteral(pattern),value):CreateRecord(pattern,value)}function FlattenType(type){return IsUnion(type)?Flatten(type.anyOf):[type]}function Flatten(types,result=[]){return ShiftLeft(types,(left,right)=>Flatten(right,[...result,...FlattenType(left)]),()=>result)}function StringOrNumberCheck(types){return types.some((type)=>IsString3(type)||IsNumber3(type)||IsInteger2(type))}function TryBuildRecord(types,value){return IsEqual(StringOrNumberCheck(types),!0)?CreateRecord(StringKey,value):void 0}function CreateProperties(types,value){return types.reduce((result,left)=>IsLiteral(left)&&(IsString(left.const)||IsNumber(left.const))?{...result,[left.const]:value}:result,{})}function CreateObject(types,value){let properties=CreateProperties(types,value);return _Object_(properties)}function FromUnionKey(types,value){let flattened=Flatten(types),record=TryBuildRecord(flattened,value);return IsSchema2(record)?record:CreateObject(flattened,value)}function FromKey(key,value){return IsAny(key)?FromAnyKey(value):IsBoolean3(key)?FromBooleanKey(value):IsEnum2(key)?FromEnumKey(key.enum,value):IsInteger2(key)?FromIntegerKey(key,value):IsIntersect(key)?FromIntersectKey(key.allOf,value):IsLiteral(key)?FromLiteralKey(key.const,value):IsNumber3(key)?FromNumberKey(key,value):IsUnion(key)?FromUnionKey(key.anyOf,value):IsString3(key)?FromStringKey(key,value):IsTemplateLiteral(key)?FromTemplateKey(key.pattern,value):_Object_({})}function RecordAction(key,value,options){return CanInstantiate([key])?Update(FromKey(key,value),{},options):RecordDeferred(key,value,options)}function RecordInstantiate(context,state,key,value,options){let instantiatedKey=InstantiateType(context,state,key),instantiatedValue=InstantiateType(context,state,value);return RecordAction(instantiatedKey,instantiatedValue,options)}var IntegerKey=`^${IntegerPattern}$`,NumberKey=`^${NumberPattern}$`,StringKey=`^${StringPattern}$`;function RecordDeferred(key,value,options={}){return Deferred("Record",[key,value],options)}function Record(key,value,options={}){return RecordAction(key,value,options)}function RecordFromPattern(pattern,value){return CreateRecord(pattern,value)}function RecordPatternToType(pattern){return IsEqual(pattern,StringKey)?String2():IsEqual(pattern,IntegerKey)?Integer():IsEqual(pattern,NumberKey)?Number2():TemplateLiteralDecodeUnsafe(pattern)}function RecordPattern(type){return Keys(type.patternProperties)[0]}function RecordKey(type){let pattern=RecordPattern(type);return RecordPatternToType(pattern)}function RecordValue(type){return type.patternProperties[RecordPattern(type)]}function IsRecord(value){return IsKind(value,"Record")}function Rest(type){return Create({"~kind":"Rest"},{type:"rest",items:type},{})}function IsRest(value){return IsKind(value,"Rest")}function IsThis(value){return IsKind(value,"This")}function Undefined(options){return Create({"~kind":"Undefined"},{type:"undefined"},options)}function IsUndefined2(value){return IsKind(value,"Undefined")}function IsVoid(value){return IsKind(value,"Void")}function PatternBigIntMapping(input){return BigInt2()}function PatternStringMapping(input){return String2()}function PatternNumberMapping(input){return Number2()}function PatternIntegerMapping(input){return Integer()}function PatternNeverMapping(input){return Never()}function PatternTextMapping(input){return Literal(input)}function PatternBaseMapping(input){return input}function PatternGroupMapping(input){return Union(input[1])}function PatternUnionMapping(input){return input.length===3?[...input[0],...input[2]]:input.length===1?[...input[0]]:[]}function PatternTermMapping(input){return[input[0],...input[1]]}function PatternBodyMapping(input){return input}function PatternMapping(input){return input[1]}function IsMatch(value){return IsEqual(value.length,2)}function Match3(input,ok,fail){return IsMatch(input)?ok(input[0],input[1]):fail()}function TakeVariant(variant,input){return IsEqual(input.indexOf(variant),0)?[variant,input.slice(variant.length)]:[]}function Take(variants,input){for(let i=0;i<variants.length;i++){let result=TakeVariant(variants[i],input);if(IsMatch(result))return result}return[]}function Range(start,end){return Array.from({length:end-start+1},(_,i)=>String.fromCharCode(start+i))}var Alpha=[...Range(97,122),...Range(65,90)],Zero="0",NonZero=Range(49,57),Digit=[Zero,...NonZero],WhiteSpace=" ",NewLine=`
332
+ </Category_Context>`,resolvePromptAppend:resolveDeepHighCategoryPromptAppend,requiresModel:DEEP_HIGH_GATE_MODEL},{name:"quick",config:{model:"chatgpt-subscription/gpt-6-luna-fast",variant:"low"},description:"Trivial tasks - single file changes, typo fixes, simple modifications",callerGuidance:QUICK_CATEGORY_CALLER_GUIDANCE,promptAppend:QUICK_CATEGORY_PROMPT_APPEND},{name:"unspecified-low",config:{model:"anthropic/claude-sonnet-5-5",variant:"medium"},description:"Tasks that don't fit other categories, low effort required",callerGuidance:UNSPECIFIED_LOW_CATEGORY_CALLER_GUIDANCE,promptAppend:UNSPECIFIED_LOW_CATEGORY_PROMPT_APPEND},{name:"unspecified-high",config:{model:"anthropic/claude-opus-5-5",variant:"medium"},description:"Tasks that don't fit other categories, high effort required",callerGuidance:UNSPECIFIED_HIGH_CATEGORY_CALLER_GUIDANCE,promptAppend:UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND,resolvePromptAppend:resolveUnspecifiedHighCategoryPromptAppend}];var CATEGORY_FALLBACK_CHAINS={"visual-engineering":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],architect:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"}],ultrabrain:[{providers:["chatgpt-subscription","openai"],model:"gpt-6-astra",variant:"max"},{providers:["github-copilot"],model:"gpt-6-astra",variant:"max"},{providers:["chatgpt-subscription","openai","opencode"],model:"gpt-6-astra",variant:"max"},{providers:["chatgpt-subscription","openai"],model:"gpt-5.6-sol",variant:"max"},{providers:["github-copilot"],model:"gpt-5.6-sol",variant:"max"},{providers:["chatgpt-subscription","openai","opencode"],model:"gpt-5.6-sol",variant:"max"}],"deep-low":[{providers:["chatgpt-subscription","openai"],model:"gpt-6.1-sol",variant:"medium"},{providers:["chatgpt-subscription","openai"],model:"gpt-6.1-sol-fast",variant:"medium"},{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-5.6-sol",variant:"medium"},{providers:["chatgpt-subscription","openai"],model:"gpt-5.6-sol-fast",variant:"medium"}],"deep-high":[{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-6-astra",variant:"xhigh"}],artistry:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-fable-5-1",variant:"max"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],quick:[{providers:["chatgpt-subscription","openai"],model:"gpt-6-luna-fast",variant:"low"},{providers:["deepseek"],model:"deepseek-flash",variant:"off"},{providers:["qwen-token-plan","alibaba-token-plan","bailian-coding-plan"],model:"qwen3.6-flash",variant:"low"},{providers:["opencode-go"],model:"minimax-m3",variant:"max"},{providers:["opencode-go"],model:"minimax-m2.7",variant:"max"},{providers:["xai"],model:"grok-4.20-0309-non-reasoning"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot"],model:"claude-haiku-4-5",variant:"off"},{providers:["zai","zai-coding-cn"],model:"glm-5.3-flash",variant:"low"},{providers:["xiaomi"],model:"mimo-v2.6-flash",variant:"low"}],"unspecified-low":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-sonnet-5-5",variant:"medium"},{providers:["xiaomi","opencode-go"],model:"mimo-v2.6-pro",variant:"max"},{providers:["xai","github-copilot","opencode-go"],model:"grok-4.7",variant:"xhigh"},{providers:["chatgpt-subscription","openai","github-copilot","opencode"],model:"gpt-5.6-terra",variant:"high"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-sonnet-5",variant:"low"},{providers:["qwen-token-plan","alibaba-token-plan","qwen-token-plan-cn","alibaba-token-plan-cn"],model:"qwen3.8-max-preview",variant:"max"},{providers:["deepseek","opencode-go"],model:"deepseek-v4-pro",variant:"max"},{providers:["xiaomi","opencode-go"],model:"mimo-v2.5-pro",variant:"max"}],"unspecified-high":[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"medium"},{providers:["zai","zai-coding-cn","opencode-go"],model:"glm-5.3",variant:"max"},{providers:["kimi-coding","kimi-for-coding","moonshotai","opencode-go"],model:"kimi-k3",variant:"max"}],writing:[{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-5-5",variant:"low"},{providers:["anthropic-subscription","anthropic","anthropic-api","github-copilot","opencode"],model:"claude-opus-4-6",variant:"max"}]};var BUILTIN_CATEGORY_DEFAULTS=[...GOOGLE_CATEGORIES,...OPENAI_CATEGORIES,...ANTHROPIC_CATEGORIES,...KIMI_CATEGORIES],DEFAULT_CATEGORIES=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.config])),CATEGORY_DESCRIPTIONS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.description])),CATEGORY_CALLER_GUIDANCE=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.callerGuidance])),CATEGORY_PROMPT_APPENDS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.map((definition)=>[definition.name,definition.promptAppend]));function hasRequiresModel(definition){return definition.requiresModel!==void 0}var BUILTIN_CATEGORY_REQUIRES_MODEL=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.filter(hasRequiresModel).map((definition)=>[definition.name,typeof definition.requiresModel==="string"?[definition.requiresModel]:definition.requiresModel]));function categoryGateModels(categoryName){return Object.hasOwn(BUILTIN_CATEGORY_REQUIRES_MODEL,categoryName)?BUILTIN_CATEGORY_REQUIRES_MODEL[categoryName]:void 0}function categoryChainProviders(categoryName){return(Object.hasOwn(CATEGORY_FALLBACK_CHAINS,categoryName)?CATEGORY_FALLBACK_CHAINS[categoryName]:[]).flatMap((rung)=>rung.providers)}function providerServesModel(provider,model,availableModels){return availableModels.has(`${provider}/${model}`)||availableModels.has(`${provider}/${transformModelForProvider(provider,model)}`)}function isCategoryGateSatisfied(categoryName,hasExplicitUserConfig,availableModels){let gateModels=categoryGateModels(categoryName);if(gateModels===void 0||hasExplicitUserConfig)return!0;let chainProviders=categoryChainProviders(categoryName);return gateModels.some((gateModel)=>chainProviders.some((provider)=>providerServesModel(provider,gateModel,availableModels)))}function isCategoryChainRungResolvable(entry,availableModels){return entry.providers.some((provider)=>providerServesModel(provider,entry.model,availableModels))}function isCategoryChainViable(categoryName,hasExplicitUserConfig,availableModels){if(hasExplicitUserConfig)return!0;let chain=Object.hasOwn(CATEGORY_FALLBACK_CHAINS,categoryName)?CATEGORY_FALLBACK_CHAINS[categoryName]:void 0;if(chain===void 0||chain.length===0)return!0;return chain.some((rung)=>isCategoryChainRungResolvable(rung,availableModels))}var CATEGORY_PROMPT_APPEND_RESOLVERS=Object.fromEntries(BUILTIN_CATEGORY_DEFAULTS.filter(hasPromptAppendResolver).map((definition)=>[definition.name,definition.resolvePromptAppend]));function hasPromptAppendResolver(definition){return definition.resolvePromptAppend!==void 0}var SECRET_LIKE_MODEL_FIELD_NAMES=new Set(["accesstoken","apikey","auth","authorization","bearertoken","clientsecret","password","privatekey","privatetoken","secret","secretkey","token"]);function formatModel(model){return`${model.provider}/${model.modelId}`}function normalizeModelFieldName(key){return key.replaceAll(/[^a-zA-Z0-9]/g,"").toLowerCase()}function hasSecretLikeModelField(model){return Object.getOwnPropertyNames(model).some((key)=>SECRET_LIKE_MODEL_FIELD_NAMES.has(normalizeModelFieldName(key)))}function ownStringDataProperty(model,key){let descriptor=Object.getOwnPropertyDescriptor(model,key);return descriptor&&"value"in descriptor&&typeof descriptor.value==="string"?descriptor.value:void 0}function isSenpiModelPort(model){if(typeof model!=="object"||model===null||hasSecretLikeModelField(model))return!1;return ownStringDataProperty(model,"provider")!==void 0&&ownStringDataProperty(model,"id")!==void 0}function parseRegistryModel(model,expected){if(!isSenpiModelPort(model))return;let provider=ownStringDataProperty(model,"provider"),modelId=ownStringDataProperty(model,"id"),displayName=ownStringDataProperty(model,"name");if(!provider||!modelId||expected!==void 0&&(provider!==expected.provider||modelId!==expected.modelId))return;return{model,provider,modelId,...displayName!==void 0&&displayName.trim().length>0&&displayName.length<=120&&!/[\u0000-\u001f\u007f-\u009f]/u.test(displayName)?{displayName}:{}}}function availableCategoryNames(config,availableModels){let names=Array.from(new Set([...Object.keys(DEFAULT_CATEGORIES),...Object.keys(config.categories??{})])).sort();if(availableModels===void 0)return names;let userCategories=config.categories??{};return names.filter((name)=>{let hasExplicitUserConfig=getOwnRecordValue(userCategories,name)!==void 0;return isCategoryGateSatisfied(name,hasExplicitUserConfig,availableModels)&&isCategoryChainViable(name,hasExplicitUserConfig,availableModels)})}function gatedAvailableCategories(config,senpiModelRegistry){try{let parsed=parseAvailableModels(senpiModelRegistry.getAvailable());if(!parsed.validContainer)return availableCategoryNames(config);return availableCategoryNames(config,new Set(parsed.models))}catch{return availableCategoryNames(config)}}function resolveAvailableCategoryNames(config,senpiModelRegistry){return gatedAvailableCategories(config,senpiModelRegistry)}function missingChainProviders(chain,availableModels){let connected=new Set(availableModels.map((model)=>model.slice(0,model.indexOf("/")))),missing=[];for(let rung of chain)for(let provider of rung.providers)if(!connected.has(provider)&&!missing.includes(provider))missing.push(provider);return missing}function unlistedProviderModel(chain,availableModels){let available=new Set(availableModels);for(let rung of chain){let match=resolveModelForDelegateTask({fallbackChain:[rung],allowUnlistedProviders:!0,availableModels:available},{connectedProviders:null,hasProviderModelsCache:!0,hasConnectedProvidersCache:!0});if(match!==void 0&&"model"in match)return match.model}return}function getOwnRecordValue(record,key){return Object.hasOwn(record,key)?record[key]:void 0}function parseAvailableModels(models){if(!Array.isArray(models))return{models:[],validContainer:!1};return{models:models.map((model)=>parseRegistryModel(model)).filter((model)=>model!==void 0).map(formatModel).sort(),validContainer:!0}}function resolveCategoryCoverage(config,registry){let available=parseAvailableModels(registry.getAvailable());if(!available.validContainer)throw Error("the model registry did not return a model list");let userCategories=config.categories??{},enabled=(name)=>!Object.hasOwn(userCategories,name)||userCategories[name]?.disable!==!0,usable=new Set(resolveAvailableCategoryNames(config,registry)),names=Array.from(new Set([...Object.keys(DEFAULT_CATEGORIES),...Object.keys(userCategories)])).sort().filter(enabled);return{usable:names.filter((name)=>usable.has(name)),unusable:names.filter((name)=>!usable.has(name)).map((name)=>{let chain=Object.hasOwn(CATEGORY_FALLBACK_CHAINS,name)?CATEGORY_FALLBACK_CHAINS[name]:[],optIn=unlistedProviderModel(chain,available.models);return{name,providers:missingChainProviders(chain,available.models),...optIn!==void 0?{unlistedProviderModel:optIn}:{}}})}}import{accessSync as accessSync2,constants as constants2,existsSync as existsSync3}from"node:fs";import{dirname as dirname4,resolve as resolve3}from"node:path";var PROTOCOL_VERSION="1",ENGINE_ABI="senpi-desktop/1",ENGINE_METHODS=["engine.hello","session.open","session.close","capabilities","displays","windows","capture","click","moveMouse","drag","scroll","typeText","keyChord","raiseWindow","clipboard.read","clipboard.write","ax.snapshot","ax.query","ax.elementAt","ax.focused","ax.node","ax.attributes","ax.children","ax.parent","ax.perform","ax.setValue","ax.focus","ax.click","stopPath.start","stopPath.status","stopPath.heartbeat","stopPath.stop","stopPath.resume","$/cancel","$/test.advanceClock"];var ERROR_CODES=["PermissionDenied","CaptureFailed","InputFailed","BackgroundUnavailable","WindowNotFound","InvalidTarget","InvalidKey","InvalidCoordinateFrame","StaleRef","AxUnsupported","AxFailed","Timeout","Closed","Internal","StopPathUnavailable","Suspended","ScreenLocked","Cancelled","CursorRestoreFailed","FocusRestoreFailed","TransactionFailed"];import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var DESKTOP_ENGINE_BINARY="senpi-desktop-engine",QUARANTINE_ATTRIBUTE="com.apple.quarantine",defaultPackageDir=join2(dirname2(fileURLToPath(import.meta.url)),"..");function getDesktopEngineHost(platform=process.platform,arch=process.arch,libc=platform==="linux"&&platform===process.platform?runningLibc():void 0){return platform==="linux"&&libc==="musl"?`${platform}-${arch}-musl`:`${platform}-${arch}`}var detectedLibc;function runningLibc(){return detectedLibc??=libcFromSignals(process.report?.getReport(),readProcessMaps),detectedLibc}function libcFromSignals(report,readMaps){let header=typeof report==="object"&&report!==null?Reflect.get(report,"header"):void 0,glibc=typeof header==="object"&&header!==null?Reflect.get(header,"glibcVersionRuntime"):void 0;if(typeof glibc==="string"&&glibc.length>0)return"glibc";return/\/ld-musl-[^/\s]+\.so\.1$/m.test(readMaps()??"")?"musl":"glibc"}function readProcessMaps(){try{return readFileSync2("/proc/self/maps","utf8")}catch(error){if(error instanceof Error&&"code"in error)return;throw error}}function getDesktopEngineFileName(platform=process.platform){return platform==="win32"?`${DESKTOP_ENGINE_BINARY}.exe`:DESKTOP_ENGINE_BINARY}function getDesktopEngineCandidatePaths(options={}){let host=getDesktopEngineHost(options.platform,options.arch,options.libc),file=getDesktopEngineFileName(options.platform),packageDir=options.packageDir??defaultPackageDir,execDir=options.execDir??dirname2(process.execPath),repoRoot=options.repoRoot??join2(packageDir,"..",".."),prebuild=join2("native","prebuilds",host,file),runtimeDir=options.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...runtimeDir?[join2(runtimeDir,prebuild)]:[],join2(execDir,prebuild),join2(packageDir,prebuild),join2(repoRoot,"target","release",file)]}function locateDesktopEngine(options={}){let platform=options.platform??process.platform,host=getDesktopEngineHost(platform,options.arch,options.libc),attemptedPaths=getDesktopEngineCandidatePaths(options),isQuarantined=options.isQuarantined??((enginePath)=>isQuarantinedFile(enginePath,platform)),causes=[],quarantinedPaths=[];for(let enginePath of attemptedPaths){if(!existsSync2(enginePath)){causes.push(`${enginePath}: missing`);continue}if(isQuarantined(enginePath)){quarantinedPaths.push(enginePath),causes.push(`${enginePath}: blocked because ${QUARANTINE_ATTRIBUTE} is present (macOS Gatekeeper)`);continue}if(!isExecutable(enginePath)){causes.push(`${enginePath}: not executable (chmod +x)`);continue}return{path:enginePath,diagnostic:null}}let code=quarantinedPaths.length>0?"quarantined":"native-unavailable",message=code==="quarantined"?`The ${DESKTOP_ENGINE_BINARY} binary for ${host} is quarantined by macOS Gatekeeper: ${quarantinedPaths.join(", ")}.`:`No ${DESKTOP_ENGINE_BINARY} binary is available for ${host}.`;return{path:null,diagnostic:{code,host,attemptedPaths,message,cause:causes.join("; ")}}}function isQuarantinedFile(enginePath,platform=process.platform){if(platform!=="darwin")return!1;let probe=spawnSync("/usr/bin/xattr",["-p",QUARANTINE_ATTRIBUTE,enginePath],{stdio:["ignore","ignore","ignore"],timeout:2000});return probe.error===void 0&&probe.status===0}function isExecutable(enginePath){try{return accessSync(enginePath,constants.X_OK),!0}catch(error){if(error instanceof Error&&"code"in error)return!1;throw error}}var GC_NEVER_STALE_MS=Number.MAX_SAFE_INTEGER;function Match(args,match){return match[args.length]?.(...args)??(()=>{throw Error("Invalid Arguments")})()}function CodePointCount(value){let result=0,index=0,prev=0;while(index<value.length){let next=value.charCodeAt(index++)>>10;result+=+((prev<<8|next)!==13879),prev=next}return result}function IsMaxLength(value,maxLength){return value.length<=maxLength||value.length<=maxLength<<1&&CodePointCount(value)<=maxLength}function IsMinLength(value,minLength){return value.length>=minLength<<1||value.length>=minLength&&CodePointCount(value)>=minLength}function IsArray(value){return Array.isArray(value)}function IsBigInt(value){return IsEqual(typeof value,"bigint")}function IsBoolean(value){return IsEqual(typeof value,"boolean")}function IsConstructor(value){if(IsUndefined(value)||!IsFunction(value))return!1;let result=Function.prototype.toString.call(value);if(/^class\s/.test(result))return!0;if(/\[native code\]/.test(result))return!0;return!1}function IsFunction(value){return IsEqual(typeof value,"function")}function IsInteger(value){return Number.isInteger(value)}function IsNull(value){return IsEqual(value,null)}function IsNumber(value){return Number.isFinite(value)}function IsObjectNotArray(value){return IsObject(value)&&!IsArray(value)}function IsObject(value){return IsEqual(typeof value,"object")&&!IsNull(value)}function IsString(value){return IsEqual(typeof value,"string")}function IsSymbol(value){return IsEqual(typeof value,"symbol")}function IsUndefined(value){return IsEqual(value,void 0)}function IsEqual(left,right){return left===right}function IsGreaterThan(left,right){return left>right}function IsLessThan(left,right){return left<right}function IsLessEqualThan(left,right){return left<=right}function IsGreaterEqualThan(left,right){return left>=right}function IsMultipleOf(dividend,divisor){if(IsBigInt(dividend)||IsBigInt(divisor))return BigInt(dividend)%BigInt(divisor)===0n;let tolerance=0.0000000001;if(!IsNumber(dividend))return!0;if(IsInteger(dividend)&&1/divisor%1===0)return!0;let mod=dividend%divisor;return Math.min(Math.abs(mod),Math.abs(mod-divisor),Math.abs(mod+divisor))<tolerance}function IsClassInstance(value){if(!IsObject(value))return!1;let proto=globalThis.Object.getPrototypeOf(value);if(IsNull(proto))return!1;return IsEqual(typeof proto.constructor,"function")&&!(IsEqual(proto.constructor,globalThis.Object)||IsEqual(proto.constructor.name,"Object"))}function IsValueLike(value){return IsBigInt(value)||IsBoolean(value)||IsNull(value)||IsNumber(value)||IsString(value)||IsUndefined(value)}function IsMaxLength2(value,maxLength){return IsMaxLength(value,maxLength)}function IsMinLength2(value,minLength){return IsMinLength(value,minLength)}function Every(value,offset,callback){return value.every((item,index)=>index<offset||callback(item,index))}function EveryAll(value,offset,callback){let result=!0;return value.forEach((item,index)=>{if(index>=offset&&!callback(item,index))result=!1}),result}function Some(value,callback){return value.some((value,index)=>callback(value,index))}function SomeAll(value,callback){let result=!1;return value.forEach((item,index)=>{if(callback(item,index))result=!0}),result}function Counted(value,callback){return value.reduce((result,value,index)=>callback(value,index)?++result:result,0)}function ShiftLeft(array,true_,false_){return IsEqual(array.length,0)?false_():true_(array[0],array.slice(1))}function IsUnsafePropertyKey(key){return IsEqual(key,"__proto__")||IsEqual(key,"constructor")||IsEqual(key,"prototype")}function HasPropertyKey(value,key){return IsUnsafePropertyKey(key)?Object.prototype.hasOwnProperty.call(value,key):(key in value)}function EntriesRegExp(value){return Keys(value).map((key)=>[new RegExp(`^${key}$`),value[key]])}function Entries(value){return Object.entries(value)}function Keys(value){return Object.getOwnPropertyNames(value)}function Symbols(value){return Object.getOwnPropertySymbols(value)}function Values(value){return Object.values(value)}function DeepEqualObject(left,right){if(!IsObject(right))return!1;let keys=Keys(left);return IsEqual(keys.length,Keys(right).length)&&keys.every((key)=>IsDeepEqual(left[key],right[key]))}function DeepEqualArray(left,right){return IsArray(right)&&IsEqual(left.length,right.length)&&left.every((_,index)=>IsDeepEqual(left[index],right[index]))}function IsDeepEqual(left,right){return IsArray(left)?DeepEqualArray(left,right):IsObject(left)?DeepEqualObject(left,right):IsEqual(left,right)}function IsBoolean2(value){return value instanceof Boolean}function IsNumber2(value){return value instanceof Number}function IsString2(value){return value instanceof String}function IsTypeArray(value){return globalThis.ArrayBuffer.isView(value)}function IsRegExp(value){return value instanceof globalThis.RegExp}function IsDate(value){return value instanceof globalThis.Date}function IsSet(value){return value instanceof globalThis.Set}function IsMap(value){return value instanceof globalThis.Map}var settings={immutableTypes:!1,maxErrors:8,maxParseErrors:1,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Get(){return settings}function IsRefine(value){return HasPropertyKey(value,"~refine")&&IsArray(value["~refine"])&&Every(value["~refine"],0,(value)=>IsObject(value)&&HasPropertyKey(value,"check")&&HasPropertyKey(value,"error")&&IsFunction(value.check)&&IsFunction(value.error))}function IsSchemaObject(value){return IsObject(value)&&!IsArray(value)}function IsSchemaBoolean(value){return IsBoolean(value)}function IsSchema(value){return IsSchemaObject(value)||IsSchemaBoolean(value)}function IsAdditionalItems(schema){return HasPropertyKey(schema,"additionalItems")&&IsSchema(schema.additionalItems)}function IsAdditionalProperties(schema){return HasPropertyKey(schema,"additionalProperties")&&IsSchema(schema.additionalProperties)}function IsAllOf(schema){return HasPropertyKey(schema,"allOf")&&IsArray(schema.allOf)&&schema.allOf.every((value)=>IsSchema(value))}function IsAnchor(schema){return HasPropertyKey(schema,"$anchor")&&IsString(schema.$anchor)}function IsAnyOf(schema){return HasPropertyKey(schema,"anyOf")&&IsArray(schema.anyOf)&&schema.anyOf.every((value)=>IsSchema(value))}function IsConst(value){return HasPropertyKey(value,"const")}function IsContains(schema){return HasPropertyKey(schema,"contains")&&IsSchema(schema.contains)}function IsDefault(schema){return HasPropertyKey(schema,"default")}function IsDependencies(schema){return HasPropertyKey(schema,"dependencies")&&IsObject(schema.dependencies)&&Object.values(schema.dependencies).every((value)=>IsSchema(value)||IsArray(value)&&value.every((value)=>IsString(value)))}function IsDependentRequired(schema){return HasPropertyKey(schema,"dependentRequired")&&IsObject(schema.dependentRequired)&&Object.values(schema.dependentRequired).every((value)=>IsArray(value)&&value.every((value)=>IsString(value)))}function IsDependentSchemas(schema){return HasPropertyKey(schema,"dependentSchemas")&&IsObject(schema.dependentSchemas)&&Object.values(schema.dependentSchemas).every((value)=>IsSchema(value))}function IsDynamicAnchor(schema){return HasPropertyKey(schema,"$dynamicAnchor")&&IsString(schema.$dynamicAnchor)}function IsDynamicRef(schema){return HasPropertyKey(schema,"$dynamicRef")&&IsString(schema.$dynamicRef)}function IsElse(schema){return HasPropertyKey(schema,"else")&&IsSchema(schema.else)}function IsEnum(schema){return HasPropertyKey(schema,"enum")&&IsArray(schema.enum)}function IsExclusiveMaximum(schema){return HasPropertyKey(schema,"exclusiveMaximum")&&(IsNumber(schema.exclusiveMaximum)||IsBigInt(schema.exclusiveMaximum))}function IsExclusiveMinimum(schema){return HasPropertyKey(schema,"exclusiveMinimum")&&(IsNumber(schema.exclusiveMinimum)||IsBigInt(schema.exclusiveMinimum))}function IsFormat(schema){return HasPropertyKey(schema,"format")&&IsString(schema.format)}function IsId(schema){return HasPropertyKey(schema,"$id")&&IsString(schema.$id)}function IsIf(schema){return HasPropertyKey(schema,"if")&&IsSchema(schema.if)}function IsItems(schema){return HasPropertyKey(schema,"items")&&(IsSchema(schema.items)||IsArray(schema.items)&&schema.items.every((value)=>IsSchema(value)))}function IsItemsSized(schema){return IsItems(schema)&&IsArray(schema.items)}function IsMaximum(schema){return HasPropertyKey(schema,"maximum")&&(IsNumber(schema.maximum)||IsBigInt(schema.maximum))}function IsMaxContains(schema){return HasPropertyKey(schema,"maxContains")&&IsNumber(schema.maxContains)}function IsMaxItems(schema){return HasPropertyKey(schema,"maxItems")&&IsNumber(schema.maxItems)}function IsMaxLength3(schema){return HasPropertyKey(schema,"maxLength")&&IsNumber(schema.maxLength)}function IsMaxProperties(schema){return HasPropertyKey(schema,"maxProperties")&&IsNumber(schema.maxProperties)}function IsMinimum(schema){return HasPropertyKey(schema,"minimum")&&(IsNumber(schema.minimum)||IsBigInt(schema.minimum))}function IsMinContains(schema){return HasPropertyKey(schema,"minContains")&&IsNumber(schema.minContains)}function IsMinItems(schema){return HasPropertyKey(schema,"minItems")&&IsNumber(schema.minItems)}function IsMinLength3(schema){return HasPropertyKey(schema,"minLength")&&IsNumber(schema.minLength)}function IsMinProperties(schema){return HasPropertyKey(schema,"minProperties")&&IsNumber(schema.minProperties)}function IsMultipleOf2(schema){return HasPropertyKey(schema,"multipleOf")&&(IsNumber(schema.multipleOf)||IsBigInt(schema.multipleOf))}function IsNot(schema){return HasPropertyKey(schema,"not")&&IsSchema(schema.not)}function IsOneOf(schema){return HasPropertyKey(schema,"oneOf")&&IsArray(schema.oneOf)&&schema.oneOf.every((value)=>IsSchema(value))}function IsPattern(schema){return HasPropertyKey(schema,"pattern")&&(IsString(schema.pattern)||schema.pattern instanceof RegExp)}function IsPatternProperties(schema){return HasPropertyKey(schema,"patternProperties")&&IsObject(schema.patternProperties)&&Object.values(schema.patternProperties).every((value)=>IsSchema(value))}function IsPrefixItems(schema){return HasPropertyKey(schema,"prefixItems")&&IsArray(schema.prefixItems)&&schema.prefixItems.every((schema)=>IsSchema(schema))}function IsProperties(schema){return HasPropertyKey(schema,"properties")&&IsObject(schema.properties)&&Object.values(schema.properties).every((value)=>IsSchema(value))}function IsPropertyNames(schema){return HasPropertyKey(schema,"propertyNames")&&(IsObject(schema.propertyNames)||IsSchema(schema.propertyNames))}function IsRecursiveAnchor(schema){return HasPropertyKey(schema,"$recursiveAnchor")&&IsBoolean(schema.$recursiveAnchor)}function IsRecursiveAnchorTrue(schema){return IsRecursiveAnchor(schema)&&IsEqual(schema.$recursiveAnchor,!0)}function IsRecursiveRef(schema){return HasPropertyKey(schema,"$recursiveRef")&&IsString(schema.$recursiveRef)}function IsRef(schema){return HasPropertyKey(schema,"$ref")&&IsString(schema.$ref)}function IsRequired(schema){return HasPropertyKey(schema,"required")&&IsArray(schema.required)&&schema.required.every((value)=>IsString(value))}function IsThen(schema){return HasPropertyKey(schema,"then")&&IsSchema(schema.then)}function IsType(schema){return HasPropertyKey(schema,"type")&&(IsString(schema.type)||IsArray(schema.type)&&schema.type.every((value)=>IsString(value)))}function IsUniqueItems(schema){return HasPropertyKey(schema,"uniqueItems")&&IsBoolean(schema.uniqueItems)}function IsUnevaluatedItems(schema){return HasPropertyKey(schema,"unevaluatedItems")&&IsSchema(schema.unevaluatedItems)}function IsUnevaluatedProperties(schema){return HasPropertyKey(schema,"unevaluatedProperties")&&IsSchema(schema.unevaluatedProperties)}class CheckContext{constructor(){let indices=new Set,keys=new Set;this.stack=[{indices,keys}]}Push(){let indices=new Set,keys=new Set;return this.stack.push({indices,keys}),!0}Pop(){return this.stack.pop(),!0}AddIndex(index){return this.GetIndices().add(index),!0}AddKey(key){return this.GetKeys().add(key),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(results){for(let context of results)context.GetIndices().forEach((value)=>this.GetIndices().add(value)),context.GetKeys().forEach((value)=>this.GetKeys().add(value));return!0}}class ErrorContext extends CheckContext{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Get().maxErrors}AddError(keyword,schemaPath,instancePath,params){return this.AddErrorObject({keyword,schemaPath,instancePath,params})}AddErrors(error){return error.forEach((error)=>this.AddErrorObject(error)),!1}GetErrors(){return this.errors}AddErrorObject(error){if(!this.AtCapacity())this.errors.push(error);return!1}}function CheckRefine(_stack,_context,schema,value){return Every(schema["~refine"],0,(refinement,_)=>refinement.check(value))}function ErrorRefine(_stack,context,schemaPath,instancePath,schema,value){return EveryAll(schema["~refine"],0,(refinement,index)=>refinement.check(value)||context.AddError("~refine",schemaPath,instancePath,{index,message:refinement.error(value)}))}var DefaultUri="urn:typebox:root";function NextUri(ref,base){return URL.canParse(ref,base)?new URL(ref,base):IsEqual(base,DefaultUri)?new URL(`${base}:${ref}`):new URL(`${base.slice(0,base.lastIndexOf(":"))}:${ref}`)}function Stack(context,schema){let base=IsSchemaObject(schema)&&IsId(schema)?NextUri(schema.$id,DefaultUri).href:DefaultUri;return{context,schema,lexicalSchema:schema,lexicalBase:base,resourceBase:base,referenceBase:base,ids:[],useResourceBaseForReference:!0,recursiveAnchor:void 0,dynamicAnchors:[],resourceEntries:new Map,pendingResource:!0,enteredResource:!1}}function RegisterResourceAnchors(anchors,schema,isRoot=!0){if(IsSchemaBoolean(schema))return anchors;if(Array.isArray(schema))return schema.reduce((result,item)=>RegisterResourceAnchors(result,item,!1),anchors);if(!IsSchemaObject(schema))return anchors;if(!isRoot&&IsId(schema))return anchors;let next=!isRoot&&IsDynamicAnchor(schema)?[...anchors,schema]:anchors;return Object.keys(schema).reduce((result,key)=>RegisterResourceAnchors(result,schema[key],!1),next)}function ResourceEntry(stack,schema){return stack.resourceEntries.get(schema)}function NextEnteredResource(stack,schema){return stack.enteredResource||ResourceEntry(stack,schema)!==void 0}function IsRelativeId(schema){return!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(schema.$id)}function NextIds(stack,schema){return IsId(schema)?[...stack.ids,schema]:stack.ids}function NextRecursiveAnchor(stack,schema){return stack.recursiveAnchor??(IsRecursiveAnchorTrue(schema)?schema:void 0)}function NextDynamicAnchors(stack,schema){let registered=IsId(schema)?RegisterResourceAnchors(stack.dynamicAnchors,schema):stack.dynamicAnchors;return IsDynamicAnchor(schema)?[...registered,schema]:registered}function NextPendingResource(stack,schema){return IsId(schema)?!1:stack.pendingResource}function NextLexicalBase(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.base;return IsId(schema)?NextUri(schema.$id,stack.lexicalBase).href:stack.lexicalBase}function NextResourceBase(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.base;return IsId(schema)&&stack.pendingResource?NextUri(schema.$id,stack.resourceBase).href:stack.resourceBase}function NextUseResourceBaseForReference(stack,schema){return IsId(schema)?!IsRelativeId(schema):stack.useResourceBaseForReference}function NextReferenceBase(stack,schema){let isRetrieved=NextEnteredResource(stack,schema),useResourceBaseForReference=NextUseResourceBaseForReference(stack,schema);return isRetrieved||useResourceBaseForReference?NextResourceBase(stack,schema):NextLexicalBase(stack,schema)}function NextLexicalSchema(stack,schema){let entry=ResourceEntry(stack,schema);if(entry)return entry.root;return IsId(schema)?schema:stack.lexicalSchema}function HasStackKeywords(stack,schema){return IsSchemaObject(schema)&&(IsId(schema)||IsDynamicAnchor(schema)||IsUndefined(stack.recursiveAnchor)&&IsRecursiveAnchorTrue(schema)||!IsUndefined(ResourceEntry(stack,schema)))}function NextStack(stack,schema){return HasStackKeywords(stack,schema)?{...stack,ids:NextIds(stack,schema),dynamicAnchors:NextDynamicAnchors(stack,schema),recursiveAnchor:NextRecursiveAnchor(stack,schema),pendingResource:NextPendingResource(stack,schema),lexicalBase:NextLexicalBase(stack,schema),resourceBase:NextResourceBase(stack,schema),useResourceBaseForReference:NextUseResourceBaseForReference(stack,schema),referenceBase:NextReferenceBase(stack,schema),lexicalSchema:NextLexicalSchema(stack,schema),enteredResource:NextEnteredResource(stack,schema)}:stack}function IsValid(schema){return IsItems(schema)&&IsArray(schema.items)}function CheckAdditionalItems(stack,context,schema,value){if(!IsValid(schema))return!0;return Every(value,0,(item,index)=>IsLessThan(index,schema.items.length)||CheckSchemaPushStack(stack,context,schema.additionalItems,item)&&context.AddIndex(index))}function ErrorAdditionalItems(stack,context,schemaPath,instancePath,schema,value){if(!IsValid(schema))return!0;return Every(value,0,(item,index)=>{let nextSchemaPath=`${schemaPath}/additionalItems`,nextInstancePath=`${instancePath}/${index}`;return IsLessThan(index,schema.items.length)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.additionalItems,item)&&context.AddIndex(index)})}function EncodeFragment(fragment){return fragment.replace(/~/g,"~0").replace(/\//g,"~1")}function UnicodeRegExp(pattern){return new RegExp(pattern,"u")}function GetPropertyKeyAsPattern(key){return`^${key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function GetPropertiesPattern(schema){let patterns=[];if(IsPatternProperties(schema))patterns.push(...Keys(schema.patternProperties));if(IsProperties(schema))patterns.push(...Keys(schema.properties).map(GetPropertyKeyAsPattern));return IsEqual(patterns.length,0)?"(?!)":`(${patterns.join("|")})`}function CheckAdditionalProperties(stack,context,schema,value){let regexp=UnicodeRegExp(GetPropertiesPattern(schema));return Every(Keys(value),0,(key,_index)=>regexp.test(key)||CheckSchemaPushStack(stack,context,schema.additionalProperties,value[key])&&context.AddKey(key))}function ErrorAdditionalProperties(stack,context,schemaPath,instancePath,schema,value){let regexp=UnicodeRegExp(GetPropertiesPattern(schema)),additionalProperties=[];return EveryAll(Keys(value),0,(key,_index)=>{let nextSchemaPath=`${schemaPath}/additionalProperties`,nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,isAdditionalProperty=regexp.test(key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.additionalProperties,value[key])&&context.AddKey(key);if(!isAdditionalProperty)additionalProperties.push(key);return isAdditionalProperty})||context.AddError("additionalProperties",schemaPath,instancePath,{additionalProperties})}function CheckAllOf(stack,context,schema,value){let results=schema.allOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsEqual(results.length,schema.allOf.length)&&context.Merge(results)}function ErrorAllOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],results=schema.allOf.reduce((result,schema,index)=>{let nextSchemaPath=`${schemaPath}/allOf/${index}`,nextContext=new ErrorContext,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isAllOf=IsEqual(results.length,schema.allOf.length)&&context.Merge(results);if(!isAllOf)failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isAllOf}function CheckAnyOf(stack,context,schema,value){let results=schema.anyOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsGreaterThan(results.length,0)&&context.Merge(results)}function ErrorAnyOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],results=schema.anyOf.reduce((result,schema,index)=>{let nextContext=new ErrorContext,nextSchemaPath=`${schemaPath}/anyOf/${index}`,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isAnyOf=IsGreaterThan(results.length,0)&&context.Merge(results);if(!isAnyOf)failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isAnyOf||context.AddError("anyOf",schemaPath,instancePath,{})}function CheckSchemaBoolean(_stack,_context,schema,_value){return schema}function ErrorSchemaBoolean(stack,context,schemaPath,instancePath,schema,value){return CheckSchemaBoolean(stack,context,schema,value)||context.AddError("boolean",schemaPath,instancePath,{})}function CheckConst(_stack,_context,schema,value){return IsValueLike(schema.const)?IsEqual(value,schema.const):IsDeepEqual(value,schema.const)}function ErrorConst(stack,context,schemaPath,instancePath,schema,value){return CheckConst(stack,context,schema,value)||context.AddError("const",schemaPath,instancePath,{allowedValue:schema.const})}function IsValid2(schema){return!(IsMinContains(schema)&&IsEqual(schema.minContains,0))}function CheckContains(stack,context,schema,value){if(!IsValid2(schema))return!0;return!IsEqual(value.length,0)&&SomeAll(value,(item,index)=>CheckSchema(stack,context,schema.contains,item)&&context.AddIndex(index))}function ErrorContains(stack,context,schemaPath,instancePath,schema,value){return CheckContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains:1})}function CheckDependencies(stack,context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependencies),0,([key,schema])=>!HasPropertyKey(value,key)||(IsArray(schema)?schema.every((key)=>HasPropertyKey(value,key)):CheckSchema(stack,context,schema,value)));return isLength||isEvery}function ErrorDependencies(stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=EveryAll(Entries(schema.dependencies),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/dependencies/${EncodeFragment(key)}`;return!HasPropertyKey(value,key)||(IsArray(schema)?schema.every((dependency)=>HasPropertyKey(value,dependency)||context.AddError("dependencies",schemaPath,instancePath,{property:key,dependencies:schema})):ErrorSchema(stack,context,nextSchemaPath,instancePath,schema,value))});return isLength||isEvery}function CheckDependentRequired(_stack,_context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependentRequired),0,([key,keys])=>!HasPropertyKey(value,key)||keys.every((key)=>HasPropertyKey(value,key)));return isLength||isEvery}function ErrorDependentRequired(_stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEveryEntry=EveryAll(Entries(schema.dependentRequired),0,([key,keys])=>!HasPropertyKey(value,key)||EveryAll(keys,0,(dependency)=>HasPropertyKey(value,dependency)||context.AddError("dependentRequired",schemaPath,instancePath,{property:key,dependencies:keys})));return isLength||isEveryEntry}function CheckDependentSchemas(stack,context,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=Every(Entries(schema.dependentSchemas),0,([key,schema])=>!HasPropertyKey(value,key)||CheckSchema(stack,context,schema,value));return isLength||isEvery}function ErrorDependentSchemas(stack,context,schemaPath,instancePath,schema,value){let isLength=IsEqual(Keys(value).length,0),isEvery=EveryAll(Entries(schema.dependentSchemas),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/dependentSchemas/${EncodeFragment(key)}`;return!HasPropertyKey(value,key)||ErrorSchema(stack,context,nextSchemaPath,instancePath,schema,value)});return isLength||isEvery}function Indices(pointer){let indices=pointer.split("/").map((index)=>index.replace(/~1/g,"/").replace(/~0/g,"~"));return indices[0]===""?indices.slice(1):indices}function Get2(value,pointer){let current=value;for(let index of Indices(pointer)){if(!IsObject(current)||IsUnsafePropertyKey(index))return;current=current[index]}return current}function RelativeBase(schema,base){return IsSchemaObject(schema)&&IsId(schema)?NextUri(schema.$id,base.href):base}function AbsoluteBase(base){return NextUri(base,DefaultUri)}function CanonicalHref(url){return url.href.split("#")[0]}function Base(schema,base,target){return SearchBase(schema,AbsoluteBase(base),target)}function RefRoot(stack,ref){return ref.$ref.startsWith("#")||stack.enteredResource?stack.lexicalSchema:stack.schema}function IsPointerFragment(fragment){return fragment.startsWith("#/")}function SearchDynamicAnchor(schema,name){if(IsObject(schema)&&IsDynamicAnchor(schema)&&IsEqual(schema.$dynamicAnchor,name))return schema;if(IsObject(schema))for(let key of Keys(schema)){let result=SearchDynamicAnchor(schema[key],name);if(result)return result}return}function SearchBase(schema,base,target){if(IsEqual(schema,target))return base.href;let nextBase=RelativeBase(schema,base);if(IsArray(schema))for(let item of schema){let result=SearchBase(item,nextBase,target);if(!IsUndefined(result))return result}else if(IsObject(schema))for(let key of Keys(schema)){let result=SearchBase(schema[key],nextBase,target);if(!IsUndefined(result))return result}return}function MatchWithHash(schema,ref){if(ref.href.endsWith("#"))return schema;if(!ref.hash.startsWith("#"))return;let fragment=decodeURIComponent(ref.hash.slice(1));if(!fragment.startsWith("/"))return;return Get2(schema,fragment)}function MatchWithId(schema,base,ref){if(!IsId(schema))return;if(IsEqual(schema.$id,ref.hash))return schema;let absoluteRef=new URL(ref.href,base.href);if(IsEqual(base.pathname,absoluteRef.pathname))return ref.hash.startsWith("#")?MatchWithHash(schema,ref):schema;return}function MatchWithAnchor(schema,base,ref){if(!IsAnchor(schema))return;let absoluteAnchor=new URL(`#${schema.$anchor}`,base.href),absoluteRef=new URL(ref.href,base.href);return IsEqual(absoluteAnchor.href,absoluteRef.href)?schema:void 0}function MatchWithDynamicAnchor(schema,base,ref){if(!IsDynamicAnchor(schema))return;let absoluteAnchor=new URL(`#${schema.$dynamicAnchor}`,base.href),absoluteRef=new URL(ref.href,base.href);return IsEqual(absoluteAnchor.href,absoluteRef.href)?schema:void 0}function MatchSchemaObject(schema,base,ref){if(!IsSchemaObject(schema))return;return MatchWithId(schema,base,ref)??MatchWithAnchor(schema,base,ref)??MatchWithDynamicAnchor(schema,base,ref)??MatchWithHash(schema,ref)}function MatchFromArray(schema,base,ref){if(!IsArray(schema))return;return schema.reduce((result,item)=>{let match=Match2(item,base,ref);return!IsUndefined(match)?match:result},void 0)}function MatchFromObject(schema,base,ref){if(!IsObject(schema))return;return Keys(schema).reduce((result,key)=>{if(IsEqual(key,"const")||IsEqual(key,"enum"))return result;let match=Match2(schema[key],base,ref);return!IsUndefined(match)?match:result},void 0)}function Match2(schema,base,ref){let relativeBase=RelativeBase(schema,base);return MatchSchemaObject(schema,relativeBase,ref)??MatchFromArray(schema,relativeBase,ref)??MatchFromObject(schema,relativeBase,ref)}function Resource(context,schema,base,ref){let result=RefInternal(context,schema,base,ref);return IsSchemaObject(result)&&IsId(result)?result:void 0}function FindDeferredResourceLegacy(stack,ref,schema){if(!ref.$ref.startsWith("#"))return;if(!IsSchemaObject(stack.schema)||HasPropertyKey(stack.schema,"$schema"))return;let targetBase=Base(stack.lexicalSchema,stack.referenceBase,schema);if(IsUndefined(targetBase)||IsEqual(targetBase,stack.referenceBase))return;return{target:schema,base:targetBase,root:stack.lexicalSchema}}function FindDeferredResourceModern(stack,canonical,schema){let remoteRoot=stack.context[canonical];if(!IsSchemaObject(remoteRoot))return;return{target:schema,base:canonical,root:remoteRoot}}function FindDeferredResource(stack,ref,schema,canonical,isRemote){let remote=isRemote?FindDeferredResourceModern(stack,canonical,schema):void 0;return IsUndefined(remote)?FindDeferredResourceLegacy(stack,ref,schema):remote}function FindResolvedResource(stack,canonical,schema){if(IsId(schema))return;let resource=Resource(stack.context,stack.schema,stack.referenceBase,canonical);if(!resource||stack.ids.includes(resource))return;return{resource}}function RefInternalWithContext(context,ref){return HasPropertyKey(context,ref)?context[ref]:void 0}function RefInternalWithLocal(schema,base,ref){return Match2(schema,base,ref)}function RefInternalWithRemote(context,base,ref){let canonicalHref=CanonicalHref(ref);if(!HasPropertyKey(context,canonicalHref)||IsEqual(canonicalHref,CanonicalHref(base)))return;let remoteSchema=context[canonicalHref],remoteBase=RelativeBase(remoteSchema,new URL(canonicalHref));return IsEqual(ref.hash,"")?remoteSchema:Match2(remoteSchema,remoteBase,ref)}function RefInternal(context,schema,base,ref){let absoluteBase=AbsoluteBase(base),target=NextUri(ref,absoluteBase.href);return RefInternalWithContext(context,ref)??RefInternalWithLocal(schema,absoluteBase,target)??RefInternalWithRemote(context,absoluteBase,target)}function RefNextStackDeferred(stack,deferredResource){if(!deferredResource)return stack;let resourceEntries=new Map(stack.resourceEntries);return resourceEntries.set(deferredResource.target,{base:deferredResource.base,root:deferredResource.root}),{...stack,resourceEntries}}function RefNextStackResolved(stack,resolvedResource){return resolvedResource?NextStack(stack,resolvedResource.resource):stack}function RefNextStack(stack,pendingResource,deferredResource,resolvedResource){let withDeferred=RefNextStackDeferred({...stack,pendingResource},deferredResource);return RefNextStackResolved(withDeferred,resolvedResource)}function RefResultFound(stack,ref,schema){let canonical=CanonicalHref(NextUri(ref.$ref,stack.referenceBase)),isRemote=!IsEqual(canonical,stack.resourceBase),deferredResource=FindDeferredResource(stack,ref,schema,canonical,isRemote),resolvedResource=isRemote?FindResolvedResource(stack,canonical,schema):void 0;return{schema,stack:RefNextStack(stack,!0,deferredResource,resolvedResource)}}function RefResultNotFound(stack,schema){return{schema,stack:RefNextStack(stack,!IsUndefined(schema))}}function Ref(stack,ref){let schema=RefInternal(stack.context,RefRoot(stack,ref),stack.referenceBase,ref.$ref);return IsSchemaObject(schema)?RefResultFound(stack,ref,schema):RefResultNotFound(stack,schema)}function IsRecursiveAnchorInScope(stack){return IsSchemaObject(stack.lexicalSchema)&&IsRecursiveAnchorTrue(stack.lexicalSchema)}function RecursiveRef(stack,recursiveRef){let schema=IsRecursiveAnchorInScope(stack)?stack.recursiveAnchor:stack.lexicalSchema;return RefInternal(stack.context,schema,stack.lexicalBase,recursiveRef.$recursiveRef)}function DynamicRefFragment(stack,dynamicRef){return NextUri(dynamicRef.$dynamicRef,AbsoluteBase(stack.lexicalBase).href).hash}function FindScopedDynamicAnchor(stack,name){return stack.dynamicAnchors.find((anchor)=>IsEqual(anchor.$dynamicAnchor,name))??SearchDynamicAnchor(stack.schema,name)}function DynamicRefWhenFound(stack,dynamicRef,fragmentTarget){if(!IsSchemaObject(fragmentTarget)||!IsDynamicAnchor(fragmentTarget))return fragmentTarget;let fragment=DynamicRefFragment(stack,dynamicRef);return IsPointerFragment(fragment)?fragmentTarget:FindScopedDynamicAnchor(stack,fragmentTarget.$dynamicAnchor)}function DynamicRefWhenNotFound(stack,dynamicRef){let fragment=DynamicRefFragment(stack,dynamicRef);return FindScopedDynamicAnchor(stack,decodeURIComponent(fragment.slice(1)))}function DynamicRef(stack,dynamicRef){let fragmentRoot=dynamicRef.$dynamicRef.startsWith("#")?stack.lexicalSchema:stack.schema,fragmentTarget=RefInternal(stack.context,fragmentRoot,stack.lexicalBase,dynamicRef.$dynamicRef);return IsUndefined(fragmentTarget)?DynamicRefWhenNotFound(stack,dynamicRef):DynamicRefWhenFound(stack,dynamicRef,fragmentTarget)}function CheckDynamicRef(stack,context,schema,value){let target=DynamicRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&CheckSchema(nextStack,context,target,value)}function ErrorDynamicRef(stack,context,schemaPath,instancePath,schema,value){let target=DynamicRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&ErrorSchema(nextStack,context,schemaPath,instancePath,target,value)}function CheckEnum(_stack,_context,schema,value){return Some(schema.enum,(option)=>IsValueLike(option)?IsEqual(value,option):IsDeepEqual(value,option))}function ErrorEnum(stack,context,schemaPath,instancePath,schema,value){return CheckEnum(stack,context,schema,value)||context.AddError("enum",schemaPath,instancePath,{allowedValues:schema.enum})}function CheckExclusiveMaximum(_stack,_context,schema,value){return IsLessThan(value,schema.exclusiveMaximum)}function ErrorExclusiveMaximum(stack,context,schemaPath,instancePath,schema,value){return CheckExclusiveMaximum(stack,context,schema,value)||context.AddError("exclusiveMaximum",schemaPath,instancePath,{comparison:"<",limit:schema.exclusiveMaximum})}function CheckExclusiveMinimum(_stack,_context,schema,value){return IsGreaterThan(value,schema.exclusiveMinimum)}function ErrorExclusiveMinimum(stack,context,schemaPath,instancePath,schema,value){return CheckExclusiveMinimum(stack,context,schema,value)||context.AddError("exclusiveMinimum",schemaPath,instancePath,{comparison:">",limit:schema.exclusiveMinimum})}var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function IsLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function IsDate2(value){let matches=DATE.exec(value);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&IsLeapYear(year)?29:DAYS[month])}var TIME=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function IsTime(value,strictTimeZone=!0){let matches=TIME.exec(value);if(!matches)return!1;if(strictTimeZone&&!matches[4]&&!matches[5])return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3];if(hr>23||min>59||sec>60)return!1;if(matches[5]){let tzH=+matches[6],tzM=+matches[7];if(tzH>23||tzM>59)return!1}if(sec<60)return!0;let tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);return((hr*60+min-tzSign*(tzH*60+tzM))%1440+1440)%1440===1439}function IsDateTime(value){let dateTime=value.split(/T/i);return dateTime.length===2&&IsDate2(dateTime[0])&&IsTime(dateTime[1])}var Duration=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function IsDuration(value){return Duration.test(value)}var Email=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function IsEmail(value){return Email.test(value)}var RE_RULE_HYPHEN_PLACEMENT=/^(?!-).*(?<!-)$/,RE_RULE_NOT_RESERVED_ACE=/^(?!..--)/,RE_ASCII_LDH=/^[a-zA-Z0-9-]*$/;var RE_NON_ASCII=/[^\p{ASCII}]/u;var RE_ASCII_DIGIT=/[0-9]/,RE_ARABIC_INDIC_DIGIT=/[\u{0660}-\u{0669}]/u,RE_EXT_ARABIC_INDIC_DIGIT=/[\u{06f0}-\u{06f9}]/u,RE_COMMON_SEPARATOR=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,RE_EUROPEAN_SEPARATOR=/[\u{002d}\u{002b}]/u,RE_MARK_NONSPACING=/\p{Mn}/u,RE_MARK_SPACING_COMBINING=/\p{Mc}/u;var RE_COMBINING_MARK=/[\p{Mn}\p{Mc}\p{Me}]/u,RE_LETTER=/\p{L}/u,RE_NUMBER_DECIMAL=/\p{Nd}/u,RE_SCRIPT_GREEK=/\p{Script=Greek}/u,RE_SCRIPT_HEBREW=/\p{Script=Hebrew}/u,RE_SCRIPT_JAPANESE=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,RE_SCRIPT_ARABIC_LETTER=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,RE_VIRAMA=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,RE_RFC5892_DISALLOWED=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,RE_CONTEXTO_EXCEPTIONS=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,RE_PVALID_EXCEPTIONS=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,RE_EUROPEAN_NUMBER=new RegExp([RE_ASCII_DIGIT,RE_EXT_ARABIC_INDIC_DIGIT].map((regexp)=>regexp.source).join("|"),"u"),RE_PERMITTED_CATEGORY=new RegExp([RE_LETTER,RE_EUROPEAN_SEPARATOR,RE_COMMON_SEPARATOR,RE_NUMBER_DECIMAL,RE_MARK_NONSPACING,RE_MARK_SPACING_COMBINING,RE_CONTEXTO_EXCEPTIONS,RE_PVALID_EXCEPTIONS].map((regexp)=>regexp.source).join("|"),"u");function IsAsciiLabel(value){return RE_RULE_HYPHEN_PLACEMENT.test(value)&&RE_RULE_NOT_RESERVED_ACE.test(value)&&RE_ASCII_LDH.test(value)}var PUNYCODE_BASE=36,PUNYCODE_TMIN=1,PUNYCODE_TMAX=26,PUNYCODE_SKEW=38,PUNYCODE_DAMP=700,PUNYCODE_INITIAL_BIAS=72,PUNYCODE_INITIAL_N=128;function ThrowDontCare(){throw null}function IsAcePrefixed(value){return value.toLowerCase().startsWith("xn--")}function Adapt(delta,numPoints,firstTime){delta=firstTime?Math.floor(delta/PUNYCODE_DAMP):delta>>1,delta+=Math.floor(delta/numPoints);let k=0;while(delta>(PUNYCODE_BASE-PUNYCODE_TMIN)*PUNYCODE_TMAX>>1)delta=Math.floor(delta/(PUNYCODE_BASE-PUNYCODE_TMIN)),k+=PUNYCODE_BASE;return k+Math.floor((PUNYCODE_BASE-PUNYCODE_TMIN+1)*delta/(delta+PUNYCODE_SKEW))}function Decode(value){let output=[],n=PUNYCODE_INITIAL_N,i=0,bias=PUNYCODE_INITIAL_BIAS,delimIdx=value.lastIndexOf("-");if(delimIdx>0)for(let j=0;j<delimIdx;j++){let cp=value.charCodeAt(j);if(cp>=128)ThrowDontCare();output.push(cp)}let inIdx=delimIdx<0?0:delimIdx+1;while(inIdx<value.length){let oldi=i,w=1,k=PUNYCODE_BASE;while(!0){if(inIdx>=value.length)ThrowDontCare();let ch=value.charCodeAt(inIdx++),digit;if(ch>=97&&ch<=122)digit=ch-97;else if(ch>=48&&ch<=57)digit=ch-48+26;else ThrowDontCare();i+=digit*w;let t=k<=bias?PUNYCODE_TMIN:k>=bias+PUNYCODE_TMAX?PUNYCODE_TMAX:k-bias;if(digit<t)break;w*=PUNYCODE_BASE-t,k+=PUNYCODE_BASE}let outLen=output.length+1;bias=Adapt(i-oldi,outLen,oldi===0),n+=Math.floor(i/outLen),i%=outLen,output.splice(i,0,n),i++}return String.fromCodePoint(...output)}function DigitToChar(digit){return digit<26?String.fromCharCode(digit+97):String.fromCharCode(digit-26+48)}var RE_REPLACE_NON_ASCII=new RegExp(RE_NON_ASCII.source,"gu");function Encode(input){let basic=input.replace(RE_REPLACE_NON_ASCII,""),basicLength=basic.length,result=basicLength>0?[basic,"-"]:[],codePoints=Array.from(input,(char)=>char.codePointAt(0)),n=PUNYCODE_INITIAL_N,delta=0,bias=PUNYCODE_INITIAL_BIAS,handledCPCount=basicLength;while(handledCPCount<codePoints.length){let m=1/0;for(let cp of codePoints)if(cp>=n&&cp<m)m=cp;delta+=(m-n)*(handledCPCount+1),n=m;for(let cp of codePoints){if(cp<n)delta++;if(cp===n){let q=delta;for(let k=PUNYCODE_BASE;;k+=PUNYCODE_BASE){let t=k<=bias?PUNYCODE_TMIN:k>=bias+PUNYCODE_TMAX?PUNYCODE_TMAX:k-bias;if(q<t)break;let digit=t+(q-t)%(PUNYCODE_BASE-t);result.push(DigitToChar(digit)),q=Math.floor((q-t)/(PUNYCODE_BASE-t))}result.push(DigitToChar(q)),bias=Adapt(delta,handledCPCount+1,handledCPCount===basicLength),delta=0,handledCPCount++}}delta++,n++}return result.join("")}var RE_RTL_ALLOWED=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,RE_LTR_ALLOWED=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,RE_RTL_CLASSES=/^(?:R|AL|AN)$/;function HasBidiChars(value){if(IsAcePrefixed(value))try{return HasRightToLeftCharacters(Decode(value.slice(4).toLowerCase()))}catch{return!1}return HasRightToLeftCharacters(value)}function GetBidiClass(codePoint){let char=String.fromCodePoint(codePoint);return RE_EUROPEAN_NUMBER.test(char)?"EN":RE_ARABIC_INDIC_DIGIT.test(char)?"AN":RE_MARK_NONSPACING.test(char)?"NSM":RE_SCRIPT_HEBREW.test(char)?"R":RE_SCRIPT_ARABIC_LETTER.test(char)?"AL":RE_LETTER.test(char)?"L":"ON"}function HasRightToLeftCharacters(value){for(let ch of value)if(RE_RTL_CLASSES.test(GetBidiClass(ch.codePointAt(0))))return!0;return!1}function SatisfiesBidiRule(value){let isRtl=!1,allowed=RE_LTR_ALLOWED,sawEN=!1,sawAN=!1,isFirst=!0;for(let ch of value){let bidiClass=GetBidiClass(ch.codePointAt(0));if(isFirst){if(bidiClass!=="L"&&bidiClass!=="R"&&bidiClass!=="AL")return!1;isRtl=bidiClass==="R"||bidiClass==="AL",allowed=isRtl?RE_RTL_ALLOWED:RE_LTR_ALLOWED,isFirst=!1}if(!allowed.test(bidiClass))return!1;if(bidiClass==="EN")sawEN=!0;else if(bidiClass==="AN")sawAN=!0}if(isRtl&&sawEN&&sawAN)return!1;return!0}function ExceedsMaxALabelLength(value){return RE_NON_ASCII.test(value)&&Encode(value).length+4>63}function HasInvalidHyphens(chars){if(chars[0]==="-"||chars[chars.length-1]==="-")return!0;return chars.slice(2).join("").startsWith("--")}function IsUnicodeLabel(value){if(ExceedsMaxALabelLength(value))return!1;if(HasRightToLeftCharacters(value)&&!SatisfiesBidiRule(value))return!1;let chars=[...value],codePoints=chars.map((c)=>c.codePointAt(0)),length=codePoints.length;if(HasInvalidHyphens(chars))return!1;if(RE_COMBINING_MARK.test(chars[0]))return!1;let hasJapanese=!1;for(let i=0;i<length;i++){let codePoint=codePoints[i],char=chars[i];if(RE_RFC5892_DISALLOWED.test(char))return!1;if(!RE_PERMITTED_CATEGORY.test(char))return!1;if(RE_SCRIPT_JAPANESE.test(char))hasJapanese=!0;let prev=codePoints[i-1],next=codePoints[i+1];switch(codePoint){case 183:if(prev!==108||next!==108)return!1;break;case 885:if(!next||!RE_SCRIPT_GREEK.test(chars[i+1]))return!1;break;case 1523:case 1524:if(!prev||!RE_SCRIPT_HEBREW.test(chars[i-1]))return!1;break;case 8204:if(!prev||prev<128&&!RE_VIRAMA.test(chars[i-1]))return!1;break;case 8205:if(!prev||!RE_VIRAMA.test(chars[i-1]))return!1;break;case 12539:break}}if(value.includes("・")&&!hasJapanese)return!1;return!0}function IsPunyLabel(value){if(!IsAcePrefixed(value))return!1;try{let body=value.slice(4).toLowerCase();if(body.lastIndexOf("-")===0)return!1;let decoded=Decode(body);if(!RE_NON_ASCII.test(decoded))return!1;return IsUnicodeLabel(decoded)}catch{return!1}}function IsValidLabelLength(value){return value.length>0&&value.length<=63}function IsLabel(value){return IsValidLabelLength(value)&&(IsPunyLabel(value)||IsAsciiLabel(value))}function IsHostname(value){if(value.length===0||value.length>253)return!1;if(value.charCodeAt(value.length-1)===46)return!1;return value.split(".").every((label)=>IsLabel(label))}function IsValidLabelLength2(value){return value.length>0&&value.length<=63}function IsLabel2(value){return IsValidLabelLength2(value)&&(IsPunyLabel(value)||IsUnicodeLabel(value))}function NormalizeHostname(value){return value.replace(/[\uff01-\uff5e]/g,(char)=>String.fromCharCode(char.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function IsIdnHostname(value){if(value.length===0||value.includes(" "))return!1;let normalized=NormalizeHostname(value);if(normalized.length>253)return!1;let labels=normalized.split("."),hasBidiChars=labels.some((label)=>HasBidiChars(label));return labels.every((label)=>IsLabel2(label)&&(!hasBidiChars||SatisfiesBidiRule(label)))}function IsHostname2(value){return IsHostname(value)}var IdnEmail=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function IsIdnEmail(value){return IdnEmail.test(value.normalize("NFC"))}function IsIdnHostname2(value){return IsIdnHostname(value)}var IPv4=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function IsIPv4(value){return IPv4.test(value)}var IPv6=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function IsIPv6(value){return IPv6.test(value)}var InvalidIriChars=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,MalformedScheme=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function IsIriReference(value){return!InvalidIriChars.test(value)&&!MalformedScheme.test(value)&&URL.canParse(value,"http://example.com")}var InvalidIriChars2=/[\x00-\x20<>\^`{|}\\]/,InvalidPercentEncoding=/%(?![0-9a-fA-F]{2})/;function IsIri(value){if(InvalidIriChars2.test(value))return!1;if(InvalidPercentEncoding.test(value))return!1;return URL.canParse(value)}var JsonPointerUriFragment=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function IsJsonPointerUriFragment(value){return JsonPointerUriFragment.test(value)}var JsonPointer=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function IsJsonPointer(value){return JsonPointer.test(value)}function IsRegex(value){try{return new RegExp(value,"u"),!0}catch{return!1}}var RelativeJsonPointer=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function IsRelativeJsonPointer(value){return RelativeJsonPointer.test(value)}var UriReference=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function IsUriReference(value){return UriReference.test(value)}var UriTemplate=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function IsUriTemplate(value){return UriTemplate.test(value)}var Uri=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function IsUri(value){return Uri.test(value)}function IsUrl(value){return URL.canParse(value)}var Uuid=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function IsUuid(value){return Uuid.test(value)}var formats=new Map;function Clear(){formats.clear()}function Test(format,value){return formats.get(format)?.(value)??!0}function Reset(){Clear(),formats.set("date-time",IsDateTime),formats.set("date",IsDate2),formats.set("duration",IsDuration),formats.set("email",IsEmail),formats.set("hostname",IsHostname2),formats.set("idn-email",IsIdnEmail),formats.set("idn-hostname",IsIdnHostname2),formats.set("ipv4",IsIPv4),formats.set("ipv6",IsIPv6),formats.set("iri-reference",IsIriReference),formats.set("iri",IsIri),formats.set("json-pointer-uri-fragment",IsJsonPointerUriFragment),formats.set("json-pointer",IsJsonPointer),formats.set("regex",IsRegex),formats.set("relative-json-pointer",IsRelativeJsonPointer),formats.set("time",IsTime),formats.set("uri-reference",IsUriReference),formats.set("uri-template",IsUriTemplate),formats.set("uri",IsUri),formats.set("url",IsUrl),formats.set("uuid",IsUuid)}Reset();function CheckFormat(_stack,_context,schema,value){return Test(schema.format,value)}function ErrorFormat(stack,context,schemaPath,instancePath,schema,value){return CheckFormat(stack,context,schema,value)||context.AddError("format",schemaPath,instancePath,{format:schema.format})}function CheckIf(stack,context,schema,value){let thenSchema=IsThen(schema)?schema.then:!0,elseSchema=IsElse(schema)?schema.else:!0;return CheckSchema(stack,context,schema.if,value)?CheckSchema(stack,context,thenSchema,value):CheckSchema(stack,context,elseSchema,value)}function ErrorIf(stack,context,schemaPath,instancePath,schema,value){let thenSchema=IsThen(schema)?schema.then:!0,elseSchema=IsElse(schema)?schema.else:!0,trueContext=new ErrorContext,isIf=ErrorSchema(stack,trueContext,`${schemaPath}/if`,instancePath,schema.if,value)?ErrorSchema(stack,trueContext,`${schemaPath}/then`,instancePath,thenSchema,value)||context.AddError("if",schemaPath,instancePath,{failingKeyword:"then"}):ErrorSchema(stack,context,`${schemaPath}/else`,instancePath,elseSchema,value)||context.AddError("if",schemaPath,instancePath,{failingKeyword:"else"});if(isIf)context.Merge([trueContext]);return isIf}function CheckItemsSized(stack,context,schema,value){return Every(schema.items,0,(schema,index)=>IsLessEqualThan(value.length,index)||CheckSchemaPushStack(stack,context,schema,value[index])&&context.AddIndex(index))}function ErrorItemsSized(stack,context,schemaPath,instancePath,schema,value){return EveryAll(schema.items,0,(schema,index)=>{let nextSchemaPath=`${schemaPath}/items/${index}`,nextInstancePath=`${instancePath}/${index}`;return IsLessEqualThan(value.length,index)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[index])&&context.AddIndex(index)})}function CheckItemsUnsized(stack,context,schema,value){let offset=IsPrefixItems(schema)?schema.prefixItems.length:0;return Every(value,offset,(element,index)=>CheckSchemaPushStack(stack,context,schema.items,element)&&context.AddIndex(index))}function ErrorItemsUnsized(stack,context,schemaPath,instancePath,schema,value){let offset=IsPrefixItems(schema)?schema.prefixItems.length:0;return EveryAll(value,offset,(element,index)=>{let nextSchemaPath=`${schemaPath}/items`,nextInstancePath=`${instancePath}/${index}`;return ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema.items,element)&&context.AddIndex(index)})}function CheckItems(stack,context,schema,value){return IsItemsSized(schema)?CheckItemsSized(stack,context,schema,value):CheckItemsUnsized(stack,context,schema,value)}function ErrorItems(stack,context,schemaPath,instancePath,schema,value){return IsItemsSized(schema)?ErrorItemsSized(stack,context,schemaPath,instancePath,schema,value):ErrorItemsUnsized(stack,context,schemaPath,instancePath,schema,value)}function IsValid3(schema){return IsContains(schema)}function CheckMaxContains(stack,context,schema,value){if(!IsValid3(schema))return!0;let count=Counted(value,(item)=>CheckSchema(stack,context,schema.contains,item));return IsLessEqualThan(count,schema.maxContains)}function ErrorMaxContains(stack,context,schemaPath,instancePath,schema,value){let minContains=IsMinContains(schema)?schema.minContains:1;return CheckMaxContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains,maxContains:schema.maxContains})}function CheckMaximum(_stack,_context,schema,value){return IsLessEqualThan(value,schema.maximum)}function ErrorMaximum(stack,context,schemaPath,instancePath,schema,value){return CheckMaximum(stack,context,schema,value)||context.AddError("maximum",schemaPath,instancePath,{comparison:"<=",limit:schema.maximum})}function CheckMaxItems(_stack,_context,schema,value){return IsLessEqualThan(value.length,schema.maxItems)}function ErrorMaxItems(stack,context,schemaPath,instancePath,schema,value){return CheckMaxItems(stack,context,schema,value)||context.AddError("maxItems",schemaPath,instancePath,{limit:schema.maxItems})}function CheckMaxLength(_stack,_context,schema,value){return IsMaxLength2(value,schema.maxLength)}function ErrorMaxLength(stack,context,schemaPath,instancePath,schema,value){return CheckMaxLength(stack,context,schema,value)||context.AddError("maxLength",schemaPath,instancePath,{limit:schema.maxLength})}function CheckMaxProperties(_stack,_context,schema,value){return IsLessEqualThan(Keys(value).length,schema.maxProperties)}function ErrorMaxProperties(stack,context,schemaPath,instancePath,schema,value){return CheckMaxProperties(stack,context,schema,value)||context.AddError("maxProperties",schemaPath,instancePath,{limit:schema.maxProperties})}function IsValid4(schema){return IsContains(schema)}function CheckMinContains(stack,context,schema,value){if(!IsValid4(schema))return!0;let count=Counted(value,(item,index)=>CheckSchema(stack,context,schema.contains,item)&&context.AddIndex(index));return IsGreaterEqualThan(count,schema.minContains)}function ErrorMinContains(stack,context,schemaPath,instancePath,schema,value){return CheckMinContains(stack,context,schema,value)||context.AddError("contains",schemaPath,instancePath,{minContains:schema.minContains})}function CheckMinimum(_stack,_context,schema,value){return IsGreaterEqualThan(value,schema.minimum)}function ErrorMinimum(stack,context,schemaPath,instancePath,schema,value){return CheckMinimum(stack,context,schema,value)||context.AddError("minimum",schemaPath,instancePath,{comparison:">=",limit:schema.minimum})}function CheckMinItems(_stack,_context,schema,value){return IsGreaterEqualThan(value.length,schema.minItems)}function ErrorMinItems(stack,context,schemaPath,instancePath,schema,value){return CheckMinItems(stack,context,schema,value)||context.AddError("minItems",schemaPath,instancePath,{limit:schema.minItems})}function CheckMinLength(_stack,_context,schema,value){return IsMinLength2(value,schema.minLength)}function ErrorMinLength(stack,context,schemaPath,instancePath,schema,value){return CheckMinLength(stack,context,schema,value)||context.AddError("minLength",schemaPath,instancePath,{limit:schema.minLength})}function CheckMinProperties(_stack,_context,schema,value){return IsGreaterEqualThan(Keys(value).length,schema.minProperties)}function ErrorMinProperties(stack,context,schemaPath,instancePath,schema,value){return CheckMinProperties(stack,context,schema,value)||context.AddError("minProperties",schemaPath,instancePath,{limit:schema.minProperties})}function CheckMultipleOf(_stack,_context,schema,value){return IsMultipleOf(value,schema.multipleOf)}function ErrorMultipleOf(stack,context,schemaPath,instancePath,schema,value){return CheckMultipleOf(stack,context,schema,value)||context.AddError("multipleOf",schemaPath,instancePath,{multipleOf:schema.multipleOf})}function CheckNot(stack,context,schema,value){let nextContext=new CheckContext;return!CheckSchema(stack,nextContext,schema.not,value)&&context.Merge([nextContext])}function ErrorNot(stack,context,schemaPath,instancePath,schema,value){return CheckNot(stack,context,schema,value)||context.AddError("not",schemaPath,instancePath,{})}function CheckOneOf(stack,context,schema,value){let passedContexts=schema.oneOf.reduce((result,schema)=>{let nextContext=new CheckContext;return CheckSchema(stack,nextContext,schema,value)?[...result,nextContext]:result},[]);return IsEqual(passedContexts.length,1)&&context.Merge(passedContexts)}function ErrorOneOf(stack,context,schemaPath,instancePath,schema,value){let failedContexts=[],passingSchemas=[],passedContexts=schema.oneOf.reduce((result,schema,index)=>{let nextContext=new ErrorContext,nextSchemaPath=`${schemaPath}/oneOf/${index}`,isSchema=ErrorSchema(stack,nextContext,nextSchemaPath,instancePath,schema,value);if(isSchema)passingSchemas.push(index);if(!isSchema)failedContexts.push(nextContext);return isSchema?[...result,nextContext]:result},[]),isOneOf=IsEqual(passedContexts.length,1)&&context.Merge(passedContexts);if(!isOneOf&&IsEqual(passingSchemas.length,0))failedContexts.forEach((failed)=>context.AddErrors(failed.GetErrors()));return isOneOf||context.AddError("oneOf",schemaPath,instancePath,{passingSchemas})}function CheckPattern(_stack,_context,schema,value){return(IsString(schema.pattern)?UnicodeRegExp(schema.pattern):schema.pattern).test(value)}function ErrorPattern(stack,context,schemaPath,instancePath,schema,value){return CheckPattern(stack,context,schema,value)||context.AddError("pattern",schemaPath,instancePath,{pattern:schema.pattern})}function CheckPatternProperties(stack,context,schema,value){return Every(Entries(schema.patternProperties),0,([pattern,schema])=>{let regexp=UnicodeRegExp(pattern);return Every(Entries(value),0,([key,prop])=>!regexp.test(key)||CheckSchemaPushStack(stack,context,schema,prop)&&context.AddKey(key))})}function ErrorPatternProperties(stack,context,schemaPath,instancePath,schema,value){return EveryAll(Entries(schema.patternProperties),0,([pattern,schema])=>{let nextSchemaPath=`${schemaPath}/patternProperties/${EncodeFragment(pattern)}`,regexp=UnicodeRegExp(pattern);return EveryAll(Entries(value),0,([key,value])=>{let nextInstancePath=`${instancePath}/${EncodeFragment(key)}`;return!regexp.test(key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value)&&context.AddKey(key)})})}function CheckPrefixItems(stack,context,schema,value){return IsEqual(value.length,0)||Every(schema.prefixItems,0,(schema,index)=>IsLessEqualThan(value.length,index)||CheckSchemaPushStack(stack,context,schema,value[index])&&context.AddIndex(index))}function ErrorPrefixItems(stack,context,schemaPath,instancePath,schema,value){return IsEqual(value.length,0)||EveryAll(schema.prefixItems,0,(schema,index)=>{let nextSchemaPath=`${schemaPath}/prefixItems/${index}`,nextInstancePath=`${instancePath}/${index}`;return IsLessEqualThan(value.length,index)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[index])&&context.AddIndex(index)})}function IsExactOptional(required,key){return required.includes(key)||Get().exactOptionalPropertyTypes}function InexactOptionalCheck(value,key){return IsUndefined(value[key])}function CheckProperties(stack,context,schema,value){let required=IsRequired(schema)?schema.required:[];return Every(Entries(schema.properties),0,([key,schema])=>{let isProperty=!HasPropertyKey(value,key)||CheckSchemaPushStack(stack,context,schema,value[key])&&context.AddKey(key);return IsExactOptional(required,key)?isProperty:InexactOptionalCheck(value,key)||isProperty})}function ErrorProperties(stack,context,schemaPath,instancePath,schema,value){let required=IsRequired(schema)?schema.required:[];return EveryAll(Entries(schema.properties),0,([key,schema])=>{let nextSchemaPath=`${schemaPath}/properties/${EncodeFragment(key)}`,nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,isProperty=()=>!HasPropertyKey(value,key)||ErrorSchemaPushStack(stack,context,nextSchemaPath,nextInstancePath,schema,value[key])&&context.AddKey(key);return IsExactOptional(required,key)?isProperty():InexactOptionalCheck(value,key)||isProperty()})}function CheckPropertyNames(stack,context,schema,value){return Every(Keys(value),0,(key,_index)=>CheckSchema(stack,context,schema.propertyNames,key))}function ErrorPropertyNames(stack,context,schemaPath,instancePath,schema,value){let propertyNames=[];return EveryAll(Keys(value),0,(key,_index)=>{let nextInstancePath=`${instancePath}/${EncodeFragment(key)}`,nextSchemaPath=`${schemaPath}/propertyNames`,isPropertyName=ErrorSchema(stack,context,nextSchemaPath,nextInstancePath,schema.propertyNames,key);if(!isPropertyName)propertyNames.push(key);return isPropertyName})||context.AddError("propertyNames",schemaPath,instancePath,{propertyNames})}function CheckRecursiveRef(stack,context,schema,value){let target=RecursiveRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&CheckSchema(nextStack,context,target,value)}function ErrorRecursiveRef(stack,context,schemaPath,instancePath,schema,value){let target=RecursiveRef(stack,schema)??!1,nextStack=target?{...stack,pendingResource:!0}:stack;return IsSchema(target)&&ErrorSchema(nextStack,context,schemaPath,instancePath,target,value)}function CheckRef(stack,context,schema,value){let result=Ref(stack,schema),target=result.schema??!1,nextContext=new CheckContext,valid=IsSchema(target)&&CheckSchema(result.stack,nextContext,target,value);if(valid)context.Merge([nextContext]);return valid}function ErrorRef(stack,context,schemaPath,instancePath,schema,value){let result=Ref(stack,schema),target=result.schema??!1,nextContext=new ErrorContext,valid=IsSchema(target)&&ErrorSchema(result.stack,nextContext,schemaPath,instancePath,target,value);if(valid)context.Merge([nextContext]);if(!valid)context.AddErrors(nextContext.GetErrors());return valid}function CheckRequired(_stack,_context,schema,value){return Every(schema.required,0,(key)=>HasPropertyKey(value,key))}function ErrorRequired(_stack,context,schemaPath,instancePath,schema,value){let requiredProperties=[];return EveryAll(schema.required,0,(key)=>{let hasKey=HasPropertyKey(value,key);if(!hasKey)requiredProperties.push(key);return hasKey})||context.AddError("required",schemaPath,instancePath,{requiredProperties})}function CheckTypeName(_stack,_context,type,_schema,value){return IsEqual(type,"object")?IsObjectNotArray(value):IsEqual(type,"array")?IsArray(value):IsEqual(type,"boolean")?IsBoolean(value):IsEqual(type,"integer")?IsInteger(value):IsEqual(type,"number")?IsNumber(value):IsEqual(type,"null")?IsNull(value):IsEqual(type,"string")?IsString(value):IsEqual(type,"bigint")?IsBigInt(value):IsEqual(type,"constructor")?IsConstructor(value):IsEqual(type,"function")?IsFunction(value):IsEqual(type,"symbol")?IsSymbol(value):IsEqual(type,"undefined")?IsUndefined(value):IsEqual(type,"void")?IsUndefined(value):!0}function CheckTypeNames(stack,context,types,schema,value){return Some(types,(type)=>CheckTypeName(stack,context,type,schema,value))}function CheckType(stack,context,schema,value){return IsArray(schema.type)?CheckTypeNames(stack,context,schema.type,schema,value):CheckTypeName(stack,context,schema.type,schema,value)}function ErrorType(stack,context,schemaPath,instancePath,schema,value){return(IsArray(schema.type)?CheckTypeNames(stack,context,schema.type,schema,value):CheckTypeName(stack,context,schema.type,schema,value))||context.AddError("type",schemaPath,instancePath,{type:schema.type})}function CheckUnevaluatedItems(stack,context,schema,value){let indices=context.GetIndices();return Every(value,0,(item,index)=>(indices.has(index)||CheckSchema(stack,context,schema.unevaluatedItems,item))&&context.AddIndex(index))}function ErrorUnevaluatedItems(stack,context,schemaPath,instancePath,schema,value){let indices=context.GetIndices(),unevaluatedItems=[];return EveryAll(value,0,(item,index)=>{let nextContext=new ErrorContext,isEvaluatedItem=(indices.has(index)||ErrorSchema(stack,nextContext,schemaPath,instancePath,schema.unevaluatedItems,item))&&context.AddIndex(index);if(!isEvaluatedItem)unevaluatedItems.push(index);return isEvaluatedItem})||context.AddError("unevaluatedItems",schemaPath,instancePath,{unevaluatedItems})}function CheckUnevaluatedProperties(stack,context,schema,value){let keys=context.GetKeys();return Every(Entries(value),0,([key,prop])=>keys.has(key)||CheckSchema(stack,context,schema.unevaluatedProperties,prop)&&context.AddKey(key))}function ErrorUnevaluatedProperties(stack,context,schemaPath,instancePath,schema,value){let keys=context.GetKeys(),unevaluatedProperties=[];return EveryAll(Entries(value),0,([key,prop])=>{let nextContext=new ErrorContext,isEvaluatedProperty=keys.has(key)||ErrorSchema(stack,nextContext,schemaPath,instancePath,schema.unevaluatedProperties,prop)&&context.AddKey(key);if(!isEvaluatedProperty)unevaluatedProperties.push(key);return isEvaluatedProperty})||context.AddError("unevaluatedProperties",schemaPath,instancePath,{unevaluatedProperties})}function Unreachable(){throw Error("Unreachable")}function InstanceKeys(value){let propertyKeys=new Set,current=value;while(current&&current!==Object.prototype){for(let key of Reflect.ownKeys(current))if(key!=="constructor"&&typeof key!=="symbol")propertyKeys.add(key);current=Object.getPrototypeOf(current)}return[...propertyKeys]}function IsIEEE754(value){return typeof value==="number"}var ByteMarker;(function(ByteMarker){ByteMarker[ByteMarker.Array=0]="Array",ByteMarker[ByteMarker.BigInt=1]="BigInt",ByteMarker[ByteMarker.Boolean=2]="Boolean",ByteMarker[ByteMarker.Date=3]="Date",ByteMarker[ByteMarker.Constructor=4]="Constructor",ByteMarker[ByteMarker.Function=5]="Function",ByteMarker[ByteMarker.Null=6]="Null",ByteMarker[ByteMarker.Number=7]="Number",ByteMarker[ByteMarker.Object=8]="Object",ByteMarker[ByteMarker.RegExp=9]="RegExp",ByteMarker[ByteMarker.String=10]="String",ByteMarker[ByteMarker.Symbol=11]="Symbol",ByteMarker[ByteMarker.TypeArray=12]="TypeArray",ByteMarker[ByteMarker.Undefined=13]="Undefined"})(ByteMarker||(ByteMarker={}));var Accumulator=BigInt("14695981039346656037"),[Prime,Size]=[BigInt("1099511628211"),BigInt("18446744073709551616")],Bytes=Array.from({length:256}).map((_,i)=>BigInt(i)),F64=new Float64Array(1),F64In=new DataView(F64.buffer),F64Out=new Uint8Array(F64.buffer);function FNV1A64_OP(byte){Accumulator=Accumulator^Bytes[byte],Accumulator=Accumulator*Prime%Size}function FromArray(value){FNV1A64_OP(ByteMarker.Array);for(let item of value)FromValue(item)}function FromBigInt(value){FNV1A64_OP(ByteMarker.BigInt),F64In.setBigInt64(0,value);for(let byte of F64Out)FNV1A64_OP(byte)}function FromBoolean(value){FNV1A64_OP(ByteMarker.Boolean),FNV1A64_OP(value?1:0)}function FromConstructor(value){FNV1A64_OP(ByteMarker.Constructor),FromValue(value.toString())}function FromDate(value){FNV1A64_OP(ByteMarker.Date),FromValue(value.getTime())}function FromFunction(value){FNV1A64_OP(ByteMarker.Function),FromValue(value.toString())}function FromNull(_value){FNV1A64_OP(ByteMarker.Null)}function FromNumber(value){FNV1A64_OP(ByteMarker.Number),F64In.setFloat64(0,value,!0);for(let byte of F64Out)FNV1A64_OP(byte)}function FromObject(value){FNV1A64_OP(ByteMarker.Object);for(let key of InstanceKeys(value).sort())FromValue(key),FromValue(value[key])}function FromRegExp(value){FNV1A64_OP(ByteMarker.RegExp),FromString(value.toString())}var encoder=new TextEncoder;function FromString(value){FNV1A64_OP(ByteMarker.String);for(let byte of encoder.encode(value))FNV1A64_OP(byte)}function FromSymbol(value){FNV1A64_OP(ByteMarker.Symbol),FromValue(value.toString())}function FromTypeArray(value){FNV1A64_OP(ByteMarker.TypeArray);let buffer=new Uint8Array(value.buffer);for(let i=0;i<buffer.length;i++)FNV1A64_OP(buffer[i])}function FromUndefined(_value){return FNV1A64_OP(ByteMarker.Undefined)}function FromValue(value){return IsTypeArray(value)?FromTypeArray(value):IsDate(value)?FromDate(value):IsRegExp(value)?FromRegExp(value):IsBoolean2(value)?FromBoolean(value.valueOf()):IsString2(value)?FromString(value.valueOf()):IsNumber2(value)?FromNumber(value.valueOf()):IsIEEE754(value)?FromNumber(value):IsArray(value)?FromArray(value):IsBoolean(value)?FromBoolean(value):IsBigInt(value)?FromBigInt(value):IsConstructor(value)?FromConstructor(value):IsNull(value)?FromNull(value):IsObject(value)?FromObject(value):IsString(value)?FromString(value):IsSymbol(value)?FromSymbol(value):IsUndefined(value)?FromUndefined(value):IsFunction(value)?FromFunction(value):Unreachable()}function HashCode(value){return Accumulator=BigInt("14695981039346656037"),FromValue(value),Accumulator}function Hash(value){return HashCode(value).toString(16).padStart(16,"0")}function IsValid5(schema){return!IsEqual(schema.uniqueItems,!1)}function CheckUniqueItems(_stack,_context,schema,value){if(!IsValid5(schema))return!0;let set=new Set(value.map(Hash)).size,isLength=value.length;return IsEqual(set,isLength)}function ErrorUniqueItems(_stack,context,schemaPath,instancePath,schema,value){if(!IsValid5(schema))return!0;let set=new Set,duplicateItems=value.reduce((result,value,index)=>{let hash=Hash(value);if(set.has(hash))return[...result,index];return set.add(hash),result},[]);return IsEqual(duplicateItems.length,0)||context.AddError("uniqueItems",schemaPath,instancePath,{duplicateItems})}function CheckSchemaPushStack(stack,context,schema,value){return context.Push()&&CheckSchema(stack,context,schema,value)&&context.Pop()}function CheckSchema(stack,context,schema,value){let current=NextStack(stack,schema);return IsSchemaBoolean(schema)?CheckSchemaBoolean(current,context,schema,value):(!IsType(schema)||CheckType(current,context,schema,value))&&(!(IsObject(value)&&!IsArray(value))||(!IsRequired(schema)||CheckRequired(current,context,schema,value))&&(!IsAdditionalProperties(schema)||CheckAdditionalProperties(current,context,schema,value))&&(!IsDependencies(schema)||CheckDependencies(current,context,schema,value))&&(!IsDependentRequired(schema)||CheckDependentRequired(current,context,schema,value))&&(!IsDependentSchemas(schema)||CheckDependentSchemas(current,context,schema,value))&&(!IsPatternProperties(schema)||CheckPatternProperties(current,context,schema,value))&&(!IsProperties(schema)||CheckProperties(current,context,schema,value))&&(!IsPropertyNames(schema)||CheckPropertyNames(current,context,schema,value))&&(!IsMinProperties(schema)||CheckMinProperties(current,context,schema,value))&&(!IsMaxProperties(schema)||CheckMaxProperties(current,context,schema,value)))&&(!IsArray(value)||(!IsAdditionalItems(schema)||CheckAdditionalItems(current,context,schema,value))&&(!IsContains(schema)||CheckContains(current,context,schema,value))&&(!IsItems(schema)||CheckItems(current,context,schema,value))&&(!IsMinContains(schema)||CheckMinContains(current,context,schema,value))&&(!IsMaxContains(schema)||CheckMaxContains(current,context,schema,value))&&(!IsMinItems(schema)||CheckMinItems(current,context,schema,value))&&(!IsMaxItems(schema)||CheckMaxItems(current,context,schema,value))&&(!IsPrefixItems(schema)||CheckPrefixItems(current,context,schema,value))&&(!IsUniqueItems(schema)||CheckUniqueItems(current,context,schema,value)))&&(!IsString(value)||(!IsMinLength3(schema)||CheckMinLength(current,context,schema,value))&&(!IsMaxLength3(schema)||CheckMaxLength(current,context,schema,value))&&(!IsFormat(schema)||CheckFormat(current,context,schema,value))&&(!IsPattern(schema)||CheckPattern(current,context,schema,value)))&&(!(IsNumber(value)||IsBigInt(value))||(!IsExclusiveMinimum(schema)||CheckExclusiveMinimum(current,context,schema,value))&&(!IsExclusiveMaximum(schema)||CheckExclusiveMaximum(current,context,schema,value))&&(!IsMinimum(schema)||CheckMinimum(current,context,schema,value))&&(!IsMaximum(schema)||CheckMaximum(current,context,schema,value))&&(!IsMultipleOf2(schema)||CheckMultipleOf(current,context,schema,value)))&&(!IsRef(schema)||CheckRef(current,context,schema,value))&&(!IsRecursiveRef(schema)||CheckRecursiveRef(current,context,schema,value))&&(!IsDynamicRef(schema)||CheckDynamicRef(current,context,schema,value))&&(!IsConst(schema)||CheckConst(current,context,schema,value))&&(!IsEnum(schema)||CheckEnum(current,context,schema,value))&&(!IsIf(schema)||CheckIf(current,context,schema,value))&&(!IsNot(schema)||CheckNot(current,context,schema,value))&&(!IsAllOf(schema)||CheckAllOf(current,context,schema,value))&&(!IsAnyOf(schema)||CheckAnyOf(current,context,schema,value))&&(!IsOneOf(schema)||CheckOneOf(current,context,schema,value))&&(!IsUnevaluatedItems(schema)||(!IsArray(value)||CheckUnevaluatedItems(current,context,schema,value)))&&(!IsUnevaluatedProperties(schema)||(!IsObject(value)||CheckUnevaluatedProperties(current,context,schema,value)))&&(!IsRefine(schema)||CheckRefine(current,context,schema,value))}function ErrorSchemaPushStack(stack,context,schemaPath,instancePath,schema,value){return context.Push()&&ErrorSchema(stack,context,schemaPath,instancePath,schema,value)&&context.Pop()}function ErrorSchema(stack,context,schemaPath,instancePath,schema,value){if(context.AtCapacity())return!1;let current=NextStack(stack,schema);return IsSchemaBoolean(schema)?ErrorSchemaBoolean(current,context,schemaPath,instancePath,schema,value):!!(+(!IsType(schema)||ErrorType(current,context,schemaPath,instancePath,schema,value))&+(!(IsObject(value)&&!IsArray(value))||!!(+(!IsRequired(schema)||ErrorRequired(current,context,schemaPath,instancePath,schema,value))&+(!IsAdditionalProperties(schema)||ErrorAdditionalProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsDependencies(schema)||ErrorDependencies(current,context,schemaPath,instancePath,schema,value))&+(!IsDependentRequired(schema)||ErrorDependentRequired(current,context,schemaPath,instancePath,schema,value))&+(!IsDependentSchemas(schema)||ErrorDependentSchemas(current,context,schemaPath,instancePath,schema,value))&+(!IsPatternProperties(schema)||ErrorPatternProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsProperties(schema)||ErrorProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsPropertyNames(schema)||ErrorPropertyNames(current,context,schemaPath,instancePath,schema,value))&+(!IsMinProperties(schema)||ErrorMinProperties(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxProperties(schema)||ErrorMaxProperties(current,context,schemaPath,instancePath,schema,value))))&+(!IsArray(value)||!!(+(!IsAdditionalItems(schema)||ErrorAdditionalItems(current,context,schemaPath,instancePath,schema,value))&+(!IsContains(schema)||ErrorContains(current,context,schemaPath,instancePath,schema,value))&+(!IsItems(schema)||ErrorItems(current,context,schemaPath,instancePath,schema,value))&+(!IsMinContains(schema)||ErrorMinContains(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxContains(schema)||ErrorMaxContains(current,context,schemaPath,instancePath,schema,value))&+(!IsMinItems(schema)||ErrorMinItems(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxItems(schema)||ErrorMaxItems(current,context,schemaPath,instancePath,schema,value))&+(!IsPrefixItems(schema)||ErrorPrefixItems(current,context,schemaPath,instancePath,schema,value))&+(!IsUniqueItems(schema)||ErrorUniqueItems(current,context,schemaPath,instancePath,schema,value))))&+(!IsString(value)||!!(+(!IsMinLength3(schema)||ErrorMinLength(current,context,schemaPath,instancePath,schema,value))&+(!IsMaxLength3(schema)||ErrorMaxLength(current,context,schemaPath,instancePath,schema,value))&+(!IsFormat(schema)||ErrorFormat(current,context,schemaPath,instancePath,schema,value))&+(!IsPattern(schema)||ErrorPattern(current,context,schemaPath,instancePath,schema,value))))&+(!(IsNumber(value)||IsBigInt(value))||!!(+(!IsExclusiveMinimum(schema)||ErrorExclusiveMinimum(current,context,schemaPath,instancePath,schema,value))&+(!IsExclusiveMaximum(schema)||ErrorExclusiveMaximum(current,context,schemaPath,instancePath,schema,value))&+(!IsMinimum(schema)||ErrorMinimum(current,context,schemaPath,instancePath,schema,value))&+(!IsMaximum(schema)||ErrorMaximum(current,context,schemaPath,instancePath,schema,value))&+(!IsMultipleOf2(schema)||ErrorMultipleOf(current,context,schemaPath,instancePath,schema,value))))&+(!IsRef(schema)||ErrorRef(current,context,schemaPath,instancePath,schema,value))&+(!IsRecursiveRef(schema)||ErrorRecursiveRef(current,context,schemaPath,instancePath,schema,value))&+(!IsDynamicRef(schema)||ErrorDynamicRef(current,context,schemaPath,instancePath,schema,value))&+(!IsConst(schema)||ErrorConst(current,context,schemaPath,instancePath,schema,value))&+(!IsEnum(schema)||ErrorEnum(current,context,schemaPath,instancePath,schema,value))&+(!IsIf(schema)||ErrorIf(current,context,schemaPath,instancePath,schema,value))&+(!IsNot(schema)||ErrorNot(current,context,schemaPath,instancePath,schema,value))&+(!IsAllOf(schema)||ErrorAllOf(current,context,schemaPath,instancePath,schema,value))&+(!IsAnyOf(schema)||ErrorAnyOf(current,context,schemaPath,instancePath,schema,value))&+(!IsOneOf(schema)||ErrorOneOf(current,context,schemaPath,instancePath,schema,value))&+(!IsUnevaluatedItems(schema)||(!IsArray(value)||ErrorUnevaluatedItems(current,context,schemaPath,instancePath,schema,value)))&+(!IsUnevaluatedProperties(schema)||(!IsObject(value)||ErrorUnevaluatedProperties(current,context,schemaPath,instancePath,schema,value))))&&(!IsRefine(schema)||ErrorRefine(current,context,schemaPath,instancePath,schema,value))}function en_US(error){switch(error.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"dependentRequired":return`must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"exclusiveMinimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"format":return`must match format "${error.params.format}"`;case"if":return`must match "${error.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${error.params.limit} items`;case"maxLength":return`must not have more than ${error.params.limit} characters`;case"maxProperties":return`must not have more than ${error.params.limit} properties`;case"maximum":return`must be ${error.params.comparison} ${error.params.limit}`;case"minItems":return`must not have fewer than ${error.params.limit} items`;case"minLength":return`must not have fewer than ${error.params.limit} characters`;case"minProperties":return`must not have fewer than ${error.params.limit} properties`;case"minimum":return`must be ${error.params.comparison} ${error.params.limit}`;case"multipleOf":return`must be multiple of ${error.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${error.params.pattern}"`;case"propertyNames":return`property names ${error.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${error.params.requiredProperties.join(", ")}`;case"type":return typeof error.params.type==="string"?`must be ${error.params.type}`:`must be either ${error.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return error.params.message;default:return"an unknown validation error occurred"}}var locale=en_US;function Get3(){return locale}var Metrics={assign:0,create:0,clone:0,discard:0,update:0};function Freeze(value){return Get().immutableTypes?Object.freeze(value):value}function Assign(left,right){return Metrics.assign+=1,Freeze({...left,...right})}function FromClassInstance(value){return value}function IsSchemaObject2(value){return HasPropertyKey(value,"~kind")||HasPropertyKey(value,"~unsafe")}function FromSchemaObject(value){let result={};for(let key of Keys(value)){if(IsUnsafePropertyKey(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor.value=FromValue2(descriptor.value),IsEqual(descriptor.enumerable,!0))result[key]=descriptor.value;else Object.defineProperty(result,key,descriptor)}return result}function FromPlainObject(value){let result={};for(let key of Keys(value)){if(IsUnsafePropertyKey(key))continue;result[key]=FromValue2(value[key])}for(let key of Symbols(value))result[key]=FromValue2(value[key]);return result}function FromObject2(value){return IsClassInstance(value)?FromClassInstance(value):IsSchemaObject2(value)?FromSchemaObject(value):FromPlainObject(value)}function FromArray2(value){return value.map((element)=>FromValue2(element))}function FromTypedArray(value){return value.slice()}function FromRegExp2(value){return new RegExp(value.source,value.flags)}function FromMap(value){return new Map(FromValue2([...value.entries()]))}function FromSet(value){return new Set(FromValue2([...value.values()]))}function FromValue2(value){return IsTypeArray(value)?FromTypedArray(value):IsRegExp(value)?FromRegExp2(value):IsMap(value)?FromMap(value):IsSet(value)?FromSet(value):IsArray(value)?FromArray2(value):IsObject(value)?FromObject2(value):value}function Clone(value){return Metrics.clone+=1,FromValue2(value)}function MergeHidden(left,right){for(let key of Object.keys(right))Object.defineProperty(left,key,{configurable:!0,writable:!0,enumerable:!1,value:right[key]});return left}function Merge(left,right){return{...left,...right}}function Create(hidden,enumerable,options={}){Metrics.create+=1;let withOptions=Merge(enumerable,options),withHidden=Get().enumerableKind?Merge(withOptions,hidden):MergeHidden(withOptions,hidden);return Freeze(withHidden)}function Discard(value,propertyKeys){Metrics.discard+=1;let result={};for(let key of Keys(value)){if(propertyKeys.includes(key))continue;let descriptor=Object.getOwnPropertyDescriptor(value,key);descriptor.value=Clone(descriptor.value),Object.defineProperty(result,key,descriptor)}return Freeze(result)}function Update(current,hidden,enumerable){Metrics.update+=1;let settings=Get(),result=Clone(current);for(let key of Object.keys(hidden))Object.defineProperty(result,key,{configurable:!0,writable:!0,enumerable:settings.enumerableKind,value:hidden[key]});for(let key of Object.keys(enumerable))Object.defineProperty(result,key,{configurable:!0,enumerable:!0,writable:!0,value:enumerable[key]});return Freeze(result)}function Errors(...args){let[context,schema,value]=Match(args,{3:(context,schema,value)=>[context,schema,value],2:(schema,value)=>[{},schema,value]}),stack=Stack(context,schema),errorContext=new ErrorContext,result=ErrorSchema(stack,errorContext,"#","",schema,value),errors=errorContext.GetErrors(),locale=Get3(),localized=errors.map((error)=>({...error,message:locale(error)}));return[result,localized]}var TempMaxErrors=0;function EnableParseErrors(){let settings=Get();TempMaxErrors=settings.maxErrors,settings.maxErrors=settings.maxParseErrors}function DisableParseErrors(){let settings=Get();settings.maxErrors=TempMaxErrors}function Check(...args){let[context,schema,value]=Match(args,{3:(context,schema,value)=>[context,schema,value],2:(schema,value)=>[{},schema,value]}),stack=Stack(context,schema),checkContext=new CheckContext;return CheckSchema(stack,checkContext,schema,value)}function Check2(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return Check(context,type,value)}function Errors2(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]}),[_,errors]=Errors(context,type,value);return errors}class AssertError extends Error{constructor(source,value,errors){super(source);Object.defineProperty(this,"cause",{value:{source,errors,value},writable:!1,configurable:!1,enumerable:!1})}}function IsKind(value,kind){return IsObject(value)&&HasPropertyKey(value,"~kind")&&IsEqual(value["~kind"],kind)}function IsSchema2(value){return IsObject(value)}function Deferred(action,parameters,options){return Create({"~kind":"Deferred"},{type:"deferred",action,parameters,options},{})}function IsDeferred(value){return IsKind(value,"Deferred")}function AddReadonlyOperation(type){return Update(type,{"~readonly":!0},{})}function AddReadonlyAction(type,options){return Update(AddReadonlyOperation(type),{},options)}function AddReadonlyInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddReadonlyAction(instantiatedType,options)}function AddOptionalOperation(type){return Update(type,{"~optional":!0},{})}function AddOptionalAction(type,options){return Update(AddOptionalOperation(type),{},options)}function AddOptionalInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddOptionalAction(instantiatedType,options)}function _Array_(items,options){return Create({"~kind":"Array"},{type:"array",items},options)}function IsArray2(value){return IsKind(value,"Array")}function ArrayOptions(type){return Discard(type,["~kind","type","items"])}function Constructor(parameters,instanceType,options={}){return Create({"~kind":"Constructor"},{type:"constructor",parameters,instanceType},options)}function IsConstructor2(value){return IsKind(value,"Constructor")}function ConstructorOptions(type){return Discard(type,["~kind","type","parameters","instanceType"])}function _Function_(parameters,returnType,options={}){return Create({["~kind"]:"Function"},{type:"function",parameters,returnType},options)}function IsFunction2(value){return IsKind(value,"Function")}function FunctionOptions(type){return Discard(type,["~kind","type","parameters","returnType"])}function Ref2(ref,options){return Create({["~kind"]:"Ref"},{$ref:ref},options)}function IsRef2(value){return IsKind(value,"Ref")}function Generic(parameters,expression){return Create({"~kind":"Generic"},{type:"generic",parameters,expression})}function IsGeneric(value){return IsKind(value,"Generic")}function Any(options){return Create({["~kind"]:"Any"},{},options)}function IsAny(value){return IsKind(value,"Any")}var NeverPattern="(?!)";function Never(options){return Create({"~kind":"Never"},{not:{}},options)}function IsNever(value){return IsKind(value,"Never")}function AddOptional(type,options={}){return AddOptionalAction(type,options)}function Optional(type){return AddOptional(type)}function IsOptional(value){return IsSchema2(value)&&HasPropertyKey(value,"~optional")}function RequiredArray(properties){return Keys(properties).filter((key)=>!IsOptional(properties[key]))}function PropertyKeys(properties){return Keys(properties)}function PropertyValues(properties){return Values(properties)}function _Object_(properties,options={}){let requiredKeys=RequiredArray(properties),required=requiredKeys.length>0?{required:requiredKeys}:{};return Create({"~kind":"Object"},{type:"object",...required,properties},options)}function IsObject2(value){return IsKind(value,"Object")}function ObjectOptions(type){return Discard(type,["~kind","type","properties","required"])}function Unknown(options){return Create({["~kind"]:"Unknown"},{},options)}function IsUnknown(value){return IsKind(value,"Unknown")}function Cyclic($defs,$ref,options){let defs=Keys($defs).reduce((result,key)=>({...result,[key]:Update($defs[key],{},{$id:key})}),{});return Create({["~kind"]:"Cyclic"},{$defs:defs,$ref},options)}function IsCyclic(value){return IsKind(value,"Cyclic")}function IsUnsafe(value){return IsObjectNotArray(value)&&HasPropertyKey(value,"~unsafe")&&IsNull(value["~unsafe"])}function IsInfer(value){return IsKind(value,"Infer")}function Dependent(if_,then_,else_,options={}){return Create({"~kind":"Dependent"},{if:if_,then:then_,else:else_},options)}function IsDependent(value){return IsKind(value,"Dependent")}function DependentOptions(type){return Discard(type,["~kind","if","then","else"])}function IsTypeScriptEnumLike(value){return IsObjectNotArray(value)}function TypeScriptEnumToEnumValues(type){return Keys(type).filter((key)=>isNaN(key)).reduce((result,key)=>[...result,type[key]],[])}function Enum(value,options){let values=IsTypeScriptEnumLike(value)?TypeScriptEnumToEnumValues(value):value;return Create({"~kind":"Enum"},{enum:values},options)}function IsEnum2(value){return IsKind(value,"Enum")}function Intersect(types,options={}){return Create({"~kind":"Intersect"},{allOf:types},options)}function IsIntersect(value){return IsKind(value,"Intersect")}function IntersectOptions(type){return Discard(type,["~kind","allOf"])}function IsCodec(value){return IsSchema2(value)&&HasPropertyKey(value,"~codec")&&IsObject(value["~codec"])&&HasPropertyKey(value["~codec"],"encode")&&HasPropertyKey(value["~codec"],"decode")}function IsImmutable(value){return IsSchema2(value)&&HasPropertyKey(value,"~immutable")}function AddReadonly(type,options={}){return AddReadonlyAction(type,options)}function IsReadonly(value){return IsSchema2(value)&&HasPropertyKey(value,"~readonly")}var BigIntPattern="-?(?:0|[1-9][0-9]*)n";function BigInt2(options){return Create({"~kind":"BigInt"},{type:"bigint"},options)}function IsBigInt2(value){return IsKind(value,"BigInt")}function Boolean2(options){return Create({"~kind":"Boolean"},{type:"boolean"},options)}function IsBoolean3(value){return IsKind(value,"Boolean")}var IntegerPattern="-?(?:0|[1-9][0-9]*)";function Integer(options){return Create({"~kind":"Integer"},{type:"integer"},options)}function IsInteger2(value){return IsKind(value,"Integer")}class InvalidLiteralValue extends Error{constructor(value){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value},writable:!1,configurable:!1,enumerable:!1})}}function LiteralTypeName(value){return IsBigInt(value)?"bigint":IsBoolean(value)?"boolean":IsNumber(value)?"number":IsString(value)?"string":(()=>{throw new InvalidLiteralValue(value)})()}function Literal(value,options){return Create({"~kind":"Literal"},{type:LiteralTypeName(value),const:value},options)}function IsLiteralValue(value){return IsBigInt(value)||IsBoolean(value)||IsNumber(value)||IsString(value)}function IsLiteralBigInt(value){return IsLiteral(value)&&IsBigInt(value.const)}function IsLiteralBoolean(value){return IsLiteral(value)&&IsBoolean(value.const)}function IsLiteralNumber(value){return IsLiteral(value)&&IsNumber(value.const)}function IsLiteralString(value){return IsLiteral(value)&&IsString(value.const)}function IsLiteral(value){return IsKind(value,"Literal")}function Null(options){return Create({"~kind":"Null"},{type:"null"},options)}function IsNull2(value){return IsKind(value,"Null")}var NumberPattern="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Number2(options){return Create({"~kind":"Number"},{type:"number"},options)}function IsNumber3(value){return IsKind(value,"Number")}function Symbol2(options){return Create({"~kind":"Symbol"},{type:"symbol"},options)}function IsSymbol2(value){return IsKind(value,"Symbol")}var StringPattern=".*";function String2(options){return Create({"~kind":"String"},{type:"string"},options)}function IsString3(value){return IsKind(value,"String")}function Union(anyOf,options={}){return Create({"~kind":"Union"},{anyOf},options)}function IsUnion(value){return IsKind(value,"Union")}function UnionOptions(type){return Discard(type,["~kind","anyOf"])}function ParsePatternIntoTypes(pattern){let parsed=Pattern(pattern);return IsEqual(parsed.length,2)?parsed[0]:[]}function FromLiteral(_value){return!0}function FromTypesReduce(types){return ShiftLeft(types,(left,right)=>FromType(left)?FromTypesReduce(right):!1,()=>!0)}function FromTypes(types){return IsEqual(types.length,0)?!1:FromTypesReduce(types)}function FromType(type){return IsUnion(type)?FromTypes(type.anyOf):IsLiteral(type)?FromLiteral(type.const):!1}function IsTemplateLiteralFinite(types){return FromTypes(types)}function TemplateLiteralCreate(pattern){return Create({["~kind"]:"TemplateLiteral"},{type:"string",pattern},{})}function FromLiteralPush(variants,value,result=[]){return ShiftLeft(variants,(left,right)=>FromLiteralPush(right,value,[...result,`${left}${value}`]),()=>result)}function FromLiteral2(variants,value){return IsEqual(variants.length,0)?[`${value}`]:FromLiteralPush(variants,value)}function FromUnion(variants,types,result=[]){return ShiftLeft(types,(left,right)=>FromUnion(variants,right,[...result,...FromType2(variants,left)]),()=>result)}function FromType2(variants,type){return IsUnion(type)?FromUnion(variants,type.anyOf):IsLiteral(type)?FromLiteral2(variants,type.const):Unreachable()}function DecodeFromSpan(variants,types){return ShiftLeft(types,(left,right)=>DecodeFromSpan(FromType2(variants,left),right),()=>variants)}function VariantsToLiterals(variants){return variants.map((variant)=>Literal(variant))}function DecodeTypesAsUnion(types){let variants=DecodeFromSpan([],types),literals=VariantsToLiterals(variants);return Union(literals)}function DecodeTypes(types){return IsEqual(types.length,0)?Unreachable():IsEqual(types.length,1)&&IsLiteral(types[0])?types[0]:DecodeTypesAsUnion(types)}function TemplateLiteralDecodeUnsafe(pattern){let types=ParsePatternIntoTypes(pattern);return IsEqual(types.length,0)?String2():IsTemplateLiteralFinite(types)?DecodeTypes(types):TemplateLiteralCreate(pattern)}function TemplateLiteralDecode(pattern){let decoded=TemplateLiteralDecodeUnsafe(pattern);return IsTemplateLiteral(decoded)?String2():decoded}function CreateRecord(key,value){let patternProperties={[key]:value};return Create({["~kind"]:"Record"},{type:"object",patternProperties})}function FromAnyKey(value){return CreateRecord(StringKey,value)}function FromBooleanKey(value){return _Object_({true:value,false:value})}function Tuple(types,options={}){let[items,minItems,additionalItems]=[types,types.length,!1];return Create({["~kind"]:"Tuple"},{type:"array",additionalItems,items,minItems},options)}function IsTuple(value){return IsKind(value,"Tuple")}function TupleOptions(type){return Discard(type,["~kind","type","items","minItems","additionalItems"])}function RemoveReadonlyOperation(type){return Discard(type,["~readonly"])}function RemoveReadonlyAction(type,options){return Update(RemoveReadonlyOperation(type),{},options)}function RemoveReadonlyInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveReadonlyAction(instantiatedType,options)}function RemoveReadonly(type,options={}){return RemoveReadonlyAction(type,options)}function RemoveOptionalOperation(type){return Discard(type,["~optional"])}function RemoveOptionalAction(type,options){return Update(RemoveOptionalOperation(type),{},options)}function RemoveOptionalInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveOptionalAction(instantiatedType,options)}function RemoveOptional(type,options={}){return RemoveOptionalAction(type,options)}function TupleElementsToProperties(types){return types.reduceRight((result,right,index)=>({[index]:right,...result}),{})}function TupleToObject(type){let properties=TupleElementsToProperties(type.items);return _Object_(properties)}function CanComposite(type){return IsObject2(type)||IsTuple(type)}function IsReadonlyProperty(left,right){return IsReadonly(left)?IsReadonly(right)?!0:!1:!1}function IsOptionalProperty(left,right){return IsOptional(left)?IsOptional(right)?!0:!1:!1}function CompositeProperty(left,right){let isReadonly=IsReadonlyProperty(left,right),isOptional=IsOptionalProperty(left,right),evaluated=EvaluateIntersect([left,right]),property=RemoveReadonly(RemoveOptional(evaluated));return isReadonly&&isOptional?AddReadonly(AddOptional(property)):isReadonly&&!isOptional?AddReadonly(property):!isReadonly&&isOptional?AddOptional(property):property}function CompositePropertyKey(left,right,key){return key in left?key in right?CompositeProperty(left[key],right[key]):left[key]:(key in right)?right[key]:Never()}function CompositeProperties(left,right){return[...new Set([...Keys(left),...Keys(right)])].reduce((result,key)=>({...result,[key]:CompositePropertyKey(left,right,key)}),{})}function GetProperties(type){return IsObject2(type)?type.properties:IsTuple(type)?TupleElementsToProperties(type.items):{}}function Composite(left,right){let leftProperties=GetProperties(left),rightProperties=GetProperties(right),properties=CompositeProperties(leftProperties,rightProperties);return _Object_(properties)}function NarrowCompareRule(left,right){let result=Compare(left,right);return IsEqual(result,CompareResultLeftInside)?left:IsEqual(result,CompareResultRightInside)?right:IsEqual(result,CompareResultEqual)?right:Never()}function NarrowCompositeRule(left,right){let canCompositeLeft=CanComposite(left),canCompositeRight=CanComposite(right);return canCompositeLeft&&canCompositeRight?Composite(left,right):canCompositeLeft&&!canCompositeRight?left:!canCompositeLeft&&canCompositeRight?right:NarrowCompareRule(left,right)}function Narrow(left,right){return IsNever(left)?left:IsAny(left)?left:IsUnknown(left)?right:IsNever(right)?right:IsAny(right)?right:IsUnknown(right)?left:NarrowCompositeRule(left,right)}function ShouldEvaluate(left,right){return IsUnion(left)||IsUnion(right)}function DistributeOperation(left,right){let evaluatedLeft=EvaluateType(left),evaluatedRight=EvaluateType(right);return ShouldEvaluate(evaluatedLeft,evaluatedRight)?EvaluateIntersect([evaluatedLeft,evaluatedRight]):Narrow(evaluatedLeft,evaluatedRight)}function DistributeType(type,types,result=[]){return ShiftLeft(types,(left,right)=>DistributeType(type,right,[...result,DistributeOperation(left,type)]),()=>IsEqual(result.length,0)?[type]:result)}function DistributeUnion(types,distribution,result=[]){return ShiftLeft(types,(left,right)=>DistributeUnion(right,distribution,[...result,...Distribute([left],distribution)]),()=>result)}function Distribute(types,result=[]){return ShiftLeft(types,(left,right)=>IsUnion(left)?Distribute(right,DistributeUnion(left.anyOf,result)):Distribute(right,DistributeType(left,result)),()=>result)}function ExcludeType(left,right){let check=Extends({},left,right);return IsExtendsTrueLike(check)?[]:[left]}function ExcludeUnion(left,right,result=[]){return ShiftLeft(left,(head,tail)=>ExcludeUnion(tail,right,[...result,...ExcludeType(head,right)]),()=>result)}function ExcludeOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExcludeUnion(canonical,right);return EvaluateUnion(remaining)}function EvaluateDependent(if_,then_,else_){let intersected=EvaluateIntersect([if_,then_]),excluded=ExcludeOperation(else_,if_);return EvaluateUnion([intersected,excluded])}function EvaluateEnum(values,result=[]){return ShiftLeft(values,(left,right)=>EvaluateEnum(right,[...result,Literal(left)]),()=>EvaluateUnion(result))}function EvaluateIntersect(types){let distribution=Distribute(types),broadend=Broaden(distribution);return EvaluateUnion(broadend)}function EvaluateTemplateLiteral(pattern){let evaluated=TemplateLiteralDecode(pattern);return EvaluateType(evaluated)}function EvaluateUnion(types){let broadend=Broaden(types);return EvaluateUnionFast(broadend)}function EvaluateType(type){return IsDependent(type)?EvaluateDependent(type.if,type.then,type.else):IsEnum2(type)?EvaluateEnum(type.enum):IsIntersect(type)?EvaluateIntersect(type.allOf):IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsUnion(type)?EvaluateUnion(type.anyOf):type}function EvaluateUnionFast(types){return IsEqual(types.length,1)?types[0]:IsEqual(types.length,0)?Never():Union(types)}function FromEnumKey(values,value){let unionKey=EvaluateEnum(values);return FromKey(unionKey,value)}function FromIntegerKey(_key,value){return CreateRecord(IntegerKey,value)}function FromIntersectKey(types,value){let evaluatedKey=EvaluateIntersect(types);return FromKey(evaluatedKey,value)}function FromLiteralKey(key,value){return IsString(key)||IsNumber(key)?_Object_({[key]:value}):IsEqual(key,!1)?_Object_({false:value}):IsEqual(key,!0)?_Object_({true:value}):_Object_({})}function FromNumberKey(_key,value){return CreateRecord(NumberKey,value)}function FromStringKey(key,value){return HasPropertyKey(key,"pattern")&&(IsString(key.pattern)||key.pattern instanceof RegExp)?CreateRecord(key.pattern.toString(),value):CreateRecord(StringKey,value)}function FromTemplateKey(pattern,value){let types=ParsePatternIntoTypes(pattern);return IsTemplateLiteralFinite(types)?FromKey(EvaluateTemplateLiteral(pattern),value):CreateRecord(pattern,value)}function FlattenType(type){return IsUnion(type)?Flatten(type.anyOf):[type]}function Flatten(types,result=[]){return ShiftLeft(types,(left,right)=>Flatten(right,[...result,...FlattenType(left)]),()=>result)}function StringOrNumberCheck(types){return types.some((type)=>IsString3(type)||IsNumber3(type)||IsInteger2(type))}function TryBuildRecord(types,value){return IsEqual(StringOrNumberCheck(types),!0)?CreateRecord(StringKey,value):void 0}function CreateProperties(types,value){return types.reduce((result,left)=>IsLiteral(left)&&(IsString(left.const)||IsNumber(left.const))?{...result,[left.const]:value}:result,{})}function CreateObject(types,value){let properties=CreateProperties(types,value);return _Object_(properties)}function FromUnionKey(types,value){let flattened=Flatten(types),record=TryBuildRecord(flattened,value);return IsSchema2(record)?record:CreateObject(flattened,value)}function FromKey(key,value){return IsAny(key)?FromAnyKey(value):IsBoolean3(key)?FromBooleanKey(value):IsEnum2(key)?FromEnumKey(key.enum,value):IsInteger2(key)?FromIntegerKey(key,value):IsIntersect(key)?FromIntersectKey(key.allOf,value):IsLiteral(key)?FromLiteralKey(key.const,value):IsNumber3(key)?FromNumberKey(key,value):IsUnion(key)?FromUnionKey(key.anyOf,value):IsString3(key)?FromStringKey(key,value):IsTemplateLiteral(key)?FromTemplateKey(key.pattern,value):_Object_({})}function RecordAction(key,value,options){return CanInstantiate([key])?Update(FromKey(key,value),{},options):RecordDeferred(key,value,options)}function RecordInstantiate(context,state,key,value,options){let instantiatedKey=InstantiateType(context,state,key),instantiatedValue=InstantiateType(context,state,value);return RecordAction(instantiatedKey,instantiatedValue,options)}var IntegerKey=`^${IntegerPattern}$`,NumberKey=`^${NumberPattern}$`,StringKey=`^${StringPattern}$`;function RecordDeferred(key,value,options={}){return Deferred("Record",[key,value],options)}function Record(key,value,options={}){return RecordAction(key,value,options)}function RecordFromPattern(pattern,value){return CreateRecord(pattern,value)}function RecordPatternToType(pattern){return IsEqual(pattern,StringKey)?String2():IsEqual(pattern,IntegerKey)?Integer():IsEqual(pattern,NumberKey)?Number2():TemplateLiteralDecodeUnsafe(pattern)}function RecordPattern(type){return Keys(type.patternProperties)[0]}function RecordKey(type){let pattern=RecordPattern(type);return RecordPatternToType(pattern)}function RecordValue(type){return type.patternProperties[RecordPattern(type)]}function IsRecord(value){return IsKind(value,"Record")}function Rest(type){return Create({"~kind":"Rest"},{type:"rest",items:type},{})}function IsRest(value){return IsKind(value,"Rest")}function IsThis(value){return IsKind(value,"This")}function Undefined(options){return Create({"~kind":"Undefined"},{type:"undefined"},options)}function IsUndefined2(value){return IsKind(value,"Undefined")}function IsVoid(value){return IsKind(value,"Void")}function PatternBigIntMapping(input){return BigInt2()}function PatternStringMapping(input){return String2()}function PatternNumberMapping(input){return Number2()}function PatternIntegerMapping(input){return Integer()}function PatternNeverMapping(input){return Never()}function PatternTextMapping(input){return Literal(input)}function PatternBaseMapping(input){return input}function PatternGroupMapping(input){return Union(input[1])}function PatternUnionMapping(input){return input.length===3?[...input[0],...input[2]]:input.length===1?[...input[0]]:[]}function PatternTermMapping(input){return[input[0],...input[1]]}function PatternBodyMapping(input){return input}function PatternMapping(input){return input[1]}function IsMatch(value){return IsEqual(value.length,2)}function Match3(input,ok,fail){return IsMatch(input)?ok(input[0],input[1]):fail()}function TakeVariant(variant,input){return IsEqual(input.indexOf(variant),0)?[variant,input.slice(variant.length)]:[]}function Take(variants,input){for(let i=0;i<variants.length;i++){let result=TakeVariant(variants[i],input);if(IsMatch(result))return result}return[]}function Range(start,end){return Array.from({length:end-start+1},(_,i)=>String.fromCharCode(start+i))}var Alpha=[...Range(97,122),...Range(65,90)],Zero="0",NonZero=Range(49,57),Digit=[Zero,...NonZero],WhiteSpace=" ",NewLine=`
333
333
  `;var UnderScore="_";var DollarSign="$";var LineComment="//",OpenComment="/*",CloseComment="*/";function DiscardMultilineComment(input){let index=input.indexOf(CloseComment);return IsEqual(index,-1)?"":input.slice(index+2)}function DiscardLineComment(input){let index=input.indexOf(NewLine);return IsEqual(index,-1)?"":input.slice(index)}function TrimStartUntilNewline(input){return input.replace(/^[ \t\r\f\v]+/,"")}function TrimWhitespace(input){let trimmed=TrimStartUntilNewline(input);return trimmed.startsWith(OpenComment)?TrimWhitespace(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?TrimWhitespace(DiscardLineComment(trimmed.slice(2))):trimmed}function Trim(input){let trimmed=input.trimStart();return trimmed.startsWith(OpenComment)?Trim(DiscardMultilineComment(trimmed.slice(2))):trimmed.startsWith(LineComment)?Trim(DiscardLineComment(trimmed.slice(2))):trimmed}var AllowedDigits=[...Digit,UnderScore];function TakeConst(const_,input){return Take([const_],input)}function Const(const_,input){return IsEqual(const_,"")?["",input]:const_.startsWith(NewLine)?TakeConst(const_,TrimWhitespace(input)):const_.startsWith(WhiteSpace)?TakeConst(const_,input):TakeConst(const_,Trim(input))}var Initial=[...Alpha,UnderScore,DollarSign];var Remaining=[...Initial,...Digit];var AllowedDigits2=[...Digit,UnderScore];function TakeOne(input){return IsEqual(input,"")?[]:[input.slice(0,1),input.slice(1)]}function IsInputMatchSentinal(end,input){return ShiftLeft(end,(left,right)=>input.startsWith(left)?!0:IsInputMatchSentinal(right,input),()=>!1)}function Until(end,input,result=""){return Match3(TakeOne(input),(One,Rest)=>IsInputMatchSentinal(end,input)?[result,input]:Until(end,Rest,`${result}${One}`),()=>[])}function Until_1(end,input){return Match3(Until(end,input),(Until,UntilRest)=>IsEqual(Until,"")?[]:[Until,UntilRest],()=>[])}var If=(result,left,right=()=>[])=>result.length===2?left(result):right();var PatternBigInt=(input)=>If(Const("-?(?:0|[1-9][0-9]*)n",input),([_0,input])=>[PatternBigIntMapping(_0),input]),PatternString=(input)=>If(Const(".*",input),([_0,input])=>[PatternStringMapping(_0),input]),PatternNumber=(input)=>If(Const("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",input),([_0,input])=>[PatternNumberMapping(_0),input]),PatternInteger=(input)=>If(Const("-?(?:0|[1-9][0-9]*)",input),([_0,input])=>[PatternIntegerMapping(_0),input]),PatternNever=(input)=>If(Const("(?!)",input),([_0,input])=>[PatternNeverMapping(_0),input]),PatternText=(input)=>If(Until_1(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],input),([_0,input])=>[PatternTextMapping(_0),input]),PatternBase=(input)=>If(If(PatternBigInt(input),([_0,input])=>[_0,input],()=>If(PatternString(input),([_0,input])=>[_0,input],()=>If(PatternNumber(input),([_0,input])=>[_0,input],()=>If(PatternInteger(input),([_0,input])=>[_0,input],()=>If(PatternNever(input),([_0,input])=>[_0,input],()=>If(PatternGroup(input),([_0,input])=>[_0,input],()=>If(PatternText(input),([_0,input])=>[_0,input],()=>[]))))))),([_0,input])=>[PatternBaseMapping(_0),input]),PatternGroup=(input)=>If(If(Const("(",input),([_0,input])=>If(PatternBody(input),([_1,input])=>If(Const(")",input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[PatternGroupMapping(_0),input]),PatternUnion=(input)=>If(If(If(PatternTerm(input),([_0,input])=>If(Const("|",input),([_1,input])=>If(PatternUnion(input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[_0,input],()=>If(If(PatternTerm(input),([_0,input])=>[[_0],input]),([_0,input])=>[_0,input],()=>If([[],input],([_0,input])=>[_0,input],()=>[]))),([_0,input])=>[PatternUnionMapping(_0),input]),PatternTerm=(input)=>If(If(PatternBase(input),([_0,input])=>If(PatternBody(input),([_1,input])=>[[_0,_1],input])),([_0,input])=>[PatternTermMapping(_0),input]),PatternBody=(input)=>If(If(PatternUnion(input),([_0,input])=>[_0,input],()=>If(PatternTerm(input),([_0,input])=>[_0,input],()=>[])),([_0,input])=>[PatternBodyMapping(_0),input]),Pattern=(input)=>If(If(Const("^",input),([_0,input])=>If(PatternBody(input),([_1,input])=>If(Const("$",input),([_2,input])=>[[_0,_1,_2],input]))),([_0,input])=>[PatternMapping(_0),input]);function JoinString(input){return input.join("|")}function UnwrapTemplateLiteralPattern(pattern){return pattern.slice(1,pattern.length-1)}function EncodeLiteral(value,right,pattern){return EncodeTypes(right,`${pattern}${value}`)}function EncodeBigInt(right,pattern){return EncodeTypes(right,`${pattern}${BigIntPattern}`)}function EncodeInteger(right,pattern){return EncodeTypes(right,`${pattern}${IntegerPattern}`)}function EncodeNumber(right,pattern){return EncodeTypes(right,`${pattern}${NumberPattern}`)}function EncodeBoolean(right,pattern){return EncodeType(Union([Literal("false"),Literal("true")]),right,pattern)}function EncodeString(right,pattern){return EncodeTypes(right,`${pattern}${StringPattern}`)}function EncodeTemplateLiteral(templatePattern,right,pattern){return EncodeTypes(right,`${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`)}function EncodeTemplateLiteralDeferred(types,right,pattern){let templateLiteral=TemplateLiteralAction(types,{});return EncodeType(templateLiteral,right,pattern)}function EncodeEnum(values,right,pattern){let evaluated=EvaluateEnum(values);return EncodeType(evaluated,right,pattern)}function EncodeUnion(types,right,pattern,result=[]){return ShiftLeft(types,(head,tail)=>EncodeUnion(tail,right,pattern,[...result,EncodeType(head,[],"")]),()=>EncodeTypes(right,`${pattern}(${JoinString(result)})`))}function EncodeType(type,right,pattern){return IsEnum2(type)?EncodeEnum(type.enum,right,pattern):IsInteger2(type)?EncodeInteger(right,pattern):IsLiteral(type)?EncodeLiteral(type.const,right,pattern):IsBigInt2(type)?EncodeBigInt(right,pattern):IsBoolean3(type)?EncodeBoolean(right,pattern):IsNumber3(type)?EncodeNumber(right,pattern):IsString3(type)?EncodeString(right,pattern):IsTemplateLiteral(type)?EncodeTemplateLiteral(type.pattern,right,pattern):IsTemplateLiteralDeferred(type)?EncodeTemplateLiteralDeferred(type.parameters[0],right,pattern):IsUnion(type)?EncodeUnion(type.anyOf,right,pattern):NeverPattern}function EncodeTypes(types,pattern){return ShiftLeft(types,(left,right)=>EncodeType(left,right,pattern),()=>pattern)}function EncodePattern(types){return`^${EncodeTypes(types,"")}$`}function TemplateLiteralEncode(types){let pattern=EncodePattern(types);return TemplateLiteralCreate(pattern)}function TemplateLiteralAction(types,options){return CanInstantiate(types)?Update(TemplateLiteralEncode(types),{},options):TemplateLiteralDeferred(types,options)}function TemplateLiteralInstantiate(context,state,types,options){let instantiatedTypes=InstantiateTypes(context,state,types);return TemplateLiteralAction(instantiatedTypes,options)}function TemplateLiteralDeferred(types,options={}){return Deferred("TemplateLiteral",[types],options)}function IsTemplateLiteralDeferred(value){return IsSchema2(value)&&HasPropertyKey(value,"action")&&IsEqual(value.action,"TemplateLiteral")}function IsTemplateLiteral(value){return IsKind(value,"TemplateLiteral")}function ExtendsUnion(inferred){return Create({["~kind"]:"ExtendsUnion"},{inferred})}function IsExtendsUnion(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"inferred")&&IsEqual(value["~kind"],"ExtendsUnion")&&IsObject(value.inferred)}function ExtendsTrue(inferred){return Create({["~kind"]:"ExtendsTrue"},{inferred})}function IsExtendsTrue(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"inferred")&&IsEqual(value["~kind"],"ExtendsTrue")&&IsObject(value.inferred)}function ExtendsFalse(){return Create({["~kind"]:"ExtendsFalse"},{})}function IsExtendsFalse(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&IsEqual(value["~kind"],"ExtendsFalse")}function IsExtendsTrueLike(value){return IsExtendsUnion(value)||IsExtendsTrue(value)}function Match4(result,true_,false_){return IsExtendsTrueLike(result)?true_(result.inferred):false_()}function ExtendsRightInfer(inferred,name,left,right){return Match4(ExtendsLeft(inferred,left,right),(checkInferred)=>ExtendsTrue(Assign(Assign(inferred,checkInferred),{[name]:left})),()=>ExtendsFalse())}function ExtendsRightAny(inferred,_left){return ExtendsTrue(inferred)}function ExtendsRightDependent(inferred,left,if_,then_,else_){return Match4(ExtendsLeft(inferred,left,if_),(inferred)=>Match4(ExtendsLeft(inferred,left,then_),(inferred)=>ExtendsTrue(inferred),()=>ExtendsFalse()),()=>Match4(ExtendsLeft(inferred,left,else_),(inferred)=>ExtendsTrue(inferred),()=>ExtendsFalse()))}function ExtendsRightEnum(inferred,left,right){let evaluated=EvaluateEnum(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightIntersect(inferred,left,right){return ShiftLeft(right,(head,tail)=>Match4(ExtendsLeft(inferred,left,head),(inferred)=>ExtendsRightIntersect(inferred,left,tail),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsRightTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(right);return ExtendsLeft(inferred,left,evaluated)}function ExtendsRightUnion(inferred,left,right){return ShiftLeft(right,(head,tail)=>Match4(ExtendsLeft(inferred,left,head),(inferred)=>ExtendsTrue(inferred),()=>ExtendsRightUnion(inferred,left,tail)),()=>ExtendsFalse())}function ExtendsRight(inferred,left,right){return IsAny(right)?ExtendsRightAny(inferred,left):IsDependent(right)?ExtendsRightDependent(inferred,left,right.if,right.then,right.else):IsEnum2(right)?ExtendsRightEnum(inferred,left,right.enum):IsInfer(right)?ExtendsRightInfer(inferred,right.name,left,right.extends):IsIntersect(right)?ExtendsRightIntersect(inferred,left,right.allOf):IsTemplateLiteral(right)?ExtendsRightTemplateLiteral(inferred,left,right.pattern):IsUnion(right)?ExtendsRightUnion(inferred,left,right.anyOf):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsAny(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsUnion(inferred)}function ExtendsImmutable(left,right){let isImmutableLeft=IsImmutable(left),isImmutableRight=IsImmutable(right);return isImmutableLeft&&isImmutableRight?!0:!isImmutableLeft&&isImmutableRight?!0:isImmutableLeft&&!isImmutableRight?!1:!0}function ExtendsArray(inferred,arrayLeft,left,right){return IsArray2(right)?ExtendsImmutable(arrayLeft,right)?ExtendsLeft(inferred,left,right.items):ExtendsFalse():ExtendsRight(inferred,arrayLeft,right)}function ExtendsBigInt(inferred,left,right){return IsBigInt2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsBoolean(inferred,left,right){return IsBoolean3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ParameterCompare(inferred,left,leftRest,right,rightRest){let checkLeft=IsInfer(right)?left:right,checkRight=IsInfer(right)?right:left,isLeftOptional=IsOptional(left),isRightOptional=IsOptional(right);return!isLeftOptional&&isRightOptional?ExtendsFalse():Match4(ExtendsLeft(inferred,checkLeft,checkRight),(inferred)=>ExtendsParameters(inferred,leftRest,rightRest),()=>ExtendsFalse())}function ParameterRight(inferred,left,leftRest,rightRest){return ShiftLeft(rightRest,(head,tail)=>ParameterCompare(inferred,left,leftRest,head,tail),()=>IsOptional(left)?ExtendsTrue(inferred):ExtendsFalse())}function ParametersLeft(inferred,left,rightRest){return ShiftLeft(left,(head,tail)=>ParameterRight(inferred,head,tail,rightRest),()=>ExtendsTrue(inferred))}function ExtendsParameters(inferred,left,right){return ParametersLeft(inferred,left,right)}function ExtendsReturnType(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsLeft(inferred,left,right)}function ExtendsConstructor(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsConstructor2(right)?Match4(ExtendsParameters(inferred,parameters,right.parameters),(inferred)=>ExtendsReturnType(inferred,returnType,right.instanceType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsDependent(inferred,if_,then_,else_,right){return Match4(ExtendsLeft(inferred,if_,right),()=>ExtendsLeft(inferred,then_,right),()=>ExtendsLeft(inferred,else_,right))}function ExtendsEnum(inferred,left,right){let evaluated=EvaluateEnum(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsFunction(inferred,parameters,returnType,right){return IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):IsFunction2(right)?Match4(ExtendsParameters(inferred,parameters,right.parameters),(inferred)=>ExtendsReturnType(inferred,returnType,right.returnType),()=>ExtendsFalse()):ExtendsFalse()}function ExtendsInteger(inferred,left,right){return IsInteger2(right)?ExtendsTrue(inferred):IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsIntersect(inferred,left,right){let evaluated=EvaluateIntersect(left);return ExtendsLeft(inferred,evaluated,right)}function ExtendsLiteralValue(inferred,left,right){return left===right?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsLiteralBigInt(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBigInt2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralBoolean(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsBoolean3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralNumber(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteralString(inferred,left,right){return IsLiteral(right)?ExtendsLiteralValue(inferred,left,right.const):IsString3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,Literal(left),right)}function ExtendsLiteral(inferred,left,right){return IsBigInt(left.const)?ExtendsLiteralBigInt(inferred,left.const,right):IsBoolean(left.const)?ExtendsLiteralBoolean(inferred,left.const,right):IsNumber(left.const)?ExtendsLiteralNumber(inferred,left.const,right):IsString(left.const)?ExtendsLiteralString(inferred,left.const,right):Unreachable()}function ExtendsNever(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):ExtendsTrue(inferred)}function ExtendsNull(inferred,left,right){return IsNull2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsNumber(inferred,left,right){return IsNumber3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsPropertyOptional(inferred,left,right){return IsOptional(left)?IsOptional(right)?ExtendsTrue(inferred):ExtendsFalse():ExtendsTrue(inferred)}function ExtendsProperty(inferred,left,right){return IsInfer(right)&&IsNever(right.extends)?ExtendsFalse():Match4(ExtendsLeft(inferred,left,right),(inferred)=>ExtendsPropertyOptional(inferred,left,right),()=>ExtendsFalse())}function ExtractInferredProperties(keys,properties){return keys.reduce((result,key)=>(key in properties)?IsExtendsTrueLike(properties[key])?{...result,...properties[key].inferred}:Unreachable():Unreachable(),{})}function ExtendsPropertiesComparer(inferred,left,right){let properties={};for(let rightKey of Keys(right))properties[rightKey]=rightKey in left?ExtendsProperty({},left[rightKey],right[rightKey]):IsOptional(right[rightKey])?IsInfer(right[rightKey])?ExtendsTrue(Assign(inferred,{[right[rightKey].name]:right[rightKey].extends})):ExtendsTrue(inferred):ExtendsFalse();let checked=Values(properties).every((result)=>IsExtendsTrueLike(result)),extracted=checked?ExtractInferredProperties(Keys(properties),properties):{};return checked?ExtendsTrue(extracted):ExtendsFalse()}function ExtendsProperties(inferred,left,right){let compared=ExtendsPropertiesComparer(inferred,left,right);return IsExtendsTrueLike(compared)?ExtendsTrue(Assign(inferred,compared.inferred)):ExtendsFalse()}function ExtendsObjectToObject(inferred,left,right){return ExtendsProperties(inferred,left,right)}function RecordMergeInferred(left,right){return Keys(right).reduce((result,key)=>({...result,[key]:HasPropertyKey(left,key)?IsUnion(result[key])?Union([...result[key].anyOf,right[key]]):Union([left[key],right[key]]):right[key]}),left)}function ExtendsRecordComparer(properties,keys,type,result){return ShiftLeft(keys,(left,right)=>Match4(ExtendsLeft({},properties[left],type),(inferred)=>ExtendsRecordComparer(properties,right,type,RecordMergeInferred(result,inferred)),()=>ExtendsFalse()),()=>ExtendsTrue(result))}function ExtendsObjectToRecord(inferred,properties,_pattern,value){let keys=Keys(properties);return ExtendsRecordComparer(properties,keys,value,inferred)}function ExtendsObject(inferred,left,right){return IsRecord(right)?ExtendsObjectToRecord(inferred,left,RecordPattern(right),RecordValue(right)):IsObject2(right)?ExtendsObjectToObject(inferred,left,right.properties):ExtendsRight(inferred,_Object_(left),right)}function FromObject3(inferred,properties){return IsEqual(Keys(properties).length,0)?ExtendsTrue(inferred):ExtendsFalse()}function FromRecord(inferred,_leftKey,leftValue,_rightKey,rightValue){return ExtendsLeft(inferred,leftValue,rightValue)}function ExtendsRecord(inferred,leftPattern,leftValue,right){return IsRecord(right)?FromRecord(inferred,RecordPatternToType(leftPattern),leftValue,RecordPatternToType(RecordPattern(right)),RecordValue(right)):IsObject2(right)?FromObject3(inferred,right.properties):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsString(inferred,left,right){return IsString3(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsSymbol(inferred,left,right){return IsSymbol2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsTemplateLiteral(inferred,left,right){let evaluated=EvaluateTemplateLiteral(left);return ExtendsLeft(inferred,evaluated,right)}function Inferrable(name,type){return Create({"~kind":"Inferrable"},{name,type},{})}function IsInferable(value){return IsObject(value)&&HasPropertyKey(value,"~kind")&&HasPropertyKey(value,"name")&&HasPropertyKey(value,"type")&&IsEqual(value["~kind"],"Inferrable")&&IsString(value.name)&&IsObject(value.type)}function TryRestInferable(type){return IsRest(type)?IsInfer(type.items)?IsArray2(type.items.extends)?Inferrable(type.items.name,type.items.extends.items):IsUnknown(type.items.extends)?Inferrable(type.items.name,type.items.extends):void 0:Unreachable():void 0}function TryInferable(type){return IsInfer(type)?Inferrable(type.name,type.extends):void 0}function TryInferResults(rest,right){let result=[];for(let head of rest){if(!IsExtendsTrueLike(ExtendsLeft({},head,right)))return;result.push(head)}return result}function InferTupleResult(inferred,name,left,right){let results=TryInferResults(left,right);return IsArray(results)?ExtendsTrue(Assign(inferred,{[name]:Tuple(results)})):ExtendsFalse()}function InferUnionResult(inferred,name,left,right){let results=TryInferResults(left,right);return IsArray(results)?ExtendsTrue(Assign(inferred,{[name]:Union(results)})):ExtendsFalse()}function Reverse(types){return[...types].reverse()}function ApplyReverse(types,reversed){return reversed?Reverse(types):types}function Reversed(types){let first=types.length>0?types[0]:void 0,inferrable=IsSchema2(first)?TryRestInferable(first):void 0;return IsSchema2(inferrable)}function ElementsCompare(inferred,reversed,left,leftRest,right,rightRest){return Match4(ExtendsLeft(inferred,left,right),(checkInferred)=>Elements(checkInferred,reversed,leftRest,rightRest),()=>ExtendsFalse())}function ElementsLeft(inferred,reversed,leftRest,right,rightRest){let inferable=TryRestInferable(right);return IsInferable(inferable)?InferTupleResult(inferred,inferable.name,ApplyReverse(leftRest,reversed),inferable.type):ShiftLeft(leftRest,(head,tail)=>ElementsCompare(inferred,reversed,head,tail,right,rightRest),()=>ExtendsFalse())}function ElementsRight(inferred,reversed,leftRest,rightRest){return ShiftLeft(rightRest,(head,tail)=>ElementsLeft(inferred,reversed,leftRest,head,tail),()=>IsEqual(leftRest.length,0)?ExtendsTrue(inferred):ExtendsFalse())}function Elements(inferred,reversed,leftRest,rightRest){return ElementsRight(inferred,reversed,leftRest,rightRest)}function ExtendsTupleToTuple(inferred,left,right){let instantiatedRight=InstantiateElements(inferred,State([],[]),right),reversed=Reversed(instantiatedRight);return Elements(inferred,reversed,ApplyReverse(left,reversed),ApplyReverse(instantiatedRight,reversed))}function ExtendsTupleToArrayReduce(inferred,left,right){for(let head of left){let result=ExtendsLeft(inferred,head,right);if(!IsExtendsTrueLike(result))return result;inferred=result.inferred}return ExtendsTrue(inferred)}function ExtendsTupleToArray(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):ExtendsTupleToArrayReduce(inferred,left,right)}function ExtendsTuple(inferred,left,right){let instantiatedLeft=InstantiateElements(inferred,State([],[]),left);return IsTuple(right)?ExtendsTupleToTuple(inferred,instantiatedLeft,right.items):IsArray2(right)?ExtendsTupleToArray(inferred,instantiatedLeft,right.items):ExtendsRight(inferred,Tuple(instantiatedLeft),right)}function ExtendsUndefined(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):IsUndefined2(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsUnionSome(inferred,type,unionTypes){return ShiftLeft(unionTypes,(head,tail)=>Match4(ExtendsLeft(inferred,type,head),(inferred)=>ExtendsTrue(inferred),()=>ExtendsUnionSome(inferred,type,tail)),()=>ExtendsFalse())}function ExtendsUnionLeft(inferred,left,right){return ShiftLeft(left,(head,tail)=>Match4(ExtendsUnionSome(inferred,head,right),(inferred)=>ExtendsUnionLeft(inferred,tail,right),()=>ExtendsFalse()),()=>ExtendsTrue(inferred))}function ExtendsUnion2(inferred,left,right){let inferrable=TryInferable(right);return IsInferable(inferrable)?InferUnionResult(inferred,inferrable.name,left,inferrable.type):IsUnion(right)?ExtendsUnionLeft(inferred,left,right.anyOf):ExtendsUnionLeft(inferred,left,[right])}function ExtendsUnknown(inferred,left,right){return IsInfer(right)?ExtendsRight(inferred,left,right):IsAny(right)?ExtendsTrue(inferred):IsUnknown(right)?ExtendsTrue(inferred):ExtendsFalse()}function ExtendsVoid(inferred,left,right){return IsVoid(right)?ExtendsTrue(inferred):ExtendsRight(inferred,left,right)}function ExtendsLeft(inferred,left,right){return IsAny(left)?ExtendsAny(inferred,left,right):IsArray2(left)?ExtendsArray(inferred,left,left.items,right):IsBigInt2(left)?ExtendsBigInt(inferred,left,right):IsBoolean3(left)?ExtendsBoolean(inferred,left,right):IsConstructor2(left)?ExtendsConstructor(inferred,left.parameters,left.instanceType,right):IsDependent(left)?ExtendsDependent(inferred,left.if,left.then,left.else,right):IsEnum2(left)?ExtendsEnum(inferred,left.enum,right):IsFunction2(left)?ExtendsFunction(inferred,left.parameters,left.returnType,right):IsInteger2(left)?ExtendsInteger(inferred,left,right):IsIntersect(left)?ExtendsIntersect(inferred,left.allOf,right):IsLiteral(left)?ExtendsLiteral(inferred,left,right):IsNever(left)?ExtendsNever(inferred,left,right):IsNull2(left)?ExtendsNull(inferred,left,right):IsNumber3(left)?ExtendsNumber(inferred,left,right):IsObject2(left)?ExtendsObject(inferred,left.properties,right):IsRecord(left)?ExtendsRecord(inferred,RecordPattern(left),RecordValue(left),right):IsString3(left)?ExtendsString(inferred,left,right):IsSymbol2(left)?ExtendsSymbol(inferred,left,right):IsTemplateLiteral(left)?ExtendsTemplateLiteral(inferred,left.pattern,right):IsTuple(left)?ExtendsTuple(inferred,left.items,right):IsUndefined2(left)?ExtendsUndefined(inferred,left,right):IsUnion(left)?ExtendsUnion2(inferred,left.anyOf,right):IsUnknown(left)?ExtendsUnknown(inferred,left,right):IsVoid(left)?ExtendsVoid(inferred,left,right):ExtendsFalse()}function InterfaceOperation(heritage,properties){return EvaluateIntersect([...heritage,_Object_(properties)])}function InterfaceAction(heritage,properties,options){return CanInstantiate(heritage)?Update(InterfaceOperation(heritage,properties),{},options):InterfaceDeferred(heritage,properties,options)}function InterfaceInstantiate(context,state,heritage,properties,options){let instantiatedHeritage=InstantiateTypes(context,state,heritage),instantiatedProperties=InstantiateProperties(context,state,properties);return InterfaceAction(instantiatedHeritage,instantiatedProperties,options)}function InterfaceDeferred(heritage,properties,options={}){return Deferred("Interface",[heritage,properties],options)}function IsInterfaceDeferred(value){return IsSchema2(value)&&HasPropertyKey(value,"action")&&IsEqual(value.action,"Interface")}function FromRef(stack,context,ref){return stack.includes(ref)?!0:FromType3([...stack,ref],context,context[ref])}function FromProperties(stack,context,properties){let types=PropertyValues(properties);return FromTypes2(stack,context,types)}function FromTypes2(stack,context,types){return ShiftLeft(types,(left,right)=>FromType3(stack,context,left)?!0:FromTypes2(stack,context,right),()=>!1)}function FromType3(stack,context,type){return IsRef2(type)?FromRef(stack,context,type.$ref):IsArray2(type)?FromType3(stack,context,type.items):IsConstructor2(type)?FromTypes2(stack,context,[...type.parameters,type.instanceType]):IsFunction2(type)?FromTypes2(stack,context,[...type.parameters,type.returnType]):IsInterfaceDeferred(type)?FromProperties(stack,context,type.parameters[1]):IsIntersect(type)?FromTypes2(stack,context,type.allOf):IsObject2(type)?FromProperties(stack,context,type.properties):IsUnion(type)?FromTypes2(stack,context,type.anyOf):IsTuple(type)?FromTypes2(stack,context,type.items):IsRecord(type)?FromType3(stack,context,RecordValue(type)):!1}function CyclicCheck(stack,context,type){return FromType3(stack,context,type)}function ResolveCandidateKeys(context,keys){return keys.reduce((result,left)=>CyclicCheck([left],context,context[left])?[...result,left]:result,[])}function CyclicCandidates(context){let keys=PropertyKeys(context);return ResolveCandidateKeys(context,keys)}function FromRef2(context,ref,result){return result.includes(ref)?result:(ref in context)?FromType4(context,context[ref],[...result,ref]):Unreachable()}function FromProperties2(context,properties,result){let types=PropertyValues(properties);return FromTypes3(context,types,result)}function FromTypes3(context,types,result){return types.reduce((result,left)=>FromType4(context,left,result),result)}function FromType4(context,type,result){return IsRef2(type)?FromRef2(context,type.$ref,result):IsArray2(type)?FromType4(context,type.items,result):IsConstructor2(type)?FromTypes3(context,[...type.parameters,type.instanceType],result):IsFunction2(type)?FromTypes3(context,[...type.parameters,type.returnType],result):IsInterfaceDeferred(type)?FromProperties2(context,type.parameters[1],result):IsIntersect(type)?FromTypes3(context,type.allOf,result):IsObject2(type)?FromProperties2(context,type.properties,result):IsUnion(type)?FromTypes3(context,type.anyOf,result):IsTuple(type)?FromTypes3(context,type.items,result):IsRecord(type)?FromType4(context,RecordValue(type),result):result}function CyclicDependencies(context,key,type){return FromType4(context,type,[key])}function FromRef3(_ref){return Any()}function FromProperties3(properties){return Keys(properties).reduce((result,key)=>({...result,[key]:FromType5(properties[key])}),{})}function FromTypes4(types){return types.reduce((result,left)=>[...result,FromType5(left)],[])}function FromType5(type){return IsRef2(type)?FromRef3(type.$ref):IsArray2(type)?_Array_(FromType5(type.items),ArrayOptions(type)):IsConstructor2(type)?Constructor(FromTypes4(type.parameters),FromType5(type.instanceType)):IsFunction2(type)?_Function_(FromTypes4(type.parameters),FromType5(type.returnType)):IsIntersect(type)?Intersect(FromTypes4(type.allOf)):IsObject2(type)?_Object_(FromProperties3(type.properties)):IsRecord(type)?Record(RecordKey(type),FromType5(RecordValue(type))):IsUnion(type)?Union(FromTypes4(type.anyOf)):IsTuple(type)?Tuple(FromTypes4(type.items)):type}function CyclicAnyFromParameters(defs,ref){return ref in defs?FromType5(defs[ref]):Unknown()}function CyclicExtends(type){return CyclicAnyFromParameters(type.$defs,type.$ref)}function CyclicInterface(context,heritage,properties){let instantiatedHeritage=InstantiateTypes(context,State([],[]),heritage),instantiatedProperties=InstantiateProperties({},State([],[]),properties);return EvaluateIntersect([...instantiatedHeritage,_Object_(instantiatedProperties)])}function CyclicDefinitions(context,dependencies){return Keys(context).filter((key)=>dependencies.includes(key)).reduce((result,key)=>{let type=context[key],instantiatedType=IsInterfaceDeferred(type)?CyclicInterface(context,type.parameters[0],type.parameters[1]):type;return{...result,[key]:instantiatedType}},{})}function InstantiateCyclic(context,ref,type){let dependencies=CyclicDependencies(context,ref,type),definitions=CyclicDefinitions(context,dependencies);return Cyclic(definitions,ref)}function Resolve(defs,ref){return ref in defs?IsRef2(defs[ref])?Resolve(defs,defs[ref].$ref):defs[ref]:Never()}function CyclicTarget(defs,ref){return Resolve(defs,ref)}function Canonical(type){return IsCyclic(type)?CyclicExtends(type):IsUnsafe(type)?Unknown():type}function Extends(inferred,left,right){let canonicalLeft=Canonical(left),canonicalRight=Canonical(right);return ExtendsLeft(inferred,canonicalLeft,canonicalRight)}var CompareResultEqual=0,CompareResultDisjoint=1,CompareResultLeftInside=2,CompareResultRightInside=3;function Compare(left,right){let extendsCheck=[Extends({},left,right),Extends({},right,left)];return IsExtendsTrueLike(extendsCheck[0])&&IsExtendsTrueLike(extendsCheck[1])?CompareResultEqual:IsExtendsTrueLike(extendsCheck[0])&&IsExtendsFalse(extendsCheck[1])?CompareResultLeftInside:IsExtendsFalse(extendsCheck[0])&&IsExtendsTrueLike(extendsCheck[1])?CompareResultRightInside:CompareResultDisjoint}function BroadenFilter(type,types,result=[],all=types){return ShiftLeft(types,(left,right)=>{let compare=Compare(type,left);return IsEqual(compare,CompareResultLeftInside)||IsEqual(compare,CompareResultEqual)?all:IsEqual(compare,CompareResultDisjoint)?BroadenFilter(type,right,[...result,left],all):BroadenFilter(type,right,result,all)},()=>[...result,type])}function BroadenType(type,types,result){let evaluated=EvaluateType(type);return IsAny(evaluated)?[evaluated]:IsUnknown(evaluated)?[evaluated]:IsNever(evaluated)?BroadenTypes(types,result):IsObject2(evaluated)?BroadenTypes(types,[...result,evaluated]):BroadenTypes(types,BroadenFilter(evaluated,result))}function BroadenTypes(types,result=[]){return ShiftLeft(types,(left,right)=>BroadenType(left,right,result),()=>result)}function Broaden(types){let broadened=BroadenTypes(types);return Flatten(broadened)}function EvaluateAction(type,options){return Update(EvaluateType(type),{},options)}function EvaluateInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return EvaluateAction(instantiatedType,options)}function CollectDistributionNames(expression,result=[]){return IsDeferred(expression)&&IsEqual(expression.action,"Conditional")?IsRef2(expression.parameters[0])?CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],[...result,expression.parameters[0].$ref])):CollectDistributionNames(expression.parameters[2],CollectDistributionNames(expression.parameters[3],result)):IsDeferred(expression)&&IsEqual(expression.action,"Mapped")?IsDeferred(expression.parameters[1])&&IsEqual(expression.parameters[1].action,"KeyOf")&&IsRef2(expression.parameters[1].parameters[0])?[...result,expression.parameters[1].parameters[0].$ref]:result:result}function BuildDistributionArray(parameters,names){return parameters.reduce((result,left)=>[...result,names.includes(left.name)],[])}function ZipDistributionArray(arguments_,distributionArray,result=[]){return ShiftLeft(arguments_,(argumentLeft,argumentRight)=>ShiftLeft(distributionArray,(booleanLeft,booleanRight)=>ZipDistributionArray(argumentRight,booleanRight,[...result,[booleanLeft,argumentLeft]]),()=>result),()=>result)}function CanonicalArgument(type){return IsTemplateLiteral(type)?EvaluateTemplateLiteral(type.pattern):IsEnum2(type)?EvaluateEnum(type.enum):type}function Expand(type){let canonicalArgument=CanonicalArgument(type);return IsUnion(canonicalArgument)?[...canonicalArgument.anyOf]:[canonicalArgument]}function Append(current,type){return current.reduce((result,left)=>[...result,[...left,type]],[])}function Cross(current,variants){return variants.reduce((result,left)=>[...result,...Append(current,left)],[])}function Distribute2(zipped){return zipped.reduce((result,left)=>IsEqual(left[0],!0)?Cross(result,Expand(left[1])):Cross(result,[left[1]]),[[]])}function DistributeArguments(parameters,arguments_,expression){let distributionNames=CollectDistributionNames(expression),distributionArray=BuildDistributionArray(parameters,distributionNames),zippedArguments=ZipDistributionArray(arguments_,distributionArray);return IsDeferred(expression)&&IsEqual(expression.action,"Conditional")?Distribute2(zippedArguments):IsDeferred(expression)&&IsEqual(expression.action,"Mapped")?Distribute2(zippedArguments):[arguments_]}function FromNotResolvable(){return["(not-resolvable)",Never()]}function FromNotGeneric(){return["(not-generic)",Never()]}function FromGeneric(name,parameters,expression){return[name,Generic(parameters,expression)]}function FromRef4(context,ref,arguments_){return ref in context?FromType6(context,ref,context[ref],arguments_):FromNotResolvable()}function FromType6(context,name,target,arguments_){return IsGeneric(target)?FromGeneric(name,target.parameters,target.expression):IsRef2(target)?FromRef4(context,target.$ref,arguments_):FromNotGeneric()}function ResolveTarget(context,target,arguments_){return FromType6(context,"(anonymous)",target,arguments_)}function AssertArgumentExtends(name,type,extends_){if(IsInfer(type)||IsCall(type)||IsExtendsTrueLike(Extends({},type,extends_)))return;let cause={parameter:name,expect:extends_,actual:type};throw Error(`Argument for parameter ${name} does not satisfy constraint`,{cause})}function BindArgument(context,state,name,extends_,type){let instantiatedArgument=InstantiateType(context,state,type);return AssertArgumentExtends(name,instantiatedArgument,extends_),Assign(context,{[name]:instantiatedArgument})}function BindArguments(context,state,parameterLeft,parameterRight,arguments_){let instantiatedExtends=InstantiateType(context,state,parameterLeft.extends),instantiatedEquals=InstantiateType(context,state,parameterLeft.equals);return ShiftLeft(arguments_,(left,right)=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,left),state,parameterRight,right),()=>BindParameters(BindArgument(context,state,parameterLeft.name,instantiatedExtends,instantiatedEquals),state,parameterRight,[]))}function BindParameters(context,state,parameters,arguments_){return ShiftLeft(parameters,(left,right)=>BindArguments(context,state,left,right,arguments_),()=>context)}function ResolveArgumentsContext(context,state,parameters,arguments_){return BindParameters(context,state,parameters,arguments_)}var instantiationDepth=0,instantiationCount=0;function InstantiationAssert(){if(IsLessThan(instantiationCount,Get().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function InstantiationIncrement(){InstantiationAssert(),instantiationCount++,instantiationDepth++}function InstantiationDecrement(){if(instantiationDepth--,IsEqual(instantiationDepth,0))instantiationCount=0}function Peek(state){return IsGreaterThan(state.callstack.length,0)?state.callstack[state.callstack.length-1]:""}function IsTailCall(state,name){return IsEqual(Peek(state),name)}function CallDispatch(context,state,target,parameters,expression,arguments_){InstantiationIncrement();try{let argumentsContext=ResolveArgumentsContext(context,state,parameters,arguments_),returnType=InstantiateType(argumentsContext,State([...state.callstack,target.$ref],state.visited),expression);return InstantiateType(argumentsContext,State([],[]),returnType)}finally{InstantiationDecrement()}}function CallDistributed(context,state,target,parameters,expression,distributedArguments){return distributedArguments.reduce((result,arguments_)=>{let returnType=CallDispatch(context,state,target,parameters,expression,arguments_);return[...result,returnType]},[])}function CallImmediate(context,state,target,parameters,expression,arguments_){let distributedArguments=DistributeArguments(parameters,arguments_,expression),returnTypes=CallDistributed(context,state,target,parameters,expression,distributedArguments);return IsEqual(returnTypes.length,1)?returnTypes[0]:EvaluateUnion(returnTypes)}function CallInstantiate(context,state,target,arguments_){let instantiatedArguments=InstantiateTypes(context,state,arguments_),resolved=ResolveTarget(context,target,arguments_),name=resolved[0],type=resolved[1];return IsGeneric(type)?IsTailCall(state,name)?CallConstruct(Ref2(name),instantiatedArguments):CallImmediate(context,state,Ref2(name),type.parameters,type.expression,instantiatedArguments):CallConstruct(target,instantiatedArguments)}function CallConstruct(target,arguments_){return Create({["~kind"]:"Call"},{type:"call",target,arguments:arguments_},{})}function IsCall(value){return IsKind(value,"Call")}function RemoveImmutableOperation(type){return Discard(type,["~immutable"])}function RemoveImmutableAction(type,options){return Update(RemoveImmutableOperation(type),{},options)}function RemoveImmutableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return RemoveImmutableAction(instantiatedType,options)}function ApplyMapping(mapping,value){return mapping(value)}function FromLiteral3(mapping,value){return IsString(value)?Literal(ApplyMapping(mapping,value)):Literal(value)}function FromTemplateLiteral(mapping,pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType7(mapping,evaluated)}function FromUnion2(mapping,types){let result=types.map((type)=>FromType7(mapping,type));return Union(result)}function FromType7(mapping,type){return IsLiteral(type)?FromLiteral3(mapping,type.const):IsTemplateLiteral(type)?FromTemplateLiteral(mapping,type.pattern):IsUnion(type)?FromUnion2(mapping,type.anyOf):type}function CapitalizeDeferred(type,options={}){return Deferred("Capitalize",[type],options)}function LowercaseDeferred(type,options={}){return Deferred("Lowercase",[type],options)}function UncapitalizeDeferred(type,options={}){return Deferred("Uncapitalize",[type],options)}function UppercaseDeferred(type,options={}){return Deferred("Uppercase",[type],options)}var CapitalizeMapping=(input)=>input[0].toUpperCase()+input.slice(1),LowercaseMapping=(input)=>input.toLowerCase(),UncapitalizeMapping=(input)=>input[0].toLowerCase()+input.slice(1),UppercaseMapping=(input)=>input.toUpperCase();function CapitalizeAction(type,options){return CanInstantiate([type])?Update(FromType7(CapitalizeMapping,type),{},options):CapitalizeDeferred(type,options)}function LowercaseAction(type,options){return CanInstantiate([type])?Update(FromType7(LowercaseMapping,type),{},options):LowercaseDeferred(type,options)}function UncapitalizeAction(type,options){return CanInstantiate([type])?Update(FromType7(UncapitalizeMapping,type),{},options):UncapitalizeDeferred(type,options)}function UppercaseAction(type,options){return CanInstantiate([type])?Update(FromType7(UppercaseMapping,type),{},options):UppercaseDeferred(type,options)}function CapitalizeInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return CapitalizeAction(instantiatedType,options)}function LowercaseInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return LowercaseAction(instantiatedType,options)}function UncapitalizeInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return UncapitalizeAction(instantiatedType,options)}function UppercaseInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return UppercaseAction(instantiatedType,options)}function ConditionalDeferred(left,right,true_,false_,options={}){return Deferred("Conditional",[left,right,true_,false_],options)}function ConditionalOperation(context,state,left,right,true_,false_){let extendsResult=Extends(context,left,right);return IsExtendsUnion(extendsResult)?Union([InstantiateType(extendsResult.inferred,state,true_),InstantiateType(context,state,false_)]):IsExtendsTrue(extendsResult)?InstantiateType(extendsResult.inferred,state,true_):InstantiateType(context,state,false_)}function ConditionalAction(context,state,left,right,true_,false_,options){return CanInstantiate([left,right])?Update(ConditionalOperation(context,state,left,right,true_,false_),{},options):ConditionalDeferred(left,right,true_,false_,options)}function ConditionalInstantiate(context,state,left,right,true_,false_,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ConditionalAction(context,state,instantiatedLeft,instantiatedRight,true_,false_,options)}function ConstructorParametersDeferred(type,options={}){return Deferred("ConstructorParameters",[type],options)}function ConstructorParametersOperation(type){let parameters=IsConstructor2(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ConstructorParametersAction(type,options){return CanInstantiate([type])?Update(ConstructorParametersOperation(type),{},options):ConstructorParametersDeferred(type,options)}function ConstructorParametersInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ConstructorParametersAction(instantiatedType,options)}function ExcludeDeferred(left,right,options={}){return Deferred("Exclude",[left,right],options)}function ExcludeAction(left,right,options){return CanInstantiate([left,right])?Update(ExcludeOperation(left,right),{},options):ExcludeDeferred(left,right,options)}function ExcludeInstantiate(context,state,left,right,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExcludeAction(instantiatedLeft,instantiatedRight,options)}function ExtractDeferred(left,right,options={}){return Deferred("Extract",[left,right],options)}function ExtractType(left,right){let check=Extends({},left,right);return IsExtendsTrueLike(check)?[left]:[]}function ExtractUnion(left,right,result=[]){return ShiftLeft(left,(head,tail)=>ExtractUnion(tail,right,[...result,...ExtractType(head,right)]),()=>result)}function ExtractOperation(left,right){let evaluated=EvaluateType(left),canonical=IsUnion(evaluated)?evaluated.anyOf:[evaluated],remaining=ExtractUnion(canonical,right);return EvaluateUnion(remaining)}function ExtractAction(left,right,options){return CanInstantiate([left,right])?Update(ExtractOperation(left,right),{},options):ExtractDeferred(left,right,options)}function ExtractInstantiate(context,state,left,right,options){let instantiatedLeft=InstantiateType(context,state,left),instantiatedRight=InstantiateType(context,state,right);return ExtractAction(instantiatedLeft,instantiatedRight,options)}function IndexDeferred(type,indexer,options={}){return Deferred("Index",[type,indexer],options)}function FromCyclic(defs,ref){let target=CyclicTarget(defs,ref);return FromType8(target)}function FromDependent(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType8(evaluated)}function CollapseIntersectProperties(left,right){let leftKeys=Keys(left).filter((key)=>!HasPropertyKey(right,key)),rightKeys=Keys(right).filter((key)=>!HasPropertyKey(left,key)),sharedKeys=Keys(left).filter((key)=>HasPropertyKey(right,key)),leftProperties=leftKeys.reduce((result,key)=>({...result,[key]:left[key]}),{}),rightProperties=rightKeys.reduce((result,key)=>({...result,[key]:right[key]}),{}),sharedProperties=sharedKeys.reduce((result,key)=>({...result,[key]:EvaluateIntersect([left[key],right[key]])}),{}),unique=Assign(leftProperties,rightProperties);return Assign(unique,sharedProperties)}function FromIntersect(types){return types.reduce((result,left)=>CollapseIntersectProperties(result,FromType8(left)),{})}function FromObject4(properties){return properties}function FromTuple(types){let object=TupleToObject(Tuple(types));return FromType8(object)}function CollapseUnionProperties(left,right){return Keys(left).filter((key)=>(key in right)).reduce((result,key)=>({...result,[key]:EvaluateUnion([left[key],right[key]])}),{})}function ReduceVariants(types,result){return ShiftLeft(types,(left,right)=>ReduceVariants(right,CollapseUnionProperties(result,FromType8(left))),()=>result)}function FromUnion3(types){return ShiftLeft(types,(left,right)=>ReduceVariants(right,FromType8(left)),()=>Unreachable())}function FromType8(type){return IsCyclic(type)?FromCyclic(type.$defs,type.$ref):IsDependent(type)?FromDependent(type.if,type.then,type.else):IsIntersect(type)?FromIntersect(type.allOf):IsUnion(type)?FromUnion3(type.anyOf):IsTuple(type)?FromTuple(type.items):IsObject2(type)?FromObject4(type.properties):{}}function CollapseToObject(type){let properties=FromType8(type);return _Object_(properties)}var integerKeyPattern=new RegExp("^(?:0|[1-9][0-9]*)$");function ConvertToIntegerKey(value){let normal=`${value}`;return integerKeyPattern.test(normal)?parseInt(normal):value}function NormalizeLiteral(value){return Literal(ConvertToIntegerKey(value))}function NormalizeIndexerTypes(types){return types.map((type)=>NormalizeIndexer(type))}function NormalizeIndexer(type){return IsIntersect(type)?Intersect(NormalizeIndexerTypes(type.allOf)):IsUnion(type)?Union(NormalizeIndexerTypes(type.anyOf)):IsLiteral(type)?NormalizeLiteral(type.const):type}function FromArray3(type,indexer){let normalizedIndexer=NormalizeIndexer(indexer),check=Extends({},normalizedIndexer,Number2());return IsExtendsTrueLike(check)?type:IsLiteral(indexer)&&IsEqual(indexer.const,"length")?Number2():Never()}function FromCyclic2(defs,ref){let target=CyclicTarget(defs,ref);return FromType9(target)}function FromDependent2(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType9(evaluated)}function FromEnum(values){let evaluated=EvaluateEnum(values);return FromType9(evaluated)}function FromIntersect2(types){let evaluated=EvaluateIntersect(types);return FromType9(evaluated)}function FromLiteral4(value){return[`${value}`]}function FromTemplateLiteral2(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType9(evaluated)}function FromUnion4(types){return types.reduce((result,left)=>[...result,...FromType9(left)],[])}function FromType9(type){return IsCyclic(type)?FromCyclic2(type.$defs,type.$ref):IsDependent(type)?FromDependent2(type.if,type.then,type.else):IsEnum2(type)?FromEnum(type.enum):IsIntersect(type)?FromIntersect2(type.allOf):IsLiteral(type)?FromLiteral4(type.const):IsTemplateLiteral(type)?FromTemplateLiteral2(type.pattern):IsUnion(type)?FromUnion4(type.anyOf):[]}function ToIndexableKeys(type){return FromType9(type)}function FromTypes5(properties,types){return types.map((type)=>FromType10(properties,type))}function FromType10(properties,type){return IsArray2(type)?_Array_(FromType10(properties,type.items)):IsConstructor2(type)?Constructor(FromTypes5(properties,type.parameters),FromType10(properties,type.instanceType)):IsFunction2(type)?_Function_(FromTypes5(properties,type.parameters),FromType10(properties,type.returnType)):IsTuple(type)?Tuple(FromTypes5(properties,type.items)):IsUnion(type)?Union(FromTypes5(properties,type.anyOf)):IsIntersect(type)?Intersect(FromTypes5(properties,type.allOf)):IsThis(type)?_Object_(properties):type}function ExpandThis(properties,type){return FromType10(properties,type)}function IndexProperty(properties,key){let selectedType=key in properties?properties[key]:Never();return ExpandThis(properties,selectedType)}function IndexProperties(properties,keys){return keys.reduce((result,left)=>[...result,IndexProperty(properties,left)],[])}function FromIndexer(properties,indexer){let keys=ToIndexableKeys(indexer),variants=IndexProperties(properties,keys);return EvaluateUnion(variants)}var NumericKeyPattern=new RegExp(IntegerKey);function NumericKeys(keys){return keys.filter((key)=>NumericKeyPattern.test(key))}function FromIndexerNumber(properties){let keys=PropertyKeys(properties),numericKeys=NumericKeys(keys),variants=IndexProperties(properties,numericKeys);return EvaluateUnion(variants)}function FromObject5(properties,indexer){return IsNumber3(indexer)?FromIndexerNumber(properties):FromIndexer(properties,indexer)}function ConvertLiteral(value){return Literal(ConvertToIntegerKey(value))}function ArrayIndexerTypes(types){return types.map((type)=>FormatArrayIndexer(type))}function FormatArrayIndexer(type){return IsIntersect(type)?Intersect(ArrayIndexerTypes(type.allOf)):IsUnion(type)?Union(ArrayIndexerTypes(type.anyOf)):IsLiteral(type)?ConvertLiteral(type.const):type}function IndexElementsWithIndexer(types,indexer){return types.reduceRight((result,right,index)=>{let check=Extends({},Literal(index),indexer);return IsExtendsTrueLike(check)?[right,...result]:result},[])}function FromTupleWithIndexer(types,indexer){let formattedArrayIndexer=FormatArrayIndexer(indexer),elements=IndexElementsWithIndexer(types,formattedArrayIndexer);return EvaluateUnionFast(elements)}function FromTupleWithoutIndexer(types){return EvaluateUnionFast(types)}function FromTuple2(types,indexer){return IsLiteral(indexer)&&IsEqual(indexer.const,"length")?Literal(types.length):IsNumber3(indexer)||IsInteger2(indexer)?FromTupleWithoutIndexer(types):FromTupleWithIndexer(types,indexer)}function FromType11(type,indexer){return IsArray2(type)?FromArray3(type.items,indexer):IsObject2(type)?FromObject5(type.properties,indexer):IsTuple(type)?FromTuple2(type.items,indexer):Never()}function NormalizeType(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function IndexAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType11(NormalizeType(type),indexer),{},options):IndexDeferred(type,indexer,options)}function IndexInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return IndexAction(instantiatedType,instantiatedIndexer,options)}function InstanceTypeDeferred(type,options={}){return Deferred("InstanceType",[type],options)}function InstanceTypeOperation(type){return IsConstructor2(type)?type.instanceType:Never()}function InstanceTypeAction(type,options){return CanInstantiate([type])?Update(InstanceTypeOperation(type),{},options):InstanceTypeDeferred(type,options)}function InstanceTypeInstantiate(context,state,type,options={}){let instantiatedType=InstantiateType(context,state,type);return InstanceTypeAction(instantiatedType,options)}function KeyOfDeferred(type,options={}){return Deferred("KeyOf",[type],options)}function FromAny(){return Union([Number2(),String2(),Symbol2()])}function FromArray4(_type){return Number2()}function FromPropertyKeys(keys){return keys.reduce((result,left)=>IsLiteralValue(left)?[...result,Literal(ConvertToIntegerKey(left))]:Unreachable(),[])}function FromObject6(properties){let propertyKeys=Keys(properties),variants=FromPropertyKeys(propertyKeys);return EvaluateUnionFast(variants)}function FromRecord2(type){return RecordKey(type)}function FromTuple3(types){let result=types.map((_,index)=>Literal(index));return EvaluateUnionFast(result)}function FromType12(type){return IsAny(type)?FromAny():IsArray2(type)?FromArray4(type.items):IsObject2(type)?FromObject6(type.properties):IsRecord(type)?FromRecord2(type):IsTuple(type)?FromTuple3(type.items):Never()}function NormalizeType2(type){return IsCyclic(type)||IsDependent(type)||IsIntersect(type)||IsUnion(type)?CollapseToObject(type):type}function KeyOfAction(type,options){return CanInstantiate([type])?Update(FromType12(NormalizeType2(type)),{},options):KeyOfDeferred(type,options)}function KeyOfInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return KeyOfAction(instantiatedType,options)}function MappedDeferred(identifier,type,as,property,options={}){return Deferred("Mapped",[identifier,type,as,property],options)}function FromTemplateLiteral3(pattern){let evaluated=EvaluateTemplateLiteral(pattern);return FromType13(evaluated)}function FromUnion5(types){return types.reduce((result,left)=>[...result,...FromType13(left)],[])}function FromEnum2(values){let evaluated=EvaluateEnum(values);return FromType13(evaluated)}function FromLiteral5(value){return IsNumber(value)?[Literal(`${value}`)]:[Literal(value)]}function FromType13(type){return IsEnum2(type)?FromEnum2(type.enum):IsLiteral(type)?FromLiteral5(type.const):IsTemplateLiteral(type)?FromTemplateLiteral3(type.pattern):IsUnion(type)?FromUnion5(type.anyOf):[type]}function MappedVariants(type){return FromType13(type)}function CanonicalAs(instantiatedAs){return IsTemplateLiteral(instantiatedAs)?EvaluateTemplateLiteral(instantiatedAs.pattern):instantiatedAs}function MappedVariant(context,state,identifier,variant,as,property){let variantContext=Assign(context,{[identifier.name]:variant}),instantiatedAs=InstantiateType(variantContext,state,as),canonicalAs=CanonicalAs(instantiatedAs),instantiatedProperty=InstantiateType(variantContext,state,property);return IsLiteralNumber(canonicalAs)||IsLiteralString(canonicalAs)?{[canonicalAs.const]:instantiatedProperty}:{}}function MappedProperties(context,state,identifier,variants,as,property){return variants.reduce((result,left)=>[...result,MappedVariant(context,state,identifier,left,as,property)],[])}function MappedObjects(properties){return properties.reduce((result,left)=>[...result,_Object_(left)],[])}function MappedOperation(context,state,identifier,type,as,property){let variants=MappedVariants(type),mappedProperties=MappedProperties(context,state,identifier,variants,as,property),mappedObjects=MappedObjects(mappedProperties);return EvaluateIntersect(mappedObjects)}function MappedAction(context,state,identifier,type,as,property,options){return CanInstantiate([type])?Update(MappedOperation(context,state,identifier,type,as,property),{},options):MappedDeferred(identifier,type,as,property,options)}function MappedInstantiate(context,state,identifier,type,as,property,options){let instantiatedType=InstantiateType(context,state,type);return MappedAction(context,state,identifier,instantiatedType,as,property,options)}function InstantiateCyclics(context,declarations,cyclicKeys){let declarationContext=Assign(context,declarations);return Keys(declarations).filter((key)=>cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateCyclic(declarationContext,key,declarations[key])}),{})}function InstantiateNonCyclics(context,declarations,cyclicKeys){let declarationContext=Assign(context,declarations);return Keys(declarations).filter((key)=>!cyclicKeys.includes(key)).reduce((result,key)=>({...result,[key]:InstantiateType(declarationContext,State([],[]),declarations[key])}),{})}function InstantiateModule(context,declarations,options){let cyclicCandidates=CyclicCandidates(declarations),instantiatedCyclics=InstantiateCyclics(context,declarations,cyclicCandidates),instantiatedNonCyclics=InstantiateNonCyclics(context,declarations,cyclicCandidates),instantiatedModule={...instantiatedCyclics,...instantiatedNonCyclics};return Update(instantiatedModule,{},options)}function ModuleInstantiate(context,_state,declarations,options){return InstantiateModule(context,declarations,options)}function NonNullableDeferred(type,options={}){return Deferred("NonNullable",[type],options)}function NonNullableOperation(type){let excluded=Union([Null(),Undefined()]);return ExcludeAction(type,excluded,{})}function NonNullableAction(type,options){return CanInstantiate([type])?Update(NonNullableOperation(type),{},options):NonNullableDeferred(type,options)}function NonNullableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return NonNullableAction(instantiatedType,options)}function OmitDeferred(type,indexer,options={}){return Deferred("Omit",[type,indexer],options)}function ToIndexable(type){let collapsed=CollapseToObject(type);return IsObject2(collapsed)?collapsed.properties:Unreachable()}function FromKeys(properties,keys){return Keys(properties).reduce((result,key)=>keys.includes(key)?result:{...result,[key]:properties[key]},{})}function FromType14(type,indexer){let indexable=ToIndexable(type),indexableKeys=ToIndexableKeys(indexer),omitted=FromKeys(indexable,indexableKeys);return _Object_(omitted)}function OmitAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType14(type,indexer),{},options):OmitDeferred(type,indexer,options)}function OmitInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return OmitAction(instantiatedType,instantiatedIndexer,options)}function ParametersDeferred(type,options={}){return Deferred("Parameters",[type],options)}function ParametersOperation(type){let parameters=IsFunction2(type)?type.parameters:[],instantiatedParameters=InstantiateElements({},State([],[]),parameters);return Tuple(instantiatedParameters)}function ParametersAction(type,options){return CanInstantiate([type])?Update(ParametersOperation(type),{},options):ParametersDeferred(type,options)}function ParametersInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ParametersAction(instantiatedType,options)}function PartialDeferred(type,options={}){return Deferred("Partial",[type],options)}function FromCyclic3(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType15(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent3(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType15(evaluated)}function FromIntersect3(types){let evaluated=EvaluateIntersect(types);return FromType15(evaluated)}function FromUnion6(types){let result=types.map((type)=>FromType15(type));return Union(result)}function FromObject7(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:AddOptional(properties[left])}),{});return _Object_(mapped)}function FromType15(type){return IsCyclic(type)?FromCyclic3(type.$defs,type.$ref):IsDependent(type)?FromDependent3(type.if,type.then,type.else):IsIntersect(type)?FromIntersect3(type.allOf):IsUnion(type)?FromUnion6(type.anyOf):IsObject2(type)?FromObject7(type.properties):_Object_({})}function PartialAction(type,options){return CanInstantiate([type])?Update(FromType15(type),{},options):PartialDeferred(type,options)}function PartialInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return PartialAction(instantiatedType,options)}function PickDeferred(type,indexer,options={}){return Deferred("Pick",[type,indexer],options)}function FromKeys2(properties,keys){return Keys(properties).reduce((result,key)=>keys.includes(key)?Assign(result,{[key]:properties[key]}):result,{})}function FromType16(type,indexer){let indexable=ToIndexable(type),keys=ToIndexableKeys(indexer),applied=FromKeys2(indexable,keys);return _Object_(applied)}function PickAction(type,indexer,options){return CanInstantiate([type,indexer])?Update(FromType16(type,indexer),{},options):PickDeferred(type,indexer,options)}function PickInstantiate(context,state,type,indexer,options){let instantiatedType=InstantiateType(context,state,type),instantiatedIndexer=InstantiateType(context,state,indexer);return PickAction(instantiatedType,instantiatedIndexer,options)}function ReadonlyObjectDeferred(type,options={}){return Deferred("ReadonlyObject",[type],options)}function FromArray5(type){return AddImmutable(_Array_(type))}function FromCyclic4(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType17(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent4(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType17(evaluated)}function FromIntersect4(types){let evaluated=EvaluateIntersect(types);return FromType17(evaluated)}function FromObject8(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:AddReadonly(properties[left])}),{});return _Object_(mapped)}function FromTuple4(types){return AddImmutable(Tuple(types))}function FromUnion7(types){let result=types.map((type)=>FromType17(type));return Union(result)}function FromType17(type){return IsArray2(type)?FromArray5(type.items):IsCyclic(type)?FromCyclic4(type.$defs,type.$ref):IsDependent(type)?FromDependent4(type.if,type.then,type.else):IsIntersect(type)?FromIntersect4(type.allOf):IsObject2(type)?FromObject8(type.properties):IsTuple(type)?FromTuple4(type.items):IsUnion(type)?FromUnion7(type.anyOf):type}function ReadonlyObjectAction(type,options){return CanInstantiate([type])?Update(FromType17(type),{},options):ReadonlyObjectDeferred(type)}function ReadonlyObjectInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return ReadonlyObjectAction(instantiatedType,options)}function RefInstantiate(context,state,type,ref){return state.visited.includes(ref)?type:(ref in context)?InstantiateType(context,State(state.callstack,[...state.visited,ref]),context[ref]):type}function FromCyclic5(defs,ref){let target=CyclicTarget(defs,ref),partial=FromType18(target);return Cyclic(Assign(defs,{[ref]:partial}),ref)}function FromDependent5(if_,then_,else_){let evaluated=EvaluateDependent(if_,then_,else_);return FromType18(evaluated)}function FromIntersect5(types){let evaluated=EvaluateIntersect(types);return FromType18(evaluated)}function FromUnion8(types){let result=types.map((type)=>FromType18(type));return Union(result)}function FromObject9(properties){let mapped=Keys(properties).reduce((result,left)=>({...result,[left]:RemoveOptional(properties[left])}),{});return _Object_(mapped)}function FromType18(type){return IsCyclic(type)?FromCyclic5(type.$defs,type.$ref):IsDependent(type)?FromDependent5(type.if,type.then,type.else):IsIntersect(type)?FromIntersect5(type.allOf):IsUnion(type)?FromUnion8(type.anyOf):IsObject2(type)?FromObject9(type.properties):_Object_({})}function RequiredDeferred(type,options={}){return Deferred("Required",[type],options)}function RequiredAction(type,options){return CanInstantiate([type])?Update(FromType18(type),{},options):RequiredDeferred(type,options)}function RequiredInstantiate(context,state,type,options){let instaniatedType=InstantiateType(context,state,type);return RequiredAction(instaniatedType,options)}function ReturnTypeDeferred(type,options={}){return Deferred("ReturnType",[type],options)}function ReturnTypeOperation(type){return IsFunction2(type)?type.returnType:Never()}function ReturnTypeAction(type,options){return CanInstantiate([type])?Update(ReturnTypeOperation(type),{},options):ReturnTypeDeferred(type,options)}function ReturnTypeInstantiate(context,state,type,options={}){let instantiatedType=InstantiateType(context,state,type);return ReturnTypeAction(instantiatedType,options)}function WithDeferred(type,options){return Deferred("With",[type,options],{})}function With(type,options){return WithAction(type,options)}function WithAction(type,options){return CanInstantiate([type])?Update(type,{},options):WithDeferred(type,options)}function WithInstantiate(context,state,type,options){let instaniatedType=InstantiateType(context,state,type);return WithAction(instaniatedType,options)}function SpreadElement(type){return IsRest(type)?IsTuple(type.items)?RestSpread(type.items.items):IsInfer(type.items)?[type]:IsRef2(type.items)?[type]:[Never()]:[type]}function RestSpread(types){return types.reduce((result,left)=>[...result,...SpreadElement(left)],[])}function State(callstack,visited){return{callstack,visited}}function CanInstantiate(types){return ShiftLeft(types,(left,right)=>IsRef2(left)?!1:CanInstantiate(right),()=>!0)}function InstantiateProperties(context,state,properties){return Keys(properties).reduce((result,key)=>({...result,[key]:InstantiateType(context,state,properties[key])}),{})}function InstantiateElements(context,state,types){let elements=InstantiateTypes(context,state,types);return RestSpread(elements)}function InstantiateTypes(context,state,types){return types.map((type)=>InstantiateType(context,state,type))}function WithModifiers(type,instantiatedType){let withOptional=IsOptional(type)?AddOptionalAction(instantiatedType,{}):instantiatedType,withReadonly=IsReadonly(type)?AddReadonlyAction(withOptional,{}):withOptional;return IsImmutable(type)?AddImmutableAction(withReadonly,{}):withReadonly}function InstantiateDeferred(context,state,action,parameters,options){return IsEqual(action,"AddImmutable")?AddImmutableInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveImmutable")?RemoveImmutableInstantiate(context,state,parameters[0],options):IsEqual(action,"AddReadonly")?AddReadonlyInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveReadonly")?RemoveReadonlyInstantiate(context,state,parameters[0],options):IsEqual(action,"AddOptional")?AddOptionalInstantiate(context,state,parameters[0],options):IsEqual(action,"RemoveOptional")?RemoveOptionalInstantiate(context,state,parameters[0],options):IsEqual(action,"Capitalize")?CapitalizeInstantiate(context,state,parameters[0],options):IsEqual(action,"Conditional")?ConditionalInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options):IsEqual(action,"ConstructorParameters")?ConstructorParametersInstantiate(context,state,parameters[0],options):IsEqual(action,"Evaluate")?EvaluateInstantiate(context,state,parameters[0],options):IsEqual(action,"Exclude")?ExcludeInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Extract")?ExtractInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Index")?IndexInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"InstanceType")?InstanceTypeInstantiate(context,state,parameters[0],options):IsEqual(action,"Interface")?InterfaceInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"KeyOf")?KeyOfInstantiate(context,state,parameters[0],options):IsEqual(action,"Lowercase")?LowercaseInstantiate(context,state,parameters[0],options):IsEqual(action,"Mapped")?MappedInstantiate(context,state,parameters[0],parameters[1],parameters[2],parameters[3],options):IsEqual(action,"Module")?ModuleInstantiate(context,state,parameters[0],options):IsEqual(action,"NonNullable")?NonNullableInstantiate(context,state,parameters[0],options):IsEqual(action,"Pick")?PickInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Parameters")?ParametersInstantiate(context,state,parameters[0],options):IsEqual(action,"Partial")?PartialInstantiate(context,state,parameters[0],options):IsEqual(action,"Omit")?OmitInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"ReadonlyObject")?ReadonlyObjectInstantiate(context,state,parameters[0],options):IsEqual(action,"Record")?RecordInstantiate(context,state,parameters[0],parameters[1],options):IsEqual(action,"Required")?RequiredInstantiate(context,state,parameters[0],options):IsEqual(action,"ReturnType")?ReturnTypeInstantiate(context,state,parameters[0],options):IsEqual(action,"TemplateLiteral")?TemplateLiteralInstantiate(context,state,parameters[0],options):IsEqual(action,"Uncapitalize")?UncapitalizeInstantiate(context,state,parameters[0],options):IsEqual(action,"Uppercase")?UppercaseInstantiate(context,state,parameters[0],options):IsEqual(action,"With")?WithInstantiate(context,state,parameters[0],parameters[1]):Deferred(action,parameters,options)}function InstantiateImmediate(context,state,type){let instantiatedType=IsRef2(type)?RefInstantiate(context,state,type,type.$ref):IsArray2(type)?_Array_(InstantiateType(context,state,type.items),ArrayOptions(type)):IsCall(type)?CallInstantiate(context,state,type.target,type.arguments):IsConstructor2(type)?Constructor(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.instanceType),ConstructorOptions(type)):IsFunction2(type)?_Function_(InstantiateTypes(context,state,type.parameters),InstantiateType(context,state,type.returnType),FunctionOptions(type)):IsDependent(type)?Dependent(InstantiateType(context,state,type.if),InstantiateType(context,state,type.then),InstantiateType(context,state,type.else),DependentOptions(type)):IsIntersect(type)?Intersect(InstantiateTypes(context,state,type.allOf),IntersectOptions(type)):IsObject2(type)?_Object_(InstantiateProperties(context,state,type.properties),ObjectOptions(type)):IsRecord(type)?RecordFromPattern(RecordPattern(type),InstantiateType(context,state,RecordValue(type))):IsRest(type)?Rest(InstantiateType(context,state,type.items)):IsTuple(type)?Tuple(InstantiateElements(context,state,type.items),TupleOptions(type)):IsUnion(type)?Union(InstantiateTypes(context,state,type.anyOf),UnionOptions(type)):type;return WithModifiers(type,instantiatedType)}function InstantiateType(context,state,type){return IsDeferred(type)?InstantiateDeferred(context,state,type.action,type.parameters,type.options):InstantiateImmediate(context,state,type)}function Instantiate(context,type){return InstantiateType(context,State([],[]),type)}function AddImmutableOperation(type){return Update(type,{"~immutable":!0},{})}function AddImmutableAction(type,options){return Update(AddImmutableOperation(type),{},options)}function AddImmutableInstantiate(context,state,type,options){let instantiatedType=InstantiateType(context,state,type);return AddImmutableAction(instantiatedType,options)}function AddImmutable(type,options={}){return AddImmutableAction(type,options)}function Evaluate(type,options={}){return EvaluateAction(type,options)}function Comparer(left,right){let compareResult=Compare(left,right);return IsEqual(compareResult,CompareResultRightInside)?1:IsEqual(compareResult,CompareResultDisjoint)?1:0}function Insert(type,types,result=[]){return ShiftLeft(types,(left,right)=>IsEqual(Comparer(type,left),1)?Insert(type,right,[...result,left]):[...result,type,...types],()=>[...result,type])}function Sort(types,result=[]){return ShiftLeft(types,(left,right)=>Sort(right,Insert(left,result)),()=>result)}function Priority(types){return Sort(types)}function FromArray6(context,type,value){if(!IsArray(value))return value;return value.map((value)=>FromType19(context,type.items,value))}function FromCyclic6(context,type,value){return FromType19({...context,...type.$defs},Ref2(type.$ref),value)}function EvaluateIntersection(context,type){let additionalProperties=HasPropertyKey(type,"unevaluatedProperties")?{additionalProperties:type.unevaluatedProperties}:{},instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return IsObject2(evaluated)?With(evaluated,additionalProperties):evaluated}function FromIntersect6(context,type,value){let evaluated=EvaluateIntersection(context,type);return FromType19(context,evaluated,value)}function GetAdditionalProperties(type){return HasPropertyKey(type,"additionalProperties")?type.additionalProperties:void 0}function FromObject10(context,type,value){if(!IsObject(value)||IsArray(value))return value;let additionalProperties=GetAdditionalProperties(type);for(let key of Keys(value)){if(HasPropertyKey(type.properties,key)){value[key]=FromType19(context,type.properties[key],value[key]);continue}if(IsBoolean(additionalProperties)&&IsEqual(additionalProperties,!0)||IsSchema2(additionalProperties)&&Check2(context,additionalProperties,value[key])){value[key]=FromType19(context,additionalProperties,value[key]);continue}delete value[key]}return value}function FromRecord3(context,type,value){if(!IsObject(value))return value;let additionalProperties=GetAdditionalProperties(type),[recordPattern,recordValue]=[new RegExp(RecordPattern(type)),RecordValue(type)];for(let key of Keys(value)){if(recordPattern.test(key)){value[key]=FromType19(context,recordValue,value[key]);continue}if(IsBoolean(additionalProperties)&&IsEqual(additionalProperties,!0)||IsSchema2(additionalProperties)&&Check2(context,additionalProperties,value[key])){value[key]=FromType19(context,additionalProperties,value[key]);continue}delete value[key]}return value}function FromRef5(context,type,value){return HasPropertyKey(context,type.$ref)?FromType19(context,context[type.$ref],value):value}function FromTuple5(context,schema,value){if(!IsArray(value))return value;let length=Math.min(value.length,schema.items.length);for(let index=0;index<length;index++)value[index]=FromType19(context,schema.items[index],value[index]);return IsGreaterThan(value.length,length)?value.slice(0,length):value}function Clone2(value){return Clone(value)}function FromUnion9(context,type,value){for(let schema of type.anyOf){let clean=FromType19(context,schema,Clone2(value));if(Check2(context,schema,clean))return clean}return value}function FromType19(context,type,value){return IsArray2(type)?FromArray6(context,type,value):IsCyclic(type)?FromCyclic6(context,type,value):IsIntersect(type)?FromIntersect6(context,type,value):IsObject2(type)?FromObject10(context,type,value):IsRecord(type)?FromRecord3(context,type,value):IsRef2(type)?FromRef5(context,type,value):IsTuple(type)?FromTuple5(context,type,value):IsUnion(type)?FromUnion9(context,type,value):value}function Modifiers(type,next){for(let key of Keys(type)){if(HasPropertyKey(next,key))continue;next[key]=type[key]}return next}function FromProperties4(properties){let result={};for(let key of Keys(properties))result[key]=FromType20(properties[key]);return result}function FromPriorityTypes(types){return FromTypes6(Priority(types))}function FromTypes6(types){return types.map((type)=>FromType20(type))}function FromType20(type){let next=IsArray2(type)?_Array_(FromType20(type.items),ArrayOptions(type)):IsIntersect(type)?Intersect(FromTypes6(type.allOf)):IsUnion(type)?Union(FromPriorityTypes(type.anyOf)):IsObject2(type)?_Object_(FromProperties4(type.properties)):IsRecord(type)?Record(RecordKey(type),FromType20(RecordValue(type))):IsTuple(type)?Tuple(FromTypes6(type.items)):type;return Modifiers(type,next)}function UnionPrioritySort(type){return FromType20(type)}function Clean(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]}),sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType19(context,sorted,value)}function IsOk(value){return IsObject(value)&&HasPropertyKey(value,"value")}function Ok(value){return{value}}function Fail(){return}function TryArray(value){return IsArray(value)?Ok(value):Ok([value])}function FromBoolean2(value){return IsEqual(value,!0)?Ok(BigInt(1)):Ok(BigInt(0))}var bigintPattern=/^-?(0|[1-9]\d*)n$/,decimalPattern=/^-?(0|[1-9]\d*)\.\d+$/,integerPattern=/^-?(0|[1-9]\d*)$/;function IsStringBigIntLike(value){return bigintPattern.test(value)}function IsStringDecimalLike(value){return decimalPattern.test(value)}function IsStringIntegerLike(value){return integerPattern.test(value)}function FromString2(value){let lowercase=value.toLowerCase();return IsStringBigIntLike(value)?Ok(BigInt(value.slice(0,value.length-1))):IsStringDecimalLike(value)?Ok(BigInt(value.split(".")[0])):IsStringIntegerLike(value)?Ok(BigInt(value)):IsEqual(lowercase,"false")?Ok(BigInt(0)):IsEqual(lowercase,"true")?Ok(BigInt(1)):Fail()}function TryBigInt(value){return IsBigInt(value)?Ok(value):IsBoolean(value)?FromBoolean2(value):IsNumber(value)?Ok(BigInt(Math.trunc(value))):IsNull(value)?Ok(BigInt(0)):IsString(value)?FromString2(value):IsUndefined(value)?Ok(BigInt(0)):Fail()}function FromBigInt2(value){return IsEqual(value,BigInt(0))?Ok(!1):IsEqual(value,BigInt(1))?Ok(!0):Fail()}function FromNumber2(value){return IsEqual(value,0)?Ok(!1):IsEqual(value,1)?Ok(!0):Fail()}function FromString3(value){return IsEqual(value.toLowerCase(),"false")?Ok(!1):IsEqual(value.toLowerCase(),"true")?Ok(!0):IsEqual(value,"0")?Ok(!1):IsEqual(value,"1")?Ok(!0):Fail()}function TryBoolean(value){return IsBigInt(value)?FromBigInt2(value):IsBoolean(value)?Ok(value):IsNumber(value)?FromNumber2(value):IsNull(value)?Ok(!1):IsString(value)?FromString3(value):IsUndefined(value)?Ok(!1):Fail()}function FromBigInt3(value){return IsEqual(value,BigInt(0))?Ok(null):Fail()}function FromBoolean3(value){return IsEqual(value,!1)?Ok(null):Fail()}function FromNumber3(value){return IsEqual(value,0)?Ok(null):Fail()}function FromString4(value){let lowercase=value.toLowerCase();return IsEqual(lowercase,"undefined")||IsEqual(lowercase,"null")||IsEqual(value,"")||IsEqual(value,"0")?Ok(null):Fail()}function TryNull(value){return IsBigInt(value)?FromBigInt3(value):IsBoolean(value)?FromBoolean3(value):IsNumber(value)?FromNumber3(value):IsNull(value)?Ok(null):IsString(value)?FromString4(value):IsUndefined(value)?Ok(null):Fail()}var maxBigInt=BigInt(Number.MAX_SAFE_INTEGER),minBigInt=BigInt(Number.MIN_SAFE_INTEGER);function FromBigInt4(value){return value<=maxBigInt&&value>=minBigInt?Ok(Number(value)):Fail()}function FromBoolean4(value){return Ok(value?1:0)}function FromString5(value){let coerced=+value;if(IsNumber(coerced))return Ok(coerced);let lowercase=value.toLowerCase();if(IsEqual(lowercase,"false"))return Ok(0);if(IsEqual(lowercase,"true"))return Ok(1);let result=TryBigInt(value);if(IsOk(result))return result.value<=maxBigInt&&result.value>=minBigInt?Ok(Number(result.value)):Fail();return Fail()}function TryNumber(value){return IsBigInt(value)?FromBigInt4(value):IsBoolean(value)?FromBoolean4(value):IsNumber(value)?Ok(value):IsNull(value)?Ok(0):IsString(value)?FromString5(value):IsUndefined(value)?Ok(0):Fail()}function TryString(value){return IsBigInt(value)?Ok(value.toString()):IsBoolean(value)?Ok(value.toString()):IsNumber(value)?Ok(value.toString()):IsNull(value)?Ok("null"):IsString(value)?Ok(value):IsUndefined(value)?Ok(""):Fail()}function FromBigInt5(value){return IsEqual(value,BigInt(0))?Ok(void 0):Fail()}function FromBoolean5(value){return IsEqual(value,!1)?Ok(void 0):Fail()}function FromNumber4(value){return IsEqual(value,0)?Ok(void 0):Fail()}function FromString6(value){let lowercase=value.toLowerCase();return IsEqual(lowercase,"undefined")||IsEqual(lowercase,"null")||IsEqual(value,"")||IsEqual(value,"0")?Ok(void 0):Fail()}function TryUndefined(value){return IsBigInt(value)?FromBigInt5(value):IsBoolean(value)?FromBoolean5(value):IsNumber(value)?FromNumber4(value):IsNull(value)?Ok(void 0):IsString(value)?FromString6(value):IsUndefined(value)?Ok(value):Fail()}function FromArray7(context,type,value){return TryArray(value).value.map((value)=>FromType21(context,type.items,value))}function FromBigInt6(_context,_type,value){let result=TryBigInt(value);return IsOk(result)?result.value:value}function FromBoolean6(_context,_type,value){let result=TryBoolean(value);return IsOk(result)?result.value:value}function FromCyclic7(context,type,value){return FromType21({...context,...type.$defs},Ref2(type.$ref),value)}function FromEnum3(context,type,value){return FromType21(context,Evaluate(type),value)}function FromInteger(_context,_type,value){let result=TryNumber(value);return IsOk(result)?Math.trunc(result.value):value}function FromIntersect7(context,type,value){let instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return FromType21(context,evaluated,value)}function FromLiteralBigInt(_context,type,value){let result=TryBigInt(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralBoolean(_context,type,value){let result=TryBoolean(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralNumber(_context,type,value){let result=TryNumber(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteralString(_context,type,value){let result=TryString(value);return IsOk(result)&&IsEqual(type.const,result.value)?result.value:value}function FromLiteral6(context,type,value){if(IsEqual(type.const,value))return value;return IsLiteralBigInt(type)?FromLiteralBigInt(context,type,value):IsLiteralBoolean(type)?FromLiteralBoolean(context,type,value):IsLiteralNumber(type)?FromLiteralNumber(context,type,value):IsLiteralString(type)?FromLiteralString(context,type,value):Unreachable()}function FromNull2(_context,_type,value){let result=TryNull(value);return IsOk(result)?result.value:value}function FromNumber5(_context,_type,value){let result=TryNumber(value);return IsOk(result)?result.value:value}function FromAdditionalProperties(context,entries,additionalProperties,value){let keys=Keys(value);for(let[regexp,_]of entries)for(let key of keys)if(!regexp.test(key))value[key]=FromType21(context,additionalProperties,value[key]);return value}function IsOptionalUndefined(property,key,value){return IsOptional(property)&&IsUndefined(value[key])}function FromProperties5(context,type,value){let entries=EntriesRegExp(type.properties),keys=Keys(value);for(let[regexp,property]of entries)for(let key of keys){if(!regexp.test(key)||IsOptionalUndefined(property,key,value))continue;value[key]=FromType21(context,property,value[key])}return HasPropertyKey(type,"additionalProperties")&&IsObject(type.additionalProperties)?FromAdditionalProperties(context,entries,type.additionalProperties,value):value}function FromObject11(context,type,value){return IsObjectNotArray(value)?FromProperties5(context,type,value):value}function FromPatternProperties(context,type,value){let entries=EntriesRegExp(type.patternProperties),keys=Keys(value);for(let[regexp,schema]of entries)for(let key of keys)if(regexp.test(key))value[key]=FromType21(context,schema,value[key]);return HasPropertyKey(type,"additionalProperties")&&IsObject(type.additionalProperties)?FromAdditionalProperties(context,entries,type.additionalProperties,value):value}function FromRecord4(context,type,value){return IsObjectNotArray(value)?FromPatternProperties(context,type,value):value}function FromRef6(context,type,value){return HasPropertyKey(context,type.$ref)?FromType21(context,context[type.$ref],value):value}function FromString7(_context,_type,value){let result=TryString(value);return IsOk(result)?result.value:value}function FromTemplateLiteral4(context,type,value){return FromType21(context,Evaluate(type),value)}function FromTuple6(context,type,value){if(!IsArray(value))return value;for(let index=0;index<Math.min(type.items.length,value.length);index++)value[index]=FromType21(context,type.items[index],value[index]);return value}function FromUndefined2(_context,_type,value){let result=TryUndefined(value);return IsOk(result)?result.value:value}function FromUnion10(context,type,value){if(type.anyOf.some((type)=>Check2(context,type,value)))return value;let selected=type.anyOf.map((type)=>FromType21(context,type,Clone2(value))).find((value)=>Check2(context,type,value));return IsUndefined(selected)?value:selected}function FromVoid(_context,_type,value){let result=TryUndefined(value);return IsOk(result)?void 0:value}function FromType21(context,type,value){return IsArray2(type)?FromArray7(context,type,value):IsBigInt2(type)?FromBigInt6(context,type,value):IsBoolean3(type)?FromBoolean6(context,type,value):IsCyclic(type)?FromCyclic7(context,type,value):IsEnum2(type)?FromEnum3(context,type,value):IsInteger2(type)?FromInteger(context,type,value):IsIntersect(type)?FromIntersect7(context,type,value):IsLiteral(type)?FromLiteral6(context,type,value):IsNull2(type)?FromNull2(context,type,value):IsNumber3(type)?FromNumber5(context,type,value):IsObject2(type)?FromObject11(context,type,value):IsRecord(type)?FromRecord4(context,type,value):IsRef2(type)?FromRef6(context,type,value):IsString3(type)?FromString7(context,type,value):IsTemplateLiteral(type)?FromTemplateLiteral4(context,type,value):IsTuple(type)?FromTuple6(context,type,value):IsUndefined2(type)?FromUndefined2(context,type,value):IsUnion(type)?FromUnion10(context,type,value):IsVoid(type)?FromVoid(context,type,value):value}function Convert(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return FromType21(context,type,value)}function FromArray8(context,type,value){if(!IsArray(value))return value;for(let i=0;i<value.length;i++)value[i]=FromType22(context,type.items,value[i]);return value}function FromCyclic8(context,type,value){return FromType22({...context,...type.$defs},Ref2(type.$ref),value)}function FromDefault(type,value){if(!IsUndefined(value))return value;return IsFunction(type.default)?type.default():Clone2(type.default)}function FromIntersect8(context,type,value){let instantiated=Instantiate(context,type),evaluated=Evaluate(instantiated);return FromType22(context,evaluated,value)}function FromObject12(context,type,value){if(!IsObject(value))return value;let knownPropertyKeys=Keys(type.properties);for(let key of knownPropertyKeys){let propertyValue=FromType22(context,type.properties[key],value[key]);if(IsUndefined(propertyValue)&&(IsOptional(type.properties[key])||!HasPropertyKey(type.properties[key],"default")))continue;value[key]=propertyValue}if(!IsAdditionalProperties(type)||IsBoolean(type.additionalProperties))return value;for(let key of Keys(value)){if(knownPropertyKeys.includes(key))continue;value[key]=FromType22(context,type.additionalProperties,value[key])}return value}function FromRecord5(context,type,value){if(!IsObject(value))return value;let[recordKey,recordValue]=[new RegExp(RecordPattern(type)),RecordValue(type)];for(let key of Keys(value)){if(!(recordKey.test(key)&&IsDefault(recordValue)))continue;value[key]=FromType22(context,recordValue,value[key])}if(!IsAdditionalProperties(type))return value;for(let key of Keys(value)){if(recordKey.test(key))continue;value[key]=FromType22(context,type.additionalProperties,value[key])}return value}function FromRef7(context,type,value){return HasPropertyKey(context,type.$ref)?FromType22(context,context[type.$ref],value):value}function FromTuple7(context,schema,value){if(!IsArray(value))return value;let[items,max]=[schema.items,Math.max(schema.items.length,value.length)];for(let i=0;i<max;i++)if(i<items.length)value[i]=FromType22(context,items[i],value[i]);return value}function FromUnion11(context,schema,value){for(let inner of schema.anyOf){let result=FromType22(context,inner,Clone2(value));if(Check2(context,inner,result))return result}return value}function FromType22(context,type,value){let defaulted=IsDefault(type)?FromDefault(type,value):value;return IsArray2(type)?FromArray8(context,type,defaulted):IsCyclic(type)?FromCyclic8(context,type,defaulted):IsIntersect(type)?FromIntersect8(context,type,defaulted):IsObject2(type)?FromObject12(context,type,defaulted):IsRecord(type)?FromRecord5(context,type,defaulted):IsRef2(type)?FromRef7(context,type,defaulted):IsTuple(type)?FromTuple7(context,type,defaulted):IsUnion(type)?FromUnion11(context,type,defaulted):defaulted}function Default(...args){let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return FromType22(context,type,value)}function Pipeline(pipeline){return(...args)=>{let[context,type,value]=Match(args,{3:(context,type,value)=>[context,type,value],2:(type,value)=>[{},type,value]});return pipeline.reduce((result,func)=>func(context,type,result),value)}}function Decode2(_context,type,value){return type["~codec"].decode(value)}function Encode2(_context,type,value){return type["~codec"].encode(value)}function Callback(direction,context,type,value){if(!IsCodec(type))return value;return IsEqual(direction,"Decode")?Decode2(context,type,value):Encode2(context,type,value)}function Decode3(direction,context,type,value){if(!IsArray(value))return value;for(let i=0;i<value.length;i++)value[i]=FromType23(direction,context,type.items,value[i]);return Callback(direction,context,type,value)}function Encode3(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsArray(exterior))return exterior;for(let i=0;i<exterior.length;i++)exterior[i]=FromType23(direction,context,type.items,exterior[i]);return exterior}function FromArray9(direction,context,type,value){return IsEqual(direction,"Decode")?Decode3(direction,context,type,value):Encode3(direction,context,type,value)}function FromCyclic9(direction,context,type,value){return value=FromType23(direction,{...context,...type.$defs},Ref2(type.$ref),value),Callback(direction,context,type,value)}function MergeInteriors(interiors){return interiors.reduce((results,interior)=>({...results,...interior}),{})}function NonMatchingInterior(value,interiors){for(let interior of interiors)if(!IsDeepEqual(value,interior))return interior;return value}function Decode4(direction,context,type,value){if(IsEqual(type.allOf.length,0))return Callback(direction,context,type,value);let interiors=type.allOf.map((schema)=>FromType23(direction,context,schema,Clean(schema,Clone2(value)))),exterior=interiors.every((result)=>IsObject(result))?MergeInteriors(interiors):NonMatchingInterior(value,interiors);return Callback(direction,context,type,exterior)}function Encode4(direction,context,type,value){if(IsEqual(type.allOf.length,0))return Callback(direction,context,type,value);let exterior=Callback(direction,context,type,value),interiors=type.allOf.map((schema)=>FromType23(direction,context,schema,Clean(schema,Clone2(exterior))));if(interiors.every((result)=>IsObject(result)))return MergeInteriors(interiors);return NonMatchingInterior(exterior,interiors)}function FromIntersect9(direction,context,type,value){return IsEqual(direction,"Decode")?Decode4(direction,context,type,value):Encode4(direction,context,type,value)}function Decode5(direction,context,type,value){if(!IsObjectNotArray(value))return value;for(let key of Keys(type.properties)){if(!HasPropertyKey(value,key)||IsOptionalUndefined(type.properties[key],key,value))continue;value[key]=FromType23(direction,context,type.properties[key],value[key])}return Callback(direction,context,type,value)}function Encode5(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsObjectNotArray(exterior))return exterior;for(let key of Keys(type.properties)){if(!HasPropertyKey(exterior,key)||IsOptionalUndefined(type.properties[key],key,exterior))continue;exterior[key]=FromType23(direction,context,type.properties[key],exterior[key])}return exterior}function FromObject13(direction,context,type,value){return IsEqual(direction,"Decode")?Decode5(direction,context,type,value):Encode5(direction,context,type,value)}function Decode6(direction,context,type,value){if(!IsObjectNotArray(value))return value;let regexp=new RegExp(RecordPattern(type));for(let key of Keys(value)){if(!regexp.test(key))continue;value[key]=FromType23(direction,context,RecordValue(type),value[key])}return Callback(direction,context,type,value)}function Encode6(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsObjectNotArray(exterior))return exterior;let regexp=new RegExp(RecordPattern(type));for(let key of Keys(exterior)){if(!regexp.test(key))continue;exterior[key]=FromType23(direction,context,RecordValue(type),exterior[key])}return exterior}function FromRecord6(direction,context,type,value){return IsEqual(direction,"Decode")?Decode6(direction,context,type,value):Encode6(direction,context,type,value)}function ResolveRef(direction,context,type,value){return HasPropertyKey(context,type.$ref)?FromType23(direction,context,context[type.$ref],value):value}function FromRef8(direction,context,type,value){return IsEqual(direction,"Decode")?Callback(direction,context,type,ResolveRef(direction,context,type,value)):ResolveRef(direction,context,type,Callback(direction,context,type,value))}function Decode7(direction,context,type,value){if(!IsArray(value))return value;for(let i=0;i<Math.min(type.items.length,value.length);i++)value[i]=FromType23(direction,context,type.items[i],value[i]);return Callback(direction,context,type,value)}function Encode7(direction,context,type,value){let exterior=Callback(direction,context,type,value);if(!IsArray(exterior))return value;for(let i=0;i<Math.min(type.items.length,exterior.length);i++)exterior[i]=FromType23(direction,context,type.items[i],exterior[i]);return exterior}function FromTuple8(direction,context,type,value){return IsEqual(direction,"Decode")?Decode7(direction,context,type,value):Encode7(direction,context,type,value)}function Decode8(direction,context,type,value){for(let schema of type.anyOf){if(!Check2(context,schema,value))continue;let variant=FromType23(direction,context,schema,value);return Callback(direction,context,type,variant)}return value}function Encode8(direction,context,type,value){let exterior=Callback(direction,context,type,value);for(let schema of type.anyOf){let variant=FromType23(direction,context,schema,Clone2(exterior));if(!Check2(context,schema,variant))continue;return variant}return exterior}function FromUnion12(direction,context,type,value){return IsEqual(direction,"Decode")?Decode8(direction,context,type,value):Encode8(direction,context,type,value)}function FromType23(direction,context,type,value){return IsArray2(type)?FromArray9(direction,context,type,value):IsCyclic(type)?FromCyclic9(direction,context,type,value):IsIntersect(type)?FromIntersect9(direction,context,type,value):IsObject2(type)?FromObject13(direction,context,type,value):IsRecord(type)?FromRecord6(direction,context,type,value):IsRef2(type)?FromRef8(direction,context,type,value):IsTuple(type)?FromTuple8(direction,context,type,value):IsUnion(type)?FromUnion12(direction,context,type,value):Callback(direction,context,type,value)}class DecodeError extends AssertError{constructor(value,errors){super("Decode",value,errors)}}function Assert(context,type,value){if(!Check2(context,type,value))throw new DecodeError(value,Errors2(context,type,value));return value}function DecodeUnsafe(context,type,value){let sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType23("Decode",context,sorted,value)}var Decoder=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert(context,type,value),(context,type,value)=>DecodeUnsafe(context,type,value)]);class EncodeError extends AssertError{constructor(value,errors){super("Encode",value,errors)}}function Assert2(context,type,value){if(!Check2(context,type,value))throw new EncodeError(value,Errors2(context,type,value));return value}function EncodeUnsafe(context,type,value){let sorted=Get().unionPrioritySort?UnionPrioritySort(type):type;return FromType23("Encode",context,sorted,value)}var Encoder=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>EncodeUnsafe(context,type,value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert2(context,type,value)]);class ParseError extends AssertError{constructor(value,errors){super("Parse",value,errors)}}function Assert3(context,type,value){EnableParseErrors();let errors=Errors2(context,type,value);if(DisableParseErrors(),!Check2(context,type,value))throw new ParseError(value,errors);return value}var Parser=Pipeline([(_context,_type,value)=>Clone2(value),(context,type,value)=>Default(context,type,value),(context,type,value)=>Convert(context,type,value),(context,type,value)=>Clean(context,type,value),(context,type,value)=>Assert3(context,type,value)]);var Insert2=_Object_({type:Literal("insert"),path:String2(),value:Unknown()}),Update2=Object({type:Literal("update"),path:String2(),value:Unknown()}),Delete=_Object_({type:Literal("delete"),path:String2()}),Edit=Union([Insert2,Update2,Delete]);function actionBranches(branches){return new Map(branches.map((branch)=>[String(Reflect.get(branch.properties.action??{},"const")),branch]))}var Button=Union([Literal("left"),Literal("right"),Literal("middle")]),shared2={timeout:Optional(Number2({exclusiveMinimum:0,description:"Maximum time in seconds for this action."})),include_screenshot:Optional(Boolean2({description:"Capture a screenshot after the action."}))},point={x:Number2(),y:Number2()},strict={additionalProperties:!1},SingleActionBranches=[_Object_({action:Literal("screenshot"),...shared2},strict),_Object_({action:Literal("click"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("double_click"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("move"),...point,button:Optional(Button),...shared2},strict),_Object_({action:Literal("drag"),...point,to_x:Number2(),to_y:Number2(),button:Optional(Button),...shared2},strict),_Object_({action:Literal("scroll"),...point,scroll_x:Number2(),scroll_y:Number2(),...shared2},strict),_Object_({action:Literal("type"),text:String2(),...shared2},strict),_Object_({action:Literal("keypress"),keys:_Array_(String2(),{minItems:1}),...shared2},strict),_Object_({action:Literal("wait"),ms:Integer({minimum:0}),...shared2},strict)],SingleAction=Union([...SingleActionBranches]),BatchShape=_Object_({action:Literal("batch"),actions:_Array_(SingleAction,{minItems:1}),...shared2},strict),ComputerActionsShape=Union([SingleAction,BatchShape]),ACTION_NAMES=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],flatActionFields={x:Optional(Number2({description:"click, double_click, move, drag (start), scroll (required): x pixel"})),y:Optional(Number2({description:"click, double_click, move, drag (start), scroll (required): y pixel"})),button:Optional(Enum(["left","right","middle"],{type:"string",description:"click, double_click, move, drag: mouse button (default left)"})),to_x:Optional(Number2({description:"drag (required): end x pixel"})),to_y:Optional(Number2({description:"drag (required): end y pixel"})),scroll_x:Optional(Number2({description:"scroll (required): horizontal scroll distance in pixels on every OS (one wheel notch is about 40 px); positive scrolls right"})),scroll_y:Optional(Number2({description:"scroll (required): vertical scroll distance in pixels on every OS (one wheel notch is about 40 px); positive moves the view toward the end of the content (down)"})),text:Optional(String2({description:"type (required): text to type"})),keys:Optional(_Array_(String2(),{minItems:1,description:"keypress (required): keys pressed together"})),ms:Optional(Integer({minimum:0,description:"wait (required): milliseconds"})),...shared2},ComputerActionsParams=_Object_({action:Enum([...ACTION_NAMES,"batch"],{type:"string",description:"The action to perform, or batch to run `actions` in order"}),actions:Optional(_Array_(_Object_({action:Enum([...ACTION_NAMES],{type:"string",description:"The action to perform"}),...flatActionFields},strict),{minItems:1,description:"batch (required): actions to execute in order"})),...flatActionFields},strict),SINGLE_BRANCHES=actionBranches(SingleActionBranches),TOP_BRANCHES=actionBranches([...SingleActionBranches,BatchShape]);var DESCRIPTION=["Drive the user's real desktop with OpenAI computer-use actions (experimental): screenshot, click, double_click, move, drag, scroll, type, keypress, wait, or a batch of them.","x,y are pixels of the latest screenshot. A batch stops at the first failed action; an in-batch screenshot becomes the frame for the actions after it.","Pass only the fields the chosen action takes (each field's description names its actions); anything else is refused with COMPUTER_INVALID_ARGUMENTS before any input.","Errors carry COMPUTER_* codes with a recovery hint. COMPUTER_SUSPENDED or COMPUTER_SUPERVISOR_NOT_LIVE means the user stopped you: stop and wait."].join(`
334
334
  `);var DEFAULT_TIMEOUT_SECONDS=60,MAX_TIMEOUT_SECONDS=600,CallStep=_Object_({method:String2({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:Optional(_Array_(Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),RunTimeout=Number2({minimum:1,maximum:MAX_TIMEOUT_SECONDS,description:`run: budget in seconds (default ${DEFAULT_TIMEOUT_SECONDS})`}),ComputerActionBranches=[_Object_({action:Literal("call"),chain:_Array_(CallStep,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),_Object_({action:Literal("run"),code:String2({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:Optional(Boolean2({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Optional(RunTimeout)},{additionalProperties:!1}),_Object_({action:Literal("capabilities")},{additionalProperties:!1}),_Object_({action:Literal("close")},{additionalProperties:!1})],ComputerActionShape=Union([...ComputerActionBranches]),ComputerParams=_Object_({action:Enum(["call","run","capabilities","close"],{type:"string",description:"call: one desktop helper chain; run: a JavaScript body; capabilities: host report; close: end the session"}),chain:Optional(_Array_(CallStep,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:Optional(String2({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:Optional(Boolean2({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Optional(RunTimeout)},{additionalProperties:!1});var METHOD_NAMES=new Set(ENGINE_METHODS),ERROR_CODE_NAMES=new Set(ERROR_CODES);import{readFileSync as readFileSync3}from"node:fs";import{dirname as dirname3,join as join3}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var ASSET_FIELDS=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],ASSETS_JSON_PATH=join3(dirname3(fileURLToPath2(import.meta.url)),"assets.generated.json"),cached2;function preludeAssets(){if(cached2===void 0){let parsed=JSON.parse(readFileSync3(ASSETS_JSON_PATH,"utf8"));cached2=validateAssets(parsed)}return cached2}function validateAssets(value){let record=value&&typeof value==="object"?value:void 0,missing=ASSET_FIELDS.filter((field)=>typeof record?.[field]!=="string");if(missing.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${ASSETS_JSON_PATH}: missing ${missing.join(", ")}`);return value}var METHOD_ALLOWLIST=["actions","attributes","ax","bounds","capabilities","children","click","clipboard.read","clipboard.write","displays","doubleClick","drag","elementAt","find","focus","focusedElement","focusedWindow","move","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows"],computerPreludeAssets={get javascript(){return preludeAssets().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return preludeAssets().COMPUTER_PRELUDE_PYTHON},get declarations(){return preludeAssets().COMPUTER_DECLARATIONS},get documentation(){return preludeAssets().COMPUTER_DOCUMENTATION},get safety(){return preludeAssets().COMPUTER_SAFETY},exports:["computer"],methodAllowlist:METHOD_ALLOWLIST};var DESCRIPTION2=["Drive the user's real desktop (experimental): windows, screenshots, native mouse and keyboard input, the OS accessibility (AX) tree, and the clipboard. Not a browser.",'- `{action:"call", chain}` runs one desktop helper, optionally followed by one call on the window/element it returns, e.g. `[{method:"window",args:[{app:"Code"}]},{method:"screenshot"}]`.','- `{action:"run", code, read_only?, timeout?}` runs a JavaScript async function body with `desktop`, `wait`, `assert`, and `tool` in scope; `read_only: true` blocks input.','- `{action:"capabilities"}` reports backend, permissions, `stopPath`, and `focusGuard`. `{action:"close"}` ends the desktop session.',"Pass only the fields of the chosen action; any other field is refused with COMPUTER_INVALID_ARGUMENTS.","In eval cells prefer the `computer` global, which wraps these actions. Pointer x,y are pixels of the latest screenshot of the same target."].join(`
335
335
  `),SAFETY_GUIDELINES=computerPreludeAssets.safety.split(`