trigger_system 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.browser.js +25 -25
- package/dist/browser/index.browser.js.map +8 -8
- package/dist/core/action-registry.d.ts.map +1 -1
- package/dist/core/expression-engine.d.ts.map +1 -1
- package/dist/core/rule-engine-new.d.ts.map +1 -1
- package/dist/core/rule-engine.d.ts.map +1 -1
- package/dist/core/trigger-engine.d.ts.map +1 -1
- package/dist/domain/validator.d.ts +124 -124
- package/dist/io/loader.node.d.ts.map +1 -1
- package/dist/lsp/completions.d.ts.map +1 -1
- package/dist/lsp/data-context.d.ts.map +1 -1
- package/dist/lsp/hover.d.ts.map +1 -1
- package/dist/node/index.js +98 -98
- package/dist/node/index.js.map +8 -8
- package/dist/node/node.js +99 -99
- package/dist/node/node.js.map +9 -9
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
var GU=Object.defineProperty;var _U=(Q,X)=>{for(var Y in X)GU(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(U)=>X[Y]=()=>U})};var xQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);class i{static evaluate(Q,X){try{if(Q.includes("${")){let Y=this.interpolate(Q,X);if(!isNaN(Number(Y))&&Y.trim()!=="")return Number(Y);return Y}return this.evaluateExpression(Q,X)}catch(Y){return console.error(`Error evaluating expression: ${Q}`,Y),null}}static interpolate(Q,X){return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{try{let Z=this.evaluateExpression(U,X);if(Z===void 0||Z===null)return"undefined";return String(Z)}catch(Z){return console.error(`Error en interpolación: ${Y}`,Z),Y}})}static evaluateMathExpression(Q){try{return Function("Math",`return ${Q}`)(Math)}catch(X){throw Error(`Error evaluando expresión matemática: ${Q}`)}}static evaluateExpression(Q,X){if(/^(data|globals|request|computed)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);try{return Function("context","with(context) { return "+Q+" }")(X)}catch(Y){return console.error(`ERROR evaluating expression '${Q}':`,Y),Q}}static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0||typeof U!=="object"||!(Z in U))return;U=U[Z]}return U}static evaluateMath(Q,X){let Y=Q;Y=Y.replace(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,(U)=>{if(["Math","random","floor","ceil","round","sqrt","abs","pow","min","max","sin","cos","tan"].includes(U))return U;let Z=this.getNestedValue(U,X);if(Z!==void 0)return typeof Z==="string"?`"${Z}"`:String(Z);return U});try{return this.evaluateMathExpression(Y)}catch(U){return console.error(`Error en evaluación matemática: ${Q}`,U),NaN}}}class B6{store=new Map;async loadState(){return new Map(this.store)}async saveState(Q,X){this.store.set(Q,X)}async deleteState(Q){this.store.delete(Q)}async clearState(){this.store.clear()}}class Q1{static instance;state;persistence;constructor(){this.state=new Map,this.persistence=new B6}static getInstance(){if(!Q1.instance)Q1.instance=new Q1;return Q1.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();this.state=Q,console.log(`[StateManager] Initialized with ${this.state.size} keys.`)}get(Q){return this.state.get(Q)}async set(Q,X){this.state.set(Q,X),await this.persistence.saveState(Q,X)}async increment(Q,X=1){let Y=this.get(Q)||0,U=Number(Y)+X;return await this.set(Q,U),U}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){let X=this.state.delete(Q);if(X)await this.persistence.deleteState(Q);return X}async clear(){this.state.clear(),await this.persistence.clearState()}getAll(){return Object.fromEntries(this.state)}}var U2=()=>{};var uQ={};_U(uQ,{ActionRegistry:()=>v1});class v1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new v1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}registerDefaults(){this.register("log",(Q,X)=>{let Y=Q.params?.message||Q.params?.content||"Log Trigger",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);return console.log(`[TriggerLog] ${U}`),{message:U}}),this.register("response",(Q,X)=>{let Y=Q.params?.content||Q.params?.body||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);return{statusCode:Q.params?.statusCode||200,headers:Q.params?.headers||{"Content-Type":"application/json"},body:U}}),this.register("execute",async(Q,X)=>{let Y=Q.params?.command||Q.params?.content||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y);if(!Q.params?.safe)console.warn(`[Trigger] Ejecutando comando no seguro: ${U}`);try{let Z=Bun.spawn(U.split(" "),{stdout:"pipe",stderr:"pipe"}),[W,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{command:U,stdout:W,stderr:G,exitCode:await Z.exited}}catch(Z){return{command:U,error:String(Z)}}}),this.register("forward",async(Q,X)=>{let Y=Q.params?.url||"",U=typeof Y==="string"?i.interpolate(Y,X):String(Y),Z=String(Q.params?.method||"POST");try{let W=await fetch(U,{method:Z,headers:{"Content-Type":"application/json",...typeof Q.params?.headers==="object"&&Q.params.headers!==null&&!Array.isArray(Q.params.headers)?Q.params.headers:{}},body:JSON.stringify(X.data)});return{url:U,method:Z,status:W.status,headers:(()=>{let G={};return W.headers.forEach((_,H)=>G[H]=_),G})(),body:await W.text()}}catch(W){return{url:U,method:Z,error:String(W)}}}),this.register("STATE_SET",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Q.params?.value;if(!Y)return{error:"Missing key for STATE_SET"};let Z=U;if(typeof U==="string"&&U.includes("${"))Z=i.interpolate(U,X);return await Q1.getInstance().set(Y,Z),{key:Y,value:Z}}),this.register("STATE_INCREMENT",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Number(Q.params?.amount)||1;if(!Y)return{error:"Missing key for STATE_INCREMENT"};let Z=await Q1.getInstance().increment(Y,U);return{key:Y,newValue:Z}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}})}}var Z2=xQ(()=>{U2()});class JU{queue=[];engine;config;timer=null;isProcessing=!1;constructor(Q,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=Q,this.config=X}push(Q){if(this.queue.push(Q),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let Q=this.queue.splice(0,this.config.maxBatchSize);if(Q.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${Q.length} events.`);for(let X of Q)try{await this.engine.evaluateContext(X)}catch(Y){console.error(`[EventQueue] Error processing event ${X.event}:`,Y)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class hQ{keyPrefix;cache=new Map;isLoaded=!1;constructor(Q="trigger_system:"){this.keyPrefix=Q}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let Q=window.localStorage.getItem(this.keyPrefix+"state");if(Q){let X=JSON.parse(Q);this.cache=new Map(Object.entries(X))}}catch(Q){console.error("[BrowserPersistence] Failed to load from localStorage:",Q)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let Q=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(Q))}catch(Q){console.error("[BrowserPersistence] Failed to save to localStorage:",Q)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(Q,X){this.ensureLoaded(),this.cache.set(Q,X),this.persist()}async deleteState(Q){this.ensureLoaded(),this.cache.delete(Q),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y2{static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0)return;if(typeof U==="object"&&U!==null&&Z in U)U=U[Z];else return}return U}static interpolate(Q,X){if(typeof Q!=="string")return Q;return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{let Z=this.getNestedValue(U,X);if(Z!==void 0)return String(Z);return Y})}static compare(Q,X,Y){switch(X){case"EQ":case"==":return Q==Y;case"NEQ":case"!=":return Q!=Y;case"GT":case">":return Number(Q)>Number(Y);case"GTE":case">=":return Number(Q)>=Number(Y);case"LT":case"<":return Number(Q)<Number(Y);case"LTE":case"<=":return Number(Q)<=Number(Y);case"IN":return Array.isArray(Y)&&Y.some((U)=>U===Q);case"NOT_IN":return Array.isArray(Y)&&!Y.some((U)=>U===Q);case"CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return Q.includes(Y);return!1;case"MATCHES":if(typeof Y==="string")return new RegExp(Y).test(String(Q));return!1;case"RANGE":if(Array.isArray(Y)&&Y.length===2){let U=Number(Q),Z=Number(Y[0]),W=Number(Y[1]);return!isNaN(U)&&!isNaN(Z)&&!isNaN(W)&&U>=Z&&U<=W}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var pQ;((U)=>{U.RULE_ADDED="rule:added";U.RULE_REMOVED="rule:removed";U.RULE_UPDATED="rule:updated"})(pQ||={});var k2=pQ;class M6{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new M6;return this.instance}on(Q,X){let Y=Q;if(!this.handlers.has(Y))this.handlers.set(Y,new Set);return this.handlers.get(Y).add(X),()=>this.off(Y,X)}off(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.delete(X)}emit(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.forEach((Z)=>{try{Z(X)}catch(W){console.error(`Error in event handler for ${Y}:`,W)}})}}var G1=M6.getInstance();class W2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(Q=[]){if(Array.isArray(Q))this._rules=Q;else this._config=Q,this._rules=[...Q.rules];this.sortRules()}sortRules(){this._rules.sort((Q,X)=>(X.priority||0)-(Q.priority||0))}registerAction(Q,X){this.actionHandlers.set(Q,X)}async processEvent(Q){let X=[],Y=this._rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown))continue;if(this.evaluateConditions(U.if,Q)){let Z=await this.executeRuleActions(U.do,Q);if(this.lastExecution.set(U.id,Date.now()),X.push({ruleId:U.id,success:!0,executedActions:Z}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(U)}updateRules(Q){let X=this.getRules(),Y=new Set(X.map((G)=>G.id)),U=new Set(Q.map((G)=>G.id)),Z=Q.filter((G)=>!Y.has(G.id)),W=X.filter((G)=>!U.has(G.id));this.rules=[...Q],this.sortRules(),Z.forEach((G)=>{this.emitRuleEvent(k2.RULE_ADDED,{ruleId:G.id,timestamp:Date.now()})}),W.forEach((G)=>{this.emitRuleEvent(k2.RULE_REMOVED,{ruleId:G.id,timestamp:Date.now()})}),this.emitRuleEvent(k2.RULE_UPDATED,{count:Q.length,added:Z.length,removed:W.length,unchanged:Q.length-Z.length,timestamp:Date.now()})}emitRuleEvent(Q,X){try{if(G1)G1.emit(Q,{...X,timestamp:Date.now()})}catch(Y){console.warn(`Could not emit event ${Q}:`,Y)}}getRules(){return[...this.rules]}checkCooldown(Q,X){let Y=this.lastExecution.get(Q);if(!Y)return!1;return Date.now()-Y<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Q,X){if(!Q)return!0;if(Array.isArray(Q))return Q.every((Y)=>this.evaluateSingleCondition(Y,X));return this.evaluateSingleCondition(Q,X)}evaluateSingleCondition(Q,X){if("operator"in Q&&"conditions"in Q){let W=Q;if(W.operator==="OR")return W.conditions.some((G)=>this.evaluateSingleCondition(G,X));else return W.conditions.every((G)=>this.evaluateSingleCondition(G,X))}let Y=Q,U=Y2.getNestedValue(Y.field,X),Z=Y.value;if(typeof Z==="string"&&Z.includes("${"))Z=i.interpolate(Z,X);return Y2.compare(U,Y.operator,Z)}async executeRuleActions(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if("mode"in Q&&"actions"in Q){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=U.reduce((H,J)=>H+(J.probability||1),0),G=Math.random()*W,_;for(let H of U){let J=H.probability||1;if(G-=J,G<=0){_=H;break}}if(!_&&U.length>0)_=U[U.length-1];if(_)U=[_];else U=[]}for(let W of U){let G=await this.executeSingleAction(W,X);Y.push(G)}return Y}async executeSingleAction(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y;try{let{ActionRegistry:Z}=await Promise.resolve().then(() => (Z2(),uQ)),W=Z.getInstance().get(Q.type);if(W)Y=(G)=>W({...Q,params:G},X)}catch{Y=this.actionHandlers.get(Q.type)}let U;if(Y)U=await Y(Q.params||{},X);else{let Z=`No handler registered for action type: ${Q.type}`;console.warn(Z),U={warning:Z}}return{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error(`Error executing action ${Q.type}:`,Y),{type:Q.type,error:String(Y),timestamp:Date.now()}}}interpolateParams(Q,X){let Y={};for(let[U,Z]of Object.entries(Q))if(typeof Z==="string")Y[U]=i.interpolate(Z,X);else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))Y[U]=this.interpolateDeep(Z,X);else Y[U]=Z;return Y}interpolateDeep(Q,X){if(typeof Q==="string")return i.interpolate(Q,X);if(Array.isArray(Q))return Q.map((Y)=>this.interpolateDeep(Y,X));if(typeof Q==="object"&&Q!==null){let Y={};for(let U in Q)Y[U]=this.interpolateDeep(Q[U],X);return Y}return Q}get rules(){return[...this._rules]}get config(){return this._config}set rules(Q){this._rules=[...Q],this.sortRules()}}Z2();U2();class T6 extends W2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=v1.getInstance(),this.stateManager=Q1.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getAll(),G1.emit("engine:start",{context:Q,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${Q.event}`);let Y=this.rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${U.id} in cooldown`);continue}if(this.evaluateConditions(U.if,Q)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${U.name||U.id}`);G1.emit("rule:match",{rule:U,context:Q});let W=await this.executeRuleActionsWithRegistry(U.do,Q);if(X.push({ruleId:U.id,executedActions:W,success:!0}),this.updateLastExecution(U.id),!this.shouldEvaluateAll())break}}return G1.emit("engine:done",{results:X,context:Q}),X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.stateManager.getAll()};return this.processEvent(U)}async executeRuleActionsWithRegistry(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if(this.isActionGroup(Q)){let W=Q;Z=W.mode,U=W.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let W=Math.floor(Math.random()*U.length),G=U[W];if(G)U=[G]}if(Z==="SEQUENCE")for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}else for(let W of U){let G=await this.executeSingleActionWithRegistry(W,X);Y.push(G)}return Y}isActionGroup(Q){return typeof Q==="object"&&Q!==null&&"mode"in Q&&"actions"in Q}async executeSingleActionWithRegistry(Q,X){if(Q.probability!==void 0&&Math.random()>Q.probability)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.delay&&Q.delay>0)await new Promise((Y)=>setTimeout(Y,Q.delay));try{let Y=this.actionRegistry.get(Q.type),U;if(Y)U=await Y(Q,X);else{let Z=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(Z);console.warn(Z),U={warning:`Generic action executed: ${Q.type}`}}return G1.emit("action:success",{action:Q,context:X,result:U}),{type:Q.type,result:U,timestamp:Date.now()}}catch(Y){return console.error("Error executing action:",Q,Y),G1.emit("action:error",{action:Q,context:X,error:String(Y)}),{type:Q.type,error:String(Y),timestamp:Date.now()}}}updateLastExecution(Q){this.lastExecution.set(Q,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(Q,X){return this.executeRuleActionsWithRegistry(Q,X)}async executeSingleAction(Q,X){return this.executeSingleActionWithRegistry(Q,X)}}Z2();class HU{static create(Q,X,Y={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},globals:Y,helpers:this.getDefaultHelpers()}}static fromRequest(Q,X,Y={}){let U=new URL(Q.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Q.method,path:U.pathname,query:Object.fromEntries(U.searchParams),headers:(()=>{let Z={};return Q.headers.forEach((W,G)=>Z[G]=W),Z})(),body:X||{}},globals:{...Y,ip:Q.headers.get("x-forwarded-for")||"unknown"},helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,Y,U={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Y,globals:{...U,provider:Q},helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>typeof Q==="string"?JSON.parse(Q):null,jsonStringify:(Q)=>JSON.stringify(Q)}}}U2();Z2();U2();var B1=(Q)=>Array.isArray(Q)?Q:[Q],mQ=(Q,X)=>{let Y=[[],[]];for(let U of Q)if(X(U))Y[0].push(U);else Y[1].push(U);return Y},g2=Array,n=(Q,X)=>Q.includes(X),lQ=(Q,X=0)=>[...Array(Q)].map((Y,U)=>U+X),D=(Q,X,Y)=>{if(Q===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(Y?.prepend)if(Array.isArray(X))Q.unshift(...X);else Q.unshift(X);else if(Array.isArray(X))Q.push(...X);else Q.push(X);return Q},q1=(Q,X)=>{if(X===void 0||X===null)return Q??[];if(Q===void 0||Q===null)return B1(X);return Q.concat(X)},dQ=(...Q)=>Q.reduce(q1,[]),_1=(Q,X,Y)=>{if(Q===void 0)return Array.isArray(X)?X:[X];let U=Y?.isEqual??((Z,W)=>Z===W);for(let Z of B1(X))if(!Q.some((W)=>U(W,Z)))Q.push(Z);return Q},cQ=(Q,X)=>Q.reduce((Y,U)=>{let Z=U[X];return Y[Z]=D(Y[Z],U),Y},{}),$1=(Q,X,Y)=>Q.length===X.length&&Q.every(Y?.isEqual?(U,Z)=>Y.isEqual(U,X[Z]):(U,Z)=>U===X[Z]);var p=(Q,X)=>y(Q)===X,y=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},u={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},oQ={...u,function:"a function"};class iQ extends Error{}var C=(Q)=>P1(Q,iQ),P1=(Q,X=Error)=>{throw new X(Q)};class G2 extends Error{name="ParseError"}var L=(Q)=>P1(Q,G2),X1=(Q)=>` ${Q}`,sQ="";var V=(Q,X)=>{let Y={},U=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let _=U?X(W,G[1]):X(...G,W);Z||=typeof _[0]==="number";let H=Array.isArray(_[0])||_.length===0?_:[_];for(let[J,$]of H)if(typeof J==="object")Y[J.group]=D(Y[J.group],$);else Y[J]=$}return Z?Object.values(Y):Y};var D6=Object.entries;var f=(Q,X)=>(Q in X),k1=(Q,X)=>(X in Q);class R6{constructor(Q){Object.assign(this,Q)}}var nQ=class{};class _2 extends nQ{}var FU=(Q,X)=>{let Y={},U={},Z;for(Z in Q)if(Z in X)Y[Z]=Q[Z];else U[Z]=Q[Z];return[Y,U]};var x2=(Q,X)=>FU(Q,X)[1],J1=(Q)=>Object.keys(Q).length===0,N1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],rQ=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),tQ=(Q)=>{let X=Object.keys(Q).sort(),Y={};for(let U=0;U<X.length;U++)Y[X[U]]=Q[X[U]];return Y};var m=X1(`unset${sQ}`),aQ=(Q)=>Object.values(Q).filter((X)=>{if(typeof X==="number")return!0;return typeof Q[X]!=="number"});var C6={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},w6=globalThis.File??Blob,K6={ArrayBuffer,Blob,File:w6,FormData,Headers,Request,Response,URL},qU={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},E1={...C6,...K6,...qU,String,Number,Boolean},J2=(Q)=>{let X=Object.getPrototypeOf(Q);while(X?.constructor&&(!f(X.constructor.name,E1)||!(Q instanceof E1[X.constructor.name])))X=Object.getPrototypeOf(X);let Y=X?.constructor?.name;if(Y===void 0||Y==="Object")return;return Y},L2=(Q)=>typeof Q==="object"&&Q!==null?J2(Q)??"object":y(Q);var K=Array.isArray,$U={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},AU={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},zU={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},eQ={...$U,...AU,...zU},H2=(Q)=>{let X=Object(Q).name??null;return X&&f(X,E1)&&E1[X]===Q?X:null};var P6=(Q,X)=>{let Y=Q.prototype;while(Y!==null){if(Y===X.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1};var Q4=(Q)=>X4(Q,new Map),X4=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let Y=H2(Q.constructor);if(Y==="Date")return new Date(Q.getTime());if(Y&&Y!=="Array")return Q;let U=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),Z=Object.getOwnPropertyDescriptors(Q);if(X){X.set(Q,U);for(let W in Z){let G=Z[W];if("get"in G||"set"in G)continue;G.value=X4(G.value,X)}}return Object.defineProperties(U,Z),U};var OU=(Q)=>{let X=m;return()=>X===m?X=Q():X},M1=(Q)=>typeof Q==="function"&&Q.length===0;var Y4=class extends Function{constructor(...Q){let X=Q.slice(0,-1),Y=Q[Q.length-1];try{super(...X,Y)}catch(U){return C(`Encountered an unexpected error while compiling your definition:
|
|
1
|
+
var{defineProperty:V6,getOwnPropertyNames:FU,getOwnPropertyDescriptor:qU}=Object,AU=Object.prototype.hasOwnProperty;var pQ=new WeakMap,uQ=(Q)=>{var X=pQ.get(Q),Y;if(X)return X;if(X=V6({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function")FU(Q).map((U)=>!AU.call(X,U)&&V6(X,U,{get:()=>Q[U],enumerable:!(Y=qU(Q,U))||Y.enumerable}));return pQ.set(Q,X),X};var mQ=(Q,X)=>{for(var Y in X)V6(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:(U)=>X[Y]=()=>U})};var lQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);var M6={};mQ(M6,{ExpressionEngine:()=>k});class k{static evaluate(Q,X){try{if(Q.includes("${")){let Y=this.interpolate(Q,X);if(!isNaN(Number(Y))&&Y.trim()!=="")return Number(Y);return Y}return this.evaluateExpression(Q,X)}catch(Y){return console.error(`Error evaluating expression: ${Q}`,Y),null}}static interpolate(Q,X){return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{try{let Z=this.evaluateExpression(U,X);if(Z===void 0||Z===null)return"undefined";return String(Z)}catch(Z){return console.error(`Error en interpolación: ${Y}`,Z),Y}})}static evaluateMathExpression(Q){try{return Function("Math",`return ${Q}`)(Math)}catch(X){throw Error(`Error evaluando expresión matemática: ${Q}`)}}static evaluateExpression(Q,X){if(/^(data|globals|request|computed)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);try{return Function("context","with(context) { return "+Q+" }")(X)}catch(Y){return console.error(`ERROR evaluating expression '${Q}':`,Y),Q}}static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0||typeof U!=="object"||!(Z in U))return;U=U[Z]}return U}static evaluateMath(Q,X){let Y=Q;Y=Y.replace(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,(U)=>{if(["Math","random","floor","ceil","round","sqrt","abs","pow","min","max","sin","cos","tan"].includes(U))return U;let Z=this.getNestedValue(U,X);if(Z!==void 0)return typeof Z==="string"?`"${Z}"`:String(Z);return U});try{return this.evaluateMathExpression(Y)}catch(U){return console.error(`Error en evaluación matemática: ${Q}`,U),NaN}}}class T6{store=new Map;async loadState(){return new Map(this.store)}async saveState(Q,X){this.store.set(Q,X)}async deleteState(Q){this.store.delete(Q)}async clearState(){this.store.clear()}}class Q1{static instance;state;persistence;constructor(){this.state=new Map,this.persistence=new T6}static getInstance(){if(!Q1.instance)Q1.instance=new Q1;return Q1.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();this.state=Q,console.log(`[StateManager] Initialized with ${this.state.size} keys.`)}get(Q){return this.state.get(Q)}async set(Q,X){this.state.set(Q,X),await this.persistence.saveState(Q,X)}async increment(Q,X=1){let Y=this.get(Q)||0,U=Number(Y)+X;return await this.set(Q,U),U}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){let X=this.state.delete(Q);if(X)await this.persistence.deleteState(Q);return X}async clear(){this.state.clear(),await this.persistence.clearState()}getAll(){return Object.fromEntries(this.state)}}var U2=()=>{};var oQ={};mQ(oQ,{ActionRegistry:()=>v1});class v1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new v1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}registerDefaults(){this.register("log",(Q,X)=>{let Y=Q.params?.message||Q.params?.content||"Log Trigger",U=typeof Y==="string"?k.interpolate(Y,X):String(Y);return console.log(`[TriggerLog] ${U}`),{message:U}}),this.register("math",(Q,X)=>{let Y=String(Q.params?.expression||"0");return k.evaluate(Y,X)}),this.register("response",(Q,X)=>{let Y=Q.params?.content||Q.params?.body||"",U=typeof Y==="string"?k.interpolate(Y,X):String(Y);return{statusCode:Q.params?.statusCode||200,headers:Q.params?.headers||{"Content-Type":"application/json"},body:U}}),this.register("execute",async(Q,X)=>{let Y=Q.params?.command||Q.params?.content||"",U=typeof Y==="string"?k.interpolate(Y,X):String(Y);if(!Q.params?.safe)console.warn(`[Trigger] Ejecutando comando no seguro: ${U}`);try{let Z=Bun.spawn(U.split(" "),{stdout:"pipe",stderr:"pipe"}),[W,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{command:U,stdout:W,stderr:G,exitCode:await Z.exited}}catch(Z){return{command:U,error:String(Z)}}}),this.register("forward",async(Q,X)=>{let Y=Q.params?.url||"",U=typeof Y==="string"?k.interpolate(Y,X):String(Y),Z=String(Q.params?.method||"POST");try{let W=await fetch(U,{method:Z,headers:{"Content-Type":"application/json",...typeof Q.params?.headers==="object"&&Q.params.headers!==null&&!Array.isArray(Q.params.headers)?Q.params.headers:{}},body:JSON.stringify(X.data)});return{url:U,method:Z,status:W.status,headers:(()=>{let G={};return W.headers.forEach((_,L)=>G[L]=_),G})(),body:await W.text()}}catch(W){return{url:U,method:Z,error:String(W)}}}),this.register("STATE_SET",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Q.params?.value;if(!Y)return{error:"Missing key for STATE_SET"};let Z=U;if(typeof U==="string"&&U.includes("${"))Z=k.interpolate(U,X);return await Q1.getInstance().set(Y,Z),{key:Y,value:Z}}),this.register("STATE_INCREMENT",async(Q,X)=>{let Y=String(Q.params?.key||""),U=Number(Q.params?.amount)||1;if(!Y)return{error:"Missing key for STATE_INCREMENT"};let Z=await Q1.getInstance().increment(Y,U);return{key:Y,newValue:Z}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}})}}var Z2=lQ(()=>{U2()});class $U{queue=[];engine;config;timer=null;isProcessing=!1;constructor(Q,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=Q,this.config=X}push(Q){if(this.queue.push(Q),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let Q=this.queue.splice(0,this.config.maxBatchSize);if(Q.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${Q.length} events.`);for(let X of Q)try{await this.engine.evaluateContext(X)}catch(Y){console.error(`[EventQueue] Error processing event ${X.event}:`,Y)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class dQ{keyPrefix;cache=new Map;isLoaded=!1;constructor(Q="trigger_system:"){this.keyPrefix=Q}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let Q=window.localStorage.getItem(this.keyPrefix+"state");if(Q){let X=JSON.parse(Q);this.cache=new Map(Object.entries(X))}}catch(Q){console.error("[BrowserPersistence] Failed to load from localStorage:",Q)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let Q=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(Q))}catch(Q){console.error("[BrowserPersistence] Failed to save to localStorage:",Q)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(Q,X){this.ensureLoaded(),this.cache.set(Q,X),this.persist()}async deleteState(Q){this.ensureLoaded(),this.cache.delete(Q),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y2{static getNestedValue(Q,X){let Y=Q.split("."),U=X;for(let Z of Y){if(U===null||U===void 0)return;if(typeof U==="object"&&U!==null&&Z in U)U=U[Z];else return}return U}static interpolate(Q,X){if(typeof Q!=="string")return Q;return Q.replace(/\$\{([^}]+)\}/g,(Y,U)=>{let Z=this.getNestedValue(U,X);if(Z!==void 0)return String(Z);return Y})}static compare(Q,X,Y){switch(X){case"EQ":case"==":return Q==Y;case"NEQ":case"!=":return Q!=Y;case"GT":case">":return Number(Q)>Number(Y);case"GTE":case">=":return Number(Q)>=Number(Y);case"LT":case"<":return Number(Q)<Number(Y);case"LTE":case"<=":return Number(Q)<=Number(Y);case"IN":return Array.isArray(Y)&&Y.some((U)=>U===Q);case"NOT_IN":return Array.isArray(Y)&&!Y.some((U)=>U===Q);case"CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return Q.includes(Y);return!1;case"MATCHES":if(typeof Y==="string")return new RegExp(Y).test(String(Q));return!1;case"RANGE":if(Array.isArray(Y)&&Y.length===2){let U=Number(Q),Z=Number(Y[0]),W=Number(Y[1]);return!isNaN(U)&&!isNaN(Z)&&!isNaN(W)&&U>=Z&&U<=W}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var cQ;((U)=>{U.RULE_ADDED="rule:added";U.RULE_REMOVED="rule:removed";U.RULE_UPDATED="rule:updated"})(cQ||={});var k2=cQ;class D6{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new D6;return this.instance}on(Q,X){let Y=Q;if(!this.handlers.has(Y))this.handlers.set(Y,new Set);return this.handlers.get(Y).add(X),()=>this.off(Y,X)}off(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.delete(X)}emit(Q,X){let Y=Q,U=this.handlers.get(Y);if(U)U.forEach((Z)=>{try{Z(X)}catch(W){console.error(`Error in event handler for ${Y}:`,W)}})}}var G1=D6.getInstance();class W2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(Q=[]){if(Array.isArray(Q))this._rules=Q;else this._config=Q,this._rules=[...Q.rules];this.sortRules()}sortRules(){this._rules.sort((Q,X)=>(X.priority||0)-(Q.priority||0))}registerAction(Q,X){this.actionHandlers.set(Q,X)}async processEvent(Q){let X=[],Y=this._rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown))continue;if(this.evaluateConditions(U.if,Q)){let Z=await this.executeRuleActions(U.do,Q);if(this.lastExecution.set(U.id,Date.now()),X.push({ruleId:U.id,success:!0,executedActions:Z}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(U)}updateRules(Q){let X=this.getRules(),Y=new Set(X.map((G)=>G.id)),U=new Set(Q.map((G)=>G.id)),Z=Q.filter((G)=>!Y.has(G.id)),W=X.filter((G)=>!U.has(G.id));this.rules=[...Q],this.sortRules(),Z.forEach((G)=>{this.emitRuleEvent(k2.RULE_ADDED,{ruleId:G.id,timestamp:Date.now()})}),W.forEach((G)=>{this.emitRuleEvent(k2.RULE_REMOVED,{ruleId:G.id,timestamp:Date.now()})}),this.emitRuleEvent(k2.RULE_UPDATED,{count:Q.length,added:Z.length,removed:W.length,unchanged:Q.length-Z.length,timestamp:Date.now()})}emitRuleEvent(Q,X){try{if(G1)G1.emit(Q,{...X,timestamp:Date.now()})}catch(Y){console.warn(`Could not emit event ${Q}:`,Y)}}getRules(){return[...this.rules]}checkCooldown(Q,X){let Y=this.lastExecution.get(Q);if(!Y)return!1;return Date.now()-Y<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Q,X){if(!Q)return!0;if(Array.isArray(Q))return Q.every((Y)=>this.evaluateSingleCondition(Y,X));return this.evaluateSingleCondition(Q,X)}evaluateSingleCondition(Q,X){if("operator"in Q&&"conditions"in Q){let W=Q;if(W.operator==="OR")return W.conditions.some((G)=>this.evaluateSingleCondition(G,X));else return W.conditions.every((G)=>this.evaluateSingleCondition(G,X))}let Y=Q,U=Y2.getNestedValue(Y.field,X),Z=Y.value;if(typeof Z==="string"&&Z.includes("${"))Z=k.interpolate(Z,X);return Y2.compare(U,Y.operator,Z)}async executeRuleActions(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if("mode"in Q&&"actions"in Q){let G=Q;Z=G.mode,U=G.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let G=U.reduce((J,A)=>J+(A.probability||1),0),_=Math.random()*G,L;for(let J of U){let A=J.probability||1;if(_-=A,_<=0){L=J;break}}if(!L&&U.length>0)L=U[U.length-1];if(L)U=[L];else U=[]}let W=X.lastResult;for(let G of U){let _={...X,lastResult:W},L=await this.executeSingleAction(G,_);if(Y.push(L),Z==="SEQUENCE")W=L.result}return Y}async executeSingleAction(Q,X){let Y=Q.probability;if(typeof Y==="string"){let W=k.evaluate(Y,X);Y=typeof W==="number"?W:Number(W)}if(Y!==void 0&&Math.random()>Y)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};let U=Q.delay;if(typeof U==="string"){let W=k.evaluate(U,X);U=typeof W==="number"?W:Number(W)}if(U&&U>0)await new Promise((W)=>setTimeout(W,U));let Z=this.interpolateParams(Q.params||{},X);try{let W;try{let{ActionRegistry:_}=await Promise.resolve().then(() => (Z2(),oQ)),L=_.getInstance().get(Q.type);if(L)W=(J)=>L({...Q,params:J},X)}catch{W=this.actionHandlers.get(Q.type)}let G;if(W)G=await W(Z,X);else{let _=`No handler registered for action type: ${Q.type}`;console.warn(_),G={warning:_}}return{type:Q.type,result:G,timestamp:Date.now()}}catch(W){return console.error(`Error executing action ${Q.type}:`,W),{type:Q.type,error:String(W),timestamp:Date.now()}}}interpolateParams(Q,X){let Y={};for(let[U,Z]of Object.entries(Q))if(typeof Z==="string")Y[U]=k.interpolate(Z,X);else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))Y[U]=this.interpolateDeep(Z,X);else Y[U]=Z;return Y}interpolateDeep(Q,X){if(typeof Q==="string")return k.interpolate(Q,X);if(Array.isArray(Q))return Q.map((Y)=>this.interpolateDeep(Y,X));if(typeof Q==="object"&&Q!==null){let Y={};for(let U in Q)Y[U]=this.interpolateDeep(Q[U],X);return Y}return Q}get rules(){return[...this._rules]}get config(){return this._config}set rules(Q){this._rules=[...Q],this.sortRules()}}Z2();U2();class R6 extends W2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=v1.getInstance(),this.stateManager=Q1.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getAll(),G1.emit("engine:start",{context:Q,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${Q.event}`);let Y=this.rules.filter((U)=>U.enabled!==!1&&U.on===Q.event);for(let U of Y){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${U.id} in cooldown`);continue}if(this.evaluateConditions(U.if,Q)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${U.name||U.id}`);G1.emit("rule:match",{rule:U,context:Q});let W=await this.executeRuleActionsWithRegistry(U.do,Q);if(X.push({ruleId:U.id,executedActions:W,success:!0}),this.updateLastExecution(U.id),!this.shouldEvaluateAll())break}}return G1.emit("engine:done",{results:X,context:Q}),X}async processEventSimple(Q,X={},Y={}){let U={event:Q,data:X,globals:Y,timestamp:Date.now(),state:this.stateManager.getAll()};return this.processEvent(U)}async executeRuleActionsWithRegistry(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if(this.isActionGroup(Q)){let G=Q;Z=G.mode,U=G.actions}else U=[Q];if(Z==="EITHER"&&U.length>0){let G=U.reduce((J,A)=>J+(A.probability||1),0),_=Math.random()*G,L;for(let J of U){let A=J.probability||1;if(_-=A,_<=0){L=J;break}}if(L)U=[L]}let W=X.lastResult;for(let G of U){let _={...X,lastResult:W},L=await this.executeSingleActionWithRegistry(G,_);if(Y.push(L),Z==="SEQUENCE")W=L.result}return Y}isActionGroup(Q){return typeof Q==="object"&&Q!==null&&"mode"in Q&&"actions"in Q}async executeSingleActionWithRegistry(Q,X){let Y=Q.probability;if(typeof Y==="string"){let{ExpressionEngine:W}=uQ(M6),G=W.evaluate(Y,X);Y=typeof G==="number"?G:Number(G)}if(Y!==void 0&&Math.random()>Y)return{type:Q.type,timestamp:Date.now(),result:{skipped:"probability check failed"}};let U=Q.delay;if(typeof U==="string"){let{ExpressionEngine:W}=uQ(M6),G=W.evaluate(U,X);U=typeof G==="number"?G:Number(G)}if(U&&U>0)await new Promise((W)=>setTimeout(W,U));let Z=this.interpolateParams(Q.params||{},X);try{let W=this.actionRegistry.get(Q.type),G;if(W)G=await W({...Q,params:Z},X);else{let _=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(_);console.warn(_),G={warning:`Generic action executed: ${Q.type}`}}return G1.emit("action:success",{action:{...Q,params:Z},context:X,result:G}),{type:Q.type,result:G,timestamp:Date.now()}}catch(W){return console.error("Error executing action:",Q,W),G1.emit("action:error",{action:Q,context:X,error:String(W)}),{type:Q.type,error:String(W),timestamp:Date.now()}}}updateLastExecution(Q){this.lastExecution.set(Q,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(Q,X){return this.executeRuleActionsWithRegistry(Q,X)}async executeSingleAction(Q,X){return this.executeSingleActionWithRegistry(Q,X)}}Z2();class OU{static create(Q,X,Y={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},globals:Y,helpers:this.getDefaultHelpers()}}static fromRequest(Q,X,Y={}){let U=new URL(Q.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Q.method,path:U.pathname,query:Object.fromEntries(U.searchParams),headers:(()=>{let Z={};return Q.headers.forEach((W,G)=>Z[G]=W),Z})(),body:X||{}},globals:{...Y,ip:Q.headers.get("x-forwarded-for")||"unknown"},helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,Y,U={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Y,globals:{...U,provider:Q},helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>typeof Q==="string"?JSON.parse(Q):null,jsonStringify:(Q)=>JSON.stringify(Q)}}}U2();Z2();U2();var B1=(Q)=>Array.isArray(Q)?Q:[Q],iQ=(Q,X)=>{let Y=[[],[]];for(let U of Q)if(X(U))Y[0].push(U);else Y[1].push(U);return Y},g2=Array,n=(Q,X)=>Q.includes(X),sQ=(Q,X=0)=>[...Array(Q)].map((Y,U)=>U+X),D=(Q,X,Y)=>{if(Q===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(Y?.prepend)if(Array.isArray(X))Q.unshift(...X);else Q.unshift(X);else if(Array.isArray(X))Q.push(...X);else Q.push(X);return Q},q1=(Q,X)=>{if(X===void 0||X===null)return Q??[];if(Q===void 0||Q===null)return B1(X);return Q.concat(X)},nQ=(...Q)=>Q.reduce(q1,[]),_1=(Q,X,Y)=>{if(Q===void 0)return Array.isArray(X)?X:[X];let U=Y?.isEqual??((Z,W)=>Z===W);for(let Z of B1(X))if(!Q.some((W)=>U(W,Z)))Q.push(Z);return Q},rQ=(Q,X)=>Q.reduce((Y,U)=>{let Z=U[X];return Y[Z]=D(Y[Z],U),Y},{}),A1=(Q,X,Y)=>Q.length===X.length&&Q.every(Y?.isEqual?(U,Z)=>Y.isEqual(U,X[Z]):(U,Z)=>U===X[Z]);var u=(Q,X)=>b(Q)===X,b=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},m={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},tQ={...m,function:"a function"};class aQ extends Error{}var C=(Q)=>P1(Q,aQ),P1=(Q,X=Error)=>{throw new X(Q)};class G2 extends Error{name="ParseError"}var H=(Q)=>P1(Q,G2),X1=(Q)=>` ${Q}`,eQ="";var V=(Q,X)=>{let Y={},U=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let _=U?X(W,G[1]):X(...G,W);Z||=typeof _[0]==="number";let L=Array.isArray(_[0])||_.length===0?_:[_];for(let[J,A]of L)if(typeof J==="object")Y[J.group]=D(Y[J.group],A);else Y[J]=A}return Z?Object.values(Y):Y};var C6=Object.entries;var y=(Q,X)=>(Q in X),k1=(Q,X)=>(X in Q);class w6{constructor(Q){Object.assign(this,Q)}}var Q4=class{};class _2 extends Q4{}var VU=(Q,X)=>{let Y={},U={},Z;for(Z in Q)if(Z in X)Y[Z]=Q[Z];else U[Z]=Q[Z];return[Y,U]};var x2=(Q,X)=>VU(Q,X)[1],J1=(Q)=>Object.keys(Q).length===0,N1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],X4=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),Y4=(Q)=>{let X=Object.keys(Q).sort(),Y={};for(let U=0;U<X.length;U++)Y[X[U]]=Q[X[U]];return Y};var l=X1(`unset${eQ}`),U4=(Q)=>Object.values(Q).filter((X)=>{if(typeof X==="number")return!0;return typeof Q[X]!=="number"});var K6={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},P6=globalThis.File??Blob,N6={ArrayBuffer,Blob,File:P6,FormData,Headers,Request,Response,URL},BU={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I1={...K6,...N6,...BU,String,Number,Boolean},J2=(Q)=>{let X=Object.getPrototypeOf(Q);while(X?.constructor&&(!y(X.constructor.name,I1)||!(Q instanceof I1[X.constructor.name])))X=Object.getPrototypeOf(X);let Y=X?.constructor?.name;if(Y===void 0||Y==="Object")return;return Y},L2=(Q)=>typeof Q==="object"&&Q!==null?J2(Q)??"object":b(Q);var K=Array.isArray,MU={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},TU={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},DU={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},Z4={...MU,...TU,...DU},H2=(Q)=>{let X=Object(Q).name??null;return X&&y(X,I1)&&I1[X]===Q?X:null};var I6=(Q,X)=>{let Y=Q.prototype;while(Y!==null){if(Y===X.prototype)return!0;Y=Object.getPrototypeOf(Y)}return!1};var W4=(Q)=>G4(Q,new Map),G4=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let Y=H2(Q.constructor);if(Y==="Date")return new Date(Q.getTime());if(Y&&Y!=="Array")return Q;let U=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),Z=Object.getOwnPropertyDescriptors(Q);if(X){X.set(Q,U);for(let W in Z){let G=Z[W];if("get"in G||"set"in G)continue;G.value=G4(G.value,X)}}return Object.defineProperties(U,Z),U};var RU=(Q)=>{let X=l;return()=>X===l?X=Q():X},M1=(Q)=>typeof Q==="function"&&Q.length===0;var _4=class extends Function{constructor(...Q){let X=Q.slice(0,-1),Y=Q[Q.length-1];try{super(...X,Y)}catch(U){return C(`Encountered an unexpected error while compiling your definition:
|
|
2
2
|
Message: ${U}
|
|
3
3
|
Source: (${Q.slice(0,-1)}) => {
|
|
4
4
|
${Q[Q.length-1]}
|
|
5
|
-
}`)}}};class
|
|
6
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
5
|
+
}`)}}};class d{constructor(Q,...[X]){return Object.assign(Object.setPrototypeOf(Q.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var J4=RU(()=>{try{return Function("return false")()}catch{return!0}});var P0=X1("brand");var L4=X1("arkInferred");var E0=X1("args");class g{constructor(){}}var CU=()=>{try{return((Error().stack?.split(`
|
|
6
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},wU=globalThis.process?.env??{},H4={fileName:CU,env:wU};var F4=(Q)=>Q[0].toUpperCase()+Q.slice(1),q4=(Q)=>Q[0].toLowerCase()+Q.slice(1),E6=(Q)=>new RegExp(KU(Q),typeof Q==="string"?"":Q.flags);var KU=(Q)=>{return`^(?:${typeof Q==="string"?Q:Q.source})$`};var $1={negativeLookahead:(Q)=>`(?!${Q})`,nonCapturingGroup:(Q)=>`(?:${Q})`},E1="\\",T1={" ":1,"\n":1,"\t":1};var PU=/^-0\.?0*$/.source,$4=/[1-9]\d*/.source,NU=/\.\d+/.source,IU=/\.\d*[1-9]/.source,z4=(Q)=>E6($1.negativeLookahead(PU)+$1.nonCapturingGroup("-?"+$1.nonCapturingGroup($1.nonCapturingGroup("0|"+$4)+$1.nonCapturingGroup(Q.decimalPattern)+"?")+(Q.allowDecimalOnly?"|"+Q.decimalPattern:"")+"?")),A4=z4({decimalPattern:IU,allowDecimalOnly:!1}),EU=A4.test.bind(A4),h2=z4({decimalPattern:NU,allowDecimalOnly:!0}),k0=h2.test.bind(h2),SU=/^-?\d*\.?\d*$/,jU=(Q)=>Q.length!==0&&SU.test(Q),F2=E6($1.negativeLookahead("^-0$")+"-?"+$1.nonCapturingGroup($1.nonCapturingGroup("0|"+$4))),fU=F2.test.bind(F2),S6=/^-?\d+$/,bU=S6.test.bind(S6),O4={number:"a number",bigint:"a bigint",integer:"an integer"},V4=(Q,X)=>`'${Q}' was parsed as ${O4[X]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,yU=(Q,X)=>X==="number"?EU(Q):fU(Q),vU=(Q,X)=>X==="number"?Number(Q):Number.parseInt(Q),kU=(Q,X)=>X==="number"?jU(Q):bU(Q),B4=(Q,X)=>j6(Q,"number",X),M4=(Q,X)=>j6(Q,"number",{...X,strict:!0}),T4=(Q,X)=>j6(Q,"integer",X),j6=(Q,X,Y)=>{let U=vU(Q,X);if(!Number.isNaN(U)){if(kU(Q,X)){if(Y?.strict)return yU(Q,X)?U:H(V4(Q,X));return U}}return Y?.errorOnFail?H(Y?.errorOnFail===!0?`Failed to parse ${O4[X]} from '${Q}'`:Y?.errorOnFail):void 0},D4=(Q)=>{if(Q[Q.length-1]!=="n")return;let X=Q.slice(0,-1),Y;try{Y=BigInt(X)}catch{return}if(F2.test(X))return Y;if(S6.test(X))return H(V4(Q,"bigint"))};var gU="0.56.0",xU={version:gU,filename:H4.fileName(),FileConstructor:P6},S1=xU,R4=new Map,f6=Object.create(null),q2=(Q)=>{let X=R4.get(Q);if(X)return X;let Y=hU(Q);if(f6[Y])Y=`${Y}${f6[Y]++}`;else f6[Y]=1;return S1[Y]=Q,R4.set(Q,Y),Y},D1=(Q)=>/^[$A-Z_a-z][\w$]*$/.test(Q),hU=(Q)=>{switch(typeof Q){case"object":{if(Q===null)break;let X=J2(Q)??"object";return X[0].toLowerCase()+X.slice(1)}case"function":return D1(Q.name)?Q.name:"fn";case"symbol":return Q.description&&D1(Q.description)?Q.description:"symbol"}return C(`Unexpected attempt to register serializable value of type ${b(Q)}`)};var A2=(Q)=>typeof Q==="string"?JSON.stringify(Q):typeof Q==="bigint"?`${Q}n`:`${Q}`;var C4=(Q,X={})=>$2(Q,{onUndefined:"$ark.undefined",onBigInt:(Y)=>`$ark.bigint-${Y}`,...X},[]);var B=(Q,X)=>{switch(b(Q)){case"object":let Y=Q,U=Y.constructor?.name??"Object";return U==="Object"||U==="Array"?X?.quoteKeys===!1?p2(Y,X?.indent??0,""):JSON.stringify($2(Y,g1,[]),null,X?.indent):p2(Y,X?.indent??0,"");case"symbol":return g1.onSymbol(Q);default:return A2(Q)}},p2=(Q,X,Y)=>{if(typeof Q==="function")return g1.onFunction(Q);if(typeof Q!=="object"||Q===null)return A2(Q);let U=Y+" ".repeat(X);if(Array.isArray(Q)){if(Q.length===0)return"[]";let W=Q.map((G)=>p2(G,X,U)).join(`,
|
|
7
7
|
`+U);return X?`[
|
|
8
8
|
${U}${W}
|
|
9
|
-
${Y}]`:`[${W}]`}let Z=Q.constructor?.name??"Object";if(Z==="Object"){let W=N1(Q).map(([G,_])=>{let
|
|
9
|
+
${Y}]`:`[${W}]`}let Z=Q.constructor?.name??"Object";if(Z==="Object"){let W=N1(Q).map(([G,_])=>{let L=typeof G==="symbol"?g1.onSymbol(G):D1(G)?G:JSON.stringify(G),J=p2(_,X,U);return`${U}${L}: ${J}`});if(W.length===0)return"{}";return X?`{
|
|
10
10
|
${W.join(`,
|
|
11
11
|
`)}
|
|
12
|
-
${Y}}`:`{${W.join(", ")}}`}if(Q instanceof Date)return j1(Q);if("expression"in Q&&typeof Q.expression==="string")return Q.expression;return Z},g1={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${q2(Q)})`,onFunction:(Q)=>`Function(${q2(Q)})`}
|
|
12
|
+
${Y}}`:`{${W.join(", ")}}`}if(Q instanceof Date)return j1(Q);if("expression"in Q&&typeof Q.expression==="string")return Q.expression;return Z},g1={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${q2(Q)})`,onFunction:(Q)=>`Function(${q2(Q)})`},$2=(Q,X,Y)=>{switch(b(Q)){case"object":{let U=Q;if("toJSON"in U&&typeof U.toJSON==="function")return U.toJSON();if(typeof U==="function")return g1.onFunction(U);if(Y.includes(U))return"(cycle)";let Z=[...Y,U];if(Array.isArray(U))return U.map((G)=>$2(G,X,Z));if(U instanceof Date)return U.toDateString();let W={};for(let G in U)W[G]=$2(U[G],X,Z);for(let G of Object.getOwnPropertySymbols(U))W[X.onSymbol?.(G)??G.toString()]=$2(U[G],X,Z);return W}case"symbol":return g1.onSymbol(Q);case"bigint":return X.onBigInt?.(Q)??`${Q}n`;case"undefined":return X.onUndefined??"undefined";case"string":return Q.replace(/\\/g,"\\\\");default:return Q}},j1=(Q)=>{let X=Q.getFullYear(),Y=Q.getMonth(),U=Q.getDate(),Z=Q.getHours(),W=Q.getMinutes(),G=Q.getSeconds(),_=Q.getMilliseconds();if(Y===0&&U===1&&Z===0&&W===0&&G===0&&_===0)return`${X}`;let L=`${pU[Y]} ${U}, ${X}`;if(Z===0&&W===0&&G===0&&_===0)return L;let J=Q.toLocaleTimeString(),A=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(A)J=J.slice(0,-A.length);if(_)J+=`.${mU(_,3)}`;else if(uU.test(J))J=J.slice(0,-3);return`${J+A}, ${L}`},pU=["January","February","March","April","May","June","July","August","September","October","November","December"],uU=/:\d\d:00$/,mU=(Q,X)=>String(Q).padStart(X,"0");var w4=(Q,X,...[Y])=>{let U=Y?.stringifySymbol??B,Z=Q;switch(typeof X){case"string":Z=D1(X)?Q===""?X:`${Q}.${X}`:`${Q}[${JSON.stringify(X)}]`;break;case"number":Z=`${Q}[${X}]`;break;case"symbol":Z=`${Q}[${U(X)}]`;break;default:if(Y?.stringifyNonKey)Z=`${Q}[${Y.stringifyNonKey(X)}]`;else H(`${B(X)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return Z},z1=(Q,...X)=>Q.reduce((Y,U)=>w4(Y,U,...X),"");class z2 extends g2{cache={};constructor(...Q){super();this.push(...Q)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Q=0;Q<this.length;Q++)this.cache.json.push(typeof this[Q]==="symbol"?B(this[Q]):this[Q]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=z1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Q="",X=[Q];for(let Y of this)Q=w4(Q,Y),X.push(Q);return this.cache.stringifyAncestors=X}}class O2{chars;i;def;constructor(Q){this.def=Q,this.chars=[...Q],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(Q){let X="";while(this.lookahead)if(Q(this,X))break;else X+=this.shift();return X}shiftUntilEscapable(Q){let X="";while(this.lookahead)if(this.lookahead===E1)if(this.shift(),Q(this,X))X+=this.shift();else if(this.lookahead===E1)X+=this.shift();else X+=`${E1}${this.shift()}`;else if(Q(this,X))break;else X+=this.shift();return X}shiftUntilLookahead(Q){return typeof Q==="string"?this.shiftUntil((X)=>X.lookahead===Q):this.shiftUntil((X)=>(X.lookahead in Q))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in T1))}jumpToIndex(Q){this.i=Q<0?this.length+Q:Q}jumpForward(Q){this.i+=Q}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(Q,X){return this.chars.slice(Q,X).join("")}lookaheadIs(Q){return this.lookahead===Q}lookaheadIsIn(Q){return this.lookahead in Q}}var K4=(Q,X)=>`Unmatched ${Q}${X===""?"":` before ${X}`}`,u2=(Q)=>`Missing ${Q}`;var _W=X1("implementedTraits");var b6="$ark",lU=2;while(b6 in globalThis)b6=`$ark${lU++}`;var P4=b6;globalThis[P4]=S1;var F=S1,dU=(Q)=>`${P4}.${Q}`,S=(Q)=>dU(q2(Q));class m2 extends _2{argNames;body="";constructor(...Q){super();this.argNames=Q;for(let X of Q){if(X in this)throw Error(`Arg name '${X}' would overwrite an existing property on FunctionBody`);this[X]=X}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Q,X=!1){return y6(Q,X)}index(Q,X=!1){return N4(`${Q}`,X)}line(Q){return this.body+=`${" ".repeat(this.indentation)}${Q}
|
|
13
13
|
`,this}const(Q,X){return this.line(`const ${Q} = ${X}`),this}let(Q,X){return this.line(`let ${Q} = ${X}`)}set(Q,X){return this.line(`${Q} = ${X}`)}if(Q,X){return this.block(`if (${Q})`,X)}elseIf(Q,X){return this.block(`else if (${Q})`,X)}else(Q){return this.block("else",Q)}for(Q,X,Y=0){return this.block(`for (let i = ${Y}; ${Q}; i++)`,X)}forIn(Q,X){return this.block(`for (const k in ${Q})`,X)}block(Q,X,Y=""){return this.line(`${Q} {`),this.indent(),X(this),this.dedent(),this.line(`}${Y}`)}return(Q=""){return this.line(`return ${Q}`)}write(Q="anonymous",X=0){return`${Q}(${this.argNames.join(", ")}) { ${X?this.body.split(`
|
|
14
14
|
`).map((Y)=>" ".repeat(X)+`${Y}`).join(`
|
|
15
|
-
`):this.body} }`}compile(){return new
|
|
16
|
-
`)}addAncestorPaths(Q){for(let X of Q.path.stringifyAncestors())this.byAncestorPath[X]=D(this.byAncestorPath[X],Q)}}class
|
|
17
|
-
`+Q.map((X)=>` • ${
|
|
18
|
-
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var
|
|
15
|
+
`):this.body} }`}compile(){return new _4(...this.argNames,this.body)}}var Y1=(Q)=>u(Q,"object")||typeof Q==="symbol"?S(Q):A2(Q),y6=(Q,X=!1)=>{if(typeof Q==="string"&&D1(Q))return`${X?"?":""}.${Q}`;return N4(cU(Q),X)},cU=(Q)=>typeof Q==="symbol"?S(Q):JSON.stringify(Q),N4=(Q,X=!1)=>`${X?"?.":""}[${Q}]`;class V2 extends m2{traversalKind;optimistic;constructor(Q){super("data","ctx");this.traversalKind=Q.kind,this.optimistic=Q.optimistic===!0}invoke(Q,X){let Y=X?.arg??this.data,U=typeof Q==="string"?!0:this.requiresContextFor(Q),Z=typeof Q==="string"?Q:Q.id;if(U)return`${this.referenceToId(Z,X)}(${Y}, ${this.ctx})`;return`${this.referenceToId(Z,X)}(${Y})`}referenceToId(Q,X){let Y=X?.kind??this.traversalKind,U=`this.${Q}${Y}`;return X?.bind?`${U}.bind(${X?.bind})`:U}requiresContextFor(Q){return this.traversalKind==="Apply"||Q.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(Q,X,Y){let U=this.requiresContextFor(Y);if(U)this.line(`${this.ctx}.path.push(${Q})`);if(this.check(Y,{arg:X}),U)this.line(`${this.ctx}.path.pop()`);return this}check(Q,X){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Q,X)}`,()=>this.return(!1)):this.line(this.invoke(Q,X))}}var l2=(Q)=>V(Q,(X,Y)=>[X,K(Y)?[...Y]:Y]),h=X1("arkKind"),$=(Q,X)=>Q?.[h]===X,P=(Q)=>$(Q,"root")||$(Q,"constraint");var I4=["unit","proto","domain"],x1=["required","optional","index","sequence"],v6=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],k6=[...v6,"structure","predicate"],d2=[...k6,...x1],h1=["alias","union","morph","unit","intersection","proto","domain"],oU=[...h1,...d2],c2=V(d2,(Q,X)=>[X,1]),E4=V([...x1,"undeclared"],(Q,X)=>[X,1]),S4=V(oU,(Q,X)=>[X,Q]),p1=(Q)=>typeof Q==="string"&&(Q in S4);var u1=(Q)=>S4[Q],o2=(Q)=>h1.slice(u1(Q)+1),dW=[...o2("union"),"alias"],cW=[...o2("morph"),"alias"],r=(Q)=>{if(typeof Q==="string"||typeof Q==="boolean"||Q===null)return Q;if(typeof Q==="number"){if(Number.isNaN(Q))return"NaN";if(Q===Number.POSITIVE_INFINITY)return"Infinity";if(Q===Number.NEGATIVE_INFINITY)return"-Infinity";return Q}return Y1(Q)},R1=(Q)=>{let X="{ ";for(let[Y,U]of Object.entries(Q))X+=`${Y}: ${Y1(U)}, `;return X+" }"},M=(Q)=>{let X=Q;if(X.hasAssociatedError)X.defaults.expected??=(Y)=>("description"in Y)?Y.description:X.defaults.description(Y),X.defaults.actual??=(Y)=>B(Y),X.defaults.problem??=(Y)=>`must be ${Y.expected}${Y.actual?` (was ${Y.actual})`:""}`,X.defaults.message??=(Y)=>{if(Y.path.length===0)return Y.problem;let U=`${Y.propString} ${Y.problem}`;if(U[0]==="[")return`value at ${U}`;return U};return X};class j4 extends Error{name="ToJsonSchemaError";code;context;constructor(Q,X){super(B(X,{quoteKeys:!1,indent:4}));this.code=Q,this.context=X}hasCode(Q){return this.code===Q}}var iU={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Q)=>I.throw("arrayObject",Q),arrayPostfix:(Q)=>I.throw("arrayPostfix",Q),defaultValue:(Q)=>I.throw("defaultValue",Q),domain:(Q)=>I.throw("domain",Q),morph:(Q)=>I.throw("morph",Q),patternIntersection:(Q)=>I.throw("patternIntersection",Q),predicate:(Q)=>I.throw("predicate",Q),proto:(Q)=>I.throw("proto",Q),symbolKey:(Q)=>I.throw("symbolKey",Q),unit:(Q)=>I.throw("unit",Q),date:(Q)=>I.throw("date",Q)}},I={Error:j4,throw:(...Q)=>{throw new I.Error(...Q)},throwInternalOperandError:(Q,X)=>C(`Unexpected JSON Schema input for ${Q}: ${B(X)}`),defaultConfig:iU};F.config??={};var B2=(Q,X)=>{if(!X)return Q;let Y={...Q},U;for(U in X){let Z={...Q.keywords};if(U==="keywords"){for(let W in X[U]){let G=X.keywords[W];if(G===void 0)continue;Z[W]=typeof G==="string"?{description:G}:G}Y.keywords=Z}else if(U==="toJsonSchema")Y[U]=g6(Q.toJsonSchema,X.toJsonSchema);else if(p1(U))Y[U]={...Q[U],...X[U]};else Y[U]=X[U]}return Y},sU={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},g6=(Q,X)=>{if(!Q)return f4(X??{},void 0);if(!X)return Q;let Y={...Q},U;for(U in X)if(U==="fallback")Y.fallback=nU(Q.fallback,X.fallback);else Y[U]=X[U];return f4(Y,X)},f4=(Q,X)=>{if(X?.dialect!==void 0)return Q;if(X?.target!==void 0)return{...Q,dialect:sU[X.target]};return Q},nU=(Q,X)=>{Q=b4(Q),X=b4(X);let Y={},U;for(U in I.defaultConfig.fallback)Y[U]=X[U]??X.default??Q[U]??Q.default??I.defaultConfig.fallback[U];return Y},b4=(Q)=>typeof Q==="function"?{default:Q}:Q??{};class C1 extends _2{[h]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Q,relativePath:X,...Y},U){super();this.input=Y,this.ctx=U,X4(this,Y);let Z=U.data;if(Y.code==="union")Y.errors=Y.errors.flatMap((G)=>{let _=G.hasCode("union")?G.errors:[G];if(!Q&&!X)return _;return _.map((L)=>L.transform((J)=>({...J,path:nQ(Q,J.path,X)})))});this.nodeConfig=U.config[this.code];let W=[...Y.path??U.path];if(X)W.push(...X);if(Q)W.unshift(...Q);this.path=new z2(...W),this.data="data"in Y?Y.data:Z}transform(Q){return new C1(Q({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Q){return this.code===Q}get propString(){return z1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Q=this.meta?.expected??this.nodeConfig.expected;return typeof Q==="function"?Q(this.input):Q}get actual(){if(this.input.actual)return this.input.actual;let Q=this.meta?.actual??this.nodeConfig.actual;return typeof Q==="function"?Q(this.data):Q}get problem(){if(this.input.problem)return this.input.problem;let Q=this.meta?.problem??this.nodeConfig.problem;return typeof Q==="function"?Q(this):Q}get message(){if(this.input.message)return this.input.message;let Q=this.meta?.message??this.nodeConfig.message;return typeof Q==="function"?Q(this):Q}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class c extends g2{[h]="errors";ctx;constructor(Q){super();this.ctx=Q}byPath=Object.create(null);get flatByPath(){return V(this.byPath,(Q,X)=>[Q,X.flat])}get flatProblemsByPath(){return V(this.byPath,(Q,X)=>[Q,X.flat.map((Y)=>Y.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new x6(this)}add(Q){let X=this.byPath[Q.propString];if(X){if(Q===X)return;if(X.hasCode("union")&&X.errors.length===0)return;let Y=Q.hasCode("union")&&Q.errors.length===0?Q:new C1({code:"intersection",errors:X.hasCode("intersection")?[...X.errors,Q]:[X,Q]},this.ctx),U=this.indexOf(X);this.mutable[U===-1?this.length:U]=Y,this.byPath[Q.propString]=Y,this.addAncestorPaths(Q)}else this.byPath[Q.propString]=Q,this.addAncestorPaths(Q),this.mutable.push(Q);this.count++}transform(Q){let X=new c(this.ctx);for(let Y of this)X.add(Q(Y));return X}merge(Q){for(let X of Q)this.add(new C1({...X,path:[...this.ctx.path,...X.path]},this.ctx))}affectsPath(Q){if(this.length===0)return!1;return Q.stringifyAncestors().some((X)=>(X in this.byPath))||Q.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Q)=>Q.toJSON())]}toString(){return this.join(`
|
|
16
|
+
`)}addAncestorPaths(Q){for(let X of Q.path.stringifyAncestors())this.byAncestorPath[X]=D(this.byAncestorPath[X],Q)}}class x6 extends Error{name="TraversalError";constructor(Q){if(Q.length===1)super(Q.summary);else super(`
|
|
17
|
+
`+Q.map((X)=>` • ${rU(X)}`).join(`
|
|
18
|
+
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var rU=(Q)=>Q.toString().split(`
|
|
19
19
|
`).join(`
|
|
20
|
-
`);class U1{path=[];errors=new d(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Q,X){this.root=Q,this.config=X}get data(){let Q=this.root;for(let X of this.path)Q=Q?.[X];return Q}get propString(){return z1(this.path)}reject(Q){return this.error(Q),!1}mustBe(Q){return this.error(Q),!1}error(Q){let X=typeof Q==="object"?Q.code?Q:{...Q,code:"predicate"}:{code:"predicate",expected:Q};return this.errorFromContext(X)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Q){let X={path:new z2(...this.path),morphs:Q};if(this.currentBranch)this.currentBranch.queuedMorphs.push(X);else this.queuedMorphs.push(X)}finalize(Q){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Q?Q(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Q){return this.errorFromContext(Q)}errorFromContext(Q){let X=new C1(Q,this);if(this.currentBranch)this.currentBranch.error=X;else this.errors.add(X);return X}applyQueuedMorphs(){while(this.queuedMorphs.length){let Q=this.queuedMorphs;this.queuedMorphs=[];for(let{path:X,morphs:Y}of Q){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,Y)}}}applyMorphsAtPath(Q,X){let Y=Q[Q.length-1],U;if(Y!==void 0){U=this.root;for(let Z=0;Z<Q.length-1;Z++)U=U[Q[Z]]}for(let Z of X){this.path=[...Q];let W=P(Z),G=Z(U===void 0?this.root:U[Y],this);if(G instanceof C1){if(!this.errors.includes(G))this.errors.add(G);break}if(G instanceof d){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(U===void 0)this.root=G;else U[Y]=G;this.applyQueuedMorphs()}}}var c=(Q,X,Y)=>{if(!Y)return X();Y.path.push(Q);let U=X();return Y.path.pop(),U};class T2 extends l{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Q,X){super((U,Z,W=this.onFail)=>{if(Z)return this.traverseApply(U,Z),Z.hasError()?Z.errors:Z.data;return this.rootApply(U,W)},{attach:Q});this.attachments=Q,this.$=X,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((U,Z)=>sU(U,Z.shallowReferences),[this]);let Y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let U=0;U<this.children.length;U++){if(this.includesTransform||=this.children[U].includesTransform,this.includesContextualPredicate||=this.children[U].includesContextualPredicate,this.isCyclic||=this.children[U].isCyclic,!Y){let Z=this.children[U].flatRefs;for(let W=0;W<Z.length;W++){let G=Z[W];if(!this.flatRefs.some((_)=>S4(_,G))){this.flatRefs.push(G);for(let _ of G.node.branches)if(_.hasKind("morph")||_.hasKind("intersection")&&_.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:_})}}}Object.assign(this.referencesById,this.children[U].referencesById)}this.flatRefs.sort((U,Z)=>U.path.length>Z.path.length?1:U.path.length<Z.path.length?-1:U.propString>Z.propString?1:U.propString<Z.propString?-1:U.node.expression<Z.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((U)=>U.length===1||U.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((U)=>U.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(U)=>this.traverseAllows(U,new U1(U,this.$.resolvedConfig)):(U)=>this.traverseAllows(U)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,Y)=>{if(this.allows(X))return X;let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"contextual":return(X,Y)=>{let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Q=this.$.resolvedConfig.clone;return(X,Y)=>{if(this.allows(X))return this.contextFreeMorph(Q&&(typeof X==="object"&&X!==null||typeof X==="function")?Q(X):X);let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,C(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=iU(this.metaJson);cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=u1(this.kind);precompilation;assert=(Q,X)=>this(Q,X,(Y)=>Y.throw());traverse(Q,X){return this(Q,X,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(Q){if(!this.includesTransform)return this;let X={};for(let[Y,U]of this.innerEntries){let Z=this.impl.keys[Y];if(Z.reduceIo)Z.reduceIo(Q,X,U);else if(Z.child){let W=U;X[Y]=K(W)?W.map((G)=>Q==="in"?G.rawIn:G.rawOut):Q==="in"?W.rawIn:W.rawOut}else X[Y]=U}return this.$.node(this.kind,X)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Q){let X=P(Q)?Q:this.$.parseDefinition(Q);return this.innerHash===X.innerHash}ifEquals(Q){return this.equals(Q)?this:void 0}hasKind(Q){return this.kind===Q}assertHasKind(Q){if(this.kind!==Q)P1(`${this.kind} node was not of asserted kind ${Q}`);return this}hasKindIn(...Q){return Q.includes(this.kind)}assertHasKindIn(...Q){if(!n(Q,this.kind))P1(`${this.kind} node was not one of asserted kinds ${Q}`);return this}isBasis(){return n(C4,this.kind)}isConstraint(){return n(d2,this.kind)}isStructural(){return n(x1,this.kind)}isRefinement(){return n(f6,this.kind)}isRoot(){return n(h1,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Q){return this.hasKind("unit")&&this.allows(Q)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Q){let X=M2.normalize(Q);return this._select(X)}_select(Q){let X=M2.applyBoundary[Q.boundary??"references"](this);if(Q.kind)X=X.filter((Y)=>Y.kind===Q.kind);if(Q.where)X=X.filter(Q.where);return M2.applyMethod[Q.method??"filter"](X,this,Q)}transform(Q,X){return this._transform(Q,this._createTransformContext(X))}_createTransformContext(Q){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Q?.prereduced??!1},undeclaredKeyHandling:void 0,...Q}}_transform(Q,X){let Y=X.bindScope??this.$;if(X.seen[this.id])return this.$.lazilyResolve(X.seen[this.id]);if(X.shouldTransform?.(this,X)===!1)return this;let U;if(X.seen[this.id]=()=>U,this.hasKind("structure")&&this.undeclared!==X.undeclaredKeyHandling)X={...X,undeclaredKeyHandling:this.undeclared};let Z=V(this.inner,(J,$)=>{if(!this.impl.keys[J].child)return[J,$];let O=$;if(!K(O)){let b=O._transform(Q,X);return b?[J,b]:[]}if(O.length===0)return[J,$];let R=O.flatMap((b)=>{return b._transform(Q,X)??[]});return R.length?[J,R]:[]});delete X.seen[this.id];let W=Object.assign(Z,{meta:this.meta}),G=X.selected&&!X.selected.includes(this)?W:Q(this.kind,W,X);if(G===null)return null;if(P(G))return U=G;let _=Object.keys(G);if((_.length===0||_.length===1&&_[0]==="meta")&&!J1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in G))return X.undeclaredKeyHandling?{...G,value:F.intrinsic.unknown}:null;if(this.kind==="morph")G.in??=F.intrinsic.unknown;return U=Y.node(this.kind,G,X.parseOptions)}configureReferences(Q,X="references"){let Y=M2.normalize(X),U=typeof Q==="string"?(_,H)=>({...H,meta:{...H.meta,description:Q}}):typeof Q==="function"?(_,H)=>({...H,meta:Q(H.meta)}):(_,H)=>({...H,meta:{...H.meta,...Q}});if(Y.boundary==="self")return this.$.node(this.kind,U(this.kind,{...this.inner,meta:this.meta}));let Z=this._select(Y),W=Z&&B1(Z),G=Y.boundary==="child"?(_,H)=>H.root.children.includes(_):Y.boundary==="shallow"?(_)=>_.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:G,selected:W}))}}var M2={applyBoundary:{self:(Q)=>[Q],child:(Q)=>[...Q.children],shallow:(Q)=>[...Q.shallowReferences],references:(Q)=>[...Q.references]},applyMethod:{filter:(Q)=>Q,assertFilter:(Q,X,Y)=>{if(Q.length===0)P1(I4(X,Y));return Q},find:(Q)=>Q[0],assertFind:(Q,X,Y)=>{if(Q.length===0)P1(I4(X,Y));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?f(Q,M2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},I4=(Q,X)=>`${Q} had no references matching ${B(X)}.`,cU=(Q)=>z1(Q,{stringifyNonKey:(X)=>X.expression}),oU=/"(\$ark\.[^"]+)"/g,iU=(Q)=>JSON.stringify(Q).replace(oU,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:cU(Q)}),S4=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),g6=(Q,X)=>_1(Q,X,{isEqual:S4}),sU=(Q,X)=>_1(Q,X,{isEqual:(Y,U)=>Y.equals(U)});class q extends Array{static init(Q,X,Y,U){return new q({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1})}add(Q,X,Y,U){return this.push({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Q,l:X,r:Y}=this[0],U=z1(Q);return h6(`Intersection${U&&` at ${U}`} of ${j4(X,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
-
• ${this.map(({path:Q,l:X,r:Y})=>`${Q}: ${
|
|
22
|
-
• `)}`}throw(){return L(this.describeReasons())}invert(){let Q=this.map((X)=>({...X,l:X.r,r:X.l}));if(!(Q instanceof q))return new q(...Q);return Q}withPrefixKey(Q,X){return this.map((Y)=>({...Y,path:[Q,...Y.path],optional:Y.optional||X==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var j4=(Q,X)=>`${x6(Q)} and ${x6(X)}`,x6=(Q)=>P(Q)?Q.expression:K(Q)?Q.map(x6).join(" | ")||"never":String(Q),h6=(Q)=>`${Q} results in an unsatisfiable type`;var m1={},o=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!1}),D2=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!0}),N=(Q,X,Y)=>{let U=Y.pipe?"|>":"&",Z=`${Q.hash}${U}${X.hash}`;if(m1[Z]!==void 0)return m1[Z];if(!Y.pipe){let _=`${X.hash}${U}${Q.hash}`;if(m1[_]!==void 0){let H=m1[_],J=H instanceof q?H.invert():H;return m1[Z]=J,J}}let W=!Y.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?p6(Q,X,Y):Q.hasKindIn(...h1)?nU(Q,X,Y):p6(Q,X,Y);if(P(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return m1[Z]=G,G},p6=(Q,X,Y)=>{let U=Q.precedence<X.precedence?Q.kind:X.kind,Z=Q.impl.intersections[X.kind]??X.impl.intersections[Q.kind];if(Z===void 0)return null;else if(U===Q.kind)return Z(Q,X,Y);else{let W=Z(X,Q,{...Y,invert:!Y.invert});if(W instanceof q)W=W.invert();return W}},nU=(Q,X,Y)=>Q.includesTransform||X.includesTransform?Y.invert?b4(X,Q,Y):b4(Q,X,Y):p6(Q,X,Y),b4=(Q,X,Y)=>Q.distribute((U)=>rU(U,X,Y),(U)=>{let Z=U.filter(P);if(Z.length===0)return q.init("union",Q.branches,X.branches);if(Z.length<Q.branches.length||!Q.branches.every((_,H)=>_.rawIn.equals(Z[H].rawIn)))return Y.$.parseSchema(Z);let W;if(Z.length===1){let _=Z[0];if(!W)return _;return Y.$.node("morph",{..._.inner,in:_.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return Y.$.parseSchema(G)}),rU=(Q,X,Y)=>{if(Q.hasKind("morph")){let Z=[...Q.morphs];if(Q.lastMorphIfNode){let W=N(Q.lastMorphIfNode,X,Y);if(W instanceof q)return W;Z[Z.length-1]=W}else Z.push(X);return Y.$.node("morph",{morphs:Z,in:Q.inner.in})}if(X.hasKind("morph")){let Z=N(Q,X.rawIn,Y);if(Z instanceof q)return Z;return Y.$.node("morph",{morphs:[X],in:Z})}return Y.$.node("morph",{morphs:[X],in:Q})};class t extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return o(this,Q,this.$)}}class O1 extends t{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}}var g=(Q)=>(X,Y)=>{if(K(X)){if(X.length===0)return;let Z=X.map((W)=>Y.$.node(Q,W));if(Q==="predicate")return Z;return Z.sort((W,G)=>W.hash<G.hash?-1:1)}let U=Y.$.node(Q,X);return U.hasOpenIntersection()?[U]:U},l1=(Q)=>{let X=Q.r.shift();if(!X){let U=Q.l.length===0&&Q.kind==="structure"?F.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,tU(Q.l)),{prereduced:!0});for(let Z of Q.roots){if(U instanceof q)return U;U=N(Z,U,Q.ctx)}return U}let Y=!1;for(let U=0;U<Q.l.length;U++){let Z=N(Q.l[U],X,Q.ctx);if(Z===null)continue;if(Z instanceof q)return Z;if(Z.isRoot())return Q.roots.push(Z),Q.l.splice(U),l1(Q);if(!Y)Q.l[U]=Z,Y=!0;else if(!Q.l.includes(Z))return C(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!Y)Q.l.push(X);if(Q.kind==="intersection"){if(X.impliedSiblings)for(let U of X.impliedSiblings)_1(Q.r,U)}return l1(Q)},d1=(Q)=>{return Object.entries(Q).flatMap(([Y,U])=>(Y in c2)?U:[]).sort((Y,U)=>Y.precedence<U.precedence?-1:Y.precedence>U.precedence?1:Y.kind==="predicate"&&U.kind==="predicate"?0:Y.hash<U.hash?-1:1)},tU=(Q)=>{let X={};for(let Y of Q)if(Y.hasOpenIntersection())X[Y.kind]=D(X[Y.kind],Y);else{if(X[Y.kind])return C(`Unexpected intersection of closed refinements of kind ${Y.kind}`);X[Y.kind]=Y}return X},y4=(...Q)=>L(f4(...Q)),f4=(Q,X,Y)=>{let U=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude(X).defaultShortDescription;return`${G4(Q)} operand must be ${X.description} (was ${U})`};var v4=(Q,X,Y)=>new w1(Q,X,Y,Y,null);class i2 extends l{}class w1 extends l{[x]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,Y,U,Z){super((...W)=>{let G=V(this.names,(_,H)=>{let J=this.arg$.parse(W[_]);if(!J.extends(this.constraints[_]))L(aU(H,this.constraints[_].expression,J.expression));return[H,J]});if(this.defIsLazy()){let _=this.bodyDef(G);return this.$.parse(_)}return this.$.parse(X,{args:G})});this.paramDefs=Q,this.bodyDef=X,this.$=Y,this.arg$=U,this.hkt=Z,this.description=Z?new Z().description??`a generic type for ${Z.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i2}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get json(){return this.cacheGetter("json",{params:this.params.map((Q)=>Q[1].isUnknown()?Q[0]:[Q[0],Q[1].json]),body:B4(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Q)=>typeof Q==="string"?[Q,F.intrinsic.unknown]:[Q[0],this.$.parse(Q[1])]))}get names(){return this.cacheGetter("names",this.params.map((Q)=>Q[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Q)=>Q[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var aU=(Q,X,Y)=>`${Q} must be assignable to ${X} (was ${Y})`;var eU=M({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Q)=>typeof Q==="function"?{predicate:Q}:Q,defaults:{description:(Q)=>`valid according to ${Q.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class k4 extends t{serializedPredicate=S(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=R1(this.errorContext);traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(!this.predicate(Q,X.external)&&X.currentErrorCount===Y)X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows"){Q.return(this.compiledCondition);return}Q.initializeErrorCount(),Q.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Q,X){return X.fallback.predicate({code:"predicate",base:Q,predicate:this.predicate})}}var u6={implementation:eU,Node:k4};var QZ=M({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:L(XZ(Q))}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>Q.rule===1?"an integer":Q.rule===2?"even":`a multiple of ${Q.rule}`},intersections:{divisor:(Q,X,Y)=>Y.$.node("divisor",{rule:Math.abs(Q.rule*X.rule/YZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class g4 extends O1{traverseAllows=(Q)=>Q%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Q){if(Q.type="integer",this.rule===1)return Q;return Q.multipleOf=this.rule,Q}}var m6={implementation:QZ,Node:g4};var XZ=(Q)=>`divisor must be an integer (was ${Q})`,YZ=(Q,X)=>{let Y,U=Q,Z=X;while(Z!==0)Y=Z,Z=U%Z,U=Y;return U};class s extends O1{boundOperandKind=GZ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=_Z(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${UZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?JZ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Q){return(this.limitKind==="upper"?this.numericLimit<Q.numericLimit:this.numericLimit>Q.numericLimit)||this.numericLimit===Q.numericLimit&&this.exclusive===!0&&!Q.exclusive}overlapsRange(Q){if(this.isStricterThan(Q))return!1;if(this.numericLimit===Q.numericLimit&&(this.exclusive||Q.exclusive))return!1;return!0}overlapIsUnit(Q){return this.numericLimit===Q.numericLimit&&!this.exclusive&&!Q.exclusive}}var UZ={"<":">=","<=":">",">":"<=",">=":"<"},ZZ={min:"max",minLength:"maxLength",after:"before"},s2={parse:(Q)=>Q||void 0},n2=(Q)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:Y,...U}=X;return Y?{...U,rule:Q==="minLength"?U.rule+1:U.rule-1}:U},r2=(Q)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:Y,...U}=X;if(!Y)return U;let Z=typeof U.rule==="number"?U.rule:typeof U.rule==="string"?new Date(U.rule).valueOf():U.rule.valueOf();return Y?{...U,rule:Q==="after"?Z+1:Z-1}:U},t2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,WZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,c1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)L(WZ(Q,X));return X},GZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},_Z=(Q,X)=>`${f(Q,ZZ)?">":"<"}${X?"":"="}`,JZ=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),x4=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var LZ=M({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class h4 extends s{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q>=this.rule;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,after:this.rule})}}var l6={implementation:LZ,Node:h4};var HZ=M({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:j1},intersections:{before:(Q,X)=>Q.isStricterThan(X)?Q:X,after:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)}});class p4 extends s{collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,before:this.rule})}}var d6={implementation:HZ,Node:p4};var FZ=M({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:c1("exactLength")}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>`exactly length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{exactLength:(Q,X,Y)=>q.init("unit",Y.$.node("unit",{unit:Q.rule}),Y.$.node("unit",{unit:X.rule}),{path:["length"]}),minLength:(Q,X)=>Q.rule>=X.rule?Q:q.init("range",Q,X),maxLength:(Q,X)=>Q.rule<=X.rule?Q:q.init("range",Q,X)}});class u4 extends O1{traverseAllows=(Q)=>Q.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q.maxLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("exactLength",Q)}}}var c6={implementation:FZ,Node:u4};var qZ=M({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"negative":"non-positive";return`${Q.exclusive?"less than":"at most"} ${Q.rule}`}},intersections:{max:(Q,X)=>Q.isStricterThan(X)?Q:X,min:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)},obviatesBasisDescription:!0});class m4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q<this.rule:(Q)=>Q<=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMaximum=this.rule;else Q.maximum=this.rule;return Q}}var o6={implementation:qZ,Node:m4};var $Z=M({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:n2("maxLength"),defaults:{description:(Q)=>`at most length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{maxLength:(Q,X)=>Q.isStricterThan(X)?Q:X,minLength:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("exactLength",{rule:Q.rule}):null:q.init("range",Q,X)}});class l4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length<=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.maxLength=this.rule,Q;case"array":return Q.maxItems=this.rule,Q;default:return E.throwInternalOperandError("maxLength",Q)}}}var i6={implementation:$Z,Node:l4};var AZ=M({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"positive":"non-negative";return`${Q.exclusive?"more than":"at least"} ${Q.rule}`}},intersections:{min:(Q,X)=>Q.isStricterThan(X)?Q:X},obviatesBasisDescription:!0});class d4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q>this.rule:(Q)=>Q>=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMinimum=this.rule;else Q.minimum=this.rule;return Q}}var s6={implementation:AZ,Node:d4};var zZ=M({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:n2("minLength"),defaults:{description:(Q)=>Q.rule===1?"non-empty":`at least length ${Q.rule}`,actual:(Q)=>Q.length===0?"":`${Q.length}`},intersections:{minLength:(Q,X)=>Q.isStricterThan(X)?Q:X}});class c4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length>=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q;default:return E.throwInternalOperandError("minLength",Q)}}}var n6={implementation:zZ,Node:c4};var o4={min:s6.implementation,max:o6.implementation,minLength:n6.implementation,maxLength:i6.implementation,exactLength:c6.implementation,after:l6.implementation,before:d6.implementation},i4={min:s6.Node,max:o6.Node,minLength:n6.Node,maxLength:i6.Node,exactLength:c6.Node,after:l6.Node,before:d6.Node};var OZ=M({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Q)=>typeof Q==="string"?{rule:Q}:Q instanceof RegExp?Q.flags?{rule:Q.source,flags:Q.flags}:{rule:Q.source}:Q,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Q)=>`matched by ${Q.rule}`},intersections:{pattern:()=>null}});class s4 extends O1{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=F.intrinsic.string.internal;reduceJsonSchema(Q,X){if(Q.pattern)return X.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:this.rule});return Q.pattern=this.rule,Q}}var r6={implementation:OZ,Node:s4};var R2=(Q,X)=>{let Y=VZ(Q);if(X&&!X.includes(Y))return L(`Root of kind ${Y} should be one of ${X}`);return Y},VZ=(Q)=>{if(A(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in u)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return L(n4(Q));if("morphs"in Q)return"morph";if("branches"in Q||K(Q))return"union";if("unit"in Q)return"unit";if("reference"in Q)return"alias";let X=Object.keys(Q);if(X.length===0||X.some((Y)=>(Y in c2)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return L(n4(Q))},n4=(Q)=>`${B(Q)} is not a valid type schema`,r4={},BZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,h={};F.nodesByRegisteredId=h;var t6=(Q)=>{return r4[Q]??=0,`${Q}${++r4[Q]}`},a6=(Q)=>{let X=o1[Q.kind],Y=X.applyConfig?.(Q.def,Q.$.resolvedConfig)??Q.def,U={},{meta:Z,...W}=Y,G=Z===void 0?{}:typeof Z==="string"?{description:Z}:Z,_=D6(W).sort(([J],[$])=>p1(J)?p1($)?u1(J)-u1($):1:p1($)?-1:J<$?-1:1).filter(([J,$])=>{if(J.startsWith("meta.")){let O=J.slice(5);return G[O]=$,!1}return!0});for(let J of _){let $=J[0],O=X.keys[$];if(!O)return L(`Key ${$} is not valid on ${Q.kind} schema`);let R=O.parse?O.parse(J[1],Q):J[1];if(R!==m&&(R!==void 0||O.preserveUndefined))U[$]=R}if(X.reduce&&!Q.prereduced){let J=X.reduce(U,Q.$);if(J){if(J instanceof q)return J.throw();return MZ(J,G)}}return e6({id:Q.id,kind:Q.kind,inner:U,meta:G,$:Q.$})},e6=({id:Q,kind:X,inner:Y,meta:U,$:Z,ignoreCache:W})=>{let G=o1[X],_=D6(Y),H=[],J={};for(let[W1,f1]of _){let X2=G.keys[W1],WU=X2.serialize??(X2.child?BZ:r);if(J[W1]=WU(f1),X2.child===!0){let O6=f1;if(K(O6))H.push(...O6);else H.push(O6)}else if(typeof X2.child==="function")H.push(...X2.child(f1))}if(G.finalizeInnerJson)J=G.finalizeInnerJson(J);let $={...J},O={};if(!J1(U))O=V(U,(W1,f1)=>[W1,W1==="examples"?f1:r(f1)]),$.meta=a2(O,"description",!0);J=a2(J,G.collapsibleKey,!1);let R=JSON.stringify({kind:X,...J});$=a2($,G.collapsibleKey,!1);let b=a2($,G.collapsibleKey,!0),F1=JSON.stringify({kind:X,...$});if(Z.nodesByHash[F1]&&!W)return Z.nodesByHash[F1];let gQ={id:Q,kind:X,impl:G,inner:Y,innerEntries:_,innerJson:J,innerHash:R,meta:U,metaJson:O,json:$,hash:F1,collapsibleJson:b,children:H};if(X!=="intersection"){for(let W1 in Y)if(W1!=="in"&&W1!=="out")gQ[W1]=Y[W1]}let ZU=new a4[X](gQ,Z);return Z.nodesByHash[F1]=ZU},t4=(Q,X)=>{if(Q.id===X)return Q;if(P(h[X]))C(`Unexpected attempt to overwrite node id ${X}`);return e6({id:X,kind:Q.kind,inner:Q.inner,meta:Q.meta,$:Q.$,ignoreCache:!0})},MZ=(Q,X,Y)=>{if(Y&&P(h[Y]))C(`Unexpected attempt to overwrite node id ${Y}`);return e6({id:Y??t6(X.alias??Q.kind),kind:Q.kind,inner:Q.inner,meta:X,$:Q.$})},a2=(Q,X,Y)=>{let U=Object.keys(Q);if(U.length===1&&U[0]===X){let Z=Q[X];if(Y)return Z;if(p(Z,"object")&&(Object.keys(Z).length===1||Array.isArray(Z)))return Z}return Q};var C2=(Q,X,Y)=>{if(Q.key!==X.key)return null;let U=Q.key,Z=N(Q.value,X.value,Y),W=Q.required||X.required?"required":"optional";if(Z instanceof q)if(W==="optional")Z=F.intrinsic.never.internal;else return Z.withPrefixKey(Q.key,Q.required&&X.required?"required":"optional");if(W==="required")return Y.$.node("required",{key:U,value:Z});let G=Q.hasDefault()?X.hasDefault()?Q.default===X.default?Q.default:L(QQ(Q.default,X.default)):Q.default:X.hasDefault()?X.default:m;return Y.$.node("optional",{key:U,value:Z,default:G})};class w2 extends t{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=Y1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.key,...Q.path],Q.node)),Z1([this.key],this.value));_transform(Q,X){X.path.push(this.key);let Y=super._transform(Q,X);return X.path.pop(),Y}hasDefault(){return"default"in this.inner}traverseAllows=(Q,X)=>{if(this.key in Q)return c(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)c(this.key,()=>this.value.traverseApply(Q[this.key],X),X);else if(this.hasKind("required"))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.if(`${this.serializedKey} in data`,()=>Q.traverseKey(this.serializedKey,`data${Q.prop(this.key)}`,this.value)),this.hasKind("required"))Q.else(()=>Q.traversalKind==="Apply"?Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Q.return(!1));if(Q.traversalKind==="Allows")Q.return(!0)}}var QQ=(Q,X)=>`Invalid intersection of default values ${B(Q)} & ${B(X)}`;var TZ=M({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},default:{preserveUndefined:!0}},normalize:(Q)=>Q,reduce:(Q,X)=>{if(X.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Q.value.allows(void 0))return X.node("optional",{...Q,value:Q.value.or(z.undefined)},{prereduced:!0})}},defaults:{description:(Q)=>`${Q.compiledKey}?: ${Q.value.description}`},intersections:{optional:C2}});class e4 extends w2{constructor(...Q){super(...Q);if("default"in this.inner)P2(this.value,this.inner.default,this.key)}get rawIn(){let Q=super.rawIn;if(!this.hasDefault())return Q;return this.$.node("optional",x2(Q.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Q,...X}=this.inner;return this.cacheGetter("outProp",this.$.node("required",X,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${B(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=RZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var K2={implementation:TZ,Node:e4},DZ={},RZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${r(Q.default)}}`;return DZ[X]??=XQ(Q.key,Q.value,Q.default)},XQ=(Q,X,Y)=>{if(typeof Y==="function")return X.includesTransform?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y(),W),W),Z}:(Z)=>{return Z[Q]=Y(),Z};let U=X.includesTransform?X.assert(Y):Y;return p(U,"object")?(Z,W)=>{return c(Q,()=>X(Z[Q]=Y,W),W),Z}:(Z)=>{return Z[Q]=U,Z}},P2=(Q,X,Y)=>{let U=M1(X);if(p(X,"object")&&!U)L(CZ(Y));let Z=Q.in(U?X():X);if(Z instanceof d){if(Y===null)L(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((_)=>({..._,prefixPath:[Y]})));L(`Default for ${W.summary}`)}return X},CZ=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${Y1(Q)} `}must be specified as a function like () => ({my: 'object'})`};class a extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,x,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Q)=>{let X=this(Q);if(X instanceof d)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:QX(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:QX(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return L(wZ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,X){let Y=this.branches.map(Q);return X?.(Y)??Y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Q={}){let X=v6(this.$.resolvedConfig.toJsonSchema,Q);X.useRefs||=this.isCyclic;let Y=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(Y,this.toJsonSchemaRecurse(X)),X.useRefs){let U=V(this.references,(Z,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(Y,{definitions:U});else Y.$defs=U}return Y}toJsonSchemaRecurse(Q){if(Q.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Q.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Q)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Q){let X=this.innerToJsonSchema(Q);return Object.assign(X,this.metaJson)}intersect(Q){let X=this.$.parseDefinition(Q),Y=this.rawIntersect(X);if(Y instanceof q)return Y;return this.$.finalize(Y)}rawIntersect(Q){return o(this,Q,this.$)}toNeverIfDisjoint(){return this}and(Q){let X=this.intersect(Q);return X instanceof q?X.throw():X}rawAnd(Q){let X=this.rawIntersect(Q);return X instanceof q?X.throw():X}or(Q){let X=this.$.parseDefinition(Q);return this.$.finalize(this.rawOr(X))}rawOr(Q){let X=[...this.branches,...Q.branches];return this.$.node("union",X)}map(Q){return this.$.schema(this.applyStructuralOperation("map",[Q]))}pick(...Q){return this.$.schema(this.applyStructuralOperation("pick",Q))}omit(...Q){return this.$.schema(this.applyStructuralOperation("omit",Q))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.applyStructuralOperation("keyof",[]).reduce((X,Y)=>X.intersect(Y).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Q.branches.length===0)L(h6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return L(PZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((Y)=>this.applyStructuralOperation("merge",[XX(Y)??L(YX("merge",Y.expression))])))}applyStructuralOperation(Q,X){return this.distribute((Y)=>{if(Y.equals(F.intrinsic.object)&&Q!=="merge")return Y;let U=XX(Y);if(!U)L(YX(Q,Y.expression));if(Q==="keyof")return U.keyof();if(Q==="get")return U.get(...X);if(Q==="props")return U.props;let Z=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{domain:"object",structure:U[Z](...X)})})}get(...Q){if(Q[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Q))}extract(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>Y.extends(X)))}exclude(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>!Y.extends(X)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Q){return!(this.intersect(Q)instanceof q)}extends(Q){if(this.isNever())return!0;let X=this.intersect(Q);return!(X instanceof q)&&this.equals(X)}ifExtends(Q){return this.extends(Q)?this:void 0}subsumes(Q){return this.$.parseDefinition(Q).extends(this)}configure(Q,X="shallow"){return this.configureReferences(Q,X)}describe(Q,X="shallow"){return this.configure({description:Q},X)}optional(){return[this,"?"]}default(Q){return P2(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(U),this);return this.$.finalize(X)}tryPipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(A(U,"root")?U:(Z,W)=>{try{return U(Z,W)}catch(G){return W.error({code:"predicate",predicate:U,actual:`aborted due to error:
|
|
20
|
+
`);class U1{path=[];errors=new c(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Q,X){this.root=Q,this.config=X}get data(){let Q=this.root;for(let X of this.path)Q=Q?.[X];return Q}get propString(){return z1(this.path)}reject(Q){return this.error(Q),!1}mustBe(Q){return this.error(Q),!1}error(Q){let X=typeof Q==="object"?Q.code?Q:{...Q,code:"predicate"}:{code:"predicate",expected:Q};return this.errorFromContext(X)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Q){let X={path:new z2(...this.path),morphs:Q};if(this.currentBranch)this.currentBranch.queuedMorphs.push(X);else this.queuedMorphs.push(X)}finalize(Q){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Q?Q(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Q){return this.errorFromContext(Q)}errorFromContext(Q){let X=new C1(Q,this);if(this.currentBranch)this.currentBranch.error=X;else this.errors.add(X);return X}applyQueuedMorphs(){while(this.queuedMorphs.length){let Q=this.queuedMorphs;this.queuedMorphs=[];for(let{path:X,morphs:Y}of Q){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,Y)}}}applyMorphsAtPath(Q,X){let Y=Q[Q.length-1],U;if(Y!==void 0){U=this.root;for(let Z=0;Z<Q.length-1;Z++)U=U[Q[Z]]}for(let Z of X){this.path=[...Q];let W=P(Z),G=Z(U===void 0?this.root:U[Y],this);if(G instanceof C1){if(!this.errors.includes(G))this.errors.add(G);break}if(G instanceof c){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(U===void 0)this.root=G;else U[Y]=G;this.applyQueuedMorphs()}}}var o=(Q,X,Y)=>{if(!Y)return X();Y.path.push(Q);let U=X();return Y.path.pop(),U};class T2 extends d{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Q,X){super((U,Z,W=this.onFail)=>{if(Z)return this.traverseApply(U,Z),Z.hasError()?Z.errors:Z.data;return this.rootApply(U,W)},{attach:Q});this.attachments=Q,this.$=X,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((U,Z)=>QZ(U,Z.shallowReferences),[this]);let Y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let U=0;U<this.children.length;U++){if(this.includesTransform||=this.children[U].includesTransform,this.includesContextualPredicate||=this.children[U].includesContextualPredicate,this.isCyclic||=this.children[U].isCyclic,!Y){let Z=this.children[U].flatRefs;for(let W=0;W<Z.length;W++){let G=Z[W];if(!this.flatRefs.some((_)=>v4(_,G))){this.flatRefs.push(G);for(let _ of G.node.branches)if(_.hasKind("morph")||_.hasKind("intersection")&&_.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:_})}}}Object.assign(this.referencesById,this.children[U].referencesById)}this.flatRefs.sort((U,Z)=>U.path.length>Z.path.length?1:U.path.length<Z.path.length?-1:U.propString>Z.propString?1:U.propString<Z.propString?-1:U.node.expression<Z.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((U)=>U.length===1||U.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((U)=>U.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(U)=>this.traverseAllows(U,new U1(U,this.$.resolvedConfig)):(U)=>this.traverseAllows(U)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,Y)=>{if(this.allows(X))return X;let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"contextual":return(X,Y)=>{let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Q=this.$.resolvedConfig.clone;return(X,Y)=>{if(this.allows(X))return this.contextFreeMorph(Q&&(typeof X==="object"&&X!==null||typeof X==="function")?Q(X):X);let U=new U1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,C(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=eU(this.metaJson);cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=u1(this.kind);precompilation;assert=(Q,X)=>this(Q,X,(Y)=>Y.throw());traverse(Q,X){return this(Q,X,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(Q){if(!this.includesTransform)return this;let X={};for(let[Y,U]of this.innerEntries){let Z=this.impl.keys[Y];if(Z.reduceIo)Z.reduceIo(Q,X,U);else if(Z.child){let W=U;X[Y]=K(W)?W.map((G)=>Q==="in"?G.rawIn:G.rawOut):Q==="in"?W.rawIn:W.rawOut}else X[Y]=U}return this.$.node(this.kind,X)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Q){let X=P(Q)?Q:this.$.parseDefinition(Q);return this.innerHash===X.innerHash}ifEquals(Q){return this.equals(Q)?this:void 0}hasKind(Q){return this.kind===Q}assertHasKind(Q){if(this.kind!==Q)P1(`${this.kind} node was not of asserted kind ${Q}`);return this}hasKindIn(...Q){return Q.includes(this.kind)}assertHasKindIn(...Q){if(!n(Q,this.kind))P1(`${this.kind} node was not one of asserted kinds ${Q}`);return this}isBasis(){return n(I4,this.kind)}isConstraint(){return n(d2,this.kind)}isStructural(){return n(x1,this.kind)}isRefinement(){return n(k6,this.kind)}isRoot(){return n(h1,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Q){return this.hasKind("unit")&&this.allows(Q)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Q){let X=M2.normalize(Q);return this._select(X)}_select(Q){let X=M2.applyBoundary[Q.boundary??"references"](this);if(Q.kind)X=X.filter((Y)=>Y.kind===Q.kind);if(Q.where)X=X.filter(Q.where);return M2.applyMethod[Q.method??"filter"](X,this,Q)}transform(Q,X){return this._transform(Q,this._createTransformContext(X))}_createTransformContext(Q){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Q?.prereduced??!1},undeclaredKeyHandling:void 0,...Q}}_transform(Q,X){let Y=X.bindScope??this.$;if(X.seen[this.id])return this.$.lazilyResolve(X.seen[this.id]);if(X.shouldTransform?.(this,X)===!1)return this;let U;if(X.seen[this.id]=()=>U,this.hasKind("structure")&&this.undeclared!==X.undeclaredKeyHandling)X={...X,undeclaredKeyHandling:this.undeclared};let Z=V(this.inner,(J,A)=>{if(!this.impl.keys[J].child)return[J,A];let O=A;if(!K(O)){let f=O._transform(Q,X);return f?[J,f]:[]}if(O.length===0)return[J,A];let R=O.flatMap((f)=>{return f._transform(Q,X)??[]});return R.length?[J,R]:[]});delete X.seen[this.id];let W=Object.assign(Z,{meta:this.meta}),G=X.selected&&!X.selected.includes(this)?W:Q(this.kind,W,X);if(G===null)return null;if(P(G))return U=G;let _=Object.keys(G);if((_.length===0||_.length===1&&_[0]==="meta")&&!J1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in G))return X.undeclaredKeyHandling?{...G,value:F.intrinsic.unknown}:null;if(this.kind==="morph")G.in??=F.intrinsic.unknown;return U=Y.node(this.kind,G,X.parseOptions)}configureReferences(Q,X="references"){let Y=M2.normalize(X),U=typeof Q==="string"?(_,L)=>({...L,meta:{...L.meta,description:Q}}):typeof Q==="function"?(_,L)=>({...L,meta:Q(L.meta)}):(_,L)=>({...L,meta:{...L.meta,...Q}});if(Y.boundary==="self")return this.$.node(this.kind,U(this.kind,{...this.inner,meta:this.meta}));let Z=this._select(Y),W=Z&&B1(Z),G=Y.boundary==="child"?(_,L)=>L.root.children.includes(_):Y.boundary==="shallow"?(_)=>_.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:G,selected:W}))}}var M2={applyBoundary:{self:(Q)=>[Q],child:(Q)=>[...Q.children],shallow:(Q)=>[...Q.shallowReferences],references:(Q)=>[...Q.references]},applyMethod:{filter:(Q)=>Q,assertFilter:(Q,X,Y)=>{if(Q.length===0)P1(y4(X,Y));return Q},find:(Q)=>Q[0],assertFind:(Q,X,Y)=>{if(Q.length===0)P1(y4(X,Y));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?y(Q,M2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},y4=(Q,X)=>`${Q} had no references matching ${B(X)}.`,tU=(Q)=>z1(Q,{stringifyNonKey:(X)=>X.expression}),aU=/"(\$ark\.[^"]+)"/g,eU=(Q)=>JSON.stringify(Q).replace(aU,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:tU(Q)}),v4=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),h6=(Q,X)=>_1(Q,X,{isEqual:v4}),QZ=(Q,X)=>_1(Q,X,{isEqual:(Y,U)=>Y.equals(U)});class q extends Array{static init(Q,X,Y,U){return new q({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1})}add(Q,X,Y,U){return this.push({kind:Q,l:X,r:Y,path:U?.path??[],optional:U?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Q,l:X,r:Y}=this[0],U=z1(Q);return u6(`Intersection${U&&` at ${U}`} of ${k4(X,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
+
• ${this.map(({path:Q,l:X,r:Y})=>`${Q}: ${k4(X,Y)}`).join(`
|
|
22
|
+
• `)}`}throw(){return H(this.describeReasons())}invert(){let Q=this.map((X)=>({...X,l:X.r,r:X.l}));if(!(Q instanceof q))return new q(...Q);return Q}withPrefixKey(Q,X){return this.map((Y)=>({...Y,path:[Q,...Y.path],optional:Y.optional||X==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var k4=(Q,X)=>`${p6(Q)} and ${p6(X)}`,p6=(Q)=>P(Q)?Q.expression:K(Q)?Q.map(p6).join(" | ")||"never":String(Q),u6=(Q)=>`${Q} results in an unsatisfiable type`;var m1={},i=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!1}),D2=(Q,X,Y)=>N(Q,X,{$:Y,invert:!1,pipe:!0}),N=(Q,X,Y)=>{let U=Y.pipe?"|>":"&",Z=`${Q.hash}${U}${X.hash}`;if(m1[Z]!==void 0)return m1[Z];if(!Y.pipe){let _=`${X.hash}${U}${Q.hash}`;if(m1[_]!==void 0){let L=m1[_],J=L instanceof q?L.invert():L;return m1[Z]=J,J}}let W=!Y.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?m6(Q,X,Y):Q.hasKindIn(...h1)?XZ(Q,X,Y):m6(Q,X,Y);if(P(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return m1[Z]=G,G},m6=(Q,X,Y)=>{let U=Q.precedence<X.precedence?Q.kind:X.kind,Z=Q.impl.intersections[X.kind]??X.impl.intersections[Q.kind];if(Z===void 0)return null;else if(U===Q.kind)return Z(Q,X,Y);else{let W=Z(X,Q,{...Y,invert:!Y.invert});if(W instanceof q)W=W.invert();return W}},XZ=(Q,X,Y)=>Q.includesTransform||X.includesTransform?Y.invert?g4(X,Q,Y):g4(Q,X,Y):m6(Q,X,Y),g4=(Q,X,Y)=>Q.distribute((U)=>YZ(U,X,Y),(U)=>{let Z=U.filter(P);if(Z.length===0)return q.init("union",Q.branches,X.branches);if(Z.length<Q.branches.length||!Q.branches.every((_,L)=>_.rawIn.equals(Z[L].rawIn)))return Y.$.parseSchema(Z);let W;if(Z.length===1){let _=Z[0];if(!W)return _;return Y.$.node("morph",{..._.inner,in:_.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return Y.$.parseSchema(G)}),YZ=(Q,X,Y)=>{if(Q.hasKind("morph")){let Z=[...Q.morphs];if(Q.lastMorphIfNode){let W=N(Q.lastMorphIfNode,X,Y);if(W instanceof q)return W;Z[Z.length-1]=W}else Z.push(X);return Y.$.node("morph",{morphs:Z,in:Q.inner.in})}if(X.hasKind("morph")){let Z=N(Q,X.rawIn,Y);if(Z instanceof q)return Z;return Y.$.node("morph",{morphs:[X],in:Z})}return Y.$.node("morph",{morphs:[X],in:Q})};class t extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,h,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return i(this,Q,this.$)}}class O1 extends t{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}}var x=(Q)=>(X,Y)=>{if(K(X)){if(X.length===0)return;let Z=X.map((W)=>Y.$.node(Q,W));if(Q==="predicate")return Z;return Z.sort((W,G)=>W.hash<G.hash?-1:1)}let U=Y.$.node(Q,X);return U.hasOpenIntersection()?[U]:U},l1=(Q)=>{let X=Q.r.shift();if(!X){let U=Q.l.length===0&&Q.kind==="structure"?F.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,UZ(Q.l)),{prereduced:!0});for(let Z of Q.roots){if(U instanceof q)return U;U=N(Z,U,Q.ctx)}return U}let Y=!1;for(let U=0;U<Q.l.length;U++){let Z=N(Q.l[U],X,Q.ctx);if(Z===null)continue;if(Z instanceof q)return Z;if(Z.isRoot())return Q.roots.push(Z),Q.l.splice(U),l1(Q);if(!Y)Q.l[U]=Z,Y=!0;else if(!Q.l.includes(Z))return C(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!Y)Q.l.push(X);if(Q.kind==="intersection"){if(X.impliedSiblings)for(let U of X.impliedSiblings)_1(Q.r,U)}return l1(Q)},d1=(Q)=>{return Object.entries(Q).flatMap(([Y,U])=>(Y in c2)?U:[]).sort((Y,U)=>Y.precedence<U.precedence?-1:Y.precedence>U.precedence?1:Y.kind==="predicate"&&U.kind==="predicate"?0:Y.hash<U.hash?-1:1)},UZ=(Q)=>{let X={};for(let Y of Q)if(Y.hasOpenIntersection())X[Y.kind]=D(X[Y.kind],Y);else{if(X[Y.kind])return C(`Unexpected intersection of closed refinements of kind ${Y.kind}`);X[Y.kind]=Y}return X},x4=(...Q)=>H(h4(...Q)),h4=(Q,X,Y)=>{let U=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude(X).defaultShortDescription;return`${F4(Q)} operand must be ${X.description} (was ${U})`};var p4=(Q,X,Y)=>new w1(Q,X,Y,Y,null);class i2 extends d{}class w1 extends d{[h]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,Y,U,Z){super((...W)=>{let G=V(this.names,(_,L)=>{let J=this.arg$.parse(W[_]);if(!J.extends(this.constraints[_]))H(ZZ(L,this.constraints[_].expression,J.expression));return[L,J]});if(this.defIsLazy()){let _=this.bodyDef(G);return this.$.parse(_)}return this.$.parse(X,{args:G})});this.paramDefs=Q,this.bodyDef=X,this.$=Y,this.arg$=U,this.hkt=Z,this.description=Z?new Z().description??`a generic type for ${Z.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i2}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get json(){return this.cacheGetter("json",{params:this.params.map((Q)=>Q[1].isUnknown()?Q[0]:[Q[0],Q[1].json]),body:C4(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Q)=>typeof Q==="string"?[Q,F.intrinsic.unknown]:[Q[0],this.$.parse(Q[1])]))}get names(){return this.cacheGetter("names",this.params.map((Q)=>Q[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Q)=>Q[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var ZZ=(Q,X,Y)=>`${Q} must be assignable to ${X} (was ${Y})`;var WZ=M({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Q)=>typeof Q==="function"?{predicate:Q}:Q,defaults:{description:(Q)=>`valid according to ${Q.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class u4 extends t{serializedPredicate=S(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=R1(this.errorContext);traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(!this.predicate(Q,X.external)&&X.currentErrorCount===Y)X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows"){Q.return(this.compiledCondition);return}Q.initializeErrorCount(),Q.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Q,X){return X.fallback.predicate({code:"predicate",base:Q,predicate:this.predicate})}}var l6={implementation:WZ,Node:u4};var GZ=M({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:H(_Z(Q))}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>Q.rule===1?"an integer":Q.rule===2?"even":`a multiple of ${Q.rule}`},intersections:{divisor:(Q,X,Y)=>Y.$.node("divisor",{rule:Math.abs(Q.rule*X.rule/JZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class m4 extends O1{traverseAllows=(Q)=>Q%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Q){if(Q.type="integer",this.rule===1)return Q;return Q.multipleOf=this.rule,Q}}var d6={implementation:GZ,Node:m4};var _Z=(Q)=>`divisor must be an integer (was ${Q})`,JZ=(Q,X)=>{let Y,U=Q,Z=X;while(Z!==0)Y=Z,Z=U%Z,U=Y;return U};class s extends O1{boundOperandKind=qZ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=AZ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${LZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?$Z(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Q){return(this.limitKind==="upper"?this.numericLimit<Q.numericLimit:this.numericLimit>Q.numericLimit)||this.numericLimit===Q.numericLimit&&this.exclusive===!0&&!Q.exclusive}overlapsRange(Q){if(this.isStricterThan(Q))return!1;if(this.numericLimit===Q.numericLimit&&(this.exclusive||Q.exclusive))return!1;return!0}overlapIsUnit(Q){return this.numericLimit===Q.numericLimit&&!this.exclusive&&!Q.exclusive}}var LZ={"<":">=","<=":">",">":"<=",">=":"<"},HZ={min:"max",minLength:"maxLength",after:"before"},s2={parse:(Q)=>Q||void 0},n2=(Q)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:Y,...U}=X;return Y?{...U,rule:Q==="minLength"?U.rule+1:U.rule-1}:U},r2=(Q)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:Y,...U}=X;if(!Y)return U;let Z=typeof U.rule==="number"?U.rule:typeof U.rule==="string"?new Date(U.rule).valueOf():U.rule.valueOf();return Y?{...U,rule:Q==="after"?Z+1:Z-1}:U},t2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,FZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,c1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)H(FZ(Q,X));return X},qZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},AZ=(Q,X)=>`${y(Q,HZ)?">":"<"}${X?"":"="}`,$Z=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),l4=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var zZ=M({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class d4 extends s{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q>=this.rule;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,after:this.rule})}}var c6={implementation:zZ,Node:d4};var OZ=M({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:r2("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:j1},intersections:{before:(Q,X)=>Q.isStricterThan(X)?Q:X,after:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)}});class c4 extends s{collapsibleLimitString=j1(this.rule);traverseAllows=(Q)=>Q<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Q,X){return X.fallback.date({code:"date",base:Q,before:this.rule})}}var o6={implementation:OZ,Node:c4};var VZ=M({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:c1("exactLength")}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>`exactly length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{exactLength:(Q,X,Y)=>q.init("unit",Y.$.node("unit",{unit:Q.rule}),Y.$.node("unit",{unit:X.rule}),{path:["length"]}),minLength:(Q,X)=>Q.rule>=X.rule?Q:q.init("range",Q,X),maxLength:(Q,X)=>Q.rule<=X.rule?Q:q.init("range",Q,X)}});class o4 extends O1{traverseAllows=(Q)=>Q.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q.maxLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q.maxItems=this.rule,Q;default:return I.throwInternalOperandError("exactLength",Q)}}}var i6={implementation:VZ,Node:o4};var BZ=M({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"negative":"non-positive";return`${Q.exclusive?"less than":"at most"} ${Q.rule}`}},intersections:{max:(Q,X)=>Q.isStricterThan(X)?Q:X,min:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)},obviatesBasisDescription:!0});class i4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q<this.rule:(Q)=>Q<=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMaximum=this.rule;else Q.maximum=this.rule;return Q}}var s6={implementation:BZ,Node:i4};var MZ=M({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:n2("maxLength"),defaults:{description:(Q)=>`at most length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{maxLength:(Q,X)=>Q.isStricterThan(X)?Q:X,minLength:(Q,X,Y)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?Y.$.node("exactLength",{rule:Q.rule}):null:q.init("range",Q,X)}});class s4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length<=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.maxLength=this.rule,Q;case"array":return Q.maxItems=this.rule,Q;default:return I.throwInternalOperandError("maxLength",Q)}}}var n6={implementation:MZ,Node:s4};var TZ=M({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:s2},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>{if(Q.rule===0)return Q.exclusive?"positive":"non-negative";return`${Q.exclusive?"more than":"at least"} ${Q.rule}`}},intersections:{min:(Q,X)=>Q.isStricterThan(X)?Q:X},obviatesBasisDescription:!0});class n4 extends s{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q>this.rule:(Q)=>Q>=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMinimum=this.rule;else Q.minimum=this.rule;return Q}}var r6={implementation:TZ,Node:n4};var DZ=M({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:c1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:n2("minLength"),defaults:{description:(Q)=>Q.rule===1?"non-empty":`at least length ${Q.rule}`,actual:(Q)=>Q.length===0?"":`${Q.length}`},intersections:{minLength:(Q,X)=>Q.isStricterThan(X)?Q:X}});class r4 extends s{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length>=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q;default:return I.throwInternalOperandError("minLength",Q)}}}var t6={implementation:DZ,Node:r4};var t4={min:r6.implementation,max:s6.implementation,minLength:t6.implementation,maxLength:n6.implementation,exactLength:i6.implementation,after:c6.implementation,before:o6.implementation},a4={min:r6.Node,max:s6.Node,minLength:t6.Node,maxLength:n6.Node,exactLength:i6.Node,after:c6.Node,before:o6.Node};var RZ=M({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Q)=>typeof Q==="string"?{rule:Q}:Q instanceof RegExp?Q.flags?{rule:Q.source,flags:Q.flags}:{rule:Q.source}:Q,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Q)=>`matched by ${Q.rule}`},intersections:{pattern:()=>null}});class e4 extends O1{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=F.intrinsic.string.internal;reduceJsonSchema(Q,X){if(Q.pattern)return X.fallback.patternIntersection({code:"patternIntersection",base:Q,pattern:this.rule});return Q.pattern=this.rule,Q}}var a6={implementation:RZ,Node:e4};var R2=(Q,X)=>{let Y=CZ(Q);if(X&&!X.includes(Y))return H(`Root of kind ${Y} should be one of ${X}`);return Y},CZ=(Q)=>{if($(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in m)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return H(QX(Q));if("morphs"in Q)return"morph";if("branches"in Q||K(Q))return"union";if("unit"in Q)return"unit";if("reference"in Q)return"alias";let X=Object.keys(Q);if(X.length===0||X.some((Y)=>(Y in c2)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return H(QX(Q))},QX=(Q)=>`${B(Q)} is not a valid type schema`,XX={},wZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,p={};F.nodesByRegisteredId=p;var e6=(Q)=>{return XX[Q]??=0,`${Q}${++XX[Q]}`},QQ=(Q)=>{let X=o1[Q.kind],Y=X.applyConfig?.(Q.def,Q.$.resolvedConfig)??Q.def,U={},{meta:Z,...W}=Y,G=Z===void 0?{}:typeof Z==="string"?{description:Z}:Z,_=C6(W).sort(([J],[A])=>p1(J)?p1(A)?u1(J)-u1(A):1:p1(A)?-1:J<A?-1:1).filter(([J,A])=>{if(J.startsWith("meta.")){let O=J.slice(5);return G[O]=A,!1}return!0});for(let J of _){let A=J[0],O=X.keys[A];if(!O)return H(`Key ${A} is not valid on ${Q.kind} schema`);let R=O.parse?O.parse(J[1],Q):J[1];if(R!==l&&(R!==void 0||O.preserveUndefined))U[A]=R}if(X.reduce&&!Q.prereduced){let J=X.reduce(U,Q.$);if(J){if(J instanceof q)return J.throw();return KZ(J,G)}}return XQ({id:Q.id,kind:Q.kind,inner:U,meta:G,$:Q.$})},XQ=({id:Q,kind:X,inner:Y,meta:U,$:Z,ignoreCache:W})=>{let G=o1[X],_=C6(Y),L=[],J={};for(let[W1,y1]of _){let X2=G.keys[W1],HU=X2.serialize??(X2.child?wZ:r);if(J[W1]=HU(y1),X2.child===!0){let O6=y1;if(K(O6))L.push(...O6);else L.push(O6)}else if(typeof X2.child==="function")L.push(...X2.child(y1))}if(G.finalizeInnerJson)J=G.finalizeInnerJson(J);let A={...J},O={};if(!J1(U))O=V(U,(W1,y1)=>[W1,W1==="examples"?y1:r(y1)]),A.meta=a2(O,"description",!0);J=a2(J,G.collapsibleKey,!1);let R=JSON.stringify({kind:X,...J});A=a2(A,G.collapsibleKey,!1);let f=a2(A,G.collapsibleKey,!0),F1=JSON.stringify({kind:X,...A});if(Z.nodesByHash[F1]&&!W)return Z.nodesByHash[F1];let hQ={id:Q,kind:X,impl:G,inner:Y,innerEntries:_,innerJson:J,innerHash:R,meta:U,metaJson:O,json:A,hash:F1,collapsibleJson:f,children:L};if(X!=="intersection"){for(let W1 in Y)if(W1!=="in"&&W1!=="out")hQ[W1]=Y[W1]}let LU=new UX[X](hQ,Z);return Z.nodesByHash[F1]=LU},YX=(Q,X)=>{if(Q.id===X)return Q;if(P(p[X]))C(`Unexpected attempt to overwrite node id ${X}`);return XQ({id:X,kind:Q.kind,inner:Q.inner,meta:Q.meta,$:Q.$,ignoreCache:!0})},KZ=(Q,X,Y)=>{if(Y&&P(p[Y]))C(`Unexpected attempt to overwrite node id ${Y}`);return XQ({id:Y??e6(X.alias??Q.kind),kind:Q.kind,inner:Q.inner,meta:X,$:Q.$})},a2=(Q,X,Y)=>{let U=Object.keys(Q);if(U.length===1&&U[0]===X){let Z=Q[X];if(Y)return Z;if(u(Z,"object")&&(Object.keys(Z).length===1||Array.isArray(Z)))return Z}return Q};var C2=(Q,X,Y)=>{if(Q.key!==X.key)return null;let U=Q.key,Z=N(Q.value,X.value,Y),W=Q.required||X.required?"required":"optional";if(Z instanceof q)if(W==="optional")Z=F.intrinsic.never.internal;else return Z.withPrefixKey(Q.key,Q.required&&X.required?"required":"optional");if(W==="required")return Y.$.node("required",{key:U,value:Z});let G=Q.hasDefault()?X.hasDefault()?Q.default===X.default?Q.default:H(YQ(Q.default,X.default)):Q.default:X.hasDefault()?X.default:l;return Y.$.node("optional",{key:U,value:Z,default:G})};class w2 extends t{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=Y1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.key,...Q.path],Q.node)),Z1([this.key],this.value));_transform(Q,X){X.path.push(this.key);let Y=super._transform(Q,X);return X.path.pop(),Y}hasDefault(){return"default"in this.inner}traverseAllows=(Q,X)=>{if(this.key in Q)return o(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)o(this.key,()=>this.value.traverseApply(Q[this.key],X),X);else if(this.hasKind("required"))X.errorFromNodeContext(this.errorContext)};compile(Q){if(Q.if(`${this.serializedKey} in data`,()=>Q.traverseKey(this.serializedKey,`data${Q.prop(this.key)}`,this.value)),this.hasKind("required"))Q.else(()=>Q.traversalKind==="Apply"?Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Q.return(!1));if(Q.traversalKind==="Allows")Q.return(!0)}}var YQ=(Q,X)=>`Invalid intersection of default values ${B(Q)} & ${B(X)}`;var PZ=M({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},default:{preserveUndefined:!0}},normalize:(Q)=>Q,reduce:(Q,X)=>{if(X.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Q.value.allows(void 0))return X.node("optional",{...Q,value:Q.value.or(z.undefined)},{prereduced:!0})}},defaults:{description:(Q)=>`${Q.compiledKey}?: ${Q.value.description}`},intersections:{optional:C2}});class ZX extends w2{constructor(...Q){super(...Q);if("default"in this.inner)P2(this.value,this.inner.default,this.key)}get rawIn(){let Q=super.rawIn;if(!this.hasDefault())return Q;return this.$.node("optional",x2(Q.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Q,...X}=this.inner;return this.cacheGetter("outProp",this.$.node("required",X,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${B(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=IZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var K2={implementation:PZ,Node:ZX},NZ={},IZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${r(Q.default)}}`;return NZ[X]??=UQ(Q.key,Q.value,Q.default)},UQ=(Q,X,Y)=>{if(typeof Y==="function")return X.includesTransform?(Z,W)=>{return o(Q,()=>X(Z[Q]=Y(),W),W),Z}:(Z)=>{return Z[Q]=Y(),Z};let U=X.includesTransform?X.assert(Y):Y;return u(U,"object")?(Z,W)=>{return o(Q,()=>X(Z[Q]=Y,W),W),Z}:(Z)=>{return Z[Q]=U,Z}},P2=(Q,X,Y)=>{let U=M1(X);if(u(X,"object")&&!U)H(EZ(Y));let Z=Q.in(U?X():X);if(Z instanceof c){if(Y===null)H(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((_)=>({..._,prefixPath:[Y]})));H(`Default for ${W.summary}`)}return X},EZ=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${Y1(Q)} `}must be specified as a function like () => ({my: 'object'})`};class a extends T2{constructor(Q,X){super(Q,X);Object.defineProperty(this,h,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Q)=>{let X=this(Q);if(X instanceof c)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:WX(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:WX(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return H(SZ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,X){let Y=this.branches.map(Q);return X?.(Y)??Y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Q={}){let X=g6(this.$.resolvedConfig.toJsonSchema,Q);X.useRefs||=this.isCyclic;let Y=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(Y,this.toJsonSchemaRecurse(X)),X.useRefs){let U=V(this.references,(Z,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(Y,{definitions:U});else Y.$defs=U}return Y}toJsonSchemaRecurse(Q){if(Q.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Q.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Q)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Q){let X=this.innerToJsonSchema(Q);return Object.assign(X,this.metaJson)}intersect(Q){let X=this.$.parseDefinition(Q),Y=this.rawIntersect(X);if(Y instanceof q)return Y;return this.$.finalize(Y)}rawIntersect(Q){return i(this,Q,this.$)}toNeverIfDisjoint(){return this}and(Q){let X=this.intersect(Q);return X instanceof q?X.throw():X}rawAnd(Q){let X=this.rawIntersect(Q);return X instanceof q?X.throw():X}or(Q){let X=this.$.parseDefinition(Q);return this.$.finalize(this.rawOr(X))}rawOr(Q){let X=[...this.branches,...Q.branches];return this.$.node("union",X)}map(Q){return this.$.schema(this.applyStructuralOperation("map",[Q]))}pick(...Q){return this.$.schema(this.applyStructuralOperation("pick",Q))}omit(...Q){return this.$.schema(this.applyStructuralOperation("omit",Q))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.applyStructuralOperation("keyof",[]).reduce((X,Y)=>X.intersect(Y).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Q.branches.length===0)H(u6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return H(fZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((Y)=>this.applyStructuralOperation("merge",[GX(Y)??H(_X("merge",Y.expression))])))}applyStructuralOperation(Q,X){return this.distribute((Y)=>{if(Y.equals(F.intrinsic.object)&&Q!=="merge")return Y;let U=GX(Y);if(!U)H(_X(Q,Y.expression));if(Q==="keyof")return U.keyof();if(Q==="get")return U.get(...X);if(Q==="props")return U.props;let Z=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{domain:"object",structure:U[Z](...X)})})}get(...Q){if(Q[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Q))}extract(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>Y.extends(X)))}exclude(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((Y)=>!Y.extends(X)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Q){return!(this.intersect(Q)instanceof q)}extends(Q){if(this.isNever())return!0;let X=this.intersect(Q);return!(X instanceof q)&&this.equals(X)}ifExtends(Q){return this.extends(Q)?this:void 0}subsumes(Q){return this.$.parseDefinition(Q).extends(this)}configure(Q,X="shallow"){return this.configureReferences(Q,X)}describe(Q,X="shallow"){return this.configure({description:Q},X)}optional(){return[this,"?"]}default(Q){return P2(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce(U),this);return this.$.finalize(X)}tryPipe(...Q){let X=Q.reduce((Y,U)=>Y.rawPipeOnce($(U,"root")?U:(Z,W)=>{try{return U(Z,W)}catch(G){return W.error({code:"predicate",predicate:U,actual:`aborted due to error:
|
|
23
23
|
${G}
|
|
24
|
-
`})}}),this);return this.$.finalize(X)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Q){return this.$.finalize(this.toNode(this.$.parseDefinition(Q)))}toNode(Q){let X=D2(this,Q,this.$);if(X instanceof q)return X.throw();return X}rawPipeOnce(Q){if(
|
|
25
|
-
${Q}`,
|
|
24
|
+
`})}}),this);return this.$.finalize(X)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Q){return this.$.finalize(this.toNode(this.$.parseDefinition(Q)))}toNode(Q){let X=D2(this,Q,this.$);if(X instanceof q)return X.throw();return X}rawPipeOnce(Q){if($(Q,"root"))return this.toNode(Q);return this.distribute((X)=>X.hasKind("morph")?this.$.node("morph",{in:X.inner.in,morphs:[...X.morphs,Q]}):this.$.node("morph",{in:X,morphs:[Q]}),this.$.parseSchema)}narrow(Q){return this.constrainOut("predicate",Q)}constrain(Q,X){return this._constrain("root",Q,X)}constrainIn(Q,X){return this._constrain("in",Q,X)}constrainOut(Q,X){return this._constrain("out",Q,X)}_constrain(Q,X,Y){let U=this.$.node(X,Y);if(U.isRoot())return U.isUnknown()?this:C(`Unexpected constraint node ${U}`);let Z=Q==="root"?this:Q==="in"?this.rawIn:this.rawOut;if(Z.hasKind("morph")||U.impliedBasis&&!Z.extends(U.impliedBasis))return x4(X,U.impliedBasis,this);let W=this.$.node("intersection",{[U.kind]:U}),G=Q==="out"?D2(this,W,this.$):i(this,W,this.$);if(G instanceof q)G.throw();return this.$.finalize(G)}onUndeclaredKey(Q){let X=typeof Q==="string"?Q:Q.rule,Y=typeof Q==="string"?!1:Q.deep;return this.$.finalize(this.transform((U,Z)=>U==="structure"?X==="ignore"?x2(Z,{undeclared:1}):{...Z,undeclared:X}:Z,Y?void 0:{shouldTransform:(U)=>!n(x1,U.kind)}))}hasEqualMorphs(Q){if(!this.includesTransform&&!Q.includesTransform)return!0;if(!A1(this.shallowMorphs,Q.shallowMorphs))return!1;if(!A1(this.flatMorphs,Q.flatMorphs,{isEqual:(X,Y)=>X.propString===Y.propString&&(X.node.hasKind("morph")&&Y.node.hasKind("morph")?X.node.hasEqualMorphs(Y.node):X.node.hasKind("intersection")&&Y.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Q){return this.onUndeclaredKey({rule:Q,deep:!0})}filter(Q){return this.constrainIn("predicate",Q)}divisibleBy(Q){return this.constrain("divisor",Q)}matching(Q){return this.constrain("pattern",Q)}atLeast(Q){return this.constrain("min",Q)}atMost(Q){return this.constrain("max",Q)}moreThan(Q){return this.constrain("min",i1(Q))}lessThan(Q){return this.constrain("max",i1(Q))}atLeastLength(Q){return this.constrain("minLength",Q)}atMostLength(Q){return this.constrain("maxLength",Q)}moreThanLength(Q){return this.constrain("minLength",i1(Q))}lessThanLength(Q){return this.constrain("maxLength",i1(Q))}exactlyLength(Q){return this.constrain("exactLength",Q)}atOrAfter(Q){return this.constrain("after",Q)}atOrBefore(Q){return this.constrain("before",Q)}laterThan(Q){return this.constrain("after",i1(Q))}earlierThan(Q){return this.constrain("before",i1(Q))}}var SZ="Expected a non-empty brand name after #",JX=["draft-2020-12","draft-07"],jZ=(Q)=>`JSONSchema target '${Q}' is not supported (must be ${JX.map((X)=>`"${X}"`).join(" or ")})`,WX=(Q)=>{if(!n(JX,Q))H(jZ(Q));return Q},i1=(Q)=>typeof Q==="object"&&!(Q instanceof Date)?{...Q,exclusive:!0}:{rule:Q,exclusive:!0},N2=(Q,X)=>$(X,"root")?$(Q,"root")?Q.extends(X):X.allows(Q):$(Q,"root")?Q.hasUnit(X):X===Q,GX=(Q)=>{if(Q.hasKind("morph"))return null;if(Q.hasKind("intersection"))return Q.inner.structure??(Q.basis?.domain==="object"?Q.$.bindReference(F.intrinsic.emptyStructure):null);if(Q.isBasis()&&Q.domain==="object")return Q.$.bindReference(F.intrinsic.emptyStructure);return null},fZ=(Q)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
25
|
+
${Q}`,_X=(Q,X)=>`${Q} operand must be an object (was ${X})`;var L1=(Q,X)=>V(o2(Q),(Y,U)=>[U,X]);var bZ=(Q)=>typeof Q==="string"?{reference:Q}:Q,LX=(Q)=>Q instanceof q?F.intrinsic.never.internal:Q,yZ=M({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Q)=>Q.startsWith("$")?Q:`$ark.${Q}`},resolve:{}},normalize:bZ,defaults:{description:(Q)=>Q.reference},intersections:{alias:(Q,X,Y)=>Y.$.lazilyResolve(()=>LX(N(Q.resolution,X.resolution,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.reference}`),...L1("alias",(Q,X,Y)=>{if(X.isUnknown())return Q;if(X.isNever())return X;if(X.isBasis()&&!X.overlaps(F.intrinsic.object))return q.init("assignability",F.intrinsic.object,X);return Y.$.lazilyResolve(()=>LX(N(Q.resolution,X,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.id}`)})}});class HX extends a{expression=this.reference;structure=void 0;get resolution(){let Q=this._resolve();return p[this.id]=Q}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Q=this.reference,X=p[Q],Y=[];while($(X,"context")){if(Y.includes(X.id))return H(vZ(X.id,Y));Y.push(X.id),X=p[X.id]}if(!$(X,"root"))return C(`Unexpected resolution for reference ${this.reference}
|
|
26
26
|
Seen: [${Y.join("->")}]
|
|
27
|
-
Resolution: ${B(X)}`);return X}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Q=this.reference.slice(1),X=this.$.resolutions[Q];if(typeof X==="string")return X;if(
|
|
27
|
+
Resolution: ${B(X)}`);return X}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Q=this.reference.slice(1),X=this.$.resolutions[Q];if(typeof X==="string")return X;if($(X,"root"))return X.id;return C(`Unexpected resolution for reference ${this.reference}: ${B(X)}`)}get defaultShortDescription(){return m.object}innerToJsonSchema(Q){return this.resolution.toJsonSchemaRecurse(Q)}traverseAllows=(Q,X)=>{let Y=X.seen[this.reference];if(Y?.includes(Q))return!0;return X.seen[this.reference]=D(Y,Q),this.resolution.traverseAllows(Q,X)};traverseApply=(Q,X)=>{let Y=X.seen[this.reference];if(Y?.includes(Q))return;X.seen[this.reference]=D(Y,Q),this.resolution.traverseApply(Q,X)};compile(Q){let X=this.resolutionId;Q.if(`ctx.seen.${X} && ctx.seen.${X}.includes(data)`,()=>Q.return(!0)),Q.if(`!ctx.seen.${X}`,()=>Q.line(`ctx.seen.${X} = []`)),Q.line(`ctx.seen.${X}.push(data)`),Q.return(Q.invoke(X))}}var vZ=(Q,X)=>`Alias '${Q}' has a shallow resolution cycle: ${[...X,Q].join("->")}`,I2={implementation:yZ,Node:HX};class f1 extends a{traverseApply=(Q,X)=>{if(!this.traverseAllows(Q,X))X.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return R1(this.errorContext)}compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var kZ=M({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Q)=>typeof Q==="string"?{domain:Q}:k1(Q,"numberAllowsNaN")&&Q.domain!=="number"?H(e2.writeBadAllowNanMessage(Q.domain)):Q,applyConfig:(Q,X)=>Q.numberAllowsNaN===void 0&&Q.domain==="number"&&X.numberAllowsNaN?{...Q,numberAllowsNaN:!0}:Q,defaults:{description:(Q)=>m[Q.domain],actual:(Q)=>Number.isNaN(Q)?"NaN":m[b(Q)]},intersections:{domain:(Q,X)=>Q.domain==="number"&&X.domain==="number"?Q.numberAllowsNaN?X:Q:q.init("domain",Q,X)}});class FX extends f1{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Q)=>typeof Q==="number"&&!Number.isNaN(Q):(Q)=>b(Q)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return m[this.domain]}innerToJsonSchema(Q){if(this.domain==="bigint"||this.domain==="symbol")return Q.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var e2={implementation:kZ,Node:FX,writeBadAllowNanMessage:(Q)=>`numberAllowsNaN may only be specified with domain "number" (was ${Q})`};var gZ=M({kind:"intersection",hasAssociatedError:!0,normalize:(Q)=>{if(P(Q))return Q;let{structure:X,...Y}=Q,U=!!X,Z=X??{},W=V(Y,(G,_)=>{if(y(G,E4)){if(U)H(`Flattened structure key ${G} cannot be specified alongside a root 'structure' key.`);return Z[G]=_,[]}return[G,_]});if($(Z,"constraint")||!J1(Z))W.structure=Z;return W},finalizeInnerJson:({structure:Q,...X})=>u(Q,"object")?{...Q,...X}:X,keys:{domain:{child:!0,parse:(Q,X)=>X.$.node("domain",Q)},proto:{child:!0,parse:(Q,X)=>X.$.node("proto",Q)},structure:{child:!0,parse:(Q,X)=>X.$.node("structure",Q),serialize:(Q)=>{if(!Q.sequence?.minLength)return Q.collapsibleJson;let{sequence:X,...Y}=Q.collapsibleJson,{minVariadicLength:U,...Z}=X,W=Z.variadic&&Object.keys(Z).length===1?Z.variadic:Z;return{...Y,sequence:W}}},divisor:{child:!0,parse:x("divisor")},max:{child:!0,parse:x("max")},min:{child:!0,parse:x("min")},maxLength:{child:!0,parse:x("maxLength")},minLength:{child:!0,parse:x("minLength")},exactLength:{child:!0,parse:x("exactLength")},before:{child:!0,parse:x("before")},after:{child:!0,parse:x("after")},pattern:{child:!0,parse:x("pattern")},predicate:{child:!0,parse:x("predicate")}},reduce:(Q,X)=>qX({},Q,{$:X,invert:!1,pipe:!1}),defaults:{description:(Q)=>{if(Q.children.length===0)return"unknown";if(Q.structure)return Q.structure.description;let X=[];if(Q.basis&&!Q.prestructurals.some((Y)=>Y.impl.obviatesBasisDescription))X.push(Q.basis.description);if(Q.prestructurals.length){let Y=Q.prestructurals.slice().sort((U,Z)=>U.kind==="min"&&Z.kind==="max"?-1:0).map((U)=>U.description);X.push(...Y)}if(Q.inner.predicate)X.push(...Q.inner.predicate.map((Y)=>Y.description));return X.join(" and ")},expected:(Q)=>` ◦ ${Q.errors.map((X)=>X.expected).join(`
|
|
28
28
|
◦ `)}`,problem:(Q)=>`(${Q.actual}) must be...
|
|
29
|
-
${Q.expected}`},intersections:{intersection:(Q,X,Y)=>
|
|
29
|
+
${Q.expected}`},intersections:{intersection:(Q,X,Y)=>qX(Q.inner,X.inner,Y),...L1("intersection",(Q,X,Y)=>{if(Q.children.length===0)return X;let{domain:U,proto:Z,...W}=Q.inner,G=Z??U,_=G?N(G,X,Y):X;return _ instanceof q?_:Q?.basis?.equals(_)?Q:Q.$.node("intersection",{...W,[_.kind]:_},{prereduced:!0})})}});class AX extends a{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((Q)=>{if(!Q.isRefinement())return!1;if(n(v6,Q.kind))this.prestructurals.push(Q);return!0});structure=this.inner.structure;expression=xZ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Q){return this.children.reduce((X,Y)=>Y.isBasis()?Y.toJsonSchemaRecurse(Q):Y.reduceJsonSchema(X,Q),{})}traverseAllows=(Q,X)=>this.children.every((Y)=>Y.traverseAllows(Q,X));traverseApply=(Q,X)=>{let Y=X.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.prestructurals.length){for(let U=0;U<this.prestructurals.length-1;U++)if(this.prestructurals[U].traverseApply(Q,X),X.failFast&&X.currentErrorCount>Y)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.structure){if(this.structure.traverseApply(Q,X),X.currentErrorCount>Y)return}if(this.inner.predicate){for(let U=0;U<this.inner.predicate.length-1;U++)if(this.inner.predicate[U].traverseApply(Q,X),X.failFast&&X.currentErrorCount>Y)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(Q,X)}};compile(Q){if(Q.traversalKind==="Allows"){for(let X of this.children)Q.check(X);Q.return(!0);return}if(Q.initializeErrorCount(),this.basis){if(Q.check(this.basis),this.children.length>1)Q.returnIfFail()}if(this.prestructurals.length){for(let X=0;X<this.prestructurals.length-1;X++)Q.check(this.prestructurals[X]),Q.returnIfFailFast();if(Q.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)Q.returnIfFail()}if(this.structure){if(Q.check(this.structure),this.inner.predicate)Q.returnIfFail()}if(this.inner.predicate){for(let X=0;X<this.inner.predicate.length-1;X++)Q.check(this.inner.predicate[X]),Q.returnIfFail();Q.check(this.inner.predicate[this.inner.predicate.length-1])}}}var ZQ={implementation:gZ,Node:AX},xZ=(Q)=>{if(Q.structure?.expression)return Q.structure.expression;let X=Q.basis&&!Q.prestructurals.some((Z)=>Z.impl.obviatesBasisExpression)?Q.basis.nestableExpression:"",Y=Q.prestructurals.map((Z)=>Z.expression).join(" & "),U=`${X}${X?" ":""}${Y}`;if(U==="Array == 0")return"[]";return U||"unknown"},qX=(Q,X,Y)=>{let U={},Z=Q.proto??Q.domain,W=X.proto??X.domain,G=Z?W?N(Z,W,Y):Z:W;if(G instanceof q)return G;if(G)U[G.kind]=G;return l1({kind:"intersection",baseInner:U,l:d1(Q),r:d1(X),roots:[],ctx:Y})};var hZ=M({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},morphs:{parse:B1,serialize:(Q)=>Q.map((X)=>$(X,"root")?X.json:S(X))},declaredIn:{child:!1,serialize:(Q)=>Q.json},declaredOut:{child:!1,serialize:(Q)=>Q.json}},normalize:(Q)=>Q,defaults:{description:(Q)=>`a morph from ${Q.rawIn.description} to ${Q.rawOut?.description??"unknown"}`},intersections:{morph:(Q,X,Y)=>{if(!Q.hasEqualMorphs(X))return H(pZ(Q.expression,X.expression));let U=N(Q.rawIn,X.rawIn,Y);if(U instanceof q)return U;let Z={morphs:Q.morphs};if(Q.declaredIn||X.declaredIn){let W=N(Q.rawIn,X.rawIn,Y);if(W instanceof q)return W.throw();else Z.declaredIn=W}if(Q.declaredOut||X.declaredOut){let W=N(Q.rawOut,X.rawOut,Y);if(W instanceof q)return W.throw();else Z.declaredOut=W}return U.distribute((W)=>Y.$.node("morph",{...Z,in:W}),Y.$.parseSchema)},...L1("morph",(Q,X,Y)=>{let U=Q.inner.in?N(Q.inner.in,X,Y):X;return U instanceof q?U:U.equals(Q.inner.in)?Q:Y.$.node("morph",{...Q.inner,in:U})})}});class $X extends a{serializedMorphs=this.morphs.map(S);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=$(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??F.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??F.intrinsic.unknown.internal}declareIn(Q){return this.$.node("morph",{...this.inner,declaredIn:Q})}declareOut(Q){return this.$.node("morph",{...this.inner,declaredOut:Q})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(Q){return Q.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(Q),out:this.introspectableOut?.toJsonSchemaRecurse(Q)??null})}compile(Q){if(Q.traversalKind==="Allows"){if(!this.introspectableIn)return;Q.return(Q.invoke(this.introspectableIn));return}if(this.introspectableIn)Q.line(Q.invoke(this.introspectableIn));Q.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Q,X)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Q,X);traverseApply=(Q,X)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Q,X);X.queueMorphs(this.morphs)};hasEqualMorphs(Q){return A1(this.morphs,Q.morphs,{isEqual:(X,Y)=>X===Y||$(X,"root")&&$(Y,"root")&&X.equals(Y)})}}var WQ={implementation:hZ,Node:$X},pZ=(Q,X)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
30
30
|
Left: ${Q}
|
|
31
|
-
Right: ${X}`;var
|
|
31
|
+
Right: ${X}`;var uZ=M({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Q)=>H2(Q)??r(Q)},dateAllowsInvalid:{}},normalize:(Q)=>{let X=typeof Q==="string"?{proto:I1[Q]}:typeof Q==="function"?P(Q)?Q:{proto:Q}:typeof Q.proto==="string"?{...Q,proto:I1[Q.proto]}:Q;if(typeof X.proto!=="function")H(E2.writeInvalidSchemaMessage(X.proto));if(k1(X,"dateAllowsInvalid")&&X.proto!==Date)H(E2.writeBadInvalidDateMessage(X.proto));return X},applyConfig:(Q,X)=>{if(Q.dateAllowsInvalid===void 0&&Q.proto===Date&&X.dateAllowsInvalid)return{...Q,dateAllowsInvalid:!0};return Q},defaults:{description:(Q)=>Q.builtinName?Z4[Q.builtinName]:`an instance of ${Q.proto.name}`,actual:(Q)=>Q instanceof Date&&Q.toString()==="Invalid Date"?"an invalid Date":L2(Q)},intersections:{proto:(Q,X)=>Q.proto===Date&&X.proto===Date?Q.dateAllowsInvalid?X:Q:I6(Q.proto,X.proto)?Q:I6(X.proto,Q.proto)?X:q.init("proto",Q,X),domain:(Q,X)=>X.domain==="object"?Q:q.init("domain",F.intrinsic.object.internal,X)}});class zX extends f1{builtinName=H2(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Q)=>Q instanceof Date&&Q.toString()!=="Invalid Date":(Q)=>Q instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Q){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Q.fallback.date?.({code:"date",base:{}})??Q.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Q.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var E2={implementation:uZ,Node:zX,writeBadInvalidDateMessage:(Q)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Q.name})`,writeInvalidSchemaMessage:(Q)=>`instanceOf operand must be a function (was ${b(Q)})`};var mZ=M({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Q,X)=>{let Y=[];for(let U of Q){let Z=$(U,"root")?U.branches:X.$.parseSchema(U).branches;for(let W of Z)if(W.hasKind("morph")){let G=Y.findIndex((_)=>_.hasKind("morph")&&_.hasEqualMorphs(W));if(G===-1)Y.push(W);else{let _=Y[G];Y[G]=X.$.node("morph",{..._.inner,in:_.rawIn.rawOr(W.rawIn)})}}else Y.push(W)}if(!X.def.ordered)Y.sort((U,Z)=>U.hash<Z.hash?-1:1);return Y}}},normalize:(Q)=>K(Q)?{branches:Q}:Q,reduce:(Q,X)=>{let Y=aZ(Q);if(Y.length===1)return Y[0];if(Y.length===Q.branches.length)return;return X.node("union",{...Q,branches:Y},{prereduced:!0})},defaults:{description:(Q)=>Q.distribute((X)=>X.description,s1),expected:(Q)=>{let X=rQ(Q.errors,"propString"),Y=Object.entries(X).map(([U,Z])=>{let W=[];for(let L of Z)_1(W,L.expected);let G=s1(W),_=Z.every((L)=>L.actual===Z[0].actual)?Z[0].actual:B(Z[0].data);return`${U&&`${U} `}must be ${G}${_&&` (was ${_})`}`});return s1(Y)},problem:(Q)=>Q.expected,message:(Q)=>{if(Q.problem[0]==="[")return`value at ${Q.problem}`;return Q.problem}},intersections:{union:(Q,X,Y)=>{if(Q.isNever!==X.isNever)return q.init("presence",Q,X);let U;if(Q.ordered){if(X.ordered)H(Q8(Q.expression,X.expression));if(U=GQ(X.branches,Q.branches,Y),U instanceof q)U.invert()}else U=GQ(Q.branches,X.branches,Y);if(U instanceof q)return U;return Y.$.parseSchema(Q.ordered||X.ordered?{branches:U,ordered:!0}:{branches:U})},...L1("union",(Q,X,Y)=>{let U=GQ(Q.branches,[X],Y);if(U instanceof q)return U;if(U.length===1)return U[0];return Y.$.parseSchema(Q.ordered?{branches:U,ordered:!0}:{branches:U})})}});class BX extends a{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Q=[],X=-1;for(let Y of this.branches){if(Y.hasKind("unit")&&Y.domain==="boolean"){if(X===-1)X=Q.length,Q.push(Y);else Q[X]=F.intrinsic.boolean;continue}Q.push(Y)}return Q}unitBranches=this.branches.filter((Q)=>Q.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?nZ(this.discriminant):null;expression=this.distribute((Q)=>Q.nestableExpression,tZ);createBranchedOptimisticRootApply(){return(Q,X)=>{let Y=this.traverseOptimistic(Q);if(Y!==l)return Y;let U=new U1(Q,this.$.resolvedConfig);return this.traverseApply(Q,U),U.finalize(X)}}get shallowMorphs(){return this.branches.reduce((Q,X)=>_1(Q,X.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Q)=>Q.defaultShortDescription,s1)}innerToJsonSchema(Q){if(this.branchGroups.length===1&&this.branchGroups[0].equals(F.intrinsic.boolean))return{type:"boolean"};let X=this.branchGroups.map((Y)=>Y.toJsonSchemaRecurse(Q));if(X.every((Y)=>Object.keys(Y).length===1&&k1(Y,"const")))return{enum:X.map((Y)=>Y.const)};return{anyOf:X}}traverseAllows=(Q,X)=>this.branches.some((Y)=>Y.traverseAllows(Q,X));traverseApply=(Q,X)=>{let Y=[];for(let U=0;U<this.branches.length;U++){if(X.pushBranch(),this.branches[U].traverseApply(Q,X),!X.hasError()){if(this.branches[U].includesTransform)return X.queuedMorphs.push(...X.popBranch().queuedMorphs);return X.popBranch()}Y.push(X.popBranch().error)}X.errorFromNodeContext({code:"union",errors:Y,meta:this.meta})};traverseOptimistic=(Q)=>{for(let X=0;X<this.branches.length;X++){let Y=this.branches[X];if(Y.traverseAllows(Q)){if(Y.contextFreeMorph)return Y.contextFreeMorph(Q);return Q}}return l};compile(Q){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Q);let X=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")X=`typeof ${X} === "object" ? ${X} === null ? "null" : "object" : typeof ${X} === "function" ? "object" : typeof ${X}`;let Y=this.discriminant.cases,U=Object.keys(Y),{optimistic:Z}=Q;if(Q.optimistic=!1,Q.block(`switch(${X})`,()=>{for(let J in Y){let A=Y[J],O=J==="default"?J:`case ${J}`,R;if(A===!0)R=Z?"data":"true";else if(Z)if(A.rootApplyStrategy==="branchedOptimistic")R=Q.invoke(A,{kind:"Optimistic"});else if(A.contextFreeMorph)R=`${Q.invoke(A)} ? ${S(A.contextFreeMorph)}(data) : "${l}"`;else R=`${Q.invoke(A)} ? data : "${l}"`;else R=Q.invoke(A);Q.line(`${O}: return ${R}`)}return Q}),Q.traversalKind==="Allows"){Q.return(Z?`"${l}"`:!1);return}let W=s1(this.discriminant.kind==="domain"?U.map((J)=>{let A=J.slice(1,-1);return A==="function"?m.object:m[A]}):U),G=this.discriminant.path.map((J)=>typeof J==="symbol"?S(J):JSON.stringify(J)),_=JSON.stringify(W),L=this.discriminant.kind==="domain"?`${iZ}[${X}]`:`${sZ}(${X})`;Q.line(`ctx.errorFromNodeContext({
|
|
32
32
|
code: "predicate",
|
|
33
33
|
expected: ${_},
|
|
34
|
-
actual: ${
|
|
34
|
+
actual: ${L},
|
|
35
35
|
relativePath: [${G}],
|
|
36
36
|
meta: ${this.compiledMeta}
|
|
37
|
-
})`)}compileIndiscriminable(Q){if(Q.traversalKind==="Apply"){Q.const("errors","[]");for(let X of this.branches)Q.line("ctx.pushBranch()").line(Q.invoke(X)).if("!ctx.hasError()",()=>Q.return(X.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Q.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:X}=Q;Q.optimistic=!1;for(let Y of this.branches)Q.if(`${Q.invoke(Y)}`,()=>Q.return(X?Y.contextFreeMorph?`${S(Y.contextFreeMorph)}(data)`:"data":!0));Q.return(X?`"${
|
|
37
|
+
})`)}compileIndiscriminable(Q){if(Q.traversalKind==="Apply"){Q.const("errors","[]");for(let X of this.branches)Q.line("ctx.pushBranch()").line(Q.invoke(X)).if("!ctx.hasError()",()=>Q.return(X.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Q.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:X}=Q;Q.optimistic=!1;for(let Y of this.branches)Q.if(`${Q.invoke(Y)}`,()=>Q.return(X?Y.contextFreeMorph?`${S(Y.contextFreeMorph)}(data)`:"data":!0));Q.return(X?`"${l}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let Z=V(this.unitBranches,(W,G)=>[`${G.rawIn.serializedValue}`,G.hasKind("morph")?G:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:Z}}let Q=[];for(let Z=0;Z<this.branches.length-1;Z++){let W=this.branches[Z];for(let G=Z+1;G<this.branches.length;G++){let _=this.branches[G],L=i(W.rawIn,_.rawIn,W.$);if(!(L instanceof q))continue;for(let J of L){if(!J.kind||J.optional)continue;let A,O;if(J.kind==="domain"){let{l:f,r:F1}=J;A=`"${typeof f==="string"?f:f.domain}"`,O=`"${typeof F1==="string"?F1:F1.domain}"`}else if(J.kind==="unit")A=J.l.serializedValue,O=J.r.serializedValue;else continue;let R=Q.find((f)=>A1(f.path,J.path)&&f.kind===J.kind);if(!R)Q.push({kind:J.kind,cases:{[A]:{branchIndices:[Z],condition:J.l},[O]:{branchIndices:[G],condition:J.r}},path:J.path});else{if(R.cases[A])R.cases[A].branchIndices=_1(R.cases[A].branchIndices,Z);else R.cases[A]??={branchIndices:[Z],condition:J.l};if(R.cases[O])R.cases[O].branchIndices=_1(R.cases[O].branchIndices,G);else R.cases[O]??={branchIndices:[G],condition:J.r}}}}}let X=this.ordered?cZ(Q,this.branches):Q;if(!X.length)return null;let Y=lZ(X,this),U={};for(let Z in Y.best.cases){let W=dZ(Y,Z);if(W===null){U[Z]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((L,J)=>L.originalIndex-J.originalIndex);let G=W.map((L)=>L.branch),_=G.length===1?G[0]:this.$.node("union",this.ordered?{branches:G,ordered:!0}:G);Object.assign(this.referencesById,_.referencesById),U[Z]=_}if(Y.defaultEntries.length){let Z=Y.defaultEntries.map((W)=>W.branch);U.default=this.$.node("union",this.ordered?{branches:Z,ordered:!0}:Z,{prereduced:!0}),Object.assign(this.referencesById,U.default.referencesById)}return Object.assign(Y.location,{cases:U})}}var lZ=(Q,X)=>{let U=Q.sort((G,_)=>G.path.length===_.path.length?Object.keys(_.cases).length-Object.keys(G.cases).length:G.path.length-_.path.length)[0],Z={kind:U.kind,path:U.path,optionallyChainedPropString:MX(U.path)},W=X.branches.map((G,_)=>({originalIndex:_,branch:G}));return{best:U,location:Z,defaultEntries:W,node:X}},dZ=(Q,X)=>{let Y=Q.best.cases[X],U=oZ(Y.condition,Q.location.path,Q.node.$),Z=[],W=[];for(let G=0;G<Q.defaultEntries.length;G++){let _=Q.defaultEntries[G];if(Y.branchIndices.includes(_.originalIndex)){let L=OX(Q.node.branches[_.originalIndex],Q.location);if(L===null)Z=null;else Z?.push({originalIndex:_.originalIndex,branch:L})}else if(_.branch.hasKind("alias")&&U.hasKind("domain")&&U.domain==="object")Z?.push(_);else{if(_.branch.rawIn.overlaps(U)){let L=OX(_.branch,Q.location);Z?.push({originalIndex:_.originalIndex,branch:L})}W.push(_)}}return Q.defaultEntries=W,Z},cZ=(Q,X)=>{return Q.filter((U)=>{let Z=Object.values(U.cases).map((W)=>W.branchIndices);for(let W=0;W<Z.length-1;W++){let G=Z[W];for(let _=W+1;_<Z.length;_++){let L=Z[_];for(let J of G)for(let A of L)if(J>A){if(X[J].overlaps(X[A]))return!1}}}return!0})},oZ=(Q,X,Y)=>{let U=Q==="undefined"?Y.node("unit",{unit:void 0}):Q==="null"?Y.node("unit",{unit:null}):Q==="boolean"?Y.units([!0,!1]):Q;for(let Z=X.length-1;Z>=0;Z--){let W=X[Z];U=Y.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...sQ(W).map((G)=>({})),U]}:{domain:"object",required:[{key:W,value:U}]})}return U},MX=(Q)=>Q.reduce((X,Y)=>X+y6(Y,!0),"data"),iZ=S(tQ),sZ=S(B),_Q={implementation:mZ,Node:BX},nZ=(Q)=>({kind:Q.kind,path:Q.path.map((X)=>typeof X==="string"?X:Y1(X)),cases:V(Q.cases,(X,Y)=>[X,Y===!0?Y:Y.hasKind("union")&&Y.discriminantJson?Y.discriminantJson:Y.json])}),rZ={delimiter:" | ",finalDelimiter:" | "},tZ=(Q)=>s1(Q,rZ),s1=(Q,X)=>{let Y=X?.delimiter??", ",U=X?.finalDelimiter??" or ";if(Q.length===0)return"never";if(Q.length===1)return Q[0];if(Q.length===2&&Q[0]==="false"&&Q[1]==="true"||Q[0]==="true"&&Q[1]==="false")return"boolean";let Z={},W=Q.filter((_)=>Z[_]?!1:Z[_]=!0),G=W.pop();return`${W.join(Y)}${W.length?U:""}${G}`},GQ=(Q,X,Y)=>{let U=X.map(()=>[]);for(let W=0;W<Q.length;W++){let G={};for(let _=0;_<X.length;_++){if(U[_]===null)continue;if(Q[W].equals(X[_])){U[_]=null,G={};break}let L=N(Q[W],X[_],Y);if(L instanceof q)continue;if(L.equals(Q[W])){U[_].push(Q[W]),G={};break}if(L.equals(X[_]))U[_]=null;else G[_]=L}for(let _ in G)U[_][W]=G[_]}let Z=U.flatMap((W,G)=>W?.flatMap((_)=>_.branches)??X[G]);return Z.length===0?q.init("union",Q,X):Z},aZ=({branches:Q,ordered:X})=>{if(Q.length<2)return Q;let Y=Q.map(()=>!0);for(let U=0;U<Q.length;U++)for(let Z=U+1;Z<Q.length&&Y[U]&&Y[Z];Z++){if(Q[U].equals(Q[Z])){Y[Z]=!1;continue}let W=i(Q[U].rawIn,Q[Z].rawIn,Q[0].$);if(W instanceof q)continue;if(!X)eZ(Q[U],Q[Z]);if(W.equals(Q[U].rawIn))Y[U]=!!X;else if(W.equals(Q[Z].rawIn))Y[Z]=!1}return Q.filter((U,Z)=>Y[Z])},eZ=(Q,X)=>{if(!Q.includesTransform&&!X.includesTransform)return;if(!A1(Q.shallowMorphs,X.shallowMorphs))H(VX(Q.expression,X.expression));if(!A1(Q.flatMorphs,X.flatMorphs,{isEqual:(Y,U)=>Y.propString===U.propString&&(Y.node.hasKind("morph")&&U.node.hasKind("morph")?Y.node.hasEqualMorphs(U.node):Y.node.hasKind("intersection")&&U.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===U.node.structure?.structuralMorphRef:!1)}))H(VX(Q.expression,X.expression))},OX=(Q,X)=>Q.transform((Y,U)=>{if(Y==="domain"||Y==="unit")return null;return U},{shouldTransform:(Y,U)=>{let Z=MX(U.path);if(!X.optionallyChainedPropString.startsWith(Z))return!1;if(Y.hasKind("domain")&&Y.domain==="object")return!0;if((Y.hasKind("domain")||X.kind==="unit")&&Z===X.optionallyChainedPropString)return!0;return Y.children.length!==0&&Y.kind!=="index"}}),VX=(Q,X)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
38
38
|
Left: ${Q}
|
|
39
|
-
Right: ${X}`,
|
|
39
|
+
Right: ${X}`,Q8=(Q,X)=>`The intersection of two ordered unions is indeterminate:
|
|
40
40
|
Left: ${Q}
|
|
41
|
-
Right: ${X}`;var nZ=M({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():r(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>B(Q.unit),problem:({expected:Q,actual:X})=>`${Q===X?`must be reference equal to ${Q} (serialized to the same value)`:`must be ${Q} (was ${X})`}`},intersections:{unit:(Q,X)=>q.init("unit",Q,X),...L1("unit",(Q,X)=>{if(X.allows(Q.unit))return Q;let Y=X.hasKind("intersection")?X.basis:X;if(Y){let U=Y.hasKind("domain")?Y:F.intrinsic.object;if(Q.domain!==U.domain){let Z=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:F.intrinsic[Q.domain];return q.init("domain",Z,U)}}return q.init("assignability",Q,X.hasKind("intersection")?X.children.find((U)=>!U.allows(Q.unit)):X)})}});class OX extends b1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=zX(this.unit,this.serializedValue);compiledNegation=zX(this.unit,this.serializedValue,"negated");expression=B(this.unit);domain=y(this.unit);get defaultShortDescription(){return this.domain==="object"?u.object:this.description}innerToJsonSchema(Q){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Q.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Q)=>Q instanceof Date&&Q.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Q)=>Number.isNaN(Q):(Q)=>Q===this.unit}var GQ={implementation:nZ,Node:OX},zX=(Q,X,Y)=>{if(Q instanceof Date){let U=`data instanceof Date && data.toISOString() === ${X}`;return Y?`!(${U})`:U}if(Number.isNaN(Q))return`${Y?"!":""}Number.isNaN(data)`;return`data ${Y?"!":"="}== ${X}`};var rZ=M({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,X)=>{let Y=X.$.parseSchema(Q);if(!Y.extends(F.intrinsic.key))return L(aZ(Y.expression));let U=Y.branches.filter((Z)=>Z.hasKind("unit"));if(U.length)return L(tZ(U.map((Z)=>B(Z.unit))));return Y}},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`[${Q.signature.expression}]: ${Q.value.description}`},intersections:{index:(Q,X,Y)=>{if(Q.signature.equals(X.signature)){let U=N(Q.value,X.value,Y),Z=U instanceof q?F.intrinsic.never.internal:U;return Y.$.node("index",{signature:Q.signature,value:Z})}if(Q.signature.extends(X.signature)&&Q.value.subsumes(X.value))return X;if(X.signature.extends(Q.signature)&&X.value.subsumes(Q.value))return Q;return null}}});class VX extends t{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.signature,...Q.path],Q.node)),Z1([this.signature],this.value));traverseAllows=(Q,X)=>N1(Q).every((Y)=>{if(this.signature.traverseAllows(Y[0],X))return c(Y[0],()=>this.value.traverseAllows(Y[1],X),X);return!0});traverseApply=(Q,X)=>{for(let Y of N1(Q))if(this.signature.traverseAllows(Y[0],X))c(Y[0],()=>this.value.traverseApply(Y[1],X),X)};_transform(Q,X){X.path.push(this.signature);let Y=super._transform(Q,X);return X.path.pop(),Y}compile(){}}var _Q={implementation:rZ,Node:VX},tZ=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,aZ=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var eZ=M({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}: ${Q.value.description}`,expected:(Q)=>Q.missingValueDescription,actual:()=>"missing"},intersections:{required:C2,optional:C2}});class BX extends w2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=R1(this.errorContext)}var JQ={implementation:eZ,Node:BX};var Q8=M({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},optionals:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},defaultables:{child:(Q)=>Q.map((X)=>X[0]),parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>{let U=X.$.parseSchema(Y[0]);return P2(U,Y[1],null),[U,Y[1]]})},serialize:(Q)=>Q.map((X)=>[X[0].collapsibleJson,r(X[1])]),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optionals=Y.map((U)=>U[0].rawIn);return}X.prefix=Y.map((U)=>U[0].rawOut);return}},variadic:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q,X)},minVariadicLength:{parse:(Q)=>Q===0?void 0:Q},postfix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}}},normalize:(Q)=>{if(typeof Q==="string")return{variadic:Q};if("variadic"in Q||"prefix"in Q||"defaultables"in Q||"optionals"in Q||"postfix"in Q||"minVariadicLength"in Q){if(Q.postfix?.length){if(!Q.variadic)return L(Z8);if(Q.optionals?.length||Q.defaultables?.length)return L(HQ)}if(Q.minVariadicLength&&!Q.variadic)return L("minVariadicLength may not be specified without a variadic element");return Q}return{variadic:Q}},reduce:(Q,X)=>{let Y=Q.minVariadicLength??0,U=Q.prefix?.slice()??[],Z=Q.defaultables?.slice()??[],W=Q.optionals?.slice()??[],G=Q.postfix?.slice()??[];if(Q.variadic){while(W[W.length-1]?.equals(Q.variadic))W.pop();if(W.length===0&&Z.length===0)while(U[U.length-1]?.equals(Q.variadic))U.pop(),Y++;while(G[0]?.equals(Q.variadic))G.shift(),Y++}else if(W.length===0&&Z.length===0)U.push(...G.splice(0));if(Y!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==U.length)return X.node("sequence",{...Q,prefix:U,defaultables:Z,optionals:W,postfix:G,minVariadicLength:Y},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((Y)=>Y.kind==="defaultables"?`${Y.node.nestableExpression} = ${B(Y.default)}`:Y.kind==="optionals"?`${Y.node.nestableExpression}?`:Y.kind==="variadic"?`...${Y.node.nestableExpression}[]`:Y.node.expression).join(", ")}]`}},intersections:{sequence:(Q,X,Y)=>{let U=S2({l:Q.tuple,r:X.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:Y}),Z=U.disjoint.length===0?[U,...U.fixedVariants]:U.fixedVariants;return Z.length===0?U.disjoint:Z.length===1?Y.$.node("sequence",MX(Z[0].result)):Y.$.node("union",Z.map((W)=>({proto:Array,sequence:MX(W.result)})))}}});class DX extends t{impliedBasis=F.intrinsic.Array.internal;tuple=U8(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Q)=>{if(Q.kind==="defaultables"||Q.kind==="optionals")return this.defaultablesAndOptionals.push(Q.node),!0;return Q.kind==="prefix"});variadicOrPostfix=q1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return g6(this.flatRefs,this.prevariadic.flatMap((Q,X)=>D(Q.node.flatRefs.map((Y)=>Z1([`${X}`,...Y.path],Y.node)),Z1([`${X}`],Q.node)))),g6(this.flatRefs,this.variadicOrPostfix.flatMap((Q)=>D(Q.flatRefs.map((X)=>Z1([F.intrinsic.nonNegativeIntegerString.internal,...X.path],X.node)),Z1([F.intrinsic.nonNegativeIntegerString.internal],Q)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=Y8(this);defaultValueMorphsReference=this.defaultValueMorphs.length?S(this.defaultValueMorphs):void 0;elementAtIndex(Q,X){if(X<this.prevariadic.length)return this.tuple[X];let Y=Q.length-this.postfixLength;if(X>=Y)return{kind:"postfix",node:this.postfix[X-Y]};return{kind:"variadic",node:this.variadic??C(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Q,X)=>{for(let Y=0;Y<Q.length;Y++)if(!this.elementAtIndex(Q,Y).node.traverseAllows(Q[Y],X))return!1;return!0};traverseApply=(Q,X)=>{let Y=0;for(;Y<Q.length;Y++)c(Y,()=>this.elementAtIndex(Q,Y).node.traverseApply(Q[Y],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix)for(let[X,Y]of this.prefix.entries())Q.traverseKey(`${X}`,`data[${X}]`,Y);for(let[X,Y]of this.defaultablesAndOptionals.entries()){let U=`${X+this.prefixLength}`;Q.if(`${U} >= data.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(U,`data[${U}]`,Y)}if(this.variadic){if(this.postfix)Q.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Q.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Q.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[X,Y]of this.postfix.entries()){let U=`firstPostfixIndex + ${X}`;Q.traverseKey(U,`data[${U}]`,Y)}}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,X){X.path.push(F.intrinsic.nonNegativeIntegerString.internal);let Y=super._transform(Q,X);return X.path.pop(),Y}expression=this.description;reduceJsonSchema(Q,X){let Y=X.target==="draft-07";if(this.prevariadic.length){let U=this.prevariadic.map((Z)=>{let W=Z.node.toJsonSchemaRecurse(X);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;W.default=F.intrinsic.jsonData.allows(G)?G:X.fallback.defaultValue({code:"defaultValue",base:W,value:G})}return W});if(Y)Q.items=U;else Q.prefixItems=U}if(this.minLength)Q.minItems=this.minLength;if(this.variadic){let U=this.variadic.toJsonSchemaRecurse(X);if(Y&&this.prevariadic.length)Q.additionalItems=U;else Q.items=U;if(this.maxLength)Q.maxItems=this.maxLength;if(this.postfix){let Z=this.postfix.map((W)=>W.toJsonSchemaRecurse(X));Q=X.fallback.arrayPostfix({code:"arrayPostfix",base:Q,elements:Z})}}else{if(Y)Q.additionalItems=!1;else Q.items=!1;delete Q.maxItems}return Q}}var X8={},Y8=(Q)=>{if(!Q.defaultables)return[];let X=[],Y="[",U=Q.prefixLength+Q.defaultablesLength-1;for(let Z=Q.prefixLength;Z<=U;Z++){let[W,G]=Q.defaultables[Z-Q.prefixLength];X.push(XQ(Z,W,G)),Y+=`${Z}: ${W.id} = ${r(G)}, `}return Y+="]",X8[Y]??=X},LQ={implementation:Q8,Node:DX},U8=(Q)=>{let X=[];if(Q.prefix)for(let Y of Q.prefix)X.push({kind:"prefix",node:Y});if(Q.defaultables)for(let[Y,U]of Q.defaultables)X.push({kind:"defaultables",node:Y,default:U});if(Q.optionals)for(let Y of Q.optionals)X.push({kind:"optionals",node:Y});if(Q.variadic)X.push({kind:"variadic",node:Q.variadic});if(Q.postfix)for(let Y of Q.postfix)X.push({kind:"postfix",node:Y});return X},MX=(Q)=>Q.reduce((X,Y)=>{if(Y.kind==="variadic")X.variadic=Y.node;else if(Y.kind==="defaultables")X.defaultables=D(X.defaultables,[[Y.node,Y.default]]);else X[Y.kind]=D(X[Y.kind],Y.node);return X},{}),HQ="A postfix required element cannot follow an optional or defaultable element",Z8="A postfix element requires a variadic element",S2=(Q)=>{let[X,...Y]=Q.l,[U,...Z]=Q.r;if(!X||!U)return Q;let W=Y[Y.length-1]?.kind==="postfix",G=Z[Z.length-1]?.kind==="postfix",_=X.kind==="prefix"||U.kind==="prefix"?"prefix":X.kind==="postfix"||U.kind==="postfix"?"postfix":X.kind==="variadic"&&U.kind==="variadic"?"variadic":W||G?"prefix":X.kind==="defaultables"||U.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&U.kind==="variadic"&&G){let O=S2({...Q,fixedVariants:[],r:Z.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}else if(U.kind==="prefix"&&X.kind==="variadic"&&W){let O=S2({...Q,fixedVariants:[],l:Y.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}let H=N(X.node,U.node,Q.ctx);if(H instanceof q)if(_==="prefix"||_==="postfix")Q.disjoint.push(...H.withPrefixKey(_==="prefix"?Q.result.length:`-${Y.length+1}`,TX(X)&&TX(U)?"required":"optional")),Q.result=[...Q.result,{kind:_,node:F.intrinsic.never.internal}];else if(_==="optionals"||_==="defaultables")return Q;else return S2({...Q,fixedVariants:[],l:Y.map((O)=>({...O,kind:"prefix"})),r:Y.map((O)=>({...O,kind:"prefix"}))});else if(_==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)L(QQ(X.default,U.default));Q.result=[...Q.result,{kind:_,node:H,default:X.kind==="defaultables"?X.default:U.kind==="defaultables"?U.default:C(`Unexpected defaultable intersection from ${X.kind} and ${U.kind} elements.`)}]}else Q.result=[...Q.result,{kind:_,node:H}];let J=Q.l.length,$=Q.r.length;if(X.kind!=="variadic"||J>=$&&(U.kind==="variadic"||$===1))Q.l=Y;if(U.kind!=="variadic"||$>=J&&(X.kind==="variadic"||J===1))Q.r=Z;return S2(Q)},TX=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var KX=(Q)=>(X)=>{if(X.props.length||X.index){let Y=X.index?.map((Z)=>Z[Q])??[];for(let Z of X.props)Y.push(Z[Q]);if(X.undeclared)Y.push(`+ (undeclared): ${X.undeclared}`);let U=`{ ${Y.join(", ")} }`;return X.sequence?`${U} & ${X.sequence.description}`:U}return X.sequence?.description??"{}"},W8=KX("description"),G8=KX("expression"),RX=(Q,X,Y)=>{let U=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=o(Q.value,X.value,Y);if(Z instanceof q)return U==="optional"?Y.node("optional",{key:Q.key,value:F.intrinsic.never.internal}):Z.withPrefixKey(Q.key,Q.kind);return null},_8=M({kind:"structure",hasAssociatedError:!1,normalize:(Q)=>Q,applyConfig:(Q,X)=>{if(!Q.undeclared&&X.onUndeclaredKey!=="ignore")return{...Q,undeclared:X.onUndeclaredKey};return Q},keys:{required:{child:!0,parse:g("required"),reduceIo:(Q,X,Y)=>{X.required=D(X.required,Y.map((U)=>Q==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:g("optional"),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optional=Y.map((U)=>U.rawIn);return}for(let U of Y)X[U.outProp.kind]=D(X[U.outProp.kind],U.outProp.rawOut)}},index:{child:!0,parse:g("index")},sequence:{child:!0,parse:g("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q,reduceIo:(Q,X,Y)=>{if(Y==="reject"){X.undeclared="reject";return}if(Q==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:W8},intersections:{structure:(Q,X,Y)=>{let U={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let H=Q.keyof();for(let J of X.requiredKeys)if(!H.allows(J))W.add("presence",F.intrinsic.never.internal,X.propsByKey[J].value,{path:[J]});if(Z.optional)Z.optional=Z.optional.filter((J)=>H.allows(J.key));if(Z.index)Z.index=Z.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=Q6($,J.value,Y.$);if(O.required)Z.required=q1(Z.required,O.required);if(O.optional)Z.optional=q1(Z.optional,O.optional);return O.index??[]})}if(X.undeclared){let H=X.keyof();for(let J of Q.requiredKeys)if(!H.allows(J))W.add("presence",Q.propsByKey[J].value,F.intrinsic.never.internal,{path:[J]});if(U.optional)U.optional=U.optional.filter((J)=>H.allows(J.key));if(U.index)U.index=U.index.flatMap((J)=>{if(J.signature.extends(H))return J;let $=o(H,J.signature,Y.$);if($ instanceof q)return[];let O=Q6($,J.value,Y.$);if(O.required)U.required=q1(U.required,O.required);if(O.optional)U.optional=q1(U.optional,O.optional);return O.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let _=l1({kind:"structure",baseInner:G,l:d1(U),r:d1(Z),roots:[],ctx:Y});if(_ instanceof q)W.push(..._);if(W.length)return W;return _}},reduce:(Q,X)=>{if(!Q.required&&!Q.optional)return;let Y={},U=!1,Z=Q.optional?[...Q.optional]:[];if(Q.required)for(let W=0;W<Q.required.length;W++){let G=Q.required[W];if(G.key in Y)L(wX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=RX(G,_,X);if(H instanceof q)return H}}if(Q.optional)for(let W=0;W<Q.optional.length;W++){let G=Q.optional[W];if(G.key in Y)L(wX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let H=RX(G,_,X);if(H instanceof q)return H;if(H!==null)Z[W]=H,U=!0}}if(U)return X.node("structure",{...Q,optional:Z},{prereduced:!0})}});class PX extends t{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=q1(this.required,this.optional);propsByKey=V(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=G8(this);requiredKeys=this.required?.map((Q)=>Q.key)??[];optionalKeys=this.optional?.map((Q)=>Q.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:X}of this.index)Q=Q.concat(X.branches);return this._keyof=this.$.node("union",Q)}map(Q){return this.$.node("structure",this.props.flatMap(Q).reduce((X,Y)=>{let U=this.propsByKey[Y.key];if(P(Y)){if(Y.kind!=="required"&&Y.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${Y.kind})`);return X[Y.kind]=D(X[Y.kind],Y),X}let Z=Y.kind??U?.kind??"required",W=V(Y,(G,_)=>(G in K2.implementation.keys)?[G,_]:[]);return X[Z]=D(X[Z],this.$.node(Z,W)),X},{}))}assertHasKeys(Q){let X=Q.filter((Y)=>!N2(Y,this.keyof()));if(X.length)return L(CX(this.expression,X))}get(Q,...X){let Y,U=!1,Z=F8(Q);if((typeof Z==="string"||typeof Z==="symbol")&&this.propsByKey[Z])Y=this.propsByKey[Z].value,U=this.propsByKey[Z].required;if(this.index){for(let G of this.index)if(N2(Z,G.signature))Y=Y?.and(G.value)??G.value}if(this.sequence&&N2(Z,F.intrinsic.nonNegativeIntegerString))if(A(Z,"root")){if(this.sequence.variadic)Y=Y?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Z);if(G<this.sequence.prevariadic.length){let _=this.sequence.prevariadic[G].node;Y=Y?.and(_)??_,U||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let _=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(_)??_}}if(!Y){if(this.sequence?.variadic&&A(Z,"root")&&Z.extends(F.intrinsic.number))return L(q8(Z.expression,this.sequence.expression));return L(CX(this.expression,[Z]))}let W=Y.get(...X);return U?W:W.or(F.intrinsic.undefined)}pick(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("pick",Q))}omit(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("omit",Q))}optionalize(){let{required:Q,...X}=this.inner;return this.$.node("structure",{...X,optional:this.props.map((Y)=>Y.hasKind("required")?this.$.node("optional",Y.inner):Y)})}require(){let{optional:Q,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((Y)=>Y.hasKind("optional")?{key:Y.key,value:Y.value}:Y)})}merge(Q){let X=this.filterKeys("omit",[Q.keyof()]);if(Q.required)X.required=D(X.required,Q.required);if(Q.optional)X.optional=D(X.optional,Q.optional);if(Q.index)X.index=D(X.index,Q.index);if(Q.sequence)X.sequence=Q.sequence;if(Q.undeclared)X.undeclared=Q.undeclared;else delete X.undeclared;return this.$.node("structure",X)}filterKeys(Q,X){let Y=l2(this.inner),U=(Z)=>{let W=X.some((G)=>N2(Z,G));return Q==="pick"?W:!W};if(Y.required)Y.required=Y.required.filter((Z)=>U(Z.key));if(Y.optional)Y.optional=Y.optional.filter((Z)=>U(Z.key));if(Y.index)Y.index=Y.index.filter((Z)=>U(Z.signature));return Y}traverseAllows=(Q,X)=>this._traverse("Allows",Q,X);traverseApply=(Q,X)=>this._traverse("Apply",Q,X);_traverse=(Q,X,Y)=>{let U=Y?.currentErrorCount??0;for(let Z=0;Z<this.props.length;Z++)if(Q==="Allows"){if(!this.props[Z].traverseAllows(X,Y))return!1}else if(this.props[Z].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(X,Y))return!1}else if(this.sequence.traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1}if(this.index||this.undeclared==="reject"){let Z=Object.keys(X);Z.push(...Object.getOwnPropertySymbols(X));for(let W=0;W<Z.length;W++){let G=Z[W];if(this.index){for(let _ of this.index)if(_.signature.traverseAllows(G,Y)){if(Q==="Allows"){if(!c(G,()=>_.value.traverseAllows(X[G],Y),Y))return!1}else if(c(G,()=>_.value.traverseApply(X[G],Y),Y),Y.failFast&&Y.currentErrorCount>U)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if(Q==="Allows")return!1;if(Y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),Y.failFast)return!1}}}if(this.structuralMorph&&Y&&!Y.hasError())Y.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Q)=>Q.hasDefault())??[])}declaresKey=(Q)=>(Q in this.propsByKey)||this.index?.some((X)=>X.signature.allows(Q))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Q);_compileDeclaresKey(Q){let X=[];if(this.props.length)X.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Y of this.index)X.push(Q.invoke(Y.signature,{kind:"Allows",arg:"k"}));if(this.sequence)X.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return X.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",L8(this))}structuralMorphRef=this.structuralMorph&&S(this.structuralMorph);compile(Q){if(Q.traversalKind==="Apply")Q.initializeErrorCount();for(let X of this.props)if(Q.check(X),Q.traversalKind==="Apply")Q.returnIfFailFast();if(this.sequence){if(Q.check(this.sequence),Q.traversalKind==="Apply")Q.returnIfFailFast()}if(this.index||this.undeclared==="reject")Q.const("keys","Object.keys(data)"),Q.line("keys.push(...Object.getOwnPropertySymbols(data))"),Q.for("i < keys.length",()=>this.compileExhaustiveEntry(Q));if(Q.traversalKind==="Allows")return Q.return(!0);if(this.structuralMorphRef)Q.if("ctx && !ctx.hasError()",()=>{return Q.line("ctx.queueMorphs(["),H8(Q,this),Q.line("])")})}compileExhaustiveEntry(Q){if(Q.const("k","keys[i]"),this.index)for(let X of this.index)Q.if(`${Q.invoke(X.signature,{arg:"k",kind:"Allows"})}`,()=>Q.traverseKey("k","data[k]",X.value));if(this.undeclared==="reject")Q.if(`!(${this._compileDeclaresKey(Q)})`,()=>{if(Q.traversalKind==="Allows")return Q.return(!1);return Q.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Q.return())});return Q}reduceJsonSchema(Q,X){switch(Q.type){case"object":return this.reduceObjectJsonSchema(Q,X);case"array":let Y=this.sequence?.reduceJsonSchema(Q,X)??Q;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:Y,object:this.reduceObjectJsonSchema({type:"object"},X)});return Y;default:return E.throwInternalOperandError("structure",Q)}}reduceObjectJsonSchema(Q,X){if(this.props.length){Q.properties={};for(let Y of this.props){let U=Y.value.toJsonSchemaRecurse(X);if(typeof Y.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Q,key:Y.key,value:U,optional:Y.optional});continue}if(Y.hasDefault()){let Z=typeof Y.default==="function"?Y.default():Y.default;U.default=F.intrinsic.jsonData.allows(Z)?Z:X.fallback.defaultValue({code:"defaultValue",base:U,value:Z})}Q.properties[Y.key]=U}if(this.requiredKeys.length&&Q.properties)Q.required=this.requiredKeys.filter((Y)=>typeof Y==="string"&&(Y in Q.properties))}if(this.index)for(let Y of this.index){let U=Y.value.toJsonSchemaRecurse(X);if(Y.signature.equals(F.intrinsic.string)){Q.additionalProperties=U;continue}for(let Z of Y.signature.branches){if(!Z.extends(F.intrinsic.string)){Q=X.fallback.symbolKey({code:"symbolKey",base:Q,key:null,value:U,optional:!1});continue}let W={type:"string"};if(Z.hasKind("morph"))W=X.fallback.morph({code:"morph",base:Z.rawIn.toJsonSchemaRecurse(X),out:Z.rawOut.toJsonSchemaRecurse(X)});if(!Z.hasKind("intersection"))return C(`Unexpected index branch kind ${Z.kind}.`);let{pattern:G}=Z.inner;if(G){let _=Object.assign(W,{pattern:G[0].rule});for(let H=1;H<G.length;H++)W=X.fallback.patternIntersection({code:"patternIntersection",base:_,pattern:G[H].rule});Q.patternProperties??={},Q.patternProperties[_.pattern]=U}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var FQ={},J8=(Q)=>{let X="";for(let Y=0;Y<Q.defaultable.length;Y++)X+=Q.defaultable[Y].defaultValueMorphRef;if(Q.sequence?.defaultValueMorphsReference)X+=Q.sequence?.defaultValueMorphsReference;if(Q.undeclared==="delete"){if(X+="delete !(",Q.required)for(let Y of Q.required)X+=Y.compiledKey+" | ";if(Q.optional)for(let Y of Q.optional)X+=Y.compiledKey+" | ";if(Q.index)for(let Y of Q.index)X+=Y.signature.id+" | ";if(Q.sequence)if(Q.sequence.maxLength===null)X+=z.nonNegativeIntegerString.id;else for(let Y=0;Y<Q.sequence.tuple.length;Y++)X+=Y+" | ";X+=")"}return X},L8=(Q)=>{let X=J8(Q);if(!X)return;if(FQ[X])return FQ[X];let Y=(U,Z)=>{for(let W=0;W<Q.defaultable.length;W++)if(!(Q.defaultable[W].key in U))Q.defaultable[W].defaultValueMorph(U,Z);if(Q.sequence?.defaultables)for(let W=U.length-Q.sequence.prefixLength;W<Q.sequence.defaultables.length;W++)Q.sequence.defaultValueMorphs[W](U,Z);if(Q.undeclared==="delete"){for(let W in U)if(!Q.declaresKey(W))delete U[W]}return U};return FQ[X]=Y},H8=(Q,X)=>{let U=`(data${X.defaultable.some((Z)=>Z.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((Z)=>Z.length===2)?", ctx":""})`;return Q.block(`${U} => `,(Z)=>{for(let W=0;W<X.defaultable.length;W++){let{serializedKey:G,defaultValueMorphRef:_}=X.defaultable[W];Z.if(`!(${G} in data)`,(H)=>H.line(`${_}${U}`))}if(X.sequence?.defaultables)Z.for(`i < ${X.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${X.sequence.prefixLength}`);if(X.undeclared==="delete")Z.forIn("data",(W)=>W.if(`!(${X._compileDeclaresKey(W)})`,(G)=>G.line("delete data[k]")));return Z.return("data")})},qQ={implementation:_8,Node:PX},F8=(Q)=>{if(A(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},q8=(Q,X)=>`${Q} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,Q6=(Q,X,Y)=>{let[U,Z]=mQ(Q.branches,(G)=>G.hasKind("unit"));if(!U.length)return{index:Y.node("index",{signature:Q,value:X})};let W={};for(let G of U){let _=Y.node("required",{key:G.unit,value:X});W[_.kind]=D(W[_.kind],_)}if(Z.length)W.index=Y.node("index",{signature:Z,value:X});return W},$8=(Q)=>A(Q,"root")?Q.expression:B(Q),CX=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map($8).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,wX=(Q)=>`Duplicate key ${Y1(Q)}`;var o1={...o4,alias:E2.implementation,domain:e2.implementation,unit:GQ.implementation,proto:I2.implementation,union:WQ.implementation,morph:UQ.implementation,intersection:YQ.implementation,divisor:m6.implementation,pattern:r6.implementation,predicate:u6.implementation,required:JQ.implementation,optional:K2.implementation,index:_Q.implementation,sequence:LQ.implementation,structure:qQ.implementation};F.defaultConfig=tQ(Object.assign(V(o1,(Q,X)=>[Q,X.defaults]),{jitless:U4(),clone:Q4,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:E.defaultConfig}));F.resolvedConfig=B2(F.defaultConfig,F.config);var a4={...i4,alias:E2.Node,domain:e2.Node,unit:GQ.Node,proto:I2.Node,union:WQ.Node,morph:UQ.Node,intersection:YQ.Node,divisor:m6.Node,pattern:r6.Node,predicate:u6.Node,required:JQ.Node,optional:K2.Node,index:_Q.Node,sequence:LQ.Node,structure:qQ.Node};class n1 extends R6{get[x](){return"module"}}var $Q=(Q,X)=>new n1(V(Q,(Y,U)=>[Y,A(U,"module")?$Q(U,X):X.bindReference(U)]));var A8=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,z8=(Q,X)=>L(`Node of kind ${X} is not valid as a ${Q} definition`),NX=(Q)=>`#${Q} duplicates public alias ${Q}`,AQ={};F.ambient??={};var EX,SX="function $",O8=(Q)=>jX(Q,bX(Q)),jX=(Q,X)=>{let Y=X.write(SX,4),U=X.compile()();for(let Z of Q){if(Z.precompilation)continue;if(Z.traverseAllows=U[`${Z.id}Allows`].bind(U),Z.isRoot()&&!Z.allowsRequiresContext)Z.allows=Z.traverseAllows;if(Z.traverseApply=U[`${Z.id}Apply`].bind(U),U[`${Z.id}Optimistic`])Z.traverseOptimistic=U[`${Z.id}Optimistic`].bind(U);Z.precompilation=Y}},bX=(Q)=>new m2().return(Q.reduce((X,Y)=>{let U=new V2({kind:"Allows"}).indent();Y.compile(U);let Z=U.write(`${Y.id}Allows`),W=new V2({kind:"Apply"}).indent();Y.compile(W);let G=W.write(`${Y.id}Apply`),_=`${X}${Z},
|
|
41
|
+
Right: ${X}`;var X8=M({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():r(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>B(Q.unit),problem:({expected:Q,actual:X})=>`${Q===X?`must be reference equal to ${Q} (serialized to the same value)`:`must be ${Q} (was ${X})`}`},intersections:{unit:(Q,X)=>q.init("unit",Q,X),...L1("unit",(Q,X)=>{if(X.allows(Q.unit))return Q;let Y=X.hasKind("intersection")?X.basis:X;if(Y){let U=Y.hasKind("domain")?Y:F.intrinsic.object;if(Q.domain!==U.domain){let Z=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:F.intrinsic[Q.domain];return q.init("domain",Z,U)}}return q.init("assignability",Q,X.hasKind("intersection")?X.children.find((U)=>!U.allows(Q.unit)):X)})}});class DX extends f1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=TX(this.unit,this.serializedValue);compiledNegation=TX(this.unit,this.serializedValue,"negated");expression=B(this.unit);domain=b(this.unit);get defaultShortDescription(){return this.domain==="object"?m.object:this.description}innerToJsonSchema(Q){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Q.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Q)=>Q instanceof Date&&Q.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Q)=>Number.isNaN(Q):(Q)=>Q===this.unit}var JQ={implementation:X8,Node:DX},TX=(Q,X,Y)=>{if(Q instanceof Date){let U=`data instanceof Date && data.toISOString() === ${X}`;return Y?`!(${U})`:U}if(Number.isNaN(Q))return`${Y?"!":""}Number.isNaN(data)`;return`data ${Y?"!":"="}== ${X}`};var Y8=M({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,X)=>{let Y=X.$.parseSchema(Q);if(!Y.extends(F.intrinsic.key))return H(Z8(Y.expression));let U=Y.branches.filter((Z)=>Z.hasKind("unit"));if(U.length)return H(U8(U.map((Z)=>B(Z.unit))));return Y}},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`[${Q.signature.expression}]: ${Q.value.description}`},intersections:{index:(Q,X,Y)=>{if(Q.signature.equals(X.signature)){let U=N(Q.value,X.value,Y),Z=U instanceof q?F.intrinsic.never.internal:U;return Y.$.node("index",{signature:Q.signature,value:Z})}if(Q.signature.extends(X.signature)&&Q.value.subsumes(X.value))return X;if(X.signature.extends(Q.signature)&&X.value.subsumes(Q.value))return Q;return null}}});class RX extends t{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=D(this.value.flatRefs.map((Q)=>Z1([this.signature,...Q.path],Q.node)),Z1([this.signature],this.value));traverseAllows=(Q,X)=>N1(Q).every((Y)=>{if(this.signature.traverseAllows(Y[0],X))return o(Y[0],()=>this.value.traverseAllows(Y[1],X),X);return!0});traverseApply=(Q,X)=>{for(let Y of N1(Q))if(this.signature.traverseAllows(Y[0],X))o(Y[0],()=>this.value.traverseApply(Y[1],X),X)};_transform(Q,X){X.path.push(this.signature);let Y=super._transform(Q,X);return X.path.pop(),Y}compile(){}}var LQ={implementation:Y8,Node:RX},U8=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,Z8=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var W8=M({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}: ${Q.value.description}`,expected:(Q)=>Q.missingValueDescription,actual:()=>"missing"},intersections:{required:C2,optional:C2}});class CX extends w2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=R1(this.errorContext)}var HQ={implementation:W8,Node:CX};var G8=M({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},optionals:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}},defaultables:{child:(Q)=>Q.map((X)=>X[0]),parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>{let U=X.$.parseSchema(Y[0]);return P2(U,Y[1],null),[U,Y[1]]})},serialize:(Q)=>Q.map((X)=>[X[0].collapsibleJson,r(X[1])]),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optionals=Y.map((U)=>U[0].rawIn);return}X.prefix=Y.map((U)=>U[0].rawOut);return}},variadic:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q,X)},minVariadicLength:{parse:(Q)=>Q===0?void 0:Q},postfix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((Y)=>X.$.parseSchema(Y))}}},normalize:(Q)=>{if(typeof Q==="string")return{variadic:Q};if("variadic"in Q||"prefix"in Q||"defaultables"in Q||"optionals"in Q||"postfix"in Q||"minVariadicLength"in Q){if(Q.postfix?.length){if(!Q.variadic)return H(H8);if(Q.optionals?.length||Q.defaultables?.length)return H(qQ)}if(Q.minVariadicLength&&!Q.variadic)return H("minVariadicLength may not be specified without a variadic element");return Q}return{variadic:Q}},reduce:(Q,X)=>{let Y=Q.minVariadicLength??0,U=Q.prefix?.slice()??[],Z=Q.defaultables?.slice()??[],W=Q.optionals?.slice()??[],G=Q.postfix?.slice()??[];if(Q.variadic){while(W[W.length-1]?.equals(Q.variadic))W.pop();if(W.length===0&&Z.length===0)while(U[U.length-1]?.equals(Q.variadic))U.pop(),Y++;while(G[0]?.equals(Q.variadic))G.shift(),Y++}else if(W.length===0&&Z.length===0)U.push(...G.splice(0));if(Y!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==U.length)return X.node("sequence",{...Q,prefix:U,defaultables:Z,optionals:W,postfix:G,minVariadicLength:Y},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((Y)=>Y.kind==="defaultables"?`${Y.node.nestableExpression} = ${B(Y.default)}`:Y.kind==="optionals"?`${Y.node.nestableExpression}?`:Y.kind==="variadic"?`...${Y.node.nestableExpression}[]`:Y.node.expression).join(", ")}]`}},intersections:{sequence:(Q,X,Y)=>{let U=S2({l:Q.tuple,r:X.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:Y}),Z=U.disjoint.length===0?[U,...U.fixedVariants]:U.fixedVariants;return Z.length===0?U.disjoint:Z.length===1?Y.$.node("sequence",wX(Z[0].result)):Y.$.node("union",Z.map((W)=>({proto:Array,sequence:wX(W.result)})))}}});class PX extends t{impliedBasis=F.intrinsic.Array.internal;tuple=L8(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Q)=>{if(Q.kind==="defaultables"||Q.kind==="optionals")return this.defaultablesAndOptionals.push(Q.node),!0;return Q.kind==="prefix"});variadicOrPostfix=q1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return h6(this.flatRefs,this.prevariadic.flatMap((Q,X)=>D(Q.node.flatRefs.map((Y)=>Z1([`${X}`,...Y.path],Y.node)),Z1([`${X}`],Q.node)))),h6(this.flatRefs,this.variadicOrPostfix.flatMap((Q)=>D(Q.flatRefs.map((X)=>Z1([F.intrinsic.nonNegativeIntegerString.internal,...X.path],X.node)),Z1([F.intrinsic.nonNegativeIntegerString.internal],Q)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=J8(this);defaultValueMorphsReference=this.defaultValueMorphs.length?S(this.defaultValueMorphs):void 0;elementAtIndex(Q,X){if(X<this.prevariadic.length)return this.tuple[X];let Y=Q.length-this.postfixLength;if(X>=Y)return{kind:"postfix",node:this.postfix[X-Y]};return{kind:"variadic",node:this.variadic??C(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Q,X)=>{for(let Y=0;Y<Q.length;Y++)if(!this.elementAtIndex(Q,Y).node.traverseAllows(Q[Y],X))return!1;return!0};traverseApply=(Q,X)=>{let Y=0;for(;Y<Q.length;Y++)o(Y,()=>this.elementAtIndex(Q,Y).node.traverseApply(Q[Y],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix)for(let[X,Y]of this.prefix.entries())Q.traverseKey(`${X}`,`data[${X}]`,Y);for(let[X,Y]of this.defaultablesAndOptionals.entries()){let U=`${X+this.prefixLength}`;Q.if(`${U} >= data.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(U,`data[${U}]`,Y)}if(this.variadic){if(this.postfix)Q.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Q.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Q.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[X,Y]of this.postfix.entries()){let U=`firstPostfixIndex + ${X}`;Q.traverseKey(U,`data[${U}]`,Y)}}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,X){X.path.push(F.intrinsic.nonNegativeIntegerString.internal);let Y=super._transform(Q,X);return X.path.pop(),Y}expression=this.description;reduceJsonSchema(Q,X){let Y=X.target==="draft-07";if(this.prevariadic.length){let U=this.prevariadic.map((Z)=>{let W=Z.node.toJsonSchemaRecurse(X);if(Z.kind==="defaultables"){let G=typeof Z.default==="function"?Z.default():Z.default;W.default=F.intrinsic.jsonData.allows(G)?G:X.fallback.defaultValue({code:"defaultValue",base:W,value:G})}return W});if(Y)Q.items=U;else Q.prefixItems=U}if(this.minLength)Q.minItems=this.minLength;if(this.variadic){let U=this.variadic.toJsonSchemaRecurse(X);if(Y&&this.prevariadic.length)Q.additionalItems=U;else Q.items=U;if(this.maxLength)Q.maxItems=this.maxLength;if(this.postfix){let Z=this.postfix.map((W)=>W.toJsonSchemaRecurse(X));Q=X.fallback.arrayPostfix({code:"arrayPostfix",base:Q,elements:Z})}}else{if(Y)Q.additionalItems=!1;else Q.items=!1;delete Q.maxItems}return Q}}var _8={},J8=(Q)=>{if(!Q.defaultables)return[];let X=[],Y="[",U=Q.prefixLength+Q.defaultablesLength-1;for(let Z=Q.prefixLength;Z<=U;Z++){let[W,G]=Q.defaultables[Z-Q.prefixLength];X.push(UQ(Z,W,G)),Y+=`${Z}: ${W.id} = ${r(G)}, `}return Y+="]",_8[Y]??=X},FQ={implementation:G8,Node:PX},L8=(Q)=>{let X=[];if(Q.prefix)for(let Y of Q.prefix)X.push({kind:"prefix",node:Y});if(Q.defaultables)for(let[Y,U]of Q.defaultables)X.push({kind:"defaultables",node:Y,default:U});if(Q.optionals)for(let Y of Q.optionals)X.push({kind:"optionals",node:Y});if(Q.variadic)X.push({kind:"variadic",node:Q.variadic});if(Q.postfix)for(let Y of Q.postfix)X.push({kind:"postfix",node:Y});return X},wX=(Q)=>Q.reduce((X,Y)=>{if(Y.kind==="variadic")X.variadic=Y.node;else if(Y.kind==="defaultables")X.defaultables=D(X.defaultables,[[Y.node,Y.default]]);else X[Y.kind]=D(X[Y.kind],Y.node);return X},{}),qQ="A postfix required element cannot follow an optional or defaultable element",H8="A postfix element requires a variadic element",S2=(Q)=>{let[X,...Y]=Q.l,[U,...Z]=Q.r;if(!X||!U)return Q;let W=Y[Y.length-1]?.kind==="postfix",G=Z[Z.length-1]?.kind==="postfix",_=X.kind==="prefix"||U.kind==="prefix"?"prefix":X.kind==="postfix"||U.kind==="postfix"?"postfix":X.kind==="variadic"&&U.kind==="variadic"?"variadic":W||G?"prefix":X.kind==="defaultables"||U.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&U.kind==="variadic"&&G){let O=S2({...Q,fixedVariants:[],r:Z.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}else if(U.kind==="prefix"&&X.kind==="variadic"&&W){let O=S2({...Q,fixedVariants:[],l:Y.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}let L=N(X.node,U.node,Q.ctx);if(L instanceof q)if(_==="prefix"||_==="postfix")Q.disjoint.push(...L.withPrefixKey(_==="prefix"?Q.result.length:`-${Y.length+1}`,KX(X)&&KX(U)?"required":"optional")),Q.result=[...Q.result,{kind:_,node:F.intrinsic.never.internal}];else if(_==="optionals"||_==="defaultables")return Q;else return S2({...Q,fixedVariants:[],l:Y.map((O)=>({...O,kind:"prefix"})),r:Y.map((O)=>({...O,kind:"prefix"}))});else if(_==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)H(YQ(X.default,U.default));Q.result=[...Q.result,{kind:_,node:L,default:X.kind==="defaultables"?X.default:U.kind==="defaultables"?U.default:C(`Unexpected defaultable intersection from ${X.kind} and ${U.kind} elements.`)}]}else Q.result=[...Q.result,{kind:_,node:L}];let J=Q.l.length,A=Q.r.length;if(X.kind!=="variadic"||J>=A&&(U.kind==="variadic"||A===1))Q.l=Y;if(U.kind!=="variadic"||A>=J&&(X.kind==="variadic"||J===1))Q.r=Z;return S2(Q)},KX=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var SX=(Q)=>(X)=>{if(X.props.length||X.index){let Y=X.index?.map((Z)=>Z[Q])??[];for(let Z of X.props)Y.push(Z[Q]);if(X.undeclared)Y.push(`+ (undeclared): ${X.undeclared}`);let U=`{ ${Y.join(", ")} }`;return X.sequence?`${U} & ${X.sequence.description}`:U}return X.sequence?.description??"{}"},F8=SX("description"),q8=SX("expression"),NX=(Q,X,Y)=>{let U=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=i(Q.value,X.value,Y);if(Z instanceof q)return U==="optional"?Y.node("optional",{key:Q.key,value:F.intrinsic.never.internal}):Z.withPrefixKey(Q.key,Q.kind);return null},A8=M({kind:"structure",hasAssociatedError:!1,normalize:(Q)=>Q,applyConfig:(Q,X)=>{if(!Q.undeclared&&X.onUndeclaredKey!=="ignore")return{...Q,undeclared:X.onUndeclaredKey};return Q},keys:{required:{child:!0,parse:x("required"),reduceIo:(Q,X,Y)=>{X.required=D(X.required,Y.map((U)=>Q==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:x("optional"),reduceIo:(Q,X,Y)=>{if(Q==="in"){X.optional=Y.map((U)=>U.rawIn);return}for(let U of Y)X[U.outProp.kind]=D(X[U.outProp.kind],U.outProp.rawOut)}},index:{child:!0,parse:x("index")},sequence:{child:!0,parse:x("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q,reduceIo:(Q,X,Y)=>{if(Y==="reject"){X.undeclared="reject";return}if(Q==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:F8},intersections:{structure:(Q,X,Y)=>{let U={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let L=Q.keyof();for(let J of X.requiredKeys)if(!L.allows(J))W.add("presence",F.intrinsic.never.internal,X.propsByKey[J].value,{path:[J]});if(Z.optional)Z.optional=Z.optional.filter((J)=>L.allows(J.key));if(Z.index)Z.index=Z.index.flatMap((J)=>{if(J.signature.extends(L))return J;let A=i(L,J.signature,Y.$);if(A instanceof q)return[];let O=Q6(A,J.value,Y.$);if(O.required)Z.required=q1(Z.required,O.required);if(O.optional)Z.optional=q1(Z.optional,O.optional);return O.index??[]})}if(X.undeclared){let L=X.keyof();for(let J of Q.requiredKeys)if(!L.allows(J))W.add("presence",Q.propsByKey[J].value,F.intrinsic.never.internal,{path:[J]});if(U.optional)U.optional=U.optional.filter((J)=>L.allows(J.key));if(U.index)U.index=U.index.flatMap((J)=>{if(J.signature.extends(L))return J;let A=i(L,J.signature,Y.$);if(A instanceof q)return[];let O=Q6(A,J.value,Y.$);if(O.required)U.required=q1(U.required,O.required);if(O.optional)U.optional=q1(U.optional,O.optional);return O.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let _=l1({kind:"structure",baseInner:G,l:d1(U),r:d1(Z),roots:[],ctx:Y});if(_ instanceof q)W.push(..._);if(W.length)return W;return _}},reduce:(Q,X)=>{if(!Q.required&&!Q.optional)return;let Y={},U=!1,Z=Q.optional?[...Q.optional]:[];if(Q.required)for(let W=0;W<Q.required.length;W++){let G=Q.required[W];if(G.key in Y)H(EX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let L=NX(G,_,X);if(L instanceof q)return L}}if(Q.optional)for(let W=0;W<Q.optional.length;W++){let G=Q.optional[W];if(G.key in Y)H(EX(G.key));if(Y[G.key]=!0,Q.index)for(let _ of Q.index){let L=NX(G,_,X);if(L instanceof q)return L;if(L!==null)Z[W]=L,U=!0}}if(U)return X.node("structure",{...Q,optional:Z},{prereduced:!0})}});class jX extends t{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=q1(this.required,this.optional);propsByKey=V(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=q8(this);requiredKeys=this.required?.map((Q)=>Q.key)??[];optionalKeys=this.optional?.map((Q)=>Q.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:X}of this.index)Q=Q.concat(X.branches);return this._keyof=this.$.node("union",Q)}map(Q){return this.$.node("structure",this.props.flatMap(Q).reduce((X,Y)=>{let U=this.propsByKey[Y.key];if(P(Y)){if(Y.kind!=="required"&&Y.kind!=="optional")return H(`Map result must have kind "required" or "optional" (was ${Y.kind})`);return X[Y.kind]=D(X[Y.kind],Y),X}let Z=Y.kind??U?.kind??"required",W=V(Y,(G,_)=>(G in K2.implementation.keys)?[G,_]:[]);return X[Z]=D(X[Z],this.$.node(Z,W)),X},{}))}assertHasKeys(Q){let X=Q.filter((Y)=>!N2(Y,this.keyof()));if(X.length)return H(IX(this.expression,X))}get(Q,...X){let Y,U=!1,Z=V8(Q);if((typeof Z==="string"||typeof Z==="symbol")&&this.propsByKey[Z])Y=this.propsByKey[Z].value,U=this.propsByKey[Z].required;if(this.index){for(let G of this.index)if(N2(Z,G.signature))Y=Y?.and(G.value)??G.value}if(this.sequence&&N2(Z,F.intrinsic.nonNegativeIntegerString))if($(Z,"root")){if(this.sequence.variadic)Y=Y?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Z);if(G<this.sequence.prevariadic.length){let _=this.sequence.prevariadic[G].node;Y=Y?.and(_)??_,U||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let _=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(_)??_}}if(!Y){if(this.sequence?.variadic&&$(Z,"root")&&Z.extends(F.intrinsic.number))return H(B8(Z.expression,this.sequence.expression));return H(IX(this.expression,[Z]))}let W=Y.get(...X);return U?W:W.or(F.intrinsic.undefined)}pick(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("pick",Q))}omit(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("omit",Q))}optionalize(){let{required:Q,...X}=this.inner;return this.$.node("structure",{...X,optional:this.props.map((Y)=>Y.hasKind("required")?this.$.node("optional",Y.inner):Y)})}require(){let{optional:Q,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((Y)=>Y.hasKind("optional")?{key:Y.key,value:Y.value}:Y)})}merge(Q){let X=this.filterKeys("omit",[Q.keyof()]);if(Q.required)X.required=D(X.required,Q.required);if(Q.optional)X.optional=D(X.optional,Q.optional);if(Q.index)X.index=D(X.index,Q.index);if(Q.sequence)X.sequence=Q.sequence;if(Q.undeclared)X.undeclared=Q.undeclared;else delete X.undeclared;return this.$.node("structure",X)}filterKeys(Q,X){let Y=l2(this.inner),U=(Z)=>{let W=X.some((G)=>N2(Z,G));return Q==="pick"?W:!W};if(Y.required)Y.required=Y.required.filter((Z)=>U(Z.key));if(Y.optional)Y.optional=Y.optional.filter((Z)=>U(Z.key));if(Y.index)Y.index=Y.index.filter((Z)=>U(Z.signature));return Y}traverseAllows=(Q,X)=>this._traverse("Allows",Q,X);traverseApply=(Q,X)=>this._traverse("Apply",Q,X);_traverse=(Q,X,Y)=>{let U=Y?.currentErrorCount??0;for(let Z=0;Z<this.props.length;Z++)if(Q==="Allows"){if(!this.props[Z].traverseAllows(X,Y))return!1}else if(this.props[Z].traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(X,Y))return!1}else if(this.sequence.traverseApply(X,Y),Y.failFast&&Y.currentErrorCount>U)return!1}if(this.index||this.undeclared==="reject"){let Z=Object.keys(X);Z.push(...Object.getOwnPropertySymbols(X));for(let W=0;W<Z.length;W++){let G=Z[W];if(this.index){for(let _ of this.index)if(_.signature.traverseAllows(G,Y)){if(Q==="Allows"){if(!o(G,()=>_.value.traverseAllows(X[G],Y),Y))return!1}else if(o(G,()=>_.value.traverseApply(X[G],Y),Y),Y.failFast&&Y.currentErrorCount>U)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if(Q==="Allows")return!1;if(Y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),Y.failFast)return!1}}}if(this.structuralMorph&&Y&&!Y.hasError())Y.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Q)=>Q.hasDefault())??[])}declaresKey=(Q)=>(Q in this.propsByKey)||this.index?.some((X)=>X.signature.allows(Q))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Q);_compileDeclaresKey(Q){let X=[];if(this.props.length)X.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Y of this.index)X.push(Q.invoke(Y.signature,{kind:"Allows",arg:"k"}));if(this.sequence)X.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return X.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",z8(this))}structuralMorphRef=this.structuralMorph&&S(this.structuralMorph);compile(Q){if(Q.traversalKind==="Apply")Q.initializeErrorCount();for(let X of this.props)if(Q.check(X),Q.traversalKind==="Apply")Q.returnIfFailFast();if(this.sequence){if(Q.check(this.sequence),Q.traversalKind==="Apply")Q.returnIfFailFast()}if(this.index||this.undeclared==="reject")Q.const("keys","Object.keys(data)"),Q.line("keys.push(...Object.getOwnPropertySymbols(data))"),Q.for("i < keys.length",()=>this.compileExhaustiveEntry(Q));if(Q.traversalKind==="Allows")return Q.return(!0);if(this.structuralMorphRef)Q.if("ctx && !ctx.hasError()",()=>{return Q.line("ctx.queueMorphs(["),O8(Q,this),Q.line("])")})}compileExhaustiveEntry(Q){if(Q.const("k","keys[i]"),this.index)for(let X of this.index)Q.if(`${Q.invoke(X.signature,{arg:"k",kind:"Allows"})}`,()=>Q.traverseKey("k","data[k]",X.value));if(this.undeclared==="reject")Q.if(`!(${this._compileDeclaresKey(Q)})`,()=>{if(Q.traversalKind==="Allows")return Q.return(!1);return Q.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Q.return())});return Q}reduceJsonSchema(Q,X){switch(Q.type){case"object":return this.reduceObjectJsonSchema(Q,X);case"array":let Y=this.sequence?.reduceJsonSchema(Q,X)??Q;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:Y,object:this.reduceObjectJsonSchema({type:"object"},X)});return Y;default:return I.throwInternalOperandError("structure",Q)}}reduceObjectJsonSchema(Q,X){if(this.props.length){Q.properties={};for(let Y of this.props){let U=Y.value.toJsonSchemaRecurse(X);if(typeof Y.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Q,key:Y.key,value:U,optional:Y.optional});continue}if(Y.hasDefault()){let Z=typeof Y.default==="function"?Y.default():Y.default;U.default=F.intrinsic.jsonData.allows(Z)?Z:X.fallback.defaultValue({code:"defaultValue",base:U,value:Z})}Q.properties[Y.key]=U}if(this.requiredKeys.length&&Q.properties)Q.required=this.requiredKeys.filter((Y)=>typeof Y==="string"&&(Y in Q.properties))}if(this.index)for(let Y of this.index){let U=Y.value.toJsonSchemaRecurse(X);if(Y.signature.equals(F.intrinsic.string)){Q.additionalProperties=U;continue}for(let Z of Y.signature.branches){if(!Z.extends(F.intrinsic.string)){Q=X.fallback.symbolKey({code:"symbolKey",base:Q,key:null,value:U,optional:!1});continue}let W={type:"string"};if(Z.hasKind("morph"))W=X.fallback.morph({code:"morph",base:Z.rawIn.toJsonSchemaRecurse(X),out:Z.rawOut.toJsonSchemaRecurse(X)});if(!Z.hasKind("intersection"))return C(`Unexpected index branch kind ${Z.kind}.`);let{pattern:G}=Z.inner;if(G){let _=Object.assign(W,{pattern:G[0].rule});for(let L=1;L<G.length;L++)W=X.fallback.patternIntersection({code:"patternIntersection",base:_,pattern:G[L].rule});Q.patternProperties??={},Q.patternProperties[_.pattern]=U}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var AQ={},$8=(Q)=>{let X="";for(let Y=0;Y<Q.defaultable.length;Y++)X+=Q.defaultable[Y].defaultValueMorphRef;if(Q.sequence?.defaultValueMorphsReference)X+=Q.sequence?.defaultValueMorphsReference;if(Q.undeclared==="delete"){if(X+="delete !(",Q.required)for(let Y of Q.required)X+=Y.compiledKey+" | ";if(Q.optional)for(let Y of Q.optional)X+=Y.compiledKey+" | ";if(Q.index)for(let Y of Q.index)X+=Y.signature.id+" | ";if(Q.sequence)if(Q.sequence.maxLength===null)X+=z.nonNegativeIntegerString.id;else for(let Y=0;Y<Q.sequence.tuple.length;Y++)X+=Y+" | ";X+=")"}return X},z8=(Q)=>{let X=$8(Q);if(!X)return;if(AQ[X])return AQ[X];let Y=(U,Z)=>{for(let W=0;W<Q.defaultable.length;W++)if(!(Q.defaultable[W].key in U))Q.defaultable[W].defaultValueMorph(U,Z);if(Q.sequence?.defaultables)for(let W=U.length-Q.sequence.prefixLength;W<Q.sequence.defaultables.length;W++)Q.sequence.defaultValueMorphs[W](U,Z);if(Q.undeclared==="delete"){for(let W in U)if(!Q.declaresKey(W))delete U[W]}return U};return AQ[X]=Y},O8=(Q,X)=>{let U=`(data${X.defaultable.some((Z)=>Z.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((Z)=>Z.length===2)?", ctx":""})`;return Q.block(`${U} => `,(Z)=>{for(let W=0;W<X.defaultable.length;W++){let{serializedKey:G,defaultValueMorphRef:_}=X.defaultable[W];Z.if(`!(${G} in data)`,(L)=>L.line(`${_}${U}`))}if(X.sequence?.defaultables)Z.for(`i < ${X.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${X.sequence.prefixLength}`);if(X.undeclared==="delete")Z.forIn("data",(W)=>W.if(`!(${X._compileDeclaresKey(W)})`,(G)=>G.line("delete data[k]")));return Z.return("data")})},$Q={implementation:A8,Node:jX},V8=(Q)=>{if($(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},B8=(Q,X)=>`${Q} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,Q6=(Q,X,Y)=>{let[U,Z]=iQ(Q.branches,(G)=>G.hasKind("unit"));if(!U.length)return{index:Y.node("index",{signature:Q,value:X})};let W={};for(let G of U){let _=Y.node("required",{key:G.unit,value:X});W[_.kind]=D(W[_.kind],_)}if(Z.length)W.index=Y.node("index",{signature:Z,value:X});return W},M8=(Q)=>$(Q,"root")?Q.expression:B(Q),IX=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map(M8).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,EX=(Q)=>`Duplicate key ${Y1(Q)}`;var o1={...t4,alias:I2.implementation,domain:e2.implementation,unit:JQ.implementation,proto:E2.implementation,union:_Q.implementation,morph:WQ.implementation,intersection:ZQ.implementation,divisor:d6.implementation,pattern:a6.implementation,predicate:l6.implementation,required:HQ.implementation,optional:K2.implementation,index:LQ.implementation,sequence:FQ.implementation,structure:$Q.implementation};F.defaultConfig=Y4(Object.assign(V(o1,(Q,X)=>[Q,X.defaults]),{jitless:J4(),clone:W4,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:I.defaultConfig}));F.resolvedConfig=B2(F.defaultConfig,F.config);var UX={...a4,alias:I2.Node,domain:e2.Node,unit:JQ.Node,proto:E2.Node,union:_Q.Node,morph:WQ.Node,intersection:ZQ.Node,divisor:d6.Node,pattern:a6.Node,predicate:l6.Node,required:HQ.Node,optional:K2.Node,index:LQ.Node,sequence:FQ.Node,structure:$Q.Node};class n1 extends w6{get[h](){return"module"}}var zQ=(Q,X)=>new n1(V(Q,(Y,U)=>[Y,$(U,"module")?zQ(U,X):X.bindReference(U)]));var T8=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,D8=(Q,X)=>H(`Node of kind ${X} is not valid as a ${Q} definition`),fX=(Q)=>`#${Q} duplicates public alias ${Q}`,OQ={};F.ambient??={};var bX,vX="function $",R8=(Q)=>kX(Q,gX(Q)),kX=(Q,X)=>{let Y=X.write(vX,4),U=X.compile()();for(let Z of Q){if(Z.precompilation)continue;if(Z.traverseAllows=U[`${Z.id}Allows`].bind(U),Z.isRoot()&&!Z.allowsRequiresContext)Z.allows=Z.traverseAllows;if(Z.traverseApply=U[`${Z.id}Apply`].bind(U),U[`${Z.id}Optimistic`])Z.traverseOptimistic=U[`${Z.id}Optimistic`].bind(U);Z.precompilation=Y}},gX=(Q)=>new m2().return(Q.reduce((X,Y)=>{let U=new V2({kind:"Allows"}).indent();Y.compile(U);let Z=U.write(`${Y.id}Allows`),W=new V2({kind:"Apply"}).indent();Y.compile(W);let G=W.write(`${Y.id}Apply`),_=`${X}${Z},
|
|
42
42
|
${G},
|
|
43
|
-
`;if(!Y.hasKind("union"))return _;let
|
|
43
|
+
`;if(!Y.hasKind("union"))return _;let L=new V2({kind:"Allows",optimistic:!0}).indent();Y.compile(L);let J=L.write(`${Y.id}Optimistic`);return`${_}${J},
|
|
44
44
|
`},`{
|
|
45
|
-
`)+"}");class X6{config;resolvedConfig;name;get[x](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Q,X){if(this.config=B2(F.config,X),this.resolvedConfig=B2(F.resolvedConfig,X),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(AQ).length}`,this.name in AQ)L(`A Scope already named ${this.name} already exists`);AQ[this.name]=this;let Y=Object.entries(Q).map((U)=>this.preparseOwnAliasEntry(...U));for(let[U,Z]of Y){let W=U;if(U[0]==="#"){if(W=U.slice(1),W in this.aliases)L(NX(W));this.aliases[W]=Z}else{if(W in this.aliases)L(NX(U));this.aliases[W]=Z,this.exportedNames.push(W)}if(!A(Z,"module")&&!A(Z,"generic")&&!M1(Z)){let G=this.preparseOwnDefinitionFormat(Z,{alias:W});this.resolutions[W]=A(G,"root")?this.bindReference(G):this.createParseContext(G).id}}EX??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[EX.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?V(F.intrinsic,(U,Z)=>U.startsWith("json")?[]:[U,this.bindReference(Z)]):{}}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Q){return Q}generic=(...Q)=>{let X=this;return(Y,U)=>new w1(Q,U?new i2(Y):Y,X,X,U??null)};units=(Q,X)=>{let Y=[];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);let U=Y.map((Z)=>this.node("unit",{unit:Z},X));return this.node("union",U,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,X){let Y=this.node("alias",{reference:X??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Y);return Y}schema=(Q,X)=>this.finalize(this.parseSchema(Q,X));parseSchema=(Q,X)=>this.node(R2(Q),Q,X);preparseNode(Q,X,Y){let U=typeof Q==="string"?Q:R2(X,Q);if(P(X)&&X.kind===U)return X;if(U==="alias"&&!Y?.prereduced){let{reference:G}=E2.implementation.normalize(X,this);if(G.startsWith("$")){let _=this.resolveRoot(G.slice(1));X=_,U=_.kind}}else if(U==="union"&&p(X,"object")){let G=A8(X);if(G?.length===1)X=G[0],U=R2(X)}if(P(X)&&X.kind===U)return X;let W=o1[U].normalize?.(X,this)??X;if(P(W))return W.kind===U?W:z8(U,W.kind);return{...Y,$:this,kind:U,def:W,prefix:Y.alias??U}}bindReference(Q){let X;if(P(Q))X=Q.$===this?Q:new Q.constructor(Q.attachments,this);else X=Q.$===this?Q:new w1(Q.params,Q.bodyDef,Q.$,this,Q.hkt);if(!this.resolved)Object.assign(this.referencesById,X.referencesById);return X}resolveRoot(Q){return this.maybeResolveRoot(Q)??L(VQ(Q))}maybeResolveRoot(Q){let X=this.maybeResolve(Q);if(A(X,"generic"))return;return X}maybeResolveSubalias(Q){return zQ(this.aliases,Q)??zQ(this.ambient,Q)}get ambient(){return F.ambient}maybeResolve(Q){let X=this.resolutions[Q];if(X){if(typeof X!=="string")return this.bindReference(X);let U=h[X];if(A(U,"root"))return this.resolutions[Q]=U;if(A(U,"context")){if(U.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(U.phase==="resolved")return C(`Unexpected resolved context for was uncached by its scope: ${B(U)}`);U.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",h[Z.id]=Z,h[U.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${B(U)}`)}let Y=this.aliases[Q]??this.ambient?.[Q];if(!Y)return this.maybeResolveSubalias(Q);if(Y=this.normalizeRootScopeValue(Y),A(Y,"generic"))return this.resolutions[Q]=this.bindReference(Y);if(A(Y,"module")){if(!Y.root)L(vX(Q));return this.resolutions[Q]=this.bindReference(Y.root)}return this.resolutions[Q]=this.parse(Y,{alias:Q})}createParseContext(Q){let X=Q.id??t6(Q.prefix);return h[X]=Object.assign(Q,{[x]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new U1(Q,this.resolvedConfig)}import(...Q){return new n1(V(this.export(...Q),(X,Y)=>[`#${X}`,Y]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let Y of this.exportedNames){let U=this.aliases[Y];this._exports[Y]=A(U,"module")?$Q(U,this):IX(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=fX(this,this._exports),this._json=yX(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=bX(this.references);this.precompilation=Y.write(SX,4),jX(this.references,Y)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(V(X,(Y,U)=>[U,this._exports[U]]))}resolve(Q){return this.export()[Q]}node=(Q,X,Y={})=>{let U=this.preparseNode(Q,X,Y);if(P(U))return this.bindReference(U);let Z=this.createParseContext(U),W=a6(Z),G=this.bindReference(W);return h[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if(A(Q,"root"))return this.bindReference(Q);let Y=this.preparseOwnDefinitionFormat(Q,X);if(A(Y,"root"))return this.bindReference(Y);let U=this.createParseContext(Y);h[U.id]=U;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,U));if(Z.isCyclic)Z=t4(Z,U.id);return h[U.id]=Z,Z}finalize(Q){if(IX(Q),!Q.precompilation&&!this.resolvedConfig.jitless)O8(Q.references);return Q}}class OQ extends X6{parseOwnDefinitionFormat(Q,X){return a6(X)}preparseOwnDefinitionFormat(Q,X){return this.preparseNode(R2(Q),Q,X)}preparseOwnAliasEntry(Q,X){return[Q,X]}normalizeRootScopeValue(Q){return Q}}var IX=(Q)=>{let X=Q.references.filter((Y)=>Y.hasKind("alias"));for(let Y of X){Object.assign(Y.referencesById,Y.resolution.referencesById);for(let U of Q.references)if(Y.id in U.referencesById)Object.assign(U.referencesById,Y.referencesById)}return Q},yX=(Q)=>V(Q,(X,Y)=>[X,A(Y,"root")||A(Y,"generic")?Y.json:A(Y,"module")?yX(Y):C(`Unexpected resolution ${B(Y)}`)]),zQ=(Q,X)=>{let Y=X.indexOf(".");if(Y===-1)return;let U=X.slice(0,Y),Z=Q[U];if(Z===void 0)return;if(!A(Z,"module"))return L(V8(U));let W=X.slice(Y+1),G=Z[W];if(G===void 0)return zQ(Z,W);if(A(G,"root")||A(G,"generic"))return G;if(A(G,"module"))return G.root??L(vX(X));C(`Unexpected resolution for alias '${X}': ${B(G)}`)},Y6=(Q,X)=>new OQ(Q,X),j2=new OQ({});var fX=(Q,X)=>{let Y={};for(let U in X){let Z=X[U];if(A(Z,"module")){let W=fX(Q,Z),G=V(W,(_,H)=>[`${U}.${_}`,H]);Object.assign(Y,G)}else if(A(Z,"root")||A(Z,"generic"))Y[U]=Z;else C(`Unexpected scope resolution ${B(Z)}`)}return Y},VQ=(Q)=>`'${Q}' is unresolvable`,V8=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,vX=(Q)=>`Reference to submodule '${Q}' must specify an alias`;j2.export();var{schema:w,node:r1,defineSchema:o7,generic:e}=j2;var BQ="^(?:0|[1-9]\\d*)$",B8=new RegExp(BQ),n7=S(B8);var kX=Y6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();F.intrinsic={...kX};var gX=Y6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:BQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,gX);var M8=Y6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),z={...kX,...gX,...M8,emptyStructure:r1("structure",{},{prereduced:!0})};F.intrinsic={...z};var U6=(Q,X)=>new RegExp(Q,X);Object.assign(U6,{as:U6});var hX=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],xX=(Q)=>Q.toString()!=="Invalid Date",pX=(Q)=>Q.slice(2,-1),MQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,uX=(Q,X)=>T8(Q,X),T8=(Q,X)=>{let Y=new Date(Q);if(xX(Y))return Y;let U=$4(Q);if(U!==void 0){let Z=new Date(U);if(xX(Z))return Z}return X?L(X===!0?MQ(Q):X):void 0};var D8=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Z6=(Q,X)=>{let Y=Q.scanner.shiftUntilEscapable(C8[dX[X]]);if(Q.scanner.lookahead==="")return Q.error(K8(Y,X));if(Q.scanner.shift(),X in lX){let U;try{U=new RegExp(Y)}catch(Z){L(String(Z))}if(Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0}),X==="x/")Q.root=Q.ctx.$.node("morph",{in:Q.root,morphs:(Z)=>U.exec(Z),declaredOut:D8})}else if(f(X,TQ))Q.root=Q.ctx.$.node("unit",{unit:Y});else{let U=uX(Y,MQ(Y));Q.root=Q.ctx.$.node("unit",{meta:Y,unit:U})}},TQ={"'":1,'"':1},mX={"/":1,"'":1,'"':1},R8={"d'":"'",'d"':'"',"'":"'",'"':'"'},lX={"/":"/","x/":"/"},dX={...R8,...lX},C8={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},w8={'"':"double-quote","'":"single-quote","/":"forward slash"},K8=(Q,X)=>`${X}${Q} requires a closing ${w8[dX[X]]}`;var cX=(Q)=>`Private type references should not include '#'. Use '${Q}' instead.`,W6="Optional definitions like 'string?' are only valid as properties in an object or tuple",G6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var H1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...T1};var oX=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||f(X.trimStart()[0],H1):Q==="="?X[0]!=="=":Q===","||Q==="?";var iX=(Q,X,Y)=>sX(Q,X,Y,[]),sX=(Q,X,Y,U)=>{let Z=Y.parseUntilFinalizer();if(U.push(Z.root),Z.finalizer===">"){if(U.length!==X.params.length)return Y.error(DQ(Q,X.names,U.map((W)=>W.expression)));return U}if(Z.finalizer===",")return sX(Q,X,Y,U);return Z.error(u2(">"))},DQ=(Q,X,Y)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var _6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(H1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=N8(Q,X)},P8=(Q,X,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(DQ(Q,X.names,[]));let Z=iX(Q,X,Y);return X(...Z)},N8=(Q,X)=>E8(Q,X)??I8(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?cX(Q.shiftedBy(1).scanner.shiftUntilLookahead(H1)):RQ(Q):VQ(X)),E8=(Q,X)=>{if(Q.ctx.args?.[X]){let U=Q.ctx.args[X];if(typeof U!=="string")return U;return Q.ctx.$.node("alias",{reference:U},{prereduced:!0})}let Y=Q.ctx.$.maybeResolve(X);if(A(Y,"root"))return Y;if(Y===void 0)return;if(A(Y,"generic"))return P8(X,Y,Q);return L(`Unexpected resolution ${B(Y)}`)},I8=(Q,X)=>{let Y=A4(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y});let U=O4(X);if(U!==void 0)return Q.ctx.$.node("unit",{unit:U})},RQ=(Q)=>{let X=Q.previousOperator();return X?CQ(X,Q.scanner.unscanned):S8(Q.scanner.unscanned)},CQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,S8=(Q)=>`Expected an expression${Q?` before '${Q}'`:""}`;var wQ=(Q)=>Q.scanner.lookahead===""?Q.error(RQ(Q)):Q.scanner.lookahead==="("?Q.shiftedBy(1).reduceGroupOpen():Q.scanner.lookaheadIsIn(mX)?Z6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(T1)?wQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in TQ?Z6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):_6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&Z6(Q,"x/"):_6(Q):_6(Q);var nX={">":!0,">=":!0},rX={"<":!0,"<=":!0};var t1={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},tX=(Q,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Q})`,J6=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,aX=(Q,X,Y,U)=>`An expression may have at most one left bound (parsed ${Q}${t1[X]}, ${Y}${t1[U]})`;var QY=(Q,X)=>{let Y=j8(Q,X);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,Y),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let U=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(U,Y);return}}return y8(Q,Y)},XY={"<":1,">":1,"=":1},j8=(Q,X)=>Q.scanner.lookaheadIs("=")?`${X}${Q.scanner.shift()}`:X;var eX=(Q,X,Y,U)=>{if(Y.extends(F.intrinsic.number)){if(typeof X!=="number")return L(KQ(Q,X,U));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(Y.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return L(KQ(Q,X,U));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(Y.extends(F.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return L(x4(Y.expression))},b8=(Q)=>({rule:hX(Q.limit)?pX(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),y8=(Q,X)=>{let Y=Q.unsetRoot(),U=Q.scanner.location;Q.parseOperand();let Z=Q.unsetRoot(),W=Q.scanner.sliceChars(U,Q.scanner.location);if(Q.root=Y,!Z.hasKind("unit")||typeof Z.unit!=="number"&&!(Z.unit instanceof Date))return Q.error(KQ(X,W,"right"));let G=Z.unit,_=X.length===1,H=eX(X,typeof G==="number"?G:W,Y,"right");for(let $ of H)Q.constrainRoot($,X==="=="?{rule:G}:{rule:G,exclusive:_});if(!Q.branches.leftBound)return;if(!f(X,rX))return Q.error(J6(X));let J=eX(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,Y,"left");Q.constrainRoot(J[0],b8(Q.branches.leftBound)),Q.branches.leftBound=null},KQ=(Q,X,Y)=>`Comparator ${Y==="left"?t1[Q]:Q} must be ${Y==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var YY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1);Q.root=Q.root.brand(X)};var ZY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1),Y=z4(X,{errorOnFail:UY(X)});if(Y===0)Q.error(UY(0));Q.root=Q.root.constrain("divisor",Y)},UY=(Q)=>`% operator must be followed by a non-zero integer literal (was ${Q})`;var PQ=(Q)=>{let X=Q.scanner.shift();return X===""?Q.finalize(""):X==="["?Q.scanner.shift()==="]"?Q.setRoot(Q.root.array()):Q.error(f8):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():oX(X,Q.scanner.unscanned)?Q.finalize(X):f(X,XY)?QY(Q,X):X==="%"?ZY(Q):X==="#"?YY(Q):(X in T1)?PQ(Q):Q.error(L6(X))},L6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,f8="Missing expected ']'";var WY=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let Y=Q.unsetRoot();if(!Y.hasKind("unit"))return Q.error(v8(Y.expression));let U=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[X,"=",U]},v8=(Q)=>`Default value '${Q}' must be a literal value`;var NQ=(Q,X)=>{let Y=X.$.maybeResolveRoot(Q);if(Y)return Y;if(Q.endsWith("[]")){let W=X.$.maybeResolveRoot(Q.slice(0,-2));if(W)return W.array()}let U=new a1(new O2(Q),X),Z=k8(U);if(U.finalizer===">")L(L6(">"));return Z},k8=(Q)=>{Q.parseOperand();let X=b2(Q).root;if(!X)return C(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")X=WY(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)L(L6(Q.scanner.lookahead));return X},b2=(Q)=>{while(Q.finalizer===void 0)g8(Q);return Q},g8=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class a1{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Q,X){this.scanner=Q,this.ctx=X}error(Q){return L(Q)}hasRoot(){return this.root!==void 0}setRoot(Q){this.root=Q}unsetRoot(){let Q=this.root;return this.root=void 0,Q}constrainRoot(...Q){this.root=this.root.constrain(Q[0],Q[1])}finalize(Q){if(this.groups.length)return this.error(u2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let Y=t1[X];if(!f(Y,nX))return this.error(J6(X));if(this.branches.leftBound)return this.error(aX(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,Y));this.branches.leftBound={comparator:Y,limit:Q}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Q=this.groups.pop();if(!Q)return this.error(T4(")",this.scanner.unscanned));this.branches=Q}addPrefix(Q){this.branches.prefixes.push(Q)}applyPrefixes(){while(this.branches.prefixes.length){let Q=this.branches.prefixes.pop();this.root=Q==="keyof"?this.root.keyof():C(`Unexpected prefix '${Q}'`)}}pushRootToBranch(Q){this.assertRangeUnset(),this.applyPrefixes();let X=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(X)??X,Q==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Q==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return b2(new a1(this.scanner,this.ctx))}parseOperator(){return PQ(this)}parseOperand(){return wQ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(tX(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(Q){return this.scanner.jumpForward(Q),this}}var x8="An empty string is not a valid generic parameter name",H6=(Q,X,Y)=>{Q.shiftUntilNonWhitespace();let U=Q.shiftUntilLookahead(H1);if(U===""){if(Q.lookahead===""&&X.length)return X;return L(x8)}return Q.shiftUntilNonWhitespace(),h8(Q,U,X,Y)},GY="extends ",h8=(Q,X,Y,U)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(GY))Q.jumpForward(GY.length);else{if(Q.lookahead===",")Q.shift();return Y.push(X),H6(Q,Y,U)}let Z=b2(new a1(Q,U));return Y.push([X,Z.root]),H6(Q,Y,U)};class EQ extends l{constructor(Q){let X={$:Q,raw:Q.fn};super((...Y)=>{let U=Y.indexOf(":"),Z=U===-1?Y.length-1:U-1,W=Y.slice(0,Z+1),G=Q.parse(W).assertHasKind("intersection"),_=Q.intrinsic.unknown;if(U!==-1){if(U!==Y.length-2)return L(p8);_=Q.parse(Y[U+1])}return(H)=>new _Y(H,G,_)},{attach:X})}}class _Y extends l{raw;params;returns;expression;constructor(Q,X,Y){let U=`typed ${Q.name}`,Z={[U]:(...G)=>{let _=X.assert(G),H=Q(..._);return Y.assert(H)}}[U];super(Z);this.raw=Q,this.params=X,this.returns=Y;let W=X.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${Y?.expression??"unknown"}`}}var p8=`":" must be followed by exactly one return type e.g:
|
|
46
|
-
fn("string", ":", "number")(s => s.length)`;class IQ extends l{$;constructor(Q){super((...X)=>new y2(Q)(...X),{bind:Q});this.$=Q}in(Q){return new y2(this.$,Q===void 0?void 0:this.$.parse(Q))}at(Q,X){return new y2(this.$).at(Q,X)}case(Q,X){return new y2(this.$).case(Q,X)}}class y2 extends l{$;in;key;branches=[];constructor(Q,X){super((Y)=>this.caseEntries(Object.entries(Y).map(([U,Z])=>U==="default"?[U,Z]:[this.$.parse(U),Z])));this.$=Q,this.in=X}at(Q,X){if(this.key)L(m8);if(this.branches.length)L(u8);return this.key=Q,X?this.match(X):this}case(Q,X){return this.caseEntry(this.$.parse(Q),X)}caseEntry(Q,X){let U=(this.key?this.$.parse({[this.key]:Q}):Q).pipe(X);return this.branches.push(U),this}match(Q){return this(Q)}strings(Q){return this.caseEntries(Object.entries(Q).map(([X,Y])=>X==="default"?[X,Y]:[this.$.node("unit",{unit:X}),Y]))}caseEntries(Q){for(let X=0;X<Q.length;X++){let[Y,U]=Q[X];if(Y==="default"){if(X!==Q.length-1)L("default may only be specified as the last key of a switch definition");return this.default(U)}if(typeof U!=="function")return L(`Value for case "${Y}" must be a function (was ${y(U)})`);this.caseEntry(Y,U)}return this}default(Q){if(typeof Q==="function")this.case(z.unknown,Q);let X={branches:this.branches,ordered:!0};if(Q==="never"||Q==="assert")X.meta={onFail:JY};let Y=this.$.node("union",X);if(!this.in)return this.$.finalize(Y);let U=this.in.pipe(Y);if(Q==="never"||Q==="assert")U=U.configureReferences({onFail:JY},"self");return this.$.finalize(U)}}var JY=(Q)=>Q.throw(),u8="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",m8="At most one key matcher may be specified per expression";var F6=(Q,X)=>{if(K(Q)){if(Q[1]==="=")return[X.$.parseOwnDefinitionFormat(Q[0],X),"=",Q[2]];if(Q[1]==="?")return[X.$.parseOwnDefinitionFormat(Q[0],X),"?"]}return q6(Q,X)},LY="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",HY="Only required keys may specify default values, e.g. { value: 'number = 0' }";var FY=(Q,X)=>{let Y,U={},Z=N1(Q);for(let[G,_]of Z){let H=c8(G);if(H.kind==="spread"){if(!J1(U))return L(d8);let b=X.$.parseOwnDefinitionFormat(_,X);if(b.equals(z.object))continue;if(!b.hasKind("intersection")||!b.basis?.equals(z.object))return L(o8(b.expression));Y=b.structure;continue}if(H.kind==="undeclared"){if(_!=="reject"&&_!=="delete"&&_!=="ignore")L(l8(_));U.undeclared=_;continue}let J=F6(_,X),$=H;if(H.kind==="required"){if(!K(J))SQ(U,"required",{key:H.normalized,value:J},X);else SQ(U,"optional",J[1]==="="?{key:H.normalized,value:J[0],default:J[2]}:{key:H.normalized,value:J[0]},X);continue}if(K(J)){if(J[1]==="?")L(LY);if(J[1]==="=")L(HY)}if(H.kind==="optional"){SQ(U,"optional",{key:H.normalized,value:J},X);continue}let O=X.$.parseOwnDefinitionFormat($.normalized,X),R=Q6(O,J,X.$);if(R.index)U.index=D(U.index,R.index);if(R.required)U.required=D(U.required,R.required)}let W=X.$.node("structure",U);return X.$.parseSchema({domain:"object",structure:Y?.merge(W)??W})},SQ=(Q,X,Y,U)=>{Q[X]=D(Q[X],U.$.node(X,Y))},l8=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${B(Q)})`,d8="Spread operator may only be used as the first key in an object",c8=(Q)=>typeof Q==="symbol"?{kind:"required",normalized:Q}:Q[Q.length-1]==="?"?Q[Q.length-2]===I1?{kind:"required",normalized:`${Q.slice(0,-2)}?`}:{kind:"optional",normalized:Q.slice(0,-1)}:Q[0]==="["&&Q[Q.length-1]==="]"?{kind:"index",normalized:Q.slice(1,-1)}:Q[0]===I1&&Q[1]==="["&&Q[Q.length-1]==="]"?{kind:"required",normalized:Q.slice(1)}:Q==="..."?{kind:"spread"}:Q==="+"?{kind:"undeclared"}:{kind:"required",normalized:Q==="\\..."?"...":Q==="\\+"?"+":Q},o8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var $Y=(Q,X)=>Y3(Q)?VY[Q[0]](Q,X):Q3(Q)?OY[Q[1]](Q,X):null,i8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),jQ=(Q,X)=>{if(Q[2]===void 0)return L(CQ(Q[1],""));let Y=X.$.parseOwnDefinitionFormat(Q[0],X),U=X.$.parseOwnDefinitionFormat(Q[2],X);if(Q[1]==="|")return X.$.node("union",{branches:[Y,U]});let Z=Q[1]==="&"?o(Y,U,X.$):D2(Y,U,X.$);if(Z instanceof q)return Z.throw();return Z},s8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),n8=(Q,X)=>{if(typeof Q[2]!=="function")return L(AY("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},AY=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,r8=(Q,X)=>{if(typeof Q[2]!=="function")return L(AY(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},t8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),zY=(Q)=>Q,a8=zY({"[]":s8,"?":()=>L(W6)}),e8=zY({"|":jQ,"&":jQ,":":r8,"=>":n8,"|>":jQ,"@":t8,"=":()=>L(G6)}),OY={...a8,...e8},Q3=(Q)=>OY[Q[1]]!==void 0,X3=(Q)=>Q,VY=X3({keyof:i8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return L(qY(L2(Q[1])));let Y=Q.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):L(qY(L2(U))));return Y.length===1?Y[0]:X.$.node("union",{branches:Y})},"===":(Q,X)=>X.$.units(Q.slice(1))}),Y3=(Q)=>VY[Q[0]]!==void 0,qY=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var TY=(Q,X)=>{let Y=[{}],U=0;while(U<Q.length){let Z=!1;if(Q[U]==="..."&&U<Q.length-1)Z=!0,U++;let W=F6(Q[U],X),[G,_,H]=!K(W)?[W]:W;if(U++,Z){if(!G.extends(F.intrinsic.Array))return L(W3(G.expression));Y=Y.flatMap((J)=>G.distribute(($)=>Z3(l2(J),$)))}else Y=Y.map((J)=>{if(_==="?")return DY(J,G);if(_==="=")return U3(J,G,H);return bQ(J,G)})}return X.$.parseSchema(Y.map((Z)=>J1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},bQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return L(Q.variadic?HQ:G3);if(Q.variadic)Q.postfix=D(Q.postfix,X);else Q.prefix=D(Q.prefix,X);return Q},DY=(Q,X)=>{if(Q.variadic)return L(RY);return Q.optionals=D(Q.optionals,X),Q},U3=(Q,X,Y)=>{if(Q.variadic)return L(RY);if(Q.optionals)return L(_3);return Q.defaultables=D(Q.defaultables,[[X,Y]]),Q},BY=(Q,X)=>{if(Q.postfix)L(MY);if(Q.variadic){if(!Q.variadic.equals(X))L(MY)}else Q.variadic=X.internal;return Q},Z3=(Q,X)=>{let Y=X.select({method:"find",kind:"sequence"});if(!Y)return BY(Q,F.intrinsic.unknown);if(Y.prefix)for(let U of Y.prefix)bQ(Q,U);if(Y.optionals)for(let U of Y.optionals)DY(Q,U);if(Y.variadic)BY(Q,Y.variadic);if(Y.postfix)for(let U of Y.postfix)bQ(Q,U);return Q},W3=(Q)=>`Spread element must be an array (was ${Q})`,MY="A tuple may have at most one variadic element",G3="A required element may not follow an optional element",RY="An optional element may not follow a variadic element";var _3="A defaultable element may not follow an optional element without a default";var J3={},q6=(Q,X)=>{if(typeof Q==="string"){if(X.args&&Object.keys(X.args).some((U)=>Q.includes(U)))return NQ(Q,X);let Y=J3[X.$.name]??={};return Y[Q]??=NQ(Q,X)}return p(Q,"object")?L3(Q,X):L(yQ(y(Q)))},L3=(Q,X)=>{let Y=J2(Q);switch(Y){case void 0:if(A(Q,"root"))return Q;if("~standard"in Q)return H3(Q,X);return FY(Q,X);case"Array":return F3(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let U=M1(Q)?Q():Q;if(A(U,"root"))return U;return L(yQ("Function"))}default:return L(yQ(Y??B(Q)))}},H3=(Q,X)=>X.$.intrinsic.unknown.pipe((Y,U)=>{let Z=Q["~standard"].validate(Y);if(!Z.issues)return Z.value;for(let{message:W,path:G}of Z.issues)if(G)if(G.length)U.error({problem:_4(W),relativePath:G.map((_)=>typeof _==="object"?_.key:_)});else U.error({message:W});else U.error({message:W})}),F3=(Q,X)=>$Y(Q,X)??TY(Q,X),yQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class fQ extends l{constructor(Q){let X=Object.assign({errors:d,hkt:k,$:Q,raw:Q.parse,module:Q.constructor.module,scope:Q.constructor.scope,declare:Q.declare,define:Q.define,match:Q.match,generic:Q.generic,schema:Q.schema,keywords:Q.ambient,unit:Q.unit,enumerated:Q.enumerated,instanceOf:Q.instanceOf,valueOf:Q.valueOf,or:Q.or,and:Q.and,merge:Q.merge,pipe:Q.pipe,fn:Q.fn},Q.ambientAttachments);super((...Y)=>{if(Y.length===1)return Q.parse(Y[0]);if(Y.length===2&&typeof Y[0]==="string"&&Y[0][0]==="<"&&Y[0][Y[0].length-1]===">"){let U=Y[0].slice(1,-1),Z=Q.parseGenericParams(U,{});return new w1(Z,Y[1],Q,Q,null)}return Q.parse(Y)},{attach:X})}}var e1=F;class $6 extends X6{get ambientAttachments(){if(!e1.typeAttachments)return;return this.cacheGetter("ambientAttachments",V(e1.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let Y=Q.indexOf("<");if(Y===-1){if(A(X,"module")||A(X,"generic"))return[Q,X];let W=this.name==="ark"?Q:Q==="root"?this.name:`${this.name}.${Q}`,G=this.resolvedConfig.keywords?.[W];if(G)X=[X,"@",G];return[Q,X]}if(Q[Q.length-1]!==">")L("'>' must be the last character of a generic declaration in a scope");let U=Q.slice(0,Y),Z=Q.slice(Y+1,-1);return[U,()=>{let W=this.parseGenericParams(Z,{alias:U});return v4(W,X,this)}]}parseGenericParams(Q,X){return H6(new O2(Q),[],this.createParseContext({...X,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(M1(Q)&&!A(Q,"generic"))return Q();return Q}preparseOwnDefinitionFormat(Q,X){return{...X,def:Q,prefix:X.alias??"type"}}parseOwnDefinitionFormat(Q,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let U=q6(Q,X);if(K(U)){if(U[1]==="=")return L(G6);if(U[1]==="?")return L(W6)}return U}unit=(Q)=>this.units([Q]);valueOf=(Q)=>this.units(aQ(Q));enumerated=(...Q)=>this.units(Q);instanceOf=(Q)=>this.node("proto",{proto:Q},{prereduced:!0});or=(...Q)=>this.schema(Q.map((X)=>this.parse(X)));and=(...Q)=>Q.reduce((X,Y)=>X.and(this.parse(Y)),this.intrinsic.unknown);merge=(...Q)=>Q.reduce((X,Y)=>X.merge(this.parse(Y)),this.intrinsic.object);pipe=(...Q)=>this.intrinsic.unknown.pipe(...Q);fn=new EQ(this);match=new IQ(this);declare=()=>({type:this.type});define(Q){return Q}type=new fQ(this);static scope=(Q,X={})=>new $6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var f2=Object.assign($6.scope,{define:(Q)=>Q}),T=$6;class CY extends k{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var q3=e(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),CY),wY=T.module({Key:z.key,Merge:q3});class KY extends k{}var $3=e("element")((Q)=>{let X=Q.element.exclude(z.Array),Y=X.array();return X.rawOr(Y).pipe(B1).distribute((U)=>U.assertHasKind("morph").declareOut(Y),w)},KY),PY=T.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:$3},{name:"Array"});var vQ=w(["string",S1.FileConstructor]),A3=vQ.rawOr(vQ.array()),NY=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:A3}}),EY=T.module({root:["instanceof",FormData],value:vQ,parsed:NY,parse:w({in:FormData,morphs:(Q)=>{let X={};for(let[Y,U]of Q)if(Y in X){let Z=X[Y];if(typeof Z==="string"||Z instanceof S1.FileConstructor)X[Y]=[Z,U];else Z.push(U)}else X[Y]=U;return X},declaredOut:NY})},{name:"FormData"});var IY=T.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var z3={Boolean:1,Number:1,String:1},SY=T.module({...V({...C6,...K6},(Q,X)=>(Q in z3)?[]:[Q,["instanceof",X]]),Array:PY,TypedArray:IY,FormData:EY});var O3=w({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),V3=w({domain:"number",divisor:1}),A6=T.module({root:z.number,integer:V3,epoch:O3,safe:w({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var I=(Q,X,Y)=>{let U={domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:X}};if(Y)U.meta={format:Y};return r1("intersection",U)},jY=I(F2,"a well-formed integer string"),lY=T.module({root:jY,parse:w({in:jY,morphs:(Q,X)=>{let Y=Number.parseInt(Q);return Number.isSafeInteger(Y)?Y:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:z.integer})},{name:"string.integer"}),B3=I(/^[\dA-Fa-f]+$/,"hex characters only"),M3=T.module({root:I(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),bY=I(/^[A-Z].*$/,"capitalized"),T3=T.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:bY}),preformatted:bY},{name:"string.capitalize"}),D3=(Q)=>{let X=Q.replace(/[ -]+/g,""),Y=0,U,Z,W=!1;for(let G=X.length-1;G>=0;G--){if(U=X.substring(G,G+1),Z=Number.parseInt(U,10),W)Z*=2,Y+=Z>=10?Z%10+1:Z;else Y+=Z;W=!W}return!!(Y%10===0?X:!1)},R3=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,C3=w({domain:"string",pattern:{meta:"a credit card number",rule:R3.source},predicate:{meta:"a credit card number",predicate:D3}});var w3=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var K3=(Q)=>!Number.isNaN(new Date(Q).valueOf()),yY=w({domain:"string",predicate:{meta:"a parsable date",predicate:K3}}).assertHasKind("intersection"),fY=lY.root.internal.narrow((Q,X)=>{let Y=Number.parseInt(Q),U=A6.epoch(Y);if(U instanceof d)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),P3=T.module({root:fY,parse:w({in:fY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),vY=I(w3,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),N3=T.module({root:vY,parse:w({in:vY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),E3=T.module({root:yY,parse:w({declaredIn:yY,in:"string",morphs:(Q,X)=>{let Y=new Date(Q);if(Number.isNaN(Y.valueOf()))return X.error("a parsable date");return Y},declaredOut:z.Date}),iso:N3,epoch:P3},{name:"string.date"}),I3=I(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),kY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",K1=`(${kY}[.]){3}${kY}`,S3=new RegExp(`^${K1}$`),j="(?:[0-9a-fA-F]{1,4})",j3=new RegExp(`^((?:${j}:){7}(?:${j}|:)|(?:${j}:){6}(?:${K1}|:${j}|:)|(?:${j}:){5}(?::${K1}|(:${j}){1,2}|:)|(?:${j}:){4}(?:(:${j}){0,1}:${K1}|(:${j}){1,3}|:)|(?:${j}:){3}(?:(:${j}){0,2}:${K1}|(:${j}){1,4}|:)|(?:${j}:){2}(?:(:${j}){0,3}:${K1}|(:${j}){1,5}|:)|(?:${j}:){1}(?:(:${j}){0,4}:${K1}|(:${j}){1,6}|:)|(?::((?::${j}){0,5}:${K1}|(?::${j}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),b3=T.module({root:["v4 | v6","@","an IP address"],v4:I(S3,"an IPv4 address","ipv4"),v6:I(j3,"an IPv6 address","ipv6")},{name:"string.ip"}),Q2="a JSON string",dY=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${Q2} (${Q})`},y3=w({meta:Q2,domain:"string",predicate:{meta:Q2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(Y){return X.reject({code:"predicate",expected:Q2,problem:dY(Y)})}}}}),f3=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:Q2,actual:"empty"});try{return JSON.parse(Q)}catch(Y){return X.error({code:"predicate",expected:Q2,problem:dY(Y)})}},v3=T.module({root:y3,parse:w({meta:"safe JSON string parser",in:"string",morphs:f3,declaredOut:z.jsonObject})},{name:"string.json"}),gY=I(/^[a-z]*$/,"only lowercase letters"),k3=T.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:gY}),preformatted:gY},{name:"string.lower"}),cY=["NFC","NFD","NFKC","NFKD"],v2=V(cY,(Q,X)=>[X,w({domain:"string",predicate:(Y)=>Y.normalize(X)===Y,meta:`${X}-normalized unicode`})]),z6=V(cY,(Q,X)=>[X,w({in:"string",morphs:(Y)=>Y.normalize(X),declaredOut:v2[X]})]),g3=T.module({root:z6.NFC,preformatted:v2.NFC},{name:"string.normalize.NFC"}),x3=T.module({root:z6.NFD,preformatted:v2.NFD},{name:"string.normalize.NFD"}),h3=T.module({root:z6.NFKC,preformatted:v2.NFKC},{name:"string.normalize.NFKC"}),p3=T.module({root:z6.NFKD,preformatted:v2.NFKD},{name:"string.normalize.NFKD"}),u3=T.module({root:"NFC",NFC:g3,NFD:x3,NFKC:h3,NFKD:p3},{name:"string.normalize"}),xY=I(h2,"a well-formed numeric string"),m3=T.module({root:xY,parse:w({in:xY,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),hY="a regex pattern",l3=w({domain:"string",predicate:{meta:hY,predicate:(Q,X)=>{try{return new RegExp(Q),!0}catch(Y){return X.reject({code:"predicate",expected:hY,problem:String(Y)})}}},meta:{format:"regex"}}),d3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,c3=I(d3,"a semantic version (see https://semver.org/)"),pY=I(/^\S.*\S$|^\S?$/,"trimmed"),o3=T.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:pY}),preformatted:pY},{name:"string.trim"}),uY=I(/^[A-Z]*$/,"only uppercase letters"),i3=T.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:uY}),preformatted:uY},{name:"string.upper"}),s3=(Q)=>URL.canParse(Q),mY=w({domain:"string",predicate:{meta:"a URL string",predicate:s3},meta:{format:"uri"}}),n3=T.module({root:mY,parse:w({declaredIn:mY,in:"string",morphs:(Q,X)=>{try{return new URL(Q)}catch{return X.error("a URL string")}},declaredOut:w(URL)})},{name:"string.url"}),r3=T.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:I(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),oY=T.module({root:z.string,alpha:I(/^[A-Za-z]*$/,"only letters"),alphanumeric:I(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:B3,base64:M3,capitalize:T3,creditCard:C3,date:E3,digits:I(/^\d*$/,"only digits 0-9"),email:I3,integer:lY,ip:b3,json:v3,lower:k3,normalize:u3,numeric:m3,regex:l3,semver:c3,trim:o3,upper:i3,url:n3,uuid:r3},{name:"string"});var iY=T.module({bigint:z.bigint,boolean:z.boolean,false:z.false,never:z.never,null:z.null,number:z.number,object:z.object,string:z.string,symbol:z.symbol,true:z.true,unknown:z.unknown,undefined:z.undefined}),sY=T.module({root:z.unknown,any:z.unknown},{name:"unknown"}),t3=T.module({root:z.jsonObject,stringify:r1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),nY=T.module({root:z.object,json:t3},{name:"object"});class rY extends k{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var a3=e(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),rY);class tY extends k{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var e3=e(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),tY);class aY extends k{description='omit a set of properties from an object like `Omit(User, "age")`'}var Q9=e(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),aY);class eY extends k{description="make all named properties of an object optional like `Partial(User)`"}var X9=e(["T",z.object])((Q)=>Q.T.partial(),eY);class QU extends k{description="make all named properties of an object required like `Required(User)`"}var Y9=e(["T",z.object])((Q)=>Q.T.required(),QU);class XU extends k{description='exclude branches of a union like `Exclude("boolean", "true")`'}var U9=e("T","U")((Q)=>Q.T.exclude(Q.U),XU);class YU extends k{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var Z9=e("T","U")((Q)=>Q.T.extract(Q.U),YU),UU=T.module({Exclude:U9,Extract:Z9,Omit:Q9,Partial:X9,Pick:e3,Record:a3,Required:Y9});var V1=f2({...iY,...UU,...SY,...wY,string:oY,number:A6,object:nY,unknown:sY},{prereducedAliases:!0,name:"ark"}),v=V1.export();Object.assign(e1.ambient,v);e1.typeAttachments={string:v.string.root,number:v.number.root,bigint:v.bigint,boolean:v.boolean,symbol:v.symbol,undefined:v.undefined,null:v.null,object:v.object.root,unknown:v.unknown.root,false:v.false,true:v.true,never:v.never,arrayIndex:v.Array.index,Key:v.Key,Record:v.Record,Array:v.Array.root,Date:v.Date};var kQ=Object.assign(V1.type,e1.typeAttachments),W9=V1.match,G9=V1.fn,_9=V1.generic,Nq=V1.schema,J9=V1.define,L9=V1.declare;var y1=f2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition",RangeCondition:{field:"string > 0",operator:"'RANGE'",value:"unknown[] == 2"},ListCondition:{field:"string > 0",operator:"'IN' | 'NOT_IN'",value:"unknown[]"},ContainsCondition:{field:"string > 0",operator:"'CONTAINS'",value:"string | unknown[]"},NumericCondition:{field:"string > 0",operator:"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'",value:"number | string"},RegexCondition:{field:"string > 0",operator:"'MATCHES'",value:"string"},BasicCondition:{field:"string > 0",operator:"Operator",value:"unknown"},ConditionGroup:{operator:"'AND' | 'OR'",conditions:"(Condition | ConditionGroup)[] >= 1"},RuleCondition:"Condition | ConditionGroup",Action:{type:"string > 0","params?":"object","delay?":"number.integer >= 0","probability?":"0 <= number <= 1"},ActionGroup:{"mode?":"'ALL' | 'EITHER' | 'SEQUENCE'",actions:"(Action | ActionGroup)[] >= 1"},RuleAction:"Action | ActionGroup",TriggerRule:{id:"string > 0","name?":"string","description?":"string","priority?":"number.integer","enabled?":"boolean","cooldown?":"number.integer >= 0","tags?":"string[]",on:"string > 0","if?":"RuleCondition | RuleCondition[]",do:"RuleAction | RuleAction[]","comment?":"string"}}).export(),cq=y1.Operator,oq=y1.Condition,iq=y1.ConditionGroup,sq=y1.RuleCondition,nq=y1.Action,rq=y1.ActionGroup,H9=y1.TriggerRule;class F9{static validate(Q){let X=H9(Q);if(X instanceof kQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),_=W.message,H=void 0;if(G.endsWith("on")&&(_.includes("string")||_.includes("must be")))if(typeof Q==="object"&&Q!==null&&"on"in Q&&Q.on===!0)_="The 'on' field is incorrect (boolean true found).",H=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else H="Ensure 'on' is a string event name.";Z.push({path:G,message:_,suggestion:H,severity:"error"})}return{valid:!1,issues:Z}}let Y=X,U=[];if(this.validateConditionsRecursive(Y.if,U,"if"),U.length>0)return{valid:!1,issues:U};return{valid:!0,rule:Y}}static validateConditionsRecursive(Q,X,Y){if(!Q)return;if(Array.isArray(Q)){Q.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"conditions"in Q&&Array.isArray(Q.conditions)){Q.conditions.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.conditions.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"operator"in Q&&"value"in Q)this.validateConditionValue(Q,X,Y)}static validateConditionValue(Q,X,Y){let{operator:U,value:Z}=Q;if(typeof U==="string"&&["IN","NOT_IN","RANGE","CONTAINS"].includes(U)){if(U==="CONTAINS"){if(typeof Z!=="string"&&!Array.isArray(Z))X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof Z}.`,suggestion:"Use a substring or a list of items.",severity:"error"});return}if(!Array.isArray(Z)){X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a List (Array), but received ${typeof Z}.`,suggestion:U==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(U==="RANGE"){if(Z.length!==2)X.push({path:`${Y}.value`,message:"Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).",suggestion:"Use format [min, max], e.g. [1, 10]",severity:"error"});else if(typeof Z[0]!=="number"&&typeof Z[0]!=="string")X.push({path:`${Y}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(U==="MATCHES")if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof Z}.`,severity:"error"});else try{new RegExp(Z)}catch(W){X.push({path:`${Y}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(typeof U==="string"&&["GT","GTE","LT","LTE",">",">=","<","<="].includes(U)){if(typeof Z!=="number"&&typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a number or expression string, but received ${typeof Z}.`,severity:"error"})}}}export{F9 as TriggerValidator,Y2 as TriggerUtils,H9 as TriggerRuleSchema,W2 as TriggerEngine,Q1 as StateManager,T6 as RuleEngine,sq as RuleConditionSchema,B6 as InMemoryPersistence,i as ExpressionEngine,JU as EventQueue,W2 as Engine,HU as ContextAdapter,oq as ConditionSchema,iq as ConditionGroupSchema,cq as ComparisonOperatorSchema,hQ as BrowserPersistence,T6 as AdvancedRuleEngine,nq as ActionSchema,v1 as ActionRegistry,rq as ActionGroupSchema};
|
|
45
|
+
`)+"}");class X6{config;resolvedConfig;name;get[h](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Q,X){if(this.config=B2(F.config,X),this.resolvedConfig=B2(F.resolvedConfig,X),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(OQ).length}`,this.name in OQ)H(`A Scope already named ${this.name} already exists`);OQ[this.name]=this;let Y=Object.entries(Q).map((U)=>this.preparseOwnAliasEntry(...U));for(let[U,Z]of Y){let W=U;if(U[0]==="#"){if(W=U.slice(1),W in this.aliases)H(fX(W));this.aliases[W]=Z}else{if(W in this.aliases)H(fX(U));this.aliases[W]=Z,this.exportedNames.push(W)}if(!$(Z,"module")&&!$(Z,"generic")&&!M1(Z)){let G=this.preparseOwnDefinitionFormat(Z,{alias:W});this.resolutions[W]=$(G,"root")?this.bindReference(G):this.createParseContext(G).id}}bX??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[bX.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?V(F.intrinsic,(U,Z)=>U.startsWith("json")?[]:[U,this.bindReference(Z)]):{}}cacheGetter(Q,X){return Object.defineProperty(this,Q,{value:X}),X}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Q){return Q}generic=(...Q)=>{let X=this;return(Y,U)=>new w1(Q,U?new i2(Y):Y,X,X,U??null)};units=(Q,X)=>{let Y=[];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);let U=Y.map((Z)=>this.node("unit",{unit:Z},X));return this.node("union",U,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,X){let Y=this.node("alias",{reference:X??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Y);return Y}schema=(Q,X)=>this.finalize(this.parseSchema(Q,X));parseSchema=(Q,X)=>this.node(R2(Q),Q,X);preparseNode(Q,X,Y){let U=typeof Q==="string"?Q:R2(X,Q);if(P(X)&&X.kind===U)return X;if(U==="alias"&&!Y?.prereduced){let{reference:G}=I2.implementation.normalize(X,this);if(G.startsWith("$")){let _=this.resolveRoot(G.slice(1));X=_,U=_.kind}}else if(U==="union"&&u(X,"object")){let G=T8(X);if(G?.length===1)X=G[0],U=R2(X)}if(P(X)&&X.kind===U)return X;let W=o1[U].normalize?.(X,this)??X;if(P(W))return W.kind===U?W:D8(U,W.kind);return{...Y,$:this,kind:U,def:W,prefix:Y.alias??U}}bindReference(Q){let X;if(P(Q))X=Q.$===this?Q:new Q.constructor(Q.attachments,this);else X=Q.$===this?Q:new w1(Q.params,Q.bodyDef,Q.$,this,Q.hkt);if(!this.resolved)Object.assign(this.referencesById,X.referencesById);return X}resolveRoot(Q){return this.maybeResolveRoot(Q)??H(MQ(Q))}maybeResolveRoot(Q){let X=this.maybeResolve(Q);if($(X,"generic"))return;return X}maybeResolveSubalias(Q){return VQ(this.aliases,Q)??VQ(this.ambient,Q)}get ambient(){return F.ambient}maybeResolve(Q){let X=this.resolutions[Q];if(X){if(typeof X!=="string")return this.bindReference(X);let U=p[X];if($(U,"root"))return this.resolutions[Q]=U;if($(U,"context")){if(U.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(U.phase==="resolved")return C(`Unexpected resolved context for was uncached by its scope: ${B(U)}`);U.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",p[Z.id]=Z,p[U.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${B(U)}`)}let Y=this.aliases[Q]??this.ambient?.[Q];if(!Y)return this.maybeResolveSubalias(Q);if(Y=this.normalizeRootScopeValue(Y),$(Y,"generic"))return this.resolutions[Q]=this.bindReference(Y);if($(Y,"module")){if(!Y.root)H(pX(Q));return this.resolutions[Q]=this.bindReference(Y.root)}return this.resolutions[Q]=this.parse(Y,{alias:Q})}createParseContext(Q){let X=Q.id??e6(Q.prefix);return p[X]=Object.assign(Q,{[h]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new U1(Q,this.resolvedConfig)}import(...Q){return new n1(V(this.export(...Q),(X,Y)=>[`#${X}`,Y]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let Y of this.exportedNames){let U=this.aliases[Y];this._exports[Y]=$(U,"module")?zQ(U,this):yX(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=hX(this,this._exports),this._json=xX(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=gX(this.references);this.precompilation=Y.write(vX,4),kX(this.references,Y)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(V(X,(Y,U)=>[U,this._exports[U]]))}resolve(Q){return this.export()[Q]}node=(Q,X,Y={})=>{let U=this.preparseNode(Q,X,Y);if(P(U))return this.bindReference(U);let Z=this.createParseContext(U),W=QQ(Z),G=this.bindReference(W);return p[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if($(Q,"root"))return this.bindReference(Q);let Y=this.preparseOwnDefinitionFormat(Q,X);if($(Y,"root"))return this.bindReference(Y);let U=this.createParseContext(Y);p[U.id]=U;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,U));if(Z.isCyclic)Z=YX(Z,U.id);return p[U.id]=Z,Z}finalize(Q){if(yX(Q),!Q.precompilation&&!this.resolvedConfig.jitless)R8(Q.references);return Q}}class BQ extends X6{parseOwnDefinitionFormat(Q,X){return QQ(X)}preparseOwnDefinitionFormat(Q,X){return this.preparseNode(R2(Q),Q,X)}preparseOwnAliasEntry(Q,X){return[Q,X]}normalizeRootScopeValue(Q){return Q}}var yX=(Q)=>{let X=Q.references.filter((Y)=>Y.hasKind("alias"));for(let Y of X){Object.assign(Y.referencesById,Y.resolution.referencesById);for(let U of Q.references)if(Y.id in U.referencesById)Object.assign(U.referencesById,Y.referencesById)}return Q},xX=(Q)=>V(Q,(X,Y)=>[X,$(Y,"root")||$(Y,"generic")?Y.json:$(Y,"module")?xX(Y):C(`Unexpected resolution ${B(Y)}`)]),VQ=(Q,X)=>{let Y=X.indexOf(".");if(Y===-1)return;let U=X.slice(0,Y),Z=Q[U];if(Z===void 0)return;if(!$(Z,"module"))return H(C8(U));let W=X.slice(Y+1),G=Z[W];if(G===void 0)return VQ(Z,W);if($(G,"root")||$(G,"generic"))return G;if($(G,"module"))return G.root??H(pX(X));C(`Unexpected resolution for alias '${X}': ${B(G)}`)},Y6=(Q,X)=>new BQ(Q,X),j2=new BQ({});var hX=(Q,X)=>{let Y={};for(let U in X){let Z=X[U];if($(Z,"module")){let W=hX(Q,Z),G=V(W,(_,L)=>[`${U}.${_}`,L]);Object.assign(Y,G)}else if($(Z,"root")||$(Z,"generic"))Y[U]=Z;else C(`Unexpected scope resolution ${B(Z)}`)}return Y},MQ=(Q)=>`'${Q}' is unresolvable`,C8=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,pX=(Q)=>`Reference to submodule '${Q}' must specify an alias`;j2.export();var{schema:w,node:r1,defineSchema:t7,generic:e}=j2;var TQ="^(?:0|[1-9]\\d*)$",w8=new RegExp(TQ),QL=S(w8);var uX=Y6({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();F.intrinsic={...uX};var mX=Y6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:TQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,mX);var K8=Y6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),z={...uX,...mX,...K8,emptyStructure:r1("structure",{},{prereduced:!0})};F.intrinsic={...z};var U6=(Q,X)=>new RegExp(Q,X);Object.assign(U6,{as:U6});var dX=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],lX=(Q)=>Q.toString()!=="Invalid Date",cX=(Q)=>Q.slice(2,-1),DQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,oX=(Q,X)=>P8(Q,X),P8=(Q,X)=>{let Y=new Date(Q);if(lX(Y))return Y;let U=B4(Q);if(U!==void 0){let Z=new Date(U);if(lX(Z))return Z}return X?H(X===!0?DQ(Q):X):void 0};var N8=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Z6=(Q,X)=>{let Y=Q.scanner.shiftUntilEscapable(E8[nX[X]]);if(Q.scanner.lookahead==="")return Q.error(j8(Y,X));if(Q.scanner.shift(),X in sX){let U;try{U=new RegExp(Y)}catch(Z){H(String(Z))}if(Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0}),X==="x/")Q.root=Q.ctx.$.node("morph",{in:Q.root,morphs:(Z)=>U.exec(Z),declaredOut:N8})}else if(y(X,RQ))Q.root=Q.ctx.$.node("unit",{unit:Y});else{let U=oX(Y,DQ(Y));Q.root=Q.ctx.$.node("unit",{meta:Y,unit:U})}},RQ={"'":1,'"':1},iX={"/":1,"'":1,'"':1},I8={"d'":"'",'d"':'"',"'":"'",'"':'"'},sX={"/":"/","x/":"/"},nX={...I8,...sX},E8={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},S8={'"':"double-quote","'":"single-quote","/":"forward slash"},j8=(Q,X)=>`${X}${Q} requires a closing ${S8[nX[X]]}`;var rX=(Q)=>`Private type references should not include '#'. Use '${Q}' instead.`,W6="Optional definitions like 'string?' are only valid as properties in an object or tuple",G6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var H1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...T1};var tX=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||y(X.trimStart()[0],H1):Q==="="?X[0]!=="=":Q===","||Q==="?";var aX=(Q,X,Y)=>eX(Q,X,Y,[]),eX=(Q,X,Y,U)=>{let Z=Y.parseUntilFinalizer();if(U.push(Z.root),Z.finalizer===">"){if(U.length!==X.params.length)return Y.error(CQ(Q,X.names,U.map((W)=>W.expression)));return U}if(Z.finalizer===",")return eX(Q,X,Y,U);return Z.error(u2(">"))},CQ=(Q,X,Y)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var _6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(H1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=b8(Q,X)},f8=(Q,X,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(CQ(Q,X.names,[]));let Z=aX(Q,X,Y);return X(...Z)},b8=(Q,X)=>y8(Q,X)??v8(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?rX(Q.shiftedBy(1).scanner.shiftUntilLookahead(H1)):wQ(Q):MQ(X)),y8=(Q,X)=>{if(Q.ctx.args?.[X]){let U=Q.ctx.args[X];if(typeof U!=="string")return U;return Q.ctx.$.node("alias",{reference:U},{prereduced:!0})}let Y=Q.ctx.$.maybeResolve(X);if($(Y,"root"))return Y;if(Y===void 0)return;if($(Y,"generic"))return f8(X,Y,Q);return H(`Unexpected resolution ${B(Y)}`)},v8=(Q,X)=>{let Y=M4(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y});let U=D4(X);if(U!==void 0)return Q.ctx.$.node("unit",{unit:U})},wQ=(Q)=>{let X=Q.previousOperator();return X?KQ(X,Q.scanner.unscanned):k8(Q.scanner.unscanned)},KQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,k8=(Q)=>`Expected an expression${Q?` before '${Q}'`:""}`;var PQ=(Q)=>Q.scanner.lookahead===""?Q.error(wQ(Q)):Q.scanner.lookahead==="("?Q.shiftedBy(1).reduceGroupOpen():Q.scanner.lookaheadIsIn(iX)?Z6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(T1)?PQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in RQ?Z6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):_6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&Z6(Q,"x/"):_6(Q):_6(Q);var QY={">":!0,">=":!0},XY={"<":!0,"<=":!0};var t1={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},YY=(Q,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Q})`,J6=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,UY=(Q,X,Y,U)=>`An expression may have at most one left bound (parsed ${Q}${t1[X]}, ${Y}${t1[U]})`;var WY=(Q,X)=>{let Y=g8(Q,X);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,Y),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let U=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(U,Y);return}}return h8(Q,Y)},GY={"<":1,">":1,"=":1},g8=(Q,X)=>Q.scanner.lookaheadIs("=")?`${X}${Q.scanner.shift()}`:X;var ZY=(Q,X,Y,U)=>{if(Y.extends(F.intrinsic.number)){if(typeof X!=="number")return H(NQ(Q,X,U));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(Y.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return H(NQ(Q,X,U));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(Y.extends(F.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return H(l4(Y.expression))},x8=(Q)=>({rule:dX(Q.limit)?cX(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),h8=(Q,X)=>{let Y=Q.unsetRoot(),U=Q.scanner.location;Q.parseOperand();let Z=Q.unsetRoot(),W=Q.scanner.sliceChars(U,Q.scanner.location);if(Q.root=Y,!Z.hasKind("unit")||typeof Z.unit!=="number"&&!(Z.unit instanceof Date))return Q.error(NQ(X,W,"right"));let G=Z.unit,_=X.length===1,L=ZY(X,typeof G==="number"?G:W,Y,"right");for(let A of L)Q.constrainRoot(A,X==="=="?{rule:G}:{rule:G,exclusive:_});if(!Q.branches.leftBound)return;if(!y(X,XY))return Q.error(J6(X));let J=ZY(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,Y,"left");Q.constrainRoot(J[0],x8(Q.branches.leftBound)),Q.branches.leftBound=null},NQ=(Q,X,Y)=>`Comparator ${Y==="left"?t1[Q]:Q} must be ${Y==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var _Y=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1);Q.root=Q.root.brand(X)};var LY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1),Y=T4(X,{errorOnFail:JY(X)});if(Y===0)Q.error(JY(0));Q.root=Q.root.constrain("divisor",Y)},JY=(Q)=>`% operator must be followed by a non-zero integer literal (was ${Q})`;var IQ=(Q)=>{let X=Q.scanner.shift();return X===""?Q.finalize(""):X==="["?Q.scanner.shift()==="]"?Q.setRoot(Q.root.array()):Q.error(p8):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():tX(X,Q.scanner.unscanned)?Q.finalize(X):y(X,GY)?WY(Q,X):X==="%"?LY(Q):X==="#"?_Y(Q):(X in T1)?IQ(Q):Q.error(L6(X))},L6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,p8="Missing expected ']'";var HY=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let Y=Q.unsetRoot();if(!Y.hasKind("unit"))return Q.error(u8(Y.expression));let U=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[X,"=",U]},u8=(Q)=>`Default value '${Q}' must be a literal value`;var EQ=(Q,X)=>{let Y=X.$.maybeResolveRoot(Q);if(Y)return Y;if(Q.endsWith("[]")){let W=X.$.maybeResolveRoot(Q.slice(0,-2));if(W)return W.array()}let U=new a1(new O2(Q),X),Z=m8(U);if(U.finalizer===">")H(L6(">"));return Z},m8=(Q)=>{Q.parseOperand();let X=f2(Q).root;if(!X)return C(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")X=HY(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)H(L6(Q.scanner.lookahead));return X},f2=(Q)=>{while(Q.finalizer===void 0)l8(Q);return Q},l8=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class a1{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Q,X){this.scanner=Q,this.ctx=X}error(Q){return H(Q)}hasRoot(){return this.root!==void 0}setRoot(Q){this.root=Q}unsetRoot(){let Q=this.root;return this.root=void 0,Q}constrainRoot(...Q){this.root=this.root.constrain(Q[0],Q[1])}finalize(Q){if(this.groups.length)return this.error(u2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let Y=t1[X];if(!y(Y,QY))return this.error(J6(X));if(this.branches.leftBound)return this.error(UY(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,Y));this.branches.leftBound={comparator:Y,limit:Q}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Q=this.groups.pop();if(!Q)return this.error(K4(")",this.scanner.unscanned));this.branches=Q}addPrefix(Q){this.branches.prefixes.push(Q)}applyPrefixes(){while(this.branches.prefixes.length){let Q=this.branches.prefixes.pop();this.root=Q==="keyof"?this.root.keyof():C(`Unexpected prefix '${Q}'`)}}pushRootToBranch(Q){this.assertRangeUnset(),this.applyPrefixes();let X=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(X)??X,Q==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Q==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return f2(new a1(this.scanner,this.ctx))}parseOperator(){return IQ(this)}parseOperand(){return PQ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(YY(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(Q){return this.scanner.jumpForward(Q),this}}var d8="An empty string is not a valid generic parameter name",H6=(Q,X,Y)=>{Q.shiftUntilNonWhitespace();let U=Q.shiftUntilLookahead(H1);if(U===""){if(Q.lookahead===""&&X.length)return X;return H(d8)}return Q.shiftUntilNonWhitespace(),c8(Q,U,X,Y)},FY="extends ",c8=(Q,X,Y,U)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(FY))Q.jumpForward(FY.length);else{if(Q.lookahead===",")Q.shift();return Y.push(X),H6(Q,Y,U)}let Z=f2(new a1(Q,U));return Y.push([X,Z.root]),H6(Q,Y,U)};class SQ extends d{constructor(Q){let X={$:Q,raw:Q.fn};super((...Y)=>{let U=Y.indexOf(":"),Z=U===-1?Y.length-1:U-1,W=Y.slice(0,Z+1),G=Q.parse(W).assertHasKind("intersection"),_=Q.intrinsic.unknown;if(U!==-1){if(U!==Y.length-2)return H(o8);_=Q.parse(Y[U+1])}return(L)=>new qY(L,G,_)},{attach:X})}}class qY extends d{raw;params;returns;expression;constructor(Q,X,Y){let U=`typed ${Q.name}`,Z={[U]:(...G)=>{let _=X.assert(G),L=Q(..._);return Y.assert(L)}}[U];super(Z);this.raw=Q,this.params=X,this.returns=Y;let W=X.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${Y?.expression??"unknown"}`}}var o8=`":" must be followed by exactly one return type e.g:
|
|
46
|
+
fn("string", ":", "number")(s => s.length)`;class jQ extends d{$;constructor(Q){super((...X)=>new b2(Q)(...X),{bind:Q});this.$=Q}in(Q){return new b2(this.$,Q===void 0?void 0:this.$.parse(Q))}at(Q,X){return new b2(this.$).at(Q,X)}case(Q,X){return new b2(this.$).case(Q,X)}}class b2 extends d{$;in;key;branches=[];constructor(Q,X){super((Y)=>this.caseEntries(Object.entries(Y).map(([U,Z])=>U==="default"?[U,Z]:[this.$.parse(U),Z])));this.$=Q,this.in=X}at(Q,X){if(this.key)H(s8);if(this.branches.length)H(i8);return this.key=Q,X?this.match(X):this}case(Q,X){return this.caseEntry(this.$.parse(Q),X)}caseEntry(Q,X){let U=(this.key?this.$.parse({[this.key]:Q}):Q).pipe(X);return this.branches.push(U),this}match(Q){return this(Q)}strings(Q){return this.caseEntries(Object.entries(Q).map(([X,Y])=>X==="default"?[X,Y]:[this.$.node("unit",{unit:X}),Y]))}caseEntries(Q){for(let X=0;X<Q.length;X++){let[Y,U]=Q[X];if(Y==="default"){if(X!==Q.length-1)H("default may only be specified as the last key of a switch definition");return this.default(U)}if(typeof U!=="function")return H(`Value for case "${Y}" must be a function (was ${b(U)})`);this.caseEntry(Y,U)}return this}default(Q){if(typeof Q==="function")this.case(z.unknown,Q);let X={branches:this.branches,ordered:!0};if(Q==="never"||Q==="assert")X.meta={onFail:AY};let Y=this.$.node("union",X);if(!this.in)return this.$.finalize(Y);let U=this.in.pipe(Y);if(Q==="never"||Q==="assert")U=U.configureReferences({onFail:AY},"self");return this.$.finalize(U)}}var AY=(Q)=>Q.throw(),i8="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",s8="At most one key matcher may be specified per expression";var F6=(Q,X)=>{if(K(Q)){if(Q[1]==="=")return[X.$.parseOwnDefinitionFormat(Q[0],X),"=",Q[2]];if(Q[1]==="?")return[X.$.parseOwnDefinitionFormat(Q[0],X),"?"]}return q6(Q,X)},$Y="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",zY="Only required keys may specify default values, e.g. { value: 'number = 0' }";var OY=(Q,X)=>{let Y,U={},Z=N1(Q);for(let[G,_]of Z){let L=t8(G);if(L.kind==="spread"){if(!J1(U))return H(r8);let f=X.$.parseOwnDefinitionFormat(_,X);if(f.equals(z.object))continue;if(!f.hasKind("intersection")||!f.basis?.equals(z.object))return H(a8(f.expression));Y=f.structure;continue}if(L.kind==="undeclared"){if(_!=="reject"&&_!=="delete"&&_!=="ignore")H(n8(_));U.undeclared=_;continue}let J=F6(_,X),A=L;if(L.kind==="required"){if(!K(J))fQ(U,"required",{key:L.normalized,value:J},X);else fQ(U,"optional",J[1]==="="?{key:L.normalized,value:J[0],default:J[2]}:{key:L.normalized,value:J[0]},X);continue}if(K(J)){if(J[1]==="?")H($Y);if(J[1]==="=")H(zY)}if(L.kind==="optional"){fQ(U,"optional",{key:L.normalized,value:J},X);continue}let O=X.$.parseOwnDefinitionFormat(A.normalized,X),R=Q6(O,J,X.$);if(R.index)U.index=D(U.index,R.index);if(R.required)U.required=D(U.required,R.required)}let W=X.$.node("structure",U);return X.$.parseSchema({domain:"object",structure:Y?.merge(W)??W})},fQ=(Q,X,Y,U)=>{Q[X]=D(Q[X],U.$.node(X,Y))},n8=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${B(Q)})`,r8="Spread operator may only be used as the first key in an object",t8=(Q)=>typeof Q==="symbol"?{kind:"required",normalized:Q}:Q[Q.length-1]==="?"?Q[Q.length-2]===E1?{kind:"required",normalized:`${Q.slice(0,-2)}?`}:{kind:"optional",normalized:Q.slice(0,-1)}:Q[0]==="["&&Q[Q.length-1]==="]"?{kind:"index",normalized:Q.slice(1,-1)}:Q[0]===E1&&Q[1]==="["&&Q[Q.length-1]==="]"?{kind:"required",normalized:Q.slice(1)}:Q==="..."?{kind:"spread"}:Q==="+"?{kind:"undeclared"}:{kind:"required",normalized:Q==="\\..."?"...":Q==="\\+"?"+":Q},a8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var BY=(Q,X)=>J3(Q)?RY[Q[0]](Q,X):G3(Q)?DY[Q[1]](Q,X):null,e8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),bQ=(Q,X)=>{if(Q[2]===void 0)return H(KQ(Q[1],""));let Y=X.$.parseOwnDefinitionFormat(Q[0],X),U=X.$.parseOwnDefinitionFormat(Q[2],X);if(Q[1]==="|")return X.$.node("union",{branches:[Y,U]});let Z=Q[1]==="&"?i(Y,U,X.$):D2(Y,U,X.$);if(Z instanceof q)return Z.throw();return Z},Q3=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),X3=(Q,X)=>{if(typeof Q[2]!=="function")return H(MY("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},MY=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,Y3=(Q,X)=>{if(typeof Q[2]!=="function")return H(MY(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},U3=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),TY=(Q)=>Q,Z3=TY({"[]":Q3,"?":()=>H(W6)}),W3=TY({"|":bQ,"&":bQ,":":Y3,"=>":X3,"|>":bQ,"@":U3,"=":()=>H(G6)}),DY={...Z3,...W3},G3=(Q)=>DY[Q[1]]!==void 0,_3=(Q)=>Q,RY=_3({keyof:e8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return H(VY(L2(Q[1])));let Y=Q.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):H(VY(L2(U))));return Y.length===1?Y[0]:X.$.node("union",{branches:Y})},"===":(Q,X)=>X.$.units(Q.slice(1))}),J3=(Q)=>RY[Q[0]]!==void 0,VY=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var KY=(Q,X)=>{let Y=[{}],U=0;while(U<Q.length){let Z=!1;if(Q[U]==="..."&&U<Q.length-1)Z=!0,U++;let W=F6(Q[U],X),[G,_,L]=!K(W)?[W]:W;if(U++,Z){if(!G.extends(F.intrinsic.Array))return H(F3(G.expression));Y=Y.flatMap((J)=>G.distribute((A)=>H3(l2(J),A)))}else Y=Y.map((J)=>{if(_==="?")return PY(J,G);if(_==="=")return L3(J,G,L);return yQ(J,G)})}return X.$.parseSchema(Y.map((Z)=>J1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},yQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return H(Q.variadic?qQ:q3);if(Q.variadic)Q.postfix=D(Q.postfix,X);else Q.prefix=D(Q.prefix,X);return Q},PY=(Q,X)=>{if(Q.variadic)return H(NY);return Q.optionals=D(Q.optionals,X),Q},L3=(Q,X,Y)=>{if(Q.variadic)return H(NY);if(Q.optionals)return H(A3);return Q.defaultables=D(Q.defaultables,[[X,Y]]),Q},CY=(Q,X)=>{if(Q.postfix)H(wY);if(Q.variadic){if(!Q.variadic.equals(X))H(wY)}else Q.variadic=X.internal;return Q},H3=(Q,X)=>{let Y=X.select({method:"find",kind:"sequence"});if(!Y)return CY(Q,F.intrinsic.unknown);if(Y.prefix)for(let U of Y.prefix)yQ(Q,U);if(Y.optionals)for(let U of Y.optionals)PY(Q,U);if(Y.variadic)CY(Q,Y.variadic);if(Y.postfix)for(let U of Y.postfix)yQ(Q,U);return Q},F3=(Q)=>`Spread element must be an array (was ${Q})`,wY="A tuple may have at most one variadic element",q3="A required element may not follow an optional element",NY="An optional element may not follow a variadic element";var A3="A defaultable element may not follow an optional element without a default";var $3={},q6=(Q,X)=>{if(typeof Q==="string"){if(X.args&&Object.keys(X.args).some((U)=>Q.includes(U)))return EQ(Q,X);let Y=$3[X.$.name]??={};return Y[Q]??=EQ(Q,X)}return u(Q,"object")?z3(Q,X):H(vQ(b(Q)))},z3=(Q,X)=>{let Y=J2(Q);switch(Y){case void 0:if($(Q,"root"))return Q;if("~standard"in Q)return O3(Q,X);return OY(Q,X);case"Array":return V3(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let U=M1(Q)?Q():Q;if($(U,"root"))return U;return H(vQ("Function"))}default:return H(vQ(Y??B(Q)))}},O3=(Q,X)=>X.$.intrinsic.unknown.pipe((Y,U)=>{let Z=Q["~standard"].validate(Y);if(!Z.issues)return Z.value;for(let{message:W,path:G}of Z.issues)if(G)if(G.length)U.error({problem:q4(W),relativePath:G.map((_)=>typeof _==="object"?_.key:_)});else U.error({message:W});else U.error({message:W})}),V3=(Q,X)=>BY(Q,X)??KY(Q,X),vQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class kQ extends d{constructor(Q){let X=Object.assign({errors:c,hkt:g,$:Q,raw:Q.parse,module:Q.constructor.module,scope:Q.constructor.scope,declare:Q.declare,define:Q.define,match:Q.match,generic:Q.generic,schema:Q.schema,keywords:Q.ambient,unit:Q.unit,enumerated:Q.enumerated,instanceOf:Q.instanceOf,valueOf:Q.valueOf,or:Q.or,and:Q.and,merge:Q.merge,pipe:Q.pipe,fn:Q.fn},Q.ambientAttachments);super((...Y)=>{if(Y.length===1)return Q.parse(Y[0]);if(Y.length===2&&typeof Y[0]==="string"&&Y[0][0]==="<"&&Y[0][Y[0].length-1]===">"){let U=Y[0].slice(1,-1),Z=Q.parseGenericParams(U,{});return new w1(Z,Y[1],Q,Q,null)}return Q.parse(Y)},{attach:X})}}var e1=F;class A6 extends X6{get ambientAttachments(){if(!e1.typeAttachments)return;return this.cacheGetter("ambientAttachments",V(e1.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let Y=Q.indexOf("<");if(Y===-1){if($(X,"module")||$(X,"generic"))return[Q,X];let W=this.name==="ark"?Q:Q==="root"?this.name:`${this.name}.${Q}`,G=this.resolvedConfig.keywords?.[W];if(G)X=[X,"@",G];return[Q,X]}if(Q[Q.length-1]!==">")H("'>' must be the last character of a generic declaration in a scope");let U=Q.slice(0,Y),Z=Q.slice(Y+1,-1);return[U,()=>{let W=this.parseGenericParams(Z,{alias:U});return p4(W,X,this)}]}parseGenericParams(Q,X){return H6(new O2(Q),[],this.createParseContext({...X,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(M1(Q)&&!$(Q,"generic"))return Q();return Q}preparseOwnDefinitionFormat(Q,X){return{...X,def:Q,prefix:X.alias??"type"}}parseOwnDefinitionFormat(Q,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let U=q6(Q,X);if(K(U)){if(U[1]==="=")return H(G6);if(U[1]==="?")return H(W6)}return U}unit=(Q)=>this.units([Q]);valueOf=(Q)=>this.units(U4(Q));enumerated=(...Q)=>this.units(Q);instanceOf=(Q)=>this.node("proto",{proto:Q},{prereduced:!0});or=(...Q)=>this.schema(Q.map((X)=>this.parse(X)));and=(...Q)=>Q.reduce((X,Y)=>X.and(this.parse(Y)),this.intrinsic.unknown);merge=(...Q)=>Q.reduce((X,Y)=>X.merge(this.parse(Y)),this.intrinsic.object);pipe=(...Q)=>this.intrinsic.unknown.pipe(...Q);fn=new SQ(this);match=new jQ(this);declare=()=>({type:this.type});define(Q){return Q}type=new kQ(this);static scope=(Q,X={})=>new A6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var y2=Object.assign(A6.scope,{define:(Q)=>Q}),T=A6;class IY extends g{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var B3=e(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),IY),EY=T.module({Key:z.key,Merge:B3});class SY extends g{}var M3=e("element")((Q)=>{let X=Q.element.exclude(z.Array),Y=X.array();return X.rawOr(Y).pipe(B1).distribute((U)=>U.assertHasKind("morph").declareOut(Y),w)},SY),jY=T.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:M3},{name:"Array"});var gQ=w(["string",S1.FileConstructor]),T3=gQ.rawOr(gQ.array()),fY=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:T3}}),bY=T.module({root:["instanceof",FormData],value:gQ,parsed:fY,parse:w({in:FormData,morphs:(Q)=>{let X={};for(let[Y,U]of Q)if(Y in X){let Z=X[Y];if(typeof Z==="string"||Z instanceof S1.FileConstructor)X[Y]=[Z,U];else Z.push(U)}else X[Y]=U;return X},declaredOut:fY})},{name:"FormData"});var yY=T.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var D3={Boolean:1,Number:1,String:1},vY=T.module({...V({...K6,...N6},(Q,X)=>(Q in D3)?[]:[Q,["instanceof",X]]),Array:jY,TypedArray:yY,FormData:bY});var R3=w({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),C3=w({domain:"number",divisor:1}),$6=T.module({root:z.number,integer:C3,epoch:R3,safe:w({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var E=(Q,X,Y)=>{let U={domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:X}};if(Y)U.meta={format:Y};return r1("intersection",U)},kY=E(F2,"a well-formed integer string"),sY=T.module({root:kY,parse:w({in:kY,morphs:(Q,X)=>{let Y=Number.parseInt(Q);return Number.isSafeInteger(Y)?Y:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:z.integer})},{name:"string.integer"}),w3=E(/^[\dA-Fa-f]+$/,"hex characters only"),K3=T.module({root:E(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:E(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),gY=E(/^[A-Z].*$/,"capitalized"),P3=T.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:gY}),preformatted:gY},{name:"string.capitalize"}),N3=(Q)=>{let X=Q.replace(/[ -]+/g,""),Y=0,U,Z,W=!1;for(let G=X.length-1;G>=0;G--){if(U=X.substring(G,G+1),Z=Number.parseInt(U,10),W)Z*=2,Y+=Z>=10?Z%10+1:Z;else Y+=Z;W=!W}return!!(Y%10===0?X:!1)},I3=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,E3=w({domain:"string",pattern:{meta:"a credit card number",rule:I3.source},predicate:{meta:"a credit card number",predicate:N3}});var S3=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var j3=(Q)=>!Number.isNaN(new Date(Q).valueOf()),xY=w({domain:"string",predicate:{meta:"a parsable date",predicate:j3}}).assertHasKind("intersection"),hY=sY.root.internal.narrow((Q,X)=>{let Y=Number.parseInt(Q),U=$6.epoch(Y);if(U instanceof c)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),f3=T.module({root:hY,parse:w({in:hY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),pY=E(S3,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),b3=T.module({root:pY,parse:w({in:pY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),y3=T.module({root:xY,parse:w({declaredIn:xY,in:"string",morphs:(Q,X)=>{let Y=new Date(Q);if(Number.isNaN(Y.valueOf()))return X.error("a parsable date");return Y},declaredOut:z.Date}),iso:b3,epoch:f3},{name:"string.date"}),v3=E(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),uY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",K1=`(${uY}[.]){3}${uY}`,k3=new RegExp(`^${K1}$`),j="(?:[0-9a-fA-F]{1,4})",g3=new RegExp(`^((?:${j}:){7}(?:${j}|:)|(?:${j}:){6}(?:${K1}|:${j}|:)|(?:${j}:){5}(?::${K1}|(:${j}){1,2}|:)|(?:${j}:){4}(?:(:${j}){0,1}:${K1}|(:${j}){1,3}|:)|(?:${j}:){3}(?:(:${j}){0,2}:${K1}|(:${j}){1,4}|:)|(?:${j}:){2}(?:(:${j}){0,3}:${K1}|(:${j}){1,5}|:)|(?:${j}:){1}(?:(:${j}){0,4}:${K1}|(:${j}){1,6}|:)|(?::((?::${j}){0,5}:${K1}|(?::${j}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),x3=T.module({root:["v4 | v6","@","an IP address"],v4:E(k3,"an IPv4 address","ipv4"),v6:E(g3,"an IPv6 address","ipv6")},{name:"string.ip"}),Q2="a JSON string",nY=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${Q2} (${Q})`},h3=w({meta:Q2,domain:"string",predicate:{meta:Q2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(Y){return X.reject({code:"predicate",expected:Q2,problem:nY(Y)})}}}}),p3=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:Q2,actual:"empty"});try{return JSON.parse(Q)}catch(Y){return X.error({code:"predicate",expected:Q2,problem:nY(Y)})}},u3=T.module({root:h3,parse:w({meta:"safe JSON string parser",in:"string",morphs:p3,declaredOut:z.jsonObject})},{name:"string.json"}),mY=E(/^[a-z]*$/,"only lowercase letters"),m3=T.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:mY}),preformatted:mY},{name:"string.lower"}),rY=["NFC","NFD","NFKC","NFKD"],v2=V(rY,(Q,X)=>[X,w({domain:"string",predicate:(Y)=>Y.normalize(X)===Y,meta:`${X}-normalized unicode`})]),z6=V(rY,(Q,X)=>[X,w({in:"string",morphs:(Y)=>Y.normalize(X),declaredOut:v2[X]})]),l3=T.module({root:z6.NFC,preformatted:v2.NFC},{name:"string.normalize.NFC"}),d3=T.module({root:z6.NFD,preformatted:v2.NFD},{name:"string.normalize.NFD"}),c3=T.module({root:z6.NFKC,preformatted:v2.NFKC},{name:"string.normalize.NFKC"}),o3=T.module({root:z6.NFKD,preformatted:v2.NFKD},{name:"string.normalize.NFKD"}),i3=T.module({root:"NFC",NFC:l3,NFD:d3,NFKC:c3,NFKD:o3},{name:"string.normalize"}),lY=E(h2,"a well-formed numeric string"),s3=T.module({root:lY,parse:w({in:lY,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),dY="a regex pattern",n3=w({domain:"string",predicate:{meta:dY,predicate:(Q,X)=>{try{return new RegExp(Q),!0}catch(Y){return X.reject({code:"predicate",expected:dY,problem:String(Y)})}}},meta:{format:"regex"}}),r3=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,t3=E(r3,"a semantic version (see https://semver.org/)"),cY=E(/^\S.*\S$|^\S?$/,"trimmed"),a3=T.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:cY}),preformatted:cY},{name:"string.trim"}),oY=E(/^[A-Z]*$/,"only uppercase letters"),e3=T.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:oY}),preformatted:oY},{name:"string.upper"}),Q9=(Q)=>URL.canParse(Q),iY=w({domain:"string",predicate:{meta:"a URL string",predicate:Q9},meta:{format:"uri"}}),X9=T.module({root:iY,parse:w({declaredIn:iY,in:"string",morphs:(Q,X)=>{try{return new URL(Q)}catch{return X.error("a URL string")}},declaredOut:w(URL)})},{name:"string.url"}),Y9=T.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:E(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:E(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:E(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:E(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:E(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:E(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:E(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:E(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),tY=T.module({root:z.string,alpha:E(/^[A-Za-z]*$/,"only letters"),alphanumeric:E(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:w3,base64:K3,capitalize:P3,creditCard:E3,date:y3,digits:E(/^\d*$/,"only digits 0-9"),email:v3,integer:sY,ip:x3,json:u3,lower:m3,normalize:i3,numeric:s3,regex:n3,semver:t3,trim:a3,upper:e3,url:X9,uuid:Y9},{name:"string"});var aY=T.module({bigint:z.bigint,boolean:z.boolean,false:z.false,never:z.never,null:z.null,number:z.number,object:z.object,string:z.string,symbol:z.symbol,true:z.true,unknown:z.unknown,undefined:z.undefined}),eY=T.module({root:z.unknown,any:z.unknown},{name:"unknown"}),U9=T.module({root:z.jsonObject,stringify:r1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),QU=T.module({root:z.object,json:U9},{name:"object"});class XU extends g{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var Z9=e(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),XU);class YU extends g{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var W9=e(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),YU);class UU extends g{description='omit a set of properties from an object like `Omit(User, "age")`'}var G9=e(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),UU);class ZU extends g{description="make all named properties of an object optional like `Partial(User)`"}var _9=e(["T",z.object])((Q)=>Q.T.partial(),ZU);class WU extends g{description="make all named properties of an object required like `Required(User)`"}var J9=e(["T",z.object])((Q)=>Q.T.required(),WU);class GU extends g{description='exclude branches of a union like `Exclude("boolean", "true")`'}var L9=e("T","U")((Q)=>Q.T.exclude(Q.U),GU);class _U extends g{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var H9=e("T","U")((Q)=>Q.T.extract(Q.U),_U),JU=T.module({Exclude:L9,Extract:H9,Omit:G9,Partial:_9,Pick:W9,Record:Z9,Required:J9});var V1=y2({...aY,...JU,...vY,...EY,string:tY,number:$6,object:QU,unknown:eY},{prereducedAliases:!0,name:"ark"}),v=V1.export();Object.assign(e1.ambient,v);e1.typeAttachments={string:v.string.root,number:v.number.root,bigint:v.bigint,boolean:v.boolean,symbol:v.symbol,undefined:v.undefined,null:v.null,object:v.object.root,unknown:v.unknown.root,false:v.false,true:v.true,never:v.never,arrayIndex:v.Array.index,Key:v.Key,Record:v.Record,Array:v.Array.root,Date:v.Date};var xQ=Object.assign(V1.type,e1.typeAttachments),F9=V1.match,q9=V1.fn,A9=V1.generic,fq=V1.schema,$9=V1.define,z9=V1.declare;var b1=y2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition",RangeCondition:{field:"string > 0",operator:"'RANGE'",value:"unknown[] == 2"},ListCondition:{field:"string > 0",operator:"'IN' | 'NOT_IN'",value:"unknown[]"},ContainsCondition:{field:"string > 0",operator:"'CONTAINS'",value:"string | unknown[]"},NumericCondition:{field:"string > 0",operator:"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'",value:"number | string"},RegexCondition:{field:"string > 0",operator:"'MATCHES'",value:"string"},BasicCondition:{field:"string > 0",operator:"Operator",value:"unknown"},ConditionGroup:{operator:"'AND' | 'OR'",conditions:"(Condition | ConditionGroup)[] >= 1"},RuleCondition:"Condition | ConditionGroup",Action:{type:"string > 0","params?":"object","delay?":"number.integer >= 0 | string","probability?":"0 <= number <= 1 | string"},ActionGroup:{"mode?":"'ALL' | 'EITHER' | 'SEQUENCE'",actions:"(Action | ActionGroup)[] >= 1"},RuleAction:"Action | ActionGroup",TriggerRule:{id:"string > 0","name?":"string","description?":"string","priority?":"number.integer","enabled?":"boolean","cooldown?":"number.integer >= 0","tags?":"string[]",on:"string > 0","if?":"RuleCondition | RuleCondition[]",do:"RuleAction | RuleAction[]","comment?":"string"}}).export(),rq=b1.Operator,tq=b1.Condition,aq=b1.ConditionGroup,eq=b1.RuleCondition,QA=b1.Action,XA=b1.ActionGroup,O9=b1.TriggerRule;class V9{static validate(Q){let X=O9(Q);if(X instanceof xQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),_=W.message,L=void 0;if(G.endsWith("on")&&(_.includes("string")||_.includes("must be")))if(typeof Q==="object"&&Q!==null&&"on"in Q&&Q.on===!0)_="The 'on' field is incorrect (boolean true found).",L=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else L="Ensure 'on' is a string event name.";Z.push({path:G,message:_,suggestion:L,severity:"error"})}return{valid:!1,issues:Z}}let Y=X,U=[];if(this.validateConditionsRecursive(Y.if,U,"if"),U.length>0)return{valid:!1,issues:U};return{valid:!0,rule:Y}}static validateConditionsRecursive(Q,X,Y){if(!Q)return;if(Array.isArray(Q)){Q.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"conditions"in Q&&Array.isArray(Q.conditions)){Q.conditions.forEach((U,Z)=>{this.validateConditionsRecursive(U,X,`${Y}.conditions.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"operator"in Q&&"value"in Q)this.validateConditionValue(Q,X,Y)}static validateConditionValue(Q,X,Y){let{operator:U,value:Z}=Q;if(typeof U==="string"&&["IN","NOT_IN","RANGE","CONTAINS"].includes(U)){if(U==="CONTAINS"){if(typeof Z!=="string"&&!Array.isArray(Z))X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof Z}.`,suggestion:"Use a substring or a list of items.",severity:"error"});return}if(!Array.isArray(Z)){X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a List (Array), but received ${typeof Z}.`,suggestion:U==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(U==="RANGE"){if(Z.length!==2)X.push({path:`${Y}.value`,message:"Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).",suggestion:"Use format [min, max], e.g. [1, 10]",severity:"error"});else if(typeof Z[0]!=="number"&&typeof Z[0]!=="string")X.push({path:`${Y}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(U==="MATCHES")if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof Z}.`,severity:"error"});else try{new RegExp(Z)}catch(W){X.push({path:`${Y}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(typeof U==="string"&&["GT","GTE","LT","LTE",">",">=","<","<="].includes(U)){if(typeof Z!=="number"&&typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a number or expression string, but received ${typeof Z}.`,severity:"error"})}}}export{V9 as TriggerValidator,Y2 as TriggerUtils,O9 as TriggerRuleSchema,W2 as TriggerEngine,Q1 as StateManager,R6 as RuleEngine,eq as RuleConditionSchema,T6 as InMemoryPersistence,k as ExpressionEngine,$U as EventQueue,W2 as Engine,OU as ContextAdapter,tq as ConditionSchema,aq as ConditionGroupSchema,rq as ComparisonOperatorSchema,dQ as BrowserPersistence,R6 as AdvancedRuleEngine,QA as ActionSchema,v1 as ActionRegistry,XA as ActionGroupSchema};
|
|
47
47
|
|
|
48
|
-
//# debugId=
|
|
48
|
+
//# debugId=56F97B9AB966D9B364756E2164756E21
|