trigger_system 1.1.8 → 1.2.1
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 +30 -30
- package/dist/browser/index.browser.js.map +6 -6
- 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/node/index.js +83 -83
- package/dist/node/index.js.map +6 -6
- package/dist/node/node.js +130 -130
- package/dist/node/node.js.map +6 -6
- package/dist/utils/utils.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
var{defineProperty:B6,getOwnPropertyNames:FY,getOwnPropertyDescriptor:qY}=Object,$Y=Object.prototype.hasOwnProperty;function AY(Q){return this[Q]}var mQ=(Q)=>{var X=(pQ??=new WeakMap).get(Q),U;if(X)return X;if(X=B6({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function"){for(var Y of FY(Q))if(!$Y.call(X,Y))B6(X,Y,{get:AY.bind(Q,Y),enumerable:!(U=qY(Q,Y))||U.enumerable})}return pQ.set(Q,X),X},pQ;var zY=(Q)=>Q;function OY(Q,X){this[Q]=zY.bind(null,X)}var uQ=(Q,X)=>{for(var U in X)B6(Q,U,{get:X[U],enumerable:!0,configurable:!0,set:OY.bind(X,U)})};var lQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);var M6={};uQ(M6,{ExpressionEngine:()=>k});class k{static evaluate(Q,X){try{if(Q.includes("${")){let U=this.interpolate(Q,X);if(!isNaN(Number(U))&&U.trim()!=="")return Number(U);return U}return this.evaluateExpression(Q,X)}catch(U){return console.error(`Error evaluating expression: ${Q}`,U),null}}static interpolate(Q,X){return Q.replace(/\$\{([^}]+)\}/g,(U,Y)=>{try{let Z=this.evaluateExpression(Y,X);if(Z===void 0||Z===null)return"undefined";return String(Z)}catch(Z){return console.error(`Error en interpolación: ${U}`,Z),U}})}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|vars|request|computed|env|state)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);if(/^(vars|env|state)(\.[a-zA-Z0-9_]+)$/.test(Q))return this.getNestedValue(Q,X);try{return Function("context","with(context) { return "+Q+" }")(X)}catch(U){return console.error(`ERROR evaluating expression '${Q}':`,U),Q}}static getNestedValue(Q,X){let U=Q.split("."),Y=X;for(let Z of U){if(Y===null||Y===void 0||typeof Y!=="object"||!(Z in Y))return;Y=Y[Z]}return Y}static evaluateMath(Q,X){let U=Q;U=U.replace(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,(Y)=>{if(["Math","random","floor","ceil","round","sqrt","abs","pow","min","max","sin","cos","tan"].includes(Y))return Y;let Z=this.getNestedValue(Y,X);if(Z!==void 0)return typeof Z==="string"?`"${Z}"`:String(Z);return Y});try{return this.evaluateMathExpression(U)}catch(Y){return console.error(`Error en evaluación matemática: ${Q}`,Y),NaN}}}class V6{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 g{static instance;state;persistence;constructor(){this.state={},this.persistence=new V6}static getInstance(){if(!g.instance)g.instance=new g;return g.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();if(Q instanceof Map)this.state=Object.fromEntries(Q);else this.state=Q||{};console.log(`[StateManager] Initialized with ${Object.keys(this.state).length} root keys.`)}get(Q){return this.state[Q]}async set(Q,X){this.state[Q]=X,await this.persistence.saveState(Q,X)}async increment(Q,X=1){let U=this.state[Q]||0,Y=Number(U)+X;return this.state[Q]=Y,await this.persistence.saveState(Q,Y),Y}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){if(Q in this.state)return delete this.state[Q],await this.persistence.deleteState(Q),!0;return!1}async clear(){this.state={},await this.persistence.clearState()}async applyConfig(Q){if(!Q.state)return;for(let[X,U]of Object.entries(Q.state))if(typeof U!=="object"||U===null||!("value"in U)){if(this.state[X]===void 0)await this.set(X,U)}else{let Y=U;if(this.state[X]===void 0)await this.set(X,Y.value);if(Y.lifecycle?.ttl)this.setupTTL(X,Y.lifecycle.ttl)}}setupTTL(Q,X){let U=0;if(typeof X==="number")U=X;else{let Y=X.match(/^(\d+)([smhd])$/);if(Y&&Y[1]&&Y[2]){let Z=parseInt(Y[1]),W=Y[2];U=Z*({s:1000,m:60000,h:3600000,d:86400000}[W]||0)}}if(U>0)setTimeout(()=>{this.delete(Q).catch(console.error)},U)}getAll(){return{...this.state}}getLiveProxy(){let Q=this;function X(U,Y=[]){return new Proxy(U,{get(Z,W){let G=Z[W];if(G&&typeof G==="object"&&!Array.isArray(G))return X(G,[...Y,W]);return G},set(Z,W,G){if(typeof W!=="string")return!1;Z[W]=G;let J=Y.length>0?Y[0]:W;if(J)Q.persistence.saveState(J,Q.state[J]);return!0}})}return X(this.state)}}var v1=()=>{};var oQ={};uQ(oQ,{ActionRegistry:()=>k1});class k1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new k1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}get Handlers(){return this.handlers}registerDefaults(){this.register("log",(Q,X)=>{let U=Q.params?.message||Q.params?.content||"Log Trigger",Y=typeof U==="string"?k.interpolate(U,X):String(U);return console.log(`[TriggerLog] ${Y}`),{message:Y}}),this.register("math",(Q,X)=>{let U=String(Q.params?.expression||"0");return k.evaluate(U,X)}),this.register("response",(Q,X)=>{let U=Q.params?.content||Q.params?.body||"",Y=typeof U==="string"?k.interpolate(U,X):String(U);return{statusCode:Q.params?.statusCode||200,headers:Q.params?.headers||{"Content-Type":"application/json"},body:Y}}),this.register("execute",async(Q,X)=>{let U=Q.params?.command||Q.params?.content||"",Y=typeof U==="string"?k.interpolate(U,X):String(U);if(!Q.params?.safe)console.warn(`[Trigger] Ejecutando comando no seguro: ${Y}`);try{let Z=Bun.spawn(Y.split(" "),{stdout:"pipe",stderr:"pipe"}),[W,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{command:Y,stdout:W,stderr:G,exitCode:await Z.exited}}catch(Z){return{command:Y,error:String(Z)}}}),this.register("forward",async(Q,X)=>{let U=Q.params?.url||"",Y=typeof U==="string"?k.interpolate(U,X):String(U),Z=String(Q.params?.method||"POST").toUpperCase(),G=["POST","PUT","PATCH"].includes(Z);try{let J=await fetch(Y,{method:Z,headers:{"Content-Type":"application/json",...typeof Q.params?.headers==="object"&&Q.params.headers!==null&&!Array.isArray(Q.params.headers)?Q.params.headers:{}},...G?{body:JSON.stringify(X.data)}:{}});return{url:Y,method:Z,status:J.status,headers:(()=>{let L={};return J.headers.forEach((_,$)=>L[$]=_),L})(),body:await J.text()}}catch(J){return{url:Y,method:Z,error:String(J)}}}),this.register("STATE_SET",async(Q,X)=>{let U=String(Q.params?.key||""),Y=Q.params?.value;if(!U)return{error:"Missing key for STATE_SET"};let Z=Y;if(typeof Y==="string"&&Y.includes("${"))Z=k.interpolate(Y,X);return await g.getInstance().set(U,Z),{key:U,value:Z}}),this.register("STATE_INCREMENT",async(Q,X)=>{let U=String(Q.params?.key||""),Y=Number(Q.params?.amount)||1;if(!U)return{error:"Missing key for STATE_INCREMENT"};let Z=await g.getInstance().increment(U,Y);return{key:U,newValue:Z}}),this.register("STATE_GET",async(Q,X)=>{let U=String(Q.params?.key||""),Y=String(Q.params?.as||U);if(!U)return{error:"Missing key for STATE_GET"};let Z=await g.getInstance().get(U);if(!X.env)X.env={};return X.env[Y]=Z,{key:U,value:Z,storedAs:Y}}),this.register("STATE_DELETE",async(Q,X)=>{let U=String(Q.params?.key||"");if(!U)return{error:"Missing key for STATE_DELETE"};let Y=await g.getInstance().delete(U);return{key:U,deleted:Y}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}}),this.register("notify",(Q,X)=>{let U=Q.params?.message||Q.params?.content||"Notification",Y=Q.params?.target||"default";return console.log(`[Notification] To: ${Y}, Msg: ${U}`),{target:Y,message:U}}),this.register("STATE_OP",(Q,X)=>{if(Q.params?.run)return Function("context","state","data","vars","env","helpers",`with(context) { ${Q.params.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers);return{warning:"Missing 'run' param for STATE_OP"}})}}var Y2=lQ(()=>{v1()});class BY{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(U){console.error(`[EventQueue] Error processing event ${X.event}:`,U)}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 v2{static getNestedValue(Q,X){let U=Q.split("."),Y=X;for(let Z of U){if(Y===null||Y===void 0)return;if(typeof Y==="object"&&Y!==null&&Z in Y)Y=Y[Z];else return}return Y}static interpolate(Q,X){if(typeof Q!=="string")return Q;return Q.replace(/\$\{([^}]+)\}/g,(U,Y)=>{let Z=this.getNestedValue(Y,X);if(Z!==void 0)return String(Z);return U})}static compare(Q,X,U){switch(X){case"EQ":case"==":return Q==U;case"NEQ":case"!=":return Q!=U;case"GT":case">":return Number(Q)>Number(U);case"GTE":case">=":return Number(Q)>=Number(U);case"LT":case"<":return Number(Q)<Number(U);case"LTE":case"<=":return Number(Q)<=Number(U);case"IN":return Array.isArray(U)&&U.some((Y)=>Y===Q);case"NOT_IN":return Array.isArray(U)&&!U.some((Y)=>Y===Q);case"CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return Q.includes(U);return!1;case"NOT_CONTAINS":if(Array.isArray(Q)||typeof Q==="string")return!Q.includes(U);return!1;case"STARTS_WITH":if(typeof Q==="string"&&typeof U==="string")return Q.startsWith(U);return!1;case"ENDS_WITH":if(typeof Q==="string"&&typeof U==="string")return Q.endsWith(U);return!1;case"IS_EMPTY":if(typeof Q==="string")return Q==="";if(Array.isArray(Q))return Q.length===0;if(Q===null||Q===void 0)return!0;if(typeof Q==="object")return Object.keys(Q).length===0;return!1;case"IS_NULL":case"IS_NONE":return Q===null||Q===void 0;case"HAS_KEY":if(typeof Q==="object"&&Q!==null&&typeof U==="string")return U in Q;return!1;case"MATCHES":if(typeof U==="string")return new RegExp(U).test(String(Q));return!1;case"RANGE":if(Array.isArray(U)&&U.length===2){let Y=Number(Q),Z=Number(U[0]),W=Number(U[1]);return!isNaN(Y)&&!isNaN(Z)&&!isNaN(W)&&Y>=Z&&Y<=W}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var cQ;((Y)=>{Y.RULE_ADDED="rule:added";Y.RULE_REMOVED="rule:removed";Y.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 U=Q;if(!this.handlers.has(U))this.handlers.set(U,new Set);return this.handlers.get(U).add(X),()=>this.off(U,X)}off(Q,X){let U=Q,Y=this.handlers.get(U);if(Y)Y.delete(X)}emit(Q,X){let U=Q,Y=this.handlers.get(U);if(Y)Y.forEach((Z)=>{try{Z(X)}catch(W){console.error(`Error in event handler for ${U}:`,W)}})}}var G1=D6.getInstance();class Z2{_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=[];if(!Q.state)Q.state={};let U=this._rules.filter((Y)=>Y.enabled!==!1&&Y.on===Q.event);for(let Y of U){if(Y.cooldown&&this.checkCooldown(Y.id,Y.cooldown))continue;if(this.evaluateConditions(Y.if,Q)){let Z=await this.executeRuleActions(Y.do,Q);if(this.lastExecution.set(Y.id,Date.now()),X.push({ruleId:Y.id,success:!0,executedActions:Z}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(Q,X={},U={}){let Y={event:Q,data:X,vars:U,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(Y)}updateRules(Q){let X=this.getRules(),U=new Set(X.map((G)=>G.id)),Y=new Set(Q.map((G)=>G.id)),Z=Q.filter((G)=>!U.has(G.id)),W=X.filter((G)=>!Y.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(U){console.warn(`Could not emit event ${Q}:`,U)}}getRules(){return[...this.rules]}checkCooldown(Q,X){let U=this.lastExecution.get(Q);if(!U)return!1;return Date.now()-U<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Q,X){if(!Q)return!0;if(Array.isArray(Q))return Q.every((U)=>this.evaluateSingleCondition(U,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 U=Q,Y=k.evaluate(U.field,X),Z=U.value;if(typeof Z==="string"&&Z.includes("${"))Z=k.interpolate(Z,X);return v2.compare(Y,U.operator,Z)}async executeRuleActions(Q,X){let U=[],Y=[],Z="ALL";if(Array.isArray(Q))Y=Q;else if(Q&&typeof Q==="object"&&"mode"in Q&&"actions"in Q){let W=Q;Z=W.mode,Y=W.actions}else Y=[Q];if(Z==="EITHER"&&Y.length>0){let W=Y.reduce((L,_)=>L+(_.probability||1),0),G=Math.random()*W,J;for(let L of Y){let _=L.probability||1;if(G-=_,G<=0){J=L;break}}if(!J&&Y.length>0)J=Y[Y.length-1];if(J)Y=[J];else Y=[]}for(let W of Y){let G=await this.executeSingleAction(W,X);U.push(G)}return U}async executeSingleAction(Q,X){if(!Q.type&&!Q.run&&!Q.break&&!Q.continue){let W=["params","run","delay","probability","if","then","else","break","continue","mode","actions"],G=Object.keys(Q).filter((J)=>!W.includes(J));for(let J of G){if(Q.type=J,typeof Q[J]==="string")Q.params={...Q.params,message:Q[J],content:Q[J]};else if(typeof Q[J]==="object"&&Q[J]!==null)Q.params={...Q.params,...Q[J]};break}}if(Q.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${Q.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(W){return{type:"RUN",error:String(W),timestamp:Date.now()}}let U=Q.probability;if(typeof U==="string"){let W=k.evaluate(U,X);U=typeof W==="number"?W:Number(W)}if(U!==void 0&&Math.random()>U)return{type:Q.type||"skipped",timestamp:Date.now(),result:{skipped:"probability check failed"}};let Y=Q.delay;if(typeof Y==="string"){let W=k.evaluate(Y,X);Y=typeof W==="number"?W:Number(W)}if(Y&&Y>0)await new Promise((W)=>setTimeout(W,Y));let Z=this.interpolateParams(Q.params||{},X);try{let W;try{let{ActionRegistry:J}=await Promise.resolve().then(() => (Y2(),oQ)),L=J.getInstance().get(Q.type);if(L)W=(_)=>L({...Q,params:_},X)}catch{W=this.actionHandlers.get(Q.type)}let G;if(W)G=await W(Z,X);else{let J=`No handler registered for action type: ${Q.type}`;console.warn(J),G={warning:J}}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 U={};for(let[Y,Z]of Object.entries(Q))if(typeof Z==="string")U[Y]=k.interpolate(Z,X);else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))U[Y]=this.interpolateDeep(Z,X);else U[Y]=Z;return U}interpolateDeep(Q,X){if(typeof Q==="string")return k.interpolate(Q,X);if(Array.isArray(Q))return Q.map((U)=>this.interpolateDeep(U,X));if(typeof Q==="object"&&Q!==null){let U={};for(let Y in Q)U[Y]=this.interpolateDeep(Q[Y],X);return U}return Q}get rules(){return[...this._rules]}get config(){return this._config}set rules(Q){this._rules=[...Q],this.sortRules()}}Y2();v1();class R6 extends Z2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=k1.getInstance(),this.stateManager=g.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getLiveProxy(),this.config?.stateConfig)await this.stateManager.applyConfig(this.config.stateConfig);if(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 U=this.rules.filter((Y)=>Y.enabled!==!1&&Y.on===Q.event);for(let Y of U){if(Y.cooldown&&this.checkCooldown(Y.id,Y.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${Y.id} in cooldown`);continue}if(this.evaluateConditions(Y.if,Q)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${Y.name||Y.id}`);G1.emit("rule:match",{rule:Y,context:Q});let W=await this.executeRuleActionsWithRegistry(Y.do,Q);if(X.push({ruleId:Y.id,executedActions:W,success:!0}),this.updateLastExecution(Y.id),!this.shouldEvaluateAll())break}}return G1.emit("engine:done",{results:X,context:Q}),X}async processEventSimple(Q,X={},U={}){let Y={event:Q,data:X,vars:U,timestamp:Date.now(),state:this.stateManager.getLiveProxy()};return this.processEvent(Y)}async executeRuleActionsWithRegistry(Q,X){let U=[],Y=[],Z="ALL";if(Array.isArray(Q))Y=Q;else if(this.isActionGroup(Q)){let W=Q;Z=W.mode,Y=W.actions}else Y=[Q];if(Z==="EITHER"&&Y.length>0){let W=Y.reduce((L,_)=>L+(_.probability||1),0),G=Math.random()*W,J;for(let L of Y){let _=L.probability||1;if(G-=_,G<=0){J=L;break}}if(J)Y=[J]}for(let W of Y){let G=await this.executeSingleActionWithRegistry(W,X);U.push(G)}return U}isActionGroup(Q){return typeof Q==="object"&&Q!==null&&"mode"in Q&&"actions"in Q}async executeSingleActionWithRegistry(Q,X){if(!Q.type&&!Q.run&&!Q.break&&!Q.continue){let W=Object.keys(Q);for(let G of W)if(this.actionRegistry.get(G)){if(Q.type=G,typeof Q[G]==="string")Q.params={...Q.params,message:Q[G],content:Q[G]};else if(typeof Q[G]==="object"&&Q[G]!==null)Q.params={...Q.params,...Q[G]};break}}if(Q.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${Q.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(W){return{type:"RUN",error:String(W),timestamp:Date.now()}}let U=Q.probability;if(typeof U==="string"){let{ExpressionEngine:W}=mQ(M6),G=W.evaluate(U,X);U=typeof G==="number"?G:Number(G)}if(U!==void 0&&Math.random()>U)return{type:Q.type||"unknown",timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.break)return{type:"BREAK",result:"Break action",timestamp:Date.now()};if(Q.continue)return{type:"CONTINUE",result:"Continue action",timestamp:Date.now()};let Y=Q.delay;if(typeof Y==="string"){let{ExpressionEngine:W}=mQ(M6),G=W.evaluate(Y,X);Y=typeof G==="number"?G:Number(G)}if(Y&&Y>0)await new Promise((W)=>setTimeout(W,Y));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 J=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(J);console.warn(J),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)}}Y2();v1();class MY{static create(Q,X,U={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},vars:U,state:g.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromRequest(Q,X,U={}){let Y=new URL(Q.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Q.method,path:Y.pathname,query:Object.fromEntries(Y.searchParams),headers:(()=>{let Z={};return Q.headers.forEach((W,G)=>Z[G]=W),Z})(),body:X||{}},vars:{...U,ip:Q.headers.get("x-forwarded-for")||"unknown"},state:g.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,U,Y={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:U,vars:{...Y,provider:Q},state:g.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>{try{return typeof Q==="string"?JSON.parse(Q):null}catch{return null}},jsonStringify:(Q)=>{try{return JSON.stringify(Q)}catch{return null}}}}}v1();Y2();v1();var T1=(Q)=>Array.isArray(Q)?Q:[Q],iQ=(Q,X)=>{let U=[[],[]];for(let Y of Q)if(X(Y))U[0].push(Y);else U[1].push(Y);return U},g2=Array,n=(Q,X)=>Q.includes(X),sQ=(Q,X=0)=>[...Array(Q)].map((U,Y)=>Y+X),D=(Q,X,U)=>{if(Q===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(U?.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 T1(X);return Q.concat(X)},rQ=(...Q)=>Q.reduce(q1,[]),J1=(Q,X,U)=>{if(Q===void 0)return Array.isArray(X)?X:[X];let Y=U?.isEqual??((Z,W)=>Z===W);for(let Z of T1(X))if(!Q.some((W)=>Y(W,Z)))Q.push(Z);return Q},nQ=(Q,X)=>Q.reduce((U,Y)=>{let Z=Y[X];return U[Z]=D(U[Z],Y),U},{}),$1=(Q,X,U)=>Q.length===X.length&&Q.every(U?.isEqual?(Y,Z)=>U.isEqual(Y,X[Z]):(Y,Z)=>Y===X[Z]);var u=(Q,X)=>f(Q)===X,f=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},l={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},tQ={...l,function:"a function"};class aQ extends Error{}var C=(Q)=>P1(Q,aQ),P1=(Q,X=Error)=>{throw new X(Q)};class W2 extends Error{name="ParseError"}var H=(Q)=>P1(Q,W2),X1=(Q)=>` ${Q}`,eQ="";var B=(Q,X)=>{let U={},Y=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let J=Y?X(W,G[1]):X(...G,W);Z||=typeof J[0]==="number";let L=Array.isArray(J[0])||J.length===0?J:[J];for(let[_,$]of L)if(typeof _==="object")U[_.group]=D(U[_.group],$);else U[_]=$}return Z?Object.values(U):U};var C6=Object.entries;var y=(Q,X)=>(Q in X),g1=(Q,X)=>(X in Q);class w6{constructor(Q){Object.assign(this,Q)}}var QX=class{};class G2 extends QX{}var VY=(Q,X)=>{let U={},Y={},Z;for(Z in Q)if(Z in X)U[Z]=Q[Z];else Y[Z]=Q[Z];return[U,Y]};var x2=(Q,X)=>VY(Q,X)[1],_1=(Q)=>Object.keys(Q).length===0,N1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],XX=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),UX=(Q)=>{let X=Object.keys(Q).sort(),U={};for(let Y=0;Y<X.length;Y++)U[X[Y]]=Q[X[Y]];return U};var d=X1(`unset${eQ}`),YX=(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},DY={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I1={...K6,...N6,...DY,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 U=X?.constructor?.name;if(U===void 0||U==="Object")return;return U},_2=(Q)=>typeof Q==="object"&&Q!==null?J2(Q)??"object":f(Q);var K=Array.isArray,RY={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"},CY={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"},wY={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"},ZX={...RY,...CY,...wY},L2=(Q)=>{let X=Object(Q).name??null;return X&&y(X,I1)&&I1[X]===Q?X:null};var I6=(Q,X)=>{let U=Q.prototype;while(U!==null){if(U===X.prototype)return!0;U=Object.getPrototypeOf(U)}return!1};var WX=(Q)=>GX(Q,new Map),GX=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let U=L2(Q.constructor);if(U==="Date")return new Date(Q.getTime());if(U&&U!=="Array")return Q;let Y=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),Z=Object.getOwnPropertyDescriptors(Q);if(X){X.set(Q,Y);for(let W in Z){let G=Z[W];if("get"in G||"set"in G)continue;G.value=GX(G.value,X)}}return Object.defineProperties(Y,Z),Y};var KY=(Q)=>{let X=d;return()=>X===d?X=Q():X},M1=(Q)=>typeof Q==="function"&&Q.length===0;var JX=class extends Function{constructor(...Q){let X=Q.slice(0,-1),U=Q[Q.length-1];try{super(...X,U)}catch(Y){return C(`Encountered an unexpected error while compiling your definition:
|
|
2
|
-
Message: ${
|
|
1
|
+
var{defineProperty:O6,getOwnPropertyNames:FU,getOwnPropertyDescriptor:qU}=Object,$U=Object.prototype.hasOwnProperty;function VU(Q){return this[Q]}var mQ=(Q)=>{var X=(pQ??=new WeakMap).get(Q),Y;if(X)return X;if(X=O6({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function"){for(var U of FU(Q))if(!$U.call(X,U))O6(X,U,{get:VU.bind(Q,U),enumerable:!(Y=qU(Q,U))||Y.enumerable})}return pQ.set(Q,X),X},pQ;var zU=(Q)=>Q;function AU(Q,X){this[Q]=zU.bind(null,X)}var uQ=(Q,X)=>{for(var Y in X)O6(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:AU.bind(X,Y)})};var lQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);var B6={};uQ(B6,{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|vars|request|computed|env|state)(\.[a-zA-Z0-9_]+)+$/.test(Q))return this.getNestedValue(Q,X);if(/^(vars|env|state)(\.[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 M6{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 g{static instance;state;persistence;constructor(){this.state={},this.persistence=new M6}static getInstance(){if(!g.instance)g.instance=new g;return g.instance}setPersistence(Q){this.persistence=Q}async initialize(){let Q=await this.persistence.loadState();if(Q instanceof Map)this.state=Object.fromEntries(Q);else this.state=Q||{};console.log(`[StateManager] Initialized with ${Object.keys(this.state).length} root keys.`)}get(Q){return this.state[Q]}async set(Q,X){this.state[Q]=X,await this.persistence.saveState(Q,X)}async increment(Q,X=1){let Y=this.state[Q]||0,U=Number(Y)+X;return this.state[Q]=U,await this.persistence.saveState(Q,U),U}async decrement(Q,X=1){return this.increment(Q,-X)}async delete(Q){if(Q in this.state)return delete this.state[Q],await this.persistence.deleteState(Q),!0;return!1}async clear(){this.state={},await this.persistence.clearState()}async applyConfig(Q){if(!Q.state)return;for(let[X,Y]of Object.entries(Q.state))if(typeof Y!=="object"||Y===null||!("value"in Y)){if(this.state[X]===void 0)await this.set(X,Y)}else{let U=Y;if(this.state[X]===void 0)await this.set(X,U.value);if(U.lifecycle?.ttl)this.setupTTL(X,U.lifecycle.ttl)}}setupTTL(Q,X){let Y=0;if(typeof X==="number")Y=X;else{let U=X.match(/^(\d+)([smhd])$/);if(U&&U[1]&&U[2]){let Z=parseInt(U[1]),W=U[2];Y=Z*({s:1000,m:60000,h:3600000,d:86400000}[W]||0)}}if(Y>0)setTimeout(()=>{this.delete(Q).catch(console.error)},Y)}getAll(){return{...this.state}}getLiveProxy(){let Q=this;function X(Y,U=[]){return new Proxy(Y,{get(Z,W){let G=Z[W];if(G&&typeof G==="object"&&!Array.isArray(G))return X(G,[...U,W]);return G},set(Z,W,G){if(typeof W!=="string")return!1;Z[W]=G;let J=U.length>0?U[0]:W;if(J)Q.persistence.saveState(J,Q.state[J]);return!0}})}return X(this.state)}}var v1=()=>{};var oQ={};uQ(oQ,{ActionRegistry:()=>k1});class k1{static instance;handlers=new Map;constructor(){this.registerDefaults()}static getInstance(){if(!this.instance)this.instance=new k1;return this.instance}register(Q,X){this.handlers.set(Q.toUpperCase(),X)}get(Q){return this.handlers.get(Q.toUpperCase())}get Handlers(){return this.handlers}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").toUpperCase(),G=["POST","PUT","PATCH"].includes(Z);try{let J=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:{}},...G?{body:JSON.stringify(X.data)}:{}});return{url:U,method:Z,status:J.status,headers:(()=>{let H={};return J.headers.forEach((_,$)=>H[$]=_),H})(),body:await J.text()}}catch(J){return{url:U,method:Z,error:String(J)}}}),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 g.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 g.getInstance().increment(Y,U);return{key:Y,newValue:Z}}),this.register("STATE_GET",async(Q,X)=>{let Y=String(Q.params?.key||""),U=String(Q.params?.as||Y);if(!Y)return{error:"Missing key for STATE_GET"};let Z=await g.getInstance().get(Y);if(!X.env)X.env={};return X.env[U]=Z,{key:Y,value:Z,storedAs:U}}),this.register("STATE_DELETE",async(Q,X)=>{let Y=String(Q.params?.key||"");if(!Y)return{error:"Missing key for STATE_DELETE"};let U=await g.getInstance().delete(Y);return{key:Y,deleted:U}}),this.register("EMIT_EVENT",(Q,X)=>{return{event:Q.params?.event,payload:Q.params?.data||{}}}),this.register("notify",(Q,X)=>{let Y=Q.params?.message||Q.params?.content||"Notification",U=Q.params?.target||"default";return console.log(`[Notification] To: ${U}, Msg: ${Y}`),{target:U,message:Y}}),this.register("STATE_OP",(Q,X)=>{if(Q.params?.run)return Function("context","state","data","vars","env","helpers",`with(context) { ${Q.params.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers);return{warning:"Missing 'run' param for STATE_OP"}})}}var Z2=lQ(()=>{v1()});class OU{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 U2{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){let U=(W)=>{if(W instanceof Date)return W.getTime();if(typeof W==="number")return W;if(typeof W==="string"){let G=new Date(W);return isNaN(G.getTime())?0:G.getTime()}return 0},Z=(W)=>{if(typeof W==="number")return W;if(W===null||W===void 0||W==="")return null;let G=Number(W);return isNaN(G)?null:G};switch(X){case"EQ":case"==":return Q==Y;case"NEQ":case"!=":return Q!=Y;case"GT":case">":{let W=Z(Q),G=Z(Y);return W!==null&&G!==null&&W>G}case"GTE":case">=":{let W=Z(Q),G=Z(Y);return W!==null&&G!==null&&W>=G}case"LT":case"<":{let W=Z(Q),G=Z(Y);return W!==null&&G!==null&&W<G}case"LTE":case"<=":{let W=Z(Q),G=Z(Y);return W!==null&&G!==null&&W<=G}case"IN":return Array.isArray(Y)&&Y.some((W)=>W===Q);case"NOT_IN":return Array.isArray(Y)&&!Y.some((W)=>W===Q);case"CONTAINS":if(Array.isArray(Y))return Y.some((W)=>String(Q).includes(String(W)));if(Array.isArray(Q)||typeof Q==="string")return Q.includes(Y);return!1;case"NOT_CONTAINS":if(Array.isArray(Y))return!Y.some((W)=>String(Q).includes(String(W)));if(Array.isArray(Q)||typeof Q==="string")return!Q.includes(Y);return!1;case"STARTS_WITH":if(Array.isArray(Y))return Y.some((W)=>String(Q).startsWith(String(W)));if(typeof Q==="string"&&typeof Y==="string")return Q.startsWith(Y);return!1;case"ENDS_WITH":if(Array.isArray(Y))return Y.some((W)=>String(Q).endsWith(String(W)));if(typeof Q==="string"&&typeof Y==="string")return Q.endsWith(Y);return!1;case"IS_EMPTY":{let W=!1;if(typeof Q==="string")W=Q==="";else if(Array.isArray(Q))W=Q.length===0;else if(Q===null||Q===void 0)W=!0;else if(typeof Q==="object")W=Object.keys(Q).length===0;return Y===!1?!W:W}case"IS_NULL":case"IS_NONE":{let W=Q===null||Q===void 0;return Y===!1?!W:W}case"HAS_KEY":if(typeof Q==="object"&&Q!==null&&typeof Y==="string")return Y in Q;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 W=Z(Q),G=Z(Y[0]),J=Z(Y[1]);return W!==null&&G!==null&&J!==null&&W>=G&&W<=J}return!1;case"SINCE":case"AFTER":return U(Q)>=U(Y);case"BEFORE":case"UNTIL":return U(Q)<U(Y);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=[];if(!Q.state)Q.state={};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))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,vars: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=k.evaluate(Y.field,X),Z=Y.value;if(typeof Z==="string"&&Z.includes("${"))Z=k.interpolate(Z,X);return U2.compare(U,Y.operator,Z)}async executeRuleActions(Q,X){let Y=[],U=[],Z="ALL";if(Array.isArray(Q))U=Q;else if(Q&&typeof Q==="object"&&"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((_,$)=>_+($.probability||1),0),J=Math.random()*G,H;for(let _ of U){let $=_.probability||1;if(J-=$,J<=0){H=_;break}}if(!H&&U.length>0)H=U[U.length-1];if(H)U=[H];else U=[]}let W=!1;for(let G of U){if(W)break;if("if"in G&&G.if&&(G.then||G.else)){let H=this.evaluateConditions(G.if,X);if(H&&G.then){let _=await this.executeRuleActions(G.then,X);Y.push(..._)}else if(!H&&G.else){let _=await this.executeRuleActions(G.else,X);Y.push(..._)}continue}if("if"in G&&G.if){if(!this.evaluateConditions(G.if,X))continue}if(G.break){W=!0,Y.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(G.continue){Y.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleAction(G,X);Y.push(J)}return Y}async executeSingleAction(Q,X){if(!Q.type&&!Q.run&&!Q.break&&!Q.continue){let W=["params","run","delay","probability","if","then","else","break","continue","mode","actions"],G=Object.keys(Q).filter((J)=>!W.includes(J));for(let J of G){if(Q.type=J,typeof Q[J]==="string")Q.params={...Q.params,message:Q[J],content:Q[J]};else if(typeof Q[J]==="object"&&Q[J]!==null)Q.params={...Q.params,...Q[J]};break}}if(Q.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${Q.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(W){return{type:"RUN",error:String(W),timestamp:Date.now()}}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||"skipped",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:J}=await Promise.resolve().then(() => (Z2(),oQ)),H=J.getInstance().get(Q.type);if(H)W=(_)=>H({...Q,params:_},X)}catch{W=this.actionHandlers.get(Q.type)}let G;if(W)G=await W(Z,X);else{let J=`No handler registered for action type: ${Q.type}`;console.warn(J),G={warning:J}}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();v1();class R6 extends W2{actionRegistry;stateManager;constructor(Q){super(Q);this.actionRegistry=k1.getInstance(),this.stateManager=g.getInstance()}async processEvent(Q){let X=[];if(Q.state=this.stateManager.getLiveProxy(),this.config?.stateConfig)await this.stateManager.applyConfig(this.config.stateConfig);if(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,vars:Y,timestamp:Date.now(),state:this.stateManager.getLiveProxy()};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((_,$)=>_+($.probability||1),0),J=Math.random()*G,H;for(let _ of U){let $=_.probability||1;if(J-=$,J<=0){H=_;break}}if(H)U=[H]}let W=!1;for(let G of U){if(W)break;if("if"in G&&G.if&&(G.then||G.else)){let H=this.evaluateConditions(G.if,X);if(H&&G.then){let _=await this.executeRuleActionsWithRegistry(G.then,X);Y.push(..._)}else if(!H&&G.else){let _=await this.executeRuleActionsWithRegistry(G.else,X);Y.push(..._)}continue}if("if"in G&&G.if){if(!this.evaluateConditions(G.if,X))continue}if(G.break){W=!0,Y.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(G.continue){Y.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleActionWithRegistry(G,X);Y.push(J)}return Y}isActionGroup(Q){return typeof Q==="object"&&Q!==null&&"mode"in Q&&"actions"in Q}async executeSingleActionWithRegistry(Q,X){if(!Q.type&&!Q.run&&!Q.break&&!Q.continue){let W=Object.keys(Q);for(let G of W)if(this.actionRegistry.get(G)){if(Q.type=G,typeof Q[G]==="string")Q.params={...Q.params,message:Q[G],content:Q[G]};else if(typeof Q[G]==="object"&&Q[G]!==null)Q.params={...Q.params,...Q[G]};break}}if(Q.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${Q.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(W){return{type:"RUN",error:String(W),timestamp:Date.now()}}let Y=Q.probability;if(typeof Y==="string"){let{ExpressionEngine:W}=mQ(B6),G=W.evaluate(Y,X);Y=typeof G==="number"?G:Number(G)}if(Y!==void 0&&Math.random()>Y)return{type:Q.type||"unknown",timestamp:Date.now(),result:{skipped:"probability check failed"}};if(Q.break)return{type:"BREAK",result:"Break action",timestamp:Date.now()};if(Q.continue)return{type:"CONTINUE",result:"Continue action",timestamp:Date.now()};let U=Q.delay;if(typeof U==="string"){let{ExpressionEngine:W}=mQ(B6),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 J=`Generic or unknown action type: ${Q.type}`;if(this.config?.globalSettings?.strictActions)throw Error(J);console.warn(J),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();v1();class BU{static create(Q,X,Y={}){return{event:Q,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},vars:Y,state:g.getInstance().getLiveProxy(),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||{}},vars:{...Y,ip:Q.headers.get("x-forwarded-for")||"unknown"},state:g.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromWebhook(Q,X,Y,U={}){return{event:`WEBHOOK_${Q.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Y,vars:{...U,provider:Q},state:g.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Q)=>{try{return typeof Q==="string"?JSON.parse(Q):null}catch{return null}},jsonStringify:(Q)=>{try{return JSON.stringify(Q)}catch{return null}}}}}v1();Z2();v1();var T1=(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 T1(X);return Q.concat(X)},rQ=(...Q)=>Q.reduce(q1,[]),J1=(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 T1(X))if(!Q.some((W)=>U(W,Z)))Q.push(Z);return Q},nQ=(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 u=(Q,X)=>b(Q)===X,b=(Q)=>{let X=typeof Q;return X==="object"?Q===null?"null":"object":X==="function"?"object":X},l={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},aQ={...l,function:"a function"};class tQ extends Error{}var C=(Q)=>P1(Q,tQ),P1=(Q,X=Error)=>{throw new X(Q)};class G2 extends Error{name="ParseError"}var L=(Q)=>P1(Q,G2),X1=(Q)=>` ${Q}`,eQ="";var O=(Q,X)=>{let Y={},U=Array.isArray(Q),Z=!1;for(let[W,G]of Object.entries(Q).entries()){let J=U?X(W,G[1]):X(...G,W);Z||=typeof J[0]==="number";let H=Array.isArray(J[0])||J.length===0?J:[J];for(let[_,$]of H)if(typeof _==="object")Y[_.group]=D(Y[_.group],$);else Y[_]=$}return Z?Object.values(Y):Y};var C6=Object.entries;var y=(Q,X)=>(Q in X),g1=(Q,X)=>(X in Q);class w6{constructor(Q){Object.assign(this,Q)}}var QX=class{};class J2 extends QX{}var MU=(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)=>MU(Q,X)[1],_1=(Q)=>Object.keys(Q).length===0,N1=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((X)=>[X,Q[X]])],XX=(Q,X)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(X)),YX=(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 d=X1(`unset${eQ}`),UX=(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},DU={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I1={...K6,...N6,...DU,String,Number,Boolean},_2=(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},H2=(Q)=>typeof Q==="object"&&Q!==null?_2(Q)??"object":b(Q);var K=Array.isArray,RU={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"},CU={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"},wU={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"},ZX={...RU,...CU,...wU},L2=(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 WX=(Q)=>GX(Q,new Map),GX=(Q,X)=>{if(typeof Q!=="object"||Q===null)return Q;if(X?.has(Q))return X.get(Q);let Y=L2(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=GX(G.value,X)}}return Object.defineProperties(U,Z),U};var KU=(Q)=>{let X=d;return()=>X===d?X=Q():X},B1=(Q)=>typeof Q==="function"&&Q.length===0;var JX=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
|
+
Message: ${U}
|
|
3
3
|
Source: (${Q.slice(0,-1)}) => {
|
|
4
4
|
${Q[Q.length-1]}
|
|
5
|
-
}`)}}};class c{constructor(Q,...[X]){return Object.assign(Object.setPrototypeOf(Q.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var _X=
|
|
6
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
7
|
-
`+
|
|
8
|
-
${
|
|
9
|
-
${
|
|
5
|
+
}`)}}};class c{constructor(Q,...[X]){return Object.assign(Object.setPrototypeOf(Q.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var _X=KU(()=>{try{return Function("return false")()}catch{return!0}});var j0=X1("brand");var HX=X1("arkInferred");var y0=X1("args");class x{constructor(){}}var PU=()=>{try{return((Error().stack?.split(`
|
|
6
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},NU=globalThis.process?.env??{},LX={fileName:PU,env:NU};var FX=(Q)=>Q[0].toUpperCase()+Q.slice(1),qX=(Q)=>Q[0].toLowerCase()+Q.slice(1),E6=(Q)=>new RegExp(IU(Q),typeof Q==="string"?"":Q.flags);var IU=(Q)=>{return`^(?:${typeof Q==="string"?Q:Q.source})$`};var V1={negativeLookahead:(Q)=>`(?!${Q})`,nonCapturingGroup:(Q)=>`(?:${Q})`},E1="\\",M1={" ":1,"\n":1,"\t":1};var EU=/^-0\.?0*$/.source,VX=/[1-9]\d*/.source,SU=/\.\d+/.source,jU=/\.\d*[1-9]/.source,zX=(Q)=>E6(V1.negativeLookahead(EU)+V1.nonCapturingGroup("-?"+V1.nonCapturingGroup(V1.nonCapturingGroup("0|"+VX)+V1.nonCapturingGroup(Q.decimalPattern)+"?")+(Q.allowDecimalOnly?"|"+Q.decimalPattern:"")+"?")),$X=zX({decimalPattern:jU,allowDecimalOnly:!1}),fU=$X.test.bind($X),h2=zX({decimalPattern:SU,allowDecimalOnly:!0}),m0=h2.test.bind(h2),bU=/^-?\d*\.?\d*$/,yU=(Q)=>Q.length!==0&&bU.test(Q),F2=E6(V1.negativeLookahead("^-0$")+"-?"+V1.nonCapturingGroup(V1.nonCapturingGroup("0|"+VX))),vU=F2.test.bind(F2),S6=/^-?\d+$/,kU=S6.test.bind(S6),AX={number:"a number",bigint:"a bigint",integer:"an integer"},OX=(Q,X)=>`'${Q}' was parsed as ${AX[X]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,gU=(Q,X)=>X==="number"?fU(Q):vU(Q),xU=(Q,X)=>X==="number"?Number(Q):Number.parseInt(Q),hU=(Q,X)=>X==="number"?yU(Q):kU(Q),TX=(Q,X)=>j6(Q,"number",X),BX=(Q,X)=>j6(Q,"number",{...X,strict:!0}),MX=(Q,X)=>j6(Q,"integer",X),j6=(Q,X,Y)=>{let U=xU(Q,X);if(!Number.isNaN(U)){if(hU(Q,X)){if(Y?.strict)return gU(Q,X)?U:L(OX(Q,X));return U}}return Y?.errorOnFail?L(Y?.errorOnFail===!0?`Failed to parse ${AX[X]} from '${Q}'`:Y?.errorOnFail):void 0},DX=(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 L(OX(Q,"bigint"))};var pU="0.56.0",mU={version:pU,filename:LX.fileName(),FileConstructor:P6},S1=mU,RX=new Map,f6=Object.create(null),q2=(Q)=>{let X=RX.get(Q);if(X)return X;let Y=uU(Q);if(f6[Y])Y=`${Y}${f6[Y]++}`;else f6[Y]=1;return S1[Y]=Q,RX.set(Q,Y),Y},D1=(Q)=>/^[$A-Z_a-z][\w$]*$/.test(Q),uU=(Q)=>{switch(typeof Q){case"object":{if(Q===null)break;let X=_2(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 $2=(Q)=>typeof Q==="string"?JSON.stringify(Q):typeof Q==="bigint"?`${Q}n`:`${Q}`;var CX=(Q,X={})=>V2(Q,{onUndefined:"$ark.undefined",onBigInt:(Y)=>`$ark.bigint-${Y}`,...X},[]);var T=(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(V2(Y,x1,[]),null,X?.indent):p2(Y,X?.indent??0,"");case"symbol":return x1.onSymbol(Q);default:return $2(Q)}},p2=(Q,X,Y)=>{if(typeof Q==="function")return x1.onFunction(Q);if(typeof Q!=="object"||Q===null)return $2(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
|
+
`+U);return X?`[
|
|
8
|
+
${U}${W}
|
|
9
|
+
${Y}]`:`[${W}]`}let Z=Q.constructor?.name??"Object";if(Z==="Object"){let W=N1(Q).map(([G,J])=>{let H=typeof G==="symbol"?x1.onSymbol(G):D1(G)?G:JSON.stringify(G),_=p2(J,X,U);return`${U}${H}: ${_}`});if(W.length===0)return"{}";return X?`{
|
|
10
10
|
${W.join(`,
|
|
11
11
|
`)}
|
|
12
|
-
${
|
|
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,
|
|
14
|
-
`).map((
|
|
15
|
-
`):this.body} }`}compile(){return new JX(...this.argNames,this.body)}}var
|
|
12
|
+
${Y}}`:`{${W.join(", ")}}`}if(Q instanceof Date)return j1(Q);if("expression"in Q&&typeof Q.expression==="string")return Q.expression;return Z},x1={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${q2(Q)})`,onFunction:(Q)=>`Function(${q2(Q)})`},V2=(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 x1.onFunction(U);if(Y.includes(U))return"(cycle)";let Z=[...Y,U];if(Array.isArray(U))return U.map((G)=>V2(G,X,Z));if(U instanceof Date)return U.toDateString();let W={};for(let G in U)W[G]=V2(U[G],X,Z);for(let G of Object.getOwnPropertySymbols(U))W[X.onSymbol?.(G)??G.toString()]=V2(U[G],X,Z);return W}case"symbol":return x1.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(),J=Q.getMilliseconds();if(Y===0&&U===1&&Z===0&&W===0&&G===0&&J===0)return`${X}`;let H=`${lU[Y]} ${U}, ${X}`;if(Z===0&&W===0&&G===0&&J===0)return H;let _=Q.toLocaleTimeString(),$=_.endsWith(" AM")||_.endsWith(" PM")?_.slice(-3):"";if($)_=_.slice(0,-$.length);if(J)_+=`.${cU(J,3)}`;else if(dU.test(_))_=_.slice(0,-3);return`${_+$}, ${H}`},lU=["January","February","March","April","May","June","July","August","September","October","November","December"],dU=/:\d\d:00$/,cU=(Q,X)=>String(Q).padStart(X,"0");var wX=(Q,X,...[Y])=>{let U=Y?.stringifySymbol??T,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 L(`${T(X)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return Z},z1=(Q,...X)=>Q.reduce((Y,U)=>wX(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"?T(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=wX(Q,Y),X.push(Q);return this.cache.stringifyAncestors=X}}class A2{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 M1))}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 KX=(Q,X)=>`Unmatched ${Q}${X===""?"":` before ${X}`}`,m2=(Q)=>`Missing ${Q}`;var qW=X1("implementedTraits");var b6="$ark",oU=2;while(b6 in globalThis)b6=`$ark${oU++}`;var PX=b6;globalThis[PX]=S1;var F=S1,iU=(Q)=>`${PX}.${Q}`,S=(Q)=>iU(q2(Q));class u2 extends J2{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 NX(`${Q}`,X)}line(Q){return this.body+=`${" ".repeat(this.indentation)}${Q}
|
|
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
|
+
`).map((Y)=>" ".repeat(X)+`${Y}`).join(`
|
|
15
|
+
`):this.body} }`}compile(){return new JX(...this.argNames,this.body)}}var Y1=(Q)=>u(Q,"object")||typeof Q==="symbol"?S(Q):$2(Q),y6=(Q,X=!1)=>{if(typeof Q==="string"&&D1(Q))return`${X?"?":""}.${Q}`;return NX(sU(Q),X)},sU=(Q)=>typeof Q==="symbol"?S(Q):JSON.stringify(Q),NX=(Q,X=!1)=>`${X?"?.":""}[${Q}]`;class O2 extends u2{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)=>O(Q,(X,Y)=>[X,K(Y)?[...Y]:Y]),p=X1("arkKind"),V=(Q,X)=>Q?.[p]===X,P=(Q)=>V(Q,"root")||V(Q,"constraint");var IX=["unit","proto","domain"],h1=["required","optional","index","sequence"],v6=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],k6=[...v6,"structure","predicate"],d2=[...k6,...h1],p1=["alias","union","morph","unit","intersection","proto","domain"],rU=[...p1,...d2],c2=O(d2,(Q,X)=>[X,1]),EX=O([...h1,"undeclared"],(Q,X)=>[X,1]),SX=O(rU,(Q,X)=>[X,Q]),m1=(Q)=>typeof Q==="string"&&(Q in SX);var u1=(Q)=>SX[Q],o2=(Q)=>p1.slice(u1(Q)+1),rW=[...o2("union"),"alias"],nW=[...o2("morph"),"alias"],a=(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+" }"},B=(Q)=>{let X=Q;if(X.hasAssociatedError)X.defaults.expected??=(Y)=>("description"in Y)?Y.description:X.defaults.description(Y),X.defaults.actual??=(Y)=>T(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 jX extends Error{name="ToJsonSchemaError";code;context;constructor(Q,X){super(T(X,{quoteKeys:!1,indent:4}));this.code=Q,this.context=X}hasCode(Q){return this.code===Q}}var nU={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:jX,throw:(...Q)=>{throw new I.Error(...Q)},throwInternalOperandError:(Q,X)=>C(`Unexpected JSON Schema input for ${Q}: ${T(X)}`),defaultConfig:nU};F.config??={};var T2=(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(m1(U))Y[U]={...Q[U],...X[U]};else Y[U]=X[U]}return Y},aU={"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 fX(X??{},void 0);if(!X)return Q;let Y={...Q},U;for(U in X)if(U==="fallback")Y.fallback=tU(Q.fallback,X.fallback);else Y[U]=X[U];return fX(Y,X)},fX=(Q,X)=>{if(X?.dialect!==void 0)return Q;if(X?.target!==void 0)return{...Q,dialect:aU[X.target]};return Q},tU=(Q,X)=>{Q=bX(Q),X=bX(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},bX=(Q)=>typeof Q==="function"?{default:Q}:Q??{};class C1 extends J2{[p]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Q,relativePath:X,...Y},U){super();this.input=Y,this.ctx=U,XX(this,Y);let Z=U.data;if(Y.code==="union")Y.errors=Y.errors.flatMap((G)=>{let J=G.hasCode("union")?G.errors:[G];if(!Q&&!X)return J;return J.map((H)=>H.transform((_)=>({..._,path:rQ(Q,_.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 o extends g2{[p]="errors";ctx;constructor(Q){super();this.ctx=Q}byPath=Object.create(null);get flatByPath(){return O(this.byPath,(Q,X)=>[Q,X.flat])}get flatProblemsByPath(){return O(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 o(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
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)=>` • ${
|
|
18
|
-
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var
|
|
17
|
+
`+Q.map((X)=>` • ${eU(X)}`).join(`
|
|
18
|
+
`));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var eU=(Q)=>Q.toString().split(`
|
|
19
19
|
`).join(`
|
|
20
|
-
`);class Y1{path=[];errors=new o(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 A2(...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:U}of Q){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,U)}}}applyMorphsAtPath(Q,X){let U=Q[Q.length-1],Y;if(U!==void 0){Y=this.root;for(let Z=0;Z<Q.length-1;Z++)Y=Y[Q[Z]]}for(let Z of X){this.path=[...Q];let W=P(Z),G=Z(Y===void 0?this.root:Y[U],this);if(G instanceof C1){if(!this.errors.includes(G))this.errors.add(G);break}if(G instanceof o){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(Y===void 0)this.root=G;else Y[U]=G;this.applyQueuedMorphs()}}}var i=(Q,X,U)=>{if(!U)return X();U.path.push(Q);let Y=X();return U.path.pop(),Y};class M2 extends c{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Q,X){super((Y,Z,W=this.onFail)=>{if(Z)return this.traverseApply(Y,Z),Z.hasError()?Z.errors:Z.data;return this.rootApply(Y,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((Y,Z)=>YZ(Y,Z.shallowReferences),[this]);let U=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Y=0;Y<this.children.length;Y++){if(this.includesTransform||=this.children[Y].includesTransform,this.includesContextualPredicate||=this.children[Y].includesContextualPredicate,this.isCyclic||=this.children[Y].isCyclic,!U){let Z=this.children[Y].flatRefs;for(let W=0;W<Z.length;W++){let G=Z[W];if(!this.flatRefs.some((J)=>vX(J,G))){this.flatRefs.push(G);for(let J of G.node.branches)if(J.hasKind("morph")||J.hasKind("intersection")&&J.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:J})}}}Object.assign(this.referencesById,this.children[Y].referencesById)}this.flatRefs.sort((Y,Z)=>Y.path.length>Z.path.length?1:Y.path.length<Z.path.length?-1:Y.propString>Z.propString?1:Y.propString<Z.propString?-1:Y.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((Y)=>Y.length===1||Y.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Y)=>Y.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Y)=>this.traverseAllows(Y,new Y1(Y,this.$.resolvedConfig)):(Y)=>this.traverseAllows(Y)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,U)=>{if(this.allows(X))return X;let Y=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,Y),Y.finalize(U)};case"contextual":return(X,U)=>{let Y=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,Y),Y.finalize(U)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Q=this.$.resolvedConfig.clone;return(X,U)=>{if(this.allows(X))return this.contextFreeMorph(Q&&(typeof X==="object"&&X!==null||typeof X==="function")?Q(X):X);let Y=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,Y),Y.finalize(U)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,C(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=UZ(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,(U)=>U.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[U,Y]of this.innerEntries){let Z=this.impl.keys[U];if(Z.reduceIo)Z.reduceIo(Q,X,Y);else if(Z.child){let W=Y;X[U]=K(W)?W.map((G)=>Q==="in"?G.rawIn:G.rawOut):Q==="in"?W.rawIn:W.rawOut}else X[U]=Y}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(IX,this.kind)}isConstraint(){return n(d2,this.kind)}isStructural(){return n(h1,this.kind)}isRefinement(){return n(k6,this.kind)}isRoot(){return n(p1,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=T2.normalize(Q);return this._select(X)}_select(Q){let X=T2.applyBoundary[Q.boundary??"references"](this);if(Q.kind)X=X.filter((U)=>U.kind===Q.kind);if(Q.where)X=X.filter(Q.where);return T2.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 U=X.bindScope??this.$;if(X.seen[this.id])return this.$.lazilyResolve(X.seen[this.id]);if(X.shouldTransform?.(this,X)===!1)return this;let Y;if(X.seen[this.id]=()=>Y,this.hasKind("structure")&&this.undeclared!==X.undeclaredKeyHandling)X={...X,undeclaredKeyHandling:this.undeclared};let Z=B(this.inner,(_,$)=>{if(!this.impl.keys[_].child)return[_,$];let O=$;if(!K(O)){let b=O._transform(Q,X);return b?[_,b]:[]}if(O.length===0)return[_,$];let R=O.flatMap((b)=>{return b._transform(Q,X)??[]});return R.length?[_,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 Y=G;let J=Object.keys(G);if((J.length===0||J.length===1&&J[0]==="meta")&&!_1(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 Y=U.node(this.kind,G,X.parseOptions)}configureReferences(Q,X="references"){let U=T2.normalize(X),Y=typeof Q==="string"?(J,L)=>({...L,meta:{...L.meta,description:Q}}):typeof Q==="function"?(J,L)=>({...L,meta:Q(L.meta)}):(J,L)=>({...L,meta:{...L.meta,...Q}});if(U.boundary==="self")return this.$.node(this.kind,Y(this.kind,{...this.inner,meta:this.meta}));let Z=this._select(U),W=Z&&T1(Z),G=U.boundary==="child"?(J,L)=>L.root.children.includes(J):U.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Y,{shouldTransform:G,selected:W}))}}var T2={applyBoundary:{self:(Q)=>[Q],child:(Q)=>[...Q.children],shallow:(Q)=>[...Q.shallowReferences],references:(Q)=>[...Q.references]},applyMethod:{filter:(Q)=>Q,assertFilter:(Q,X,U)=>{if(Q.length===0)P1(yX(X,U));return Q},find:(Q)=>Q[0],assertFind:(Q,X,U)=>{if(Q.length===0)P1(yX(X,U));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?y(Q,T2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},yX=(Q,X)=>`${Q} had no references matching ${T(X)}.`,QZ=(Q)=>z1(Q,{stringifyNonKey:(X)=>X.expression}),XZ=/"(\$ark\.[^"]+)"/g,UZ=(Q)=>JSON.stringify(Q).replace(XZ,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:QZ(Q)}),vX=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),h6=(Q,X)=>J1(Q,X,{isEqual:vX}),YZ=(Q,X)=>J1(Q,X,{isEqual:(U,Y)=>U.equals(Y)});class q extends Array{static init(Q,X,U,Y){return new q({kind:Q,l:X,r:U,path:Y?.path??[],optional:Y?.optional??!1})}add(Q,X,U,Y){return this.push({kind:Q,l:X,r:U,path:Y?.path??[],optional:Y?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Q,l:X,r:U}=this[0],Y=z1(Q);return m6(`Intersection${Y&&` at ${Y}`} of ${kX(X,U)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
-
• ${this.map(({path:Q,l:X,r:
|
|
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((U)=>({...U,path:[Q,...U.path],optional:U.optional||X==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var kX=(Q,X)=>`${p6(Q)} and ${p6(X)}`,p6=(Q)=>P(Q)?Q.expression:K(Q)?Q.map(p6).join(" | ")||"never":String(Q),m6=(Q)=>`${Q} results in an unsatisfiable type`;var l1={},s=(Q,X,U)=>N(Q,X,{$:U,invert:!1,pipe:!1}),V2=(Q,X,U)=>N(Q,X,{$:U,invert:!1,pipe:!0}),N=(Q,X,U)=>{let Y=U.pipe?"|>":"&",Z=`${Q.hash}${Y}${X.hash}`;if(l1[Z]!==void 0)return l1[Z];if(!U.pipe){let J=`${X.hash}${Y}${Q.hash}`;if(l1[J]!==void 0){let L=l1[J],_=L instanceof q?L.invert():L;return l1[Z]=_,_}}let W=!U.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?u6(Q,X,U):Q.hasKindIn(...p1)?ZZ(Q,X,U):u6(Q,X,U);if(P(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return l1[Z]=G,G},u6=(Q,X,U)=>{let Y=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(Y===Q.kind)return Z(Q,X,U);else{let W=Z(X,Q,{...U,invert:!U.invert});if(W instanceof q)W=W.invert();return W}},ZZ=(Q,X,U)=>Q.includesTransform||X.includesTransform?U.invert?gX(X,Q,U):gX(Q,X,U):u6(Q,X,U),gX=(Q,X,U)=>Q.distribute((Y)=>WZ(Y,X,U),(Y)=>{let Z=Y.filter(P);if(Z.length===0)return q.init("union",Q.branches,X.branches);if(Z.length<Q.branches.length||!Q.branches.every((J,L)=>J.rawIn.equals(Z[L].rawIn)))return U.$.parseSchema(Z);let W;if(Z.length===1){let J=Z[0];if(!W)return J;return U.$.node("morph",{...J.inner,in:J.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return U.$.parseSchema(G)}),WZ=(Q,X,U)=>{if(Q.hasKind("morph")){let Z=[...Q.morphs];if(Q.lastMorphIfNode){let W=N(Q.lastMorphIfNode,X,U);if(W instanceof q)return W;Z[Z.length-1]=W}else Z.push(X);return U.$.node("morph",{morphs:Z,in:Q.inner.in})}if(X.hasKind("morph")){let Z=N(Q,X.rawIn,U);if(Z instanceof q)return Z;return U.$.node("morph",{morphs:[X],in:Z})}return U.$.node("morph",{morphs:[X],in:Q})};class a extends M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,p,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return s(this,Q,this.$)}}class O1 extends a{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 h=(Q)=>(X,U)=>{if(K(X)){if(X.length===0)return;let Z=X.map((W)=>U.$.node(Q,W));if(Q==="predicate")return Z;return Z.sort((W,G)=>W.hash<G.hash?-1:1)}let Y=U.$.node(Q,X);return Y.hasOpenIntersection()?[Y]:Y},d1=(Q)=>{let X=Q.r.shift();if(!X){let Y=Q.l.length===0&&Q.kind==="structure"?F.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,GZ(Q.l)),{prereduced:!0});for(let Z of Q.roots){if(Y instanceof q)return Y;Y=N(Z,Y,Q.ctx)}return Y}let U=!1;for(let Y=0;Y<Q.l.length;Y++){let Z=N(Q.l[Y],X,Q.ctx);if(Z===null)continue;if(Z instanceof q)return Z;if(Z.isRoot())return Q.roots.push(Z),Q.l.splice(Y),d1(Q);if(!U)Q.l[Y]=Z,U=!0;else if(!Q.l.includes(Z))return C(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!U)Q.l.push(X);if(Q.kind==="intersection"){if(X.impliedSiblings)for(let Y of X.impliedSiblings)J1(Q.r,Y)}return d1(Q)},c1=(Q)=>{return Object.entries(Q).flatMap(([U,Y])=>(U in c2)?Y:[]).sort((U,Y)=>U.precedence<Y.precedence?-1:U.precedence>Y.precedence?1:U.kind==="predicate"&&Y.kind==="predicate"?0:U.hash<Y.hash?-1:1)},GZ=(Q)=>{let X={};for(let U of Q)if(U.hasOpenIntersection())X[U.kind]=D(X[U.kind],U);else{if(X[U.kind])return C(`Unexpected intersection of closed refinements of kind ${U.kind}`);X[U.kind]=U}return X},xX=(...Q)=>H(hX(...Q)),hX=(Q,X,U)=>{let Y=U.hasKind("morph")?"a morph":U.isUnknown()?"unknown":U.exclude(X).defaultShortDescription;return`${FX(Q)} operand must be ${X.description} (was ${Y})`};var pX=(Q,X,U)=>new w1(Q,X,U,U,null);class i2 extends c{}class w1 extends c{[p]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,U,Y,Z){super((...W)=>{let G=B(this.names,(J,L)=>{let _=this.arg$.parse(W[J]);if(!_.extends(this.constraints[J]))H(JZ(L,this.constraints[J].expression,_.expression));return[L,_]});if(this.defIsLazy()){let J=this.bodyDef(G);return this.$.parse(J)}return this.$.parse(X,{args:G})});this.paramDefs=Q,this.bodyDef=X,this.$=U,this.arg$=Y,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:CX(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 JZ=(Q,X,U)=>`${Q} must be assignable to ${X} (was ${U})`;var _Z=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 mX extends a{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 U=X.currentErrorCount;if(!this.predicate(Q,X.external)&&X.currentErrorCount===U)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:_Z,Node:mX};var LZ=M({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:H(HZ(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,U)=>U.$.node("divisor",{rule:Math.abs(Q.rule*X.rule/FZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class uX 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:LZ,Node:uX};var HZ=(Q)=>`divisor must be an integer (was ${Q})`,FZ=(Q,X)=>{let U,Y=Q,Z=X;while(Z!==0)U=Z,Z=Y%Z,Y=U;return Y};class r extends O1{boundOperandKind=zZ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=OZ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${qZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?BZ(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 qZ={"<":">=","<=":">",">":"<=",">=":"<"},$Z={min:"max",minLength:"maxLength",after:"before"},s2={parse:(Q)=>Q||void 0},r2=(Q)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:U,...Y}=X;return U?{...Y,rule:Q==="minLength"?Y.rule+1:Y.rule-1}:Y},n2=(Q)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:U,...Y}=X;if(!U)return Y;let Z=typeof Y.rule==="number"?Y.rule:typeof Y.rule==="string"?new Date(Y.rule).valueOf():Y.rule.valueOf();return U?{...Y,rule:Q==="after"?Z+1:Z-1}:Y},t2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,AZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,o1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)H(AZ(Q,X));return X},zZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},OZ=(Q,X)=>`${y(Q,$Z)?">":"<"}${X?"":"="}`,BZ=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),lX=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var TZ=M({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:n2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class dX extends r{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:TZ,Node:dX};var MZ=M({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t2,serialize:(Q)=>Q.toISOString()}},normalize:n2("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:j1},intersections:{before:(Q,X)=>Q.isStricterThan(X)?Q:X,after:(Q,X,U)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?U.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)}});class cX extends r{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:MZ,Node:cX};var VZ=M({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:o1("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,U)=>q.init("unit",U.$.node("unit",{unit:Q.rule}),U.$.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 oX 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:oX};var DZ=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,U)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?U.$.node("unit",{unit:Q.rule}):null:q.init("range",Q,X)},obviatesBasisDescription:!0});class iX extends r{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:DZ,Node:iX};var RZ=M({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:o1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:r2("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,U)=>Q.overlapsRange(X)?Q.overlapIsUnit(X)?U.$.node("exactLength",{rule:Q.rule}):null:q.init("range",Q,X)}});class sX extends r{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 r6={implementation:RZ,Node:sX};var CZ=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 rX extends r{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 n6={implementation:CZ,Node:rX};var wZ=M({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:o1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:r2("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 nX extends r{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:wZ,Node:nX};var tX={min:n6.implementation,max:s6.implementation,minLength:t6.implementation,maxLength:r6.implementation,exactLength:i6.implementation,after:c6.implementation,before:o6.implementation},aX={min:n6.Node,max:s6.Node,minLength:t6.Node,maxLength:r6.Node,exactLength:i6.Node,after:c6.Node,before:o6.Node};var KZ=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 eX 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:KZ,Node:eX};var D2=(Q,X)=>{let U=PZ(Q);if(X&&!X.includes(U))return H(`Root of kind ${U} should be one of ${X}`);return U},PZ=(Q)=>{if(A(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in l)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return H(Q4(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((U)=>(U in c2)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return H(Q4(Q))},Q4=(Q)=>`${T(Q)} is not a valid type schema`,X4={},NZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,m={};F.nodesByRegisteredId=m;var e6=(Q)=>{return X4[Q]??=0,`${Q}${++X4[Q]}`},QQ=(Q)=>{let X=i1[Q.kind],U=X.applyConfig?.(Q.def,Q.$.resolvedConfig)??Q.def,Y={},{meta:Z,...W}=U,G=Z===void 0?{}:typeof Z==="string"?{description:Z}:Z,J=C6(W).sort(([_],[$])=>m1(_)?m1($)?u1(_)-u1($):1:m1($)?-1:_<$?-1:1).filter(([_,$])=>{if(_.startsWith("meta.")){let O=_.slice(5);return G[O]=$,!1}return!0});for(let _ of J){let $=_[0],O=X.keys[$];if(!O)return H(`Key ${$} is not valid on ${Q.kind} schema`);let R=O.parse?O.parse(_[1],Q):_[1];if(R!==d&&(R!==void 0||O.preserveUndefined))Y[$]=R}if(X.reduce&&!Q.prereduced){let _=X.reduce(Y,Q.$);if(_){if(_ instanceof q)return _.throw();return IZ(_,G)}}return XQ({id:Q.id,kind:Q.kind,inner:Y,meta:G,$:Q.$})},XQ=({id:Q,kind:X,inner:U,meta:Y,$:Z,ignoreCache:W})=>{let G=i1[X],J=C6(U),L=[],_={};for(let[W1,y1]of J){let U2=G.keys[W1],HY=U2.serialize??(U2.child?NZ:t);if(_[W1]=HY(y1),U2.child===!0){let O6=y1;if(K(O6))L.push(...O6);else L.push(O6)}else if(typeof U2.child==="function")L.push(...U2.child(y1))}if(G.finalizeInnerJson)_=G.finalizeInnerJson(_);let $={..._},O={};if(!_1(Y))O=B(Y,(W1,y1)=>[W1,W1==="examples"?y1:t(y1)]),$.meta=a2(O,"description",!0);_=a2(_,G.collapsibleKey,!1);let R=JSON.stringify({kind:X,..._});$=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 hQ={id:Q,kind:X,impl:G,inner:U,innerEntries:J,innerJson:_,innerHash:R,meta:Y,metaJson:O,json:$,hash:F1,collapsibleJson:b,children:L};if(X!=="intersection"){for(let W1 in U)if(W1!=="in"&&W1!=="out")hQ[W1]=U[W1]}let LY=new Y4[X](hQ,Z);return Z.nodesByHash[F1]=LY},U4=(Q,X)=>{if(Q.id===X)return Q;if(P(m[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})},IZ=(Q,X,U)=>{if(U&&P(m[U]))C(`Unexpected attempt to overwrite node id ${U}`);return XQ({id:U??e6(X.alias??Q.kind),kind:Q.kind,inner:Q.inner,meta:X,$:Q.$})},a2=(Q,X,U)=>{let Y=Object.keys(Q);if(Y.length===1&&Y[0]===X){let Z=Q[X];if(U)return Z;if(u(Z,"object")&&(Object.keys(Z).length===1||Array.isArray(Z)))return Z}return Q};var R2=(Q,X,U)=>{if(Q.key!==X.key)return null;let Y=Q.key,Z=N(Q.value,X.value,U),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 U.$.node("required",{key:Y,value:Z});let G=Q.hasDefault()?X.hasDefault()?Q.default===X.default?Q.default:H(UQ(Q.default,X.default)):Q.default:X.hasDefault()?X.default:d;return U.$.node("optional",{key:Y,value:Z,default:G})};class C2 extends a{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=U1(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 U=super._transform(Q,X);return X.path.pop(),U}hasDefault(){return"default"in this.inner}traverseAllows=(Q,X)=>{if(this.key in Q)return i(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)i(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 UQ=(Q,X)=>`Invalid intersection of default values ${T(Q)} & ${T(X)}`;var EZ=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:R2}});class Z4 extends C2{constructor(...Q){super(...Q);if("default"in this.inner)K2(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} = ${T(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=jZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var w2={implementation:EZ,Node:Z4},SZ={},jZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${t(Q.default)}}`;return SZ[X]??=YQ(Q.key,Q.value,Q.default)},YQ=(Q,X,U)=>{if(typeof U==="function")return X.includesTransform?(Z,W)=>{return i(Q,()=>X(Z[Q]=U(),W),W),Z}:(Z)=>{return Z[Q]=U(),Z};let Y=X.includesTransform?X.assert(U):U;return u(Y,"object")?(Z,W)=>{return i(Q,()=>X(Z[Q]=U,W),W),Z}:(Z)=>{return Z[Q]=Y,Z}},K2=(Q,X,U)=>{let Y=M1(X);if(u(X,"object")&&!Y)H(bZ(U));let Z=Q.in(Y?X():X);if(Z instanceof o){if(U===null)H(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((J)=>({...J,prefixPath:[U]})));H(`Default for ${W.summary}`)}return X},bZ=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${U1(Q)} `}must be specified as a function like () => ({my: 'object'})`};class e extends M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,p,{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 o)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:W4(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:W4(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return H(fZ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,X){let U=this.branches.map(Q);return X?.(U)??U}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Q={}){let X=g6(this.$.resolvedConfig.toJsonSchema,Q);X.useRefs||=this.isCyclic;let U=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(U,this.toJsonSchemaRecurse(X)),X.useRefs){let Y=B(this.references,(Z,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(U,{definitions:Y});else U.$defs=Y}return U}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),U=this.rawIntersect(X);if(U instanceof q)return U;return this.$.finalize(U)}rawIntersect(Q){return s(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,U)=>X.intersect(U).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Q.branches.length===0)H(m6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return H(vZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((U)=>this.applyStructuralOperation("merge",[G4(U)??H(J4("merge",U.expression))])))}applyStructuralOperation(Q,X){return this.distribute((U)=>{if(U.equals(F.intrinsic.object)&&Q!=="merge")return U;let Y=G4(U);if(!Y)H(J4(Q,U.expression));if(Q==="keyof")return Y.keyof();if(Q==="get")return Y.get(...X);if(Q==="props")return Y.props;let Z=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{domain:"object",structure:Y[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((U)=>U.extends(X)))}exclude(Q){let X=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((U)=>!U.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 K2(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){let X=Q.reduce((U,Y)=>U.rawPipeOnce(Y),this);return this.$.finalize(X)}tryPipe(...Q){let X=Q.reduce((U,Y)=>U.rawPipeOnce(A(Y,"root")?Y:(Z,W)=>{try{return Y(Z,W)}catch(G){return W.error({code:"predicate",predicate:Y,actual:`aborted due to error:
|
|
20
|
+
`);class U1{path=[];errors=new o(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 o){if(!W)this.errors.merge(G);this.queuedMorphs=[];break}if(U===void 0)this.root=G;else U[Y]=G;this.applyQueuedMorphs()}}}var i=(Q,X,Y)=>{if(!Y)return X();Y.path.push(Q);let U=X();return Y.path.pop(),U};class M2 extends c{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)=>UZ(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((J)=>vX(J,G))){this.flatRefs.push(G);for(let J of G.node.branches)if(J.hasKind("morph")||J.hasKind("intersection")&&J.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:G.path,propString:G.propString,node:J})}}}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=YZ(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(IX,this.kind)}isConstraint(){return n(d2,this.kind)}isStructural(){return n(h1,this.kind)}isRefinement(){return n(k6,this.kind)}isRoot(){return n(p1,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=B2.normalize(Q);return this._select(X)}_select(Q){let X=B2.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 B2.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=O(this.inner,(_,$)=>{if(!this.impl.keys[_].child)return[_,$];let A=$;if(!K(A)){let f=A._transform(Q,X);return f?[_,f]:[]}if(A.length===0)return[_,$];let R=A.flatMap((f)=>{return f._transform(Q,X)??[]});return R.length?[_,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 J=Object.keys(G);if((J.length===0||J.length===1&&J[0]==="meta")&&!_1(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=B2.normalize(X),U=typeof Q==="string"?(J,H)=>({...H,meta:{...H.meta,description:Q}}):typeof Q==="function"?(J,H)=>({...H,meta:Q(H.meta)}):(J,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&&T1(Z),G=Y.boundary==="child"?(J,H)=>H.root.children.includes(J):Y.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:G,selected:W}))}}var B2={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(yX(X,Y));return Q},find:(Q)=>Q[0],assertFind:(Q,X,Y)=>{if(Q.length===0)P1(yX(X,Y));return Q[0]}},normalize:(Q)=>typeof Q==="function"?{boundary:"references",method:"filter",where:Q}:typeof Q==="string"?y(Q,B2.applyBoundary)?{method:"filter",boundary:Q}:{boundary:"references",method:"filter",kind:Q}:{boundary:"references",method:"filter",...Q}},yX=(Q,X)=>`${Q} had no references matching ${T(X)}.`,QZ=(Q)=>z1(Q,{stringifyNonKey:(X)=>X.expression}),XZ=/"(\$ark\.[^"]+)"/g,YZ=(Q)=>JSON.stringify(Q).replace(XZ,"$1"),Z1=(Q,X)=>({path:Q,node:X,propString:QZ(Q)}),vX=(Q,X)=>Q.propString===X.propString&&Q.node.equals(X.node),h6=(Q,X)=>J1(Q,X,{isEqual:vX}),UZ=(Q,X)=>J1(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 m6(`Intersection${U&&` at ${U}`} of ${kX(X,Y)}`)}return`The following intersections result in unsatisfiable types:
|
|
21
|
+
• ${this.map(({path:Q,l:X,r:Y})=>`${Q}: ${kX(X,Y)}`).join(`
|
|
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 kX=(Q,X)=>`${p6(Q)} and ${p6(X)}`,p6=(Q)=>P(Q)?Q.expression:K(Q)?Q.map(p6).join(" | ")||"never":String(Q),m6=(Q)=>`${Q} results in an unsatisfiable type`;var l1={},s=(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(l1[Z]!==void 0)return l1[Z];if(!Y.pipe){let J=`${X.hash}${U}${Q.hash}`;if(l1[J]!==void 0){let H=l1[J],_=H instanceof q?H.invert():H;return l1[Z]=_,_}}let W=!Y.pipe||!Q.includesTransform&&!X.includesTransform;if(W&&Q.equals(X))return Q;let G=W?u6(Q,X,Y):Q.hasKindIn(...p1)?ZZ(Q,X,Y):u6(Q,X,Y);if(P(G)){if(Q.equals(G))G=Q;else if(X.equals(G))G=X}return l1[Z]=G,G},u6=(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}},ZZ=(Q,X,Y)=>Q.includesTransform||X.includesTransform?Y.invert?gX(X,Q,Y):gX(Q,X,Y):u6(Q,X,Y),gX=(Q,X,Y)=>Q.distribute((U)=>WZ(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((J,H)=>J.rawIn.equals(Z[H].rawIn)))return Y.$.parseSchema(Z);let W;if(Z.length===1){let J=Z[0];if(!W)return J;return Y.$.node("morph",{...J.inner,in:J.rawIn.configure(W,"self")})}let G={branches:Z};if(W)G.meta=W;return Y.$.parseSchema(G)}),WZ=(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 M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,p,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return s(this,Q,this.$)}}class A1 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 h=(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},d1=(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,GZ(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),d1(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)J1(Q.r,U)}return d1(Q)},c1=(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)},GZ=(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},xX=(...Q)=>L(hX(...Q)),hX=(Q,X,Y)=>{let U=Y.hasKind("morph")?"a morph":Y.isUnknown()?"unknown":Y.exclude(X).defaultShortDescription;return`${FX(Q)} operand must be ${X.description} (was ${U})`};var pX=(Q,X,Y)=>new w1(Q,X,Y,Y,null);class i2 extends c{}class w1 extends c{[p]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,X,Y,U,Z){super((...W)=>{let G=O(this.names,(J,H)=>{let _=this.arg$.parse(W[J]);if(!_.extends(this.constraints[J]))L(JZ(H,this.constraints[J].expression,_.expression));return[H,_]});if(this.defIsLazy()){let J=this.bodyDef(G);return this.$.parse(J)}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:CX(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 JZ=(Q,X,Y)=>`${Q} must be assignable to ${X} (was ${Y})`;var _Z=B({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 mX 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:_Z,Node:mX};var HZ=B({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Q)=>Number.isInteger(Q)?Q:L(LZ(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/FZ(Q.rule,X.rule))})},obviatesBasisDescription:!0});class uX extends A1{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:HZ,Node:uX};var LZ=(Q)=>`divisor must be an integer (was ${Q})`,FZ=(Q,X)=>{let Y,U=Q,Z=X;while(Z!==0)Y=Z,Z=U%Z,U=Y;return U};class r extends A1{boundOperandKind=zZ[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} ${qZ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?OZ(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 qZ={"<":">=","<=":">",">":"<=",">=":"<"},$Z={min:"max",minLength:"maxLength",after:"before"},s2={parse:(Q)=>Q||void 0},r2=(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},n2=(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},a2=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,VZ=(Q,X)=>`${Q} bound must be a positive integer (was ${X})`,o1=(Q)=>(X)=>{if(!Number.isInteger(X)||X<0)L(VZ(Q,X));return X},zZ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},AZ=(Q,X)=>`${y(Q,$Z)?">":"<"}${X?"":"="}`,OZ=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),lX=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var TZ=B({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(Q)=>Q.toISOString()}},normalize:n2("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:j1},intersections:{after:(Q,X)=>Q.isStricterThan(X)?Q:X}});class dX extends r{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:TZ,Node:dX};var BZ=B({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a2,serialize:(Q)=>Q.toISOString()}},normalize:n2("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 cX extends r{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:BZ,Node:cX};var MZ=B({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:o1("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 oX extends A1{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:MZ,Node:oX};var DZ=B({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 iX extends r{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:DZ,Node:iX};var RZ=B({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:o1("maxLength")}},reduce:(Q,X)=>Q.rule===0?X.node("exactLength",Q):void 0,normalize:r2("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 sX extends r{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 r6={implementation:RZ,Node:sX};var CZ=B({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 rX extends r{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 n6={implementation:CZ,Node:rX};var wZ=B({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:o1("minLength")}},reduce:(Q)=>Q.rule===0?F.intrinsic.unknown:void 0,normalize:r2("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 nX extends r{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 a6={implementation:wZ,Node:nX};var aX={min:n6.implementation,max:s6.implementation,minLength:a6.implementation,maxLength:r6.implementation,exactLength:i6.implementation,after:c6.implementation,before:o6.implementation},tX={min:n6.Node,max:s6.Node,minLength:a6.Node,maxLength:r6.Node,exactLength:i6.Node,after:c6.Node,before:o6.Node};var KZ=B({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 eX extends A1{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 t6={implementation:KZ,Node:eX};var R2=(Q,X)=>{let Y=PZ(Q);if(X&&!X.includes(Y))return L(`Root of kind ${Y} should be one of ${X}`);return Y},PZ=(Q)=>{if(V(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":(Q in l)?"domain":"proto";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return L(Q4(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(Q4(Q))},Q4=(Q)=>`${T(Q)} is not a valid type schema`,X4={},NZ=(Q)=>K(Q)?Q.map((X)=>X.collapsibleJson):Q.collapsibleJson,m={};F.nodesByRegisteredId=m;var e6=(Q)=>{return X4[Q]??=0,`${Q}${++X4[Q]}`},QQ=(Q)=>{let X=i1[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,J=C6(W).sort(([_],[$])=>m1(_)?m1($)?u1(_)-u1($):1:m1($)?-1:_<$?-1:1).filter(([_,$])=>{if(_.startsWith("meta.")){let A=_.slice(5);return G[A]=$,!1}return!0});for(let _ of J){let $=_[0],A=X.keys[$];if(!A)return L(`Key ${$} is not valid on ${Q.kind} schema`);let R=A.parse?A.parse(_[1],Q):_[1];if(R!==d&&(R!==void 0||A.preserveUndefined))U[$]=R}if(X.reduce&&!Q.prereduced){let _=X.reduce(U,Q.$);if(_){if(_ instanceof q)return _.throw();return IZ(_,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=i1[X],J=C6(Y),H=[],_={};for(let[W1,y1]of J){let Y2=G.keys[W1],LU=Y2.serialize??(Y2.child?NZ:a);if(_[W1]=LU(y1),Y2.child===!0){let A6=y1;if(K(A6))H.push(...A6);else H.push(A6)}else if(typeof Y2.child==="function")H.push(...Y2.child(y1))}if(G.finalizeInnerJson)_=G.finalizeInnerJson(_);let $={..._},A={};if(!_1(U))A=O(U,(W1,y1)=>[W1,W1==="examples"?y1:a(y1)]),$.meta=t2(A,"description",!0);_=t2(_,G.collapsibleKey,!1);let R=JSON.stringify({kind:X,..._});$=t2($,G.collapsibleKey,!1);let f=t2($,G.collapsibleKey,!0),F1=JSON.stringify({kind:X,...$});if(Z.nodesByHash[F1]&&!W)return Z.nodesByHash[F1];let hQ={id:Q,kind:X,impl:G,inner:Y,innerEntries:J,innerJson:_,innerHash:R,meta:U,metaJson:A,json:$,hash:F1,collapsibleJson:f,children:H};if(X!=="intersection"){for(let W1 in Y)if(W1!=="in"&&W1!=="out")hQ[W1]=Y[W1]}let HU=new U4[X](hQ,Z);return Z.nodesByHash[F1]=HU},Y4=(Q,X)=>{if(Q.id===X)return Q;if(P(m[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})},IZ=(Q,X,Y)=>{if(Y&&P(m[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.$})},t2=(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:L(YQ(Q.default,X.default)):Q.default:X.hasDefault()?X.default:d;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 i(this.key,()=>this.value.traverseAllows(Q[this.key],X),X);return this.optional};traverseApply=(Q,X)=>{if(this.key in Q)i(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 ${T(Q)} & ${T(X)}`;var EZ=B({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 Z4 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} = ${T(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=jZ(this);defaultValueMorphRef=this.defaultValueMorph&&S(this.defaultValueMorph)}var K2={implementation:EZ,Node:Z4},SZ={},jZ=(Q)=>{if(!Q.hasDefault())return;let X=`{${Q.compiledKey}: ${Q.value.id} = ${a(Q.default)}}`;return SZ[X]??=UQ(Q.key,Q.value,Q.default)},UQ=(Q,X,Y)=>{if(typeof Y==="function")return X.includesTransform?(Z,W)=>{return i(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 i(Q,()=>X(Z[Q]=Y,W),W),Z}:(Z)=>{return Z[Q]=U,Z}},P2=(Q,X,Y)=>{let U=B1(X);if(u(X,"object")&&!U)L(fZ(Y));let Z=Q.in(U?X():X);if(Z instanceof o){if(Y===null)L(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((J)=>({...J,prefixPath:[Y]})));L(`Default for ${W.summary}`)}return X},fZ=(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 e extends M2{constructor(Q,X){super(Q,X);Object.defineProperty(this,p,{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 o)return X;return{value:X}},jsonSchema:{input:(Q)=>this.rawIn.toJsonSchema({target:W4(Q.target),...Q.libraryOptions}),output:(Q)=>this.rawOut.toJsonSchema({target:W4(Q.target),...Q.libraryOptions})}}}as(){return this}brand(Q){if(Q==="")return L(bZ);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=O(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 s(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(m6(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return L(vZ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let X=this.$.parseDefinition(Q);return this.$.schema(X.distribute((Y)=>this.applyStructuralOperation("merge",[G4(Y)??L(J4("merge",Y.expression))])))}applyStructuralOperation(Q,X){return this.distribute((Y)=>{if(Y.equals(F.intrinsic.object)&&Q!=="merge")return Y;let U=G4(Y);if(!U)L(J4(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(V(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=
|
|
25
|
-
${Q}`,J4=(Q,X)=>`${Q} operand must be an object (was ${X})`;var
|
|
26
|
-
Seen: [${
|
|
27
|
-
Resolution: ${T(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(
|
|
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(V(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 xX(X,U.impliedBasis,this);let W=this.$.node("intersection",{[U.kind]:U}),G=Q==="out"?D2(this,W,this.$):s(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(h1,U.kind)}))}hasEqualMorphs(Q){if(!this.includesTransform&&!Q.includesTransform)return!0;if(!$1(this.shallowMorphs,Q.shallowMorphs))return!1;if(!$1(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",s1(Q))}lessThan(Q){return this.constrain("max",s1(Q))}atLeastLength(Q){return this.constrain("minLength",Q)}atMostLength(Q){return this.constrain("maxLength",Q)}moreThanLength(Q){return this.constrain("minLength",s1(Q))}lessThanLength(Q){return this.constrain("maxLength",s1(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",s1(Q))}earlierThan(Q){return this.constrain("before",s1(Q))}}var bZ="Expected a non-empty brand name after #",_4=["draft-2020-12","draft-07"],yZ=(Q)=>`JSONSchema target '${Q}' is not supported (must be ${_4.map((X)=>`"${X}"`).join(" or ")})`,W4=(Q)=>{if(!n(_4,Q))L(yZ(Q));return Q},s1=(Q)=>typeof Q==="object"&&!(Q instanceof Date)?{...Q,exclusive:!0}:{rule:Q,exclusive:!0},N2=(Q,X)=>V(X,"root")?V(Q,"root")?Q.extends(X):X.allows(Q):V(Q,"root")?Q.hasUnit(X):X===Q,G4=(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},vZ=(Q)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
25
|
+
${Q}`,J4=(Q,X)=>`${Q} operand must be an object (was ${X})`;var H1=(Q,X)=>O(o2(Q),(Y,U)=>[U,X]);var kZ=(Q)=>typeof Q==="string"?{reference:Q}:Q,H4=(Q)=>Q instanceof q?F.intrinsic.never.internal:Q,gZ=B({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Q)=>Q.startsWith("$")?Q:`$ark.${Q}`},resolve:{}},normalize:kZ,defaults:{description:(Q)=>Q.reference},intersections:{alias:(Q,X,Y)=>Y.$.lazilyResolve(()=>H4(N(Q.resolution,X.resolution,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.reference}`),...H1("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(()=>H4(N(Q.resolution,X,Y)),`${Q.reference}${Y.pipe?"=>":"&"}${X.id}`)})}});class L4 extends e{expression=this.reference;structure=void 0;get resolution(){let Q=this._resolve();return m[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=m[Q],Y=[];while(V(X,"context")){if(Y.includes(X.id))return L(xZ(X.id,Y));Y.push(X.id),X=m[X.id]}if(!V(X,"root"))return C(`Unexpected resolution for reference ${this.reference}
|
|
26
|
+
Seen: [${Y.join("->")}]
|
|
27
|
+
Resolution: ${T(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(V(X,"root"))return X.id;return C(`Unexpected resolution for reference ${this.reference}: ${T(X)}`)}get defaultShortDescription(){return l.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 xZ=(Q,X)=>`Alias '${Q}' has a shallow resolution cycle: ${[...X,Q].join("->")}`,I2={implementation:gZ,Node:L4};class f1 extends e{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 hZ=B({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Q)=>typeof Q==="string"?{domain:Q}:g1(Q,"numberAllowsNaN")&&Q.domain!=="number"?L(e2.writeBadAllowNanMessage(Q.domain)):Q,applyConfig:(Q,X)=>Q.numberAllowsNaN===void 0&&Q.domain==="number"&&X.numberAllowsNaN?{...Q,numberAllowsNaN:!0}:Q,defaults:{description:(Q)=>l[Q.domain],actual:(Q)=>Number.isNaN(Q)?"NaN":l[b(Q)]},intersections:{domain:(Q,X)=>Q.domain==="number"&&X.domain==="number"?Q.numberAllowsNaN?X:Q:q.init("domain",Q,X)}});class F4 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 l[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:hZ,Node:F4,writeBadAllowNanMessage:(Q)=>`numberAllowsNaN may only be specified with domain "number" (was ${Q})`};var pZ=B({kind:"intersection",hasAssociatedError:!0,normalize:(Q)=>{if(P(Q))return Q;let{structure:X,...Y}=Q,U=!!X,Z=X??{},W=O(Y,(G,J)=>{if(y(G,EX)){if(U)L(`Flattened structure key ${G} cannot be specified alongside a root 'structure' key.`);return Z[G]=J,[]}return[G,J]});if(V(Z,"constraint")||!_1(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:h("divisor")},max:{child:!0,parse:h("max")},min:{child:!0,parse:h("min")},maxLength:{child:!0,parse:h("maxLength")},minLength:{child:!0,parse:h("minLength")},exactLength:{child:!0,parse:h("exactLength")},before:{child:!0,parse:h("before")},after:{child:!0,parse:h("after")},pattern:{child:!0,parse:h("pattern")},predicate:{child:!0,parse:h("predicate")}},reduce:(Q,X)=>q4({},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,
|
|
29
|
+
${Q.expected}`},intersections:{intersection:(Q,X,Y)=>q4(Q.inner,X.inner,Y),...H1("intersection",(Q,X,Y)=>{if(Q.children.length===0)return X;let{domain:U,proto:Z,...W}=Q.inner,G=Z??U,J=G?N(G,X,Y):X;return J instanceof q?J:Q?.basis?.equals(J)?Q:Q.$.node("intersection",{...W,[J.kind]:J},{prereduced:!0})})}});class $4 extends e{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=mZ(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:pZ,Node:$4},mZ=(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"},q4=(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 d1({kind:"intersection",baseInner:U,l:c1(Q),r:c1(X),roots:[],ctx:Y})};var uZ=B({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},morphs:{parse:T1,serialize:(Q)=>Q.map((X)=>V(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 L(lZ(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)},...H1("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 V4 extends e{serializedMorphs=this.morphs.map(S);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=V(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 $1(this.morphs,Q.morphs,{isEqual:(X,Y)=>X===Y||V(X,"root")&&V(Y,"root")&&X.equals(Y)})}}var WQ={implementation:uZ,Node:V4},lZ=(Q,X)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
30
30
|
Left: ${Q}
|
|
31
|
-
Right: ${X}`;var dZ=
|
|
31
|
+
Right: ${X}`;var dZ=B({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Q)=>L2(Q)??a(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")L(E2.writeInvalidSchemaMessage(X.proto));if(g1(X,"dateAllowsInvalid")&&X.proto!==Date)L(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?ZX[Q.builtinName]:`an instance of ${Q.proto.name}`,actual:(Q)=>Q instanceof Date&&Q.toString()==="Invalid Date"?"an invalid Date":H2(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 z4 extends f1{builtinName=L2(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:dZ,Node:z4,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 cZ=B({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Q,X)=>{let Y=[];for(let U of Q){let Z=V(U,"root")?U.branches:X.$.parseSchema(U).branches;for(let W of Z)if(W.hasKind("morph")){let G=Y.findIndex((J)=>J.hasKind("morph")&&J.hasEqualMorphs(W));if(G===-1)Y.push(W);else{let J=Y[G];Y[G]=X.$.node("morph",{...J.inner,in:J.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=X3(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,r1),expected:(Q)=>{let X=nQ(Q.errors,"propString"),Y=Object.entries(X).map(([U,Z])=>{let W=[];for(let H of Z)J1(W,H.expected);let G=r1(W),J=Z.every((H)=>H.actual===Z[0].actual)?Z[0].actual:T(Z[0].data);return`${U&&`${U} `}must be ${G}${J&&` (was ${J})`}`});return r1(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)L(U3(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})},...H1("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 T4 extends e{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?tZ(this.discriminant):null;expression=this.distribute((Q)=>Q.nestableExpression,Q3);createBranchedOptimisticRootApply(){return(Q,X)=>{let Y=this.traverseOptimistic(Q);if(Y!==d)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)=>J1(Q,X.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Q)=>Q.defaultShortDescription,r1)}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&&g1(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 d};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 _ in Y){let $=Y[_],A=_==="default"?_:`case ${_}`,R;if($===!0)R=Z?"data":"true";else if(Z)if($.rootApplyStrategy==="branchedOptimistic")R=Q.invoke($,{kind:"Optimistic"});else if($.contextFreeMorph)R=`${Q.invoke($)} ? ${S($.contextFreeMorph)}(data) : "${d}"`;else R=`${Q.invoke($)} ? data : "${d}"`;else R=Q.invoke($);Q.line(`${A}: return ${R}`)}return Q}),Q.traversalKind==="Allows"){Q.return(Z?`"${d}"`:!1);return}let W=r1(this.discriminant.kind==="domain"?U.map((_)=>{let $=_.slice(1,-1);return $==="function"?l.object:l[$]}):U),G=this.discriminant.path.map((_)=>typeof _==="symbol"?S(_):JSON.stringify(_)),J=JSON.stringify(W),H=this.discriminant.kind==="domain"?`${nZ}[${X}]`:`${aZ}(${X})`;Q.line(`ctx.errorFromNodeContext({
|
|
32
32
|
code: "predicate",
|
|
33
33
|
expected: ${J},
|
|
34
|
-
actual: ${
|
|
34
|
+
actual: ${H},
|
|
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
|
|
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?`"${d}"`:!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=O(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 J=this.branches[G],H=s(W.rawIn,J.rawIn,W.$);if(!(H instanceof q))continue;for(let _ of H){if(!_.kind||_.optional)continue;let $,A;if(_.kind==="domain"){let{l:f,r:F1}=_;$=`"${typeof f==="string"?f:f.domain}"`,A=`"${typeof F1==="string"?F1:F1.domain}"`}else if(_.kind==="unit")$=_.l.serializedValue,A=_.r.serializedValue;else continue;let R=Q.find((f)=>$1(f.path,_.path)&&f.kind===_.kind);if(!R)Q.push({kind:_.kind,cases:{[$]:{branchIndices:[Z],condition:_.l},[A]:{branchIndices:[G],condition:_.r}},path:_.path});else{if(R.cases[$])R.cases[$].branchIndices=J1(R.cases[$].branchIndices,Z);else R.cases[$]??={branchIndices:[Z],condition:_.l};if(R.cases[A])R.cases[A].branchIndices=J1(R.cases[A].branchIndices,G);else R.cases[A]??={branchIndices:[G],condition:_.r}}}}}let X=this.ordered?sZ(Q,this.branches):Q;if(!X.length)return null;let Y=oZ(X,this),U={};for(let Z in Y.best.cases){let W=iZ(Y,Z);if(W===null){U[Z]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((H,_)=>H.originalIndex-_.originalIndex);let G=W.map((H)=>H.branch),J=G.length===1?G[0]:this.$.node("union",this.ordered?{branches:G,ordered:!0}:G);Object.assign(this.referencesById,J.referencesById),U[Z]=J}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 oZ=(Q,X)=>{let U=Q.sort((G,J)=>G.path.length===J.path.length?Object.keys(J.cases).length-Object.keys(G.cases).length:G.path.length-J.path.length)[0],Z={kind:U.kind,path:U.path,optionallyChainedPropString:B4(U.path)},W=X.branches.map((G,J)=>({originalIndex:J,branch:G}));return{best:U,location:Z,defaultEntries:W,node:X}},iZ=(Q,X)=>{let Y=Q.best.cases[X],U=rZ(Y.condition,Q.location.path,Q.node.$),Z=[],W=[];for(let G=0;G<Q.defaultEntries.length;G++){let J=Q.defaultEntries[G];if(Y.branchIndices.includes(J.originalIndex)){let H=A4(Q.node.branches[J.originalIndex],Q.location);if(H===null)Z=null;else Z?.push({originalIndex:J.originalIndex,branch:H})}else if(J.branch.hasKind("alias")&&U.hasKind("domain")&&U.domain==="object")Z?.push(J);else{if(J.branch.rawIn.overlaps(U)){let H=A4(J.branch,Q.location);Z?.push({originalIndex:J.originalIndex,branch:H})}W.push(J)}}return Q.defaultEntries=W,Z},sZ=(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 J=W+1;J<Z.length;J++){let H=Z[J];for(let _ of G)for(let $ of H)if(_>$){if(X[_].overlaps(X[$]))return!1}}}return!0})},rZ=(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},B4=(Q)=>Q.reduce((X,Y)=>X+y6(Y,!0),"data"),nZ=S(aQ),aZ=S(T),JQ={implementation:cZ,Node:T4},tZ=(Q)=>({kind:Q.kind,path:Q.path.map((X)=>typeof X==="string"?X:Y1(X)),cases:O(Q.cases,(X,Y)=>[X,Y===!0?Y:Y.hasKind("union")&&Y.discriminantJson?Y.discriminantJson:Y.json])}),eZ={delimiter:" | ",finalDelimiter:" | "},Q3=(Q)=>r1(Q,eZ),r1=(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((J)=>Z[J]?!1:Z[J]=!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 J=0;J<X.length;J++){if(U[J]===null)continue;if(Q[W].equals(X[J])){U[J]=null,G={};break}let H=N(Q[W],X[J],Y);if(H instanceof q)continue;if(H.equals(Q[W])){U[J].push(Q[W]),G={};break}if(H.equals(X[J]))U[J]=null;else G[J]=H}for(let J in G)U[J][W]=G[J]}let Z=U.flatMap((W,G)=>W?.flatMap((J)=>J.branches)??X[G]);return Z.length===0?q.init("union",Q,X):Z},X3=({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=s(Q[U].rawIn,Q[Z].rawIn,Q[0].$);if(W instanceof q)continue;if(!X)Y3(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])},Y3=(Q,X)=>{if(!Q.includesTransform&&!X.includesTransform)return;if(!$1(Q.shallowMorphs,X.shallowMorphs))L(O4(Q.expression,X.expression));if(!$1(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)}))L(O4(Q.expression,X.expression))},A4=(Q,X)=>Q.transform((Y,U)=>{if(Y==="domain"||Y==="unit")return null;return U},{shouldTransform:(Y,U)=>{let Z=B4(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"}}),O4=(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}`,U3=(Q,X)=>`The intersection of two ordered unions is indeterminate:
|
|
40
40
|
Left: ${Q}
|
|
41
|
-
Right: ${X}`;var Z3=M({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():t(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>T(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 U=X.hasKind("intersection")?X.basis:X;if(U){let Y=U.hasKind("domain")?U:F.intrinsic.object;if(Q.domain!==Y.domain){let Z=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:F.intrinsic[Q.domain];return q.init("domain",Z,Y)}}return q.init("assignability",Q,X.hasKind("intersection")?X.children.find((Y)=>!Y.allows(Q.unit)):X)})}});class D4 extends b1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=V4(this.unit,this.serializedValue);compiledNegation=V4(this.unit,this.serializedValue,"negated");expression=T(this.unit);domain=f(this.unit);get defaultShortDescription(){return this.domain==="object"?l.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 _Q={implementation:Z3,Node:D4},V4=(Q,X,U)=>{if(Q instanceof Date){let Y=`data instanceof Date && data.toISOString() === ${X}`;return U?`!(${Y})`:Y}if(Number.isNaN(Q))return`${U?"!":""}Number.isNaN(data)`;return`data ${U?"!":"="}== ${X}`};var W3=M({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,X)=>{let U=X.$.parseSchema(Q);if(!U.extends(F.intrinsic.key))return H(J3(U.expression));let Y=U.branches.filter((Z)=>Z.hasKind("unit"));if(Y.length)return H(G3(Y.map((Z)=>T(Z.unit))));return U}},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,U)=>{if(Q.signature.equals(X.signature)){let Y=N(Q.value,X.value,U),Z=Y instanceof q?F.intrinsic.never.internal:Y;return U.$.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 R4 extends a{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((U)=>{if(this.signature.traverseAllows(U[0],X))return i(U[0],()=>this.value.traverseAllows(U[1],X),X);return!0});traverseApply=(Q,X)=>{for(let U of N1(Q))if(this.signature.traverseAllows(U[0],X))i(U[0],()=>this.value.traverseApply(U[1],X),X)};_transform(Q,X){X.path.push(this.signature);let U=super._transform(Q,X);return X.path.pop(),U}compile(){}}var LQ={implementation:W3,Node:R4},G3=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,J3=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var _3=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:R2,optional:R2}});class C4 extends C2{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:_3,Node:C4};var L3=M({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((U)=>X.$.parseSchema(U))}},optionals:{child:!0,parse:(Q,X)=>{if(Q.length===0)return;return Q.map((U)=>X.$.parseSchema(U))}},defaultables:{child:(Q)=>Q.map((X)=>X[0]),parse:(Q,X)=>{if(Q.length===0)return;return Q.map((U)=>{let Y=X.$.parseSchema(U[0]);return K2(Y,U[1],null),[Y,U[1]]})},serialize:(Q)=>Q.map((X)=>[X[0].collapsibleJson,t(X[1])]),reduceIo:(Q,X,U)=>{if(Q==="in"){X.optionals=U.map((Y)=>Y[0].rawIn);return}X.prefix=U.map((Y)=>Y[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((U)=>X.$.parseSchema(U))}}},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($3);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 U=Q.minVariadicLength??0,Y=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(Y[Y.length-1]?.equals(Q.variadic))Y.pop(),U++;while(G[0]?.equals(Q.variadic))G.shift(),U++}else if(W.length===0&&Z.length===0)Y.push(...G.splice(0));if(U!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==Y.length)return X.node("sequence",{...Q,prefix:Y,defaultables:Z,optionals:W,postfix:G,minVariadicLength:U},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((U)=>U.kind==="defaultables"?`${U.node.nestableExpression} = ${T(U.default)}`:U.kind==="optionals"?`${U.node.nestableExpression}?`:U.kind==="variadic"?`...${U.node.nestableExpression}[]`:U.node.expression).join(", ")}]`}},intersections:{sequence:(Q,X,U)=>{let Y=E2({l:Q.tuple,r:X.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:U}),Z=Y.disjoint.length===0?[Y,...Y.fixedVariants]:Y.fixedVariants;return Z.length===0?Y.disjoint:Z.length===1?U.$.node("sequence",w4(Z[0].result)):U.$.node("union",Z.map((W)=>({proto:Array,sequence:w4(W.result)})))}}});class P4 extends a{impliedBasis=F.intrinsic.Array.internal;tuple=q3(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((U)=>Z1([`${X}`,...U.path],U.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=F3(this);defaultValueMorphsReference=this.defaultValueMorphs.length?S(this.defaultValueMorphs):void 0;elementAtIndex(Q,X){if(X<this.prevariadic.length)return this.tuple[X];let U=Q.length-this.postfixLength;if(X>=U)return{kind:"postfix",node:this.postfix[X-U]};return{kind:"variadic",node:this.variadic??C(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Q,X)=>{for(let U=0;U<Q.length;U++)if(!this.elementAtIndex(Q,U).node.traverseAllows(Q[U],X))return!1;return!0};traverseApply=(Q,X)=>{let U=0;for(;U<Q.length;U++)i(U,()=>this.elementAtIndex(Q,U).node.traverseApply(Q[U],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix)for(let[X,U]of this.prefix.entries())Q.traverseKey(`${X}`,`data[${X}]`,U);for(let[X,U]of this.defaultablesAndOptionals.entries()){let Y=`${X+this.prefixLength}`;Q.if(`${Y} >= data.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(Y,`data[${Y}]`,U)}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,U]of this.postfix.entries()){let Y=`firstPostfixIndex + ${X}`;Q.traverseKey(Y,`data[${Y}]`,U)}}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,X){X.path.push(F.intrinsic.nonNegativeIntegerString.internal);let U=super._transform(Q,X);return X.path.pop(),U}expression=this.description;reduceJsonSchema(Q,X){let U=X.target==="draft-07";if(this.prevariadic.length){let Y=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(U)Q.items=Y;else Q.prefixItems=Y}if(this.minLength)Q.minItems=this.minLength;if(this.variadic){let Y=this.variadic.toJsonSchemaRecurse(X);if(U&&this.prevariadic.length)Q.additionalItems=Y;else Q.items=Y;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(U)Q.additionalItems=!1;else Q.items=!1;delete Q.maxItems}return Q}}var H3={},F3=(Q)=>{if(!Q.defaultables)return[];let X=[],U="[",Y=Q.prefixLength+Q.defaultablesLength-1;for(let Z=Q.prefixLength;Z<=Y;Z++){let[W,G]=Q.defaultables[Z-Q.prefixLength];X.push(YQ(Z,W,G)),U+=`${Z}: ${W.id} = ${t(G)}, `}return U+="]",H3[U]??=X},FQ={implementation:L3,Node:P4},q3=(Q)=>{let X=[];if(Q.prefix)for(let U of Q.prefix)X.push({kind:"prefix",node:U});if(Q.defaultables)for(let[U,Y]of Q.defaultables)X.push({kind:"defaultables",node:U,default:Y});if(Q.optionals)for(let U of Q.optionals)X.push({kind:"optionals",node:U});if(Q.variadic)X.push({kind:"variadic",node:Q.variadic});if(Q.postfix)for(let U of Q.postfix)X.push({kind:"postfix",node:U});return X},w4=(Q)=>Q.reduce((X,U)=>{if(U.kind==="variadic")X.variadic=U.node;else if(U.kind==="defaultables")X.defaultables=D(X.defaultables,[[U.node,U.default]]);else X[U.kind]=D(X[U.kind],U.node);return X},{}),qQ="A postfix required element cannot follow an optional or defaultable element",$3="A postfix element requires a variadic element",E2=(Q)=>{let[X,...U]=Q.l,[Y,...Z]=Q.r;if(!X||!Y)return Q;let W=U[U.length-1]?.kind==="postfix",G=Z[Z.length-1]?.kind==="postfix",J=X.kind==="prefix"||Y.kind==="prefix"?"prefix":X.kind==="postfix"||Y.kind==="postfix"?"postfix":X.kind==="variadic"&&Y.kind==="variadic"?"variadic":W||G?"prefix":X.kind==="defaultables"||Y.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&Y.kind==="variadic"&&G){let O=E2({...Q,fixedVariants:[],r:Z.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}else if(Y.kind==="prefix"&&X.kind==="variadic"&&W){let O=E2({...Q,fixedVariants:[],l:U.map((R)=>({...R,kind:"prefix"}))});if(O.disjoint.length===0)Q.fixedVariants.push(O)}let L=N(X.node,Y.node,Q.ctx);if(L instanceof q)if(J==="prefix"||J==="postfix")Q.disjoint.push(...L.withPrefixKey(J==="prefix"?Q.result.length:`-${U.length+1}`,K4(X)&&K4(Y)?"required":"optional")),Q.result=[...Q.result,{kind:J,node:F.intrinsic.never.internal}];else if(J==="optionals"||J==="defaultables")return Q;else return E2({...Q,fixedVariants:[],l:U.map((O)=>({...O,kind:"prefix"})),r:U.map((O)=>({...O,kind:"prefix"}))});else if(J==="defaultables"){if(X.kind==="defaultables"&&Y.kind==="defaultables"&&X.default!==Y.default)H(UQ(X.default,Y.default));Q.result=[...Q.result,{kind:J,node:L,default:X.kind==="defaultables"?X.default:Y.kind==="defaultables"?Y.default:C(`Unexpected defaultable intersection from ${X.kind} and ${Y.kind} elements.`)}]}else Q.result=[...Q.result,{kind:J,node:L}];let _=Q.l.length,$=Q.r.length;if(X.kind!=="variadic"||_>=$&&(Y.kind==="variadic"||$===1))Q.l=U;if(Y.kind!=="variadic"||$>=_&&(X.kind==="variadic"||_===1))Q.r=Z;return E2(Q)},K4=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var S4=(Q)=>(X)=>{if(X.props.length||X.index){let U=X.index?.map((Z)=>Z[Q])??[];for(let Z of X.props)U.push(Z[Q]);if(X.undeclared)U.push(`+ (undeclared): ${X.undeclared}`);let Y=`{ ${U.join(", ")} }`;return X.sequence?`${Y} & ${X.sequence.description}`:Y}return X.sequence?.description??"{}"},A3=S4("description"),z3=S4("expression"),N4=(Q,X,U)=>{let Y=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=s(Q.value,X.value,U);if(Z instanceof q)return Y==="optional"?U.node("optional",{key:Q.key,value:F.intrinsic.never.internal}):Z.withPrefixKey(Q.key,Q.kind);return null},O3=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:h("required"),reduceIo:(Q,X,U)=>{X.required=D(X.required,U.map((Y)=>Q==="in"?Y.rawIn:Y.rawOut));return}},optional:{child:!0,parse:h("optional"),reduceIo:(Q,X,U)=>{if(Q==="in"){X.optional=U.map((Y)=>Y.rawIn);return}for(let Y of U)X[Y.outProp.kind]=D(X[Y.outProp.kind],Y.outProp.rawOut)}},index:{child:!0,parse:h("index")},sequence:{child:!0,parse:h("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q,reduceIo:(Q,X,U)=>{if(U==="reject"){X.undeclared="reject";return}if(Q==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:A3},intersections:{structure:(Q,X,U)=>{let Y={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let L=Q.keyof();for(let _ of X.requiredKeys)if(!L.allows(_))W.add("presence",F.intrinsic.never.internal,X.propsByKey[_].value,{path:[_]});if(Z.optional)Z.optional=Z.optional.filter((_)=>L.allows(_.key));if(Z.index)Z.index=Z.index.flatMap((_)=>{if(_.signature.extends(L))return _;let $=s(L,_.signature,U.$);if($ instanceof q)return[];let O=Q6($,_.value,U.$);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 _ of Q.requiredKeys)if(!L.allows(_))W.add("presence",Q.propsByKey[_].value,F.intrinsic.never.internal,{path:[_]});if(Y.optional)Y.optional=Y.optional.filter((_)=>L.allows(_.key));if(Y.index)Y.index=Y.index.flatMap((_)=>{if(_.signature.extends(L))return _;let $=s(L,_.signature,U.$);if($ instanceof q)return[];let O=Q6($,_.value,U.$);if(O.required)Y.required=q1(Y.required,O.required);if(O.optional)Y.optional=q1(Y.optional,O.optional);return O.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let J=d1({kind:"structure",baseInner:G,l:c1(Y),r:c1(Z),roots:[],ctx:U});if(J instanceof q)W.push(...J);if(W.length)return W;return J}},reduce:(Q,X)=>{if(!Q.required&&!Q.optional)return;let U={},Y=!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 U)H(E4(G.key));if(U[G.key]=!0,Q.index)for(let J of Q.index){let L=N4(G,J,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 U)H(E4(G.key));if(U[G.key]=!0,Q.index)for(let J of Q.index){let L=N4(G,J,X);if(L instanceof q)return L;if(L!==null)Z[W]=L,Y=!0}}if(Y)return X.node("structure",{...Q,optional:Z},{prereduced:!0})}});class j4 extends a{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=q1(this.required,this.optional);propsByKey=B(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=z3(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,U)=>{let Y=this.propsByKey[U.key];if(P(U)){if(U.kind!=="required"&&U.kind!=="optional")return H(`Map result must have kind "required" or "optional" (was ${U.kind})`);return X[U.kind]=D(X[U.kind],U),X}let Z=U.kind??Y?.kind??"required",W=B(U,(G,J)=>(G in w2.implementation.keys)?[G,J]:[]);return X[Z]=D(X[Z],this.$.node(Z,W)),X},{}))}assertHasKeys(Q){let X=Q.filter((U)=>!P2(U,this.keyof()));if(X.length)return H(I4(this.expression,X))}get(Q,...X){let U,Y=!1,Z=V3(Q);if((typeof Z==="string"||typeof Z==="symbol")&&this.propsByKey[Z])U=this.propsByKey[Z].value,Y=this.propsByKey[Z].required;if(this.index){for(let G of this.index)if(P2(Z,G.signature))U=U?.and(G.value)??G.value}if(this.sequence&&P2(Z,F.intrinsic.nonNegativeIntegerString))if(A(Z,"root")){if(this.sequence.variadic)U=U?.and(this.sequence.element)??this.sequence.element}else{let G=Number.parseInt(Z);if(G<this.sequence.prevariadic.length){let J=this.sequence.prevariadic[G].node;U=U?.and(J)??J,Y||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let J=this.$.node("union",this.sequence.variadicOrPostfix);U=U?.and(J)??J}}if(!U){if(this.sequence?.variadic&&A(Z,"root")&&Z.extends(F.intrinsic.number))return H(D3(Z.expression,this.sequence.expression));return H(I4(this.expression,[Z]))}let W=U.get(...X);return Y?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((U)=>U.hasKind("required")?this.$.node("optional",U.inner):U)})}require(){let{optional:Q,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((U)=>U.hasKind("optional")?{key:U.key,value:U.value}:U)})}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 U=l2(this.inner),Y=(Z)=>{let W=X.some((G)=>P2(Z,G));return Q==="pick"?W:!W};if(U.required)U.required=U.required.filter((Z)=>Y(Z.key));if(U.optional)U.optional=U.optional.filter((Z)=>Y(Z.key));if(U.index)U.index=U.index.filter((Z)=>Y(Z.signature));return U}traverseAllows=(Q,X)=>this._traverse("Allows",Q,X);traverseApply=(Q,X)=>this._traverse("Apply",Q,X);_traverse=(Q,X,U)=>{let Y=U?.currentErrorCount??0;for(let Z=0;Z<this.props.length;Z++)if(Q==="Allows"){if(!this.props[Z].traverseAllows(X,U))return!1}else if(this.props[Z].traverseApply(X,U),U.failFast&&U.currentErrorCount>Y)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(X,U))return!1}else if(this.sequence.traverseApply(X,U),U.failFast&&U.currentErrorCount>Y)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 J of this.index)if(J.signature.traverseAllows(G,U)){if(Q==="Allows"){if(!i(G,()=>J.value.traverseAllows(X[G],U),U))return!1}else if(i(G,()=>J.value.traverseApply(X[G],U),U),U.failFast&&U.currentErrorCount>Y)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(G)){if(Q==="Allows")return!1;if(U.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[G],meta:this.meta}),U.failFast)return!1}}}if(this.structuralMorph&&U&&!U.hasError())U.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 U of this.index)X.push(Q.invoke(U.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",T3(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(["),M3(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 U=this.sequence?.reduceJsonSchema(Q,X)??Q;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:U,object:this.reduceObjectJsonSchema({type:"object"},X)});return U;default:return I.throwInternalOperandError("structure",Q)}}reduceObjectJsonSchema(Q,X){if(this.props.length){Q.properties={};for(let U of this.props){let Y=U.value.toJsonSchemaRecurse(X);if(typeof U.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Q,key:U.key,value:Y,optional:U.optional});continue}if(U.hasDefault()){let Z=typeof U.default==="function"?U.default():U.default;Y.default=F.intrinsic.jsonData.allows(Z)?Z:X.fallback.defaultValue({code:"defaultValue",base:Y,value:Z})}Q.properties[U.key]=Y}if(this.requiredKeys.length&&Q.properties)Q.required=this.requiredKeys.filter((U)=>typeof U==="string"&&(U in Q.properties))}if(this.index)for(let U of this.index){let Y=U.value.toJsonSchemaRecurse(X);if(U.signature.equals(F.intrinsic.string)){Q.additionalProperties=Y;continue}for(let Z of U.signature.branches){if(!Z.extends(F.intrinsic.string)){Q=X.fallback.symbolKey({code:"symbolKey",base:Q,key:null,value:Y,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 J=Object.assign(W,{pattern:G[0].rule});for(let L=1;L<G.length;L++)W=X.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:G[L].rule});Q.patternProperties??={},Q.patternProperties[J.pattern]=Y}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var $Q={},B3=(Q)=>{let X="";for(let U=0;U<Q.defaultable.length;U++)X+=Q.defaultable[U].defaultValueMorphRef;if(Q.sequence?.defaultValueMorphsReference)X+=Q.sequence?.defaultValueMorphsReference;if(Q.undeclared==="delete"){if(X+="delete !(",Q.required)for(let U of Q.required)X+=U.compiledKey+" | ";if(Q.optional)for(let U of Q.optional)X+=U.compiledKey+" | ";if(Q.index)for(let U of Q.index)X+=U.signature.id+" | ";if(Q.sequence)if(Q.sequence.maxLength===null)X+=z.nonNegativeIntegerString.id;else for(let U=0;U<Q.sequence.tuple.length;U++)X+=U+" | ";X+=")"}return X},T3=(Q)=>{let X=B3(Q);if(!X)return;if($Q[X])return $Q[X];let U=(Y,Z)=>{for(let W=0;W<Q.defaultable.length;W++)if(!(Q.defaultable[W].key in Y))Q.defaultable[W].defaultValueMorph(Y,Z);if(Q.sequence?.defaultables)for(let W=Y.length-Q.sequence.prefixLength;W<Q.sequence.defaultables.length;W++)Q.sequence.defaultValueMorphs[W](Y,Z);if(Q.undeclared==="delete"){for(let W in Y)if(!Q.declaresKey(W))delete Y[W]}return Y};return $Q[X]=U},M3=(Q,X)=>{let Y=`(data${X.defaultable.some((Z)=>Z.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((Z)=>Z.length===2)?", ctx":""})`;return Q.block(`${Y} => `,(Z)=>{for(let W=0;W<X.defaultable.length;W++){let{serializedKey:G,defaultValueMorphRef:J}=X.defaultable[W];Z.if(`!(${G} in data)`,(L)=>L.line(`${J}${Y}`))}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")})},AQ={implementation:O3,Node:j4},V3=(Q)=>{if(A(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},D3=(Q,X)=>`${Q} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,Q6=(Q,X,U)=>{let[Y,Z]=iQ(Q.branches,(G)=>G.hasKind("unit"));if(!Y.length)return{index:U.node("index",{signature:Q,value:X})};let W={};for(let G of Y){let J=U.node("required",{key:G.unit,value:X});W[J.kind]=D(W[J.kind],J)}if(Z.length)W.index=U.node("index",{signature:Z,value:X});return W},R3=(Q)=>A(Q,"root")?Q.expression:T(Q),I4=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map(R3).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,E4=(Q)=>`Duplicate key ${U1(Q)}`;var i1={...tX,alias:N2.implementation,domain:e2.implementation,unit:_Q.implementation,proto:I2.implementation,union:JQ.implementation,morph:WQ.implementation,intersection:ZQ.implementation,divisor:d6.implementation,pattern:a6.implementation,predicate:l6.implementation,required:HQ.implementation,optional:w2.implementation,index:LQ.implementation,sequence:FQ.implementation,structure:AQ.implementation};F.defaultConfig=UX(Object.assign(B(i1,(Q,X)=>[Q,X.defaults]),{jitless:_X(),clone:WX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:I.defaultConfig}));F.resolvedConfig=B2(F.defaultConfig,F.config);var Y4={...aX,alias:N2.Node,domain:e2.Node,unit:_Q.Node,proto:I2.Node,union:JQ.Node,morph:WQ.Node,intersection:ZQ.Node,divisor:d6.Node,pattern:a6.Node,predicate:l6.Node,required:HQ.Node,optional:w2.Node,index:LQ.Node,sequence:FQ.Node,structure:AQ.Node};class n1 extends w6{get[p](){return"module"}}var zQ=(Q,X)=>new n1(B(Q,(U,Y)=>[U,A(Y,"module")?zQ(Y,X):X.bindReference(Y)]));var C3=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,w3=(Q,X)=>H(`Node of kind ${X} is not valid as a ${Q} definition`),b4=(Q)=>`#${Q} duplicates public alias ${Q}`,OQ={};F.ambient??={};var f4,v4="function $",K3=(Q)=>k4(Q,g4(Q)),k4=(Q,X)=>{let U=X.write(v4,4),Y=X.compile()();for(let Z of Q){if(Z.precompilation)continue;if(Z.traverseAllows=Y[`${Z.id}Allows`].bind(Y),Z.isRoot()&&!Z.allowsRequiresContext)Z.allows=Z.traverseAllows;if(Z.traverseApply=Y[`${Z.id}Apply`].bind(Y),Y[`${Z.id}Optimistic`])Z.traverseOptimistic=Y[`${Z.id}Optimistic`].bind(Y);Z.precompilation=U}},g4=(Q)=>new u2().return(Q.reduce((X,U)=>{let Y=new O2({kind:"Allows"}).indent();U.compile(Y);let Z=Y.write(`${U.id}Allows`),W=new O2({kind:"Apply"}).indent();U.compile(W);let G=W.write(`${U.id}Apply`),J=`${X}${Z},
|
|
41
|
+
Right: ${X}`;var Z3=B({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():a(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>T(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),...H1("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 D4 extends f1{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=M4(this.unit,this.serializedValue);compiledNegation=M4(this.unit,this.serializedValue,"negated");expression=T(this.unit);domain=b(this.unit);get defaultShortDescription(){return this.domain==="object"?l.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 _Q={implementation:Z3,Node:D4},M4=(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 W3=B({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(J3(Y.expression));let U=Y.branches.filter((Z)=>Z.hasKind("unit"));if(U.length)return L(G3(U.map((Z)=>T(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 R4 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 i(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))i(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 HQ={implementation:W3,Node:R4},G3=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,J3=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var _3=B({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 C4 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 LQ={implementation:_3,Node:C4};var H3=B({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,a(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($3);if(Q.optionals?.length||Q.defaultables?.length)return L(qQ)}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} = ${T(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",w4(Z[0].result)):Y.$.node("union",Z.map((W)=>({proto:Array,sequence:w4(W.result)})))}}});class P4 extends t{impliedBasis=F.intrinsic.Array.internal;tuple=q3(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=F3(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++)i(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 L3={},F3=(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} = ${a(G)}, `}return Y+="]",L3[Y]??=X},FQ={implementation:H3,Node:P4},q3=(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},w4=(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",$3="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",J=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 A=S2({...Q,fixedVariants:[],r:Z.map((R)=>({...R,kind:"prefix"}))});if(A.disjoint.length===0)Q.fixedVariants.push(A)}else if(U.kind==="prefix"&&X.kind==="variadic"&&W){let A=S2({...Q,fixedVariants:[],l:Y.map((R)=>({...R,kind:"prefix"}))});if(A.disjoint.length===0)Q.fixedVariants.push(A)}let H=N(X.node,U.node,Q.ctx);if(H instanceof q)if(J==="prefix"||J==="postfix")Q.disjoint.push(...H.withPrefixKey(J==="prefix"?Q.result.length:`-${Y.length+1}`,K4(X)&&K4(U)?"required":"optional")),Q.result=[...Q.result,{kind:J,node:F.intrinsic.never.internal}];else if(J==="optionals"||J==="defaultables")return Q;else return S2({...Q,fixedVariants:[],l:Y.map((A)=>({...A,kind:"prefix"})),r:Y.map((A)=>({...A,kind:"prefix"}))});else if(J==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)L(YQ(X.default,U.default));Q.result=[...Q.result,{kind:J,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:J,node:H}];let _=Q.l.length,$=Q.r.length;if(X.kind!=="variadic"||_>=$&&(U.kind==="variadic"||$===1))Q.l=Y;if(U.kind!=="variadic"||$>=_&&(X.kind==="variadic"||_===1))Q.r=Z;return S2(Q)},K4=(Q)=>Q.kind==="prefix"||Q.kind==="postfix";var S4=(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??"{}"},V3=S4("description"),z3=S4("expression"),N4=(Q,X,Y)=>{let U=Q.required?"required":"optional";if(!X.signature.allows(Q.key))return null;let Z=s(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},A3=B({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:h("required"),reduceIo:(Q,X,Y)=>{X.required=D(X.required,Y.map((U)=>Q==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:h("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:h("index")},sequence:{child:!0,parse:h("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:V3},intersections:{structure:(Q,X,Y)=>{let U={...Q.inner},Z={...X.inner},W=new q;if(Q.undeclared){let H=Q.keyof();for(let _ of X.requiredKeys)if(!H.allows(_))W.add("presence",F.intrinsic.never.internal,X.propsByKey[_].value,{path:[_]});if(Z.optional)Z.optional=Z.optional.filter((_)=>H.allows(_.key));if(Z.index)Z.index=Z.index.flatMap((_)=>{if(_.signature.extends(H))return _;let $=s(H,_.signature,Y.$);if($ instanceof q)return[];let A=Q6($,_.value,Y.$);if(A.required)Z.required=q1(Z.required,A.required);if(A.optional)Z.optional=q1(Z.optional,A.optional);return A.index??[]})}if(X.undeclared){let H=X.keyof();for(let _ of Q.requiredKeys)if(!H.allows(_))W.add("presence",Q.propsByKey[_].value,F.intrinsic.never.internal,{path:[_]});if(U.optional)U.optional=U.optional.filter((_)=>H.allows(_.key));if(U.index)U.index=U.index.flatMap((_)=>{if(_.signature.extends(H))return _;let $=s(H,_.signature,Y.$);if($ instanceof q)return[];let A=Q6($,_.value,Y.$);if(A.required)U.required=q1(U.required,A.required);if(A.optional)U.optional=q1(U.optional,A.optional);return A.index??[]})}let G={};if(Q.undeclared||X.undeclared)G.undeclared=Q.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let J=d1({kind:"structure",baseInner:G,l:c1(U),r:c1(Z),roots:[],ctx:Y});if(J instanceof q)W.push(...J);if(W.length)return W;return J}},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(E4(G.key));if(Y[G.key]=!0,Q.index)for(let J of Q.index){let H=N4(G,J,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(E4(G.key));if(Y[G.key]=!0,Q.index)for(let J of Q.index){let H=N4(G,J,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 j4 extends t{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=q1(this.required,this.optional);propsByKey=O(this.props,(Q,X)=>[X.key,X]);propsByKeyReference=S(this.propsByKey);expression=z3(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=O(Y,(G,J)=>(G in K2.implementation.keys)?[G,J]:[]);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(I4(this.expression,X))}get(Q,...X){let Y,U=!1,Z=M3(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(V(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 J=this.sequence.prevariadic[G].node;Y=Y?.and(J)??J,U||=G<this.sequence.prefixLength}else if(this.sequence.variadic){let J=this.$.node("union",this.sequence.variadicOrPostfix);Y=Y?.and(J)??J}}if(!Y){if(this.sequence?.variadic&&V(Z,"root")&&Z.extends(F.intrinsic.number))return L(D3(Z.expression,this.sequence.expression));return L(I4(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 J of this.index)if(J.signature.traverseAllows(G,Y)){if(Q==="Allows"){if(!i(G,()=>J.value.traverseAllows(X[G],Y),Y))return!1}else if(i(G,()=>J.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",T3(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(["),B3(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 J=Object.assign(W,{pattern:G[0].rule});for(let H=1;H<G.length;H++)W=X.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:G[H].rule});Q.patternProperties??={},Q.patternProperties[J.pattern]=U}}}if(this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var $Q={},O3=(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},T3=(Q)=>{let X=O3(Q);if(!X)return;if($Q[X])return $Q[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 $Q[X]=Y},B3=(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:J}=X.defaultable[W];Z.if(`!(${G} in data)`,(H)=>H.line(`${J}${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")})},VQ={implementation:A3,Node:j4},M3=(Q)=>{if(V(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},D3=(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 J=Y.node("required",{key:G.unit,value:X});W[J.kind]=D(W[J.kind],J)}if(Z.length)W.index=Y.node("index",{signature:Z,value:X});return W},R3=(Q)=>V(Q,"root")?Q.expression:T(Q),I4=(Q,X)=>`Key${X.length===1?"":"s"} ${X.map(R3).join(", ")} ${X.length===1?"does":"do"} not exist on ${Q}`,E4=(Q)=>`Duplicate key ${Y1(Q)}`;var i1={...aX,alias:I2.implementation,domain:e2.implementation,unit:_Q.implementation,proto:E2.implementation,union:JQ.implementation,morph:WQ.implementation,intersection:ZQ.implementation,divisor:d6.implementation,pattern:t6.implementation,predicate:l6.implementation,required:LQ.implementation,optional:K2.implementation,index:HQ.implementation,sequence:FQ.implementation,structure:VQ.implementation};F.defaultConfig=YX(Object.assign(O(i1,(Q,X)=>[Q,X.defaults]),{jitless:_X(),clone:WX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:I.defaultConfig}));F.resolvedConfig=T2(F.defaultConfig,F.config);var U4={...tX,alias:I2.Node,domain:e2.Node,unit:_Q.Node,proto:E2.Node,union:JQ.Node,morph:WQ.Node,intersection:ZQ.Node,divisor:d6.Node,pattern:t6.Node,predicate:l6.Node,required:LQ.Node,optional:K2.Node,index:HQ.Node,sequence:FQ.Node,structure:VQ.Node};class n1 extends w6{get[p](){return"module"}}var zQ=(Q,X)=>new n1(O(Q,(Y,U)=>[Y,V(U,"module")?zQ(U,X):X.bindReference(U)]));var C3=(Q)=>K(Q)?Q:("branches"in Q)&&K(Q.branches)?Q.branches:void 0,w3=(Q,X)=>L(`Node of kind ${X} is not valid as a ${Q} definition`),f4=(Q)=>`#${Q} duplicates public alias ${Q}`,AQ={};F.ambient??={};var b4,v4="function $",K3=(Q)=>k4(Q,g4(Q)),k4=(Q,X)=>{let Y=X.write(v4,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}},g4=(Q)=>new u2().return(Q.reduce((X,Y)=>{let U=new O2({kind:"Allows"}).indent();Y.compile(U);let Z=U.write(`${Y.id}Allows`),W=new O2({kind:"Apply"}).indent();Y.compile(W);let G=W.write(`${Y.id}Apply`),J=`${X}${Z},
|
|
42
42
|
${G},
|
|
43
|
-
`;if(!
|
|
43
|
+
`;if(!Y.hasKind("union"))return J;let H=new O2({kind:"Allows",optimistic:!0}).indent();Y.compile(H);let _=H.write(`${Y.id}Optimistic`);return`${J}${_},
|
|
44
44
|
`},`{
|
|
45
|
-
`)+"}");class X6{config;resolvedConfig;name;get[p](){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 U=Object.entries(Q).map((Y)=>this.preparseOwnAliasEntry(...Y));for(let[Y,Z]of U){let W=Y;if(Y[0]==="#"){if(W=Y.slice(1),W in this.aliases)H(b4(W));this.aliases[W]=Z}else{if(W in this.aliases)H(b4(Y));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}}f4??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[f4.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?B(F.intrinsic,(Y,Z)=>Y.startsWith("json")?[]:[Y,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(U,Y)=>new w1(Q,Y?new i2(U):U,X,X,Y??null)};units=(Q,X)=>{let U=[];for(let Z of Q)if(!U.includes(Z))U.push(Z);let Y=U.map((Z)=>this.node("unit",{unit:Z},X));return this.node("union",Y,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,X){let U=this.node("alias",{reference:X??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(U);return U}schema=(Q,X)=>this.finalize(this.parseSchema(Q,X));parseSchema=(Q,X)=>this.node(D2(Q),Q,X);preparseNode(Q,X,U){let Y=typeof Q==="string"?Q:D2(X,Q);if(P(X)&&X.kind===Y)return X;if(Y==="alias"&&!U?.prereduced){let{reference:G}=N2.implementation.normalize(X,this);if(G.startsWith("$")){let J=this.resolveRoot(G.slice(1));X=J,Y=J.kind}}else if(Y==="union"&&u(X,"object")){let G=C3(X);if(G?.length===1)X=G[0],Y=D2(X)}if(P(X)&&X.kind===Y)return X;let W=i1[Y].normalize?.(X,this)??X;if(P(W))return W.kind===Y?W:w3(Y,W.kind);return{...U,$:this,kind:Y,def:W,prefix:U.alias??Y}}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(A(X,"generic"))return;return X}maybeResolveSubalias(Q){return BQ(this.aliases,Q)??BQ(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 Y=m[X];if(A(Y,"root"))return this.resolutions[Q]=Y;if(A(Y,"context")){if(Y.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(Y.phase==="resolved")return C(`Unexpected resolved context for was uncached by its scope: ${T(Y)}`);Y.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(Y.def,Y));return Y.phase="resolved",m[Z.id]=Z,m[Y.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${T(Y)}`)}let U=this.aliases[Q]??this.ambient?.[Q];if(!U)return this.maybeResolveSubalias(Q);if(U=this.normalizeRootScopeValue(U),A(U,"generic"))return this.resolutions[Q]=this.bindReference(U);if(A(U,"module")){if(!U.root)H(p4(Q));return this.resolutions[Q]=this.bindReference(U.root)}return this.resolutions[Q]=this.parse(U,{alias:Q})}createParseContext(Q){let X=Q.id??e6(Q.prefix);return m[X]=Object.assign(Q,{[p]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new Y1(Q,this.resolvedConfig)}import(...Q){return new n1(B(this.export(...Q),(X,U)=>[`#${X}`,U]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let U of this.exportedNames){let Y=this.aliases[U];this._exports[U]=A(Y,"module")?zQ(Y,this):y4(this.maybeResolve(U))}for(let U of this.lazyResolutions)U.resolution;if(this._exportedResolutions=h4(this,this._exports),this._json=x4(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let U=g4(this.references);this.precompilation=U.write(v4,4),k4(this.references,U)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(B(X,(U,Y)=>[Y,this._exports[Y]]))}resolve(Q){return this.export()[Q]}node=(Q,X,U={})=>{let Y=this.preparseNode(Q,X,U);if(P(Y))return this.bindReference(Y);let Z=this.createParseContext(Y),W=QQ(Z),G=this.bindReference(W);return m[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if(A(Q,"root"))return this.bindReference(Q);let U=this.preparseOwnDefinitionFormat(Q,X);if(A(U,"root"))return this.bindReference(U);let Y=this.createParseContext(U);m[Y.id]=Y;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,Y));if(Z.isCyclic)Z=U4(Z,Y.id);return m[Y.id]=Z,Z}finalize(Q){if(y4(Q),!Q.precompilation&&!this.resolvedConfig.jitless)K3(Q.references);return Q}}class TQ extends X6{parseOwnDefinitionFormat(Q,X){return QQ(X)}preparseOwnDefinitionFormat(Q,X){return this.preparseNode(D2(Q),Q,X)}preparseOwnAliasEntry(Q,X){return[Q,X]}normalizeRootScopeValue(Q){return Q}}var y4=(Q)=>{let X=Q.references.filter((U)=>U.hasKind("alias"));for(let U of X){Object.assign(U.referencesById,U.resolution.referencesById);for(let Y of Q.references)if(U.id in Y.referencesById)Object.assign(Y.referencesById,U.referencesById)}return Q},x4=(Q)=>B(Q,(X,U)=>[X,A(U,"root")||A(U,"generic")?U.json:A(U,"module")?x4(U):C(`Unexpected resolution ${T(U)}`)]),BQ=(Q,X)=>{let U=X.indexOf(".");if(U===-1)return;let Y=X.slice(0,U),Z=Q[Y];if(Z===void 0)return;if(!A(Z,"module"))return H(P3(Y));let W=X.slice(U+1),G=Z[W];if(G===void 0)return BQ(Z,W);if(A(G,"root")||A(G,"generic"))return G;if(A(G,"module"))return G.root??H(p4(X));C(`Unexpected resolution for alias '${X}': ${T(G)}`)},U6=(Q,X)=>new TQ(Q,X),S2=new TQ({});var h4=(Q,X)=>{let U={};for(let Y in X){let Z=X[Y];if(A(Z,"module")){let W=h4(Q,Z),G=B(W,(J,L)=>[`${Y}.${J}`,L]);Object.assign(U,G)}else if(A(Z,"root")||A(Z,"generic"))U[Y]=Z;else C(`Unexpected scope resolution ${T(Z)}`)}return U},MQ=(Q)=>`'${Q}' is unresolvable`,P3=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,p4=(Q)=>`Reference to submodule '${Q}' must specify an alias`;S2.export();var{schema:w,node:t1,defineSchema:XL,generic:Q1}=S2;var VQ="^(?:0|[1-9]\\d*)$",N3=new RegExp(VQ),ZL=S(N3);var m4=U6({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={...m4};var u4=U6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:VQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,u4);var I3=U6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),z={...m4,...u4,...I3,emptyStructure:t1("structure",{},{prereduced:!0})};F.intrinsic={...z};var Y6=(Q,X)=>new RegExp(Q,X);Object.assign(Y6,{as:Y6});var d4=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],l4=(Q)=>Q.toString()!=="Invalid Date",c4=(Q)=>Q.slice(2,-1),DQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,o4=(Q,X)=>E3(Q,X),E3=(Q,X)=>{let U=new Date(Q);if(l4(U))return U;let Y=TX(Q);if(Y!==void 0){let Z=new Date(Y);if(l4(Z))return Z}return X?H(X===!0?DQ(Q):X):void 0};var S3=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Z6=(Q,X)=>{let U=Q.scanner.shiftUntilEscapable(b3[r4[X]]);if(Q.scanner.lookahead==="")return Q.error(y3(U,X));if(Q.scanner.shift(),X in s4){let Y;try{Y=new RegExp(U)}catch(Z){H(String(Z))}if(Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:U},{prereduced:!0}),X==="x/")Q.root=Q.ctx.$.node("morph",{in:Q.root,morphs:(Z)=>Y.exec(Z),declaredOut:S3})}else if(y(X,RQ))Q.root=Q.ctx.$.node("unit",{unit:U});else{let Y=o4(U,DQ(U));Q.root=Q.ctx.$.node("unit",{meta:U,unit:Y})}},RQ={"'":1,'"':1},i4={"/":1,"'":1,'"':1},j3={"d'":"'",'d"':'"',"'":"'",'"':'"'},s4={"/":"/","x/":"/"},r4={...j3,...s4},b3={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},f3={'"':"double-quote","'":"single-quote","/":"forward slash"},y3=(Q,X)=>`${X}${Q} requires a closing ${f3[r4[X]]}`;var n4=(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,...V1};var t4=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||y(X.trimStart()[0],H1):Q==="="?X[0]!=="=":Q===","||Q==="?";var a4=(Q,X,U)=>e4(Q,X,U,[]),e4=(Q,X,U,Y)=>{let Z=U.parseUntilFinalizer();if(Y.push(Z.root),Z.finalizer===">"){if(Y.length!==X.params.length)return U.error(CQ(Q,X.names,Y.map((W)=>W.expression)));return Y}if(Z.finalizer===",")return e4(Q,X,U,Y);return Z.error(m2(">"))},CQ=(Q,X,U)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${U.length}${U.length===0?"":`: ${U.join(", ")}`})`;var J6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(H1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=k3(Q,X)},v3=(Q,X,U)=>{if(U.scanner.shiftUntilNonWhitespace(),U.scanner.shift()!=="<")return U.error(CQ(Q,X.names,[]));let Z=a4(Q,X,U);return X(...Z)},k3=(Q,X)=>g3(Q,X)??x3(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?n4(Q.shiftedBy(1).scanner.shiftUntilLookahead(H1)):wQ(Q):MQ(X)),g3=(Q,X)=>{if(Q.ctx.args?.[X]){let Y=Q.ctx.args[X];if(typeof Y!=="string")return Y;return Q.ctx.$.node("alias",{reference:Y},{prereduced:!0})}let U=Q.ctx.$.maybeResolve(X);if(A(U,"root"))return U;if(U===void 0)return;if(A(U,"generic"))return v3(X,U,Q);return H(`Unexpected resolution ${T(U)}`)},x3=(Q,X)=>{let U=MX(X);if(U!==void 0)return Q.ctx.$.node("unit",{unit:U});let Y=DX(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y})},wQ=(Q)=>{let X=Q.previousOperator();return X?KQ(X,Q.scanner.unscanned):h3(Q.scanner.unscanned)},KQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,h3=(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(i4)?Z6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(V1)?PQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in RQ?Z6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):J6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&Z6(Q,"x/"):J6(Q):J6(Q);var QU={">":!0,">=":!0},XU={"<":!0,"<=":!0};var a1={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},UU=(Q,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Q})`,_6=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,YU=(Q,X,U,Y)=>`An expression may have at most one left bound (parsed ${Q}${a1[X]}, ${U}${a1[Y]})`;var WU=(Q,X)=>{let U=p3(Q,X);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,U),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let Y=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(Y,U);return}}return u3(Q,U)},GU={"<":1,">":1,"=":1},p3=(Q,X)=>Q.scanner.lookaheadIs("=")?`${X}${Q.scanner.shift()}`:X;var ZU=(Q,X,U,Y)=>{if(U.extends(F.intrinsic.number)){if(typeof X!=="number")return H(NQ(Q,X,Y));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(U.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return H(NQ(Q,X,Y));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(U.extends(F.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return H(lX(U.expression))},m3=(Q)=>({rule:d4(Q.limit)?c4(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),u3=(Q,X)=>{let U=Q.unsetRoot(),Y=Q.scanner.location;Q.parseOperand();let Z=Q.unsetRoot(),W=Q.scanner.sliceChars(Y,Q.scanner.location);if(Q.root=U,!Z.hasKind("unit")||typeof Z.unit!=="number"&&!(Z.unit instanceof Date))return Q.error(NQ(X,W,"right"));let G=Z.unit,J=X.length===1,L=ZU(X,typeof G==="number"?G:W,U,"right");for(let $ of L)Q.constrainRoot($,X==="=="?{rule:G}:{rule:G,exclusive:J});if(!Q.branches.leftBound)return;if(!y(X,XU))return Q.error(_6(X));let _=ZU(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,U,"left");Q.constrainRoot(_[0],m3(Q.branches.leftBound)),Q.branches.leftBound=null},NQ=(Q,X,U)=>`Comparator ${U==="left"?a1[Q]:Q} must be ${U==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var JU=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1);Q.root=Q.root.brand(X)};var LU=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(H1),U=VX(X,{errorOnFail:_U(X)});if(U===0)Q.error(_U(0));Q.root=Q.root.constrain("divisor",U)},_U=(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(l3):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():t4(X,Q.scanner.unscanned)?Q.finalize(X):y(X,GU)?WU(Q,X):X==="%"?LU(Q):X==="#"?JU(Q):(X in V1)?IQ(Q):Q.error(L6(X))},L6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,l3="Missing expected ']'";var HU=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let U=Q.unsetRoot();if(!U.hasKind("unit"))return Q.error(d3(U.expression));let Y=U.unit instanceof Date?()=>new Date(U.unit):U.unit;return[X,"=",Y]},d3=(Q)=>`Default value '${Q}' must be a literal value`;var EQ=(Q,X)=>{let U=X.$.maybeResolveRoot(Q);if(U)return U;if(Q.endsWith("[]")){let W=X.$.maybeResolveRoot(Q.slice(0,-2));if(W)return W.array()}let Y=new e1(new z2(Q),X),Z=c3(Y);if(Y.finalizer===">")H(L6(">"));return Z},c3=(Q)=>{Q.parseOperand();let X=j2(Q).root;if(!X)return C(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")X=HU(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)H(L6(Q.scanner.lookahead));return X},j2=(Q)=>{while(Q.finalizer===void 0)o3(Q);return Q},o3=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class e1{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(m2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let U=a1[X];if(!y(U,QU))return this.error(_6(X));if(this.branches.leftBound)return this.error(YU(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,U));this.branches.leftBound={comparator:U,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(KX(")",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 j2(new e1(this.scanner,this.ctx))}parseOperator(){return IQ(this)}parseOperand(){return PQ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(UU(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 i3="An empty string is not a valid generic parameter name",H6=(Q,X,U)=>{Q.shiftUntilNonWhitespace();let Y=Q.shiftUntilLookahead(H1);if(Y===""){if(Q.lookahead===""&&X.length)return X;return H(i3)}return Q.shiftUntilNonWhitespace(),s3(Q,Y,X,U)},FU="extends ",s3=(Q,X,U,Y)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(FU))Q.jumpForward(FU.length);else{if(Q.lookahead===",")Q.shift();return U.push(X),H6(Q,U,Y)}let Z=j2(new e1(Q,Y));return U.push([X,Z.root]),H6(Q,U,Y)};class SQ extends c{constructor(Q){let X={$:Q,raw:Q.fn};super((...U)=>{let Y=U.indexOf(":"),Z=Y===-1?U.length-1:Y-1,W=U.slice(0,Z+1),G=Q.parse(W).assertHasKind("intersection"),J=Q.intrinsic.unknown;if(Y!==-1){if(Y!==U.length-2)return H(r3);J=Q.parse(U[Y+1])}return(L)=>new qU(L,G,J)},{attach:X})}}class qU extends c{raw;params;returns;expression;constructor(Q,X,U){let Y=`typed ${Q.name}`,Z={[Y]:(...G)=>{let J=X.assert(G),L=Q(...J);return U.assert(L)}}[Y];super(Z);this.raw=Q,this.params=X,this.returns=U;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}) => ${U?.expression??"unknown"}`}}var r3=`":" must be followed by exactly one return type e.g:
|
|
46
|
-
fn("string", ":", "number")(s => s.length)`;class jQ extends c{$;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 c{$;in;key;branches=[];constructor(Q,X){super((U)=>this.caseEntries(Object.entries(U).map(([Y,Z])=>Y==="default"?[Y,Z]:[this.$.parse(Y),Z])));this.$=Q,this.in=X}at(Q,X){if(this.key)H(t3);if(this.branches.length)H(n3);return this.key=Q,X?this.match(X):this}case(Q,X){return this.caseEntry(this.$.parse(Q),X)}caseEntry(Q,X){let Y=(this.key?this.$.parse({[this.key]:Q}):Q).pipe(X);return this.branches.push(Y),this}match(Q){return this(Q)}strings(Q){return this.caseEntries(Object.entries(Q).map(([X,U])=>X==="default"?[X,U]:[this.$.node("unit",{unit:X}),U]))}caseEntries(Q){for(let X=0;X<Q.length;X++){let[U,Y]=Q[X];if(U==="default"){if(X!==Q.length-1)H("default may only be specified as the last key of a switch definition");return this.default(Y)}if(typeof Y!=="function")return H(`Value for case "${U}" must be a function (was ${f(Y)})`);this.caseEntry(U,Y)}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:$U};let U=this.$.node("union",X);if(!this.in)return this.$.finalize(U);let Y=this.in.pipe(U);if(Q==="never"||Q==="assert")Y=Y.configureReferences({onFail:$U},"self");return this.$.finalize(Y)}}var $U=(Q)=>Q.throw(),n3="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",t3="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)},AU="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",zU="Only required keys may specify default values, e.g. { value: 'number = 0' }";var OU=(Q,X)=>{let U,Y={},Z=N1(Q);for(let[G,J]of Z){let L=Q8(G);if(L.kind==="spread"){if(!_1(Y))return H(e3);let b=X.$.parseOwnDefinitionFormat(J,X);if(b.equals(z.object))continue;if(!b.hasKind("intersection")||!b.basis?.equals(z.object))return H(X8(b.expression));U=b.structure;continue}if(L.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")H(a3(J));Y.undeclared=J;continue}let _=F6(J,X),$=L;if(L.kind==="required"){if(!K(_))bQ(Y,"required",{key:L.normalized,value:_},X);else bQ(Y,"optional",_[1]==="="?{key:L.normalized,value:_[0],default:_[2]}:{key:L.normalized,value:_[0]},X);continue}if(K(_)){if(_[1]==="?")H(AU);if(_[1]==="=")H(zU)}if(L.kind==="optional"){bQ(Y,"optional",{key:L.normalized,value:_},X);continue}let O=X.$.parseOwnDefinitionFormat($.normalized,X),R=Q6(O,_,X.$);if(R.index)Y.index=D(Y.index,R.index);if(R.required)Y.required=D(Y.required,R.required)}let W=X.$.node("structure",Y);return X.$.parseSchema({domain:"object",structure:U?.merge(W)??W})},bQ=(Q,X,U,Y)=>{Q[X]=D(Q[X],Y.$.node(X,U))},a3=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${T(Q)})`,e3="Spread operator may only be used as the first key in an object",Q8=(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},X8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var TU=(Q,X)=>F8(Q)?RU[Q[0]](Q,X):L8(Q)?DU[Q[1]](Q,X):null,U8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),fQ=(Q,X)=>{if(Q[2]===void 0)return H(KQ(Q[1],""));let U=X.$.parseOwnDefinitionFormat(Q[0],X),Y=X.$.parseOwnDefinitionFormat(Q[2],X);if(Q[1]==="|")return X.$.node("union",{branches:[U,Y]});let Z=Q[1]==="&"?s(U,Y,X.$):V2(U,Y,X.$);if(Z instanceof q)return Z.throw();return Z},Y8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),Z8=(Q,X)=>{if(typeof Q[2]!=="function")return H(MU("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},MU=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,W8=(Q,X)=>{if(typeof Q[2]!=="function")return H(MU(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},G8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),VU=(Q)=>Q,J8=VU({"[]":Y8,"?":()=>H(W6)}),_8=VU({"|":fQ,"&":fQ,":":W8,"=>":Z8,"|>":fQ,"@":G8,"=":()=>H(G6)}),DU={...J8,..._8},L8=(Q)=>DU[Q[1]]!==void 0,H8=(Q)=>Q,RU=H8({keyof:U8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return H(BU(_2(Q[1])));let U=Q.slice(1).map((Y)=>typeof Y==="function"?X.$.node("proto",{proto:Y}):H(BU(_2(Y))));return U.length===1?U[0]:X.$.node("union",{branches:U})},"===":(Q,X)=>X.$.units(Q.slice(1))}),F8=(Q)=>RU[Q[0]]!==void 0,BU=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var KU=(Q,X)=>{let U=[{}],Y=0;while(Y<Q.length){let Z=!1;if(Q[Y]==="..."&&Y<Q.length-1)Z=!0,Y++;let W=F6(Q[Y],X),[G,J,L]=!K(W)?[W]:W;if(Y++,Z){if(!G.extends(F.intrinsic.Array))return H(A8(G.expression));U=U.flatMap((_)=>G.distribute(($)=>$8(l2(_),$)))}else U=U.map((_)=>{if(J==="?")return PU(_,G);if(J==="=")return q8(_,G,L);return yQ(_,G)})}return X.$.parseSchema(U.map((Z)=>_1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},yQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return H(Q.variadic?qQ:z8);if(Q.variadic)Q.postfix=D(Q.postfix,X);else Q.prefix=D(Q.prefix,X);return Q},PU=(Q,X)=>{if(Q.variadic)return H(NU);return Q.optionals=D(Q.optionals,X),Q},q8=(Q,X,U)=>{if(Q.variadic)return H(NU);if(Q.optionals)return H(O8);return Q.defaultables=D(Q.defaultables,[[X,U]]),Q},CU=(Q,X)=>{if(Q.postfix)H(wU);if(Q.variadic){if(!Q.variadic.equals(X))H(wU)}else Q.variadic=X.internal;return Q},$8=(Q,X)=>{let U=X.select({method:"find",kind:"sequence"});if(!U)return CU(Q,F.intrinsic.unknown);if(U.prefix)for(let Y of U.prefix)yQ(Q,Y);if(U.optionals)for(let Y of U.optionals)PU(Q,Y);if(U.variadic)CU(Q,U.variadic);if(U.postfix)for(let Y of U.postfix)yQ(Q,Y);return Q},A8=(Q)=>`Spread element must be an array (was ${Q})`,wU="A tuple may have at most one variadic element",z8="A required element may not follow an optional element",NU="An optional element may not follow a variadic element";var O8="A defaultable element may not follow an optional element without a default";var B8={},q6=(Q,X)=>{if(typeof Q==="string"){if(X.args&&Object.keys(X.args).some((Y)=>Q.includes(Y)))return EQ(Q,X);let U=B8[X.$.name]??={};return U[Q]??=EQ(Q,X)}return u(Q,"object")?T8(Q,X):H(vQ(f(Q)))},T8=(Q,X)=>{let U=J2(Q);switch(U){case void 0:if(A(Q,"root"))return Q;if("~standard"in Q)return M8(Q,X);return OU(Q,X);case"Array":return V8(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let Y=M1(Q)?Q():Q;if(A(Y,"root"))return Y;return H(vQ("Function"))}default:return H(vQ(U??T(Q)))}},M8=(Q,X)=>X.$.intrinsic.unknown.pipe((U,Y)=>{let Z=Q["~standard"].validate(U);if(!Z.issues)return Z.value;for(let{message:W,path:G}of Z.issues)if(G)if(G.length)Y.error({problem:qX(W),relativePath:G.map((J)=>typeof J==="object"?J.key:J)});else Y.error({message:W});else Y.error({message:W})}),V8=(Q,X)=>TU(Q,X)??KU(Q,X),vQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class kQ extends c{constructor(Q){let X=Object.assign({errors:o,hkt:x,$: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((...U)=>{if(U.length===1)return Q.parse(U[0]);if(U.length===2&&typeof U[0]==="string"&&U[0][0]==="<"&&U[0][U[0].length-1]===">"){let Y=U[0].slice(1,-1),Z=Q.parseGenericParams(Y,{});return new w1(Z,U[1],Q,Q,null)}return Q.parse(U)},{attach:X})}}var Q2=F;class $6 extends X6{get ambientAttachments(){if(!Q2.typeAttachments)return;return this.cacheGetter("ambientAttachments",B(Q2.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let U=Q.indexOf("<");if(U===-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]!==">")H("'>' must be the last character of a generic declaration in a scope");let Y=Q.slice(0,U),Z=Q.slice(U+1,-1);return[Y,()=>{let W=this.parseGenericParams(Z,{alias:Y});return pX(W,X,this)}]}parseGenericParams(Q,X){return H6(new z2(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 Y=q6(Q,X);if(K(Y)){if(Y[1]==="=")return H(G6);if(Y[1]==="?")return H(W6)}return Y}unit=(Q)=>this.units([Q]);valueOf=(Q)=>this.units(YX(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,U)=>X.and(this.parse(U)),this.intrinsic.unknown);merge=(...Q)=>Q.reduce((X,U)=>X.merge(this.parse(U)),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 $6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var f2=Object.assign($6.scope,{define:(Q)=>Q}),V=$6;class IU extends x{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var D8=Q1(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),IU),EU=V.module({Key:z.key,Merge:D8});class SU extends x{}var R8=Q1("element")((Q)=>{let X=Q.element.exclude(z.Array),U=X.array();return X.rawOr(U).pipe(T1).distribute((Y)=>Y.assertHasKind("morph").declareOut(U),w)},SU),jU=V.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:R8},{name:"Array"});var gQ=w(["string",S1.FileConstructor]),C8=gQ.rawOr(gQ.array()),bU=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:C8}}),fU=V.module({root:["instanceof",FormData],value:gQ,parsed:bU,parse:w({in:FormData,morphs:(Q)=>{let X={};for(let[U,Y]of Q)if(U in X){let Z=X[U];if(typeof Z==="string"||Z instanceof S1.FileConstructor)X[U]=[Z,Y];else Z.push(Y)}else X[U]=Y;return X},declaredOut:bU})},{name:"FormData"});var yU=V.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 w8={Boolean:1,Number:1,String:1},vU=V.module({...B({...K6,...N6},(Q,X)=>(Q in w8)?[]:[Q,["instanceof",X]]),Array:jU,TypedArray:yU,FormData:fU});var K8=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"}),P8=w({domain:"number",divisor:1}),A6=V.module({root:z.number,integer:P8,epoch:K8,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,U)=>{let Y={domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:X}};if(U)Y.meta={format:U};return t1("intersection",Y)},kU=E(H2,"a well-formed integer string"),sU=V.module({root:kU,parse:w({in:kU,morphs:(Q,X)=>{let U=Number.parseInt(Q);return Number.isSafeInteger(U)?U:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:z.integer})},{name:"string.integer"}),N8=E(/^[\dA-Fa-f]+$/,"hex characters only"),I8=V.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"}),gU=E(/^[A-Z].*$/,"capitalized"),E8=V.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:gU}),preformatted:gU},{name:"string.capitalize"}),S8=(Q)=>{let X=Q.replace(/[ -]+/g,""),U=0,Y,Z,W=!1;for(let G=X.length-1;G>=0;G--){if(Y=X.substring(G,G+1),Z=Number.parseInt(Y,10),W)Z*=2,U+=Z>=10?Z%10+1:Z;else U+=Z;W=!W}return!!(U%10===0?X:!1)},j8=/^(?: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}))$/,b8=w({domain:"string",pattern:{meta:"a credit card number",rule:j8.source},predicate:{meta:"a credit card number",predicate:S8}});var f8=/^([+-]?\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 y8=(Q)=>!Number.isNaN(new Date(Q).valueOf()),xU=w({domain:"string",predicate:{meta:"a parsable date",predicate:y8}}).assertHasKind("intersection"),hU=sU.root.internal.narrow((Q,X)=>{let U=Number.parseInt(Q),Y=A6.epoch(U);if(Y instanceof o)return X.errors.merge(Y),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),v8=V.module({root:hU,parse:w({in:hU,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),pU=E(f8,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),k8=V.module({root:pU,parse:w({in:pU,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),g8=V.module({root:xU,parse:w({declaredIn:xU,in:"string",morphs:(Q,X)=>{let U=new Date(Q);if(Number.isNaN(U.valueOf()))return X.error("a parsable date");return U},declaredOut:z.Date}),iso:k8,epoch:v8},{name:"string.date"}),x8=E(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),mU="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",K1=`(${mU}[.]){3}${mU}`,h8=new RegExp(`^${K1}$`),j="(?:[0-9a-fA-F]{1,4})",p8=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,})?$`),m8=V.module({root:["v4 | v6","@","an IP address"],v4:E(h8,"an IPv4 address","ipv4"),v6:E(p8,"an IPv6 address","ipv6")},{name:"string.ip"}),X2="a JSON string",rU=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${X2} (${Q})`},u8=w({meta:X2,domain:"string",predicate:{meta:X2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(U){return X.reject({code:"predicate",expected:X2,problem:rU(U)})}}}}),l8=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:X2,actual:"empty"});try{return JSON.parse(Q)}catch(U){return X.error({code:"predicate",expected:X2,problem:rU(U)})}},d8=V.module({root:u8,parse:w({meta:"safe JSON string parser",in:"string",morphs:l8,declaredOut:z.jsonObject})},{name:"string.json"}),uU=E(/^[a-z]*$/,"only lowercase letters"),c8=V.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:uU}),preformatted:uU},{name:"string.lower"}),nU=["NFC","NFD","NFKC","NFKD"],y2=B(nU,(Q,X)=>[X,w({domain:"string",predicate:(U)=>U.normalize(X)===U,meta:`${X}-normalized unicode`})]),z6=B(nU,(Q,X)=>[X,w({in:"string",morphs:(U)=>U.normalize(X),declaredOut:y2[X]})]),o8=V.module({root:z6.NFC,preformatted:y2.NFC},{name:"string.normalize.NFC"}),i8=V.module({root:z6.NFD,preformatted:y2.NFD},{name:"string.normalize.NFD"}),s8=V.module({root:z6.NFKC,preformatted:y2.NFKC},{name:"string.normalize.NFKC"}),r8=V.module({root:z6.NFKD,preformatted:y2.NFKD},{name:"string.normalize.NFKD"}),n8=V.module({root:"NFC",NFC:o8,NFD:i8,NFKC:s8,NFKD:r8},{name:"string.normalize"}),lU=E(h2,"a well-formed numeric string"),t8=V.module({root:lU,parse:w({in:lU,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),dU="a regex pattern",a8=w({domain:"string",predicate:{meta:dU,predicate:(Q,X)=>{try{return new RegExp(Q),!0}catch(U){return X.reject({code:"predicate",expected:dU,problem:String(U)})}}},meta:{format:"regex"}}),e8=/^(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-]+)*))?$/,Q9=E(e8,"a semantic version (see https://semver.org/)"),cU=E(/^\S.*\S$|^\S?$/,"trimmed"),X9=V.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:cU}),preformatted:cU},{name:"string.trim"}),oU=E(/^[A-Z]*$/,"only uppercase letters"),U9=V.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:oU}),preformatted:oU},{name:"string.upper"}),Y9=(Q)=>URL.canParse(Q),iU=w({domain:"string",predicate:{meta:"a URL string",predicate:Y9},meta:{format:"uri"}}),Z9=V.module({root:iU,parse:w({declaredIn:iU,in:"string",morphs:(Q,X)=>{try{return new URL(Q)}catch{return X.error("a URL string")}},declaredOut:w(URL)})},{name:"string.url"}),W9=V.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"}),tU=V.module({root:z.string,alpha:E(/^[A-Za-z]*$/,"only letters"),alphanumeric:E(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:N8,base64:I8,capitalize:E8,creditCard:b8,date:g8,digits:E(/^\d*$/,"only digits 0-9"),email:x8,integer:sU,ip:m8,json:d8,lower:c8,normalize:n8,numeric:t8,regex:a8,semver:Q9,trim:X9,upper:U9,url:Z9,uuid:W9},{name:"string"});var aU=V.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}),eU=V.module({root:z.unknown,any:z.unknown},{name:"unknown"}),G9=V.module({root:z.jsonObject,stringify:t1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),QY=V.module({root:z.object,json:G9},{name:"object"});class XY extends x{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var J9=Q1(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),XY);class UY extends x{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var _9=Q1(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),UY);class YY extends x{description='omit a set of properties from an object like `Omit(User, "age")`'}var L9=Q1(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),YY);class ZY extends x{description="make all named properties of an object optional like `Partial(User)`"}var H9=Q1(["T",z.object])((Q)=>Q.T.partial(),ZY);class WY extends x{description="make all named properties of an object required like `Required(User)`"}var F9=Q1(["T",z.object])((Q)=>Q.T.required(),WY);class GY extends x{description='exclude branches of a union like `Exclude("boolean", "true")`'}var q9=Q1("T","U")((Q)=>Q.T.exclude(Q.U),GY);class JY extends x{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var $9=Q1("T","U")((Q)=>Q.T.extract(Q.U),JY),_Y=V.module({Exclude:q9,Extract:$9,Omit:L9,Partial:H9,Pick:_9,Record:J9,Required:F9});var B1=f2({...aU,..._Y,...vU,...EU,string:tU,number:A6,object:QY,unknown:eU},{prereducedAliases:!0,name:"ark"}),v=B1.export();Object.assign(Q2.ambient,v);Q2.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(B1.type,Q2.typeAttachments),A9=B1.match,z9=B1.fn,O9=B1.generic,kq=B1.schema,B9=B1.define,T9=B1.declare;var f1=f2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | StringOperatorCondition | HasKeyCondition | NullCondition | EmptyCondition | 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' | 'NOT_CONTAINS'",value:"string | unknown[]"},StringOperatorCondition:{field:"string > 0",operator:"'STARTS_WITH' | 'ENDS_WITH'",value:"string"},HasKeyCondition:{field:"string > 0",operator:"'HAS_KEY'",value:"string"},NullCondition:{field:"string > 0",operator:"'IS_NULL' | 'IS_NONE'","value?":"boolean | null"},EmptyCondition:{field:"string > 0",operator:"'IS_EMPTY'","value?":"boolean | null"},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","if?":"RuleCondition | RuleCondition[]","then?":"Action | ActionGroup","else?":"Action | ActionGroup","break?":"boolean","continue?":"boolean"},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(),Q$=f1.Operator,X$=f1.Condition,U$=f1.ConditionGroup,Y$=f1.RuleCondition,Z$=f1.Action,W$=f1.ActionGroup,M9=f1.TriggerRule;class V9{static validate(Q){let X=M9(Q);if(X instanceof xQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),J=W.message,L=void 0;if(G.endsWith("on")&&(J.includes("string")||J.includes("must be")))if(typeof Q==="object"&&Q!==null&&"on"in Q&&Q.on===!0)J="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:J,suggestion:L,severity:"error"})}return{valid:!1,issues:Z}}let U=X,Y=[];if(this.validateConditionsRecursive(U.if,Y,"if"),Y.length>0)return{valid:!1,issues:Y};return{valid:!0,rule:U}}static validateConditionsRecursive(Q,X,U){if(!Q)return;if(Array.isArray(Q)){Q.forEach((Y,Z)=>{this.validateConditionsRecursive(Y,X,`${U}.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"conditions"in Q&&Array.isArray(Q.conditions)){Q.conditions.forEach((Y,Z)=>{this.validateConditionsRecursive(Y,X,`${U}.conditions.${Z}`)});return}if(typeof Q==="object"&&Q!==null&&"operator"in Q&&"value"in Q)this.validateConditionValue(Q,X,U)}static validateConditionValue(Q,X,U){let{operator:Y,value:Z}=Q;if(typeof Y==="string"&&["IN","NOT_IN","RANGE","CONTAINS","NOT_CONTAINS"].includes(Y)){if(Y==="CONTAINS"){if(typeof Z!=="string"&&!Array.isArray(Z))X.push({path:`${U}.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:`${U}.value`,message:`Incorrect value type: Operator '${Y}' expects a List (Array), but received ${typeof Z}.`,suggestion:Y==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(Y==="RANGE"){if(Z.length!==2)X.push({path:`${U}.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:`${U}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(Y==="MATCHES")if(typeof Z!=="string")X.push({path:`${U}.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:`${U}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(typeof Y==="string"&&["GT","GTE","LT","LTE",">",">=","<","<="].includes(Y)){if(typeof Z!=="number"&&typeof Z!=="string")X.push({path:`${U}.value`,message:`Incorrect value type: Operator '${Y}' expects a number or expression string, but received ${typeof Z}.`,severity:"error"})}else if(typeof Y==="string"&&["STARTS_WITH","ENDS_WITH"].includes(Y)){if(typeof Z!=="string")X.push({path:`${U}.value`,message:`Incorrect value type: Operator '${Y}' expects a string, but received ${typeof Z}.`,severity:"error"})}else if(Y==="HAS_KEY"){if(typeof Z!=="string")X.push({path:`${U}.value`,message:`Incorrect value type: Operator 'HAS_KEY' expects a string (key name), but received ${typeof Z}.`,severity:"error"})}}}export{V9 as TriggerValidator,v2 as TriggerUtils,M9 as TriggerRuleSchema,Z2 as TriggerEngine,g as StateManager,R6 as RuleEngine,Y$ as RuleConditionSchema,V6 as InMemoryPersistence,k as ExpressionEngine,BY as EventQueue,Z2 as Engine,MY as ContextAdapter,X$ as ConditionSchema,U$ as ConditionGroupSchema,Q$ as ComparisonOperatorSchema,dQ as BrowserPersistence,R6 as AdvancedRuleEngine,Z$ as ActionSchema,k1 as ActionRegistry,W$ as ActionGroupSchema};
|
|
45
|
+
`)+"}");class X6{config;resolvedConfig;name;get[p](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Q,X){if(this.config=T2(F.config,X),this.resolvedConfig=T2(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(f4(W));this.aliases[W]=Z}else{if(W in this.aliases)L(f4(U));this.aliases[W]=Z,this.exportedNames.push(W)}if(!V(Z,"module")&&!V(Z,"generic")&&!B1(Z)){let G=this.preparseOwnDefinitionFormat(Z,{alias:W});this.resolutions[W]=V(G,"root")?this.bindReference(G):this.createParseContext(G).id}}b4??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[b4.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?O(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 J=this.resolveRoot(G.slice(1));X=J,U=J.kind}}else if(U==="union"&&u(X,"object")){let G=C3(X);if(G?.length===1)X=G[0],U=R2(X)}if(P(X)&&X.kind===U)return X;let W=i1[U].normalize?.(X,this)??X;if(P(W))return W.kind===U?W:w3(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(BQ(Q))}maybeResolveRoot(Q){let X=this.maybeResolve(Q);if(V(X,"generic"))return;return X}maybeResolveSubalias(Q){return OQ(this.aliases,Q)??OQ(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=m[X];if(V(U,"root"))return this.resolutions[Q]=U;if(V(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: ${T(U)}`);U.phase="resolving";let Z=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",m[Z.id]=Z,m[U.id]=Z,this.resolutions[Q]=Z}return C(`Unexpected nodesById entry for ${X}: ${T(U)}`)}let Y=this.aliases[Q]??this.ambient?.[Q];if(!Y)return this.maybeResolveSubalias(Q);if(Y=this.normalizeRootScopeValue(Y),V(Y,"generic"))return this.resolutions[Q]=this.bindReference(Y);if(V(Y,"module")){if(!Y.root)L(p4(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 m[X]=Object.assign(Q,{[p]:"context",$:this,id:X,phase:"unresolved"})}traversal(Q){return new U1(Q,this.resolvedConfig)}import(...Q){return new n1(O(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]=V(U,"module")?zQ(U,this):y4(this.maybeResolve(Y))}for(let Y of this.lazyResolutions)Y.resolution;if(this._exportedResolutions=h4(this,this._exports),this._json=x4(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Y=g4(this.references);this.precompilation=Y.write(v4,4),k4(this.references,Y)}this.resolved=!0}let X=Q.length?Q:this.exportedNames;return new n1(O(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 m[Z.id]=G};parse=(Q,X={})=>this.finalize(this.parseDefinition(Q,X));parseDefinition(Q,X={}){if(V(Q,"root"))return this.bindReference(Q);let Y=this.preparseOwnDefinitionFormat(Q,X);if(V(Y,"root"))return this.bindReference(Y);let U=this.createParseContext(Y);m[U.id]=U;let Z=this.bindReference(this.parseOwnDefinitionFormat(Q,U));if(Z.isCyclic)Z=Y4(Z,U.id);return m[U.id]=Z,Z}finalize(Q){if(y4(Q),!Q.precompilation&&!this.resolvedConfig.jitless)K3(Q.references);return Q}}class TQ 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 y4=(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},x4=(Q)=>O(Q,(X,Y)=>[X,V(Y,"root")||V(Y,"generic")?Y.json:V(Y,"module")?x4(Y):C(`Unexpected resolution ${T(Y)}`)]),OQ=(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(!V(Z,"module"))return L(P3(U));let W=X.slice(Y+1),G=Z[W];if(G===void 0)return OQ(Z,W);if(V(G,"root")||V(G,"generic"))return G;if(V(G,"module"))return G.root??L(p4(X));C(`Unexpected resolution for alias '${X}': ${T(G)}`)},Y6=(Q,X)=>new TQ(Q,X),j2=new TQ({});var h4=(Q,X)=>{let Y={};for(let U in X){let Z=X[U];if(V(Z,"module")){let W=h4(Q,Z),G=O(W,(J,H)=>[`${U}.${J}`,H]);Object.assign(Y,G)}else if(V(Z,"root")||V(Z,"generic"))Y[U]=Z;else C(`Unexpected scope resolution ${T(Z)}`)}return Y},BQ=(Q)=>`'${Q}' is unresolvable`,P3=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,p4=(Q)=>`Reference to submodule '${Q}' must specify an alias`;j2.export();var{schema:w,node:a1,defineSchema:YH,generic:Q1}=j2;var MQ="^(?:0|[1-9]\\d*)$",N3=new RegExp(MQ),WH=S(N3);var m4=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={...m4};var u4=Y6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:MQ}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,u4);var I3=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={...m4,...u4,...I3,emptyStructure:a1("structure",{},{prereduced:!0})};F.intrinsic={...z};var U6=(Q,X)=>new RegExp(Q,X);Object.assign(U6,{as:U6});var d4=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q[Q.length-1]===Q[1],l4=(Q)=>Q.toString()!=="Invalid Date",c4=(Q)=>Q.slice(2,-1),DQ=(Q)=>`'${Q}' could not be parsed by the Date constructor`,o4=(Q,X)=>E3(Q,X),E3=(Q,X)=>{let Y=new Date(Q);if(l4(Y))return Y;let U=TX(Q);if(U!==void 0){let Z=new Date(U);if(l4(Z))return Z}return X?L(X===!0?DQ(Q):X):void 0};var S3=w({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Z6=(Q,X)=>{let Y=Q.scanner.shiftUntilEscapable(f3[r4[X]]);if(Q.scanner.lookahead==="")return Q.error(y3(Y,X));if(Q.scanner.shift(),X in s4){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:S3})}else if(y(X,RQ))Q.root=Q.ctx.$.node("unit",{unit:Y});else{let U=o4(Y,DQ(Y));Q.root=Q.ctx.$.node("unit",{meta:Y,unit:U})}},RQ={"'":1,'"':1},i4={"/":1,"'":1,'"':1},j3={"d'":"'",'d"':'"',"'":"'",'"':'"'},s4={"/":"/","x/":"/"},r4={...j3,...s4},f3={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},b3={'"':"double-quote","'":"single-quote","/":"forward slash"},y3=(Q,X)=>`${X}${Q} requires a closing ${b3[r4[X]]}`;var n4=(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 L1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...M1};var a4=(Q,X)=>Q===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||y(X.trimStart()[0],L1):Q==="="?X[0]!=="=":Q===","||Q==="?";var t4=(Q,X,Y)=>e4(Q,X,Y,[]),e4=(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 e4(Q,X,Y,U);return Z.error(m2(">"))},CQ=(Q,X,Y)=>`${Q}<${X.join(", ")}> requires exactly ${X.length} args (got ${Y.length}${Y.length===0?"":`: ${Y.join(", ")}`})`;var J6=(Q)=>{let X=Q.scanner.shiftUntilLookahead(L1);if(X==="keyof")Q.addPrefix("keyof");else Q.root=k3(Q,X)},v3=(Q,X,Y)=>{if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.shift()!=="<")return Y.error(CQ(Q,X.names,[]));let Z=t4(Q,X,Y);return X(...Z)},k3=(Q,X)=>g3(Q,X)??x3(Q,X)??Q.error(X===""?Q.scanner.lookahead==="#"?n4(Q.shiftedBy(1).scanner.shiftUntilLookahead(L1)):wQ(Q):BQ(X)),g3=(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(V(Y,"root"))return Y;if(Y===void 0)return;if(V(Y,"generic"))return v3(X,Y,Q);return L(`Unexpected resolution ${T(Y)}`)},x3=(Q,X)=>{let Y=BX(X);if(Y!==void 0)return Q.ctx.$.node("unit",{unit:Y});let U=DX(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):h3(Q.scanner.unscanned)},KQ=(Q,X="")=>`Token '${Q}' requires a right operand${X?` before '${X}'`:""}`,h3=(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(i4)?Z6(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(M1)?PQ(Q.shiftedBy(1)):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in RQ?Z6(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):J6(Q):Q.scanner.lookahead==="x"?Q.scanner.nextLookahead==="/"?Q.shiftedBy(2)&&Z6(Q,"x/"):J6(Q):J6(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})`,_6=(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=p3(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 u3(Q,Y)},GY={"<":1,">":1,"=":1},p3=(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 L(NQ(Q,X,U));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(Y.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return L(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 L(lX(Y.expression))},m3=(Q)=>({rule:d4(Q.limit)?c4(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),u3=(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,J=X.length===1,H=ZY(X,typeof G==="number"?G:W,Y,"right");for(let $ of H)Q.constrainRoot($,X==="=="?{rule:G}:{rule:G,exclusive:J});if(!Q.branches.leftBound)return;if(!y(X,XY))return Q.error(_6(X));let _=ZY(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,Y,"left");Q.constrainRoot(_[0],m3(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 JY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(L1);Q.root=Q.root.brand(X)};var HY=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(L1),Y=MX(X,{errorOnFail:_Y(X)});if(Y===0)Q.error(_Y(0));Q.root=Q.root.constrain("divisor",Y)},_Y=(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(l3):X==="|"?Q.scanner.lookahead===">"?Q.shiftedBy(1).pushRootToBranch("|>"):Q.pushRootToBranch(X):X==="&"?Q.pushRootToBranch(X):X===")"?Q.finalizeGroup():a4(X,Q.scanner.unscanned)?Q.finalize(X):y(X,GY)?WY(Q,X):X==="%"?HY(Q):X==="#"?JY(Q):(X in M1)?IQ(Q):Q.error(H6(X))},H6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,l3="Missing expected ']'";var LY=(Q)=>{let X=Q.unsetRoot();Q.parseOperand();let Y=Q.unsetRoot();if(!Y.hasKind("unit"))return Q.error(d3(Y.expression));let U=Y.unit instanceof Date?()=>new Date(Y.unit):Y.unit;return[X,"=",U]},d3=(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 e1(new A2(Q),X),Z=c3(U);if(U.finalizer===">")L(H6(">"));return Z},c3=(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=LY(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)L(H6(Q.scanner.lookahead));return X},f2=(Q)=>{while(Q.finalizer===void 0)o3(Q);return Q},o3=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class e1{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(m2(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,X){let Y=t1[X];if(!y(Y,QY))return this.error(_6(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(KX(")",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 e1(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 i3="An empty string is not a valid generic parameter name",L6=(Q,X,Y)=>{Q.shiftUntilNonWhitespace();let U=Q.shiftUntilLookahead(L1);if(U===""){if(Q.lookahead===""&&X.length)return X;return L(i3)}return Q.shiftUntilNonWhitespace(),s3(Q,U,X,Y)},FY="extends ",s3=(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),L6(Q,Y,U)}let Z=f2(new e1(Q,U));return Y.push([X,Z.root]),L6(Q,Y,U)};class SQ extends c{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"),J=Q.intrinsic.unknown;if(U!==-1){if(U!==Y.length-2)return L(r3);J=Q.parse(Y[U+1])}return(H)=>new qY(H,G,J)},{attach:X})}}class qY extends c{raw;params;returns;expression;constructor(Q,X,Y){let U=`typed ${Q.name}`,Z={[U]:(...G)=>{let J=X.assert(G),H=Q(...J);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 r3=`":" must be followed by exactly one return type e.g:
|
|
46
|
+
fn("string", ":", "number")(s => s.length)`;class jQ extends c{$;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 c{$;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(a3);if(this.branches.length)L(n3);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 ${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:$Y};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:$Y},"self");return this.$.finalize(U)}}var $Y=(Q)=>Q.throw(),n3="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",a3="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)},VY="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 AY=(Q,X)=>{let Y,U={},Z=N1(Q);for(let[G,J]of Z){let H=Q8(G);if(H.kind==="spread"){if(!_1(U))return L(e3);let f=X.$.parseOwnDefinitionFormat(J,X);if(f.equals(z.object))continue;if(!f.hasKind("intersection")||!f.basis?.equals(z.object))return L(X8(f.expression));Y=f.structure;continue}if(H.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")L(t3(J));U.undeclared=J;continue}let _=F6(J,X),$=H;if(H.kind==="required"){if(!K(_))fQ(U,"required",{key:H.normalized,value:_},X);else fQ(U,"optional",_[1]==="="?{key:H.normalized,value:_[0],default:_[2]}:{key:H.normalized,value:_[0]},X);continue}if(K(_)){if(_[1]==="?")L(VY);if(_[1]==="=")L(zY)}if(H.kind==="optional"){fQ(U,"optional",{key:H.normalized,value:_},X);continue}let A=X.$.parseOwnDefinitionFormat($.normalized,X),R=Q6(A,_,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))},t3=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${T(Q)})`,e3="Spread operator may only be used as the first key in an object",Q8=(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},X8=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var TY=(Q,X)=>F8(Q)?RY[Q[0]](Q,X):H8(Q)?DY[Q[1]](Q,X):null,Y8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[1],X).keyof(),bQ=(Q,X)=>{if(Q[2]===void 0)return L(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]==="&"?s(Y,U,X.$):D2(Y,U,X.$);if(Z instanceof q)return Z.throw();return Z},U8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).array(),Z8=(Q,X)=>{if(typeof Q[2]!=="function")return L(BY("=>",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).pipe(Q[2])},BY=(Q,X)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof X})`,W8=(Q,X)=>{if(typeof Q[2]!=="function")return L(BY(":",Q[2]));return X.$.parseOwnDefinitionFormat(Q[0],X).constrain("predicate",Q[2])},G8=(Q,X)=>X.$.parseOwnDefinitionFormat(Q[0],X).configure(Q[2],Q[3]),MY=(Q)=>Q,J8=MY({"[]":U8,"?":()=>L(W6)}),_8=MY({"|":bQ,"&":bQ,":":W8,"=>":Z8,"|>":bQ,"@":G8,"=":()=>L(G6)}),DY={...J8,..._8},H8=(Q)=>DY[Q[1]]!==void 0,L8=(Q)=>Q,RY=L8({keyof:Y8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return L(OY(H2(Q[1])));let Y=Q.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):L(OY(H2(U))));return Y.length===1?Y[0]:X.$.node("union",{branches:Y})},"===":(Q,X)=>X.$.units(Q.slice(1))}),F8=(Q)=>RY[Q[0]]!==void 0,OY=(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,J,H]=!K(W)?[W]:W;if(U++,Z){if(!G.extends(F.intrinsic.Array))return L(V8(G.expression));Y=Y.flatMap((_)=>G.distribute(($)=>$8(l2(_),$)))}else Y=Y.map((_)=>{if(J==="?")return PY(_,G);if(J==="=")return q8(_,G,H);return yQ(_,G)})}return X.$.parseSchema(Y.map((Z)=>_1(Z)?{proto:Array,exactLength:0}:{proto:Array,sequence:Z}))},yQ=(Q,X)=>{if(Q.defaultables||Q.optionals)return L(Q.variadic?qQ:z8);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 L(NY);return Q.optionals=D(Q.optionals,X),Q},q8=(Q,X,Y)=>{if(Q.variadic)return L(NY);if(Q.optionals)return L(A8);return Q.defaultables=D(Q.defaultables,[[X,Y]]),Q},CY=(Q,X)=>{if(Q.postfix)L(wY);if(Q.variadic){if(!Q.variadic.equals(X))L(wY)}else Q.variadic=X.internal;return Q},$8=(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},V8=(Q)=>`Spread element must be an array (was ${Q})`,wY="A tuple may have at most one variadic element",z8="A required element may not follow an optional element",NY="An optional element may not follow a variadic element";var A8="A defaultable element may not follow an optional element without a default";var O8={},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=O8[X.$.name]??={};return Y[Q]??=EQ(Q,X)}return u(Q,"object")?T8(Q,X):L(vQ(b(Q)))},T8=(Q,X)=>{let Y=_2(Q);switch(Y){case void 0:if(V(Q,"root"))return Q;if("~standard"in Q)return B8(Q,X);return AY(Q,X);case"Array":return M8(Q,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let U=B1(Q)?Q():Q;if(V(U,"root"))return U;return L(vQ("Function"))}default:return L(vQ(Y??T(Q)))}},B8=(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:qX(W),relativePath:G.map((J)=>typeof J==="object"?J.key:J)});else U.error({message:W});else U.error({message:W})}),M8=(Q,X)=>TY(Q,X)??KY(Q,X),vQ=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class kQ extends c{constructor(Q){let X=Object.assign({errors:o,hkt:x,$: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 Q2=F;class $6 extends X6{get ambientAttachments(){if(!Q2.typeAttachments)return;return this.cacheGetter("ambientAttachments",O(Q2.typeAttachments,(Q,X)=>[Q,this.bindReference(X)]))}preparseOwnAliasEntry(Q,X){let Y=Q.indexOf("<");if(Y===-1){if(V(X,"module")||V(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 pX(W,X,this)}]}parseGenericParams(Q,X){return L6(new A2(Q),[],this.createParseContext({...X,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(B1(Q)&&!V(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(UX(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 $6(Q,X);static module=(Q,X={})=>this.scope(Q,X).export()}var y2=Object.assign($6.scope,{define:(Q)=>Q}),M=$6;class IY extends x{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var D8=Q1(["base",z.object],["props",z.object])((Q)=>Q.base.merge(Q.props),IY),EY=M.module({Key:z.key,Merge:D8});class SY extends x{}var R8=Q1("element")((Q)=>{let X=Q.element.exclude(z.Array),Y=X.array();return X.rawOr(Y).pipe(T1).distribute((U)=>U.assertHasKind("morph").declareOut(Y),w)},SY),jY=M.module({root:z.Array,readonly:"root",index:z.nonNegativeIntegerString,liftFrom:R8},{name:"Array"});var gQ=w(["string",S1.FileConstructor]),C8=gQ.rawOr(gQ.array()),fY=w({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:C8}}),bY=M.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=M.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 w8={Boolean:1,Number:1,String:1},vY=M.module({...O({...K6,...N6},(Q,X)=>(Q in w8)?[]:[Q,["instanceof",X]]),Array:jY,TypedArray:yY,FormData:bY});var K8=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"}),P8=w({domain:"number",divisor:1}),V6=M.module({root:z.number,integer:P8,epoch:K8,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 a1("intersection",U)},kY=E(F2,"a well-formed integer string"),sY=M.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"}),N8=E(/^[\dA-Fa-f]+$/,"hex characters only"),I8=M.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"),E8=M.module({root:w({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:gY}),preformatted:gY},{name:"string.capitalize"}),S8=(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)},j8=/^(?: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}))$/,f8=w({domain:"string",pattern:{meta:"a credit card number",rule:j8.source},predicate:{meta:"a credit card number",predicate:S8}});var b8=/^([+-]?\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 y8=(Q)=>!Number.isNaN(new Date(Q).valueOf()),xY=w({domain:"string",predicate:{meta:"a parsable date",predicate:y8}}).assertHasKind("intersection"),hY=sY.root.internal.narrow((Q,X)=>{let Y=Number.parseInt(Q),U=V6.epoch(Y);if(U instanceof o)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),v8=M.module({root:hY,parse:w({in:hY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.epoch"}),pY=E(b8,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),k8=M.module({root:pY,parse:w({in:pY,morphs:(Q)=>new Date(Q),declaredOut:z.Date})},{name:"string.date.iso"}),g8=M.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:k8,epoch:v8},{name:"string.date"}),x8=E(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),mY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",K1=`(${mY}[.]){3}${mY}`,h8=new RegExp(`^${K1}$`),j="(?:[0-9a-fA-F]{1,4})",p8=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,})?$`),m8=M.module({root:["v4 | v6","@","an IP address"],v4:E(h8,"an IPv4 address","ipv4"),v6:E(p8,"an IPv6 address","ipv6")},{name:"string.ip"}),X2="a JSON string",rY=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${X2} (${Q})`},u8=w({meta:X2,domain:"string",predicate:{meta:X2,predicate:(Q,X)=>{try{return JSON.parse(Q),!0}catch(Y){return X.reject({code:"predicate",expected:X2,problem:rY(Y)})}}}}),l8=(Q,X)=>{if(Q.length===0)return X.error({code:"predicate",expected:X2,actual:"empty"});try{return JSON.parse(Q)}catch(Y){return X.error({code:"predicate",expected:X2,problem:rY(Y)})}},d8=M.module({root:u8,parse:w({meta:"safe JSON string parser",in:"string",morphs:l8,declaredOut:z.jsonObject})},{name:"string.json"}),uY=E(/^[a-z]*$/,"only lowercase letters"),c8=M.module({root:w({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:uY}),preformatted:uY},{name:"string.lower"}),nY=["NFC","NFD","NFKC","NFKD"],v2=O(nY,(Q,X)=>[X,w({domain:"string",predicate:(Y)=>Y.normalize(X)===Y,meta:`${X}-normalized unicode`})]),z6=O(nY,(Q,X)=>[X,w({in:"string",morphs:(Y)=>Y.normalize(X),declaredOut:v2[X]})]),o8=M.module({root:z6.NFC,preformatted:v2.NFC},{name:"string.normalize.NFC"}),i8=M.module({root:z6.NFD,preformatted:v2.NFD},{name:"string.normalize.NFD"}),s8=M.module({root:z6.NFKC,preformatted:v2.NFKC},{name:"string.normalize.NFKC"}),r8=M.module({root:z6.NFKD,preformatted:v2.NFKD},{name:"string.normalize.NFKD"}),n8=M.module({root:"NFC",NFC:o8,NFD:i8,NFKC:s8,NFKD:r8},{name:"string.normalize"}),lY=E(h2,"a well-formed numeric string"),a8=M.module({root:lY,parse:w({in:lY,morphs:(Q)=>Number.parseFloat(Q),declaredOut:z.number})},{name:"string.numeric"}),dY="a regex pattern",t8=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"}}),e8=/^(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-]+)*))?$/,Q9=E(e8,"a semantic version (see https://semver.org/)"),cY=E(/^\S.*\S$|^\S?$/,"trimmed"),X9=M.module({root:w({in:"string",morphs:(Q)=>Q.trim(),declaredOut:cY}),preformatted:cY},{name:"string.trim"}),oY=E(/^[A-Z]*$/,"only uppercase letters"),Y9=M.module({root:w({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:oY}),preformatted:oY},{name:"string.upper"}),U9=(Q)=>URL.canParse(Q),iY=w({domain:"string",predicate:{meta:"a URL string",predicate:U9},meta:{format:"uri"}}),Z9=M.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"}),W9=M.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"}),aY=M.module({root:z.string,alpha:E(/^[A-Za-z]*$/,"only letters"),alphanumeric:E(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:N8,base64:I8,capitalize:E8,creditCard:f8,date:g8,digits:E(/^\d*$/,"only digits 0-9"),email:x8,integer:sY,ip:m8,json:d8,lower:c8,normalize:n8,numeric:a8,regex:t8,semver:Q9,trim:X9,upper:Y9,url:Z9,uuid:W9},{name:"string"});var tY=M.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=M.module({root:z.unknown,any:z.unknown},{name:"unknown"}),G9=M.module({root:z.jsonObject,stringify:a1("morph",{in:z.jsonObject,morphs:(Q)=>JSON.stringify(Q),declaredOut:z.string})},{name:"object.json"}),QU=M.module({root:z.object,json:G9},{name:"object"});class XU extends x{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var J9=Q1(["K",z.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),XU);class YU extends x{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var _9=Q1(["T",z.object],["K",z.key])((Q)=>Q.T.pick(Q.K),YU);class UU extends x{description='omit a set of properties from an object like `Omit(User, "age")`'}var H9=Q1(["T",z.object],["K",z.key])((Q)=>Q.T.omit(Q.K),UU);class ZU extends x{description="make all named properties of an object optional like `Partial(User)`"}var L9=Q1(["T",z.object])((Q)=>Q.T.partial(),ZU);class WU extends x{description="make all named properties of an object required like `Required(User)`"}var F9=Q1(["T",z.object])((Q)=>Q.T.required(),WU);class GU extends x{description='exclude branches of a union like `Exclude("boolean", "true")`'}var q9=Q1("T","U")((Q)=>Q.T.exclude(Q.U),GU);class JU extends x{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var $9=Q1("T","U")((Q)=>Q.T.extract(Q.U),JU),_U=M.module({Exclude:q9,Extract:$9,Omit:H9,Partial:L9,Pick:_9,Record:J9,Required:F9});var O1=y2({...tY,..._U,...vY,...EY,string:aY,number:V6,object:QU,unknown:eY},{prereducedAliases:!0,name:"ark"}),v=O1.export();Object.assign(Q2.ambient,v);Q2.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(O1.type,Q2.typeAttachments),V9=O1.match,z9=O1.fn,A9=O1.generic,gq=O1.schema,O9=O1.define,T9=O1.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 | StringOperatorCondition | HasKeyCondition | NullCondition | EmptyCondition | 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' | 'NOT_CONTAINS'",value:"string | unknown[]"},StringOperatorCondition:{field:"string > 0",operator:"'STARTS_WITH' | 'ENDS_WITH'",value:"string"},HasKeyCondition:{field:"string > 0",operator:"'HAS_KEY'",value:"string"},NullCondition:{field:"string > 0",operator:"'IS_NULL' | 'IS_NONE'","value?":"boolean | null"},EmptyCondition:{field:"string > 0",operator:"'IS_EMPTY'","value?":"boolean | null"},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","if?":"RuleCondition | RuleCondition[]","then?":"Action | ActionGroup","else?":"Action | ActionGroup","break?":"boolean","continue?":"boolean"},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(),X$=b1.Operator,Y$=b1.Condition,U$=b1.ConditionGroup,Z$=b1.RuleCondition,W$=b1.Action,G$=b1.ActionGroup,B9=b1.TriggerRule;class M9{static validate(Q){let X=B9(Q);if(X instanceof xQ.errors){let Z=[];for(let W of X){let G=W.path.join("."),J=W.message,H=void 0;if(G.endsWith("on")&&(J.includes("string")||J.includes("must be")))if(typeof Q==="object"&&Q!==null&&"on"in Q&&Q.on===!0)J="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:J,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","NOT_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"})}else if(typeof U==="string"&&["STARTS_WITH","ENDS_WITH"].includes(U)){if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator '${U}' expects a string, but received ${typeof Z}.`,severity:"error"})}else if(U==="HAS_KEY"){if(typeof Z!=="string")X.push({path:`${Y}.value`,message:`Incorrect value type: Operator 'HAS_KEY' expects a string (key name), but received ${typeof Z}.`,severity:"error"})}}}export{M9 as TriggerValidator,U2 as TriggerUtils,B9 as TriggerRuleSchema,W2 as TriggerEngine,g as StateManager,R6 as RuleEngine,Z$ as RuleConditionSchema,M6 as InMemoryPersistence,k as ExpressionEngine,OU as EventQueue,W2 as Engine,BU as ContextAdapter,Y$ as ConditionSchema,U$ as ConditionGroupSchema,X$ as ComparisonOperatorSchema,dQ as BrowserPersistence,R6 as AdvancedRuleEngine,W$ as ActionSchema,k1 as ActionRegistry,G$ as ActionGroupSchema};
|
|
47
47
|
|
|
48
|
-
//# debugId=
|
|
48
|
+
//# debugId=18C98DD1BB21663C64756E2164756E21
|