trigger_system 1.2.0 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/browser/index.browser.js +185 -42
  2. package/dist/browser/index.browser.js.map +116 -17
  3. package/dist/core/action-registry.d.ts +29 -3
  4. package/dist/core/action-registry.d.ts.map +1 -1
  5. package/dist/core/base-engine.d.ts +3 -3
  6. package/dist/core/constants.d.ts +95 -0
  7. package/dist/core/constants.d.ts.map +1 -0
  8. package/dist/core/dependency-graph/analyzer.d.ts +60 -0
  9. package/dist/core/dependency-graph/analyzer.d.ts.map +1 -0
  10. package/dist/core/dependency-graph/builder.d.ts +28 -0
  11. package/dist/core/dependency-graph/builder.d.ts.map +1 -0
  12. package/dist/core/dependency-graph/cycles.d.ts +28 -0
  13. package/dist/core/dependency-graph/cycles.d.ts.map +1 -0
  14. package/dist/core/dependency-graph/index.d.ts +11 -0
  15. package/dist/core/dependency-graph/index.d.ts.map +1 -0
  16. package/dist/core/dependency-graph/types.d.ts +72 -0
  17. package/dist/core/dependency-graph/types.d.ts.map +1 -0
  18. package/dist/core/dependency-graph/utils.d.ts +39 -0
  19. package/dist/core/dependency-graph/utils.d.ts.map +1 -0
  20. package/dist/core/dependency-graph/validator.d.ts +28 -0
  21. package/dist/core/dependency-graph/validator.d.ts.map +1 -0
  22. package/dist/core/dependency-graph.d.ts +64 -13
  23. package/dist/core/dependency-graph.d.ts.map +1 -1
  24. package/dist/core/engine-utils.d.ts +45 -0
  25. package/dist/core/engine-utils.d.ts.map +1 -0
  26. package/dist/core/engine.d.ts +0 -8
  27. package/dist/core/engine.d.ts.map +1 -1
  28. package/dist/core/expression-engine.d.ts +52 -10
  29. package/dist/core/expression-engine.d.ts.map +1 -1
  30. package/dist/core/index.d.ts +2 -4
  31. package/dist/core/index.d.ts.map +1 -1
  32. package/dist/core/operators.d.ts +48 -0
  33. package/dist/core/operators.d.ts.map +1 -0
  34. package/dist/core/persistence-browser.d.ts +25 -2
  35. package/dist/core/persistence-browser.d.ts.map +1 -1
  36. package/dist/core/persistence.node.d.ts +25 -2
  37. package/dist/core/persistence.node.d.ts.map +1 -1
  38. package/dist/core/rule-engine-new.d.ts +2 -1
  39. package/dist/core/rule-engine-new.d.ts.map +1 -1
  40. package/dist/core/rule-engine.d.ts +22 -35
  41. package/dist/core/rule-engine.d.ts.map +1 -1
  42. package/dist/core/trigger-engine.d.ts +18 -25
  43. package/dist/core/trigger-engine.d.ts.map +1 -1
  44. package/dist/domain/validator.d.ts +36043 -5067
  45. package/dist/domain/validator.d.ts.map +1 -1
  46. package/dist/index.browser.d.ts +1 -0
  47. package/dist/index.browser.d.ts.map +1 -1
  48. package/dist/index.d.ts +1 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/io/index.d.ts +6 -1
  51. package/dist/io/index.d.ts.map +1 -1
  52. package/dist/io/loader/index.d.ts +48 -0
  53. package/dist/io/loader/index.d.ts.map +1 -0
  54. package/dist/io/loader/persistence.d.ts +41 -0
  55. package/dist/io/loader/persistence.d.ts.map +1 -0
  56. package/dist/io/loader/query.d.ts +49 -0
  57. package/dist/io/loader/query.d.ts.map +1 -0
  58. package/dist/io/loader/registry.d.ts +91 -0
  59. package/dist/io/loader/registry.d.ts.map +1 -0
  60. package/dist/io/loader/types.d.ts +32 -0
  61. package/dist/io/loader/types.d.ts.map +1 -0
  62. package/dist/io/loader/watch.d.ts +36 -0
  63. package/dist/io/loader/watch.d.ts.map +1 -0
  64. package/dist/io/loader.node.d.ts +1 -13
  65. package/dist/io/loader.node.d.ts.map +1 -1
  66. package/dist/lsp/hover-constants.d.ts +42 -0
  67. package/dist/lsp/hover-constants.d.ts.map +1 -0
  68. package/dist/lsp/server.bundle.d.ts +2 -0
  69. package/dist/lsp/server.bundle.d.ts.map +1 -0
  70. package/dist/node/index.js +183 -170
  71. package/dist/node/index.js.map +116 -91
  72. package/dist/node/node.js +183 -171
  73. package/dist/node/node.js.map +118 -93
  74. package/dist/sdk/builder.d.ts +177 -21
  75. package/dist/sdk/builder.d.ts.map +1 -1
  76. package/dist/sdk/builders/action-builder.d.ts +24 -0
  77. package/dist/sdk/builders/action-builder.d.ts.map +1 -0
  78. package/dist/sdk/builders/condition-builder.d.ts +26 -0
  79. package/dist/sdk/builders/condition-builder.d.ts.map +1 -0
  80. package/dist/sdk/builders/index.d.ts +5 -0
  81. package/dist/sdk/builders/index.d.ts.map +1 -0
  82. package/dist/sdk/builders/params-builder.d.ts +59 -0
  83. package/dist/sdk/builders/params-builder.d.ts.map +1 -0
  84. package/dist/sdk/constants.d.ts +44 -0
  85. package/dist/sdk/constants.d.ts.map +1 -0
  86. package/dist/sdk/exporter.d.ts +16 -0
  87. package/dist/sdk/exporter.d.ts.map +1 -1
  88. package/dist/sdk/graph/action-resolver.d.ts +103 -0
  89. package/dist/sdk/graph/action-resolver.d.ts.map +1 -0
  90. package/dist/sdk/graph/condition-resolver.d.ts +87 -0
  91. package/dist/sdk/graph/condition-resolver.d.ts.map +1 -0
  92. package/dist/sdk/graph/converters.d.ts +152 -0
  93. package/dist/sdk/graph/converters.d.ts.map +1 -0
  94. package/dist/sdk/graph/index.d.ts +12 -0
  95. package/dist/sdk/graph/index.d.ts.map +1 -0
  96. package/dist/sdk/graph/node-filters.d.ts +96 -0
  97. package/dist/sdk/graph/node-filters.d.ts.map +1 -0
  98. package/dist/sdk/graph/traversal.d.ts +105 -0
  99. package/dist/sdk/graph/traversal.d.ts.map +1 -0
  100. package/dist/sdk/graph/types.d.ts +28 -0
  101. package/dist/sdk/graph/types.d.ts.map +1 -0
  102. package/dist/sdk/graph-parser.d.ts +40 -0
  103. package/dist/sdk/graph-parser.d.ts.map +1 -0
  104. package/dist/sdk/index.d.ts +3 -0
  105. package/dist/sdk/index.d.ts.map +1 -1
  106. package/dist/sdk/optimize.d.ts +27 -0
  107. package/dist/sdk/optimize.d.ts.map +1 -0
  108. package/dist/sdk/yaml/converter.d.ts +81 -0
  109. package/dist/sdk/yaml/converter.d.ts.map +1 -0
  110. package/dist/sdk/yaml/index.d.ts +39 -0
  111. package/dist/sdk/yaml/index.d.ts.map +1 -0
  112. package/dist/sdk/yaml/normalizer.d.ts +44 -0
  113. package/dist/sdk/yaml/normalizer.d.ts.map +1 -0
  114. package/dist/sdk/yaml/types.d.ts +198 -0
  115. package/dist/sdk/yaml/types.d.ts.map +1 -0
  116. package/dist/sdk/yaml/utils.d.ts +131 -0
  117. package/dist/sdk/yaml/utils.d.ts.map +1 -0
  118. package/dist/sdk/yaml-parser.d.ts +18 -0
  119. package/dist/sdk/yaml-parser.d.ts.map +1 -0
  120. package/dist/types.d.ts +40 -2
  121. package/dist/types.d.ts.map +1 -1
  122. package/dist/utils/utils.d.ts.map +1 -1
  123. package/package.json +6 -1
@@ -1,48 +1,191 @@
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 H={};return J.headers.forEach((_,$)=>H[$]=_),H})(),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 G=Q;Z=G.mode,Y=G.actions}else Y=[Q];if(Z==="EITHER"&&Y.length>0){let G=Y.reduce((_,$)=>_+($.probability||1),0),J=Math.random()*G,H;for(let _ of Y){let $=_.probability||1;if(J-=$,J<=0){H=_;break}}if(!H&&Y.length>0)H=Y[Y.length-1];if(H)Y=[H];else Y=[]}let W=!1;for(let G of Y){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);U.push(..._)}else if(!H&&G.else){let _=await this.executeRuleActions(G.else,X);U.push(..._)}continue}if("if"in G&&G.if){if(!this.evaluateConditions(G.if,X))continue}if(G.break){W=!0,U.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(G.continue){U.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleAction(G,X);U.push(J)}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)),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 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 G=Q;Z=G.mode,Y=G.actions}else Y=[Q];if(Z==="EITHER"&&Y.length>0){let G=Y.reduce((_,$)=>_+($.probability||1),0),J=Math.random()*G,H;for(let _ of Y){let $=_.probability||1;if(J-=$,J<=0){H=_;break}}if(H)Y=[H]}let W=!1;for(let G of Y){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);U.push(..._)}else if(!H&&G.else){let _=await this.executeRuleActionsWithRegistry(G.else,X);U.push(..._)}continue}if("if"in G&&G.if){if(!this.evaluateConditions(G.if,X))continue}if(G.break){W=!0,U.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(G.continue){U.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleActionWithRegistry(G,X);U.push(J)}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 L=(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 H=Array.isArray(J[0])||J.length===0?J:[J];for(let[_,$]of H)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},H2=(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=H2(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: ${Y}
3
- Source: (${Q.slice(0,-1)}) => {
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=KY(()=>{try{return Function("return false")()}catch{return!0}});var S0=X1("brand");var HX=X1("arkInferred");var f0=X1("args");class x{constructor(){}}var PY=()=>{try{return((Error().stack?.split(`
6
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},NY=globalThis.process?.env??{},LX={fileName:PY,env:NY};var FX=(Q)=>Q[0].toUpperCase()+Q.slice(1),qX=(Q)=>Q[0].toLowerCase()+Q.slice(1),E6=(Q)=>new RegExp(IY(Q),typeof Q==="string"?"":Q.flags);var IY=(Q)=>{return`^(?:${typeof Q==="string"?Q:Q.source})$`};var A1={negativeLookahead:(Q)=>`(?!${Q})`,nonCapturingGroup:(Q)=>`(?:${Q})`},E1="\\",V1={" ":1,"\n":1,"\t":1};var EY=/^-0\.?0*$/.source,AX=/[1-9]\d*/.source,SY=/\.\d+/.source,jY=/\.\d*[1-9]/.source,zX=(Q)=>E6(A1.negativeLookahead(EY)+A1.nonCapturingGroup("-?"+A1.nonCapturingGroup(A1.nonCapturingGroup("0|"+AX)+A1.nonCapturingGroup(Q.decimalPattern)+"?")+(Q.allowDecimalOnly?"|"+Q.decimalPattern:"")+"?")),$X=zX({decimalPattern:jY,allowDecimalOnly:!1}),bY=$X.test.bind($X),h2=zX({decimalPattern:SY,allowDecimalOnly:!0}),p0=h2.test.bind(h2),fY=/^-?\d*\.?\d*$/,yY=(Q)=>Q.length!==0&&fY.test(Q),L2=E6(A1.negativeLookahead("^-0$")+"-?"+A1.nonCapturingGroup(A1.nonCapturingGroup("0|"+AX))),vY=L2.test.bind(L2),S6=/^-?\d+$/,kY=S6.test.bind(S6),OX={number:"a number",bigint:"a bigint",integer:"an integer"},BX=(Q,X)=>`'${Q}' was parsed as ${OX[X]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,gY=(Q,X)=>X==="number"?bY(Q):vY(Q),xY=(Q,X)=>X==="number"?Number(Q):Number.parseInt(Q),hY=(Q,X)=>X==="number"?yY(Q):kY(Q),TX=(Q,X)=>j6(Q,"number",X),MX=(Q,X)=>j6(Q,"number",{...X,strict:!0}),VX=(Q,X)=>j6(Q,"integer",X),j6=(Q,X,U)=>{let Y=xY(Q,X);if(!Number.isNaN(Y)){if(hY(Q,X)){if(U?.strict)return gY(Q,X)?Y:L(BX(Q,X));return Y}}return U?.errorOnFail?L(U?.errorOnFail===!0?`Failed to parse ${OX[X]} from '${Q}'`:U?.errorOnFail):void 0},DX=(Q)=>{if(Q[Q.length-1]!=="n")return;let X=Q.slice(0,-1),U;try{U=BigInt(X)}catch{return}if(L2.test(X))return U;if(S6.test(X))return L(BX(Q,"bigint"))};var pY="0.56.0",mY={version:pY,filename:LX.fileName(),FileConstructor:P6},S1=mY,RX=new Map,b6=Object.create(null),F2=(Q)=>{let X=RX.get(Q);if(X)return X;let U=uY(Q);if(b6[U])U=`${U}${b6[U]++}`;else b6[U]=1;return S1[U]=Q,RX.set(Q,U),U},D1=(Q)=>/^[$A-Z_a-z][\w$]*$/.test(Q),uY=(Q)=>{switch(typeof Q){case"object":{if(Q===null)break;let X=J2(Q)??"object";return X[0].toLowerCase()+X.slice(1)}case"function":return D1(Q.name)?Q.name:"fn";case"symbol":return Q.description&&D1(Q.description)?Q.description:"symbol"}return C(`Unexpected attempt to register serializable value of type ${f(Q)}`)};var q2=(Q)=>typeof Q==="string"?JSON.stringify(Q):typeof Q==="bigint"?`${Q}n`:`${Q}`;var CX=(Q,X={})=>$2(Q,{onUndefined:"$ark.undefined",onBigInt:(U)=>`$ark.bigint-${U}`,...X},[]);var T=(Q,X)=>{switch(f(Q)){case"object":let U=Q,Y=U.constructor?.name??"Object";return Y==="Object"||Y==="Array"?X?.quoteKeys===!1?p2(U,X?.indent??0,""):JSON.stringify($2(U,x1,[]),null,X?.indent):p2(U,X?.indent??0,"");case"symbol":return x1.onSymbol(Q);default:return q2(Q)}},p2=(Q,X,U)=>{if(typeof Q==="function")return x1.onFunction(Q);if(typeof Q!=="object"||Q===null)return q2(Q);let Y=U+" ".repeat(X);if(Array.isArray(Q)){if(Q.length===0)return"[]";let W=Q.map((G)=>p2(G,X,Y)).join(`,
7
- `+Y);return X?`[
8
- ${Y}${W}
9
- ${U}]`:`[${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,Y);return`${Y}${H}: ${_}`});if(W.length===0)return"{}";return X?`{
10
- ${W.join(`,
1
+ var{defineProperty:K8,getOwnPropertyNames:Y$,getOwnPropertyDescriptor:G$}=Object,_$=Object.prototype.hasOwnProperty;function L$(Z){return this[Z]}var K7=(Z)=>{var X=(O7??=new WeakMap).get(Z),Q;if(X)return X;if(X=K8({},"__esModule",{value:!0}),Z&&typeof Z==="object"||typeof Z==="function"){for(var U of Y$(Z))if(!_$.call(X,U))K8(X,U,{get:L$.bind(Z,U),enumerable:!(Q=G$(Z,U))||Q.enumerable})}return O7.set(Z,X),X},O7;var V$=(Z)=>Z;function q$(Z,X){this[Z]=V$.bind(null,X)}var f6=(Z,X)=>{for(var Q in X)K8(Z,Q,{get:X[Q],enumerable:!0,configurable:!0,set:q$.bind(X,Q)})};var R=(Z,X)=>()=>(Z&&(X=Z(Z=0)),X);var H$=((Z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Z,{get:(X,Q)=>(typeof require<"u"?require:X)[Q]}):Z)(function(Z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')});var i1=(Z)=>Array.isArray(Z)?Z:[Z],T7=(Z,X)=>{let Q=[[],[]];for(let U of Z)if(X(U))Q[0].push(U);else Q[1].push(U);return Q},y6,c0=(Z,X)=>Z.includes(X),D7=(Z,X=0)=>[...Array(Z)].map((Q,U)=>U+X),u=(Z,X,Q)=>{if(Z===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(Q?.prepend)if(Array.isArray(X))Z.unshift(...X);else Z.unshift(X);else if(Array.isArray(X))Z.push(...X);else Z.push(X);return Z},I1=(Z,X)=>{if(X===void 0||X===null)return Z??[];if(Z===void 0||Z===null)return i1(X);return Z.concat(X)},P7=(...Z)=>Z.reduce(I1,[]),M1=(Z,X,Q)=>{if(Z===void 0)return Array.isArray(X)?X:[X];let U=Q?.isEqual??((J,$)=>J===$);for(let J of i1(X))if(!Z.some(($)=>U($,J)))Z.push(J);return Z},w7=(Z,X)=>Z.reduce((Q,U)=>{let J=U[X];return Q[J]=u(Q[J],U),Q},{}),f1=(Z,X,Q)=>Z.length===X.length&&Z.every(Q?.isEqual?(U,J)=>Q.isEqual(U,X[J]):(U,J)=>U===X[J]);var k6=R(()=>{y6=Array});var E0=(Z,X)=>q0(Z)===X,q0=(Z)=>{let X=typeof Z;return X==="object"?Z===null?"null":"object":X==="function"?"object":X},b0,A7;var C2=R(()=>{b0={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},A7={...b0,function:"a function"}});var S7,d=(Z)=>F2(Z,S7),F2=(Z,X=Error)=>{throw new X(Z)},T4,M=(Z)=>F2(Z,T4),$1=(Z)=>` ${Z}`,C7="​";var R1=R(()=>{S7=class S7 extends Error{};T4=class T4 extends Error{name="ParseError"}});var y=(Z,X)=>{let Q={},U=Array.isArray(Z),J=!1;for(let[$,W]of Object.entries(Z).entries()){let Y=U?X($,W[1]):X(...W,$);J||=typeof Y[0]==="number";let G=Array.isArray(Y[0])||Y.length===0?Y:[Y];for(let[_,L]of G)if(typeof _==="object")Q[_.group]=u(Q[_.group],L);else Q[_]=L}return J?Object.values(Q):Q};var T8=R(()=>{k6()});class P8{constructor(Z){Object.assign(this,Z)}}var D8,H0=(Z,X)=>(Z in X),N2=(Z,X)=>(X in Z),N7=class{},D4,z$=(Z,X)=>{let Q={},U={},J;for(J in Z)if(J in X)Q[J]=Z[J];else U[J]=Z[J];return[Q,U]},g6=(Z,X)=>z$(Z,X)[1],O1=(Z)=>Object.keys(Z).length===0,B2=(Z)=>[...Object.entries(Z),...Object.getOwnPropertySymbols(Z).map((X)=>[X,Z[X]])],j7=(Z,X)=>Object.defineProperties(Z,Object.getOwnPropertyDescriptors(X)),E7=(Z)=>{let X=Object.keys(Z).sort(),Q={};for(let U=0;U<X.length;U++)Q[X[U]]=Z[X[U]];return Q},I0,b7=(Z)=>Object.values(Z).filter((X)=>{if(typeof X==="number")return!0;return typeof Z[X]!=="number"});var j2=R(()=>{R1();T8();D8=Object.entries;D4=class D4 extends N7{};I0=$1(`unset${C7}`)});var w8,A8,S8,F$,M2,P4=(Z)=>{let X=Object.getPrototypeOf(Z);while(X?.constructor&&(!H0(X.constructor.name,M2)||!(Z instanceof M2[X.constructor.name])))X=Object.getPrototypeOf(X);let Q=X?.constructor?.name;if(Q===void 0||Q==="Object")return;return Q},w4=(Z)=>typeof Z==="object"&&Z!==null?P4(Z)??"object":q0(Z),t,B$,M$,R$,I7,A4=(Z)=>{let X=Object(Z).name??null;return X&&H0(X,M2)&&M2[X]===Z?X:null},C8=(Z,X)=>{let Q=Z.prototype;while(Q!==null){if(Q===X.prototype)return!0;Q=Object.getPrototypeOf(Q)}return!1};var S4=R(()=>{C2();j2();w8={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},A8=globalThis.File??Blob,S8={ArrayBuffer,Blob,File:A8,FormData,Headers,Request,Response,URL},F$={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},M2={...w8,...S8,...F$,String,Number,Boolean},t=Array.isArray,B$={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"},M$={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"},R$={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"},I7={...B$,...M$,...R$}});var f7=(Z)=>y7(Z,new Map),y7=(Z,X)=>{if(typeof Z!=="object"||Z===null)return Z;if(X?.has(Z))return X.get(Z);let Q=A4(Z.constructor);if(Q==="Date")return new Date(Z.getTime());if(Q&&Q!=="Array")return Z;let U=Array.isArray(Z)?Z.slice():Object.create(Object.getPrototypeOf(Z)),J=Object.getOwnPropertyDescriptors(Z);if(X){X.set(Z,U);for(let $ in J){let W=J[$];if("get"in W||"set"in W)continue;W.value=y7(W.value,X)}}return Object.defineProperties(U,J),U};var k7=R(()=>{S4()});var g7=()=>{};class f0{constructor(Z,...[X]){return Object.assign(Object.setPrototypeOf(Z.bind(X?.bind??this),this.constructor.prototype),X?.attach)}}var O$=(Z)=>{let X=I0;return()=>X===I0?X=Z():X},s1=(Z)=>typeof Z==="function"&&Z.length===0,v7,x7;var h7=R(()=>{R1();j2();v7=class extends Function{constructor(...Z){let X=Z.slice(0,-1),Q=Z[Z.length-1];try{super(...X,Q)}catch(U){return d(`Encountered an unexpected error while compiling your definition:
2
+ Message: ${U}
3
+ Source: (${Z.slice(0,-1)}) => {
4
+ ${Z[Z.length-1]}
5
+ }`)}}};x7=O$(()=>{try{return Function("return false")()}catch{return!0}})});var nL,m7;var u7=R(()=>{R1();nL=$1("brand"),m7=$1("arkInferred")});class R0{constructor(){}}var ZV;var p7=R(()=>{R1();ZV=$1("args")});var l7=()=>{};var K$=()=>{try{return((Error().stack?.split(`
6
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},T$,d7;var N8=R(()=>{T$=globalThis.process?.env??{},d7={fileName:K$,env:T$}});var c7=()=>{};var i7=(Z)=>Z[0].toUpperCase()+Z.slice(1),s7=(Z)=>Z[0].toLowerCase()+Z.slice(1),j8=(Z)=>new RegExp(D$(Z),typeof Z==="string"?"":Z.flags),D$=(Z)=>{return`^(?:${typeof Z==="string"?Z:Z.source})$`},k1,R2="\\",r1;var v6=R(()=>{k1={negativeLookahead:(Z)=>`(?!${Z})`,nonCapturingGroup:(Z)=>`(?:${Z})`},r1={" ":1,"\n":1,"\t":1}});var P$,o7,w$,A$,a7=(Z)=>j8(k1.negativeLookahead(P$)+k1.nonCapturingGroup("-?"+k1.nonCapturingGroup(k1.nonCapturingGroup("0|"+o7)+k1.nonCapturingGroup(Z.decimalPattern)+"?")+(Z.allowDecimalOnly?"|"+Z.decimalPattern:"")+"?")),r7,S$,x6,YV,C$,N$=(Z)=>Z.length!==0&&C$.test(Z),C4,j$,E8,E$,n7,t7=(Z,X)=>`'${Z}' was parsed as ${n7[X]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,b$=(Z,X)=>X==="number"?S$(Z):j$(Z),I$=(Z,X)=>X==="number"?Number(Z):Number.parseInt(Z),f$=(Z,X)=>X==="number"?N$(Z):E$(Z),e7=(Z,X)=>b8(Z,"number",X),Z3=(Z,X)=>b8(Z,"number",{...X,strict:!0}),X3=(Z,X)=>b8(Z,"integer",X),b8=(Z,X,Q)=>{let U=I$(Z,X);if(!Number.isNaN(U)){if(f$(Z,X)){if(Q?.strict)return b$(Z,X)?U:M(t7(Z,X));return U}}return Q?.errorOnFail?M(Q?.errorOnFail===!0?`Failed to parse ${n7[X]} from '${Z}'`:Q?.errorOnFail):void 0},Q3=(Z)=>{if(Z[Z.length-1]!=="n")return;let X=Z.slice(0,-1),Q;try{Q=BigInt(X)}catch{return}if(C4.test(X))return Q;if(E8.test(X))return M(t7(Z,"bigint"))};var U3=R(()=>{R1();v6();P$=/^-0\.?0*$/.source,o7=/[1-9]\d*/.source,w$=/\.\d+/.source,A$=/\.\d*[1-9]/.source,r7=a7({decimalPattern:A$,allowDecimalOnly:!1}),S$=r7.test.bind(r7),x6=a7({decimalPattern:w$,allowDecimalOnly:!0}),YV=x6.test.bind(x6),C$=/^-?\d*\.?\d*$/,C4=j8(k1.negativeLookahead("^-0$")+"-?"+k1.nonCapturingGroup(k1.nonCapturingGroup("0|"+o7))),j$=C4.test.bind(C4),E8=/^-?\d+$/,E$=E8.test.bind(E8),n7={number:"a number",bigint:"a bigint",integer:"an integer"}});var y$="0.56.0",k$,O2,J3,I8,N4=(Z)=>{let X=J3.get(Z);if(X)return X;let Q=g$(Z);if(I8[Q])Q=`${Q}${I8[Q]++}`;else I8[Q]=1;return O2[Q]=Z,J3.set(Z,Q),Q},o1=(Z)=>/^[$A-Z_a-z][\w$]*$/.test(Z),g$=(Z)=>{switch(typeof Z){case"object":{if(Z===null)break;let X=P4(Z)??"object";return X[0].toLowerCase()+X.slice(1)}case"function":return o1(Z.name)?Z.name:"fn";case"symbol":return Z.description&&o1(Z.description)?Z.description:"symbol"}return d(`Unexpected attempt to register serializable value of type ${q0(Z)}`)};var h6=R(()=>{C2();R1();N8();S4();k$={version:y$,filename:d7.fileName(),FileConstructor:A8},O2=k$,J3=new Map,I8=Object.create(null)});var j4=(Z)=>typeof Z==="string"?JSON.stringify(Z):typeof Z==="bigint"?`${Z}n`:`${Z}`;var $3=(Z,X={})=>E4(Z,{onUndefined:"$ark.undefined",onBigInt:(Q)=>`$ark.bigint-${Q}`,...X},[]),k=(Z,X)=>{switch(q0(Z)){case"object":let Q=Z,U=Q.constructor?.name??"Object";return U==="Object"||U==="Array"?X?.quoteKeys===!1?m6(Q,X?.indent??0,""):JSON.stringify(E4(Q,E2,[]),null,X?.indent):m6(Q,X?.indent??0,"");case"symbol":return E2.onSymbol(Z);default:return j4(Z)}},m6=(Z,X,Q)=>{if(typeof Z==="function")return E2.onFunction(Z);if(typeof Z!=="object"||Z===null)return j4(Z);let U=Q+" ".repeat(X);if(Array.isArray(Z)){if(Z.length===0)return"[]";let $=Z.map((W)=>m6(W,X,U)).join(`,
7
+ `+U);return X?`[
8
+ ${U}${$}
9
+ ${Q}]`:`[${$}]`}let J=Z.constructor?.name??"Object";if(J==="Object"){let $=B2(Z).map(([W,Y])=>{let G=typeof W==="symbol"?E2.onSymbol(W):o1(W)?W:JSON.stringify(W),_=m6(Y,X,U);return`${U}${G}: ${_}`});if($.length===0)return"{}";return X?`{
10
+ ${$.join(`,
11
11
  `)}
12
- ${U}}`:`{${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(${F2(Q)})`,onFunction:(Q)=>`Function(${F2(Q)})`},$2=(Q,X,U)=>{switch(f(Q)){case"object":{let Y=Q;if("toJSON"in Y&&typeof Y.toJSON==="function")return Y.toJSON();if(typeof Y==="function")return x1.onFunction(Y);if(U.includes(Y))return"(cycle)";let Z=[...U,Y];if(Array.isArray(Y))return Y.map((G)=>$2(G,X,Z));if(Y instanceof Date)return Y.toDateString();let W={};for(let G in Y)W[G]=$2(Y[G],X,Z);for(let G of Object.getOwnPropertySymbols(Y))W[X.onSymbol?.(G)??G.toString()]=$2(Y[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(),U=Q.getMonth(),Y=Q.getDate(),Z=Q.getHours(),W=Q.getMinutes(),G=Q.getSeconds(),J=Q.getMilliseconds();if(U===0&&Y===1&&Z===0&&W===0&&G===0&&J===0)return`${X}`;let H=`${lY[U]} ${Y}, ${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)_+=`.${cY(J,3)}`;else if(dY.test(_))_=_.slice(0,-3);return`${_+$}, ${H}`},lY=["January","February","March","April","May","June","July","August","September","October","November","December"],dY=/:\d\d:00$/,cY=(Q,X)=>String(Q).padStart(X,"0");var wX=(Q,X,...[U])=>{let Y=U?.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}[${Y(X)}]`;break;default:if(U?.stringifyNonKey)Z=`${Q}[${U.stringifyNonKey(X)}]`;else L(`${T(X)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return Z},z1=(Q,...X)=>Q.reduce((U,Y)=>wX(U,Y,...X),"");class A2 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 U of this)Q=wX(Q,U),X.push(Q);return this.cache.stringifyAncestors=X}}class z2{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 V1))}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 FW=X1("implementedTraits");var f6="$ark",oY=2;while(f6 in globalThis)f6=`$ark${oY++}`;var PX=f6;globalThis[PX]=S1;var F=S1,iY=(Q)=>`${PX}.${Q}`,S=(Q)=>iY(F2(Q));class u2 extends G2{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,U=0){return this.block(`for (let i = ${U}; ${Q}; i++)`,X)}forIn(Q,X){return this.block(`for (const k in ${Q})`,X)}block(Q,X,U=""){return this.line(`${Q} {`),this.indent(),X(this),this.dedent(),this.line(`}${U}`)}return(Q=""){return this.line(`return ${Q}`)}write(Q="anonymous",X=0){return`${Q}(${this.argNames.join(", ")}) { ${X?this.body.split(`
14
- `).map((U)=>" ".repeat(X)+`${U}`).join(`
15
- `):this.body} }`}compile(){return new JX(...this.argNames,this.body)}}var U1=(Q)=>u(Q,"object")||typeof Q==="symbol"?S(Q):q2(Q),y6=(Q,X=!1)=>{if(typeof Q==="string"&&D1(Q))return`${X?"?":""}.${Q}`;return NX(sY(Q),X)},sY=(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 U=X?.arg??this.data,Y=typeof Q==="string"?!0:this.requiresContextFor(Q),Z=typeof Q==="string"?Q:Q.id;if(Y)return`${this.referenceToId(Z,X)}(${U}, ${this.ctx})`;return`${this.referenceToId(Z,X)}(${U})`}referenceToId(Q,X){let U=X?.kind??this.traversalKind,Y=`this.${Q}${U}`;return X?.bind?`${Y}.bind(${X?.bind})`:Y}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,U){let Y=this.requiresContextFor(U);if(Y)this.line(`${this.ctx}.path.push(${Q})`);if(this.check(U,{arg:X}),Y)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)=>B(Q,(X,U)=>[X,K(U)?[...U]:U]),p=X1("arkKind"),A=(Q,X)=>Q?.[p]===X,P=(Q)=>A(Q,"root")||A(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"],rY=[...p1,...d2],c2=B(d2,(Q,X)=>[X,1]),EX=B([...h1,"undeclared"],(Q,X)=>[X,1]),SX=B(rY,(Q,X)=>[X,Q]),m1=(Q)=>typeof Q==="string"&&(Q in SX);var u1=(Q)=>SX[Q],o2=(Q)=>p1.slice(u1(Q)+1),sW=[...o2("union"),"alias"],rW=[...o2("morph"),"alias"],t=(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 U1(Q)},R1=(Q)=>{let X="{ ";for(let[U,Y]of Object.entries(Q))X+=`${U}: ${U1(Y)}, `;return X+" }"},M=(Q)=>{let X=Q;if(X.hasAssociatedError)X.defaults.expected??=(U)=>("description"in U)?U.description:X.defaults.description(U),X.defaults.actual??=(U)=>T(U),X.defaults.problem??=(U)=>`must be ${U.expected}${U.actual?` (was ${U.actual})`:""}`,X.defaults.message??=(U)=>{if(U.path.length===0)return U.problem;let Y=`${U.propString} ${U.problem}`;if(Y[0]==="[")return`value at ${Y}`;return Y};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 nY={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:nY};F.config??={};var B2=(Q,X)=>{if(!X)return Q;let U={...Q},Y;for(Y in X){let Z={...Q.keywords};if(Y==="keywords"){for(let W in X[Y]){let G=X.keywords[W];if(G===void 0)continue;Z[W]=typeof G==="string"?{description:G}:G}U.keywords=Z}else if(Y==="toJsonSchema")U[Y]=g6(Q.toJsonSchema,X.toJsonSchema);else if(m1(Y))U[Y]={...Q[Y],...X[Y]};else U[Y]=X[Y]}return U},tY={"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 bX(X??{},void 0);if(!X)return Q;let U={...Q},Y;for(Y in X)if(Y==="fallback")U.fallback=aY(Q.fallback,X.fallback);else U[Y]=X[Y];return bX(U,X)},bX=(Q,X)=>{if(X?.dialect!==void 0)return Q;if(X?.target!==void 0)return{...Q,dialect:tY[X.target]};return Q},aY=(Q,X)=>{Q=fX(Q),X=fX(X);let U={},Y;for(Y in I.defaultConfig.fallback)U[Y]=X[Y]??X.default??Q[Y]??Q.default??I.defaultConfig.fallback[Y];return U},fX=(Q)=>typeof Q==="function"?{default:Q}:Q??{};class C1 extends G2{[p]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Q,relativePath:X,...U},Y){super();this.input=U,this.ctx=Y,XX(this,U);let Z=Y.data;if(U.code==="union")U.errors=U.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=Y.config[this.code];let W=[...U.path??Y.path];if(X)W.push(...X);if(Q)W.unshift(...Q);this.path=new A2(...W),this.data="data"in U?U.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 B(this.byPath,(Q,X)=>[Q,X.flat])}get flatProblemsByPath(){return B(this.byPath,(Q,X)=>[Q,X.flat.map((U)=>U.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 U=Q.hasCode("union")&&Q.errors.length===0?Q:new C1({code:"intersection",errors:X.hasCode("intersection")?[...X.errors,Q]:[X,Q]},this.ctx),Y=this.indexOf(X);this.mutable[Y===-1?this.length:Y]=U,this.byPath[Q.propString]=U,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 U of this)X.add(Q(U));return X}merge(Q){for(let X of Q)this.add(new C1({...X,path:[...this.ctx.path,...X.path]},this.ctx))}affectsPath(Q){if(this.length===0)return!1;return Q.stringifyAncestors().some((X)=>(X in this.byPath))||Q.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Q)=>Q.toJSON())]}toString(){return this.join(`
16
- `)}addAncestorPaths(Q){for(let X of Q.path.stringifyAncestors())this.byAncestorPath[X]=D(this.byAncestorPath[X],Q)}}class x6 extends Error{name="TraversalError";constructor(Q){if(Q.length===1)super(Q.summary);else super(`
17
- `+Q.map((X)=>` • ${eY(X)}`).join(`
18
- `));Object.defineProperty(this,"arkErrors",{value:Q,enumerable:!1})}}var eY=(Q)=>Q.toString().split(`
12
+ ${Q}}`:`{${$.join(", ")}}`}if(Z instanceof Date)return K2(Z);if("expression"in Z&&typeof Z.expression==="string")return Z.expression;return J},E2,E4=(Z,X,Q)=>{switch(q0(Z)){case"object":{let U=Z;if("toJSON"in U&&typeof U.toJSON==="function")return U.toJSON();if(typeof U==="function")return E2.onFunction(U);if(Q.includes(U))return"(cycle)";let J=[...Q,U];if(Array.isArray(U))return U.map((W)=>E4(W,X,J));if(U instanceof Date)return U.toDateString();let $={};for(let W in U)$[W]=E4(U[W],X,J);for(let W of Object.getOwnPropertySymbols(U))$[X.onSymbol?.(W)??W.toString()]=E4(U[W],X,J);return $}case"symbol":return E2.onSymbol(Z);case"bigint":return X.onBigInt?.(Z)??`${Z}n`;case"undefined":return X.onUndefined??"undefined";case"string":return Z.replace(/\\/g,"\\\\");default:return Z}},K2=(Z)=>{let X=Z.getFullYear(),Q=Z.getMonth(),U=Z.getDate(),J=Z.getHours(),$=Z.getMinutes(),W=Z.getSeconds(),Y=Z.getMilliseconds();if(Q===0&&U===1&&J===0&&$===0&&W===0&&Y===0)return`${X}`;let G=`${v$[Q]} ${U}, ${X}`;if(J===0&&$===0&&W===0&&Y===0)return G;let _=Z.toLocaleTimeString(),L=_.endsWith(" AM")||_.endsWith(" PM")?_.slice(-3):"";if(L)_=_.slice(0,-L.length);if(Y)_+=`.${h$(Y,3)}`;else if(x$.test(_))_=_.slice(0,-3);return`${_+L}, ${G}`},v$,x$,h$=(Z,X)=>String(Z).padStart(X,"0");var f8=R(()=>{C2();j2();h6();E2={onCycle:()=>"(cycle)",onSymbol:(Z)=>`Symbol(${N4(Z)})`,onFunction:(Z)=>`Function(${N4(Z)})`},v$=["January","February","March","April","May","June","July","August","September","October","November","December"],x$=/:\d\d:00$/});var W3=(Z,X,...[Q])=>{let U=Q?.stringifySymbol??k,J=Z;switch(typeof X){case"string":J=o1(X)?Z===""?X:`${Z}.${X}`:`${Z}[${JSON.stringify(X)}]`;break;case"number":J=`${Z}[${X}]`;break;case"symbol":J=`${Z}[${U(X)}]`;break;default:if(Q?.stringifyNonKey)J=`${Z}[${Q.stringifyNonKey(X)}]`;else M(`${k(X)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},g1=(Z,...X)=>Z.reduce((Q,U)=>W3(Q,U,...X),""),b4;var Y3=R(()=>{k6();R1();h6();f8();b4=class b4 extends y6{cache={};constructor(...Z){super();this.push(...Z)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Z=0;Z<this.length;Z++)this.cache.json.push(typeof this[Z]==="symbol"?k(this[Z]):this[Z]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=g1(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Z="",X=[Z];for(let Q of this)Z=W3(Z,Q),X.push(Z);return this.cache.stringifyAncestors=X}}});class I4{chars;i;def;constructor(Z){this.def=Z,this.chars=[...Z],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(Z){let X="";while(this.lookahead)if(Z(this,X))break;else X+=this.shift();return X}shiftUntilEscapable(Z){let X="";while(this.lookahead)if(this.lookahead===R2)if(this.shift(),Z(this,X))X+=this.shift();else if(this.lookahead===R2)X+=this.shift();else X+=`${R2}${this.shift()}`;else if(Z(this,X))break;else X+=this.shift();return X}shiftUntilLookahead(Z){return typeof Z==="string"?this.shiftUntil((X)=>X.lookahead===Z):this.shiftUntil((X)=>(X.lookahead in Z))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in r1))}jumpToIndex(Z){this.i=Z<0?this.length+Z:Z}jumpForward(Z){this.i+=Z}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(Z,X){return this.chars.slice(Z,X).join("")}lookaheadIs(Z){return this.lookahead===Z}lookaheadIsIn(Z){return this.lookahead in Z}}var G3=(Z,X)=>`Unmatched ${Z}${X===""?"":` before ${X}`}`,u6=(Z)=>`Missing ${Z}`;var _3=R(()=>{v6()});var IV;var L3=R(()=>{C2();R1();S4();j2();IV=$1("implementedTraits")});var V3=()=>{};var j=R(()=>{k6();k7();g7();C2();R1();T8();h7();u7();p7();l7();N8();c7();U3();S4();Y3();j2();h6();_3();f8();v6();L3();V3()});var y8="$ark",m$=2,q3,O,u$=(Z)=>`${q3}.${Z}`,U0=(Z)=>u$(N4(Z));var c=R(()=>{j();while(y8 in globalThis)y8=`$ark${m$++}`;q3=y8;globalThis[q3]=O2;O=O2});var p6,W1=(Z)=>E0(Z,"object")||typeof Z==="symbol"?U0(Z):j4(Z),k8=(Z,X=!1)=>{if(typeof Z==="string"&&o1(Z))return`${X?"?":""}.${Z}`;return H3(p$(Z),X)},p$=(Z)=>typeof Z==="symbol"?U0(Z):JSON.stringify(Z),H3=(Z,X=!1)=>`${X?"?.":""}[${Z}]`,f4;var a1=R(()=>{j();c();p6=class p6 extends D4{argNames;body="";constructor(...Z){super();this.argNames=Z;for(let X of Z){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(Z,X=!1){return k8(Z,X)}index(Z,X=!1){return H3(`${Z}`,X)}line(Z){return this.body+=`${" ".repeat(this.indentation)}${Z}
13
+ `,this}const(Z,X){return this.line(`const ${Z} = ${X}`),this}let(Z,X){return this.line(`let ${Z} = ${X}`)}set(Z,X){return this.line(`${Z} = ${X}`)}if(Z,X){return this.block(`if (${Z})`,X)}elseIf(Z,X){return this.block(`else if (${Z})`,X)}else(Z){return this.block("else",Z)}for(Z,X,Q=0){return this.block(`for (let i = ${Q}; ${Z}; i++)`,X)}forIn(Z,X){return this.block(`for (const k in ${Z})`,X)}block(Z,X,Q=""){return this.line(`${Z} {`),this.indent(),X(this),this.dedent(),this.line(`}${Q}`)}return(Z=""){return this.line(`return ${Z}`)}write(Z="anonymous",X=0){return`${Z}(${this.argNames.join(", ")}) { ${X?this.body.split(`
14
+ `).map((Q)=>" ".repeat(X)+`${Q}`).join(`
15
+ `):this.body} }`}compile(){return new v7(...this.argNames,this.body)}};f4=class f4 extends p6{traversalKind;optimistic;constructor(Z){super("data","ctx");this.traversalKind=Z.kind,this.optimistic=Z.optimistic===!0}invoke(Z,X){let Q=X?.arg??this.data,U=typeof Z==="string"?!0:this.requiresContextFor(Z),J=typeof Z==="string"?Z:Z.id;if(U)return`${this.referenceToId(J,X)}(${Q}, ${this.ctx})`;return`${this.referenceToId(J,X)}(${Q})`}referenceToId(Z,X){let Q=X?.kind??this.traversalKind,U=`this.${Z}${Q}`;return X?.bind?`${U}.bind(${X?.bind})`:U}requiresContextFor(Z){return this.traversalKind==="Apply"||Z.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(Z,X,Q){let U=this.requiresContextFor(Q);if(U)this.line(`${this.ctx}.path.push(${Z})`);if(this.check(Q,{arg:X}),U)this.line(`${this.ctx}.path.pop()`);return this}check(Z,X){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Z,X)}`,()=>this.return(!1)):this.line(this.invoke(Z,X))}}});var l6=(Z)=>y(Z,(X,Q)=>[X,t(Q)?[...Q]:Q]),w0,E=(Z,X)=>Z?.[w0]===X,e=(Z)=>E(Z,"root")||E(Z,"constraint");var _0=R(()=>{j();w0=$1("arkKind")});var z3,b2,g8,v8,d6,I2,l$,c6,F3,B3,f2=(Z)=>typeof Z==="string"&&(Z in B3),y2=(Z)=>B3[Z],i6=(Z)=>I2.slice(y2(Z)+1),Fq,Bq,i0=(Z)=>{if(typeof Z==="string"||typeof Z==="boolean"||Z===null)return Z;if(typeof Z==="number"){if(Number.isNaN(Z))return"NaN";if(Z===Number.POSITIVE_INFINITY)return"Infinity";if(Z===Number.NEGATIVE_INFINITY)return"-Infinity";return Z}return W1(Z)},n1=(Z)=>{let X="{ ";for(let[Q,U]of Object.entries(Z))X+=`${Q}: ${W1(U)}, `;return X+" }"},g=(Z)=>{let X=Z;if(X.hasAssociatedError)X.defaults.expected??=(Q)=>("description"in Q)?Q.description:X.defaults.description(Q),X.defaults.actual??=(Q)=>k(Q),X.defaults.problem??=(Q)=>`must be ${Q.expected}${Q.actual?` (was ${Q.actual})`:""}`,X.defaults.message??=(Q)=>{if(Q.path.length===0)return Q.problem;let U=`${Q.propString} ${Q.problem}`;if(U[0]==="[")return`value at ${U}`;return U};return X};var i=R(()=>{j();a1();_0();z3=["unit","proto","domain"],b2=["required","optional","index","sequence"],g8=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],v8=[...g8,"structure","predicate"],d6=[...v8,...b2],I2=["alias","union","morph","unit","intersection","proto","domain"],l$=[...I2,...d6],c6=y(d6,(Z,X)=>[X,1]),F3=y([...b2,"undeclared"],(Z,X)=>[X,1]),B3=y(l$,(Z,X)=>[X,Z]),Fq=[...i6("union"),"alias"],Bq=[...i6("morph"),"alias"]});var M3,d$,X0;var t1=R(()=>{j();M3=class M3 extends Error{name="ToJsonSchemaError";code;context;constructor(Z,X){super(k(X,{quoteKeys:!1,indent:4}));this.code=Z,this.context=X}hasCode(Z){return this.code===Z}};d$={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Z)=>X0.throw("arrayObject",Z),arrayPostfix:(Z)=>X0.throw("arrayPostfix",Z),defaultValue:(Z)=>X0.throw("defaultValue",Z),domain:(Z)=>X0.throw("domain",Z),morph:(Z)=>X0.throw("morph",Z),patternIntersection:(Z)=>X0.throw("patternIntersection",Z),predicate:(Z)=>X0.throw("predicate",Z),proto:(Z)=>X0.throw("proto",Z),symbolKey:(Z)=>X0.throw("symbolKey",Z),unit:(Z)=>X0.throw("unit",Z),date:(Z)=>X0.throw("date",Z)}},X0={Error:M3,throw:(...Z)=>{throw new X0.Error(...Z)},throwInternalOperandError:(Z,X)=>d(`Unexpected JSON Schema input for ${Z}: ${k(X)}`),defaultConfig:d$}});var y4=(Z,X)=>{if(!X)return Z;let Q={...Z},U;for(U in X){let J={...Z.keywords};if(U==="keywords"){for(let $ in X[U]){let W=X.keywords[$];if(W===void 0)continue;J[$]=typeof W==="string"?{description:W}:W}Q.keywords=J}else if(U==="toJsonSchema")Q[U]=x8(Z.toJsonSchema,X.toJsonSchema);else if(f2(U))Q[U]={...Z[U],...X[U]};else Q[U]=X[U]}return Q},c$,x8=(Z,X)=>{if(!Z)return R3(X??{},void 0);if(!X)return Z;let Q={...Z},U;for(U in X)if(U==="fallback")Q.fallback=i$(Z.fallback,X.fallback);else Q[U]=X[U];return R3(Q,X)},R3=(Z,X)=>{if(X?.dialect!==void 0)return Z;if(X?.target!==void 0)return{...Z,dialect:c$[X.target]};return Z},i$=(Z,X)=>{Z=O3(Z),X=O3(X);let Q={},U;for(U in X0.defaultConfig.fallback)Q[U]=X[U]??X.default??Z[U]??Z.default??X0.defaultConfig.fallback[U];return Q},O3=(Z)=>typeof Z==="function"?{default:Z}:Z??{};var k2=R(()=>{i();c();t1();O.config??={};c$={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"}});var e1,y0,h8,s$=(Z)=>Z.toString().split(`
19
16
  `).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,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(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,H)=>H.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:U})=>`${Q}: ${kX(X,U)}`).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((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 H=l1[J],_=H instanceof q?H.invert():H;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,H)=>J.rawIn.equals(Z[H].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)=>L(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,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.$=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 HZ=M({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,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:HZ,Node:uX};var LZ=(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)L(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 L(`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 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((U)=>(U 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],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 L(`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),H=[],_={};for(let[W1,y1]of J){let U2=G.keys[W1],LY=U2.serialize??(U2.child?NZ:t);if(_[W1]=LY(y1),U2.child===!0){let O6=y1;if(K(O6))H.push(...O6);else H.push(O6)}else if(typeof U2.child==="function")H.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:H};if(X!=="intersection"){for(let W1 in U)if(W1!=="in"&&W1!=="out")hQ[W1]=U[W1]}let HY=new Y4[X](hQ,Z);return Z.nodesByHash[F1]=HY},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:L(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)L(bZ(U));let Z=Q.in(Y?X():X);if(Z instanceof o){if(U===null)L(`Default ${Z.summary}`);let W=Z.transform((G)=>G.transform((J)=>({...J,prefixPath:[U]})));L(`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 L(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)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((U)=>this.applyStructuralOperation("merge",[G4(U)??L(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)L(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:
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=V2(this,Q,this.$);if(X instanceof q)return X.throw();return X}rawPipeOnce(Q){if(A(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,U){let Y=this.$.node(X,U);if(Y.isRoot())return Y.isUnknown()?this:C(`Unexpected constraint node ${Y}`);let Z=Q==="root"?this:Q==="in"?this.rawIn:this.rawOut;if(Z.hasKind("morph")||Y.impliedBasis&&!Z.extends(Y.impliedBasis))return xX(X,Y.impliedBasis,this);let W=this.$.node("intersection",{[Y.kind]:Y}),G=Q==="out"?V2(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,U=typeof Q==="string"?!1:Q.deep;return this.$.finalize(this.transform((Y,Z)=>Y==="structure"?X==="ignore"?x2(Z,{undeclared:1}):{...Z,undeclared:X}:Z,U?void 0:{shouldTransform:(Y)=>!n(h1,Y.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,U)=>X.propString===U.propString&&(X.node.hasKind("morph")&&U.node.hasKind("morph")?X.node.hasEqualMorphs(U.node):X.node.hasKind("intersection")&&U.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===U.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 fZ="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},P2=(Q,X)=>A(X,"root")?A(Q,"root")?Q.extends(X):X.allows(Q):A(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)=>B(o2(Q),(U,Y)=>[Y,X]);var kZ=(Q)=>typeof Q==="string"?{reference:Q}:Q,H4=(Q)=>Q instanceof q?F.intrinsic.never.internal:Q,gZ=M({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,U)=>U.$.lazilyResolve(()=>H4(N(Q.resolution,X.resolution,U)),`${Q.reference}${U.pipe?"=>":"&"}${X.reference}`),...H1("alias",(Q,X,U)=>{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 U.$.lazilyResolve(()=>H4(N(Q.resolution,X,U)),`${Q.reference}${U.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],U=[];while(A(X,"context")){if(U.includes(X.id))return L(xZ(X.id,U));U.push(X.id),X=m[X.id]}if(!A(X,"root"))return C(`Unexpected resolution for reference ${this.reference}
26
- Seen: [${U.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(A(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 U=X.seen[this.reference];if(U?.includes(Q))return!0;return X.seen[this.reference]=D(U,Q),this.resolution.traverseAllows(Q,X)};traverseApply=(Q,X)=>{let U=X.seen[this.reference];if(U?.includes(Q))return;X.seen[this.reference]=D(U,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("->")}`,N2={implementation:gZ,Node:L4};class b1 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=M({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[f(Q)]},intersections:{domain:(Q,X)=>Q.domain==="number"&&X.domain==="number"?Q.numberAllowsNaN?X:Q:q.init("domain",Q,X)}});class F4 extends b1{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Q)=>typeof Q==="number"&&!Number.isNaN(Q):(Q)=>f(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=M({kind:"intersection",hasAssociatedError:!0,normalize:(Q)=>{if(P(Q))return Q;let{structure:X,...U}=Q,Y=!!X,Z=X??{},W=B(U,(G,J)=>{if(y(G,EX)){if(Y)L(`Flattened structure key ${G} cannot be specified alongside a root 'structure' key.`);return Z[G]=J,[]}return[G,J]});if(A(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,...U}=Q.collapsibleJson,{minVariadicLength:Y,...Z}=X,W=Z.variadic&&Object.keys(Z).length===1?Z.variadic:Z;return{...U,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((U)=>U.impl.obviatesBasisDescription))X.push(Q.basis.description);if(Q.prestructurals.length){let U=Q.prestructurals.slice().sort((Y,Z)=>Y.kind==="min"&&Z.kind==="max"?-1:0).map((Y)=>Y.description);X.push(...U)}if(Q.inner.predicate)X.push(...Q.inner.predicate.map((U)=>U.description));return X.join(" and ")},expected:(Q)=>` ◦ ${Q.errors.map((X)=>X.expected).join(`
28
- `)}`,problem:(Q)=>`(${Q.actual}) must be...
29
- ${Q.expected}`},intersections:{intersection:(Q,X,U)=>q4(Q.inner,X.inner,U),...H1("intersection",(Q,X,U)=>{if(Q.children.length===0)return X;let{domain:Y,proto:Z,...W}=Q.inner,G=Z??Y,J=G?N(G,X,U):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,U)=>U.isBasis()?U.toJsonSchemaRecurse(Q):U.reduceJsonSchema(X,Q),{})}traverseAllows=(Q,X)=>this.children.every((U)=>U.traverseAllows(Q,X));traverseApply=(Q,X)=>{let U=X.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Q,X),X.currentErrorCount>U)return}if(this.prestructurals.length){for(let Y=0;Y<this.prestructurals.length-1;Y++)if(this.prestructurals[Y].traverseApply(Q,X),X.failFast&&X.currentErrorCount>U)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(Q,X),X.currentErrorCount>U)return}if(this.structure){if(this.structure.traverseApply(Q,X),X.currentErrorCount>U)return}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)if(this.inner.predicate[Y].traverseApply(Q,X),X.failFast&&X.currentErrorCount>U)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:"",U=Q.prestructurals.map((Z)=>Z.expression).join(" & "),Y=`${X}${X?" ":""}${U}`;if(Y==="Array == 0")return"[]";return Y||"unknown"},q4=(Q,X,U)=>{let Y={},Z=Q.proto??Q.domain,W=X.proto??X.domain,G=Z?W?N(Z,W,U):Z:W;if(G instanceof q)return G;if(G)Y[G.kind]=G;return d1({kind:"intersection",baseInner:Y,l:c1(Q),r:c1(X),roots:[],ctx:U})};var uZ=M({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Q,X)=>X.$.parseSchema(Q)},morphs:{parse:T1,serialize:(Q)=>Q.map((X)=>A(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,U)=>{if(!Q.hasEqualMorphs(X))return L(lZ(Q.expression,X.expression));let Y=N(Q.rawIn,X.rawIn,U);if(Y instanceof q)return Y;let Z={morphs:Q.morphs};if(Q.declaredIn||X.declaredIn){let W=N(Q.rawIn,X.rawIn,U);if(W instanceof q)return W.throw();else Z.declaredIn=W}if(Q.declaredOut||X.declaredOut){let W=N(Q.rawOut,X.rawOut,U);if(W instanceof q)return W.throw();else Z.declaredOut=W}return Y.distribute((W)=>U.$.node("morph",{...Z,in:W}),U.$.parseSchema)},...H1("morph",(Q,X,U)=>{let Y=Q.inner.in?N(Q.inner.in,X,U):X;return Y instanceof q?Y:Y.equals(Q.inner.in)?Q:U.$.node("morph",{...Q.inner,in:Y})})}});class A4 extends e{serializedMorphs=this.morphs.map(S);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=A(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,U)=>X===U||A(X,"root")&&A(U,"root")&&X.equals(U)})}}var WQ={implementation:uZ,Node:A4},lZ=(Q,X)=>`The intersection of distinct morphs at a single path is indeterminate:
30
- Left: ${Q}
31
- Right: ${X}`;var dZ=M({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Q)=>H2(Q)??t(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(I2.writeInvalidSchemaMessage(X.proto));if(g1(X,"dateAllowsInvalid")&&X.proto!==Date)L(I2.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":_2(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 b1{builtinName=H2(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Q)=>Q instanceof Date&&Q.toString()!=="Invalid Date":(Q)=>Q instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Q){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Q.fallback.date?.({code:"date",base:{}})??Q.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Q.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var I2={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 ${f(Q)})`};var cZ=M({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Q,X)=>{let U=[];for(let Y of Q){let Z=A(Y,"root")?Y.branches:X.$.parseSchema(Y).branches;for(let W of Z)if(W.hasKind("morph")){let G=U.findIndex((J)=>J.hasKind("morph")&&J.hasEqualMorphs(W));if(G===-1)U.push(W);else{let J=U[G];U[G]=X.$.node("morph",{...J.inner,in:J.rawIn.rawOr(W.rawIn)})}}else U.push(W)}if(!X.def.ordered)U.sort((Y,Z)=>Y.hash<Z.hash?-1:1);return U}}},normalize:(Q)=>K(Q)?{branches:Q}:Q,reduce:(Q,X)=>{let U=X3(Q);if(U.length===1)return U[0];if(U.length===Q.branches.length)return;return X.node("union",{...Q,branches:U},{prereduced:!0})},defaults:{description:(Q)=>Q.distribute((X)=>X.description,r1),expected:(Q)=>{let X=nQ(Q.errors,"propString"),U=Object.entries(X).map(([Y,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`${Y&&`${Y} `}must be ${G}${J&&` (was ${J})`}`});return r1(U)},problem:(Q)=>Q.expected,message:(Q)=>{if(Q.problem[0]==="[")return`value at ${Q.problem}`;return Q.problem}},intersections:{union:(Q,X,U)=>{if(Q.isNever!==X.isNever)return q.init("presence",Q,X);let Y;if(Q.ordered){if(X.ordered)L(Y3(Q.expression,X.expression));if(Y=GQ(X.branches,Q.branches,U),Y instanceof q)Y.invert()}else Y=GQ(Q.branches,X.branches,U);if(Y instanceof q)return Y;return U.$.parseSchema(Q.ordered||X.ordered?{branches:Y,ordered:!0}:{branches:Y})},...H1("union",(Q,X,U)=>{let Y=GQ(Q.branches,[X],U);if(Y instanceof q)return Y;if(Y.length===1)return Y[0];return U.$.parseSchema(Q.ordered?{branches:Y,ordered:!0}:{branches:Y})})}});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 U of this.branches){if(U.hasKind("unit")&&U.domain==="boolean"){if(X===-1)X=Q.length,Q.push(U);else Q[X]=F.intrinsic.boolean;continue}Q.push(U)}return Q}unitBranches=this.branches.filter((Q)=>Q.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?aZ(this.discriminant):null;expression=this.distribute((Q)=>Q.nestableExpression,Q3);createBranchedOptimisticRootApply(){return(Q,X)=>{let U=this.traverseOptimistic(Q);if(U!==d)return U;let Y=new Y1(Q,this.$.resolvedConfig);return this.traverseApply(Q,Y),Y.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((U)=>U.toJsonSchemaRecurse(Q));if(X.every((U)=>Object.keys(U).length===1&&g1(U,"const")))return{enum:X.map((U)=>U.const)};return{anyOf:X}}traverseAllows=(Q,X)=>this.branches.some((U)=>U.traverseAllows(Q,X));traverseApply=(Q,X)=>{let U=[];for(let Y=0;Y<this.branches.length;Y++){if(X.pushBranch(),this.branches[Y].traverseApply(Q,X),!X.hasError()){if(this.branches[Y].includesTransform)return X.queuedMorphs.push(...X.popBranch().queuedMorphs);return X.popBranch()}U.push(X.popBranch().error)}X.errorFromNodeContext({code:"union",errors:U,meta:this.meta})};traverseOptimistic=(Q)=>{for(let X=0;X<this.branches.length;X++){let U=this.branches[X];if(U.traverseAllows(Q)){if(U.contextFreeMorph)return U.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 U=this.discriminant.cases,Y=Object.keys(U),{optimistic:Z}=Q;if(Q.optimistic=!1,Q.block(`switch(${X})`,()=>{for(let _ in U){let $=U[_],O=_==="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(`${O}: return ${R}`)}return Q}),Q.traversalKind==="Allows"){Q.return(Z?`"${d}"`:!1);return}let W=r1(this.discriminant.kind==="domain"?Y.map((_)=>{let $=_.slice(1,-1);return $==="function"?l.object:l[$]}):Y),G=this.discriminant.path.map((_)=>typeof _==="symbol"?S(_):JSON.stringify(_)),J=JSON.stringify(W),H=this.discriminant.kind==="domain"?`${nZ}[${X}]`:`${tZ}(${X})`;Q.line(`ctx.errorFromNodeContext({
17
+ `);var k4=R(()=>{j();_0();e1=class e1 extends D4{[w0]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Z,relativePath:X,...Q},U){super();this.input=Q,this.ctx=U,j7(this,Q);let J=U.data;if(Q.code==="union")Q.errors=Q.errors.flatMap((W)=>{let Y=W.hasCode("union")?W.errors:[W];if(!Z&&!X)return Y;return Y.map((G)=>G.transform((_)=>({..._,path:P7(Z,_.path,X)})))});this.nodeConfig=U.config[this.code];let $=[...Q.path??U.path];if(X)$.push(...X);if(Z)$.unshift(...Z);this.path=new b4(...$),this.data="data"in Q?Q.data:J}transform(Z){return new e1(Z({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Z){return this.code===Z}get propString(){return g1(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Z=this.meta?.expected??this.nodeConfig.expected;return typeof Z==="function"?Z(this.input):Z}get actual(){if(this.input.actual)return this.input.actual;let Z=this.meta?.actual??this.nodeConfig.actual;return typeof Z==="function"?Z(this.data):Z}get problem(){if(this.input.problem)return this.input.problem;let Z=this.meta?.problem??this.nodeConfig.problem;return typeof Z==="function"?Z(this):Z}get message(){if(this.input.message)return this.input.message;let Z=this.meta?.message??this.nodeConfig.message;return typeof Z==="function"?Z(this):Z}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}};y0=class y0 extends y6{[w0]="errors";ctx;constructor(Z){super();this.ctx=Z}byPath=Object.create(null);get flatByPath(){return y(this.byPath,(Z,X)=>[Z,X.flat])}get flatProblemsByPath(){return y(this.byPath,(Z,X)=>[Z,X.flat.map((Q)=>Q.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new h8(this)}add(Z){let X=this.byPath[Z.propString];if(X){if(Z===X)return;if(X.hasCode("union")&&X.errors.length===0)return;let Q=Z.hasCode("union")&&Z.errors.length===0?Z:new e1({code:"intersection",errors:X.hasCode("intersection")?[...X.errors,Z]:[X,Z]},this.ctx),U=this.indexOf(X);this.mutable[U===-1?this.length:U]=Q,this.byPath[Z.propString]=Q,this.addAncestorPaths(Z)}else this.byPath[Z.propString]=Z,this.addAncestorPaths(Z),this.mutable.push(Z);this.count++}transform(Z){let X=new y0(this.ctx);for(let Q of this)X.add(Z(Q));return X}merge(Z){for(let X of Z)this.add(new e1({...X,path:[...this.ctx.path,...X.path]},this.ctx))}affectsPath(Z){if(this.length===0)return!1;return Z.stringifyAncestors().some((X)=>(X in this.byPath))||Z.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Z)=>Z.toJSON())]}toString(){return this.join(`
18
+ `)}addAncestorPaths(Z){for(let X of Z.path.stringifyAncestors())this.byAncestorPath[X]=u(this.byAncestorPath[X],Z)}};h8=class h8 extends Error{name="TraversalError";constructor(Z){if(Z.length===1)super(Z.summary);else super(`
19
+ `+Z.map((X)=>` • ${s$(X)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:Z,enumerable:!1})}}});class Y1{path=[];errors=new y0(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Z,X){this.root=Z,this.config=X}get data(){let Z=this.root;for(let X of this.path)Z=Z?.[X];return Z}get propString(){return g1(this.path)}reject(Z){return this.error(Z),!1}mustBe(Z){return this.error(Z),!1}error(Z){let X=typeof Z==="object"?Z.code?Z:{...Z,code:"predicate"}:{code:"predicate",expected:Z};return this.errorFromContext(X)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Z){let X={path:new b4(...this.path),morphs:Z};if(this.currentBranch)this.currentBranch.queuedMorphs.push(X);else this.queuedMorphs.push(X)}finalize(Z){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 Z?Z(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(Z){return this.errorFromContext(Z)}errorFromContext(Z){let X=new e1(Z,this);if(this.currentBranch)this.currentBranch.error=X;else this.errors.add(X);return X}applyQueuedMorphs(){while(this.queuedMorphs.length){let Z=this.queuedMorphs;this.queuedMorphs=[];for(let{path:X,morphs:Q}of Z){if(this.errors.affectsPath(X))continue;this.applyMorphsAtPath(X,Q)}}}applyMorphsAtPath(Z,X){let Q=Z[Z.length-1],U;if(Q!==void 0){U=this.root;for(let J=0;J<Z.length-1;J++)U=U[Z[J]]}for(let J of X){this.path=[...Z];let $=e(J),W=J(U===void 0?this.root:U[Q],this);if(W instanceof e1){if(!this.errors.includes(W))this.errors.add(W);break}if(W instanceof y0){if(!$)this.errors.merge(W);this.queuedMorphs=[];break}if(U===void 0)this.root=W;else U[Q]=W;this.applyQueuedMorphs()}}}var k0=(Z,X,Q)=>{if(!Q)return X();Q.path.push(Z);let U=X();return Q.path.pop(),U};var K1=R(()=>{j();k4();_0()});var v4,g4,K3=(Z,X)=>`${Z} had no references matching ${k(X)}.`,r$=(Z)=>g1(Z,{stringifyNonKey:(X)=>X.expression}),o$,a$=(Z)=>JSON.stringify(Z).replace(o$,"$1"),G1=(Z,X)=>({path:Z,node:X,propString:r$(Z)}),T3=(Z,X)=>Z.propString===X.propString&&Z.node.equals(X.node),m8=(Z,X)=>M1(Z,X,{isEqual:T3}),n$=(Z,X)=>M1(Z,X,{isEqual:(Q,U)=>Q.equals(U)});var T2=R(()=>{j();i();c();K1();_0();v4=class v4 extends f0{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Z,X){super((U,J,$=this.onFail)=>{if(J)return this.traverseApply(U,J),J.hasError()?J.errors:J.data;return this.rootApply(U,$)},{attach:Z});this.attachments=Z,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,J)=>n$(U,J.shallowReferences),[this]);let Q=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,!Q){let J=this.children[U].flatRefs;for(let $=0;$<J.length;$++){let W=J[$];if(!this.flatRefs.some((Y)=>T3(Y,W))){this.flatRefs.push(W);for(let Y of W.node.branches)if(Y.hasKind("morph")||Y.hasKind("intersection")&&Y.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.propString,node:Y})}}}Object.assign(this.referencesById,this.children[U].referencesById)}this.flatRefs.sort((U,J)=>U.path.length>J.path.length?1:U.path.length<J.path.length?-1:U.propString>J.propString?1:U.propString<J.propString?-1:U.node.expression<J.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 Y1(U,this.$.resolvedConfig)):(U)=>this.traverseAllows(U)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(X,Q)=>{if(this.allows(X))return X;let U=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Q)};case"contextual":return(X,Q)=>{let U=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Q)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Z=this.$.resolvedConfig.clone;return(X,Q)=>{if(this.allows(X))return this.contextFreeMorph(Z&&(typeof X==="object"&&X!==null||typeof X==="function")?Z(X):X);let U=new Y1(X,this.$.resolvedConfig);return this.traverseApply(X,U),U.finalize(Q)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,d(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=a$(this.metaJson);cacheGetter(Z,X){return Object.defineProperty(this,Z,{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=y2(this.kind);precompilation;assert=(Z,X)=>this(Z,X,(Q)=>Q.throw());traverse(Z,X){return this(Z,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(Z){if(!this.includesTransform)return this;let X={};for(let[Q,U]of this.innerEntries){let J=this.impl.keys[Q];if(J.reduceIo)J.reduceIo(Z,X,U);else if(J.child){let $=U;X[Q]=t($)?$.map((W)=>Z==="in"?W.rawIn:W.rawOut):Z==="in"?$.rawIn:$.rawOut}else X[Q]=U}return this.$.node(this.kind,X)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Z){let X=e(Z)?Z:this.$.parseDefinition(Z);return this.innerHash===X.innerHash}ifEquals(Z){return this.equals(Z)?this:void 0}hasKind(Z){return this.kind===Z}assertHasKind(Z){if(this.kind!==Z)F2(`${this.kind} node was not of asserted kind ${Z}`);return this}hasKindIn(...Z){return Z.includes(this.kind)}assertHasKindIn(...Z){if(!c0(Z,this.kind))F2(`${this.kind} node was not one of asserted kinds ${Z}`);return this}isBasis(){return c0(z3,this.kind)}isConstraint(){return c0(d6,this.kind)}isStructural(){return c0(b2,this.kind)}isRefinement(){return c0(v8,this.kind)}isRoot(){return c0(I2,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Z){return this.hasKind("unit")&&this.allows(Z)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Z){let X=g4.normalize(Z);return this._select(X)}_select(Z){let X=g4.applyBoundary[Z.boundary??"references"](this);if(Z.kind)X=X.filter((Q)=>Q.kind===Z.kind);if(Z.where)X=X.filter(Z.where);return g4.applyMethod[Z.method??"filter"](X,this,Z)}transform(Z,X){return this._transform(Z,this._createTransformContext(X))}_createTransformContext(Z){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Z?.prereduced??!1},undeclaredKeyHandling:void 0,...Z}}_transform(Z,X){let Q=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 J=y(this.inner,(_,L)=>{if(!this.impl.keys[_].child)return[_,L];let V=L;if(!t(V)){let H=V._transform(Z,X);return H?[_,H]:[]}if(V.length===0)return[_,L];let q=V.flatMap((H)=>{return H._transform(Z,X)??[]});return q.length?[_,q]:[]});delete X.seen[this.id];let $=Object.assign(J,{meta:this.meta}),W=X.selected&&!X.selected.includes(this)?$:Z(this.kind,$,X);if(W===null)return null;if(e(W))return U=W;let Y=Object.keys(W);if((Y.length===0||Y.length===1&&Y[0]==="meta")&&!O1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return X.undeclaredKeyHandling?{...W,value:O.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=O.intrinsic.unknown;return U=Q.node(this.kind,W,X.parseOptions)}configureReferences(Z,X="references"){let Q=g4.normalize(X),U=typeof Z==="string"?(Y,G)=>({...G,meta:{...G.meta,description:Z}}):typeof Z==="function"?(Y,G)=>({...G,meta:Z(G.meta)}):(Y,G)=>({...G,meta:{...G.meta,...Z}});if(Q.boundary==="self")return this.$.node(this.kind,U(this.kind,{...this.inner,meta:this.meta}));let J=this._select(Q),$=J&&i1(J),W=Q.boundary==="child"?(Y,G)=>G.root.children.includes(Y):Q.boundary==="shallow"?(Y)=>Y.kind!=="structure":()=>!0;return this.$.finalize(this.transform(U,{shouldTransform:W,selected:$}))}};g4={applyBoundary:{self:(Z)=>[Z],child:(Z)=>[...Z.children],shallow:(Z)=>[...Z.shallowReferences],references:(Z)=>[...Z.references]},applyMethod:{filter:(Z)=>Z,assertFilter:(Z,X,Q)=>{if(Z.length===0)F2(K3(X,Q));return Z},find:(Z)=>Z[0],assertFind:(Z,X,Q)=>{if(Z.length===0)F2(K3(X,Q));return Z[0]}},normalize:(Z)=>typeof Z==="function"?{boundary:"references",method:"filter",where:Z}:typeof Z==="string"?H0(Z,g4.applyBoundary)?{method:"filter",boundary:Z}:{boundary:"references",method:"filter",kind:Z}:{boundary:"references",method:"filter",...Z}},o$=/"(\$ark\.[^"]+)"/g});var A,D3=(Z,X)=>`${u8(Z)} and ${u8(X)}`,u8=(Z)=>e(Z)?Z.expression:t(Z)?Z.map(u8).join(" | ")||"never":String(Z),p8=(Z)=>`${Z} results in an unsatisfiable type`;var Y0=R(()=>{j();c();_0();A=class A extends Array{static init(Z,X,Q,U){return new A({kind:Z,l:X,r:Q,path:U?.path??[],optional:U?.optional??!1})}add(Z,X,Q,U){return this.push({kind:Z,l:X,r:Q,path:U?.path??[],optional:U?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Z,l:X,r:Q}=this[0],U=g1(Z);return p8(`Intersection${U&&` at ${U}`} of ${D3(X,Q)}`)}return`The following intersections result in unsatisfiable types:
21
+ ${this.map(({path:Z,l:X,r:Q})=>`${Z}: ${D3(X,Q)}`).join(`
22
+ • `)}`}throw(){return M(this.describeReasons())}invert(){let Z=this.map((X)=>({...X,l:X.r,r:X.l}));if(!(Z instanceof A))return new A(...Z);return Z}withPrefixKey(Z,X){return this.map((Q)=>({...Q,path:[Z,...Q.path],optional:Q.optional||X==="optional"}))}toNeverIfDisjoint(){return O.intrinsic.never}}});var g2,g0=(Z,X,Q)=>Z0(Z,X,{$:Q,invert:!1,pipe:!1}),x4=(Z,X,Q)=>Z0(Z,X,{$:Q,invert:!1,pipe:!0}),Z0=(Z,X,Q)=>{let U=Q.pipe?"|>":"&",J=`${Z.hash}${U}${X.hash}`;if(g2[J]!==void 0)return g2[J];if(!Q.pipe){let Y=`${X.hash}${U}${Z.hash}`;if(g2[Y]!==void 0){let G=g2[Y],_=G instanceof A?G.invert():G;return g2[J]=_,_}}let $=!Q.pipe||!Z.includesTransform&&!X.includesTransform;if($&&Z.equals(X))return Z;let W=$?l8(Z,X,Q):Z.hasKindIn(...I2)?t$(Z,X,Q):l8(Z,X,Q);if(e(W)){if(Z.equals(W))W=Z;else if(X.equals(W))W=X}return g2[J]=W,W},l8=(Z,X,Q)=>{let U=Z.precedence<X.precedence?Z.kind:X.kind,J=Z.impl.intersections[X.kind]??X.impl.intersections[Z.kind];if(J===void 0)return null;else if(U===Z.kind)return J(Z,X,Q);else{let $=J(X,Z,{...Q,invert:!Q.invert});if($ instanceof A)$=$.invert();return $}},t$=(Z,X,Q)=>Z.includesTransform||X.includesTransform?Q.invert?P3(X,Z,Q):P3(Z,X,Q):l8(Z,X,Q),P3=(Z,X,Q)=>Z.distribute((U)=>e$(U,X,Q),(U)=>{let J=U.filter(e);if(J.length===0)return A.init("union",Z.branches,X.branches);if(J.length<Z.branches.length||!Z.branches.every((Y,G)=>Y.rawIn.equals(J[G].rawIn)))return Q.$.parseSchema(J);let $;if(J.length===1){let Y=J[0];if(!$)return Y;return Q.$.node("morph",{...Y.inner,in:Y.rawIn.configure($,"self")})}let W={branches:J};if($)W.meta=$;return Q.$.parseSchema(W)}),e$=(Z,X,Q)=>{if(Z.hasKind("morph")){let J=[...Z.morphs];if(Z.lastMorphIfNode){let $=Z0(Z.lastMorphIfNode,X,Q);if($ instanceof A)return $;J[J.length-1]=$}else J.push(X);return Q.$.node("morph",{morphs:J,in:Z.inner.in})}if(X.hasKind("morph")){let J=Z0(Z,X.rawIn,Q);if(J instanceof A)return J;return Q.$.node("morph",{morphs:[X],in:J})}return Q.$.node("morph",{morphs:[X],in:Z})};var s0=R(()=>{Y0();i();_0();g2={}});var r0,v1,O0=(Z)=>(X,Q)=>{if(t(X)){if(X.length===0)return;let J=X.map(($)=>Q.$.node(Z,$));if(Z==="predicate")return J;return J.sort(($,W)=>$.hash<W.hash?-1:1)}let U=Q.$.node(Z,X);return U.hasOpenIntersection()?[U]:U},v2=(Z)=>{let X=Z.r.shift();if(!X){let U=Z.l.length===0&&Z.kind==="structure"?O.intrinsic.unknown.internal:Z.ctx.$.node(Z.kind,Object.assign(Z.baseInner,ZW(Z.l)),{prereduced:!0});for(let J of Z.roots){if(U instanceof A)return U;U=Z0(J,U,Z.ctx)}return U}let Q=!1;for(let U=0;U<Z.l.length;U++){let J=Z0(Z.l[U],X,Z.ctx);if(J===null)continue;if(J instanceof A)return J;if(J.isRoot())return Z.roots.push(J),Z.l.splice(U),v2(Z);if(!Q)Z.l[U]=J,Q=!0;else if(!Z.l.includes(J))return d(`Unexpectedly encountered multiple distinct intersection results for refinement ${X}`)}if(!Q)Z.l.push(X);if(Z.kind==="intersection"){if(X.impliedSiblings)for(let U of X.impliedSiblings)M1(Z.r,U)}return v2(Z)},x2=(Z)=>{return Object.entries(Z).flatMap(([Q,U])=>(Q in c6)?U:[]).sort((Q,U)=>Q.precedence<U.precedence?-1:Q.precedence>U.precedence?1:Q.kind==="predicate"&&U.kind==="predicate"?0:Q.hash<U.hash?-1:1)},ZW=(Z)=>{let X={};for(let Q of Z)if(Q.hasOpenIntersection())X[Q.kind]=u(X[Q.kind],Q);else{if(X[Q.kind])return d(`Unexpected intersection of closed refinements of kind ${Q.kind}`);X[Q.kind]=Q}return X},w3=(...Z)=>M(A3(...Z)),A3=(Z,X,Q)=>{let U=Q.hasKind("morph")?"a morph":Q.isUnknown()?"unknown":Q.exclude(X).defaultShortDescription;return`${i7(Z)} operand must be ${X.description} (was ${U})`};var h0=R(()=>{j();T2();Y0();i();s0();c();_0();r0=class r0 extends v4{constructor(Z,X){super(Z,X);Object.defineProperty(this,w0,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Z){return g0(this,Z,this.$)}};v1=class v1 extends r0{traverseApply=(Z,X)=>{if(!this.traverseAllows(Z,X))X.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return n1(this.errorContext)}}});var S3=(Z,X,Q)=>new Z2(Z,X,Q,Q,null),s6,Z2,XW=(Z,X,Q)=>`${Z} must be assignable to ${X} (was ${Q})`;var d8=R(()=>{j();c();_0();s6=class s6 extends f0{};Z2=class Z2 extends f0{[w0]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Z,X,Q,U,J){super((...$)=>{let W=y(this.names,(Y,G)=>{let _=this.arg$.parse($[Y]);if(!_.extends(this.constraints[Y]))M(XW(G,this.constraints[Y].expression,_.expression));return[G,_]});if(this.defIsLazy()){let Y=this.bodyDef(W);return this.$.parse(Y)}return this.$.parse(X,{args:W})});this.paramDefs=Z,this.bodyDef=X,this.$=Q,this.arg$=U,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof s6}cacheGetter(Z,X){return Object.defineProperty(this,Z,{value:X}),X}get json(){return this.cacheGetter("json",{params:this.params.map((Z)=>Z[1].isUnknown()?Z[0]:[Z[0],Z[1].json]),body:$3(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Z)=>typeof Z==="string"?[Z,O.intrinsic.unknown]:[Z[0],this.$.parse(Z[1])]))}get names(){return this.cacheGetter("names",this.params.map((Z)=>Z[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Z)=>Z[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}});var QW,C3,c8;var i8=R(()=>{h0();i();c();QW=g({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Z)=>typeof Z==="function"?{predicate:Z}:Z,defaults:{description:(Z)=>`valid according to ${Z.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});C3=class C3 extends r0{serializedPredicate=U0(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=n1(this.errorContext);traverseApply=(Z,X)=>{let Q=X.currentErrorCount;if(!this.predicate(Z,X.external)&&X.currentErrorCount===Q)X.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows"){Z.return(this.compiledCondition);return}Z.initializeErrorCount(),Z.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Z,X){return X.fallback.predicate({code:"predicate",base:Z,predicate:this.predicate})}};c8={implementation:QW,Node:C3}});var UW,N3,s8,JW=(Z)=>`divisor must be an integer (was ${Z})`,$W=(Z,X)=>{let Q,U=Z,J=X;while(J!==0)Q=J,J=U%J,U=Q;return U};var r8=R(()=>{j();h0();i();c();UW=g({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Z)=>Number.isInteger(Z)?Z:M(JW(Z))}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>Z.rule===1?"an integer":Z.rule===2?"even":`a multiple of ${Z.rule}`},intersections:{divisor:(Z,X,Q)=>Q.$.node("divisor",{rule:Math.abs(Z.rule*X.rule/$W(Z.rule,X.rule))})},obviatesBasisDescription:!0});N3=class N3 extends v1{traverseAllows=(Z)=>Z%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=O.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Z){if(Z.type="integer",this.rule===1)return Z;return Z.multipleOf=this.rule,Z}};s8={implementation:UW,Node:N3}});var m0,WW,YW,r6,o6=(Z)=>(X)=>{if(typeof X==="number")return{rule:X};let{exclusive:Q,...U}=X;return Q?{...U,rule:Z==="minLength"?U.rule+1:U.rule-1}:U},a6=(Z)=>(X)=>{if(typeof X==="number"||typeof X==="string"||X instanceof Date)return{rule:X};let{exclusive:Q,...U}=X;if(!Q)return U;let J=typeof U.rule==="number"?U.rule:typeof U.rule==="string"?new Date(U.rule).valueOf():U.rule.valueOf();return Q?{...U,rule:Z==="after"?J+1:J-1}:U},n6=(Z)=>typeof Z==="string"||typeof Z==="number"?new Date(Z):Z,GW=(Z,X)=>`${Z} bound must be a positive integer (was ${X})`,h2=(Z)=>(X)=>{if(!Number.isInteger(X)||X<0)M(GW(Z,X));return X},_W,LW=(Z,X)=>`${H0(Z,YW)?">":"<"}${X?"":"="}`,VW=(Z)=>typeof Z==="string"?Z:new Date(Z).toLocaleString(),j3=(Z)=>`Bounded expression ${Z} must be exactly one of number, string, Array, or Date`;var x1=R(()=>{j();h0();m0=class m0 extends v1{boundOperandKind=_W[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=LW(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${WW[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?VW(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Z){return(this.limitKind==="upper"?this.numericLimit<Z.numericLimit:this.numericLimit>Z.numericLimit)||this.numericLimit===Z.numericLimit&&this.exclusive===!0&&!Z.exclusive}overlapsRange(Z){if(this.isStricterThan(Z))return!1;if(this.numericLimit===Z.numericLimit&&(this.exclusive||Z.exclusive))return!1;return!0}overlapIsUnit(Z){return this.numericLimit===Z.numericLimit&&!this.exclusive&&!Z.exclusive}};WW={"<":">=","<=":">",">":"<=",">=":"<"},YW={min:"max",minLength:"maxLength",after:"before"},r6={parse:(Z)=>Z||void 0},_W={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"}});var qW,E3,o8;var a8=R(()=>{j();i();c();x1();qW=g({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n6,serialize:(Z)=>Z.toISOString()}},normalize:a6("after"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or later`,actual:K2},intersections:{after:(Z,X)=>Z.isStricterThan(X)?Z:X}});E3=class E3 extends m0{impliedBasis=O.intrinsic.Date.internal;collapsibleLimitString=K2(this.rule);traverseAllows=(Z)=>Z>=this.rule;reduceJsonSchema(Z,X){return X.fallback.date({code:"date",base:Z,after:this.rule})}};o8={implementation:qW,Node:E3}});var HW,b3,n8;var t8=R(()=>{j();Y0();i();c();x1();HW=g({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n6,serialize:(Z)=>Z.toISOString()}},normalize:a6("before"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or earlier`,actual:K2},intersections:{before:(Z,X)=>Z.isStricterThan(X)?Z:X,after:(Z,X,Q)=>Z.overlapsRange(X)?Z.overlapIsUnit(X)?Q.$.node("unit",{unit:Z.rule}):null:A.init("range",Z,X)}});b3=class b3 extends m0{collapsibleLimitString=K2(this.rule);traverseAllows=(Z)=>Z<=this.rule;impliedBasis=O.intrinsic.Date.internal;reduceJsonSchema(Z,X){return X.fallback.date({code:"date",base:Z,before:this.rule})}};n8={implementation:HW,Node:b3}});var zW,I3,e8;var ZZ=R(()=>{h0();Y0();i();c();t1();x1();zW=g({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:h2("exactLength")}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>`exactly length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{exactLength:(Z,X,Q)=>A.init("unit",Q.$.node("unit",{unit:Z.rule}),Q.$.node("unit",{unit:X.rule}),{path:["length"]}),minLength:(Z,X)=>Z.rule>=X.rule?Z:A.init("range",Z,X),maxLength:(Z,X)=>Z.rule<=X.rule?Z:A.init("range",Z,X)}});I3=class I3 extends v1{traverseAllows=(Z)=>Z.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=O.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z.maxLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z.maxItems=this.rule,Z;default:return X0.throwInternalOperandError("exactLength",Z)}}};e8={implementation:zW,Node:I3}});var FW,f3,XZ;var QZ=R(()=>{Y0();i();c();x1();FW=g({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r6},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"negative":"non-positive";return`${Z.exclusive?"less than":"at most"} ${Z.rule}`}},intersections:{max:(Z,X)=>Z.isStricterThan(X)?Z:X,min:(Z,X,Q)=>Z.overlapsRange(X)?Z.overlapIsUnit(X)?Q.$.node("unit",{unit:Z.rule}):null:A.init("range",Z,X)},obviatesBasisDescription:!0});f3=class f3 extends m0{impliedBasis=O.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z<this.rule:(Z)=>Z<=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMaximum=this.rule;else Z.maximum=this.rule;return Z}};XZ={implementation:FW,Node:f3}});var BW,y3,UZ;var JZ=R(()=>{Y0();i();c();t1();x1();BW=g({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:h2("maxLength")}},reduce:(Z,X)=>Z.rule===0?X.node("exactLength",Z):void 0,normalize:o6("maxLength"),defaults:{description:(Z)=>`at most length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{maxLength:(Z,X)=>Z.isStricterThan(X)?Z:X,minLength:(Z,X,Q)=>Z.overlapsRange(X)?Z.overlapIsUnit(X)?Q.$.node("exactLength",{rule:Z.rule}):null:A.init("range",Z,X)}});y3=class y3 extends m0{impliedBasis=O.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length<=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.maxLength=this.rule,Z;case"array":return Z.maxItems=this.rule,Z;default:return X0.throwInternalOperandError("maxLength",Z)}}};UZ={implementation:BW,Node:y3}});var MW,k3,$Z;var WZ=R(()=>{i();c();x1();MW=g({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r6},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"positive":"non-negative";return`${Z.exclusive?"more than":"at least"} ${Z.rule}`}},intersections:{min:(Z,X)=>Z.isStricterThan(X)?Z:X},obviatesBasisDescription:!0});k3=class k3 extends m0{impliedBasis=O.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z>this.rule:(Z)=>Z>=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMinimum=this.rule;else Z.minimum=this.rule;return Z}};$Z={implementation:MW,Node:k3}});var RW,g3,YZ;var GZ=R(()=>{i();c();t1();x1();RW=g({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:h2("minLength")}},reduce:(Z)=>Z.rule===0?O.intrinsic.unknown:void 0,normalize:o6("minLength"),defaults:{description:(Z)=>Z.rule===1?"non-empty":`at least length ${Z.rule}`,actual:(Z)=>Z.length===0?"":`${Z.length}`},intersections:{minLength:(Z,X)=>Z.isStricterThan(X)?Z:X}});g3=class g3 extends m0{impliedBasis=O.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length>=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z;default:return X0.throwInternalOperandError("minLength",Z)}}};YZ={implementation:RW,Node:g3}});var v3,x3;var _Z=R(()=>{a8();t8();ZZ();QZ();JZ();WZ();GZ();v3={min:$Z.implementation,max:XZ.implementation,minLength:YZ.implementation,maxLength:UZ.implementation,exactLength:e8.implementation,after:o8.implementation,before:n8.implementation},x3={min:$Z.Node,max:XZ.Node,minLength:YZ.Node,maxLength:UZ.Node,exactLength:e8.Node,after:o8.Node,before:n8.Node}});var OW,h3,LZ;var VZ=R(()=>{h0();i();c();OW=g({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Z)=>typeof Z==="string"?{rule:Z}:Z instanceof RegExp?Z.flags?{rule:Z.source,flags:Z.flags}:{rule:Z.source}:Z,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Z)=>`matched by ${Z.rule}`},intersections:{pattern:()=>null}});h3=class h3 extends v1{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=O.intrinsic.string.internal;reduceJsonSchema(Z,X){if(Z.pattern)return X.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:this.rule});return Z.pattern=this.rule,Z}};LZ={implementation:OW,Node:h3}});var h4=(Z,X)=>{let Q=KW(Z);if(X&&!X.includes(Q))return M(`Root of kind ${Q} should be one of ${X}`);return Q},KW=(Z)=>{if(E(Z,"root"))return Z.kind;if(typeof Z==="string")return Z[0]==="$"?"alias":(Z in b0)?"domain":"proto";if(typeof Z==="function")return"proto";if(typeof Z!=="object"||Z===null)return M(m3(Z));if("morphs"in Z)return"morph";if("branches"in Z||t(Z))return"union";if("unit"in Z)return"unit";if("reference"in Z)return"alias";let X=Object.keys(Z);if(X.length===0||X.some((Q)=>(Q in c6)))return"intersection";if("proto"in Z)return"proto";if("domain"in Z)return"domain";return M(m3(Z))},m3=(Z)=>`${k(Z)} is not a valid type schema`,u3,TW=(Z)=>t(Z)?Z.map((X)=>X.collapsibleJson):Z.collapsibleJson,A0,qZ=(Z)=>{return u3[Z]??=0,`${Z}${++u3[Z]}`},HZ=(Z)=>{let X=m2[Z.kind],Q=X.applyConfig?.(Z.def,Z.$.resolvedConfig)??Z.def,U={},{meta:J,...$}=Q,W=J===void 0?{}:typeof J==="string"?{description:J}:J,Y=D8($).sort(([_],[L])=>f2(_)?f2(L)?y2(_)-y2(L):1:f2(L)?-1:_<L?-1:1).filter(([_,L])=>{if(_.startsWith("meta.")){let V=_.slice(5);return W[V]=L,!1}return!0});for(let _ of Y){let L=_[0],V=X.keys[L];if(!V)return M(`Key ${L} is not valid on ${Z.kind} schema`);let q=V.parse?V.parse(_[1],Z):_[1];if(q!==I0&&(q!==void 0||V.preserveUndefined))U[L]=q}if(X.reduce&&!Z.prereduced){let _=X.reduce(U,Z.$);if(_){if(_ instanceof A)return _.throw();return DW(_,W)}}return zZ({id:Z.id,kind:Z.kind,inner:U,meta:W,$:Z.$})},zZ=({id:Z,kind:X,inner:Q,meta:U,$:J,ignoreCache:$})=>{let W=m2[X],Y=D8(Q),G=[],_={};for(let[T,D]of Y){let K=W.keys[T],P=K.serialize??(K.child?TW:i0);if(_[T]=P(D),K.child===!0){let S=D;if(t(S))G.push(...S);else G.push(S)}else if(typeof K.child==="function")G.push(...K.child(D))}if(W.finalizeInnerJson)_=W.finalizeInnerJson(_);let L={..._},V={};if(!O1(U))V=y(U,(T,D)=>[T,T==="examples"?D:i0(D)]),L.meta=t6(V,"description",!0);_=t6(_,W.collapsibleKey,!1);let q=JSON.stringify({kind:X,..._});L=t6(L,W.collapsibleKey,!1);let H=t6(L,W.collapsibleKey,!0),F=JSON.stringify({kind:X,...L});if(J.nodesByHash[F]&&!$)return J.nodesByHash[F];let z={id:Z,kind:X,impl:W,inner:Q,innerEntries:Y,innerJson:_,innerHash:q,meta:U,metaJson:V,json:L,hash:F,collapsibleJson:H,children:G};if(X!=="intersection"){for(let T in Q)if(T!=="in"&&T!=="out")z[T]=Q[T]}let B=new l3[X](z,J);return J.nodesByHash[F]=B},p3=(Z,X)=>{if(Z.id===X)return Z;if(e(A0[X]))d(`Unexpected attempt to overwrite node id ${X}`);return zZ({id:X,kind:Z.kind,inner:Z.inner,meta:Z.meta,$:Z.$,ignoreCache:!0})},DW=(Z,X,Q)=>{if(Q&&e(A0[Q]))d(`Unexpected attempt to overwrite node id ${Q}`);return zZ({id:Q??qZ(X.alias??Z.kind),kind:Z.kind,inner:Z.inner,meta:X,$:Z.$})},t6=(Z,X,Q)=>{let U=Object.keys(Z);if(U.length===1&&U[0]===X){let J=Z[X];if(Q)return J;if(E0(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return Z};var e6=R(()=>{j();Z9();Y0();i();c();_0();u3={},A0={};O.nodesByRegisteredId=A0});var m4=(Z,X,Q)=>{if(Z.key!==X.key)return null;let U=Z.key,J=Z0(Z.value,X.value,Q),$=Z.required||X.required?"required":"optional";if(J instanceof A)if($==="optional")J=O.intrinsic.never.internal;else return J.withPrefixKey(Z.key,Z.required&&X.required?"required":"optional");if($==="required")return Q.$.node("required",{key:U,value:J});let W=Z.hasDefault()?X.hasDefault()?Z.default===X.default?Z.default:M(FZ(Z.default,X.default)):Z.default:X.hasDefault()?X.default:I0;return Q.$.node("optional",{key:U,value:J,default:W})},u4,FZ=(Z,X)=>`Invalid intersection of default values ${k(Z)} & ${k(X)}`;var p4=R(()=>{j();h0();T2();a1();Y0();s0();c();K1();u4=class u4 extends r0{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=O.intrinsic.object.internal;serializedKey=W1(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=u(this.value.flatRefs.map((Z)=>G1([this.key,...Z.path],Z.node)),G1([this.key],this.value));_transform(Z,X){X.path.push(this.key);let Q=super._transform(Z,X);return X.path.pop(),Q}hasDefault(){return"default"in this.inner}traverseAllows=(Z,X)=>{if(this.key in Z)return k0(this.key,()=>this.value.traverseAllows(Z[this.key],X),X);return this.optional};traverseApply=(Z,X)=>{if(this.key in Z)k0(this.key,()=>this.value.traverseApply(Z[this.key],X),X);else if(this.hasKind("required"))X.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.if(`${this.serializedKey} in data`,()=>Z.traverseKey(this.serializedKey,`data${Z.prop(this.key)}`,this.value)),this.hasKind("required"))Z.else(()=>Z.traversalKind==="Apply"?Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Z.return(!1));if(Z.traversalKind==="Allows")Z.return(!0)}}});var PW,d3,l4,wW,AW=(Z)=>{if(!Z.hasDefault())return;let X=`{${Z.compiledKey}: ${Z.value.id} = ${i0(Z.default)}}`;return wW[X]??=BZ(Z.key,Z.value,Z.default)},BZ=(Z,X,Q)=>{if(typeof Q==="function")return X.includesTransform?(J,$)=>{return k0(Z,()=>X(J[Z]=Q(),$),$),J}:(J)=>{return J[Z]=Q(),J};let U=X.includesTransform?X.assert(Q):Q;return E0(U,"object")?(J,$)=>{return k0(Z,()=>X(J[Z]=Q,$),$),J}:(J)=>{return J[Z]=U,J}},d4=(Z,X,Q)=>{let U=s1(X);if(E0(X,"object")&&!U)M(SW(Q));let J=Z.in(U?X():X);if(J instanceof y0){if(Q===null)M(`Default ${J.summary}`);let $=J.transform((W)=>W.transform((Y)=>({...Y,prefixPath:[Q]})));M(`Default for ${$.summary}`)}return X},SW=(Z)=>{return`Non-primitive default ${Z===null?"":typeof Z==="number"?`for value at [${Z}] `:`for ${W1(Z)} `}must be specified as a function like () => ({my: 'object'})`};var u2=R(()=>{j();X9();a1();k4();i();c();K1();p4();PW=g({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,X)=>X.$.parseSchema(Z)},default:{preserveUndefined:!0}},normalize:(Z)=>Z,reduce:(Z,X)=>{if(X.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Z.value.allows(void 0))return X.node("optional",{...Z,value:Z.value.or(I.undefined)},{prereduced:!0})}},defaults:{description:(Z)=>`${Z.compiledKey}?: ${Z.value.description}`},intersections:{optional:m4}});d3=class d3 extends u4{constructor(...Z){super(...Z);if("default"in this.inner)d4(this.value,this.inner.default,this.key)}get rawIn(){let Z=super.rawIn;if(!this.hasDefault())return Z;return this.$.node("optional",g6(Z.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Z,...X}=this.inner;return this.cacheGetter("outProp",this.$.node("required",X,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${k(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=AW(this);defaultValueMorphRef=this.defaultValueMorph&&U0(this.defaultValueMorph)};l4={implementation:PW,Node:d3},wW={}});var o0,CW="Expected a non-empty brand name after #",r3,NW=(Z)=>`JSONSchema target '${Z}' is not supported (must be ${r3.map((X)=>`"${X}"`).join(" or ")})`,c3=(Z)=>{if(!c0(r3,Z))M(NW(Z));return Z},p2=(Z)=>typeof Z==="object"&&!(Z instanceof Date)?{...Z,exclusive:!0}:{rule:Z,exclusive:!0},c4=(Z,X)=>E(X,"root")?E(Z,"root")?Z.extends(X):X.allows(Z):E(Z,"root")?Z.hasUnit(X):X===Z,i3=(Z)=>{if(Z.hasKind("morph"))return null;if(Z.hasKind("intersection"))return Z.inner.structure??(Z.basis?.domain==="object"?Z.$.bindReference(O.intrinsic.emptyStructure):null);if(Z.isBasis()&&Z.domain==="object")return Z.$.bindReference(O.intrinsic.emptyStructure);return null},jW=(Z)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
23
+ ${Z}`,s3=(Z,X)=>`${Z} operand must be an object (was ${X})`;var X2=R(()=>{j();k2();h0();T2();Y0();k4();i();s0();c();_0();u2();o0=class o0 extends v4{constructor(Z,X){super(Z,X);Object.defineProperty(this,w0,{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:(Z)=>{let X=this(Z);if(X instanceof y0)return X;return{value:X}},jsonSchema:{input:(Z)=>this.rawIn.toJsonSchema({target:c3(Z.target),...Z.libraryOptions}),output:(Z)=>this.rawOut.toJsonSchema({target:c3(Z.target),...Z.libraryOptions})}}}as(){return this}brand(Z){if(Z==="")return M(CW);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Z,X){let Q=this.branches.map(Z);return X?.(Q)??Q}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Z={}){let X=x8(this.$.resolvedConfig.toJsonSchema,Z);X.useRefs||=this.isCyclic;let Q=typeof X.dialect==="string"?{$schema:X.dialect}:{};if(Object.assign(Q,this.toJsonSchemaRecurse(X)),X.useRefs){let U=y(this.references,(J,$)=>$.isRoot()&&!$.alwaysExpandJsonSchema?[$.id,$.toResolvedJsonSchema(X)]:[]);if(X.target==="draft-07")Object.assign(Q,{definitions:U});else Q.$defs=U}return Q}toJsonSchemaRecurse(Z){if(Z.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Z.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Z)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Z){let X=this.innerToJsonSchema(Z);return Object.assign(X,this.metaJson)}intersect(Z){let X=this.$.parseDefinition(Z),Q=this.rawIntersect(X);if(Q instanceof A)return Q;return this.$.finalize(Q)}rawIntersect(Z){return g0(this,Z,this.$)}toNeverIfDisjoint(){return this}and(Z){let X=this.intersect(Z);return X instanceof A?X.throw():X}rawAnd(Z){let X=this.rawIntersect(Z);return X instanceof A?X.throw():X}or(Z){let X=this.$.parseDefinition(Z);return this.$.finalize(this.rawOr(X))}rawOr(Z){let X=[...this.branches,...Z.branches];return this.$.node("union",X)}map(Z){return this.$.schema(this.applyStructuralOperation("map",[Z]))}pick(...Z){return this.$.schema(this.applyStructuralOperation("pick",Z))}omit(...Z){return this.$.schema(this.applyStructuralOperation("omit",Z))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.applyStructuralOperation("keyof",[]).reduce((X,Q)=>X.intersect(Q).toNeverIfDisjoint(),O.intrinsic.unknown.internal);if(Z.branches.length===0)M(p8(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Z)}get props(){if(this.branches.length!==1)return M(jW(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Z){let X=this.$.parseDefinition(Z);return this.$.schema(X.distribute((Q)=>this.applyStructuralOperation("merge",[i3(Q)??M(s3("merge",Q.expression))])))}applyStructuralOperation(Z,X){return this.distribute((Q)=>{if(Q.equals(O.intrinsic.object)&&Z!=="merge")return Q;let U=i3(Q);if(!U)M(s3(Z,Q.expression));if(Z==="keyof")return U.keyof();if(Z==="get")return U.get(...X);if(Z==="props")return U.props;let J=Z==="required"?"require":Z==="partial"?"optionalize":Z;return this.$.node("intersection",{domain:"object",structure:U[J](...X)})})}get(...Z){if(Z[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Z))}extract(Z){let X=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((Q)=>Q.extends(X)))}exclude(Z){let X=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((Q)=>!Q.extends(X)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Z){return!(this.intersect(Z)instanceof A)}extends(Z){if(this.isNever())return!0;let X=this.intersect(Z);return!(X instanceof A)&&this.equals(X)}ifExtends(Z){return this.extends(Z)?this:void 0}subsumes(Z){return this.$.parseDefinition(Z).extends(this)}configure(Z,X="shallow"){return this.configureReferences(Z,X)}describe(Z,X="shallow"){return this.configure({description:Z},X)}optional(){return[this,"?"]}default(Z){return d4(this,Z,null),[this,"=",Z]}from(Z){return this.assert(Z)}_pipe(...Z){let X=Z.reduce((Q,U)=>Q.rawPipeOnce(U),this);return this.$.finalize(X)}tryPipe(...Z){let X=Z.reduce((Q,U)=>Q.rawPipeOnce(E(U,"root")?U:(J,$)=>{try{return U(J,$)}catch(W){return $.error({code:"predicate",predicate:U,actual:`aborted due to error:
24
+ ${W}
25
+ `})}}),this);return this.$.finalize(X)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Z){return this.$.finalize(this.toNode(this.$.parseDefinition(Z)))}toNode(Z){let X=x4(this,Z,this.$);if(X instanceof A)return X.throw();return X}rawPipeOnce(Z){if(E(Z,"root"))return this.toNode(Z);return this.distribute((X)=>X.hasKind("morph")?this.$.node("morph",{in:X.inner.in,morphs:[...X.morphs,Z]}):this.$.node("morph",{in:X,morphs:[Z]}),this.$.parseSchema)}narrow(Z){return this.constrainOut("predicate",Z)}constrain(Z,X){return this._constrain("root",Z,X)}constrainIn(Z,X){return this._constrain("in",Z,X)}constrainOut(Z,X){return this._constrain("out",Z,X)}_constrain(Z,X,Q){let U=this.$.node(X,Q);if(U.isRoot())return U.isUnknown()?this:d(`Unexpected constraint node ${U}`);let J=Z==="root"?this:Z==="in"?this.rawIn:this.rawOut;if(J.hasKind("morph")||U.impliedBasis&&!J.extends(U.impliedBasis))return w3(X,U.impliedBasis,this);let $=this.$.node("intersection",{[U.kind]:U}),W=Z==="out"?x4(this,$,this.$):g0(this,$,this.$);if(W instanceof A)W.throw();return this.$.finalize(W)}onUndeclaredKey(Z){let X=typeof Z==="string"?Z:Z.rule,Q=typeof Z==="string"?!1:Z.deep;return this.$.finalize(this.transform((U,J)=>U==="structure"?X==="ignore"?g6(J,{undeclared:1}):{...J,undeclared:X}:J,Q?void 0:{shouldTransform:(U)=>!c0(b2,U.kind)}))}hasEqualMorphs(Z){if(!this.includesTransform&&!Z.includesTransform)return!0;if(!f1(this.shallowMorphs,Z.shallowMorphs))return!1;if(!f1(this.flatMorphs,Z.flatMorphs,{isEqual:(X,Q)=>X.propString===Q.propString&&(X.node.hasKind("morph")&&Q.node.hasKind("morph")?X.node.hasEqualMorphs(Q.node):X.node.hasKind("intersection")&&Q.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Q.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Z){return this.onUndeclaredKey({rule:Z,deep:!0})}filter(Z){return this.constrainIn("predicate",Z)}divisibleBy(Z){return this.constrain("divisor",Z)}matching(Z){return this.constrain("pattern",Z)}atLeast(Z){return this.constrain("min",Z)}atMost(Z){return this.constrain("max",Z)}moreThan(Z){return this.constrain("min",p2(Z))}lessThan(Z){return this.constrain("max",p2(Z))}atLeastLength(Z){return this.constrain("minLength",Z)}atMostLength(Z){return this.constrain("maxLength",Z)}moreThanLength(Z){return this.constrain("minLength",p2(Z))}lessThanLength(Z){return this.constrain("maxLength",p2(Z))}exactlyLength(Z){return this.constrain("exactLength",Z)}atOrAfter(Z){return this.constrain("after",Z)}atOrBefore(Z){return this.constrain("before",Z)}laterThan(Z){return this.constrain("after",p2(Z))}earlierThan(Z){return this.constrain("before",p2(Z))}};r3=["draft-2020-12","draft-07"]});var T1=(Z,X)=>y(i6(Z),(Q,U)=>[U,X]);var l2=R(()=>{j();i()});var EW=(Z)=>typeof Z==="string"?{reference:Z}:Z,o3=(Z)=>Z instanceof A?O.intrinsic.never.internal:Z,bW,a3,IW=(Z,X)=>`Alias '${Z}' has a shallow resolution cycle: ${[...X,Z].join("->")}`,i4;var MZ=R(()=>{j();e6();Y0();i();s0();c();_0();X2();l2();bW=g({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Z)=>Z.startsWith("$")?Z:`$ark.${Z}`},resolve:{}},normalize:EW,defaults:{description:(Z)=>Z.reference},intersections:{alias:(Z,X,Q)=>Q.$.lazilyResolve(()=>o3(Z0(Z.resolution,X.resolution,Q)),`${Z.reference}${Q.pipe?"=>":"&"}${X.reference}`),...T1("alias",(Z,X,Q)=>{if(X.isUnknown())return Z;if(X.isNever())return X;if(X.isBasis()&&!X.overlaps(O.intrinsic.object))return A.init("assignability",O.intrinsic.object,X);return Q.$.lazilyResolve(()=>o3(Z0(Z.resolution,X,Q)),`${Z.reference}${Q.pipe?"=>":"&"}${X.id}`)})}});a3=class a3 extends o0{expression=this.reference;structure=void 0;get resolution(){let Z=this._resolve();return A0[this.id]=Z}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Z=this.reference,X=A0[Z],Q=[];while(E(X,"context")){if(Q.includes(X.id))return M(IW(X.id,Q));Q.push(X.id),X=A0[X.id]}if(!E(X,"root"))return d(`Unexpected resolution for reference ${this.reference}
26
+ Seen: [${Q.join("->")}]
27
+ Resolution: ${k(X)}`);return X}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Z=this.reference.slice(1),X=this.$.resolutions[Z];if(typeof X==="string")return X;if(E(X,"root"))return X.id;return d(`Unexpected resolution for reference ${this.reference}: ${k(X)}`)}get defaultShortDescription(){return b0.object}innerToJsonSchema(Z){return this.resolution.toJsonSchemaRecurse(Z)}traverseAllows=(Z,X)=>{let Q=X.seen[this.reference];if(Q?.includes(Z))return!0;return X.seen[this.reference]=u(Q,Z),this.resolution.traverseAllows(Z,X)};traverseApply=(Z,X)=>{let Q=X.seen[this.reference];if(Q?.includes(Z))return;X.seen[this.reference]=u(Q,Z),this.resolution.traverseApply(Z,X)};compile(Z){let X=this.resolutionId;Z.if(`ctx.seen.${X} && ctx.seen.${X}.includes(data)`,()=>Z.return(!0)),Z.if(`!ctx.seen.${X}`,()=>Z.line(`ctx.seen.${X} = []`)),Z.line(`ctx.seen.${X}.push(data)`),Z.return(Z.invoke(X))}};i4={implementation:bW,Node:a3}});var D2;var Q9=R(()=>{i();X2();D2=class D2 extends o0{traverseApply=(Z,X)=>{if(!this.traverseAllows(Z,X))X.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return n1(this.errorContext)}compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}});var fW,n3,U9;var RZ=R(()=>{j();Y0();i();Q9();fW=g({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Z)=>typeof Z==="string"?{domain:Z}:N2(Z,"numberAllowsNaN")&&Z.domain!=="number"?M(U9.writeBadAllowNanMessage(Z.domain)):Z,applyConfig:(Z,X)=>Z.numberAllowsNaN===void 0&&Z.domain==="number"&&X.numberAllowsNaN?{...Z,numberAllowsNaN:!0}:Z,defaults:{description:(Z)=>b0[Z.domain],actual:(Z)=>Number.isNaN(Z)?"NaN":b0[q0(Z)]},intersections:{domain:(Z,X)=>Z.domain==="number"&&X.domain==="number"?Z.numberAllowsNaN?X:Z:A.init("domain",Z,X)}});n3=class n3 extends D2{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Z)=>typeof Z==="number"&&!Number.isNaN(Z):(Z)=>q0(Z)===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 b0[this.domain]}innerToJsonSchema(Z){if(this.domain==="bigint"||this.domain==="symbol")return Z.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}};U9={implementation:fW,Node:n3,writeBadAllowNanMessage:(Z)=>`numberAllowsNaN may only be specified with domain "number" (was ${Z})`}});var yW,e3,OZ,kW=(Z)=>{if(Z.structure?.expression)return Z.structure.expression;let X=Z.basis&&!Z.prestructurals.some((J)=>J.impl.obviatesBasisExpression)?Z.basis.nestableExpression:"",Q=Z.prestructurals.map((J)=>J.expression).join(" & "),U=`${X}${X?" ":""}${Q}`;if(U==="Array == 0")return"[]";return U||"unknown"},t3=(Z,X,Q)=>{let U={},J=Z.proto??Z.domain,$=X.proto??X.domain,W=J?$?Z0(J,$,Q):J:$;if(W instanceof A)return W;if(W)U[W.kind]=W;return v2({kind:"intersection",baseInner:U,l:x2(Z),r:x2(X),roots:[],ctx:Q})};var KZ=R(()=>{j();h0();Y0();i();s0();_0();X2();l2();yW=g({kind:"intersection",hasAssociatedError:!0,normalize:(Z)=>{if(e(Z))return Z;let{structure:X,...Q}=Z,U=!!X,J=X??{},$=y(Q,(W,Y)=>{if(H0(W,F3)){if(U)M(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return J[W]=Y,[]}return[W,Y]});if(E(J,"constraint")||!O1(J))$.structure=J;return $},finalizeInnerJson:({structure:Z,...X})=>E0(Z,"object")?{...Z,...X}:X,keys:{domain:{child:!0,parse:(Z,X)=>X.$.node("domain",Z)},proto:{child:!0,parse:(Z,X)=>X.$.node("proto",Z)},structure:{child:!0,parse:(Z,X)=>X.$.node("structure",Z),serialize:(Z)=>{if(!Z.sequence?.minLength)return Z.collapsibleJson;let{sequence:X,...Q}=Z.collapsibleJson,{minVariadicLength:U,...J}=X,$=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{...Q,sequence:$}}},divisor:{child:!0,parse:O0("divisor")},max:{child:!0,parse:O0("max")},min:{child:!0,parse:O0("min")},maxLength:{child:!0,parse:O0("maxLength")},minLength:{child:!0,parse:O0("minLength")},exactLength:{child:!0,parse:O0("exactLength")},before:{child:!0,parse:O0("before")},after:{child:!0,parse:O0("after")},pattern:{child:!0,parse:O0("pattern")},predicate:{child:!0,parse:O0("predicate")}},reduce:(Z,X)=>t3({},Z,{$:X,invert:!1,pipe:!1}),defaults:{description:(Z)=>{if(Z.children.length===0)return"unknown";if(Z.structure)return Z.structure.description;let X=[];if(Z.basis&&!Z.prestructurals.some((Q)=>Q.impl.obviatesBasisDescription))X.push(Z.basis.description);if(Z.prestructurals.length){let Q=Z.prestructurals.slice().sort((U,J)=>U.kind==="min"&&J.kind==="max"?-1:0).map((U)=>U.description);X.push(...Q)}if(Z.inner.predicate)X.push(...Z.inner.predicate.map((Q)=>Q.description));return X.join(" and ")},expected:(Z)=>` ◦ ${Z.errors.map((X)=>X.expected).join(`
28
+ `)}`,problem:(Z)=>`(${Z.actual}) must be...
29
+ ${Z.expected}`},intersections:{intersection:(Z,X,Q)=>t3(Z.inner,X.inner,Q),...T1("intersection",(Z,X,Q)=>{if(Z.children.length===0)return X;let{domain:U,proto:J,...$}=Z.inner,W=J??U,Y=W?Z0(W,X,Q):X;return Y instanceof A?Y:Z?.basis?.equals(Y)?Z:Z.$.node("intersection",{...$,[Y.kind]:Y},{prereduced:!0})})}});e3=class e3 extends o0{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((Z)=>{if(!Z.isRefinement())return!1;if(c0(g8,Z.kind))this.prestructurals.push(Z);return!0});structure=this.inner.structure;expression=kW(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Z){return this.children.reduce((X,Q)=>Q.isBasis()?Q.toJsonSchemaRecurse(Z):Q.reduceJsonSchema(X,Z),{})}traverseAllows=(Z,X)=>this.children.every((Q)=>Q.traverseAllows(Z,X));traverseApply=(Z,X)=>{let Q=X.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Z,X),X.currentErrorCount>Q)return}if(this.prestructurals.length){for(let U=0;U<this.prestructurals.length-1;U++)if(this.prestructurals[U].traverseApply(Z,X),X.failFast&&X.currentErrorCount>Q)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(Z,X),X.currentErrorCount>Q)return}if(this.structure){if(this.structure.traverseApply(Z,X),X.currentErrorCount>Q)return}if(this.inner.predicate){for(let U=0;U<this.inner.predicate.length-1;U++)if(this.inner.predicate[U].traverseApply(Z,X),X.failFast&&X.currentErrorCount>Q)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(Z,X)}};compile(Z){if(Z.traversalKind==="Allows"){for(let X of this.children)Z.check(X);Z.return(!0);return}if(Z.initializeErrorCount(),this.basis){if(Z.check(this.basis),this.children.length>1)Z.returnIfFail()}if(this.prestructurals.length){for(let X=0;X<this.prestructurals.length-1;X++)Z.check(this.prestructurals[X]),Z.returnIfFailFast();if(Z.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)Z.returnIfFail()}if(this.structure){if(Z.check(this.structure),this.inner.predicate)Z.returnIfFail()}if(this.inner.predicate){for(let X=0;X<this.inner.predicate.length-1;X++)Z.check(this.inner.predicate[X]),Z.returnIfFail();Z.check(this.inner.predicate[this.inner.predicate.length-1])}}};OZ={implementation:yW,Node:e3}});var gW,ZQ,TZ,vW=(Z,X)=>`The intersection of distinct morphs at a single path is indeterminate:
30
+ Left: ${Z}
31
+ Right: ${X}`;var DZ=R(()=>{j();Y0();i();s0();c();_0();X2();l2();gW=g({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Z,X)=>X.$.parseSchema(Z)},morphs:{parse:i1,serialize:(Z)=>Z.map((X)=>E(X,"root")?X.json:U0(X))},declaredIn:{child:!1,serialize:(Z)=>Z.json},declaredOut:{child:!1,serialize:(Z)=>Z.json}},normalize:(Z)=>Z,defaults:{description:(Z)=>`a morph from ${Z.rawIn.description} to ${Z.rawOut?.description??"unknown"}`},intersections:{morph:(Z,X,Q)=>{if(!Z.hasEqualMorphs(X))return M(vW(Z.expression,X.expression));let U=Z0(Z.rawIn,X.rawIn,Q);if(U instanceof A)return U;let J={morphs:Z.morphs};if(Z.declaredIn||X.declaredIn){let $=Z0(Z.rawIn,X.rawIn,Q);if($ instanceof A)return $.throw();else J.declaredIn=$}if(Z.declaredOut||X.declaredOut){let $=Z0(Z.rawOut,X.rawOut,Q);if($ instanceof A)return $.throw();else J.declaredOut=$}return U.distribute(($)=>Q.$.node("morph",{...J,in:$}),Q.$.parseSchema)},...T1("morph",(Z,X,Q)=>{let U=Z.inner.in?Z0(Z.inner.in,X,Q):X;return U instanceof A?U:U.equals(Z.inner.in)?Z:Q.$.node("morph",{...Z.inner,in:U})})}});ZQ=class ZQ extends o0{serializedMorphs=this.morphs.map(U0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=E(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??O.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??O.intrinsic.unknown.internal}declareIn(Z){return this.$.node("morph",{...this.inner,declaredIn:Z})}declareOut(Z){return this.$.node("morph",{...this.inner,declaredOut:Z})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(Z){return Z.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(Z),out:this.introspectableOut?.toJsonSchemaRecurse(Z)??null})}compile(Z){if(Z.traversalKind==="Allows"){if(!this.introspectableIn)return;Z.return(Z.invoke(this.introspectableIn));return}if(this.introspectableIn)Z.line(Z.invoke(this.introspectableIn));Z.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Z,X)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Z,X);traverseApply=(Z,X)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Z,X);X.queueMorphs(this.morphs)};hasEqualMorphs(Z){return f1(this.morphs,Z.morphs,{isEqual:(X,Q)=>X===Q||E(X,"root")&&E(Q,"root")&&X.equals(Q)})}};TZ={implementation:gW,Node:ZQ}});var xW,XQ,s4;var PZ=R(()=>{j();Y0();i();c();_0();Q9();xW=g({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Z)=>A4(Z)??i0(Z)},dateAllowsInvalid:{}},normalize:(Z)=>{let X=typeof Z==="string"?{proto:M2[Z]}:typeof Z==="function"?e(Z)?Z:{proto:Z}:typeof Z.proto==="string"?{...Z,proto:M2[Z.proto]}:Z;if(typeof X.proto!=="function")M(s4.writeInvalidSchemaMessage(X.proto));if(N2(X,"dateAllowsInvalid")&&X.proto!==Date)M(s4.writeBadInvalidDateMessage(X.proto));return X},applyConfig:(Z,X)=>{if(Z.dateAllowsInvalid===void 0&&Z.proto===Date&&X.dateAllowsInvalid)return{...Z,dateAllowsInvalid:!0};return Z},defaults:{description:(Z)=>Z.builtinName?I7[Z.builtinName]:`an instance of ${Z.proto.name}`,actual:(Z)=>Z instanceof Date&&Z.toString()==="Invalid Date"?"an invalid Date":w4(Z)},intersections:{proto:(Z,X)=>Z.proto===Date&&X.proto===Date?Z.dateAllowsInvalid?X:Z:C8(Z.proto,X.proto)?Z:C8(X.proto,Z.proto)?X:A.init("proto",Z,X),domain:(Z,X)=>X.domain==="object"?Z:A.init("domain",O.intrinsic.object.internal,X)}});XQ=class XQ extends D2{builtinName=A4(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Z)=>Z instanceof Date&&Z.toString()!=="Invalid Date":(Z)=>Z instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Z){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Z.fallback.date?.({code:"date",base:{}})??Z.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Z.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}};s4={implementation:xW,Node:XQ,writeBadInvalidDateMessage:(Z)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Z.name})`,writeInvalidSchemaMessage:(Z)=>`instanceOf operand must be a function (was ${q0(Z)})`}});var hW,JQ,mW=(Z,X)=>{let U=Z.sort((W,Y)=>W.path.length===Y.path.length?Object.keys(Y.cases).length-Object.keys(W.cases).length:W.path.length-Y.path.length)[0],J={kind:U.kind,path:U.path,optionallyChainedPropString:$Q(U.path)},$=X.branches.map((W,Y)=>({originalIndex:Y,branch:W}));return{best:U,location:J,defaultEntries:$,node:X}},uW=(Z,X)=>{let Q=Z.best.cases[X],U=lW(Q.condition,Z.location.path,Z.node.$),J=[],$=[];for(let W=0;W<Z.defaultEntries.length;W++){let Y=Z.defaultEntries[W];if(Q.branchIndices.includes(Y.originalIndex)){let G=QQ(Z.node.branches[Y.originalIndex],Z.location);if(G===null)J=null;else J?.push({originalIndex:Y.originalIndex,branch:G})}else if(Y.branch.hasKind("alias")&&U.hasKind("domain")&&U.domain==="object")J?.push(Y);else{if(Y.branch.rawIn.overlaps(U)){let G=QQ(Y.branch,Z.location);J?.push({originalIndex:Y.originalIndex,branch:G})}$.push(Y)}}return Z.defaultEntries=$,J},pW=(Z,X)=>{return Z.filter((U)=>{let J=Object.values(U.cases).map(($)=>$.branchIndices);for(let $=0;$<J.length-1;$++){let W=J[$];for(let Y=$+1;Y<J.length;Y++){let G=J[Y];for(let _ of W)for(let L of G)if(_>L){if(X[_].overlaps(X[L]))return!1}}}return!0})},lW=(Z,X,Q)=>{let U=Z==="undefined"?Q.node("unit",{unit:void 0}):Z==="null"?Q.node("unit",{unit:null}):Z==="boolean"?Q.units([!0,!1]):Z;for(let J=X.length-1;J>=0;J--){let $=X[J];U=Q.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...D7($).map((W)=>({})),U]}:{domain:"object",required:[{key:$,value:U}]})}return U},$Q=(Z)=>Z.reduce((X,Q)=>X+k8(Q,!0),"data"),dW,cW,AZ,iW=(Z)=>({kind:Z.kind,path:Z.path.map((X)=>typeof X==="string"?X:W1(X)),cases:y(Z.cases,(X,Q)=>[X,Q===!0?Q:Q.hasKind("union")&&Q.discriminantJson?Q.discriminantJson:Q.json])}),sW,rW=(Z)=>d2(Z,sW),d2=(Z,X)=>{let Q=X?.delimiter??", ",U=X?.finalDelimiter??" or ";if(Z.length===0)return"never";if(Z.length===1)return Z[0];if(Z.length===2&&Z[0]==="false"&&Z[1]==="true"||Z[0]==="true"&&Z[1]==="false")return"boolean";let J={},$=Z.filter((Y)=>J[Y]?!1:J[Y]=!0),W=$.pop();return`${$.join(Q)}${$.length?U:""}${W}`},wZ=(Z,X,Q)=>{let U=X.map(()=>[]);for(let $=0;$<Z.length;$++){let W={};for(let Y=0;Y<X.length;Y++){if(U[Y]===null)continue;if(Z[$].equals(X[Y])){U[Y]=null,W={};break}let G=Z0(Z[$],X[Y],Q);if(G instanceof A)continue;if(G.equals(Z[$])){U[Y].push(Z[$]),W={};break}if(G.equals(X[Y]))U[Y]=null;else W[Y]=G}for(let Y in W)U[Y][$]=W[Y]}let J=U.flatMap(($,W)=>$?.flatMap((Y)=>Y.branches)??X[W]);return J.length===0?A.init("union",Z,X):J},oW=({branches:Z,ordered:X})=>{if(Z.length<2)return Z;let Q=Z.map(()=>!0);for(let U=0;U<Z.length;U++)for(let J=U+1;J<Z.length&&Q[U]&&Q[J];J++){if(Z[U].equals(Z[J])){Q[J]=!1;continue}let $=g0(Z[U].rawIn,Z[J].rawIn,Z[0].$);if($ instanceof A)continue;if(!X)aW(Z[U],Z[J]);if($.equals(Z[U].rawIn))Q[U]=!!X;else if($.equals(Z[J].rawIn))Q[J]=!1}return Z.filter((U,J)=>Q[J])},aW=(Z,X)=>{if(!Z.includesTransform&&!X.includesTransform)return;if(!f1(Z.shallowMorphs,X.shallowMorphs))M(UQ(Z.expression,X.expression));if(!f1(Z.flatMorphs,X.flatMorphs,{isEqual:(Q,U)=>Q.propString===U.propString&&(Q.node.hasKind("morph")&&U.node.hasKind("morph")?Q.node.hasEqualMorphs(U.node):Q.node.hasKind("intersection")&&U.node.hasKind("intersection")?Q.node.structure?.structuralMorphRef===U.node.structure?.structuralMorphRef:!1)}))M(UQ(Z.expression,X.expression))},QQ=(Z,X)=>Z.transform((Q,U)=>{if(Q==="domain"||Q==="unit")return null;return U},{shouldTransform:(Q,U)=>{let J=$Q(U.path);if(!X.optionallyChainedPropString.startsWith(J))return!1;if(Q.hasKind("domain")&&Q.domain==="object")return!0;if((Q.hasKind("domain")||X.kind==="unit")&&J===X.optionallyChainedPropString)return!0;return Q.children.length!==0&&Q.kind!=="index"}}),UQ=(Z,X)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
32
+ Left: ${Z}
33
+ Right: ${X}`,nW=(Z,X)=>`The intersection of two ordered unions is indeterminate:
34
+ Left: ${Z}
35
+ Right: ${X}`;var SZ=R(()=>{j();a1();Y0();i();s0();c();K1();_0();X2();l2();hW=g({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Z,X)=>{let Q=[];for(let U of Z){let J=E(U,"root")?U.branches:X.$.parseSchema(U).branches;for(let $ of J)if($.hasKind("morph")){let W=Q.findIndex((Y)=>Y.hasKind("morph")&&Y.hasEqualMorphs($));if(W===-1)Q.push($);else{let Y=Q[W];Q[W]=X.$.node("morph",{...Y.inner,in:Y.rawIn.rawOr($.rawIn)})}}else Q.push($)}if(!X.def.ordered)Q.sort((U,J)=>U.hash<J.hash?-1:1);return Q}}},normalize:(Z)=>t(Z)?{branches:Z}:Z,reduce:(Z,X)=>{let Q=oW(Z);if(Q.length===1)return Q[0];if(Q.length===Z.branches.length)return;return X.node("union",{...Z,branches:Q},{prereduced:!0})},defaults:{description:(Z)=>Z.distribute((X)=>X.description,d2),expected:(Z)=>{let X=w7(Z.errors,"propString"),Q=Object.entries(X).map(([U,J])=>{let $=[];for(let G of J)M1($,G.expected);let W=d2($),Y=J.every((G)=>G.actual===J[0].actual)?J[0].actual:k(J[0].data);return`${U&&`${U} `}must be ${W}${Y&&` (was ${Y})`}`});return d2(Q)},problem:(Z)=>Z.expected,message:(Z)=>{if(Z.problem[0]==="[")return`value at ${Z.problem}`;return Z.problem}},intersections:{union:(Z,X,Q)=>{if(Z.isNever!==X.isNever)return A.init("presence",Z,X);let U;if(Z.ordered){if(X.ordered)M(nW(Z.expression,X.expression));if(U=wZ(X.branches,Z.branches,Q),U instanceof A)U.invert()}else U=wZ(Z.branches,X.branches,Q);if(U instanceof A)return U;return Q.$.parseSchema(Z.ordered||X.ordered?{branches:U,ordered:!0}:{branches:U})},...T1("union",(Z,X,Q)=>{let U=wZ(Z.branches,[X],Q);if(U instanceof A)return U;if(U.length===1)return U[0];return Q.$.parseSchema(Z.ordered?{branches:U,ordered:!0}:{branches:U})})}});JQ=class JQ extends o0{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Z=[],X=-1;for(let Q of this.branches){if(Q.hasKind("unit")&&Q.domain==="boolean"){if(X===-1)X=Z.length,Z.push(Q);else Z[X]=O.intrinsic.boolean;continue}Z.push(Q)}return Z}unitBranches=this.branches.filter((Z)=>Z.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?iW(this.discriminant):null;expression=this.distribute((Z)=>Z.nestableExpression,rW);createBranchedOptimisticRootApply(){return(Z,X)=>{let Q=this.traverseOptimistic(Z);if(Q!==I0)return Q;let U=new Y1(Z,this.$.resolvedConfig);return this.traverseApply(Z,U),U.finalize(X)}}get shallowMorphs(){return this.branches.reduce((Z,X)=>M1(Z,X.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Z)=>Z.defaultShortDescription,d2)}innerToJsonSchema(Z){if(this.branchGroups.length===1&&this.branchGroups[0].equals(O.intrinsic.boolean))return{type:"boolean"};let X=this.branchGroups.map((Q)=>Q.toJsonSchemaRecurse(Z));if(X.every((Q)=>Object.keys(Q).length===1&&N2(Q,"const")))return{enum:X.map((Q)=>Q.const)};return{anyOf:X}}traverseAllows=(Z,X)=>this.branches.some((Q)=>Q.traverseAllows(Z,X));traverseApply=(Z,X)=>{let Q=[];for(let U=0;U<this.branches.length;U++){if(X.pushBranch(),this.branches[U].traverseApply(Z,X),!X.hasError()){if(this.branches[U].includesTransform)return X.queuedMorphs.push(...X.popBranch().queuedMorphs);return X.popBranch()}Q.push(X.popBranch().error)}X.errorFromNodeContext({code:"union",errors:Q,meta:this.meta})};traverseOptimistic=(Z)=>{for(let X=0;X<this.branches.length;X++){let Q=this.branches[X];if(Q.traverseAllows(Z)){if(Q.contextFreeMorph)return Q.contextFreeMorph(Z);return Z}}return I0};compile(Z){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Z);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 Q=this.discriminant.cases,U=Object.keys(Q),{optimistic:J}=Z;if(Z.optimistic=!1,Z.block(`switch(${X})`,()=>{for(let _ in Q){let L=Q[_],V=_==="default"?_:`case ${_}`,q;if(L===!0)q=J?"data":"true";else if(J)if(L.rootApplyStrategy==="branchedOptimistic")q=Z.invoke(L,{kind:"Optimistic"});else if(L.contextFreeMorph)q=`${Z.invoke(L)} ? ${U0(L.contextFreeMorph)}(data) : "${I0}"`;else q=`${Z.invoke(L)} ? data : "${I0}"`;else q=Z.invoke(L);Z.line(`${V}: return ${q}`)}return Z}),Z.traversalKind==="Allows"){Z.return(J?`"${I0}"`:!1);return}let $=d2(this.discriminant.kind==="domain"?U.map((_)=>{let L=_.slice(1,-1);return L==="function"?b0.object:b0[L]}):U),W=this.discriminant.path.map((_)=>typeof _==="symbol"?U0(_):JSON.stringify(_)),Y=JSON.stringify($),G=this.discriminant.kind==="domain"?`${dW}[${X}]`:`${cW}(${X})`;Z.line(`ctx.errorFromNodeContext({
32
36
  code: "predicate",
33
- expected: ${J},
34
- actual: ${H},
35
- relativePath: [${G}],
37
+ expected: ${Y},
38
+ actual: ${G},
39
+ relativePath: [${W}],
36
40
  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 U of this.branches)Q.if(`${Q.invoke(U)}`,()=>Q.return(X?U.contextFreeMorph?`${S(U.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=B(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 $,O;if(_.kind==="domain"){let{l:b,r:F1}=_;$=`"${typeof b==="string"?b:b.domain}"`,O=`"${typeof F1==="string"?F1:F1.domain}"`}else if(_.kind==="unit")$=_.l.serializedValue,O=_.r.serializedValue;else continue;let R=Q.find((b)=>$1(b.path,_.path)&&b.kind===_.kind);if(!R)Q.push({kind:_.kind,cases:{[$]:{branchIndices:[Z],condition:_.l},[O]:{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[O])R.cases[O].branchIndices=J1(R.cases[O].branchIndices,G);else R.cases[O]??={branchIndices:[G],condition:_.r}}}}}let X=this.ordered?sZ(Q,this.branches):Q;if(!X.length)return null;let U=oZ(X,this),Y={};for(let Z in U.best.cases){let W=iZ(U,Z);if(W===null){Y[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),Y[Z]=J}if(U.defaultEntries.length){let Z=U.defaultEntries.map((W)=>W.branch);Y.default=this.$.node("union",this.ordered?{branches:Z,ordered:!0}:Z,{prereduced:!0}),Object.assign(this.referencesById,Y.default.referencesById)}return Object.assign(U.location,{cases:Y})}}var oZ=(Q,X)=>{let Y=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:Y.kind,path:Y.path,optionallyChainedPropString:M4(Y.path)},W=X.branches.map((G,J)=>({originalIndex:J,branch:G}));return{best:Y,location:Z,defaultEntries:W,node:X}},iZ=(Q,X)=>{let U=Q.best.cases[X],Y=rZ(U.condition,Q.location.path,Q.node.$),Z=[],W=[];for(let G=0;G<Q.defaultEntries.length;G++){let J=Q.defaultEntries[G];if(U.branchIndices.includes(J.originalIndex)){let H=O4(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")&&Y.hasKind("domain")&&Y.domain==="object")Z?.push(J);else{if(J.branch.rawIn.overlaps(Y)){let H=O4(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((Y)=>{let Z=Object.values(Y.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,U)=>{let Y=Q==="undefined"?U.node("unit",{unit:void 0}):Q==="null"?U.node("unit",{unit:null}):Q==="boolean"?U.units([!0,!1]):Q;for(let Z=X.length-1;Z>=0;Z--){let W=X[Z];Y=U.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...sQ(W).map((G)=>({})),Y]}:{domain:"object",required:[{key:W,value:Y}]})}return Y},M4=(Q)=>Q.reduce((X,U)=>X+y6(U,!0),"data"),nZ=S(tQ),tZ=S(T),JQ={implementation:cZ,Node:T4},aZ=(Q)=>({kind:Q.kind,path:Q.path.map((X)=>typeof X==="string"?X:U1(X)),cases:B(Q.cases,(X,U)=>[X,U===!0?U:U.hasKind("union")&&U.discriminantJson?U.discriminantJson:U.json])}),eZ={delimiter:" | ",finalDelimiter:" | "},Q3=(Q)=>r1(Q,eZ),r1=(Q,X)=>{let U=X?.delimiter??", ",Y=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(U)}${W.length?Y:""}${G}`},GQ=(Q,X,U)=>{let Y=X.map(()=>[]);for(let W=0;W<Q.length;W++){let G={};for(let J=0;J<X.length;J++){if(Y[J]===null)continue;if(Q[W].equals(X[J])){Y[J]=null,G={};break}let H=N(Q[W],X[J],U);if(H instanceof q)continue;if(H.equals(Q[W])){Y[J].push(Q[W]),G={};break}if(H.equals(X[J]))Y[J]=null;else G[J]=H}for(let J in G)Y[J][W]=G[J]}let Z=Y.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 U=Q.map(()=>!0);for(let Y=0;Y<Q.length;Y++)for(let Z=Y+1;Z<Q.length&&U[Y]&&U[Z];Z++){if(Q[Y].equals(Q[Z])){U[Z]=!1;continue}let W=s(Q[Y].rawIn,Q[Z].rawIn,Q[0].$);if(W instanceof q)continue;if(!X)U3(Q[Y],Q[Z]);if(W.equals(Q[Y].rawIn))U[Y]=!!X;else if(W.equals(Q[Z].rawIn))U[Z]=!1}return Q.filter((Y,Z)=>U[Z])},U3=(Q,X)=>{if(!Q.includesTransform&&!X.includesTransform)return;if(!$1(Q.shallowMorphs,X.shallowMorphs))L(B4(Q.expression,X.expression));if(!$1(Q.flatMorphs,X.flatMorphs,{isEqual:(U,Y)=>U.propString===Y.propString&&(U.node.hasKind("morph")&&Y.node.hasKind("morph")?U.node.hasEqualMorphs(Y.node):U.node.hasKind("intersection")&&Y.node.hasKind("intersection")?U.node.structure?.structuralMorphRef===Y.node.structure?.structuralMorphRef:!1)}))L(B4(Q.expression,X.expression))},O4=(Q,X)=>Q.transform((U,Y)=>{if(U==="domain"||U==="unit")return null;return Y},{shouldTransform:(U,Y)=>{let Z=M4(Y.path);if(!X.optionallyChainedPropString.startsWith(Z))return!1;if(U.hasKind("domain")&&U.domain==="object")return!0;if((U.hasKind("domain")||X.kind==="unit")&&Z===X.optionallyChainedPropString)return!0;return U.children.length!==0&&U.kind!=="index"}}),B4=(Q,X)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
38
- Left: ${Q}
39
- Right: ${X}`,Y3=(Q,X)=>`The intersection of two ordered unions is indeterminate:
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),...H1("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 L(J3(U.expression));let Y=U.branches.filter((Z)=>Z.hasKind("unit"));if(Y.length)return L(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 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=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 LQ={implementation:_3,Node:C4};var H3=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 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 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 L3={},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+="]",L3[U]??=X},FQ={implementation:H3,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 H=N(X.node,Y.node,Q.ctx);if(H instanceof q)if(J==="prefix"||J==="postfix")Q.disjoint.push(...H.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)L(UQ(X.default,Y.default));Q.result=[...Q.result,{kind:J,node:H,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:H}];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 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,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 H=X.keyof();for(let _ of Q.requiredKeys)if(!H.allows(_))W.add("presence",Q.propsByKey[_].value,F.intrinsic.never.internal,{path:[_]});if(Y.optional)Y.optional=Y.optional.filter((_)=>H.allows(_.key));if(Y.index)Y.index=Y.index.flatMap((_)=>{if(_.signature.extends(H))return _;let $=s(H,_.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)L(E4(G.key));if(U[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 U)L(E4(G.key));if(U[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,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 L(`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 L(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 L(D3(Z.expression,this.sequence.expression));return L(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 H=1;H<G.length;H++)W=X.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:G[H].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)`,(H)=>H.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:LQ.implementation,optional:w2.implementation,index:HQ.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:LQ.Node,optional:w2.Node,index:HQ.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)=>L(`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},
42
- ${G},
43
- `;if(!U.hasKind("union"))return J;let H=new O2({kind:"Allows",optimistic:!0}).indent();U.compile(H);let _=H.write(`${U.id}Optimistic`);return`${J}${_},
41
+ })`)}compileIndiscriminable(Z){if(Z.traversalKind==="Apply"){Z.const("errors","[]");for(let X of this.branches)Z.line("ctx.pushBranch()").line(Z.invoke(X)).if("!ctx.hasError()",()=>Z.return(X.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Z.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:X}=Z;Z.optimistic=!1;for(let Q of this.branches)Z.if(`${Z.invoke(Q)}`,()=>Z.return(X?Q.contextFreeMorph?`${U0(Q.contextFreeMorph)}(data)`:"data":!0));Z.return(X?`"${I0}"`:!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 J=y(this.unitBranches,($,W)=>[`${W.rawIn.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let Z=[];for(let J=0;J<this.branches.length-1;J++){let $=this.branches[J];for(let W=J+1;W<this.branches.length;W++){let Y=this.branches[W],G=g0($.rawIn,Y.rawIn,$.$);if(!(G instanceof A))continue;for(let _ of G){if(!_.kind||_.optional)continue;let L,V;if(_.kind==="domain"){let{l:H,r:F}=_;L=`"${typeof H==="string"?H:H.domain}"`,V=`"${typeof F==="string"?F:F.domain}"`}else if(_.kind==="unit")L=_.l.serializedValue,V=_.r.serializedValue;else continue;let q=Z.find((H)=>f1(H.path,_.path)&&H.kind===_.kind);if(!q)Z.push({kind:_.kind,cases:{[L]:{branchIndices:[J],condition:_.l},[V]:{branchIndices:[W],condition:_.r}},path:_.path});else{if(q.cases[L])q.cases[L].branchIndices=M1(q.cases[L].branchIndices,J);else q.cases[L]??={branchIndices:[J],condition:_.l};if(q.cases[V])q.cases[V].branchIndices=M1(q.cases[V].branchIndices,W);else q.cases[V]??={branchIndices:[W],condition:_.r}}}}}let X=this.ordered?pW(Z,this.branches):Z;if(!X.length)return null;let Q=mW(X,this),U={};for(let J in Q.best.cases){let $=uW(Q,J);if($===null){U[J]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((G,_)=>G.originalIndex-_.originalIndex);let W=$.map((G)=>G.branch),Y=W.length===1?W[0]:this.$.node("union",this.ordered?{branches:W,ordered:!0}:W);Object.assign(this.referencesById,Y.referencesById),U[J]=Y}if(Q.defaultEntries.length){let J=Q.defaultEntries.map(($)=>$.branch);U.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,U.default.referencesById)}return Object.assign(Q.location,{cases:U})}};dW=U0(A7),cW=U0(k),AZ={implementation:hW,Node:JQ},sW={delimiter:" | ",finalDelimiter:" | "}});var tW,YQ,CZ,WQ=(Z,X,Q)=>{if(Z instanceof Date){let U=`data instanceof Date && data.toISOString() === ${X}`;return Q?`!(${U})`:U}if(Number.isNaN(Z))return`${Q?"!":""}Number.isNaN(data)`;return`data ${Q?"!":"="}== ${X}`};var NZ=R(()=>{j();Y0();i();c();Q9();l2();tW=g({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Z)=>Z instanceof Date?Z.toISOString():i0(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>k(Z.unit),problem:({expected:Z,actual:X})=>`${Z===X?`must be reference equal to ${Z} (serialized to the same value)`:`must be ${Z} (was ${X})`}`},intersections:{unit:(Z,X)=>A.init("unit",Z,X),...T1("unit",(Z,X)=>{if(X.allows(Z.unit))return Z;let Q=X.hasKind("intersection")?X.basis:X;if(Q){let U=Q.hasKind("domain")?Q:O.intrinsic.object;if(Z.domain!==U.domain){let J=Z.domain==="undefined"||Z.domain==="null"||Z.domain==="boolean"?Z.domain:O.intrinsic[Z.domain];return A.init("domain",J,U)}}return A.init("assignability",Z,X.hasKind("intersection")?X.children.find((U)=>!U.allows(Z.unit)):X)})}});YQ=class YQ extends D2{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=WQ(this.unit,this.serializedValue);compiledNegation=WQ(this.unit,this.serializedValue,"negated");expression=k(this.unit);domain=q0(this.unit);get defaultShortDescription(){return this.domain==="object"?b0.object:this.description}innerToJsonSchema(Z){return this.unit===null?{type:"null"}:O.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Z.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Z)=>Z instanceof Date&&Z.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Z)=>Number.isNaN(Z):(Z)=>Z===this.unit};CZ={implementation:tW,Node:YQ}});var eW,GQ,jZ,ZY=(Z)=>`Index keys ${Z.join(", ")} should be specified as named props.`,XY=(Z)=>`Indexed key definition '${Z}' must be a string or symbol`;var EZ=R(()=>{j();h0();T2();Y0();i();s0();c();K1();eW=g({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Z,X)=>{let Q=X.$.parseSchema(Z);if(!Q.extends(O.intrinsic.key))return M(XY(Q.expression));let U=Q.branches.filter((J)=>J.hasKind("unit"));if(U.length)return M(ZY(U.map((J)=>k(J.unit))));return Q}},value:{child:!0,parse:(Z,X)=>X.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`[${Z.signature.expression}]: ${Z.value.description}`},intersections:{index:(Z,X,Q)=>{if(Z.signature.equals(X.signature)){let U=Z0(Z.value,X.value,Q),J=U instanceof A?O.intrinsic.never.internal:U;return Q.$.node("index",{signature:Z.signature,value:J})}if(Z.signature.extends(X.signature)&&Z.value.subsumes(X.value))return X;if(X.signature.extends(Z.signature)&&X.value.subsumes(Z.value))return Z;return null}}});GQ=class GQ extends r0{impliedBasis=O.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=u(this.value.flatRefs.map((Z)=>G1([this.signature,...Z.path],Z.node)),G1([this.signature],this.value));traverseAllows=(Z,X)=>B2(Z).every((Q)=>{if(this.signature.traverseAllows(Q[0],X))return k0(Q[0],()=>this.value.traverseAllows(Q[1],X),X);return!0});traverseApply=(Z,X)=>{for(let Q of B2(Z))if(this.signature.traverseAllows(Q[0],X))k0(Q[0],()=>this.value.traverseApply(Q[1],X),X)};_transform(Z,X){X.path.push(this.signature);let Q=super._transform(Z,X);return X.path.pop(),Q}compile(){}};jZ={implementation:eW,Node:GQ}});var QY,_Q,bZ;var IZ=R(()=>{i();p4();QY=g({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,X)=>X.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`${Z.compiledKey}: ${Z.value.description}`,expected:(Z)=>Z.missingValueDescription,actual:()=>"missing"},intersections:{required:m4,optional:m4}});_Q=class _Q extends u4{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=n1(this.errorContext)};bZ={implementation:QY,Node:_Q}});var UY,qQ,JY,$Y=(Z)=>{if(!Z.defaultables)return[];let X=[],Q="[",U=Z.prefixLength+Z.defaultablesLength-1;for(let J=Z.prefixLength;J<=U;J++){let[$,W]=Z.defaultables[J-Z.prefixLength];X.push(BZ(J,$,W)),Q+=`${J}: ${$.id} = ${i0(W)}, `}return Q+="]",JY[Q]??=X},fZ,WY=(Z)=>{let X=[];if(Z.prefix)for(let Q of Z.prefix)X.push({kind:"prefix",node:Q});if(Z.defaultables)for(let[Q,U]of Z.defaultables)X.push({kind:"defaultables",node:Q,default:U});if(Z.optionals)for(let Q of Z.optionals)X.push({kind:"optionals",node:Q});if(Z.variadic)X.push({kind:"variadic",node:Z.variadic});if(Z.postfix)for(let Q of Z.postfix)X.push({kind:"postfix",node:Q});return X},LQ=(Z)=>Z.reduce((X,Q)=>{if(Q.kind==="variadic")X.variadic=Q.node;else if(Q.kind==="defaultables")X.defaultables=u(X.defaultables,[[Q.node,Q.default]]);else X[Q.kind]=u(X[Q.kind],Q.node);return X},{}),yZ="A postfix required element cannot follow an optional or defaultable element",YY="A postfix element requires a variadic element",r4=(Z)=>{let[X,...Q]=Z.l,[U,...J]=Z.r;if(!X||!U)return Z;let $=Q[Q.length-1]?.kind==="postfix",W=J[J.length-1]?.kind==="postfix",Y=X.kind==="prefix"||U.kind==="prefix"?"prefix":X.kind==="postfix"||U.kind==="postfix"?"postfix":X.kind==="variadic"&&U.kind==="variadic"?"variadic":$||W?"prefix":X.kind==="defaultables"||U.kind==="defaultables"?"defaultables":"optionals";if(X.kind==="prefix"&&U.kind==="variadic"&&W){let V=r4({...Z,fixedVariants:[],r:J.map((q)=>({...q,kind:"prefix"}))});if(V.disjoint.length===0)Z.fixedVariants.push(V)}else if(U.kind==="prefix"&&X.kind==="variadic"&&$){let V=r4({...Z,fixedVariants:[],l:Q.map((q)=>({...q,kind:"prefix"}))});if(V.disjoint.length===0)Z.fixedVariants.push(V)}let G=Z0(X.node,U.node,Z.ctx);if(G instanceof A)if(Y==="prefix"||Y==="postfix")Z.disjoint.push(...G.withPrefixKey(Y==="prefix"?Z.result.length:`-${Q.length+1}`,VQ(X)&&VQ(U)?"required":"optional")),Z.result=[...Z.result,{kind:Y,node:O.intrinsic.never.internal}];else if(Y==="optionals"||Y==="defaultables")return Z;else return r4({...Z,fixedVariants:[],l:Q.map((V)=>({...V,kind:"prefix"})),r:Q.map((V)=>({...V,kind:"prefix"}))});else if(Y==="defaultables"){if(X.kind==="defaultables"&&U.kind==="defaultables"&&X.default!==U.default)M(FZ(X.default,U.default));Z.result=[...Z.result,{kind:Y,node:G,default:X.kind==="defaultables"?X.default:U.kind==="defaultables"?U.default:d(`Unexpected defaultable intersection from ${X.kind} and ${U.kind} elements.`)}]}else Z.result=[...Z.result,{kind:Y,node:G}];let _=Z.l.length,L=Z.r.length;if(X.kind!=="variadic"||_>=L&&(U.kind==="variadic"||L===1))Z.l=Q;if(U.kind!=="variadic"||L>=_&&(X.kind==="variadic"||_===1))Z.r=J;return r4(Z)},VQ=(Z)=>Z.kind==="prefix"||Z.kind==="postfix";var kZ=R(()=>{j();h0();T2();Y0();i();s0();c();K1();u2();p4();UY=g({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Z,X)=>{if(Z.length===0)return;return Z.map((Q)=>X.$.parseSchema(Q))}},optionals:{child:!0,parse:(Z,X)=>{if(Z.length===0)return;return Z.map((Q)=>X.$.parseSchema(Q))}},defaultables:{child:(Z)=>Z.map((X)=>X[0]),parse:(Z,X)=>{if(Z.length===0)return;return Z.map((Q)=>{let U=X.$.parseSchema(Q[0]);return d4(U,Q[1],null),[U,Q[1]]})},serialize:(Z)=>Z.map((X)=>[X[0].collapsibleJson,i0(X[1])]),reduceIo:(Z,X,Q)=>{if(Z==="in"){X.optionals=Q.map((U)=>U[0].rawIn);return}X.prefix=Q.map((U)=>U[0].rawOut);return}},variadic:{child:!0,parse:(Z,X)=>X.$.parseSchema(Z,X)},minVariadicLength:{parse:(Z)=>Z===0?void 0:Z},postfix:{child:!0,parse:(Z,X)=>{if(Z.length===0)return;return Z.map((Q)=>X.$.parseSchema(Q))}}},normalize:(Z)=>{if(typeof Z==="string")return{variadic:Z};if("variadic"in Z||"prefix"in Z||"defaultables"in Z||"optionals"in Z||"postfix"in Z||"minVariadicLength"in Z){if(Z.postfix?.length){if(!Z.variadic)return M(YY);if(Z.optionals?.length||Z.defaultables?.length)return M(yZ)}if(Z.minVariadicLength&&!Z.variadic)return M("minVariadicLength may not be specified without a variadic element");return Z}return{variadic:Z}},reduce:(Z,X)=>{let Q=Z.minVariadicLength??0,U=Z.prefix?.slice()??[],J=Z.defaultables?.slice()??[],$=Z.optionals?.slice()??[],W=Z.postfix?.slice()??[];if(Z.variadic){while($[$.length-1]?.equals(Z.variadic))$.pop();if($.length===0&&J.length===0)while(U[U.length-1]?.equals(Z.variadic))U.pop(),Q++;while(W[0]?.equals(Z.variadic))W.shift(),Q++}else if($.length===0&&J.length===0)U.push(...W.splice(0));if(Q!==Z.minVariadicLength||Z.prefix&&Z.prefix.length!==U.length)return X.node("sequence",{...Z,prefix:U,defaultables:J,optionals:$,postfix:W,minVariadicLength:Q},{prereduced:!0})},defaults:{description:(Z)=>{if(Z.isVariadicOnly)return`${Z.variadic.nestableExpression}[]`;return`[${Z.tuple.map((Q)=>Q.kind==="defaultables"?`${Q.node.nestableExpression} = ${k(Q.default)}`:Q.kind==="optionals"?`${Q.node.nestableExpression}?`:Q.kind==="variadic"?`...${Q.node.nestableExpression}[]`:Q.node.expression).join(", ")}]`}},intersections:{sequence:(Z,X,Q)=>{let U=r4({l:Z.tuple,r:X.tuple,disjoint:new A,result:[],fixedVariants:[],ctx:Q}),J=U.disjoint.length===0?[U,...U.fixedVariants]:U.fixedVariants;return J.length===0?U.disjoint:J.length===1?Q.$.node("sequence",LQ(J[0].result)):Q.$.node("union",J.map(($)=>({proto:Array,sequence:LQ($.result)})))}}});qQ=class qQ extends r0{impliedBasis=O.intrinsic.Array.internal;tuple=WY(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((Z)=>{if(Z.kind==="defaultables"||Z.kind==="optionals")return this.defaultablesAndOptionals.push(Z.node),!0;return Z.kind==="prefix"});variadicOrPostfix=I1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return m8(this.flatRefs,this.prevariadic.flatMap((Z,X)=>u(Z.node.flatRefs.map((Q)=>G1([`${X}`,...Q.path],Q.node)),G1([`${X}`],Z.node)))),m8(this.flatRefs,this.variadicOrPostfix.flatMap((Z)=>u(Z.flatRefs.map((X)=>G1([O.intrinsic.nonNegativeIntegerString.internal,...X.path],X.node)),G1([O.intrinsic.nonNegativeIntegerString.internal],Z)))),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=$Y(this);defaultValueMorphsReference=this.defaultValueMorphs.length?U0(this.defaultValueMorphs):void 0;elementAtIndex(Z,X){if(X<this.prevariadic.length)return this.tuple[X];let Q=Z.length-this.postfixLength;if(X>=Q)return{kind:"postfix",node:this.postfix[X-Q]};return{kind:"variadic",node:this.variadic??d(`Unexpected attempt to access index ${X} on ${this}`)}}traverseAllows=(Z,X)=>{for(let Q=0;Q<Z.length;Q++)if(!this.elementAtIndex(Z,Q).node.traverseAllows(Z[Q],X))return!1;return!0};traverseApply=(Z,X)=>{let Q=0;for(;Q<Z.length;Q++)k0(Q,()=>this.elementAtIndex(Z,Q).node.traverseApply(Z[Q],X),X)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Z){if(this.prefix)for(let[X,Q]of this.prefix.entries())Z.traverseKey(`${X}`,`data[${X}]`,Q);for(let[X,Q]of this.defaultablesAndOptionals.entries()){let U=`${X+this.prefixLength}`;Z.if(`${U} >= data.length`,()=>Z.traversalKind==="Allows"?Z.return(!0):Z.return()),Z.traverseKey(U,`data[${U}]`,Q)}if(this.variadic){if(this.postfix)Z.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Z.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Z.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[X,Q]of this.postfix.entries()){let U=`firstPostfixIndex + ${X}`;Z.traverseKey(U,`data[${U}]`,Q)}}if(Z.traversalKind==="Allows")Z.return(!0)}_transform(Z,X){X.path.push(O.intrinsic.nonNegativeIntegerString.internal);let Q=super._transform(Z,X);return X.path.pop(),Q}expression=this.description;reduceJsonSchema(Z,X){let Q=X.target==="draft-07";if(this.prevariadic.length){let U=this.prevariadic.map((J)=>{let $=J.node.toJsonSchemaRecurse(X);if(J.kind==="defaultables"){let W=typeof J.default==="function"?J.default():J.default;$.default=O.intrinsic.jsonData.allows(W)?W:X.fallback.defaultValue({code:"defaultValue",base:$,value:W})}return $});if(Q)Z.items=U;else Z.prefixItems=U}if(this.minLength)Z.minItems=this.minLength;if(this.variadic){let U=this.variadic.toJsonSchemaRecurse(X);if(Q&&this.prevariadic.length)Z.additionalItems=U;else Z.items=U;if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let J=this.postfix.map(($)=>$.toJsonSchemaRecurse(X));Z=X.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:J})}}else{if(Q)Z.additionalItems=!1;else Z.items=!1;delete Z.maxItems}return Z}};JY={},fZ={implementation:UY,Node:qQ}});var BQ=(Z)=>(X)=>{if(X.props.length||X.index){let Q=X.index?.map((J)=>J[Z])??[];for(let J of X.props)Q.push(J[Z]);if(X.undeclared)Q.push(`+ (undeclared): ${X.undeclared}`);let U=`{ ${Q.join(", ")} }`;return X.sequence?`${U} & ${X.sequence.description}`:U}return X.sequence?.description??"{}"},GY,_Y,HQ=(Z,X,Q)=>{let U=Z.required?"required":"optional";if(!X.signature.allows(Z.key))return null;let J=g0(Z.value,X.value,Q);if(J instanceof A)return U==="optional"?Q.node("optional",{key:Z.key,value:O.intrinsic.never.internal}):J.withPrefixKey(Z.key,Z.kind);return null},LY,MQ,gZ,VY=(Z)=>{let X="";for(let Q=0;Q<Z.defaultable.length;Q++)X+=Z.defaultable[Q].defaultValueMorphRef;if(Z.sequence?.defaultValueMorphsReference)X+=Z.sequence?.defaultValueMorphsReference;if(Z.undeclared==="delete"){if(X+="delete !(",Z.required)for(let Q of Z.required)X+=Q.compiledKey+" | ";if(Z.optional)for(let Q of Z.optional)X+=Q.compiledKey+" | ";if(Z.index)for(let Q of Z.index)X+=Q.signature.id+" | ";if(Z.sequence)if(Z.sequence.maxLength===null)X+=I.nonNegativeIntegerString.id;else for(let Q=0;Q<Z.sequence.tuple.length;Q++)X+=Q+" | ";X+=")"}return X},qY=(Z)=>{let X=VY(Z);if(!X)return;if(gZ[X])return gZ[X];let Q=(U,J)=>{for(let $=0;$<Z.defaultable.length;$++)if(!(Z.defaultable[$].key in U))Z.defaultable[$].defaultValueMorph(U,J);if(Z.sequence?.defaultables)for(let $=U.length-Z.sequence.prefixLength;$<Z.sequence.defaultables.length;$++)Z.sequence.defaultValueMorphs[$](U,J);if(Z.undeclared==="delete"){for(let $ in U)if(!Z.declaresKey($))delete U[$]}return U};return gZ[X]=Q},HY=(Z,X)=>{let U=`(data${X.defaultable.some((J)=>J.defaultValueMorph.length===2)||X.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return Z.block(`${U} => `,(J)=>{for(let $=0;$<X.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:Y}=X.defaultable[$];J.if(`!(${W} in data)`,(G)=>G.line(`${Y}${U}`))}if(X.sequence?.defaultables)J.for(`i < ${X.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${X.sequence.prefixLength}`);if(X.undeclared==="delete")J.forIn("data",($)=>$.if(`!(${X._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return J.return("data")})},vZ,zY=(Z)=>{if(E(Z,"root")&&Z.hasKind("unit"))Z=Z.unit;if(typeof Z==="number")Z=`${Z}`;return Z},FY=(Z,X)=>`${Z} is not allowed as an array index on ${X}. Use the 'nonNegativeIntegerString' keyword instead.`,J9=(Z,X,Q)=>{let[U,J]=T7(Z.branches,(W)=>W.hasKind("unit"));if(!U.length)return{index:Q.node("index",{signature:Z,value:X})};let $={};for(let W of U){let Y=Q.node("required",{key:W.unit,value:X});$[Y.kind]=u($[Y.kind],Y)}if(J.length)$.index=Q.node("index",{signature:J,value:X});return $},BY=(Z)=>E(Z,"root")?Z.expression:k(Z),zQ=(Z,X)=>`Key${X.length===1?"":"s"} ${X.map(BY).join(", ")} ${X.length===1?"does":"do"} not exist on ${Z}`,FQ=(Z)=>`Duplicate key ${W1(Z)}`;var xZ=R(()=>{j();h0();X9();X2();a1();Y0();i();s0();c();t1();K1();_0();u2();GY=BQ("description"),_Y=BQ("expression"),LY=g({kind:"structure",hasAssociatedError:!1,normalize:(Z)=>Z,applyConfig:(Z,X)=>{if(!Z.undeclared&&X.onUndeclaredKey!=="ignore")return{...Z,undeclared:X.onUndeclaredKey};return Z},keys:{required:{child:!0,parse:O0("required"),reduceIo:(Z,X,Q)=>{X.required=u(X.required,Q.map((U)=>Z==="in"?U.rawIn:U.rawOut));return}},optional:{child:!0,parse:O0("optional"),reduceIo:(Z,X,Q)=>{if(Z==="in"){X.optional=Q.map((U)=>U.rawIn);return}for(let U of Q)X[U.outProp.kind]=u(X[U.outProp.kind],U.outProp.rawOut)}},index:{child:!0,parse:O0("index")},sequence:{child:!0,parse:O0("sequence")},undeclared:{parse:(Z)=>Z==="ignore"?void 0:Z,reduceIo:(Z,X,Q)=>{if(Q==="reject"){X.undeclared="reject";return}if(Z==="in")delete X.undeclared;else X.undeclared="reject"}}},defaults:{description:GY},intersections:{structure:(Z,X,Q)=>{let U={...Z.inner},J={...X.inner},$=new A;if(Z.undeclared){let G=Z.keyof();for(let _ of X.requiredKeys)if(!G.allows(_))$.add("presence",O.intrinsic.never.internal,X.propsByKey[_].value,{path:[_]});if(J.optional)J.optional=J.optional.filter((_)=>G.allows(_.key));if(J.index)J.index=J.index.flatMap((_)=>{if(_.signature.extends(G))return _;let L=g0(G,_.signature,Q.$);if(L instanceof A)return[];let V=J9(L,_.value,Q.$);if(V.required)J.required=I1(J.required,V.required);if(V.optional)J.optional=I1(J.optional,V.optional);return V.index??[]})}if(X.undeclared){let G=X.keyof();for(let _ of Z.requiredKeys)if(!G.allows(_))$.add("presence",Z.propsByKey[_].value,O.intrinsic.never.internal,{path:[_]});if(U.optional)U.optional=U.optional.filter((_)=>G.allows(_.key));if(U.index)U.index=U.index.flatMap((_)=>{if(_.signature.extends(G))return _;let L=g0(G,_.signature,Q.$);if(L instanceof A)return[];let V=J9(L,_.value,Q.$);if(V.required)U.required=I1(U.required,V.required);if(V.optional)U.optional=I1(U.optional,V.optional);return V.index??[]})}let W={};if(Z.undeclared||X.undeclared)W.undeclared=Z.undeclared==="reject"||X.undeclared==="reject"?"reject":"delete";let Y=v2({kind:"structure",baseInner:W,l:x2(U),r:x2(J),roots:[],ctx:Q});if(Y instanceof A)$.push(...Y);if($.length)return $;return Y}},reduce:(Z,X)=>{if(!Z.required&&!Z.optional)return;let Q={},U=!1,J=Z.optional?[...Z.optional]:[];if(Z.required)for(let $=0;$<Z.required.length;$++){let W=Z.required[$];if(W.key in Q)M(FQ(W.key));if(Q[W.key]=!0,Z.index)for(let Y of Z.index){let G=HQ(W,Y,X);if(G instanceof A)return G}}if(Z.optional)for(let $=0;$<Z.optional.length;$++){let W=Z.optional[$];if(W.key in Q)M(FQ(W.key));if(Q[W.key]=!0,Z.index)for(let Y of Z.index){let G=HQ(W,Y,X);if(G instanceof A)return G;if(G!==null)J[$]=G,U=!0}}if(U)return X.node("structure",{...Z,optional:J},{prereduced:!0})}});MQ=class MQ extends r0{impliedBasis=O.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Z)=>Z.impliedSiblings??[]);props=I1(this.required,this.optional);propsByKey=y(this.props,(Z,X)=>[X.key,X]);propsByKeyReference=U0(this.propsByKey);expression=_Y(this);requiredKeys=this.required?.map((Z)=>Z.key)??[];optionalKeys=this.optional?.map((Z)=>Z.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:X}of this.index)Z=Z.concat(X.branches);return this._keyof=this.$.node("union",Z)}map(Z){return this.$.node("structure",this.props.flatMap(Z).reduce((X,Q)=>{let U=this.propsByKey[Q.key];if(e(Q)){if(Q.kind!=="required"&&Q.kind!=="optional")return M(`Map result must have kind "required" or "optional" (was ${Q.kind})`);return X[Q.kind]=u(X[Q.kind],Q),X}let J=Q.kind??U?.kind??"required",$=y(Q,(W,Y)=>(W in l4.implementation.keys)?[W,Y]:[]);return X[J]=u(X[J],this.$.node(J,$)),X},{}))}assertHasKeys(Z){let X=Z.filter((Q)=>!c4(Q,this.keyof()));if(X.length)return M(zQ(this.expression,X))}get(Z,...X){let Q,U=!1,J=zY(Z);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])Q=this.propsByKey[J].value,U=this.propsByKey[J].required;if(this.index){for(let W of this.index)if(c4(J,W.signature))Q=Q?.and(W.value)??W.value}if(this.sequence&&c4(J,O.intrinsic.nonNegativeIntegerString))if(E(J,"root")){if(this.sequence.variadic)Q=Q?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(J);if(W<this.sequence.prevariadic.length){let Y=this.sequence.prevariadic[W].node;Q=Q?.and(Y)??Y,U||=W<this.sequence.prefixLength}else if(this.sequence.variadic){let Y=this.$.node("union",this.sequence.variadicOrPostfix);Q=Q?.and(Y)??Y}}if(!Q){if(this.sequence?.variadic&&E(J,"root")&&J.extends(O.intrinsic.number))return M(FY(J.expression,this.sequence.expression));return M(zQ(this.expression,[J]))}let $=Q.get(...X);return U?$:$.or(O.intrinsic.undefined)}pick(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("pick",Z))}omit(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("omit",Z))}optionalize(){let{required:Z,...X}=this.inner;return this.$.node("structure",{...X,optional:this.props.map((Q)=>Q.hasKind("required")?this.$.node("optional",Q.inner):Q)})}require(){let{optional:Z,...X}=this.inner;return this.$.node("structure",{...X,required:this.props.map((Q)=>Q.hasKind("optional")?{key:Q.key,value:Q.value}:Q)})}merge(Z){let X=this.filterKeys("omit",[Z.keyof()]);if(Z.required)X.required=u(X.required,Z.required);if(Z.optional)X.optional=u(X.optional,Z.optional);if(Z.index)X.index=u(X.index,Z.index);if(Z.sequence)X.sequence=Z.sequence;if(Z.undeclared)X.undeclared=Z.undeclared;else delete X.undeclared;return this.$.node("structure",X)}filterKeys(Z,X){let Q=l6(this.inner),U=(J)=>{let $=X.some((W)=>c4(J,W));return Z==="pick"?$:!$};if(Q.required)Q.required=Q.required.filter((J)=>U(J.key));if(Q.optional)Q.optional=Q.optional.filter((J)=>U(J.key));if(Q.index)Q.index=Q.index.filter((J)=>U(J.signature));return Q}traverseAllows=(Z,X)=>this._traverse("Allows",Z,X);traverseApply=(Z,X)=>this._traverse("Apply",Z,X);_traverse=(Z,X,Q)=>{let U=Q?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(Z==="Allows"){if(!this.props[J].traverseAllows(X,Q))return!1}else if(this.props[J].traverseApply(X,Q),Q.failFast&&Q.currentErrorCount>U)return!1;if(this.sequence){if(Z==="Allows"){if(!this.sequence.traverseAllows(X,Q))return!1}else if(this.sequence.traverseApply(X,Q),Q.failFast&&Q.currentErrorCount>U)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(X);J.push(...Object.getOwnPropertySymbols(X));for(let $=0;$<J.length;$++){let W=J[$];if(this.index){for(let Y of this.index)if(Y.signature.traverseAllows(W,Q)){if(Z==="Allows"){if(!k0(W,()=>Y.value.traverseAllows(X[W],Q),Q))return!1}else if(k0(W,()=>Y.value.traverseApply(X[W],Q),Q),Q.failFast&&Q.currentErrorCount>U)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Z==="Allows")return!1;if(Q.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],meta:this.meta}),Q.failFast)return!1}}}if(this.structuralMorph&&Q&&!Q.hasError())Q.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Z)=>Z.hasDefault())??[])}declaresKey=(Z)=>(Z in this.propsByKey)||this.index?.some((X)=>X.signature.allows(Z))||this.sequence!==void 0&&O.intrinsic.nonNegativeIntegerString.allows(Z);_compileDeclaresKey(Z){let X=[];if(this.props.length)X.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let Q of this.index)X.push(Z.invoke(Q.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",qY(this))}structuralMorphRef=this.structuralMorph&&U0(this.structuralMorph);compile(Z){if(Z.traversalKind==="Apply")Z.initializeErrorCount();for(let X of this.props)if(Z.check(X),Z.traversalKind==="Apply")Z.returnIfFailFast();if(this.sequence){if(Z.check(this.sequence),Z.traversalKind==="Apply")Z.returnIfFailFast()}if(this.index||this.undeclared==="reject")Z.const("keys","Object.keys(data)"),Z.line("keys.push(...Object.getOwnPropertySymbols(data))"),Z.for("i < keys.length",()=>this.compileExhaustiveEntry(Z));if(Z.traversalKind==="Allows")return Z.return(!0);if(this.structuralMorphRef)Z.if("ctx && !ctx.hasError()",()=>{return Z.line("ctx.queueMorphs(["),HY(Z,this),Z.line("])")})}compileExhaustiveEntry(Z){if(Z.const("k","keys[i]"),this.index)for(let X of this.index)Z.if(`${Z.invoke(X.signature,{arg:"k",kind:"Allows"})}`,()=>Z.traverseKey("k","data[k]",X.value));if(this.undeclared==="reject")Z.if(`!(${this._compileDeclaresKey(Z)})`,()=>{if(Z.traversalKind==="Allows")return Z.return(!1);return Z.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Z.return())});return Z}reduceJsonSchema(Z,X){switch(Z.type){case"object":return this.reduceObjectJsonSchema(Z,X);case"array":let Q=this.sequence?.reduceJsonSchema(Z,X)??Z;if(this.props.length||this.index)return X.fallback.arrayObject({code:"arrayObject",base:Q,object:this.reduceObjectJsonSchema({type:"object"},X)});return Q;default:return X0.throwInternalOperandError("structure",Z)}}reduceObjectJsonSchema(Z,X){if(this.props.length){Z.properties={};for(let Q of this.props){let U=Q.value.toJsonSchemaRecurse(X);if(typeof Q.key==="symbol"){X.fallback.symbolKey({code:"symbolKey",base:Z,key:Q.key,value:U,optional:Q.optional});continue}if(Q.hasDefault()){let J=typeof Q.default==="function"?Q.default():Q.default;U.default=O.intrinsic.jsonData.allows(J)?J:X.fallback.defaultValue({code:"defaultValue",base:U,value:J})}Z.properties[Q.key]=U}if(this.requiredKeys.length&&Z.properties)Z.required=this.requiredKeys.filter((Q)=>typeof Q==="string"&&(Q in Z.properties))}if(this.index)for(let Q of this.index){let U=Q.value.toJsonSchemaRecurse(X);if(Q.signature.equals(O.intrinsic.string)){Z.additionalProperties=U;continue}for(let J of Q.signature.branches){if(!J.extends(O.intrinsic.string)){Z=X.fallback.symbolKey({code:"symbolKey",base:Z,key:null,value:U,optional:!1});continue}let $={type:"string"};if(J.hasKind("morph"))$=X.fallback.morph({code:"morph",base:J.rawIn.toJsonSchemaRecurse(X),out:J.rawOut.toJsonSchemaRecurse(X)});if(!J.hasKind("intersection"))return d(`Unexpected index branch kind ${J.kind}.`);let{pattern:W}=J.inner;if(W){let Y=Object.assign($,{pattern:W[0].rule});for(let G=1;G<W.length;G++)$=X.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:W[G].rule});Z.patternProperties??={},Z.patternProperties[Y.pattern]=U}}}if(this.undeclared&&!Z.additionalProperties)Z.additionalProperties=!1;return Z}};gZ={},vZ={implementation:LY,Node:MQ}});var m2,l3;var Z9=R(()=>{j();k2();i8();r8();_Z();VZ();MZ();RZ();KZ();DZ();PZ();SZ();NZ();c();t1();EZ();u2();IZ();kZ();xZ();m2={...v3,alias:i4.implementation,domain:U9.implementation,unit:CZ.implementation,proto:s4.implementation,union:AZ.implementation,morph:TZ.implementation,intersection:OZ.implementation,divisor:s8.implementation,pattern:LZ.implementation,predicate:c8.implementation,required:bZ.implementation,optional:l4.implementation,index:jZ.implementation,sequence:fZ.implementation,structure:vZ.implementation};O.defaultConfig=E7(Object.assign(y(m2,(Z,X)=>[Z,X.defaults]),{jitless:x7(),clone:f7,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:X0.defaultConfig}));O.resolvedConfig=y4(O.defaultConfig,O.config);l3={...x3,alias:i4.Node,domain:U9.Node,unit:CZ.Node,proto:s4.Node,union:AZ.Node,morph:TZ.Node,intersection:OZ.Node,divisor:s8.Node,pattern:LZ.Node,predicate:c8.Node,required:bZ.Node,optional:l4.Node,index:jZ.Node,sequence:fZ.Node,structure:vZ.Node}});var c2,hZ=(Z,X)=>new c2(y(Z,(Q,U)=>[Q,E(U,"module")?hZ(U,X):X.bindReference(U)]));var mZ=R(()=>{j();_0();c2=class c2 extends P8{get[w0](){return"module"}}});var MY=(Z)=>t(Z)?Z:("branches"in Z)&&t(Z.branches)?Z.branches:void 0,RY=(Z,X)=>M(`Node of kind ${X} is not valid as a ${Z} definition`),RQ=(Z)=>`#${Z} duplicates public alias ${Z}`,uZ,OQ,TQ="function $",OY=(Z)=>DQ(Z,PQ(Z)),DQ=(Z,X)=>{let Q=X.write(TQ,4),U=X.compile()();for(let J of Z){if(J.precompilation)continue;if(J.traverseAllows=U[`${J.id}Allows`].bind(U),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=U[`${J.id}Apply`].bind(U),U[`${J.id}Optimistic`])J.traverseOptimistic=U[`${J.id}Optimistic`].bind(U);J.precompilation=Q}},PQ=(Z)=>new p6().return(Z.reduce((X,Q)=>{let U=new f4({kind:"Allows"}).indent();Q.compile(U);let J=U.write(`${Q.id}Allows`),$=new f4({kind:"Apply"}).indent();Q.compile($);let W=$.write(`${Q.id}Apply`),Y=`${X}${J},
42
+ ${W},
43
+ `;if(!Q.hasKind("union"))return Y;let G=new f4({kind:"Allows",optimistic:!0}).indent();Q.compile(G);let _=G.write(`${Q.id}Optimistic`);return`${Y}${_},
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)L(`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)L(b4(W));this.aliases[W]=Z}else{if(W in this.aliases)L(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)??L(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)L(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 L(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??L(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,H)=>[`${Y}.${J}`,H]);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:XH,generic:Q1}=S2;var VQ="^(?:0|[1-9]\\d*)$",N3=new RegExp(VQ),ZH=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?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 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){L(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 L1={"<":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],L1):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(L1);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(L1)):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 L(`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 L(NQ(Q,X,Y));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(U.extends(F.intrinsic.lengthBoundable)){if(typeof X!=="number")return L(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 L(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,H=ZU(X,typeof G==="number"?G:W,U,"right");for(let $ of H)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(L1);Q.root=Q.root.brand(X)};var HU=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let X=Q.scanner.shiftUntilLookahead(L1),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==="%"?HU(Q):X==="#"?JU(Q):(X in V1)?IQ(Q):Q.error(H6(X))},H6=(Q,X="")=>`'${Q}' is not allowed here${X&&` (should be ${X})`}`,l3="Missing expected ']'";var LU=(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===">")L(H6(">"));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=LU(Q);else if(Q.finalizer==="?")X=[X,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)L(H6(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 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 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",L6=(Q,X,U)=>{Q.shiftUntilNonWhitespace();let Y=Q.shiftUntilLookahead(L1);if(Y===""){if(Q.lookahead===""&&X.length)return X;return L(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),L6(Q,U,Y)}let Z=j2(new e1(Q,Y));return U.push([X,Z.root]),L6(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 L(r3);J=Q.parse(U[Y+1])}return(H)=>new qU(H,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),H=Q(...J);return U.assert(H)}}[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)L(t3);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 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)L("default may only be specified as the last key of a switch definition");return this.default(Y)}if(typeof Y!=="function")return L(`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 H=Q8(G);if(H.kind==="spread"){if(!_1(Y))return L(e3);let b=X.$.parseOwnDefinitionFormat(J,X);if(b.equals(z.object))continue;if(!b.hasKind("intersection")||!b.basis?.equals(z.object))return L(X8(b.expression));U=b.structure;continue}if(H.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")L(a3(J));Y.undeclared=J;continue}let _=F6(J,X),$=H;if(H.kind==="required"){if(!K(_))bQ(Y,"required",{key:H.normalized,value:_},X);else bQ(Y,"optional",_[1]==="="?{key:H.normalized,value:_[0],default:_[2]}:{key:H.normalized,value:_[0]},X);continue}if(K(_)){if(_[1]==="?")L(AU);if(_[1]==="=")L(zU)}if(H.kind==="optional"){bQ(Y,"optional",{key:H.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):H8(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 L(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 L(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 L(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,"?":()=>L(W6)}),_8=VU({"|":fQ,"&":fQ,":":W8,"=>":Z8,"|>":fQ,"@":G8,"=":()=>L(G6)}),DU={...J8,..._8},H8=(Q)=>DU[Q[1]]!==void 0,L8=(Q)=>Q,RU=L8({keyof:U8,instanceof:(Q,X)=>{if(typeof Q[1]!=="function")return L(BU(_2(Q[1])));let U=Q.slice(1).map((Y)=>typeof Y==="function"?X.$.node("proto",{proto:Y}):L(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,H]=!K(W)?[W]:W;if(Y++,Z){if(!G.extends(F.intrinsic.Array))return L(A8(G.expression));U=U.flatMap((_)=>G.distribute(($)=>$8(l2(_),$)))}else U=U.map((_)=>{if(J==="?")return PU(_,G);if(J==="=")return q8(_,G,H);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 L(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 L(NU);return Q.optionals=D(Q.optionals,X),Q},q8=(Q,X,U)=>{if(Q.variadic)return L(NU);if(Q.optionals)return L(O8);return Q.defaultables=D(Q.defaultables,[[X,U]]),Q},CU=(Q,X)=>{if(Q.postfix)L(wU);if(Q.variadic){if(!Q.variadic.equals(X))L(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):L(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 L(vQ("Function"))}default:return L(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]!==">")L("'>' 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 L6(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 L(G6);if(Y[1]==="?")return L(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(L2,"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 H9=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 L9=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:H9,Partial:L9,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,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 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
+ `)+"}"),$9,lZ,KQ=(Z)=>{let X=Z.references.filter((Q)=>Q.hasKind("alias"));for(let Q of X){Object.assign(Q.referencesById,Q.resolution.referencesById);for(let U of Z.references)if(Q.id in U.referencesById)Object.assign(U.referencesById,Q.referencesById)}return Z},wQ=(Z)=>y(Z,(X,Q)=>[X,E(Q,"root")||E(Q,"generic")?Q.json:E(Q,"module")?wQ(Q):d(`Unexpected resolution ${k(Q)}`)]),pZ=(Z,X)=>{let Q=X.indexOf(".");if(Q===-1)return;let U=X.slice(0,Q),J=Z[U];if(J===void 0)return;if(!E(J,"module"))return M(KY(U));let $=X.slice(Q+1),W=J[$];if(W===void 0)return pZ(J,$);if(E(W,"root")||E(W,"generic"))return W;if(E(W,"module"))return W.root??M(SQ(X));d(`Unexpected resolution for alias '${X}': ${k(W)}`)},W9=(Z,X)=>new lZ(Z,X),o4,AQ=(Z,X)=>{let Q={};for(let U in X){let J=X[U];if(E(J,"module")){let $=AQ(Z,J),W=y($,(Y,G)=>[`${U}.${Y}`,G]);Object.assign(Q,W)}else if(E(J,"root")||E(J,"generic"))Q[U]=J;else d(`Unexpected scope resolution ${k(J)}`)}return Q},dZ=(Z)=>`'${Z}' is unresolvable`,KY=(Z)=>`'${Z}' must reference a module to be accessed using dot syntax`,SQ=(Z)=>`Reference to submodule '${Z}' must specify an alias`,s,i2,DM,a0;var cZ=R(()=>{j();k2();d8();Z9();mZ();e6();MZ();a1();c();K1();_0();uZ={};O.ambient??={};$9=class $9{config;resolvedConfig;name;get[w0](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Z,X){if(this.config=y4(O.config,X),this.resolvedConfig=y4(O.resolvedConfig,X),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(uZ).length}`,this.name in uZ)M(`A Scope already named ${this.name} already exists`);uZ[this.name]=this;let Q=Object.entries(Z).map((U)=>this.preparseOwnAliasEntry(...U));for(let[U,J]of Q){let $=U;if(U[0]==="#"){if($=U.slice(1),$ in this.aliases)M(RQ($));this.aliases[$]=J}else{if($ in this.aliases)M(RQ(U));this.aliases[$]=J,this.exportedNames.push($)}if(!E(J,"module")&&!E(J,"generic")&&!s1(J)){let W=this.preparseOwnDefinitionFormat(J,{alias:$});this.resolutions[$]=E(W,"root")?this.bindReference(W):this.createParseContext(W).id}}OQ??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[OQ.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=O.intrinsic?y(O.intrinsic,(U,J)=>U.startsWith("json")?[]:[U,this.bindReference(J)]):{}}cacheGetter(Z,X){return Object.defineProperty(this,Z,{value:X}),X}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Z){return Z}generic=(...Z)=>{let X=this;return(Q,U)=>new Z2(Z,U?new s6(Q):Q,X,X,U??null)};units=(Z,X)=>{let Q=[];for(let J of Z)if(!Q.includes(J))Q.push(J);let U=Q.map((J)=>this.node("unit",{unit:J},X));return this.node("union",U,{...X,prereduced:!0})};lazyResolutions=[];lazilyResolve(Z,X){let Q=this.node("alias",{reference:X??"synthetic",resolve:Z},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(Q);return Q}schema=(Z,X)=>this.finalize(this.parseSchema(Z,X));parseSchema=(Z,X)=>this.node(h4(Z),Z,X);preparseNode(Z,X,Q){let U=typeof Z==="string"?Z:h4(X,Z);if(e(X)&&X.kind===U)return X;if(U==="alias"&&!Q?.prereduced){let{reference:W}=i4.implementation.normalize(X,this);if(W.startsWith("$")){let Y=this.resolveRoot(W.slice(1));X=Y,U=Y.kind}}else if(U==="union"&&E0(X,"object")){let W=MY(X);if(W?.length===1)X=W[0],U=h4(X)}if(e(X)&&X.kind===U)return X;let $=m2[U].normalize?.(X,this)??X;if(e($))return $.kind===U?$:RY(U,$.kind);return{...Q,$:this,kind:U,def:$,prefix:Q.alias??U}}bindReference(Z){let X;if(e(Z))X=Z.$===this?Z:new Z.constructor(Z.attachments,this);else X=Z.$===this?Z:new Z2(Z.params,Z.bodyDef,Z.$,this,Z.hkt);if(!this.resolved)Object.assign(this.referencesById,X.referencesById);return X}resolveRoot(Z){return this.maybeResolveRoot(Z)??M(dZ(Z))}maybeResolveRoot(Z){let X=this.maybeResolve(Z);if(E(X,"generic"))return;return X}maybeResolveSubalias(Z){return pZ(this.aliases,Z)??pZ(this.ambient,Z)}get ambient(){return O.ambient}maybeResolve(Z){let X=this.resolutions[Z];if(X){if(typeof X!=="string")return this.bindReference(X);let U=A0[X];if(E(U,"root"))return this.resolutions[Z]=U;if(E(U,"context")){if(U.phase==="resolving")return this.node("alias",{reference:`$${Z}`},{prereduced:!0});if(U.phase==="resolved")return d(`Unexpected resolved context for was uncached by its scope: ${k(U)}`);U.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(U.def,U));return U.phase="resolved",A0[J.id]=J,A0[U.id]=J,this.resolutions[Z]=J}return d(`Unexpected nodesById entry for ${X}: ${k(U)}`)}let Q=this.aliases[Z]??this.ambient?.[Z];if(!Q)return this.maybeResolveSubalias(Z);if(Q=this.normalizeRootScopeValue(Q),E(Q,"generic"))return this.resolutions[Z]=this.bindReference(Q);if(E(Q,"module")){if(!Q.root)M(SQ(Z));return this.resolutions[Z]=this.bindReference(Q.root)}return this.resolutions[Z]=this.parse(Q,{alias:Z})}createParseContext(Z){let X=Z.id??qZ(Z.prefix);return A0[X]=Object.assign(Z,{[w0]:"context",$:this,id:X,phase:"unresolved"})}traversal(Z){return new Y1(Z,this.resolvedConfig)}import(...Z){return new c2(y(this.export(...Z),(X,Q)=>[`#${X}`,Q]))}precompilation;_exportedResolutions;_exports;export(...Z){if(!this._exports){this._exports={};for(let Q of this.exportedNames){let U=this.aliases[Q];this._exports[Q]=E(U,"module")?hZ(U,this):KQ(this.maybeResolve(Q))}for(let Q of this.lazyResolutions)Q.resolution;if(this._exportedResolutions=AQ(this,this._exports),this._json=wQ(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let Q=PQ(this.references);this.precompilation=Q.write(TQ,4),DQ(this.references,Q)}this.resolved=!0}let X=Z.length?Z:this.exportedNames;return new c2(y(X,(Q,U)=>[U,this._exports[U]]))}resolve(Z){return this.export()[Z]}node=(Z,X,Q={})=>{let U=this.preparseNode(Z,X,Q);if(e(U))return this.bindReference(U);let J=this.createParseContext(U),$=HZ(J),W=this.bindReference($);return A0[J.id]=W};parse=(Z,X={})=>this.finalize(this.parseDefinition(Z,X));parseDefinition(Z,X={}){if(E(Z,"root"))return this.bindReference(Z);let Q=this.preparseOwnDefinitionFormat(Z,X);if(E(Q,"root"))return this.bindReference(Q);let U=this.createParseContext(Q);A0[U.id]=U;let J=this.bindReference(this.parseOwnDefinitionFormat(Z,U));if(J.isCyclic)J=p3(J,U.id);return A0[U.id]=J,J}finalize(Z){if(KQ(Z),!Z.precompilation&&!this.resolvedConfig.jitless)OY(Z.references);return Z}};lZ=class lZ extends $9{parseOwnDefinitionFormat(Z,X){return HZ(X)}preparseOwnDefinitionFormat(Z,X){return this.preparseNode(h4(Z),Z,X)}preparseOwnAliasEntry(Z,X){return[Z,X]}normalizeRootScopeValue(Z){return Z}};o4=new lZ({});o4.export();s=o4.schema,i2=o4.node,DM=o4.defineSchema,a0=o4.generic});var iZ="^(?:0|[1-9]\\d*)$",TY,AM;var CQ=R(()=>{c();TY=new RegExp(iZ),AM=U0(TY)});var NQ,jQ,DY,I;var X9=R(()=>{cZ();c();CQ();NQ=W9({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();O.intrinsic={...NQ};jQ=W9({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:iZ}},{prereducedAliases:!0}).export();Object.assign(O.intrinsic,jQ);DY=W9({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),I={...NQ,...jQ,...DY,emptyStructure:i2("structure",{},{prereduced:!0})};O.intrinsic={...I}});var EQ=()=>{};var bQ=()=>{};var IQ=()=>{};var L0=R(()=>{j();k2();h0();d8();X9();Z9();mZ();T2();e6();i8();a8();t8();r8();ZZ();_Z();QZ();JZ();WZ();GZ();VZ();x1();RZ();KZ();DZ();PZ();X2();SZ();NZ();cZ();a1();EQ();Y0();k4();i();s0();bQ();c();IQ();t1();K1();_0();EZ();u2();p4();IZ();kZ();xZ()});var Y9=(Z,X)=>new RegExp(Z,X);var fQ=R(()=>{Object.assign(Y9,{as:Y9})});var yQ=R(()=>{fQ()});var kQ=R(()=>{k2()});var vQ=(Z)=>typeof Z==="string"&&Z[0]==="d"&&(Z[1]==="'"||Z[1]==='"')&&Z[Z.length-1]===Z[1],gQ=(Z)=>Z.toString()!=="Invalid Date",xQ=(Z)=>Z.slice(2,-1),sZ=(Z)=>`'${Z}' could not be parsed by the Date constructor`,hQ=(Z,X)=>PY(Z,X),PY=(Z,X)=>{let Q=new Date(Z);if(gQ(Q))return Q;let U=e7(Z);if(U!==void 0){let J=new Date(U);if(gQ(J))return J}return X?M(X===!0?sZ(Z):X):void 0};var rZ=R(()=>{j()});var wY,G9=(Z,X)=>{let Q=Z.scanner.shiftUntilEscapable(SY[pQ[X]]);if(Z.scanner.lookahead==="")return Z.error(NY(Q,X));if(Z.scanner.shift(),X in uQ){let U;try{U=new RegExp(Q)}catch(J){M(String(J))}if(Z.root=Z.ctx.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0}),X==="x/")Z.root=Z.ctx.$.node("morph",{in:Z.root,morphs:(J)=>U.exec(J),declaredOut:wY})}else if(H0(X,oZ))Z.root=Z.ctx.$.node("unit",{unit:Q});else{let U=hQ(Q,sZ(Q));Z.root=Z.ctx.$.node("unit",{meta:Q,unit:U})}},oZ,mQ,AY,uQ,pQ,SY,CY,NY=(Z,X)=>`${X}${Z} requires a closing ${CY[pQ[X]]}`;var lQ=R(()=>{L0();j();rZ();wY=s({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),oZ={"'":1,'"':1},mQ={"/":1,"'":1,'"':1},AY={"d'":"'",'d"':'"',"'":"'",'"':'"'},uQ={"/":"/","x/":"/"},pQ={...AY,...uQ},SY={"'":(Z)=>Z.lookahead==="'",'"':(Z)=>Z.lookahead==='"',"/":(Z)=>Z.lookahead==="/"},CY={'"':"double-quote","'":"single-quote","/":"forward slash"}});var dQ=(Z)=>`Private type references should not include '#'. Use '${Z}' instead.`,_9="Optional definitions like 'string?' are only valid as properties in an object or tuple",L9="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var D1,cQ=(Z,X)=>Z===">"?X[0]==="="?X[1]==="=":X.trimStart()===""||H0(X.trimStart()[0],D1):Z==="="?X[0]!=="=":Z===","||Z==="?";var s2=R(()=>{j();D1={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...r1}});var iQ=(Z,X,Q)=>sQ(Z,X,Q,[]),sQ=(Z,X,Q,U)=>{let J=Q.parseUntilFinalizer();if(U.push(J.root),J.finalizer===">"){if(U.length!==X.params.length)return Q.error(aZ(Z,X.names,U.map(($)=>$.expression)));return U}if(J.finalizer===",")return sQ(Z,X,Q,U);return J.error(u6(">"))},aZ=(Z,X,Q)=>`${Z}<${X.join(", ")}> requires exactly ${X.length} args (got ${Q.length}${Q.length===0?"":`: ${Q.join(", ")}`})`;var rQ=R(()=>{j()});var V9=(Z)=>{let X=Z.scanner.shiftUntilLookahead(D1);if(X==="keyof")Z.addPrefix("keyof");else Z.root=EY(Z,X)},jY=(Z,X,Q)=>{if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.shift()!=="<")return Q.error(aZ(Z,X.names,[]));let J=iQ(Z,X,Q);return X(...J)},EY=(Z,X)=>bY(Z,X)??IY(Z,X)??Z.error(X===""?Z.scanner.lookahead==="#"?dQ(Z.shiftedBy(1).scanner.shiftUntilLookahead(D1)):nZ(Z):dZ(X)),bY=(Z,X)=>{if(Z.ctx.args?.[X]){let U=Z.ctx.args[X];if(typeof U!=="string")return U;return Z.ctx.$.node("alias",{reference:U},{prereduced:!0})}let Q=Z.ctx.$.maybeResolve(X);if(E(Q,"root"))return Q;if(Q===void 0)return;if(E(Q,"generic"))return jY(X,Q,Z);return M(`Unexpected resolution ${k(Q)}`)},IY=(Z,X)=>{let Q=Z3(X);if(Q!==void 0)return Z.ctx.$.node("unit",{unit:Q});let U=Q3(X);if(U!==void 0)return Z.ctx.$.node("unit",{unit:U})},nZ=(Z)=>{let X=Z.previousOperator();return X?tZ(X,Z.scanner.unscanned):fY(Z.scanner.unscanned)},tZ=(Z,X="")=>`Token '${Z}' requires a right operand${X?` before '${X}'`:""}`,fY=(Z)=>`Expected an expression${Z?` before '${Z}'`:""}`;var eZ=R(()=>{L0();j();s2();rQ()});var ZX=(Z)=>Z.scanner.lookahead===""?Z.error(nZ(Z)):Z.scanner.lookahead==="("?Z.shiftedBy(1).reduceGroupOpen():Z.scanner.lookaheadIsIn(mQ)?G9(Z,Z.scanner.shift()):Z.scanner.lookaheadIsIn(r1)?ZX(Z.shiftedBy(1)):Z.scanner.lookahead==="d"?Z.scanner.nextLookahead in oZ?G9(Z,`${Z.scanner.shift()}${Z.scanner.shift()}`):V9(Z):Z.scanner.lookahead==="x"?Z.scanner.nextLookahead==="/"?Z.shiftedBy(2)&&G9(Z,"x/"):V9(Z):V9(Z);var oQ=R(()=>{j();lQ();eZ()});var aQ,nQ,r2,tQ=(Z,X)=>`Left bounds are only valid when paired with right bounds (try ...${X}${Z})`,q9=(Z)=>`Left-bounded expressions must specify their limits using < or <= (was ${Z})`,eQ=(Z,X,Q,U)=>`An expression may have at most one left bound (parsed ${Z}${r2[X]}, ${Q}${r2[U]})`;var XX=R(()=>{aQ={">":!0,">=":!0},nQ={"<":!0,"<=":!0},r2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="}});var XU=(Z,X)=>{let Q=yY(Z,X);if(Z.root.hasKind("unit")){if(typeof Z.root.unit==="number"){Z.reduceLeftBound(Z.root.unit,Q),Z.unsetRoot();return}if(Z.root.unit instanceof Date){let U=`d'${Z.root.description??Z.root.unit.toISOString()}'`;Z.unsetRoot(),Z.reduceLeftBound(U,Q);return}}return gY(Z,Q)},QU,yY=(Z,X)=>Z.scanner.lookaheadIs("=")?`${X}${Z.scanner.shift()}`:X,ZU=(Z,X,Q,U)=>{if(Q.extends(O.intrinsic.number)){if(typeof X!=="number")return M(QX(Z,X,U));return Z==="=="?["min","max"]:Z[0]===">"?["min"]:["max"]}if(Q.extends(O.intrinsic.lengthBoundable)){if(typeof X!=="number")return M(QX(Z,X,U));return Z==="=="?["exactLength"]:Z[0]===">"?["minLength"]:["maxLength"]}if(Q.extends(O.intrinsic.Date))return Z==="=="?["after","before"]:Z[0]===">"?["after"]:["before"];return M(j3(Q.expression))},kY=(Z)=>({rule:vQ(Z.limit)?xQ(Z.limit):Z.limit,exclusive:Z.comparator.length===1}),gY=(Z,X)=>{let Q=Z.unsetRoot(),U=Z.scanner.location;Z.parseOperand();let J=Z.unsetRoot(),$=Z.scanner.sliceChars(U,Z.scanner.location);if(Z.root=Q,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return Z.error(QX(X,$,"right"));let W=J.unit,Y=X.length===1,G=ZU(X,typeof W==="number"?W:$,Q,"right");for(let L of G)Z.constrainRoot(L,X==="=="?{rule:W}:{rule:W,exclusive:Y});if(!Z.branches.leftBound)return;if(!H0(X,nQ))return Z.error(q9(X));let _=ZU(Z.branches.leftBound.comparator,Z.branches.leftBound.limit,Q,"left");Z.constrainRoot(_[0],kY(Z.branches.leftBound)),Z.branches.leftBound=null},QX=(Z,X,Q)=>`Comparator ${Q==="left"?r2[Z]:Z} must be ${Q==="left"?"preceded":"followed"} by a corresponding literal (was ${X})`;var UU=R(()=>{L0();j();XX();rZ();QU={"<":1,">":1,"=":1}});var JU=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let X=Z.scanner.shiftUntilLookahead(D1);Z.root=Z.root.brand(X)};var $U=R(()=>{s2()});var YU=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let X=Z.scanner.shiftUntilLookahead(D1),Q=X3(X,{errorOnFail:WU(X)});if(Q===0)Z.error(WU(0));Z.root=Z.root.constrain("divisor",Q)},WU=(Z)=>`% operator must be followed by a non-zero integer literal (was ${Z})`;var GU=R(()=>{j();s2()});var UX=(Z)=>{let X=Z.scanner.shift();return X===""?Z.finalize(""):X==="["?Z.scanner.shift()==="]"?Z.setRoot(Z.root.array()):Z.error(vY):X==="|"?Z.scanner.lookahead===">"?Z.shiftedBy(1).pushRootToBranch("|>"):Z.pushRootToBranch(X):X==="&"?Z.pushRootToBranch(X):X===")"?Z.finalizeGroup():cQ(X,Z.scanner.unscanned)?Z.finalize(X):H0(X,QU)?XU(Z,X):X==="%"?YU(Z):X==="#"?JU(Z):(X in r1)?UX(Z):Z.error(H9(X))},H9=(Z,X="")=>`'${Z}' is not allowed here${X&&` (should be ${X})`}`,vY="Missing expected ']'";var JX=R(()=>{j();s2();UU();$U();GU()});var _U=(Z)=>{let X=Z.unsetRoot();Z.parseOperand();let Q=Z.unsetRoot();if(!Q.hasKind("unit"))return Z.error(xY(Q.expression));let U=Q.unit instanceof Date?()=>new Date(Q.unit):Q.unit;return[X,"=",U]},xY=(Z)=>`Default value '${Z}' must be a literal value`;var $X=(Z,X)=>{let Q=X.$.maybeResolveRoot(Z);if(Q)return Q;if(Z.endsWith("[]")){let $=X.$.maybeResolveRoot(Z.slice(0,-2));if($)return $.array()}let U=new o2(new I4(Z),X),J=hY(U);if(U.finalizer===">")M(H9(">"));return J},hY=(Z)=>{Z.parseOperand();let X=a4(Z).root;if(!X)return d(`Root was unexpectedly unset after parsing string '${Z.scanner.scanned}'`);if(Z.finalizer==="=")X=_U(Z);else if(Z.finalizer==="?")X=[X,"?"];if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.lookahead)M(H9(Z.scanner.lookahead));return X},a4=(Z)=>{while(Z.finalizer===void 0)mY(Z);return Z},mY=(Z)=>Z.hasRoot()?Z.parseOperator():Z.parseOperand();var z9=R(()=>{j();WX();JX()});class o2{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Z,X){this.scanner=Z,this.ctx=X}error(Z){return M(Z)}hasRoot(){return this.root!==void 0}setRoot(Z){this.root=Z}unsetRoot(){let Z=this.root;return this.root=void 0,Z}constrainRoot(...Z){this.root=this.root.constrain(Z[0],Z[1])}finalize(Z){if(this.groups.length)return this.error(u6(")"));this.finalizeBranches(),this.finalizer=Z}reduceLeftBound(Z,X){let Q=r2[X];if(!H0(Q,aQ))return this.error(q9(X));if(this.branches.leftBound)return this.error(eQ(this.branches.leftBound.limit,this.branches.leftBound.comparator,Z,Q));this.branches.leftBound={comparator:Q,limit:Z}}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 Z=this.groups.pop();if(!Z)return this.error(G3(")",this.scanner.unscanned));this.branches=Z}addPrefix(Z){this.branches.prefixes.push(Z)}applyPrefixes(){while(this.branches.prefixes.length){let Z=this.branches.prefixes.pop();this.root=Z==="keyof"?this.root.keyof():d(`Unexpected prefix '${Z}'`)}}pushRootToBranch(Z){this.assertRangeUnset(),this.applyPrefixes();let X=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(X)??X,Z==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Z==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return a4(new o2(this.scanner,this.ctx))}parseOperator(){return UX(this)}parseOperand(){return ZX(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(tQ(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(Z){return this.scanner.jumpForward(Z),this}}var WX=R(()=>{j();oQ();JX();z9();XX()});var uY="An empty string is not a valid generic parameter name",F9=(Z,X,Q)=>{Z.shiftUntilNonWhitespace();let U=Z.shiftUntilLookahead(D1);if(U===""){if(Z.lookahead===""&&X.length)return X;return M(uY)}return Z.shiftUntilNonWhitespace(),pY(Z,U,X,Q)},LU="extends ",pY=(Z,X,Q,U)=>{if(Z.shiftUntilNonWhitespace(),Z.unscanned.startsWith(LU))Z.jumpForward(LU.length);else{if(Z.lookahead===",")Z.shift();return Q.push(X),F9(Z,Q,U)}let J=a4(new o2(Z,U));return Q.push([X,J.root]),F9(Z,Q,U)};var YX=R(()=>{L0();j();WX();s2();z9()});var GX,VU,lY=`":" must be followed by exactly one return type e.g:
46
+ fn("string", ":", "number")(s => s.length)`;var qU=R(()=>{j();GX=class GX extends f0{constructor(Z){let X={$:Z,raw:Z.fn};super((...Q)=>{let U=Q.indexOf(":"),J=U===-1?Q.length-1:U-1,$=Q.slice(0,J+1),W=Z.parse($).assertHasKind("intersection"),Y=Z.intrinsic.unknown;if(U!==-1){if(U!==Q.length-2)return M(lY);Y=Z.parse(Q[U+1])}return(G)=>new VU(G,W,Y)},{attach:X})}};VU=class VU extends f0{raw;params;returns;expression;constructor(Z,X,Q){let U=`typed ${Z.name}`,J={[U]:(...W)=>{let Y=X.assert(W),G=Z(...Y);return Q.assert(G)}}[U];super(J);this.raw=Z,this.params=X,this.returns=Q;let $=X.expression;if($[0]==="["&&$[$.length-1]==="]")$=$.slice(1,-1);else if($.endsWith("[]"))$=`...${$}`;this.expression=`(${$}) => ${Q?.expression??"unknown"}`}}});var _X,n4,HU=(Z)=>Z.throw(),dY="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",cY="At most one key matcher may be specified per expression";var zU=R(()=>{L0();j();_X=class _X extends f0{$;constructor(Z){super((...X)=>new n4(Z)(...X),{bind:Z});this.$=Z}in(Z){return new n4(this.$,Z===void 0?void 0:this.$.parse(Z))}at(Z,X){return new n4(this.$).at(Z,X)}case(Z,X){return new n4(this.$).case(Z,X)}};n4=class n4 extends f0{$;in;key;branches=[];constructor(Z,X){super((Q)=>this.caseEntries(Object.entries(Q).map(([U,J])=>U==="default"?[U,J]:[this.$.parse(U),J])));this.$=Z,this.in=X}at(Z,X){if(this.key)M(cY);if(this.branches.length)M(dY);return this.key=Z,X?this.match(X):this}case(Z,X){return this.caseEntry(this.$.parse(Z),X)}caseEntry(Z,X){let U=(this.key?this.$.parse({[this.key]:Z}):Z).pipe(X);return this.branches.push(U),this}match(Z){return this(Z)}strings(Z){return this.caseEntries(Object.entries(Z).map(([X,Q])=>X==="default"?[X,Q]:[this.$.node("unit",{unit:X}),Q]))}caseEntries(Z){for(let X=0;X<Z.length;X++){let[Q,U]=Z[X];if(Q==="default"){if(X!==Z.length-1)M("default may only be specified as the last key of a switch definition");return this.default(U)}if(typeof U!=="function")return M(`Value for case "${Q}" must be a function (was ${q0(U)})`);this.caseEntry(Q,U)}return this}default(Z){if(typeof Z==="function")this.case(I.unknown,Z);let X={branches:this.branches,ordered:!0};if(Z==="never"||Z==="assert")X.meta={onFail:HU};let Q=this.$.node("union",X);if(!this.in)return this.$.finalize(Q);let U=this.in.pipe(Q);if(Z==="never"||Z==="assert")U=U.configureReferences({onFail:HU},"self");return this.$.finalize(U)}}});var B9=(Z,X)=>{if(t(Z)){if(Z[1]==="=")return[X.$.parseOwnDefinitionFormat(Z[0],X),"=",Z[2]];if(Z[1]==="?")return[X.$.parseOwnDefinitionFormat(Z[0],X),"?"]}return M9(Z,X)},FU="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",BU="Only required keys may specify default values, e.g. { value: 'number = 0' }";var LX=R(()=>{j();VX()});var MU=(Z,X)=>{let Q,U={},J=B2(Z);for(let[W,Y]of J){let G=rY(W);if(G.kind==="spread"){if(!O1(U))return M(sY);let H=X.$.parseOwnDefinitionFormat(Y,X);if(H.equals(I.object))continue;if(!H.hasKind("intersection")||!H.basis?.equals(I.object))return M(oY(H.expression));Q=H.structure;continue}if(G.kind==="undeclared"){if(Y!=="reject"&&Y!=="delete"&&Y!=="ignore")M(iY(Y));U.undeclared=Y;continue}let _=B9(Y,X),L=G;if(G.kind==="required"){if(!t(_))qX(U,"required",{key:G.normalized,value:_},X);else qX(U,"optional",_[1]==="="?{key:G.normalized,value:_[0],default:_[2]}:{key:G.normalized,value:_[0]},X);continue}if(t(_)){if(_[1]==="?")M(FU);if(_[1]==="=")M(BU)}if(G.kind==="optional"){qX(U,"optional",{key:G.normalized,value:_},X);continue}let V=X.$.parseOwnDefinitionFormat(L.normalized,X),q=J9(V,_,X.$);if(q.index)U.index=u(U.index,q.index);if(q.required)U.required=u(U.required,q.required)}let $=X.$.node("structure",U);return X.$.parseSchema({domain:"object",structure:Q?.merge($)??$})},qX=(Z,X,Q,U)=>{Z[X]=u(Z[X],U.$.node(X,Q))},iY=(Z)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${k(Z)})`,sY="Spread operator may only be used as the first key in an object",rY=(Z)=>typeof Z==="symbol"?{kind:"required",normalized:Z}:Z[Z.length-1]==="?"?Z[Z.length-2]===R2?{kind:"required",normalized:`${Z.slice(0,-2)}?`}:{kind:"optional",normalized:Z.slice(0,-1)}:Z[0]==="["&&Z[Z.length-1]==="]"?{kind:"index",normalized:Z.slice(1,-1)}:Z[0]===R2&&Z[1]==="["&&Z[Z.length-1]==="]"?{kind:"required",normalized:Z.slice(1)}:Z==="..."?{kind:"spread"}:Z==="+"?{kind:"undeclared"}:{kind:"required",normalized:Z==="\\..."?"...":Z==="\\+"?"+":Z},oY=(Z)=>`Spread operand must resolve to an object literal type (was ${Z})`;var RU=R(()=>{L0();j();LX()});var KU=(Z,X)=>$G(Z)?wU[Z[0]](Z,X):UG(Z)?PU[Z[1]](Z,X):null,aY=(Z,X)=>X.$.parseOwnDefinitionFormat(Z[1],X).keyof(),HX=(Z,X)=>{if(Z[2]===void 0)return M(tZ(Z[1],""));let Q=X.$.parseOwnDefinitionFormat(Z[0],X),U=X.$.parseOwnDefinitionFormat(Z[2],X);if(Z[1]==="|")return X.$.node("union",{branches:[Q,U]});let J=Z[1]==="&"?g0(Q,U,X.$):x4(Q,U,X.$);if(J instanceof A)return J.throw();return J},nY=(Z,X)=>X.$.parseOwnDefinitionFormat(Z[0],X).array(),tY=(Z,X)=>{if(typeof Z[2]!=="function")return M(TU("=>",Z[2]));return X.$.parseOwnDefinitionFormat(Z[0],X).pipe(Z[2])},TU=(Z,X)=>`${Z===":"?"Narrow":"Morph"} expression requires a function following '${Z}' (was ${typeof X})`,eY=(Z,X)=>{if(typeof Z[2]!=="function")return M(TU(":",Z[2]));return X.$.parseOwnDefinitionFormat(Z[0],X).constrain("predicate",Z[2])},ZG=(Z,X)=>X.$.parseOwnDefinitionFormat(Z[0],X).configure(Z[2],Z[3]),DU=(Z)=>Z,XG,QG,PU,UG=(Z)=>PU[Z[1]]!==void 0,JG=(Z)=>Z,wU,$G=(Z)=>wU[Z[0]]!==void 0,OU=(Z)=>`Expected a constructor following 'instanceof' operator (was ${Z})`;var AU=R(()=>{L0();j();eZ();XG=DU({"[]":nY,"?":()=>M(_9)}),QG=DU({"|":HX,"&":HX,":":eY,"=>":tY,"|>":HX,"@":ZG,"=":()=>M(L9)}),PU={...XG,...QG},wU=JG({keyof:aY,instanceof:(Z,X)=>{if(typeof Z[1]!=="function")return M(OU(w4(Z[1])));let Q=Z.slice(1).map((U)=>typeof U==="function"?X.$.node("proto",{proto:U}):M(OU(w4(U))));return Q.length===1?Q[0]:X.$.node("union",{branches:Q})},"===":(Z,X)=>X.$.units(Z.slice(1))})});var NU=(Z,X)=>{let Q=[{}],U=0;while(U<Z.length){let J=!1;if(Z[U]==="..."&&U<Z.length-1)J=!0,U++;let $=B9(Z[U],X),[W,Y,G]=!t($)?[$]:$;if(U++,J){if(!W.extends(O.intrinsic.Array))return M(GG(W.expression));Q=Q.flatMap((_)=>W.distribute((L)=>YG(l6(_),L)))}else Q=Q.map((_)=>{if(Y==="?")return jU(_,W);if(Y==="=")return WG(_,W,G);return zX(_,W)})}return X.$.parseSchema(Q.map((J)=>O1(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},zX=(Z,X)=>{if(Z.defaultables||Z.optionals)return M(Z.variadic?yZ:_G);if(Z.variadic)Z.postfix=u(Z.postfix,X);else Z.prefix=u(Z.prefix,X);return Z},jU=(Z,X)=>{if(Z.variadic)return M(EU);return Z.optionals=u(Z.optionals,X),Z},WG=(Z,X,Q)=>{if(Z.variadic)return M(EU);if(Z.optionals)return M(LG);return Z.defaultables=u(Z.defaultables,[[X,Q]]),Z},SU=(Z,X)=>{if(Z.postfix)M(CU);if(Z.variadic){if(!Z.variadic.equals(X))M(CU)}else Z.variadic=X.internal;return Z},YG=(Z,X)=>{let Q=X.select({method:"find",kind:"sequence"});if(!Q)return SU(Z,O.intrinsic.unknown);if(Q.prefix)for(let U of Q.prefix)zX(Z,U);if(Q.optionals)for(let U of Q.optionals)jU(Z,U);if(Q.variadic)SU(Z,Q.variadic);if(Q.postfix)for(let U of Q.postfix)zX(Z,U);return Z},GG=(Z)=>`Spread element must be an array (was ${Z})`,CU="A tuple may have at most one variadic element",_G="A required element may not follow an optional element",EU="An optional element may not follow a variadic element",LG="A defaultable element may not follow an optional element without a default";var bU=R(()=>{L0();j();LX()});var VG,M9=(Z,X)=>{if(typeof Z==="string"){if(X.args&&Object.keys(X.args).some((U)=>Z.includes(U)))return $X(Z,X);let Q=VG[X.$.name]??={};return Q[Z]??=$X(Z,X)}return E0(Z,"object")?qG(Z,X):M(FX(q0(Z)))},qG=(Z,X)=>{let Q=P4(Z);switch(Q){case void 0:if(E(Z,"root"))return Z;if("~standard"in Z)return HG(Z,X);return MU(Z,X);case"Array":return zG(Z,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0});case"Function":{let U=s1(Z)?Z():Z;if(E(U,"root"))return U;return M(FX("Function"))}default:return M(FX(Q??k(Z)))}},HG=(Z,X)=>X.$.intrinsic.unknown.pipe((Q,U)=>{let J=Z["~standard"].validate(Q);if(!J.issues)return J.value;for(let{message:$,path:W}of J.issues)if(W)if(W.length)U.error({problem:s7($),relativePath:W.map((Y)=>typeof Y==="object"?Y.key:Y)});else U.error({message:$});else U.error({message:$})}),zG=(Z,X)=>KU(Z,X)??NU(Z,X),FX=(Z)=>`Type definitions must be strings or objects (was ${Z})`;var VX=R(()=>{L0();j();RU();z9();AU();bU();VG={}});var BX;var MX=R(()=>{L0();j();BX=class BX extends f0{constructor(Z){let X=Object.assign({errors:y0,hkt:R0,$:Z,raw:Z.parse,module:Z.constructor.module,scope:Z.constructor.scope,declare:Z.declare,define:Z.define,match:Z.match,generic:Z.generic,schema:Z.schema,keywords:Z.ambient,unit:Z.unit,enumerated:Z.enumerated,instanceOf:Z.instanceOf,valueOf:Z.valueOf,or:Z.or,and:Z.and,merge:Z.merge,pipe:Z.pipe,fn:Z.fn},Z.ambientAttachments);super((...Q)=>{if(Q.length===1)return Z.parse(Q[0]);if(Q.length===2&&typeof Q[0]==="string"&&Q[0][0]==="<"&&Q[0][Q[0].length-1]===">"){let U=Q[0].slice(1,-1),J=Z.parseGenericParams(U,{});return new Z2(J,Q[1],Z,Z,null)}return Z.parse(Q)},{attach:X})}}});var a2,R9,t4,m;var _1=R(()=>{L0();j();qU();YX();zU();VX();MX();a2=O;R9=class R9 extends $9{get ambientAttachments(){if(!a2.typeAttachments)return;return this.cacheGetter("ambientAttachments",y(a2.typeAttachments,(Z,X)=>[Z,this.bindReference(X)]))}preparseOwnAliasEntry(Z,X){let Q=Z.indexOf("<");if(Q===-1){if(E(X,"module")||E(X,"generic"))return[Z,X];let $=this.name==="ark"?Z:Z==="root"?this.name:`${this.name}.${Z}`,W=this.resolvedConfig.keywords?.[$];if(W)X=[X,"@",W];return[Z,X]}if(Z[Z.length-1]!==">")M("'>' must be the last character of a generic declaration in a scope");let U=Z.slice(0,Q),J=Z.slice(Q+1,-1);return[U,()=>{let $=this.parseGenericParams(J,{alias:U});return S3($,X,this)}]}parseGenericParams(Z,X){return F9(new I4(Z),[],this.createParseContext({...X,def:Z,prefix:"generic"}))}normalizeRootScopeValue(Z){if(s1(Z)&&!E(Z,"generic"))return Z();return Z}preparseOwnDefinitionFormat(Z,X){return{...X,def:Z,prefix:X.alias??"type"}}parseOwnDefinitionFormat(Z,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let U=M9(Z,X);if(t(U)){if(U[1]==="=")return M(L9);if(U[1]==="?")return M(_9)}return U}unit=(Z)=>this.units([Z]);valueOf=(Z)=>this.units(b7(Z));enumerated=(...Z)=>this.units(Z);instanceOf=(Z)=>this.node("proto",{proto:Z},{prereduced:!0});or=(...Z)=>this.schema(Z.map((X)=>this.parse(X)));and=(...Z)=>Z.reduce((X,Q)=>X.and(this.parse(Q)),this.intrinsic.unknown);merge=(...Z)=>Z.reduce((X,Q)=>X.merge(this.parse(Q)),this.intrinsic.object);pipe=(...Z)=>this.intrinsic.unknown.pipe(...Z);fn=new GX(this);match=new _X(this);declare=()=>({type:this.type});define(Z){return Z}type=new BX(this);static scope=(Z,X={})=>new R9(Z,X);static module=(Z,X={})=>this.scope(Z,X).export()};t4=Object.assign(R9.scope,{define:(Z)=>Z}),m=R9});var IU,FG,fU;var yU=R(()=>{L0();j();_1();IU=class IU extends R0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'};FG=a0(["base",I.object],["props",I.object])((Z)=>Z.base.merge(Z.props),IU),fU=m.module({Key:I.key,Merge:FG})});var kU,BG,gU;var vU=R(()=>{L0();j();_1();kU=class kU extends R0{};BG=a0("element")((Z)=>{let X=Z.element.exclude(I.Array),Q=X.array();return X.rawOr(Q).pipe(i1).distribute((U)=>U.assertHasKind("morph").declareOut(Q),s)},kU),gU=m.module({root:I.Array,readonly:"root",index:I.nonNegativeIntegerString,liftFrom:BG},{name:"Array"})});var RX,MG,xU,hU;var mU=R(()=>{L0();j();_1();RX=s(["string",O2.FileConstructor]),MG=RX.rawOr(RX.array()),xU=s({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:MG}}),hU=m.module({root:["instanceof",FormData],value:RX,parsed:xU,parse:s({in:FormData,morphs:(Z)=>{let X={};for(let[Q,U]of Z)if(Q in X){let J=X[Q];if(typeof J==="string"||J instanceof O2.FileConstructor)X[Q]=[J,U];else J.push(U)}else X[Q]=U;return X},declaredOut:xU})},{name:"FormData"})});var uU;var pU=R(()=>{_1();uU=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 RG,lU;var dU=R(()=>{j();_1();vU();mU();pU();RG={Boolean:1,Number:1,String:1},lU=m.module({...y({...w8,...S8},(Z,X)=>(Z in RG)?[]:[Z,["instanceof",X]]),Array:gU,TypedArray:uU,FormData:hU})});var OG,KG,O9;var OX=R(()=>{L0();_1();OG=s({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"}),KG=s({domain:"number",divisor:1}),O9=m.module({root:I.number,integer:KG,epoch:OG,safe:s({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 Q0=(Z,X,Q)=>{let U={domain:"string",pattern:{rule:Z.source,flags:Z.flags,meta:X}};if(Q)U.meta={format:Q};return i2("intersection",U)},cU,U5,TG,DG,iU,PG,wG=(Z)=>{let X=Z.replace(/[ -]+/g,""),Q=0,U,J,$=!1;for(let W=X.length-1;W>=0;W--){if(U=X.substring(W,W+1),J=Number.parseInt(U,10),$)J*=2,Q+=J>=10?J%10+1:J;else Q+=J;$=!$}return!!(Q%10===0?X:!1)},AG,SG,CG,NG=(Z)=>!Number.isNaN(new Date(Z).valueOf()),sU,rU,jG,oU,EG,bG,IG,aU="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Q2,fG,V0="(?:[0-9a-fA-F]{1,4})",yG,kG,n2="a JSON string",J5=(Z)=>{if(!(Z instanceof SyntaxError))throw Z;return`must be ${n2} (${Z})`},gG,vG=(Z,X)=>{if(Z.length===0)return X.error({code:"predicate",expected:n2,actual:"empty"});try{return JSON.parse(Z)}catch(Q){return X.error({code:"predicate",expected:n2,problem:J5(Q)})}},xG,nU,hG,$5,e4,K9,mG,uG,pG,lG,dG,tU,cG,eU="a regex pattern",iG,sG,rG,Z5,oG,X5,aG,nG=(Z)=>URL.canParse(Z),Q5,tG,eG,W5;var Y5=R(()=>{L0();j();_1();OX();cU=Q0(C4,"a well-formed integer string"),U5=m.module({root:cU,parse:s({in:cU,morphs:(Z,X)=>{let Q=Number.parseInt(Z);return Number.isSafeInteger(Q)?Q:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:I.integer})},{name:"string.integer"}),TG=Q0(/^[\dA-Fa-f]+$/,"hex characters only"),DG=m.module({root:Q0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Q0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),iU=Q0(/^[A-Z].*$/,"capitalized"),PG=m.module({root:s({in:"string",morphs:(Z)=>Z.charAt(0).toUpperCase()+Z.slice(1),declaredOut:iU}),preformatted:iU},{name:"string.capitalize"}),AG=/^(?: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}))$/,SG=s({domain:"string",pattern:{meta:"a credit card number",rule:AG.source},predicate:{meta:"a credit card number",predicate:wG}}),CG=/^([+-]?\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)?)?)?)?$/,sU=s({domain:"string",predicate:{meta:"a parsable date",predicate:NG}}).assertHasKind("intersection"),rU=U5.root.internal.narrow((Z,X)=>{let Q=Number.parseInt(Z),U=O9.epoch(Q);if(U instanceof y0)return X.errors.merge(U),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),jG=m.module({root:rU,parse:s({in:rU,morphs:(Z)=>new Date(Z),declaredOut:I.Date})},{name:"string.date.epoch"}),oU=Q0(CG,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),EG=m.module({root:oU,parse:s({in:oU,morphs:(Z)=>new Date(Z),declaredOut:I.Date})},{name:"string.date.iso"}),bG=m.module({root:sU,parse:s({declaredIn:sU,in:"string",morphs:(Z,X)=>{let Q=new Date(Z);if(Number.isNaN(Q.valueOf()))return X.error("a parsable date");return Q},declaredOut:I.Date}),iso:EG,epoch:jG},{name:"string.date"}),IG=Q0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Q2=`(${aU}[.]){3}${aU}`,fG=new RegExp(`^${Q2}$`),yG=new RegExp(`^((?:${V0}:){7}(?:${V0}|:)|(?:${V0}:){6}(?:${Q2}|:${V0}|:)|(?:${V0}:){5}(?::${Q2}|(:${V0}){1,2}|:)|(?:${V0}:){4}(?:(:${V0}){0,1}:${Q2}|(:${V0}){1,3}|:)|(?:${V0}:){3}(?:(:${V0}){0,2}:${Q2}|(:${V0}){1,4}|:)|(?:${V0}:){2}(?:(:${V0}){0,3}:${Q2}|(:${V0}){1,5}|:)|(?:${V0}:){1}(?:(:${V0}){0,4}:${Q2}|(:${V0}){1,6}|:)|(?::((?::${V0}){0,5}:${Q2}|(?::${V0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),kG=m.module({root:["v4 | v6","@","an IP address"],v4:Q0(fG,"an IPv4 address","ipv4"),v6:Q0(yG,"an IPv6 address","ipv6")},{name:"string.ip"}),gG=s({meta:n2,domain:"string",predicate:{meta:n2,predicate:(Z,X)=>{try{return JSON.parse(Z),!0}catch(Q){return X.reject({code:"predicate",expected:n2,problem:J5(Q)})}}}}),xG=m.module({root:gG,parse:s({meta:"safe JSON string parser",in:"string",morphs:vG,declaredOut:I.jsonObject})},{name:"string.json"}),nU=Q0(/^[a-z]*$/,"only lowercase letters"),hG=m.module({root:s({in:"string",morphs:(Z)=>Z.toLowerCase(),declaredOut:nU}),preformatted:nU},{name:"string.lower"}),$5=["NFC","NFD","NFKC","NFKD"],e4=y($5,(Z,X)=>[X,s({domain:"string",predicate:(Q)=>Q.normalize(X)===Q,meta:`${X}-normalized unicode`})]),K9=y($5,(Z,X)=>[X,s({in:"string",morphs:(Q)=>Q.normalize(X),declaredOut:e4[X]})]),mG=m.module({root:K9.NFC,preformatted:e4.NFC},{name:"string.normalize.NFC"}),uG=m.module({root:K9.NFD,preformatted:e4.NFD},{name:"string.normalize.NFD"}),pG=m.module({root:K9.NFKC,preformatted:e4.NFKC},{name:"string.normalize.NFKC"}),lG=m.module({root:K9.NFKD,preformatted:e4.NFKD},{name:"string.normalize.NFKD"}),dG=m.module({root:"NFC",NFC:mG,NFD:uG,NFKC:pG,NFKD:lG},{name:"string.normalize"}),tU=Q0(x6,"a well-formed numeric string"),cG=m.module({root:tU,parse:s({in:tU,morphs:(Z)=>Number.parseFloat(Z),declaredOut:I.number})},{name:"string.numeric"}),iG=s({domain:"string",predicate:{meta:eU,predicate:(Z,X)=>{try{return new RegExp(Z),!0}catch(Q){return X.reject({code:"predicate",expected:eU,problem:String(Q)})}}},meta:{format:"regex"}}),sG=/^(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-]+)*))?$/,rG=Q0(sG,"a semantic version (see https://semver.org/)"),Z5=Q0(/^\S.*\S$|^\S?$/,"trimmed"),oG=m.module({root:s({in:"string",morphs:(Z)=>Z.trim(),declaredOut:Z5}),preformatted:Z5},{name:"string.trim"}),X5=Q0(/^[A-Z]*$/,"only uppercase letters"),aG=m.module({root:s({in:"string",morphs:(Z)=>Z.toUpperCase(),declaredOut:X5}),preformatted:X5},{name:"string.upper"}),Q5=s({domain:"string",predicate:{meta:"a URL string",predicate:nG},meta:{format:"uri"}}),tG=m.module({root:Q5,parse:s({declaredIn:Q5,in:"string",morphs:(Z,X)=>{try{return new URL(Z)}catch{return X.error("a URL string")}},declaredOut:s(URL)})},{name:"string.url"}),eG=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:Q0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Q0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Q0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Q0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Q0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Q0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Q0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Q0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),W5=m.module({root:I.string,alpha:Q0(/^[A-Za-z]*$/,"only letters"),alphanumeric:Q0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:TG,base64:DG,capitalize:PG,creditCard:SG,date:bG,digits:Q0(/^\d*$/,"only digits 0-9"),email:IG,integer:U5,ip:kG,json:xG,lower:hG,normalize:dG,numeric:cG,regex:iG,semver:rG,trim:oG,upper:aG,url:tG,uuid:eG},{name:"string"})});var G5,_5,Z_,L5,V5,X_,q5,Q_,H5,U_,z5,J_,F5,$_,B5,W_,M5,Y_,R5;var O5=R(()=>{L0();j();_1();G5=m.module({bigint:I.bigint,boolean:I.boolean,false:I.false,never:I.never,null:I.null,number:I.number,object:I.object,string:I.string,symbol:I.symbol,true:I.true,unknown:I.unknown,undefined:I.undefined}),_5=m.module({root:I.unknown,any:I.unknown},{name:"unknown"}),Z_=m.module({root:I.jsonObject,stringify:i2("morph",{in:I.jsonObject,morphs:(Z)=>JSON.stringify(Z),declaredOut:I.string})},{name:"object.json"}),L5=m.module({root:I.object,json:Z_},{name:"object"});V5=class V5 extends R0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'};X_=a0(["K",I.key],"V")((Z)=>({domain:"object",index:{signature:Z.K,value:Z.V}}),V5);q5=class q5 extends R0{description='pick a set of properties from an object like `Pick(User, "name | age")`'};Q_=a0(["T",I.object],["K",I.key])((Z)=>Z.T.pick(Z.K),q5);H5=class H5 extends R0{description='omit a set of properties from an object like `Omit(User, "age")`'};U_=a0(["T",I.object],["K",I.key])((Z)=>Z.T.omit(Z.K),H5);z5=class z5 extends R0{description="make all named properties of an object optional like `Partial(User)`"};J_=a0(["T",I.object])((Z)=>Z.T.partial(),z5);F5=class F5 extends R0{description="make all named properties of an object required like `Required(User)`"};$_=a0(["T",I.object])((Z)=>Z.T.required(),F5);B5=class B5 extends R0{description='exclude branches of a union like `Exclude("boolean", "true")`'};W_=a0("T","U")((Z)=>Z.T.exclude(Z.U),B5);M5=class M5 extends R0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'};Y_=a0("T","U")((Z)=>Z.T.extract(Z.U),M5),R5=m.module({Exclude:W_,Extract:Y_,Omit:U_,Partial:J_,Pick:Q_,Record:X_,Required:$_})});var h1,z0,o,G_,__,L_,UT,V_,q_;var K5=R(()=>{_1();yU();dU();OX();Y5();O5();h1=t4({...G5,...R5,...lU,...fU,string:W5,number:O9,object:L5,unknown:_5},{prereducedAliases:!0,name:"ark"}),z0=h1.export();Object.assign(a2.ambient,z0);a2.typeAttachments={string:z0.string.root,number:z0.number.root,bigint:z0.bigint,boolean:z0.boolean,symbol:z0.symbol,undefined:z0.undefined,null:z0.null,object:z0.object.root,unknown:z0.unknown.root,false:z0.false,true:z0.true,never:z0.never,arrayIndex:z0.Array.index,Key:z0.Key,Record:z0.Record,Array:z0.Array.root,Date:z0.Date};o=Object.assign(h1.type,a2.typeAttachments),G_=h1.match,__=h1.fn,L_=h1.generic,UT=h1.schema,V_=h1.define,q_=h1.declare});var T5=R(()=>{L0()});var KX=R(()=>{L0();j();yQ();YX();K5();T5();_1();MX();kQ()});class v0{static evaluate(Z,X){if(Z===null||Z===void 0)return console.error(`Error evaluating expression: ${Z}`),null;try{if(Z.includes("${")){let Q=this.interpolate(Z,X);if(!isNaN(Number(Q))&&Q.trim()!=="")return Number(Q);return Q}return this.evaluateExpression(Z,X)}catch(Q){return console.error(`Error evaluating expression: ${Z}`,Q),null}}static interpolate(Z,X){return Z.replace(T9.TEMPLATE_INTERPOLATION,(Q,U)=>{try{let J=this.evaluateExpression(U,X);if(J===void 0||J===null)return"undefined";return String(J)}catch(J){return console.error(`Error in interpolation: ${Q}`,J),Q}})}static evaluateMathExpression(Z){try{return Function("Math",`return ${Z}`)(Math)}catch(X){throw Error(`Error evaluating mathematical expression: ${Z}`)}}static evaluateExpression(Z,X){if(T9.NESTED_PROPERTY_ACCESS.test(Z))return this.getNestedValue(Z,X);if(T9.SINGLE_LEVEL_ACCESS.test(Z))return this.getNestedValue(Z,X);try{return Function("context","with(context) { return "+Z+" }")(X)}catch(Q){return console.error(`ERROR evaluating expression '${Z}':`,Q),Z}}static getNestedValue(Z,X){let Q=Z.split("."),U=X;for(let J of Q){if(U===null||U===void 0||typeof U!=="object"||!(J in U))return;U=U[J]}return U}static findVariableInContext(Z,X){let Q=this.getNestedValue(Z,X);if(Q!==void 0)return Q;for(let U of D5){let J=`${U}.${Z}`,$=this.getNestedValue(J,X);if($!==void 0)return $}return}static evaluateMath(Z,X){let Q=Z;Q=Q.replace(/\b(data|vars|env|state|request|computed)(\.[a-zA-Z_][a-zA-Z0-9_]*)+/g,(U)=>{let J=this.getNestedValue(U,X);if(J!==void 0)return typeof J==="string"?`"${J}"`:String(J);return U}),Q=Q.replace(T9.WORD_BOUNDARY,(U)=>{if(z_.includes(U))return U;if(D5.has(U))return U;let J=this.findVariableInContext(U,X);if(J!==void 0)return typeof J==="string"?`"${J}"`:String(J);return U});try{return this.evaluateMathExpression(Q)}catch(U){return console.error(`Error in mathematical evaluation: ${Z}`,U),NaN}}}var H_,D5,n0,z_,T9;var D9=R(()=>{H_={DATA:"data",VARS:"vars",REQUEST:"request",COMPUTED:"computed",ENV:"env",STATE:"state",EVENT:"event",TIMESTAMP:"timestamp"},D5=new Set(Object.values(H_)),n0={RANDOM:"random",FLOOR:"floor",CEIL:"ceil",ROUND:"round",SQRT:"sqrt",ABS:"abs",POW:"pow",MIN:"min",MAX:"max",SIN:"sin",COS:"cos",TAN:"tan"},z_=[n0.RANDOM,n0.FLOOR,n0.CEIL,n0.ROUND,n0.SQRT,n0.ABS,n0.POW,n0.MIN,n0.MAX,n0.SIN,n0.COS,n0.TAN],T9={TEMPLATE_INTERPOLATION:/\$\{([^}]+)\}/g,NESTED_PROPERTY_ACCESS:/^(data|vars|request|computed|env|state)(\.[a-zA-Z0-9_]+)+$/,SINGLE_LEVEL_ACCESS:/^(vars|env|state)(\.[a-zA-Z0-9_]+)$/,WORD_BOUNDARY:/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g}});class TX{store=new Map;async loadState(){return new Map(this.store)}async saveState(Z,X){this.store.set(Z,X)}async deleteState(Z){this.store.delete(Z)}async clearState(){this.store.clear()}}class K0{static instance;state;persistence;constructor(){this.state={},this.persistence=new TX}static getInstance(){if(!K0.instance)K0.instance=new K0;return K0.instance}setPersistence(Z){this.persistence=Z}async initialize(){let Z=await this.persistence.loadState();if(Z instanceof Map)this.state=Object.fromEntries(Z);else this.state=Z||{};console.log(`[StateManager] Initialized with ${Object.keys(this.state).length} root keys.`)}get(Z){return this.state[Z]}async set(Z,X){this.state[Z]=X,await this.persistence.saveState(Z,X)}async increment(Z,X=1){let Q=this.state[Z]||0,U=Number(Q)+X;return this.state[Z]=U,await this.persistence.saveState(Z,U),U}async decrement(Z,X=1){return this.increment(Z,-X)}async delete(Z){if(Z in this.state)return delete this.state[Z],await this.persistence.deleteState(Z),!0;return!1}async clear(){this.state={},await this.persistence.clearState()}async applyConfig(Z){if(!Z.state)return;for(let[X,Q]of Object.entries(Z.state))if(typeof Q!=="object"||Q===null||!("value"in Q)){if(this.state[X]===void 0)await this.set(X,Q)}else{let U=Q;if(this.state[X]===void 0)await this.set(X,U.value);if(U.lifecycle?.ttl)this.setupTTL(X,U.lifecycle.ttl)}}setupTTL(Z,X){let Q=0;if(typeof X==="number")Q=X;else{let U=X.match(/^(\d+)([smhd])$/);if(U&&U[1]&&U[2]){let J=parseInt(U[1]),$=U[2];Q=J*({s:1000,m:60000,h:3600000,d:86400000}[$]||0)}}if(Q>0)setTimeout(()=>{this.delete(Z).catch(console.error)},Q)}getAll(){return{...this.state}}getLiveProxy(){let Z=this;function X(Q,U=[]){return new Proxy(Q,{get(J,$){let W=J[$];if(W&&typeof W==="object"&&!Array.isArray(W))return X(W,[...U,$]);return W},set(J,$,W){if(typeof $!=="string")return!1;J[$]=W;let Y=U.length>0?U[0]:$;if(Y)Z.persistence.saveState(Y,Z.state[Y]);return!0}})}return X(this.state)}}var Z6=()=>{};var DX={};f6(DX,{BuiltInAction:()=>S0,ActionRegistry:()=>X6});class X6{static instance;actions=new Map;constructor(Z=!0){if(Z)this.registerDefaults()}static getInstance(Z=!0){if(!this.instance)this.instance=new X6(Z);return this.instance}register(Z,X){let Q=Z.toUpperCase();if(typeof X==="function")this.actions.set(Q,{handler:X});else this.actions.set(Q,X)}get(Z){return this.actions.get(Z.toUpperCase())?.handler}getDefinition(Z){return this.actions.get(Z.toUpperCase())}getDefinitions(){let Z={};return this.actions.forEach((X,Q)=>{Z[Q]=X}),Z}get Handlers(){let Z=new Map;return this.actions.forEach((X,Q)=>{Z.set(Q,X.handler)}),Z}registerDefaults(){this.register(S0.LOG,{description:"Logs a message to the console with string interpolation support",params:o({"message?":"string","content?":"string"}),returns:o({message:"string"}),handler:(Z,X)=>{let Q=Z.params?.message||Z.params?.content||"Log Trigger",U=typeof Q==="string"?v0.interpolate(Q,X):String(Q);return console.log(`[TriggerLog] ${U}`),{message:U}}}),this.register(S0.MATH,{description:"Evaluates a mathematical expression or performs string concatenation",params:o({expression:"string"}),returns:o("number | string"),handler:(Z,X)=>{let Q=String(Z.params?.expression||"0");return v0.evaluate(Q,X)}}),this.register(S0.RESPONSE,{description:"Constructs a standardized response object (useful for webhooks/APIs)",params:o({"content?":"string","body?":"string","statusCode?":"number","headers?":"Record<string, string>"}),returns:o({statusCode:"number",headers:"Record<string, string>",body:"string"}),handler:(Z,X)=>{let Q=Z.params?.content||Z.params?.body||"",U=typeof Q==="string"?v0.interpolate(Q,X):String(Q);return{statusCode:Z.params?.statusCode||200,headers:Z.params?.headers||{"Content-Type":"application/json"},body:U}}}),this.register(S0.EXECUTE,{description:"Spawns a shell command and returns the output (Bun only)",params:o({"command?":"string","content?":"string","safe?":"boolean"}),returns:o({command:"string",stdout:"string",stderr:"string",exitCode:"number"}).or(o({command:"string",error:"string"})),handler:async(Z,X)=>{let Q=Z.params?.command||Z.params?.content||"",U=typeof Q==="string"?v0.interpolate(Q,X):String(Q);if(!Z.params?.safe)console.warn(`[Trigger] Executing unsafe command: ${U}`);try{if(typeof Bun>"u")return{command:U,error:"Bun is required for 'execute' action"};let J=Bun.spawn(U.split(" "),{stdout:"pipe",stderr:"pipe"}),[$,W]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]);return{command:U,stdout:$,stderr:W,exitCode:await J.exited}}catch(J){return{command:U,error:String(J)}}}}),this.register(S0.FORWARD,{description:"Forwards the current event data to a remote URL via HTTP",params:o({url:"string","method?":"'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'","headers?":"Record<string, string>"}),returns:o({url:"string",method:"string",status:"number",headers:"Record<string, string>",body:"string"}).or(o({url:"string",method:"string",error:"string"})),handler:async(Z,X)=>{let Q=Z.params?.url||"",U=typeof Q==="string"?v0.interpolate(Q,X):String(Q),J=String(Z.params?.method||"POST").toUpperCase(),W=["POST","PUT","PATCH"].includes(J);try{let Y=await fetch(U,{method:J,headers:{"Content-Type":"application/json",...typeof Z.params?.headers==="object"&&Z.params.headers!==null&&!Array.isArray(Z.params.headers)?Z.params.headers:{}},...W?{body:JSON.stringify(X.data)}:{}});return{url:U,method:J,status:Y.status,headers:(()=>{let G={};return Y.headers.forEach((_,L)=>G[L]=_),G})(),body:await Y.text()}}catch(Y){return{url:U,method:J,error:String(Y)}}}}),this.register(S0.STATE_SET,{description:"Sets a value in the persistent state",params:o({key:"string",value:"unknown"}),returns:o({key:"string",value:"unknown"}),handler:async(Z,X)=>{let Q=String(Z.params?.key||""),U=Z.params?.value;if(!Q)return{error:"Missing key for STATE_SET"};let J=U;if(typeof U==="string"&&U.includes("${"))J=v0.interpolate(U,X);return await K0.getInstance().set(Q,J),{key:Q,value:J}}}),this.register(S0.STATE_INCREMENT,{description:"Increments a numeric value in the persistent state",params:o({key:"string","amount?":"number"}),returns:o({key:"string",newValue:"number"}),handler:async(Z,X)=>{let Q=String(Z.params?.key||""),U=Number(Z.params?.amount)||1;if(!Q)return{error:"Missing key for STATE_INCREMENT"};let J=await K0.getInstance().increment(Q,U);return{key:Q,newValue:J}}}),this.register(S0.STATE_GET,{description:"Reads a value from state and optionally stores it in context.env",params:o({key:"string","as?":"string"}),returns:o({key:"string",value:"unknown","storedAs?":"string"}),handler:async(Z,X)=>{let Q=String(Z.params?.key||""),U=String(Z.params?.as||Q);if(!Q)return{error:"Missing key for STATE_GET"};let J=await K0.getInstance().get(Q);if(!X.env)X.env={};return X.env[U]=J,{key:Q,value:J,storedAs:U}}}),this.register(S0.STATE_DELETE,{description:"Deletes a key from the persistent state",params:o({key:"string"}),returns:o({key:"string",deleted:"boolean"}),handler:async(Z,X)=>{let Q=String(Z.params?.key||"");if(!Q)return{error:"Missing key for STATE_DELETE"};let U=await K0.getInstance().delete(Q);return{key:Q,deleted:U}}}),this.register(S0.EMIT_EVENT,{description:"Emits a new event back into the system",params:o({event:"string","data?":"object"}),returns:o({event:"string",payload:"object"}),handler:(Z,X)=>{return{event:String(Z.params?.event||""),payload:Z.params?.data||{}}}}),this.register(S0.NOTIFY,{description:"Sends a notification to a specific target",params:o({"message?":"string","content?":"string","target?":"string"}),returns:o({target:"string",message:"string"}),handler:(Z,X)=>{let Q=Z.params?.message||Z.params?.content||"Notification",U=Z.params?.target||"default";return console.log(`[Notification] To: ${U}, Msg: ${Q}`),{target:U,message:Q}}}),this.register(S0.STATE_OP,{description:"Executes a custom JavaScript block with access to context and state",params:o({run:"string"}),returns:o("unknown"),handler:(Z,X)=>{if(Z.params?.run)return Function("context","state","data","vars","env","helpers",`with(context) { ${Z.params.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers);return{warning:"Missing 'run' param for STATE_OP"}}})}}var S0;var t2=R(()=>{KX();D9();Z6();S0={LOG:"LOG",MATH:"MATH",RESPONSE:"RESPONSE",EXECUTE:"EXECUTE",FORWARD:"FORWARD",STATE_SET:"STATE_SET",STATE_INCREMENT:"STATE_INCREMENT",STATE_GET:"STATE_GET",STATE_DELETE:"STATE_DELETE",EMIT_EVENT:"EMIT_EVENT",NOTIFY:"NOTIFY",STATE_OP:"STATE_OP"}});var sJ={};f6(sJ,{sep:()=>dJ,resolve:()=>B8,relative:()=>vJ,posix:()=>iJ,parse:()=>lJ,normalize:()=>q7,join:()=>gJ,isAbsolute:()=>kJ,format:()=>pJ,extname:()=>uJ,dirname:()=>hJ,delimiter:()=>cJ,default:()=>YL,basename:()=>mJ,_makeLong:()=>xJ});function j1(Z){if(typeof Z!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(Z))}function yJ(Z,X){var Q="",U=0,J=-1,$=0,W;for(var Y=0;Y<=Z.length;++Y){if(Y<Z.length)W=Z.charCodeAt(Y);else if(W===47)break;else W=47;if(W===47){if(J===Y-1||$===1);else if(J!==Y-1&&$===2){if(Q.length<2||U!==2||Q.charCodeAt(Q.length-1)!==46||Q.charCodeAt(Q.length-2)!==46){if(Q.length>2){var G=Q.lastIndexOf("/");if(G!==Q.length-1){if(G===-1)Q="",U=0;else Q=Q.slice(0,G),U=Q.length-1-Q.lastIndexOf("/");J=Y,$=0;continue}}else if(Q.length===2||Q.length===1){Q="",U=0,J=Y,$=0;continue}}if(X){if(Q.length>0)Q+="/..";else Q="..";U=2}}else{if(Q.length>0)Q+="/"+Z.slice(J+1,Y);else Q=Z.slice(J+1,Y);U=Y-J-1}J=Y,$=0}else if(W===46&&$!==-1)++$;else $=-1}return Q}function WL(Z,X){var Q=X.dir||X.root,U=X.base||(X.name||"")+(X.ext||"");if(!Q)return U;if(Q===X.root)return Q+U;return Q+Z+U}function B8(){var Z="",X=!1,Q;for(var U=arguments.length-1;U>=-1&&!X;U--){var J;if(U>=0)J=arguments[U];else{if(Q===void 0)Q=process.cwd();J=Q}if(j1(J),J.length===0)continue;Z=J+"/"+Z,X=J.charCodeAt(0)===47}if(Z=yJ(Z,!X),X)if(Z.length>0)return"/"+Z;else return"/";else if(Z.length>0)return Z;else return"."}function q7(Z){if(j1(Z),Z.length===0)return".";var X=Z.charCodeAt(0)===47,Q=Z.charCodeAt(Z.length-1)===47;if(Z=yJ(Z,!X),Z.length===0&&!X)Z=".";if(Z.length>0&&Q)Z+="/";if(X)return"/"+Z;return Z}function kJ(Z){return j1(Z),Z.length>0&&Z.charCodeAt(0)===47}function gJ(){if(arguments.length===0)return".";var Z;for(var X=0;X<arguments.length;++X){var Q=arguments[X];if(j1(Q),Q.length>0)if(Z===void 0)Z=Q;else Z+="/"+Q}if(Z===void 0)return".";return q7(Z)}function vJ(Z,X){if(j1(Z),j1(X),Z===X)return"";if(Z=B8(Z),X=B8(X),Z===X)return"";var Q=1;for(;Q<Z.length;++Q)if(Z.charCodeAt(Q)!==47)break;var U=Z.length,J=U-Q,$=1;for(;$<X.length;++$)if(X.charCodeAt($)!==47)break;var W=X.length,Y=W-$,G=J<Y?J:Y,_=-1,L=0;for(;L<=G;++L){if(L===G){if(Y>G){if(X.charCodeAt($+L)===47)return X.slice($+L+1);else if(L===0)return X.slice($+L)}else if(J>G){if(Z.charCodeAt(Q+L)===47)_=L;else if(L===0)_=0}break}var V=Z.charCodeAt(Q+L),q=X.charCodeAt($+L);if(V!==q)break;else if(V===47)_=L}var H="";for(L=Q+_+1;L<=U;++L)if(L===U||Z.charCodeAt(L)===47)if(H.length===0)H+="..";else H+="/..";if(H.length>0)return H+X.slice($+_);else{if($+=_,X.charCodeAt($)===47)++$;return X.slice($)}}function xJ(Z){return Z}function hJ(Z){if(j1(Z),Z.length===0)return".";var X=Z.charCodeAt(0),Q=X===47,U=-1,J=!0;for(var $=Z.length-1;$>=1;--$)if(X=Z.charCodeAt($),X===47){if(!J){U=$;break}}else J=!1;if(U===-1)return Q?"/":".";if(Q&&U===1)return"//";return Z.slice(0,U)}function mJ(Z,X){if(X!==void 0&&typeof X!=="string")throw TypeError('"ext" argument must be a string');j1(Z);var Q=0,U=-1,J=!0,$;if(X!==void 0&&X.length>0&&X.length<=Z.length){if(X.length===Z.length&&X===Z)return"";var W=X.length-1,Y=-1;for($=Z.length-1;$>=0;--$){var G=Z.charCodeAt($);if(G===47){if(!J){Q=$+1;break}}else{if(Y===-1)J=!1,Y=$+1;if(W>=0)if(G===X.charCodeAt(W)){if(--W===-1)U=$}else W=-1,U=Y}}if(Q===U)U=Y;else if(U===-1)U=Z.length;return Z.slice(Q,U)}else{for($=Z.length-1;$>=0;--$)if(Z.charCodeAt($)===47){if(!J){Q=$+1;break}}else if(U===-1)J=!1,U=$+1;if(U===-1)return"";return Z.slice(Q,U)}}function uJ(Z){j1(Z);var X=-1,Q=0,U=-1,J=!0,$=0;for(var W=Z.length-1;W>=0;--W){var Y=Z.charCodeAt(W);if(Y===47){if(!J){Q=W+1;break}continue}if(U===-1)J=!1,U=W+1;if(Y===46){if(X===-1)X=W;else if($!==1)$=1}else if(X!==-1)$=-1}if(X===-1||U===-1||$===0||$===1&&X===U-1&&X===Q+1)return"";return Z.slice(X,U)}function pJ(Z){if(Z===null||typeof Z!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Z);return WL("/",Z)}function lJ(Z){j1(Z);var X={root:"",dir:"",base:"",ext:"",name:""};if(Z.length===0)return X;var Q=Z.charCodeAt(0),U=Q===47,J;if(U)X.root="/",J=1;else J=0;var $=-1,W=0,Y=-1,G=!0,_=Z.length-1,L=0;for(;_>=J;--_){if(Q=Z.charCodeAt(_),Q===47){if(!G){W=_+1;break}continue}if(Y===-1)G=!1,Y=_+1;if(Q===46){if($===-1)$=_;else if(L!==1)L=1}else if($!==-1)L=-1}if($===-1||Y===-1||L===0||L===1&&$===Y-1&&$===W+1){if(Y!==-1)if(W===0&&U)X.base=X.name=Z.slice(1,Y);else X.base=X.name=Z.slice(W,Y)}else{if(W===0&&U)X.name=Z.slice(1,$),X.base=Z.slice(1,Y);else X.name=Z.slice(W,$),X.base=Z.slice(W,Y);X.ext=Z.slice($,Y)}if(W>0)X.dir=Z.slice(0,W-1);else if(U)X.dir="/";return X}var dJ="/",cJ=":",iJ,YL;var rJ=R(()=>{iJ=((Z)=>(Z.posix=Z,Z))({resolve:B8,normalize:q7,isAbsolute:kJ,join:gJ,relative:vJ,_makeLong:xJ,dirname:hJ,basename:mJ,extname:uJ,format:pJ,parse:lJ,sep:dJ,delimiter:cJ,win32:null,posix:null}),YL=iJ});t2();var Q6;(($)=>{$.ENGINE_START="engine:start";$.ENGINE_DONE="engine:done";$.RULE_MATCH="rule:match";$.ACTION_SUCCESS="action:success";$.ACTION_ERROR="action:error"})(Q6||={});var P9;((U)=>{U.RULE_ADDED="rule:added";U.RULE_REMOVED="rule:removed";U.RULE_UPDATED="rule:updated"})(P9||={});var w9=P9;class PX{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new PX;return this.instance}on(Z,X){let Q=Z;if(!this.handlers.has(Q))this.handlers.set(Q,new Set);return this.handlers.get(Q).add(X),()=>this.off(Q,X)}off(Z,X){let Q=Z,U=this.handlers.get(Q);if(U)U.delete(X)}emit(Z,X){let Q=Z,U=this.handlers.get(Q);if(U)U.forEach((J)=>{try{J(X)}catch($){console.error(`Error in event handler for ${Q}:`,$)}})}}var t0=PX.getInstance();var F_=S0,B_=Q6,M_=P9,wX={IF:"if",THEN:"then",ELSE:"else",BREAK:"break",CONTINUE:"continue",MODE:"mode",ACTIONS:"actions",RUN:"run",DELAY:"delay",PROBABILITY:"probability",PARAMS:"params",TYPE:"type",ON:"on"},AX={UNKNOWN_ACTION:"Unknown or generic action type",MISSING_ACTION_TYPE:"Action has no type and no control flow properties",PROBABILITY_FAILED:"probability check failed",BUN_REQUIRED:"Bun is required for 'execute' action",MISSING_KEY:"Missing key for state operation"},A9={RULE_ENGINE_EVALUATING:(Z,X)=>`[RuleEngine] Evaluating context with ${Z} rules for event: ${X}`,TRIGGER_ENGINE_EVALUATING:(Z,X)=>`[TriggerEngine] Evaluating context with ${Z} rules for event: ${X}`},ET={Actions:F_,Events:B_,RuleEvents:M_,ControlFlow:wX,ErrorMessages:AX,DebugMessages:A9};D9();class R_{queue=[];engine;config;timer=null;isProcessing=!1;constructor(Z,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=Z,this.config=X}push(Z){if(this.queue.push(Z),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 Z=this.queue.splice(0,this.config.maxBatchSize);if(Z.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${Z.length} events.`);for(let X of Z)try{await this.engine.evaluateContext(X)}catch(Q){console.error(`[EventQueue] Error processing event ${X.event}:`,Q)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class P5{keyPrefix;cache=new Map;isLoaded=!1;pendingWrite=null;writeDelay;dirty=!1;constructor(Z="trigger_system:",X){this.keyPrefix=Z,this.writeDelay=X?.writeDelay??0}flush(){this.dirty=!0,this.persist()}getCache(){return this.ensureLoaded(),new Map(this.cache)}isDirty(){return this.dirty}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let Z=window.localStorage.getItem(this.keyPrefix+"state");if(Z){let X=JSON.parse(Z);this.cache=new Map(Object.entries(X))}}catch(Z){console.error("[BrowserPersistence] Failed to load from localStorage:",Z)}this.isLoaded=!0}schedulePersist(){if(this.writeDelay<=0){this.persist();return}if(this.pendingWrite)clearTimeout(this.pendingWrite);this.dirty=!0,this.pendingWrite=setTimeout(()=>{this.persist(),this.pendingWrite=null},this.writeDelay)}persist(){if(this.pendingWrite)clearTimeout(this.pendingWrite),this.pendingWrite=null;if(this.isAvailable())try{let Z=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(Z)),this.dirty=!1}catch(Z){console.error("[BrowserPersistence] Failed to save to localStorage:",Z)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(Z,X){this.ensureLoaded(),this.cache.set(Z,X),this.schedulePersist()}async deleteState(Z){this.ensureLoaded(),this.cache.delete(Z),this.schedulePersist()}async clearState(){this.cache.clear(),this.schedulePersist()}}class SX{static getNestedValue(Z,X){let Q=Z.split("."),U=X;for(let J of Q){if(U===null||U===void 0)return;if(typeof U==="object"&&U!==null&&J in U)U=U[J];else return}return U}static interpolate(Z,X){if(typeof Z!=="string")return Z;return Z.replace(/\$\{([^}]+)\}/g,(Q,U)=>{let J=this.getNestedValue(U,X);if(J!==void 0)return String(J);return Q})}static compare(Z,X,Q){let U=($)=>{if($ instanceof Date)return $.getTime();if(typeof $==="number")return $;if(typeof $==="string"){let W=new Date($);return isNaN(W.getTime())?0:W.getTime()}return 0},J=($)=>{if(typeof $==="number")return $;if($===null||$===void 0||$==="")return null;let W=Number($);return isNaN(W)?null:W};switch(X){case"EQ":case"==":return Z==Q;case"NEQ":case"!=":return Z!=Q;case"GT":case">":{let $=J(Z),W=J(Q);return $!==null&&W!==null&&$>W}case"GTE":case">=":{let $=J(Z),W=J(Q);return $!==null&&W!==null&&$>=W}case"LT":case"<":{let $=J(Z),W=J(Q);return $!==null&&W!==null&&$<W}case"LTE":case"<=":{let $=J(Z),W=J(Q);return $!==null&&W!==null&&$<=W}case"IN":return Array.isArray(Q)&&Q.some(($)=>$===Z);case"NOT_IN":return Array.isArray(Q)&&!Q.some(($)=>$===Z);case"CONTAINS":if(Array.isArray(Q))return Q.some(($)=>String(Z).includes(String($)));if(Array.isArray(Z)||typeof Z==="string")return Z.includes(Q);return!1;case"NOT_CONTAINS":if(Array.isArray(Q))return!Q.some(($)=>String(Z).includes(String($)));if(Array.isArray(Z)||typeof Z==="string")return!Z.includes(Q);return!1;case"STARTS_WITH":if(Array.isArray(Q))return Q.some(($)=>String(Z).startsWith(String($)));if(typeof Z==="string"&&typeof Q==="string")return Z.startsWith(Q);return!1;case"ENDS_WITH":if(Array.isArray(Q))return Q.some(($)=>String(Z).endsWith(String($)));if(typeof Z==="string"&&typeof Q==="string")return Z.endsWith(Q);return!1;case"IS_EMPTY":{let $=!1;if(typeof Z==="string")$=Z==="";else if(Array.isArray(Z))$=Z.length===0;else if(Z===null||Z===void 0)$=!0;else if(typeof Z==="object")$=Object.keys(Z).length===0;return Q===!1?!$:$}case"IS_NULL":case"IS_NONE":{let $=Z===null||Z===void 0;return Q===!1?!$:$}case"HAS_KEY":if(typeof Z==="object"&&Z!==null&&typeof Q==="string")return Q in Z;return!1;case"MATCHES":if(typeof Q==="string")return new RegExp(Q).test(String(Z));return!1;case"RANGE":if(Array.isArray(Q)&&Q.length===2){let $=J(Z),W=J(Q[0]),Y=J(Q[1]);return $!==null&&W!==null&&Y!==null&&$>=W&&$<=Y}return!1;case"SINCE":case"AFTER":return U(Z)>=U(Q);case"BEFORE":case"UNTIL":return U(Z)<U(Q);default:return console.warn(`Unknown operator: ${X}`),!1}}}D9();class U2{static evaluateConditions(Z,X){if(!Z)return!0;if(Array.isArray(Z))return Z.every((Q)=>this.evaluateRecursiveCondition(Q,X));return this.evaluateRecursiveCondition(Z,X)}static evaluateRecursiveCondition(Z,X){if("conditions"in Z&&"operator"in Z){let U=Z;if(U.operator==="OR")return U.conditions.some((J)=>this.evaluateRecursiveCondition(J,X));else return U.conditions.every((J)=>this.evaluateRecursiveCondition(J,X))}let Q=Z;try{let U=v0.evaluate(Q.field,X),J=Q.value;if(typeof J==="string"&&J.includes("${"))J=v0.interpolate(J,X);return SX.compare(U,Q.operator,J)}catch(U){return console.error("Error evaluating condition:",Q,U),!1}}static async processSingleActionBase(Z,X,Q){let U={...Z};if(!U.type&&!U.run&&!U.break&&!U.continue){let W=Object.values(wX),Y=Object.keys(U).filter((G)=>!W.includes(G));for(let G of Y)if(Q?!!Q.get(G):!0){U.type=G;let L=U[G];if(typeof L==="string")U.params={...U.params,message:L,content:L};else if(typeof L==="object"&&L!==null)U.params={...U.params,...L};break}}if(U.run)try{return{shouldExecute:!1,executedAction:{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${U.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()},normalizedAction:U}}catch(W){return{shouldExecute:!1,executedAction:{type:"RUN",error:String(W),timestamp:Date.now()},normalizedAction:U}}if(U.break)return{shouldExecute:!1,executedAction:{type:"BREAK",result:"Break execution",timestamp:Date.now()},normalizedAction:U};if(U.continue)return{shouldExecute:!1,executedAction:{type:"CONTINUE",result:"Continue execution",timestamp:Date.now()},normalizedAction:U};let J=U.probability;if(typeof J==="string"){let W=v0.evaluate(J,X);J=typeof W==="number"?W:Number(W)}if(J!==void 0&&Math.random()>J)return{shouldExecute:!1,executedAction:{type:U.type||"skipped",result:{skipped:"probability check failed"},timestamp:Date.now()},normalizedAction:U};let $=U.delay;if(typeof $==="string"){let W=v0.evaluate($,X);$=typeof W==="number"?W:Number(W)}if($&&$>0)await new Promise((W)=>setTimeout(W,$));return U.params=this.interpolateParams(U.params||{},X),{shouldExecute:!0,normalizedAction:U}}static selectActions(Z){let X=[],Q="ALL";if(Array.isArray(Z))X=Z;else if(Z&&typeof Z==="object"&&"mode"in Z&&"actions"in Z){let U=Z;Q=U.mode,X=U.actions}else X=[Z];if(Q==="EITHER"&&X.length>0){let U=(Y)=>("probability"in Y)?Y.probability:1,J=X.reduce((Y,G)=>Y+U(G),0),$=Math.random()*J;for(let Y of X){let G=U(Y);if($-=G,$<=0)return{actionsToExecute:[Y],mode:Q}}let W=X[X.length-1];return{actionsToExecute:W?[W]:[],mode:Q}}return{actionsToExecute:X,mode:Q}}static interpolateParams(Z,X){let Q={};for(let[U,J]of Object.entries(Z))Q[U]=this.interpolateDeep(J,X);return Q}static interpolateDeep(Z,X){if(typeof Z==="string"&&Z.includes("${"))return v0.interpolate(Z,X);if(Array.isArray(Z))return Z.map((Q)=>this.interpolateDeep(Q,X));if(typeof Z==="object"&&Z!==null){let Q={};for(let[U,J]of Object.entries(Z))Q[U]=this.interpolateDeep(J,X);return Q}return Z}}class U6{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(Z=[]){if(Array.isArray(Z))this._rules=Z;else this._config=Z,this._rules=[...Z.rules];try{let{ActionRegistry:X}=(t2(),K7(DX));X.getInstance(!0)}catch{}this.sortRules()}sortRules(){this._rules.sort((Z,X)=>(X.priority||0)-(Z.priority||0))}registerAction(Z,X){this.actionHandlers.set(Z,X)}async processEvent(Z){let X=[];if(!Z.state)Z.state=this.getStateContext?this.getStateContext():{};let Q=this._rules.filter((U)=>U.enabled!==!1&&U.on===Z.event);for(let U of Q){if(U.cooldown&&this.checkCooldown(U.id,U.cooldown))continue;let J=U2.evaluateConditions(U.if,Z),$;if(J)t0.emit("rule:match",{rule:U,context:Z}),$=U.do;else if(U.else)$=U.else;if($){let W=await this.executeRuleActions($,Z);this.lastExecution.set(U.id,Date.now()),X.push({ruleId:U.id,success:!0,executedActions:W})}if(!J&&!U.else&&!this.shouldEvaluateAll())break;if(J&&!this.shouldEvaluateAll())break}return X}async processEventSimple(Z,X={},Q={}){let U={event:Z,data:X,vars:Q,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(U)}updateRules(Z){let X=this.getRules(),Q=new Set(X.map((W)=>W.id)),U=new Set(Z.map((W)=>W.id)),J=Z.filter((W)=>!Q.has(W.id)),$=X.filter((W)=>!U.has(W.id));this._rules=[...Z],this.sortRules(),J.forEach((W)=>{this.emitRuleEvent(w9.RULE_ADDED,{ruleId:W.id,timestamp:Date.now()})}),$.forEach((W)=>{this.emitRuleEvent(w9.RULE_REMOVED,{ruleId:W.id,timestamp:Date.now()})}),this.emitRuleEvent(w9.RULE_UPDATED,{count:Z.length,added:J.length,removed:$.length,unchanged:Z.length-J.length,timestamp:Date.now()})}emitRuleEvent(Z,X){try{if(t0)t0.emit(Z,{...X,timestamp:Date.now()})}catch(Q){console.warn(`Could not emit event ${Z}:`,Q)}}getRules(){return[...this._rules]}checkCooldown(Z,X){let Q=this.lastExecution.get(Z);if(!Q)return!1;return Date.now()-Q<X}shouldEvaluateAll(){return this._config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(Z,X){return U2.evaluateConditions(Z,X)}evaluateSingleCondition(Z,X){return U2.evaluateConditions(Z,X)}async executeRuleActions(Z,X){let{actionsToExecute:Q}=U2.selectActions(Z),U=[];for(let J of Q){if("actions"in J&&"mode"in J){U.push(...await this.executeRuleActions(J,X));continue}let $=J;if("if"in $&&$.if&&($.then||$.else||$.do)){let Y=this.evaluateConditions($.if,X),G=$.then||$.do;if(Y&&G)U.push(...await this.executeRuleActions(G,X));else if(!Y&&$.else)U.push(...await this.executeRuleActions($.else,X));continue}if("if"in $&&$.if){if(!this.evaluateConditions($.if,X))continue}let W=await this.executeSingleAction($,X);if(U.push(W),W.type==="BREAK")break}return U}async executeSingleAction(Z,X){let{shouldExecute:Q,executedAction:U,normalizedAction:J}=await U2.processSingleActionBase(Z,X);if(!Q)return U;try{let $=this.actionHandlers.get(J.type);if($){let Y=await $(J.params||{},X);return t0.emit("action:success",{action:J,context:X,result:Y}),{type:J.type,result:Y,timestamp:Date.now()}}try{let{ActionRegistry:Y}=(t2(),K7(DX)),G=Y.getInstance().get(J.type);if(G){let _=await G(J,X);return t0.emit("action:success",{action:J,context:X,result:_}),{type:J.type,result:_,timestamp:Date.now()}}}catch{}let W=`${AX.UNKNOWN_ACTION}: ${J.type}`;if(this._config?.globalSettings?.strictActions)throw Error(W);return console.warn(W),{type:J.type,result:{warning:W},timestamp:Date.now()}}catch($){return console.error(`Error executing action ${J.type}:`,$),t0.emit("action:error",{action:J,context:X,error:String($)}),{type:J.type,error:String($),timestamp:Date.now()}}}interpolateParams(Z,X){return U2.interpolateParams(Z,X)}get rules(){return[...this._rules]}get config(){return this._config}set rules(Z){this._rules=[...Z],this.sortRules()}}t2();Z6();class w5 extends U6{actionRegistry;stateManager;constructor(Z){super(Z);this.actionRegistry=X6.getInstance(!0),this.stateManager=K0.getInstance()}async evaluateContext(Z){if(!Z.state)Z.state=this.stateManager.getLiveProxy();if(this._config?.stateConfig)await this.stateManager.applyConfig(this._config.stateConfig);if(!Z.env)Z.env={};if(this._config?.globalSettings?.debugMode)console.log(A9.RULE_ENGINE_EVALUATING(this._rules.length,Z.event));t0.emit("engine:start",{context:Z,rulesCount:this._rules.length});let X=await this.processEvent(Z);return t0.emit("engine:done",{results:X,context:Z}),X}async processEvent(Z,X={},Q={}){if(typeof Z==="string"){let $={event:Z,data:X,vars:Q,timestamp:Date.now(),state:this.stateManager.getLiveProxy()};return this.processEvent($)}let U=Z;if(U.state=this.stateManager.getLiveProxy(),this._config?.stateConfig)await this.stateManager.applyConfig(this._config.stateConfig);if(t0.emit("engine:start",{context:U,rulesCount:this._rules.length}),this._config?.globalSettings?.debugMode)console.log(A9.RULE_ENGINE_EVALUATING(this._rules.length,U.event));let J=await super.processEvent(U);return t0.emit("engine:done",{results:J,context:U}),J}getStateContext(){return this.stateManager.getLiveProxy()}get ActionRegistry(){return this.actionRegistry}get StateManager(){return this.stateManager}}t2();Z6();class O_{static create(Z,X,Q={}){return{event:Z,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},vars:Q,state:K0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromRequest(Z,X,Q={}){let U=new URL(Z.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:Z.method,path:U.pathname,query:Object.fromEntries(U.searchParams),headers:(()=>{let J={};return Z.headers.forEach(($,W)=>J[W]=$),J})(),body:X||{}},vars:{...Q,ip:Z.headers.get("x-forwarded-for")||"unknown"},state:K0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromWebhook(Z,X,Q,U={}){return{event:`WEBHOOK_${Z.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:Q,vars:{...U,provider:Z},state:K0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(Z)=>{try{return typeof Z==="string"?JSON.parse(Z):null}catch{return null}},jsonStringify:(Z)=>{try{return JSON.stringify(Z)}catch{return null}}}}}Z6();KX();var K_=["EQ","==","NEQ","!="],A5=["GT",">","GTE",">=","LT","<","LTE","<="],S5=["IN","NOT_IN","RANGE"],C5=["CONTAINS","NOT_CONTAINS","STARTS_WITH","ENDS_WITH"],T_=["IS_NULL","IS_NONE"],D_=["IS_EMPTY","HAS_KEY","MATCHES","SINCE","AFTER","BEFORE","UNTIL"],LD=[...K_,...A5,...S5,...C5,...T_,...D_];function N5(Z){return S5.includes(Z)}function j5(Z){return C5.includes(Z)}function E5(Z){return A5.includes(Z)}var J2=t4({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'NOT_CONTAINS' | 'STARTS_WITH' | 'ENDS_WITH' | '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",InlineConditionalAction:{if:"RuleCondition | RuleCondition[]","then?":"Action | ActionGroup","do?":"Action | ActionGroup","else?":"Action | ActionGroup","break?":"boolean","continue?":"boolean"},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[] | InlineConditionalAction","else?":"RuleAction | RuleAction[]","comment?":"string"}}).export(),MD=J2.Operator,RD=J2.Condition,OD=J2.ConditionGroup,KD=J2.RuleCondition,TD=J2.Action,DD=J2.ActionGroup,PD=J2.InlineConditionalAction,P_=J2.TriggerRule;class CX{static validate(Z){let X=P_(Z);if(X instanceof o.errors){let J=[];for(let $ of X){let W=$.path.join("."),Y=$.message,G=void 0;if(W.endsWith("on")&&(Y.includes("string")||Y.includes("must be")))if(typeof Z==="object"&&Z!==null&&"on"in Z&&Z.on===!0)Y="The 'on' field is incorrect (boolean true found).",G=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else G="Ensure 'on' is a string event name.";J.push({path:W,message:Y,suggestion:G,severity:"error"})}return{valid:!1,issues:J}}let Q=X,U=[];if(this.validateConditionsRecursive(Q.if,U,"if"),this.validateInlineConditionalRecursive(Q.do,U,"do"),Q.else)this.validateInlineConditionalRecursive(Q.else,U,"else");if(U.length>0)return{valid:!1,issues:U};return{valid:!0,rule:Q}}static validateInlineConditionalRecursive(Z,X,Q){if(!Z)return;if(Array.isArray(Z)){Z.forEach((U,J)=>{this.validateInlineConditionalRecursive(U,X,`${Q}.${J}`)});return}if(typeof Z==="object"&&Z!==null&&"mode"in Z&&"actions"in Z){let U=Z;if(Array.isArray(U.actions))U.actions.forEach((J,$)=>{this.validateInlineConditionalRecursive(J,X,`${Q}.actions.${$}`)});return}if(typeof Z==="object"&&Z!==null&&"if"in Z){let U=Z;if(this.validateConditionsRecursive(U.if,X,`${Q}.if`),U.then)this.validateInlineConditionalRecursive(U.then,X,`${Q}.then`);if(U.do)this.validateInlineConditionalRecursive(U.do,X,`${Q}.do`);if(U.else)this.validateInlineConditionalRecursive(U.else,X,`${Q}.else`);return}}static validateConditionsRecursive(Z,X,Q){if(!Z)return;if(Array.isArray(Z)){Z.forEach((U,J)=>{this.validateConditionsRecursive(U,X,`${Q}.${J}`)});return}if(typeof Z==="object"&&Z!==null&&"conditions"in Z&&Array.isArray(Z.conditions)){Z.conditions.forEach((U,J)=>{this.validateConditionsRecursive(U,X,`${Q}.conditions.${J}`)});return}if(typeof Z==="object"&&Z!==null&&"operator"in Z&&"value"in Z)this.validateConditionValue(Z,X,Q)}static validateConditionValue(Z,X,Q){let{operator:U,value:J}=Z,$=U;if(N5($)){if(!Array.isArray(J)){X.push({path:`${Q}.value`,message:`Incorrect value type: Operator '${$}' expects a List (Array), but received ${typeof J}.`,suggestion:$==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if($==="RANGE"){if(J.length!==2)X.push({path:`${Q}.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 J[0]!=="number"&&typeof J[0]!=="string")X.push({path:`${Q}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if($==="CONTAINS"||$==="NOT_CONTAINS"){if(typeof J!=="string"&&!Array.isArray(J))X.push({path:`${Q}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof J}.`,suggestion:"Use a substring or a list of items.",severity:"error"})}else if(j5($)){if(typeof J!=="string"&&!Array.isArray(J))X.push({path:`${Q}.value`,message:`Incorrect value type: Operator '${$}' expects a String or List (Array), but received ${typeof J}.`,suggestion:"Use a string prefix/suffix or a list of prefixes/suffixes.",severity:"error"})}else if($==="MATCHES")if(typeof J!=="string")X.push({path:`${Q}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof J}.`,severity:"error"});else try{new RegExp(J)}catch(W){X.push({path:`${Q}.value`,message:`Invalid Regex pattern: ${W.message}`,severity:"error"})}else if(E5($)){if(typeof J!=="number"&&typeof J!=="string")X.push({path:`${Q}.value`,message:`Incorrect value type: Operator '${$}' expects a number or expression string, but received ${typeof J}.`,severity:"error"})}else if($==="HAS_KEY"){if(typeof J!=="string")X.push({path:`${Q}.value`,message:`Incorrect value type: Operator 'HAS_KEY' expects a string (key name), but received ${typeof J}.`,severity:"error"})}}}function S9(Z,X){let Q=new Map,U=[];for(let $ of Z){let Y=$[X];if(Y!==void 0&&Y!==null){let G=String(Y);if(!Q.has(G))Q.set(G,$)}else U.push($)}let J=Array.from(new Set(U.map(($)=>JSON.stringify($)))).map(($)=>JSON.parse($));return[...Array.from(Q.values()),...J]}function J6(Z,X={}){let{deduplicate:Q=!0,uniqueIdField:U}=X;if(!Z)return;if(Array.isArray(Z)){let J=Z.map((W)=>J6(W,X)).filter((W)=>W!==void 0);if(!Q)return J.length===0?void 0:J.length===1?J[0]:J;let $=U?S9(J,U):Array.from(new Set(J.map((W)=>JSON.stringify(W)))).map((W)=>JSON.parse(W));return $.length===0?void 0:$.length===1?$[0]:$}if("operator"in Z&&"conditions"in Z){let J=Z,$=J6(J.conditions,X);if(!$)return;if(!Array.isArray($))$=[$];let W=[];for(let G of $)if("operator"in G&&"conditions"in G&&G.operator===J.operator)W.push(...G.conditions);else W.push(G);let Y;if(!Q)Y=W;else if(U)Y=S9(W,U);else Y=Array.from(new Set(W.map((G)=>JSON.stringify(G)))).map((G)=>JSON.parse(G));if(Y.length===0)return;if(Y.length===1)return Y[0];return{operator:J.operator,conditions:Y}}return Z}function $6(Z,X={}){let{deduplicate:Q=!1,uniqueIdField:U}=X;if(!Z)return;if(Array.isArray(Z)){let J=Z.map((G)=>$6(G,X)).filter((G)=>G!==void 0);if(!Q){let G=J.flatMap((L)=>Array.isArray(L)?L:[L]),_=[];for(let L of G)if("mode"in L&&"actions"in L&&L.mode==="ALL")_.push(...L.actions);else _.push(L);if(_.length===0)return;if(_.length===1)return _[0];return _}let $=J.flatMap((G)=>Array.isArray(G)?G:[G]),W=[];for(let G of $)if("mode"in G&&"actions"in G&&G.mode==="ALL")W.push(...G.actions);else W.push(G);if(W.length===0)return;if(W.length===1)return W[0];let Y;if(U)Y=S9(W,U);else Y=Array.from(new Set(W.map((G)=>JSON.stringify(G)))).map((G)=>JSON.parse(G));return Y}if("mode"in Z&&"actions"in Z){let J=Z,$=$6(J.actions,X);if(!$)return;if(!Array.isArray($))$=[$];let W=[];for(let G of $)if("mode"in G&&"actions"in G&&G.mode===J.mode)W.push(...G.actions);else W.push(G);if(W.length===0)return;if(W.length===1)return W[0];let Y;if(!Q)Y=W;else if(U)Y=S9(W,U);else Y=Array.from(new Set(W.map((G)=>JSON.stringify(G)))).map((G)=>JSON.parse(G));return{mode:J.mode,actions:Y}}return Z}class $2{conditions=[];op="AND";constructor(Z="AND"){this.op=Z}where(Z,X,Q){return this.conditions.push({field:Z,operator:X,value:Q}),this}and(Z){let X=new $2("AND");return this.conditions.push(Z(X).build()),this}or(Z){let X=new $2("OR");return this.conditions.push(Z(X).build()),this}build(){if(this.conditions.length===0)throw Error("Condition group must have at least one condition");if(this.conditions.length===1&&this.op==="AND")return this.conditions[0];return{operator:this.op,conditions:this.conditions}}}class W6{actions=[];mode="ALL";setMode(Z){return this.mode=Z,this}add(Z,X,Q){return this.actions.push({type:Z,params:X,...Q}),this}build(){if(this.actions.length===0)throw Error("Action group must have at least one action");if(this.actions.length===1&&this.mode==="ALL")return this.actions[0];if(this.mode==="ALL")return this.actions;return{mode:this.mode,actions:this.actions}}}class NX{params={};set(Z,X){return this.params[Z]=X,this}setAll(Z){return Object.assign(this.params,Z),this}setNested(Z,X){let Q=Z.split("."),U=this.params;for(let $=0;$<Q.length-1;$++){let W=Q[$];if(!W)continue;if(!(W in U))U[W]={};U=U[W]}let J=Q[Q.length-1];if(J)U[J]=X;return this}addItem(Z,X){if(!(Z in this.params)||!Array.isArray(this.params[Z]))this.params[Z]=[];return this.params[Z].push(X),this}remove(Z){return delete this.params[Z],this}has(Z){return Z in this.params}get(Z){return this.params[Z]}build(){return{...this.params}}getRaw(){return this.params}}var f={EVENT:"event",CONDITION:"condition",CONDITION_GROUP:"condition_group",ACTION:"action",ACTION_GROUP:"action_group",DO:"do"},w={EVENT_OUTPUT:"event-output",CONDITION_INPUT:"condition-input",CONDITION_OUTPUT:"output",CONDITION_OUTPUT_LEGACY:"condition-output",THEN_OUTPUT:"then-output",ELSE_OUTPUT:"else-output",CONDITION_GROUP_INPUT:"input",CONDITION_GROUP_OUTPUT:"cond-output",ACTION_INPUT:"action-input",ACTION_OUTPUT:"action-output",ACTION_OUTPUT_LEGACY:"action-group-output",ACTION_GROUP_INPUT:"input",ACTION_GROUP_OUTPUT:"action-output",ACTION_GROUP_CONDITION_OUTPUT:"condition-output",DO_INPUT:"do-input",DO_OUTPUT:"do-output",DO_CONDITION_OUTPUT:"do-condition-output"},u0={DO:"do",ELSE:"else"},jX={AND:"AND",OR:"OR"};var N9=(Z)=>Z.type===f.EVENT,m1=(Z)=>Z.type===f.CONDITION||Z.type===f.CONDITION_GROUP,P1=(Z)=>Z.type===f.ACTION||Z.type===f.ACTION_GROUP||Z.type===f.DO,j9=(Z)=>Z.type===f.DO;var e2=(Z)=>{return Z.data?.branchType===u0.ELSE?u0.ELSE:u0.DO};function EX(Z){let X=Z.data||{};return{id:X.id,on:X.event,name:X.name,description:X.description,priority:X.priority!==void 0?Number(X.priority):void 0,enabled:X.enabled!==void 0?!!X.enabled:void 0,cooldown:X.cooldown!==void 0?Number(X.cooldown):void 0,tags:X.tags}}function J0(Z,X,Q){let U=[...Q];return Z.edges.filter((J)=>J.source===X&&U.includes(J.sourceHandle||""))}var L1={CONDITION_OUTPUT:[w.CONDITION_OUTPUT,w.CONDITION_OUTPUT_LEGACY],ACTION_OUTPUT:[w.ACTION_OUTPUT,w.ACTION_OUTPUT_LEGACY],DO_OUTPUT:[w.DO_OUTPUT,""],THEN_ELSE:[w.THEN_OUTPUT,w.ELSE_OUTPUT],DO_CONDITION:[w.DO_CONDITION_OUTPUT],CONDITION_CHAIN:[w.CONDITION_OUTPUT,w.CONDITION_OUTPUT_LEGACY,w.THEN_OUTPUT,w.ELSE_OUTPUT],ANY:[w.CONDITION_OUTPUT,w.CONDITION_OUTPUT_LEGACY,""]};class b5{convert(Z,X){return{field:Z.field||"data",operator:Z.operator||"EQ",value:Z.value!==void 0?Z.value:""}}validate(Z){let X=[];if(!Z.field&&!Z.value)X.push("Condition must have at least a field or value");return{valid:X.length===0,errors:X.length>0?X:void 0}}}class I5{convert(Z,X){let Q={};try{if(Z.params)Q=typeof Z.params==="string"?JSON.parse(Z.params):Z.params}catch{Q={}}let U={type:Z.type||"log",params:Q};if(Z.delay!==void 0)U.delay=Number(Z.delay);if(Z.probability!==void 0)U.probability=Number(Z.probability);return U}validate(Z){let X=[];if(!Z.type)X.push('Action type defaults to "log"');return{valid:!0,warnings:X.length>0?X:void 0}}}class f5{convert(Z,X){return{id:Z.id,on:Z.event,name:Z.name,description:Z.description,priority:Z.priority!==void 0?Number(Z.priority):void 0,enabled:Z.enabled!==void 0?!!Z.enabled:void 0,cooldown:Z.cooldown!==void 0?Number(Z.cooldown):void 0,tags:Z.tags}}validate(Z){let X=[],Q=[];if(!Z.id)X.push("Event must have an ID");if(!Z.event)X.push("Event must have an event name");if(!Z.name)Q.push("Event should have a name");return{valid:X.length===0,errors:X.length>0?X:void 0,warnings:Q.length>0?Q:void 0}}}class y5{conditionConverter=new b5;actionConverter=new I5;eventConverter=new f5;getConditionConverter(){return this.conditionConverter}getActionConverter(){return this.actionConverter}getEventConverter(){return this.eventConverter}createContext(Z,X,Q,U){return{nodes:Z,edges:X,currentNode:Q,options:U}}}var k5=new y5;function bX(Z){let X=Z.data||{};return k5.getConditionConverter().convert(X,{nodes:[],edges:[]})}function IX(Z){let X=Z.data||{};return k5.getActionConverter().convert(X,{nodes:[],edges:[]})}function E9(Z,X){let Q=X.options.isCondNode||m1,U=X.nodes.find((_)=>_.id===Z);if(!U||U.type!==f.CONDITION_GROUP)return{conditions:[],operator:jX.AND};let J=U.data.operator||jX.AND,$=[],W=new Set;function Y(_){if(W.has(_))return;W.add(_);let L=X.nodes.find((H)=>H.id===_);if(!L||!Q(L)||L.type===f.CONDITION_GROUP)return;let V=bX(L);$.push(V);let q=J0(X,_,[...L1.CONDITION_OUTPUT,w.THEN_OUTPUT]).filter((H)=>{let F=X.nodes.find((z)=>z.id===H.target);return F&&Q(F)});for(let H of q)Y(H.target)}let G=J0(X,Z,[w.CONDITION_GROUP_OUTPUT]).filter((_)=>{let L=X.nodes.find((V)=>V.id===_.target);return L&&Q(L)});for(let _ of G)Y(_.target);return{conditions:$,operator:J}}function P2(Z,X){if(X.options.resolveCondition&&X.options.resolveCondition!==P2)return X.options.resolveCondition(Z,X);if(X.visitedConds.has(Z))return null;X.visitedConds.add(Z);let Q=X.nodes.find((W)=>W.id===Z),U=X.options.isCondNode||m1;if(!Q||!U(Q))return null;if(Q.type===f.CONDITION_GROUP){let{conditions:W,operator:Y}=E9(Z,X);if(W.length===0)return null;if(W.length===1)return W[0];return{operator:Y,conditions:W}}let J=bX(Q);if(X.transformers?.condition){let W=X.transformers.condition(J,Q);if(W===null)return null;return W}let $=J0(X,Z,L1.CONDITION_OUTPUT).filter((W)=>{let Y=X.nodes.find((G)=>G.id===W.target);return Y&&U(Y)});if($.length>0){let W=$.map((Y)=>P2(Y.target,X)).filter((Y)=>Y!==null);if(W.length>0)return{operator:"AND",conditions:[J,...W]}}return J}function fX(Z,X){let Q=X.options.isCondNode||m1,U,J;function $(W){let Y=X.nodes.find((L)=>L.id===W);if(!Y||!Q(Y))return;let G=X.edges.filter((L)=>L.source===W);for(let L of G){let V=X.nodes.find((q)=>q.id===L.target);if(!V)continue;if(V.type===f.ACTION||V.type===f.ACTION_GROUP||V.type===f.DO)if(L.sourceHandle===w.ELSE_OUTPUT)J=L.target;else U=L.target}let _=J0(X,W,L1.CONDITION_OUTPUT).filter((L)=>{let V=X.nodes.find((q)=>q.id===L.target);return V&&Q(V)});for(let L of _)$(L.target)}return $(Z),{thenActionId:U,elseActionId:J}}function Z4(Z,X){let Q=X.options.isActNode||P1,U=X.nodes.find((L)=>L.id===Z);if(!U||U.type!==f.ACTION_GROUP)return{actions:[],mode:"ALL"};let J=U.data.mode||"ALL",$=[],W=new Set;function Y(L){if(W.has(L))return;W.add(L);let V=X.nodes.find((F)=>F.id===L);if(!V||!Q(V)||V.type===f.ACTION_GROUP)return;let q=IX(V);$.push(q);let H=J0(X,L,L1.ACTION_OUTPUT).filter((F)=>{let z=X.nodes.find((B)=>B.id===F.target);return z&&Q(z)});for(let F of H)Y(F.target)}let G=J0(X,Z,[w.ACTION_GROUP_OUTPUT,w.DO_OUTPUT,"do-output","action-output","action-group-output"]).filter((L)=>{let V=X.nodes.find((q)=>q.id===L.target);return V&&Q(V)});for(let L of G)Y(L.target);let _=J0(X,Z,[w.ACTION_GROUP_CONDITION_OUTPUT,"condition-output"]);for(let L of _){let V=T0(L.target,X);if(V)$.push(V)}return{actions:$,mode:J}}function T0(Z,X){if(X.options.resolveAction&&X.options.resolveAction!==T0)return X.options.resolveAction(Z,X);let Q=X.nodes.find(($)=>$.id===Z);if(!Q)return null;if(Q.type===f.ACTION_GROUP){if(X.visitedActs?.has(Z))return null;X.visitedActs?.add(Z);let{actions:$,mode:W}=Z4(Z,X);if($.length===0)return null;return{mode:W,actions:$}}if(Q.type===f.CONDITION){if(X.options.resolveCondition){let $=X.options.resolveCondition(Z,X);if($){let{doBranches:W,elseBranches:Y}=Y6(Z,X),G=null,_=null;if(W.length>0){let L=W[0],V=g5(L,X);if(V.length>0)G=V.length===1?V[0]:{mode:"ALL",actions:V}}if(Y.length>0){let L=Y[0],V=g5(L,X);if(V.length>0)_=V.length===1?V[0]:{mode:"ALL",actions:V}}if(!G&&!_){let L=fX(Z,X);if(L.thenActionId)G=T0(L.thenActionId,X);if(L.elseActionId)_=T0(L.elseActionId,X)}if(G||_)return{if:$,then:G??void 0,do:G??void 0,else:_??void 0}}}}if(!(X.options.isActNode||P1)(Q))return null;if(X.visitedActs?.has(Z))return null;X.visitedActs?.add(Z);let J=IX(Q);if(X.transformers?.action){let $=X.transformers.action(J,Q);if($===null)return null;return $}return J}function g5(Z,X){let Q=X.options.isActNode||P1,U=[],J=J0(X,Z,[w.DO_OUTPUT,w.ELSE_OUTPUT,"do-output","else-output","action-output",""]).filter(($)=>{let W=X.nodes.find((Y)=>Y.id===$.target);return W&&Q(W)});for(let $ of J){let W=T0($.target,X);if(W)U.push(W)}return U}function Y6(Z,X){let Q=X.options.isActNode?(G)=>G.type===f.CONDITION||G.type===f.CONDITION_GROUP:(G)=>G.type===f.CONDITION||G.type===f.CONDITION_GROUP,U=(G)=>G.type===f.DO,J=[],$=[],W=new Set;function Y(G){if(W.has(G))return;W.add(G);let _=J0(X,G,[...L1.CONDITION_OUTPUT,w.THEN_OUTPUT]).filter((V)=>{let q=X.nodes.find((H)=>H.id===V.target);return q&&U(q)});for(let V of _){let q=X.nodes.find((F)=>F.id===V.target);if(!q)continue;if(e2(q)===u0.ELSE){if(!$.includes(V.target))$.push(V.target)}else if(!J.includes(V.target))J.push(V.target)}let L=J0(X,G,L1.CONDITION_OUTPUT).filter((V)=>{let q=X.nodes.find((H)=>H.id===V.target);return q&&Q(q)});for(let V of L)Y(V.target)}return Y(Z),{doBranches:J,elseBranches:$}}function w_(Z,X,Q={},U){let J={...Q,resolveCondition:Q.resolveCondition||P2,resolveAction:Q.resolveAction||T0};return{nodes:Z,edges:X,visitedConds:new Set,visitedActs:new Set,options:J,transformers:U}}var OP=e2,A_=EX;function S_(Z,X,Q){let U=X.options.isCondNode||m1,J=j9,$=J0(X,Z,[w.DO_CONDITION_OUTPUT]).find((F)=>{let z=X.nodes.find((B)=>B.id===F.target);return z&&U(z)}),W;if($)W=$.target;if(!W)return null;let Y=new Set(X.visitedConds);X.visitedConds.clear();let G=P2(W,X);if(X.visitedConds=Y,!G)return null;let{thenActionId:_,elseActionId:L}=yX(W,X),V=J0(X,Z,[w.DO_CONDITION_OUTPUT]).find((F)=>{let z=X.nodes.find((B)=>B.id===F.target);return z&&(X.options.isActNode?.(z)??P1(z))});if(V&&!L)L=V.target;let q=_?T0(_,X):void 0,H=L?T0(L,X):void 0;return{if:G,do:q??void 0,else:H??void 0}}function b9(Z,X,Q){let U=X.options.isActNode||P1,J=[],$=J0(X,Z,L1.DO_OUTPUT).filter((Y)=>{let G=X.nodes.find((_)=>_.id===Y.target);return G&&U(G)});for(let Y of $){let G=T0(Y.target,X);if(G)J.push(G)}let W=S_(Z,X,Q);if(W)J.push(W);return J}function yX(Z,X){let Q=X.options.isCondNode||m1,U=X.options.isActNode||P1,J=j9,$,W;function Y(G){let _=X.nodes.find((q)=>q.id===G);if(!_||!Q(_))return;let L=J0(X,G,[w.THEN_OUTPUT,w.ELSE_OUTPUT,w.CONDITION_OUTPUT,w.CONDITION_OUTPUT_LEGACY,w.DO_OUTPUT,""]);for(let q of L){let H=X.nodes.find((F)=>F.id===q.target);if(!H)continue;if(J(H)){let F=J0(X,H.id,[w.DO_OUTPUT,""]).filter((K)=>{let P=X.nodes.find((S)=>S.id===K.target);return P&&U(P)}),z=e2(H);for(let K of F)if(z===u0.ELSE)W=K.target;else $=K.target;let B=J0(X,H.id,[w.DO_CONDITION_OUTPUT]),T=B.find((K)=>{let P=X.nodes.find((S)=>S.id===K.target);return P&&Q(P)}),D=B.find((K)=>{let P=X.nodes.find((S)=>S.id===K.target);return P&&U(P)});if(D&&!W)W=D.target;continue}if(H.type===f.ACTION_GROUP){$=q.target;continue}if(!U(H))continue;if(q.sourceHandle===w.ELSE_OUTPUT)W=q.target;else $=q.target}let V=J0(X,G,L1.CONDITION_OUTPUT).filter((q)=>{let H=X.nodes.find((F)=>F.id===q.target);return H&&Q(H)});for(let q of V)Y(q.target)}return Y(Z),{thenActionId:$,elseActionId:W}}function kX(Z,X,Q={},U){let J=new gX;if(Q.optimizeOptions)J.withOptimizeOptions(Q.optimizeOptions);let $=Q.isEventNode||N9,W=Q.isCondNode||m1,Y=Q.isActNode||P1,G=Q.extractEventData||A_,_=Z.find((K)=>$(K));if(!_)throw Error("Missing Event Trigger node");let L=G(_);if(!L.id||!L.on)throw Error("Rule ID and Event Name are required");if(J.id(L.id).on(L.on),L.name)J.name(L.name);if(L.description)J.description(L.description);if(L.priority!==void 0)J.priority(Number(L.priority));if(L.enabled!==void 0)J.enabled(!!L.enabled);if(L.cooldown!==void 0)J.cooldown(Number(L.cooldown));if(L.tags)J.tags(L.tags);let V=w_(Z,X,Q,U),q=X.filter((K)=>K.source===_.id),H=[],F=[],z=[],B=[];for(let K of q){let P=V.nodes.find((S)=>S.id===K.target);if(!P)continue;if(P.type===f.CONDITION_GROUP)H.push(K.target);else if(W(P))F.push(K.target);else if(P.type===f.ACTION_GROUP)z.push(K.target);else if(Y(P))B.push(K.target)}for(let K of H){let{conditions:P,operator:S}=E9(K,V);if(P.length>0){let N={operator:S,conditions:P};J.withIf(N);let x=V.edges.filter((a)=>a.source===K&&a.sourceHandle?.startsWith("cond")).map((a)=>a.target),C=null,h=null;for(let a of x){let W0=yX(a,V),n=W0.thenActionId?T0(W0.thenActionId,V):null,B0=W0.elseActionId?T0(W0.elseActionId,V):null,{doBranches:j0,elseBranches:d0}=Y6(a,V),E1=[];for(let K4 of j0){let O8=b9(K4,V,a);E1.push(...O8)}if(E1.length>0)n=E1.length===1?E1[0]:{mode:"ALL",actions:E1};let b1=[];for(let K4 of d0){let O8=b9(K4,V,a);b1.push(...O8)}if(b1.length>0)B0=b1.length===1?b1[0]:{mode:"ALL",actions:b1};if(n)C=n;if(B0)h=B0}if(C)J.withDo(C);if(h)J.elseRule(h)}}if(F.length>0&&H.length===0){let K=[],P,S;for(let B0 of F){let j0=P2(B0,V);if(j0)K.push(j0);let d0=yX(B0,V);if(d0.thenActionId)P=d0.thenActionId;if(d0.elseActionId)S=d0.elseActionId}if(K.length===1)J.withIf(K[0]);else if(K.length>1)J.withIf({operator:"AND",conditions:K});let N=F[0];if(!N)return J;let{doBranches:x,elseBranches:C}=Y6(N,V),h=[];for(let B0 of x){let j0=b9(B0,V,N);h.push(...j0)}let a=h.length===1?h[0]:h.length>1?{mode:"ALL",actions:h}:P?T0(P,V):null,W0=[];for(let B0 of C){let j0=b9(B0,V,N);W0.push(...j0)}let n=W0.length===1?W0[0]:W0.length>1?{mode:"ALL",actions:W0}:S?T0(S,V):null;if(a)J.withDo(a);if(n)J.elseRule(n);if(!P&&!h.length)for(let B0 of F){let j0=J0(V,B0,[w.THEN_OUTPUT,w.CONDITION_OUTPUT,"condition-output","then-output","output",""]).filter((d0)=>{return V.nodes.find((b1)=>b1.id===d0.target)?.type===f.ACTION_GROUP});for(let d0 of j0){let{actions:E1,mode:b1}=Z4(d0.target,V);if(E1.length>0){let K4={mode:b1,actions:E1};J.withDo(K4);break}}}}let T=new Set;if(F.length>0&&H.length===0)for(let K of F){let P=J0(V,K,[w.THEN_OUTPUT,w.CONDITION_OUTPUT,"condition-output","then-output","output",""]).filter((S)=>{return V.nodes.find((x)=>x.id===S.target)?.type===f.ACTION_GROUP});for(let S of P)T.add(S.target)}let D=z.filter((K)=>!T.has(K));if(D.length>0)for(let K of D)if(J0(V,K,[w.ACTION_GROUP_CONDITION_OUTPUT,"condition-output"]).filter((S)=>{let N=V.nodes.find((x)=>x.id===S.target);return N&&W(N)}).length>0){let{actions:S,mode:N}=Z4(K,V);if(S.length>0){let x={mode:N,actions:S};J.withDo(x)}}else{let{actions:S,mode:N}=Z4(K,V);if(S.length>0)J.withDo({mode:N,actions:S})}if(B.length>0&&F.length===0&&H.length===0)for(let K of B){let P=T0(K,V);if(P)J.withDo(P)}return J}function v5(Z,X,Q={},U){let J=Q.isEventNode||N9,$=Z.filter((G)=>J(G));if($.length===0)return{rules:[],errors:["No Event nodes found in the graph"]};let W=[],Y=[];for(let G of $)try{let _=G.id,L=new Set([_]),V=[_];while(V.length>0){let B=V.shift(),T=X.filter((D)=>D.source===B);for(let D of T)if(!L.has(D.target))L.add(D.target),V.push(D.target)}let q=Z.filter((B)=>L.has(B.id)),H=X.filter((B)=>L.has(B.source)&&L.has(B.target)),z=kX(q,H,Q,U).build();W.push(z)}catch(_){let L=_ instanceof Error?_.message:String(_);Y.push(`Failed to parse rule for event ${G.id}: ${L}`)}return{rules:W,errors:Y}}class gX{rule={enabled:!0,priority:0};optimizeOptions={};static fromGraph(Z,X,Q,U){return kX(Z,X,Q,U)}static fromGraphMultiple(Z,X,Q,U){return v5(Z,X,Q,U)}withId(Z){return this.rule.id=Z,this}withName(Z){return this.rule.name=Z,this}withDescription(Z){return this.rule.description=Z,this}withPriority(Z){return this.rule.priority=Z,this}withCooldown(Z){return this.rule.cooldown=Z,this}withTags(Z){return this.rule.tags=Z,this}withEnabled(Z){return this.rule.enabled=Z,this}withOptimizeOptions(Z){return this.optimizeOptions=Z,this}id(Z){return this.withId(Z)}name(Z){return this.withName(Z)}description(Z){return this.withDescription(Z)}priority(Z){return this.withPriority(Z)}enabled(Z){return this.withEnabled(Z)}cooldown(Z){return this.withCooldown(Z)}tags(Z){return this.withTags(Z)}optimize(Z){return this.withOptimizeOptions(Z)}on(Z){return this.rule.on=Z,this}if(Z,X,Q){if(!this.rule.if)this.rule.if={field:Z,operator:X,value:Q};else if(Array.isArray(this.rule.if))this.rule.if.push({field:Z,operator:X,value:Q});else this.rule.if=[this.rule.if,{field:Z,operator:X,value:Q}];return this}ifComplex(Z){let X=new $2,Q=Z(X).build();return this.rule.if=Q,this}withIf(Z){return this.rule.if=Z,this}do(Z,X,Q){let U={type:Z,params:X,...Q};if(!this.rule.do)this.rule.do=U;else if(Array.isArray(this.rule.do))this.rule.do.push(U);else if(this.rule.do&&typeof this.rule.do==="object"&&"actions"in this.rule.do)this.rule.do.actions.push(U);else this.rule.do=[this.rule.do,U];return this}doComplex(Z){let X=new W6,Q=Z(X).build();return this.rule.do=Q,this}withDo(Z){return this.rule.do=Z,this}elseRule(Z){return this.rule.else=Z,this}when(Z,X,Q){return new C9(this,Z,X,Q)}whenComplex(Z){let X=new $2,Q=Z(X).build();return new C9(this,Q)}then(Z,X,Q){return this.do(Z,X,Q)}ifAction(Z,X,Q){let U=this.rule.do;if(!U)throw Error("Cannot add condition: no action defined. Use do() or then() first.");let J=($)=>({...$,if:{field:Z,operator:X,value:Q}});if(Array.isArray(U)){let $=U.length-1,W=U[$];if(W&&"actions"in W){let Y=W.actions,G=Y.length-1;if(G>=0)Y[G]=J(Y[G])}else if(W)U[$]=J(W)}else if(U&&"actions"in U){let $=U.actions,W=$.length-1;if(W>=0)$[W]=J($[W])}else if(U)this.rule.do=J(U);return this}thenAction(Z){let X=this.rule.do;if(!X)throw Error("Cannot add then: no action defined. Use do() or then() first.");let Q=(U)=>({...U,then:Z});if(Array.isArray(X)){let U=X.length-1,J=X[U];if(J&&"actions"in J){let $=J.actions,W=$.length-1;if(W>=0)$[W]=Q($[W])}else if(J)X[U]=Q(J)}else if(X&&"actions"in X){let U=X.actions,J=U.length-1;if(J>=0)U[J]=Q(U[J])}else if(X)this.rule.do=Q(X);return this}else(Z){let X=this.rule.do;if(!X)throw Error("Cannot add else: no action defined. Use do() or then() first.");let Q=(U)=>({...U,else:Z});if(Array.isArray(X)){let U=X.length-1,J=X[U];if(J&&"actions"in J){let $=J.actions,W=$.length-1;if(W>=0)$[W]=Q($[W])}else if(J)X[U]=Q(J)}else if(X&&"actions"in X){let U=X.actions,J=U.length-1;if(J>=0)U[J]=Q(U[J])}else if(X)this.rule.do=[Q(X)];return this}elseAction(Z){return this.else(Z)}build(){if(!this.rule.id)throw Error("Rule ID is required");if(!this.rule.on)throw Error("Rule 'on' event is required");if(!this.rule.do)throw Error("Rule 'do' action is required");if(this.rule.if)this.rule.if=J6(this.rule.if,this.optimizeOptions);if(this.rule.do){let Z=$6(this.rule.do,this.optimizeOptions);this.rule.do=Z?Z:this.rule.do}return this.rule}}class C9{parent;condition;thenActions;elseActions;constructor(Z,X,Q,U){if(this.parent=Z,typeof X==="string")this.condition={field:X,operator:Q,value:U};else this.condition=X}then(Z,X,Q){if(typeof Z==="string")this.thenActions={type:Z,params:X,...Q};else this.thenActions=Z;return this}do(Z,X,Q){return this.then(Z,X,Q)}done(){return this.build()}else(Z,X,Q){if(typeof Z==="string")this.elseActions={type:Z,params:X,...Q};else this.elseActions=Z;return this.build()}build(){let Z={if:this.condition};if(this.thenActions)Z.then=this.thenActions;if(this.elseActions)Z.else=this.elseActions;let X=this.parent.rule.do;if(!X)this.parent.rule.do=Z;else if(Array.isArray(X))X.push(Z);else this.parent.rule.do=[X,Z];return this.parent}}var L7={};f6(L7,{visitAsync:()=>G6,visit:()=>q1,stringify:()=>fJ,parseDocument:()=>_7,parseAllDocuments:()=>z8,parse:()=>F8,isSeq:()=>X1,isScalar:()=>v,isPair:()=>p,isNode:()=>l,isMap:()=>Z1,isDocument:()=>e0,isCollection:()=>r,isAlias:()=>l0,YAMLWarning:()=>K6,YAMLSeq:()=>D0,YAMLParseError:()=>U1,YAMLMap:()=>G0,YAMLError:()=>O6,Schema:()=>_4,Scalar:()=>b,Parser:()=>z4,Pair:()=>$0,LineCounter:()=>N6,Lexer:()=>C6,Document:()=>S1,Composer:()=>V4,CST:()=>Y7,Alias:()=>p1});var I9=Symbol.for("yaml.alias"),f9=Symbol.for("yaml.document"),V1=Symbol.for("yaml.map"),vX=Symbol.for("yaml.pair"),p0=Symbol.for("yaml.scalar"),u1=Symbol.for("yaml.seq"),C0=Symbol.for("yaml.node.type"),l0=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===I9,e0=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===f9,Z1=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===V1,p=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===vX,v=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===p0,X1=(Z)=>!!Z&&typeof Z==="object"&&Z[C0]===u1;function r(Z){if(Z&&typeof Z==="object")switch(Z[C0]){case V1:case u1:return!0}return!1}function l(Z){if(Z&&typeof Z==="object")switch(Z[C0]){case I9:case V1:case p0:case u1:return!0}return!1}var y9=(Z)=>(v(Z)||r(Z))&&!!Z.anchor;var x0=Symbol("break visit"),x5=Symbol("skip children"),w1=Symbol("remove node");function q1(Z,X){let Q=h5(X);if(e0(Z)){if(X4(null,Z.contents,Q,Object.freeze([Z]))===w1)Z.contents=null}else X4(null,Z,Q,Object.freeze([]))}q1.BREAK=x0;q1.SKIP=x5;q1.REMOVE=w1;function X4(Z,X,Q,U){let J=m5(Z,X,Q,U);if(l(J)||p(J))return u5(Z,U,J),X4(Z,J,Q,U);if(typeof J!=="symbol"){if(r(X)){U=Object.freeze(U.concat(X));for(let $=0;$<X.items.length;++$){let W=X4($,X.items[$],Q,U);if(typeof W==="number")$=W-1;else if(W===x0)return x0;else if(W===w1)X.items.splice($,1),$-=1}}else if(p(X)){U=Object.freeze(U.concat(X));let $=X4("key",X.key,Q,U);if($===x0)return x0;else if($===w1)X.key=null;let W=X4("value",X.value,Q,U);if(W===x0)return x0;else if(W===w1)X.value=null}}return J}async function G6(Z,X){let Q=h5(X);if(e0(Z)){if(await Q4(null,Z.contents,Q,Object.freeze([Z]))===w1)Z.contents=null}else await Q4(null,Z,Q,Object.freeze([]))}G6.BREAK=x0;G6.SKIP=x5;G6.REMOVE=w1;async function Q4(Z,X,Q,U){let J=await m5(Z,X,Q,U);if(l(J)||p(J))return u5(Z,U,J),Q4(Z,J,Q,U);if(typeof J!=="symbol"){if(r(X)){U=Object.freeze(U.concat(X));for(let $=0;$<X.items.length;++$){let W=await Q4($,X.items[$],Q,U);if(typeof W==="number")$=W-1;else if(W===x0)return x0;else if(W===w1)X.items.splice($,1),$-=1}}else if(p(X)){U=Object.freeze(U.concat(X));let $=await Q4("key",X.key,Q,U);if($===x0)return x0;else if($===w1)X.key=null;let W=await Q4("value",X.value,Q,U);if(W===x0)return x0;else if(W===w1)X.value=null}}return J}function h5(Z){if(typeof Z==="object"&&(Z.Collection||Z.Node||Z.Value))return Object.assign({Alias:Z.Node,Map:Z.Node,Scalar:Z.Node,Seq:Z.Node},Z.Value&&{Map:Z.Value,Scalar:Z.Value,Seq:Z.Value},Z.Collection&&{Map:Z.Collection,Seq:Z.Collection},Z);return Z}function m5(Z,X,Q,U){if(typeof Q==="function")return Q(Z,X,U);if(Z1(X))return Q.Map?.(Z,X,U);if(X1(X))return Q.Seq?.(Z,X,U);if(p(X))return Q.Pair?.(Z,X,U);if(v(X))return Q.Scalar?.(Z,X,U);if(l0(X))return Q.Alias?.(Z,X,U);return}function u5(Z,X,Q){let U=X[X.length-1];if(r(U))U.items[Z]=Q;else if(p(U))if(Z==="key")U.key=Q;else U.value=Q;else if(e0(U))U.contents=Q;else{let J=l0(U)?"alias":"scalar";throw Error(`Cannot replace node with ${J} parent`)}}var C_={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},N_=(Z)=>Z.replace(/[!,[\]{}]/g,(X)=>C_[X]);class M0{constructor(Z,X){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},M0.defaultYaml,Z),this.tags=Object.assign({},M0.defaultTags,X)}clone(){let Z=new M0(this.yaml,this.tags);return Z.docStart=this.docStart,Z}atDocument(){let Z=new M0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:M0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},M0.defaultTags);break}return Z}add(Z,X){if(this.atNextDocument)this.yaml={explicit:M0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},M0.defaultTags),this.atNextDocument=!1;let Q=Z.trim().split(/[ \t]+/),U=Q.shift();switch(U){case"%TAG":{if(Q.length!==2){if(X(0,"%TAG directive should contain exactly two parts"),Q.length<2)return!1}let[J,$]=Q;return this.tags[J]=$,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return X(0,"%YAML directive should contain exactly one part"),!1;let[J]=Q;if(J==="1.1"||J==="1.2")return this.yaml.version=J,!0;else{let $=/^\d+\.\d+$/.test(J);return X(6,`Unsupported YAML version ${J}`,$),!1}}default:return X(0,`Unknown directive ${U}`,!0),!1}}tagName(Z,X){if(Z==="!")return"!";if(Z[0]!=="!")return X(`Not a valid tag: ${Z}`),null;if(Z[1]==="<"){let $=Z.slice(2,-1);if($==="!"||$==="!!")return X(`Verbatim tags aren't resolved, so ${Z} is invalid.`),null;if(Z[Z.length-1]!==">")X("Verbatim tags must end with a >");return $}let[,Q,U]=Z.match(/^(.*!)([^!]*)$/s);if(!U)X(`The ${Z} tag has no suffix`);let J=this.tags[Q];if(J)try{return J+decodeURIComponent(U)}catch($){return X(String($)),null}if(Q==="!")return Z;return X(`Could not resolve tag: ${Z}`),null}tagString(Z){for(let[X,Q]of Object.entries(this.tags))if(Z.startsWith(Q))return X+N_(Z.substring(Q.length));return Z[0]==="!"?Z:`!<${Z}>`}toString(Z){let X=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Q=Object.entries(this.tags),U;if(Z&&Q.length>0&&l(Z.contents)){let J={};q1(Z.contents,($,W)=>{if(l(W)&&W.tag)J[W.tag]=!0}),U=Object.keys(J)}else U=[];for(let[J,$]of Q){if(J==="!!"&&$==="tag:yaml.org,2002:")continue;if(!Z||U.some((W)=>W.startsWith($)))X.push(`%TAG ${J} ${$}`)}return X.join(`
47
+ `)}}M0.defaultYaml={explicit:!1,version:"1.2"};M0.defaultTags={"!!":"tag:yaml.org,2002:"};function k9(Z){if(/[\x00-\x19\s,[\]{}]/.test(Z)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify(Z)}`;throw Error(Q)}return!0}function xX(Z){let X=new Set;return q1(Z,{Value(Q,U){if(U.anchor)X.add(U.anchor)}}),X}function hX(Z,X){for(let Q=1;;++Q){let U=`${Z}${Q}`;if(!X.has(U))return U}}function p5(Z,X){let Q=[],U=new Map,J=null;return{onAnchor:($)=>{Q.push($),J??(J=xX(Z));let W=hX(X,J);return J.add(W),W},setAnchors:()=>{for(let $ of Q){let W=U.get($);if(typeof W==="object"&&W.anchor&&(v(W.node)||r(W.node)))W.node.anchor=W.anchor;else{let Y=Error("Failed to resolve repeated object (this should not happen)");throw Y.source=$,Y}}},sourceObjects:U}}function W2(Z,X,Q,U){if(U&&typeof U==="object")if(Array.isArray(U))for(let J=0,$=U.length;J<$;++J){let W=U[J],Y=W2(Z,U,String(J),W);if(Y===void 0)delete U[J];else if(Y!==W)U[J]=Y}else if(U instanceof Map)for(let J of Array.from(U.keys())){let $=U.get(J),W=W2(Z,U,J,$);if(W===void 0)U.delete(J);else if(W!==$)U.set(J,W)}else if(U instanceof Set)for(let J of Array.from(U)){let $=W2(Z,U,J,J);if($===void 0)U.delete(J);else if($!==J)U.delete(J),U.add($)}else for(let[J,$]of Object.entries(U)){let W=W2(Z,U,J,$);if(W===void 0)delete U[J];else if(W!==$)U[J]=W}return Z.call(X,Q,U)}function F0(Z,X,Q){if(Array.isArray(Z))return Z.map((U,J)=>F0(U,String(J),Q));if(Z&&typeof Z.toJSON==="function"){if(!Q||!y9(Z))return Z.toJSON(X,Q);let U={aliasCount:0,count:1,res:void 0};Q.anchors.set(Z,U),Q.onCreate=($)=>{U.res=$,delete Q.onCreate};let J=Z.toJSON(X,Q);if(Q.onCreate)Q.onCreate(J);return J}if(typeof Z==="bigint"&&!Q?.keep)return Number(Z);return Z}class w2{constructor(Z){Object.defineProperty(this,C0,{value:Z})}clone(){let Z=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)Z.range=this.range.slice();return Z}toJS(Z,{mapAsMap:X,maxAliasCount:Q,onAnchor:U,reviver:J}={}){if(!e0(Z))throw TypeError("A document argument is required");let $={anchors:new Map,doc:Z,keep:!0,mapAsMap:X===!0,mapKeyWarned:!1,maxAliasCount:typeof Q==="number"?Q:100},W=F0(this,"",$);if(typeof U==="function")for(let{count:Y,res:G}of $.anchors.values())U(G,Y);return typeof J==="function"?W2(J,{"":W},"",W):W}}class p1 extends w2{constructor(Z){super(I9);this.source=Z,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(Z,X){let Q;if(X?.aliasResolveCache)Q=X.aliasResolveCache;else if(Q=[],q1(Z,{Node:(J,$)=>{if(l0($)||y9($))Q.push($)}}),X)X.aliasResolveCache=Q;let U=void 0;for(let J of Q){if(J===this)break;if(J.anchor===this.source)U=J}return U}toJSON(Z,X){if(!X)return{source:this.source};let{anchors:Q,doc:U,maxAliasCount:J}=X,$=this.resolve(U,X);if(!$){let Y=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(Y)}let W=Q.get($);if(!W)F0($,null,X),W=Q.get($);if(W?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(J>=0){if(W.count+=1,W.aliasCount===0)W.aliasCount=g9(U,$,Q);if(W.count*W.aliasCount>J)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return W.res}toString(Z,X,Q){let U=`*${this.source}`;if(Z){if(k9(this.source),Z.options.verifyAliasOrder&&!Z.anchors.has(this.source)){let J=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(J)}if(Z.implicitKey)return`${U} `}return U}}function g9(Z,X,Q){if(l0(X)){let U=X.resolve(Z),J=Q&&U&&Q.get(U);return J?J.count*J.aliasCount:0}else if(r(X)){let U=0;for(let J of X.items){let $=g9(Z,J,Q);if($>U)U=$}return U}else if(p(X)){let U=g9(Z,X.key,Q),J=g9(Z,X.value,Q);return Math.max(U,J)}return 1}var v9=(Z)=>!Z||typeof Z!=="function"&&typeof Z!=="object";class b extends w2{constructor(Z){super(p0);this.value=Z}toJSON(Z,X){return X?.keep?this.value:F0(this.value,Z,X)}toString(){return String(this.value)}}b.BLOCK_FOLDED="BLOCK_FOLDED";b.BLOCK_LITERAL="BLOCK_LITERAL";b.PLAIN="PLAIN";b.QUOTE_DOUBLE="QUOTE_DOUBLE";b.QUOTE_SINGLE="QUOTE_SINGLE";var j_="tag:yaml.org,2002:";function E_(Z,X,Q){if(X){let U=Q.filter(($)=>$.tag===X),J=U.find(($)=>!$.format)??U[0];if(!J)throw Error(`Tag ${X} not found`);return J}return Q.find((U)=>U.identify?.(Z)&&!U.format)}function l1(Z,X,Q){if(e0(Z))Z=Z.contents;if(l(Z))return Z;if(p(Z)){let V=Q.schema[V1].createNode?.(Q.schema,null,Q);return V.items.push(Z),V}if(Z instanceof String||Z instanceof Number||Z instanceof Boolean||typeof BigInt<"u"&&Z instanceof BigInt)Z=Z.valueOf();let{aliasDuplicateObjects:U,onAnchor:J,onTagObj:$,schema:W,sourceObjects:Y}=Q,G=void 0;if(U&&Z&&typeof Z==="object")if(G=Y.get(Z),G)return G.anchor??(G.anchor=J(Z)),new p1(G.anchor);else G={anchor:null,node:null},Y.set(Z,G);if(X?.startsWith("!!"))X=j_+X.slice(2);let _=E_(Z,X,W.tags);if(!_){if(Z&&typeof Z.toJSON==="function")Z=Z.toJSON();if(!Z||typeof Z!=="object"){let V=new b(Z);if(G)G.node=V;return V}_=Z instanceof Map?W[V1]:(Symbol.iterator in Object(Z))?W[u1]:W[V1]}if($)$(_),delete Q.onTagObj;let L=_?.createNode?_.createNode(Q.schema,Z,Q):typeof _?.nodeClass?.from==="function"?_.nodeClass.from(Q.schema,Z,Q):new b(Z);if(X)L.tag=X;else if(!_.default)L.tag=_.tag;if(G)G.node=L;return L}function _6(Z,X,Q){let U=Q;for(let J=X.length-1;J>=0;--J){let $=X[J];if(typeof $==="number"&&Number.isInteger($)&&$>=0){let W=[];W[$]=U,U=W}else U=new Map([[$,U]])}return l1(U,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:Z,sourceObjects:new Map})}var U4=(Z)=>Z==null||typeof Z==="object"&&!!Z[Symbol.iterator]().next().done;class L6 extends w2{constructor(Z,X){super(Z);Object.defineProperty(this,"schema",{value:X,configurable:!0,enumerable:!1,writable:!0})}clone(Z){let X=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(Z)X.schema=Z;if(X.items=X.items.map((Q)=>l(Q)||p(Q)?Q.clone(Z):Q),this.range)X.range=this.range.slice();return X}addIn(Z,X){if(U4(Z))this.add(X);else{let[Q,...U]=Z,J=this.get(Q,!0);if(r(J))J.addIn(U,X);else if(J===void 0&&this.schema)this.set(Q,_6(this.schema,U,X));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${U}`)}}deleteIn(Z){let[X,...Q]=Z;if(Q.length===0)return this.delete(X);let U=this.get(X,!0);if(r(U))return U.deleteIn(Q);else throw Error(`Expected YAML collection at ${X}. Remaining path: ${Q}`)}getIn(Z,X){let[Q,...U]=Z,J=this.get(Q,!0);if(U.length===0)return!X&&v(J)?J.value:J;else return r(J)?J.getIn(U,X):void 0}hasAllNullValues(Z){return this.items.every((X)=>{if(!p(X))return!1;let Q=X.value;return Q==null||Z&&v(Q)&&Q.value==null&&!Q.commentBefore&&!Q.comment&&!Q.tag})}hasIn(Z){let[X,...Q]=Z;if(Q.length===0)return this.has(X);let U=this.get(X,!0);return r(U)?U.hasIn(Q):!1}setIn(Z,X){let[Q,...U]=Z;if(U.length===0)this.set(Q,X);else{let J=this.get(Q,!0);if(r(J))J.setIn(U,X);else if(J===void 0&&this.schema)this.set(Q,_6(this.schema,U,X));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${U}`)}}}var l5=(Z)=>Z.replace(/^(?!$)(?: $)?/gm,"#");function Q1(Z,X){if(/^\n+$/.test(Z))return Z.substring(1);return X?Z.replace(/^(?! *$)/gm,X):Z}var A1=(Z,X,Q)=>Z.endsWith(`
48
+ `)?Q1(Q,X):Q.includes(`
49
+ `)?`
50
+ `+Q1(Q,X):(Z.endsWith(" ")?"":" ")+Q;var mX="flow",c5="block",i5="quoted";function V6(Z,X,Q="flow",{indentAtStart:U,lineWidth:J=80,minContentWidth:$=20,onFold:W,onOverflow:Y}={}){if(!J||J<0)return Z;if(J<$)$=0;let G=Math.max(1+$,1+J-X.length);if(Z.length<=G)return Z;let _=[],L={},V=J-X.length;if(typeof U==="number")if(U>J-Math.max(2,$))_.push(0);else V=J-U;let q=void 0,H=void 0,F=!1,z=-1,B=-1,T=-1;if(Q==="block"){if(z=d5(Z,z,X.length),z!==-1)V=z+G}for(let K;K=Z[z+=1];){if(Q==="quoted"&&K==="\\"){switch(B=z,Z[z+1]){case"x":z+=3;break;case"u":z+=5;break;case"U":z+=9;break;default:z+=1}T=z}if(K===`
51
+ `){if(Q==="block")z=d5(Z,z,X.length);V=z+X.length+G,q=void 0}else{if(K===" "&&H&&H!==" "&&H!==`
52
+ `&&H!=="\t"){let P=Z[z+1];if(P&&P!==" "&&P!==`
53
+ `&&P!=="\t")q=z}if(z>=V)if(q)_.push(q),V=q+G,q=void 0;else if(Q==="quoted"){while(H===" "||H==="\t")H=K,K=Z[z+=1],F=!0;let P=z>T+1?z-2:B-1;if(L[P])return Z;_.push(P),L[P]=!0,V=P+G,q=void 0}else F=!0}H=K}if(F&&Y)Y();if(_.length===0)return Z;if(W)W();let D=Z.slice(0,_[0]);for(let K=0;K<_.length;++K){let P=_[K],S=_[K+1]||Z.length;if(P===0)D=`
54
+ ${X}${Z.slice(0,S)}`;else{if(Q==="quoted"&&L[P])D+=`${Z[P]}\\`;D+=`
55
+ ${X}${Z.slice(P+1,S)}`}}return D}function d5(Z,X,Q){let U=X,J=X+1,$=Z[J];while($===" "||$==="\t")if(X<J+Q)$=Z[++X];else{do $=Z[++X];while($&&$!==`
56
+ `);U=X,J=X+1,$=Z[J]}return U}var h9=(Z,X)=>({indentAtStart:X?Z.indent.length:Z.indentAtStart,lineWidth:Z.options.lineWidth,minContentWidth:Z.options.minContentWidth}),m9=(Z)=>/^(%|---|\.\.\.)/m.test(Z);function b_(Z,X,Q){if(!X||X<0)return!1;let U=X-Q,J=Z.length;if(J<=U)return!1;for(let $=0,W=0;$<J;++$)if(Z[$]===`
57
+ `){if($-W>U)return!0;if(W=$+1,J-W<=U)return!1}return!0}function q6(Z,X){let Q=JSON.stringify(Z);if(X.options.doubleQuotedAsJSON)return Q;let{implicitKey:U}=X,J=X.options.doubleQuotedMinMultiLineLength,$=X.indent||(m9(Z)?" ":""),W="",Y=0;for(let G=0,_=Q[G];_;_=Q[++G]){if(_===" "&&Q[G+1]==="\\"&&Q[G+2]==="n")W+=Q.slice(Y,G)+"\\ ",G+=1,Y=G,_="\\";if(_==="\\")switch(Q[G+1]){case"u":{W+=Q.slice(Y,G);let L=Q.substr(G+2,4);switch(L){case"0000":W+="\\0";break;case"0007":W+="\\a";break;case"000b":W+="\\v";break;case"001b":W+="\\e";break;case"0085":W+="\\N";break;case"00a0":W+="\\_";break;case"2028":W+="\\L";break;case"2029":W+="\\P";break;default:if(L.substr(0,2)==="00")W+="\\x"+L.substr(2);else W+=Q.substr(G,6)}G+=5,Y=G+1}break;case"n":if(U||Q[G+2]==='"'||Q.length<J)G+=1;else{W+=Q.slice(Y,G)+`
47
58
 
48
- //# debugId=510A101DE4D2E5F964756E2164756E21
59
+ `;while(Q[G+2]==="\\"&&Q[G+3]==="n"&&Q[G+4]!=='"')W+=`
60
+ `,G+=2;if(W+=$,Q[G+2]===" ")W+="\\";G+=1,Y=G+1}break;default:G+=1}}return W=Y?W+Q.slice(Y):Q,U?W:V6(W,$,i5,h9(X,!1))}function uX(Z,X){if(X.options.singleQuote===!1||X.implicitKey&&Z.includes(`
61
+ `)||/[ \t]\n|\n[ \t]/.test(Z))return q6(Z,X);let Q=X.indent||(m9(Z)?" ":""),U="'"+Z.replace(/'/g,"''").replace(/\n+/g,`$&
62
+ ${Q}`)+"'";return X.implicitKey?U:V6(U,Q,mX,h9(X,!1))}function J4(Z,X){let{singleQuote:Q}=X.options,U;if(Q===!1)U=q6;else{let J=Z.includes('"'),$=Z.includes("'");if(J&&!$)U=uX;else if($&&!J)U=q6;else U=Q?uX:q6}return U(Z,X)}var pX;try{pX=new RegExp(`(^|(?<!
63
+ ))
64
+ +(?!
65
+ |$)`,"g")}catch{pX=/\n+(?!\n|$)/g}function x9({comment:Z,type:X,value:Q},U,J,$){let{blockQuote:W,commentString:Y,lineWidth:G}=U.options;if(!W||/\n[\t ]+$/.test(Q))return J4(Q,U);let _=U.indent||(U.forceBlockIndent||m9(Q)?" ":""),L=W==="literal"?!0:W==="folded"||X===b.BLOCK_FOLDED?!1:X===b.BLOCK_LITERAL?!0:!b_(Q,G,_.length);if(!Q)return L?`|
66
+ `:`>
67
+ `;let V,q;for(q=Q.length;q>0;--q){let S=Q[q-1];if(S!==`
68
+ `&&S!=="\t"&&S!==" ")break}let H=Q.substring(q),F=H.indexOf(`
69
+ `);if(F===-1)V="-";else if(Q===H||F!==H.length-1){if(V="+",$)$()}else V="";if(H){if(Q=Q.slice(0,-H.length),H[H.length-1]===`
70
+ `)H=H.slice(0,-1);H=H.replace(pX,`$&${_}`)}let z=!1,B,T=-1;for(B=0;B<Q.length;++B){let S=Q[B];if(S===" ")z=!0;else if(S===`
71
+ `)T=B;else break}let D=Q.substring(0,T<B?T+1:B);if(D)Q=Q.substring(D.length),D=D.replace(/\n+/g,`$&${_}`);let P=(z?_?"2":"1":"")+V;if(Z){if(P+=" "+Y(Z.replace(/ ?[\r\n]+/g," ")),J)J()}if(!L){let S=Q.replace(/\n+/g,`
72
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${_}`),N=!1,x=h9(U,!0);if(W!=="folded"&&X!==b.BLOCK_FOLDED)x.onOverflow=()=>{N=!0};let C=V6(`${D}${S}${H}`,_,c5,x);if(!N)return`>${P}
73
+ ${_}${C}`}return Q=Q.replace(/\n+/g,`$&${_}`),`|${P}
74
+ ${_}${D}${Q}${H}`}function I_(Z,X,Q,U){let{type:J,value:$}=Z,{actualString:W,implicitKey:Y,indent:G,indentStep:_,inFlow:L}=X;if(Y&&$.includes(`
75
+ `)||L&&/[[\]{},]/.test($))return J4($,X);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test($))return Y||L||!$.includes(`
76
+ `)?J4($,X):x9(Z,X,Q,U);if(!Y&&!L&&J!==b.PLAIN&&$.includes(`
77
+ `))return x9(Z,X,Q,U);if(m9($)){if(G==="")return X.forceBlockIndent=!0,x9(Z,X,Q,U);else if(Y&&G===_)return J4($,X)}let V=$.replace(/\n+/g,`$&
78
+ ${G}`);if(W){let q=(z)=>z.default&&z.tag!=="tag:yaml.org,2002:str"&&z.test?.test(V),{compat:H,tags:F}=X.doc.schema;if(F.some(q)||H?.some(q))return J4($,X)}return Y?V:V6(V,G,mX,h9(X,!1))}function d1(Z,X,Q,U){let{implicitKey:J,inFlow:$}=X,W=typeof Z.value==="string"?Z:Object.assign({},Z,{value:String(Z.value)}),{type:Y}=Z;if(Y!==b.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(W.value))Y=b.QUOTE_DOUBLE}let G=(L)=>{switch(L){case b.BLOCK_FOLDED:case b.BLOCK_LITERAL:return J||$?J4(W.value,X):x9(W,X,Q,U);case b.QUOTE_DOUBLE:return q6(W.value,X);case b.QUOTE_SINGLE:return uX(W.value,X);case b.PLAIN:return I_(W,X,Q,U);default:return null}},_=G(Y);if(_===null){let{defaultKeyType:L,defaultStringType:V}=X.options,q=J&&L||V;if(_=G(q),_===null)throw Error(`Unsupported default string type ${q}`)}return _}function u9(Z,X){let Q=Object.assign({blockQuote:!0,commentString:l5,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},Z.schema.toStringOptions,X),U;switch(Q.collectionStyle){case"block":U=!1;break;case"flow":U=!0;break;default:U=null}return{anchors:new Set,doc:Z,flowCollectionPadding:Q.flowCollectionPadding?" ":"",indent:"",indentStep:typeof Q.indent==="number"?" ".repeat(Q.indent):" ",inFlow:U,options:Q}}function f_(Z,X){if(X.tag){let J=Z.filter(($)=>$.tag===X.tag);if(J.length>0)return J.find(($)=>$.format===X.format)??J[0]}let Q=void 0,U;if(v(X)){U=X.value;let J=Z.filter(($)=>$.identify?.(U));if(J.length>1){let $=J.filter((W)=>W.test);if($.length>0)J=$}Q=J.find(($)=>$.format===X.format)??J.find(($)=>!$.format)}else U=X,Q=Z.find((J)=>J.nodeClass&&U instanceof J.nodeClass);if(!Q){let J=U?.constructor?.name??(U===null?"null":typeof U);throw Error(`Tag not resolved for ${J} value`)}return Q}function y_(Z,X,{anchors:Q,doc:U}){if(!U.directives)return"";let J=[],$=(v(Z)||r(Z))&&Z.anchor;if($&&k9($))Q.add($),J.push(`&${$}`);let W=Z.tag??(X.default?null:X.tag);if(W)J.push(U.directives.tagString(W));return J.join(" ")}function c1(Z,X,Q,U){if(p(Z))return Z.toString(X,Q,U);if(l0(Z)){if(X.doc.directives)return Z.toString(X);if(X.resolvedAliases?.has(Z))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(X.resolvedAliases)X.resolvedAliases.add(Z);else X.resolvedAliases=new Set([Z]);Z=Z.resolve(X.doc)}}let J=void 0,$=l(Z)?Z:X.doc.createNode(Z,{onTagObj:(G)=>J=G});J??(J=f_(X.doc.schema.tags,$));let W=y_($,J,X);if(W.length>0)X.indentAtStart=(X.indentAtStart??0)+W.length+1;let Y=typeof J.stringify==="function"?J.stringify($,X,Q,U):v($)?d1($,X,Q,U):$.toString(X,Q,U);if(!W)return Y;return v($)||Y[0]==="{"||Y[0]==="["?`${W} ${Y}`:`${W}
79
+ ${X.indent}${Y}`}function s5({key:Z,value:X},Q,U,J){let{allNullValues:$,doc:W,indent:Y,indentStep:G,options:{commentString:_,indentSeq:L,simpleKeys:V}}=Q,q=l(Z)&&Z.comment||null;if(V){if(q)throw Error("With simple keys, key nodes cannot have comments");if(r(Z)||!l(Z)&&typeof Z==="object")throw Error("With simple keys, collection cannot be used as a key value")}let H=!V&&(!Z||q&&X==null&&!Q.inFlow||r(Z)||(v(Z)?Z.type===b.BLOCK_FOLDED||Z.type===b.BLOCK_LITERAL:typeof Z==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!H&&(V||!$),indent:Y+G});let F=!1,z=!1,B=c1(Z,Q,()=>F=!0,()=>z=!0);if(!H&&!Q.inFlow&&B.length>1024){if(V)throw Error("With simple keys, single line scalar must not span more than 1024 characters");H=!0}if(Q.inFlow){if($||X==null){if(F&&U)U();return B===""?"?":H?`? ${B}`:B}}else if($&&!V||X==null&&H){if(B=`? ${B}`,q&&!F)B+=A1(B,Q.indent,_(q));else if(z&&J)J();return B}if(F)q=null;if(H){if(q)B+=A1(B,Q.indent,_(q));B=`? ${B}
80
+ ${Y}:`}else if(B=`${B}:`,q)B+=A1(B,Q.indent,_(q));let T,D,K;if(l(X))T=!!X.spaceBefore,D=X.commentBefore,K=X.comment;else if(T=!1,D=null,K=null,X&&typeof X==="object")X=W.createNode(X);if(Q.implicitKey=!1,!H&&!q&&v(X))Q.indentAtStart=B.length+1;if(z=!1,!L&&G.length>=2&&!Q.inFlow&&!H&&X1(X)&&!X.flow&&!X.tag&&!X.anchor)Q.indent=Q.indent.substring(2);let P=!1,S=c1(X,Q,()=>P=!0,()=>z=!0),N=" ";if(q||T||D){if(N=T?`
81
+ `:"",D){let x=_(D);N+=`
82
+ ${Q1(x,Q.indent)}`}if(S===""&&!Q.inFlow){if(N===`
83
+ `&&K)N=`
84
+
85
+ `}else N+=`
86
+ ${Q.indent}`}else if(!H&&r(X)){let x=S[0],C=S.indexOf(`
87
+ `),h=C!==-1,a=Q.inFlow??X.flow??X.items.length===0;if(h||!a){let W0=!1;if(h&&(x==="&"||x==="!")){let n=S.indexOf(" ");if(x==="&"&&n!==-1&&n<C&&S[n+1]==="!")n=S.indexOf(" ",n+1);if(n===-1||C<n)W0=!0}if(!W0)N=`
88
+ ${Q.indent}`}}else if(S===""||S[0]===`
89
+ `)N="";if(B+=N+S,Q.inFlow){if(P&&U)U()}else if(K&&!P)B+=A1(B,Q.indent,_(K));else if(z&&J)J();return B}function p9(Z,X){if(Z==="debug"||Z==="warn")console.warn(X)}var l9="<<",H1={identify:(Z)=>Z===l9||typeof Z==="symbol"&&Z.description===l9,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new b(Symbol(l9)),{addToJSMap:dX}),stringify:()=>l9},r5=(Z,X)=>(H1.identify(X)||v(X)&&(!X.type||X.type===b.PLAIN)&&H1.identify(X.value))&&Z?.doc.schema.tags.some((Q)=>Q.tag===H1.tag&&Q.default);function dX(Z,X,Q){if(Q=Z&&l0(Q)?Q.resolve(Z.doc):Q,X1(Q))for(let U of Q.items)lX(Z,X,U);else if(Array.isArray(Q))for(let U of Q)lX(Z,X,U);else lX(Z,X,Q)}function lX(Z,X,Q){let U=Z&&l0(Q)?Q.resolve(Z.doc):Q;if(!Z1(U))throw Error("Merge sources must be maps or map aliases");let J=U.toJSON(null,Z,Map);for(let[$,W]of J)if(X instanceof Map){if(!X.has($))X.set($,W)}else if(X instanceof Set)X.add($);else if(!Object.prototype.hasOwnProperty.call(X,$))Object.defineProperty(X,$,{value:W,writable:!0,enumerable:!0,configurable:!0});return X}function d9(Z,X,{key:Q,value:U}){if(l(Q)&&Q.addToJSMap)Q.addToJSMap(Z,X,U);else if(r5(Z,Q))dX(Z,X,U);else{let J=F0(Q,"",Z);if(X instanceof Map)X.set(J,F0(U,J,Z));else if(X instanceof Set)X.add(J);else{let $=k_(Q,J,Z),W=F0(U,$,Z);if($ in X)Object.defineProperty(X,$,{value:W,writable:!0,enumerable:!0,configurable:!0});else X[$]=W}}return X}function k_(Z,X,Q){if(X===null)return"";if(typeof X!=="object")return String(X);if(l(Z)&&Q?.doc){let U=u9(Q.doc,{});U.anchors=new Set;for(let $ of Q.anchors.keys())U.anchors.add($.anchor);U.inFlow=!0,U.inStringifyKey=!0;let J=Z.toString(U);if(!Q.mapKeyWarned){let $=JSON.stringify(J);if($.length>40)$=$.substring(0,36)+'..."';p9(Q.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${$}. Set mapAsMap: true to use object keys.`),Q.mapKeyWarned=!0}return J}return JSON.stringify(X)}function $4(Z,X,Q){let U=l1(Z,void 0,Q),J=l1(X,void 0,Q);return new $0(U,J)}class $0{constructor(Z,X=null){Object.defineProperty(this,C0,{value:vX}),this.key=Z,this.value=X}clone(Z){let{key:X,value:Q}=this;if(l(X))X=X.clone(Z);if(l(Q))Q=Q.clone(Z);return new $0(X,Q)}toJSON(Z,X){let Q=X?.mapAsMap?new Map:{};return d9(X,Q,this)}toString(Z,X,Q){return Z?.doc?s5(this,Z,X,Q):JSON.stringify(this)}}function i9(Z,X,Q){return(X.inFlow??Z.flow?v_:g_)(Z,X,Q)}function g_({comment:Z,items:X},Q,{blockItemPrefix:U,flowChars:J,itemIndent:$,onChompKeep:W,onComment:Y}){let{indent:G,options:{commentString:_}}=Q,L=Object.assign({},Q,{indent:$,type:null}),V=!1,q=[];for(let F=0;F<X.length;++F){let z=X[F],B=null;if(l(z)){if(!V&&z.spaceBefore)q.push("");if(c9(Q,q,z.commentBefore,V),z.comment)B=z.comment}else if(p(z)){let D=l(z.key)?z.key:null;if(D){if(!V&&D.spaceBefore)q.push("");c9(Q,q,D.commentBefore,V)}}V=!1;let T=c1(z,L,()=>B=null,()=>V=!0);if(B)T+=A1(T,$,_(B));if(V&&B)V=!1;q.push(U+T)}let H;if(q.length===0)H=J.start+J.end;else{H=q[0];for(let F=1;F<q.length;++F){let z=q[F];H+=z?`
90
+ ${G}${z}`:`
91
+ `}}if(Z){if(H+=`
92
+ `+Q1(_(Z),G),Y)Y()}else if(V&&W)W();return H}function v_({items:Z},X,{flowChars:Q,itemIndent:U}){let{indent:J,indentStep:$,flowCollectionPadding:W,options:{commentString:Y}}=X;U+=$;let G=Object.assign({},X,{indent:U,inFlow:!0,type:null}),_=!1,L=0,V=[];for(let F=0;F<Z.length;++F){let z=Z[F],B=null;if(l(z)){if(z.spaceBefore)V.push("");if(c9(X,V,z.commentBefore,!1),z.comment)B=z.comment}else if(p(z)){let D=l(z.key)?z.key:null;if(D){if(D.spaceBefore)V.push("");if(c9(X,V,D.commentBefore,!1),D.comment)_=!0}let K=l(z.value)?z.value:null;if(K){if(K.comment)B=K.comment;if(K.commentBefore)_=!0}else if(z.value==null&&D?.comment)B=D.comment}if(B)_=!0;let T=c1(z,G,()=>B=null);if(F<Z.length-1)T+=",";if(B)T+=A1(T,U,Y(B));if(!_&&(V.length>L||T.includes(`
93
+ `)))_=!0;V.push(T),L=V.length}let{start:q,end:H}=Q;if(V.length===0)return q+H;else{if(!_){let F=V.reduce((z,B)=>z+B.length+2,2);_=X.options.lineWidth>0&&F>X.options.lineWidth}if(_){let F=q;for(let z of V)F+=z?`
94
+ ${$}${J}${z}`:`
95
+ `;return`${F}
96
+ ${J}${H}`}else return`${q}${W}${V.join(" ")}${W}${H}`}}function c9({indent:Z,options:{commentString:X}},Q,U,J){if(U&&J)U=U.replace(/^\n+/,"");if(U){let $=Q1(X(U),Z);Q.push($.trimStart())}}function Y2(Z,X){let Q=v(X)?X.value:X;for(let U of Z)if(p(U)){if(U.key===X||U.key===Q)return U;if(v(U.key)&&U.key.value===Q)return U}return}class G0 extends L6{static get tagName(){return"tag:yaml.org,2002:map"}constructor(Z){super(V1,Z);this.items=[]}static from(Z,X,Q){let{keepUndefined:U,replacer:J}=Q,$=new this(Z),W=(Y,G)=>{if(typeof J==="function")G=J.call(X,Y,G);else if(Array.isArray(J)&&!J.includes(Y))return;if(G!==void 0||U)$.items.push($4(Y,G,Q))};if(X instanceof Map)for(let[Y,G]of X)W(Y,G);else if(X&&typeof X==="object")for(let Y of Object.keys(X))W(Y,X[Y]);if(typeof Z.sortMapEntries==="function")$.items.sort(Z.sortMapEntries);return $}add(Z,X){let Q;if(p(Z))Q=Z;else if(!Z||typeof Z!=="object"||!("key"in Z))Q=new $0(Z,Z?.value);else Q=new $0(Z.key,Z.value);let U=Y2(this.items,Q.key),J=this.schema?.sortMapEntries;if(U){if(!X)throw Error(`Key ${Q.key} already set`);if(v(U.value)&&v9(Q.value))U.value.value=Q.value;else U.value=Q.value}else if(J){let $=this.items.findIndex((W)=>J(Q,W)<0);if($===-1)this.items.push(Q);else this.items.splice($,0,Q)}else this.items.push(Q)}delete(Z){let X=Y2(this.items,Z);if(!X)return!1;return this.items.splice(this.items.indexOf(X),1).length>0}get(Z,X){let U=Y2(this.items,Z)?.value;return(!X&&v(U)?U.value:U)??void 0}has(Z){return!!Y2(this.items,Z)}set(Z,X){this.add(new $0(Z,X),!0)}toJSON(Z,X,Q){let U=Q?new Q:X?.mapAsMap?new Map:{};if(X?.onCreate)X.onCreate(U);for(let J of this.items)d9(X,U,J);return U}toString(Z,X,Q){if(!Z)return JSON.stringify(this);for(let U of this.items)if(!p(U))throw Error(`Map items must all be pairs; found ${JSON.stringify(U)} instead`);if(!Z.allNullValues&&this.hasAllNullValues(!1))Z=Object.assign({},Z,{allNullValues:!0});return i9(this,Z,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:Z.indent||"",onChompKeep:Q,onComment:X})}}var z1={collection:"map",default:!0,nodeClass:G0,tag:"tag:yaml.org,2002:map",resolve(Z,X){if(!Z1(Z))X("Expected a mapping for this tag");return Z},createNode:(Z,X,Q)=>G0.from(Z,X,Q)};class D0 extends L6{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(Z){super(u1,Z);this.items=[]}add(Z){this.items.push(Z)}delete(Z){let X=s9(Z);if(typeof X!=="number")return!1;return this.items.splice(X,1).length>0}get(Z,X){let Q=s9(Z);if(typeof Q!=="number")return;let U=this.items[Q];return!X&&v(U)?U.value:U}has(Z){let X=s9(Z);return typeof X==="number"&&X<this.items.length}set(Z,X){let Q=s9(Z);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${Z}.`);let U=this.items[Q];if(v(U)&&v9(X))U.value=X;else this.items[Q]=X}toJSON(Z,X){let Q=[];if(X?.onCreate)X.onCreate(Q);let U=0;for(let J of this.items)Q.push(F0(J,String(U++),X));return Q}toString(Z,X,Q){if(!Z)return JSON.stringify(this);return i9(this,Z,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(Z.indent||"")+" ",onChompKeep:Q,onComment:X})}static from(Z,X,Q){let{replacer:U}=Q,J=new this(Z);if(X&&Symbol.iterator in Object(X)){let $=0;for(let W of X){if(typeof U==="function"){let Y=X instanceof Set?W:String($++);W=U.call(X,Y,W)}J.items.push(l1(W,void 0,Q))}}return J}}function s9(Z){let X=v(Z)?Z.value:Z;if(X&&typeof X==="string")X=Number(X);return typeof X==="number"&&Number.isInteger(X)&&X>=0?X:null}var F1={collection:"seq",default:!0,nodeClass:D0,tag:"tag:yaml.org,2002:seq",resolve(Z,X){if(!X1(Z))X("Expected a sequence for this tag");return Z},createNode:(Z,X,Q)=>D0.from(Z,X,Q)};var G2={identify:(Z)=>typeof Z==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(Z)=>Z,stringify(Z,X,Q,U){return X=Object.assign({actualString:!0},X),d1(Z,X,Q,U)}};var A2={identify:(Z)=>Z==null,createNode:()=>new b(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new b(null),stringify:({source:Z},X)=>typeof Z==="string"&&A2.test.test(Z)?Z:X.options.nullStr};var H6={identify:(Z)=>typeof Z==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(Z)=>new b(Z[0]==="t"||Z[0]==="T"),stringify({source:Z,value:X},Q){if(Z&&H6.test.test(Z)){let U=Z[0]==="t"||Z[0]==="T";if(X===U)return Z}return X?Q.options.trueStr:Q.options.falseStr}};function P0({format:Z,minFractionDigits:X,tag:Q,value:U}){if(typeof U==="bigint")return String(U);let J=typeof U==="number"?U:Number(U);if(!isFinite(J))return isNaN(J)?".nan":J<0?"-.inf":".inf";let $=Object.is(U,-0)?"-0":JSON.stringify(U);if(!Z&&X&&(!Q||Q==="tag:yaml.org,2002:float")&&/^\d/.test($)){let W=$.indexOf(".");if(W<0)W=$.length,$+=".";let Y=X-($.length-W-1);while(Y-- >0)$+="0"}return $}var r9={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(Z)=>Z.slice(-3).toLowerCase()==="nan"?NaN:Z[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:P0},o9={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(Z)=>parseFloat(Z),stringify(Z){let X=Number(Z.value);return isFinite(X)?X.toExponential():P0(Z)}},a9={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(Z){let X=new b(parseFloat(Z)),Q=Z.indexOf(".");if(Q!==-1&&Z[Z.length-1]==="0")X.minFractionDigits=Z.length-Q-1;return X},stringify:P0};var n9=(Z)=>typeof Z==="bigint"||Number.isInteger(Z),cX=(Z,X,Q,{intAsBigInt:U})=>U?BigInt(Z):parseInt(Z.substring(X),Q);function o5(Z,X,Q){let{value:U}=Z;if(n9(U)&&U>=0)return Q+U.toString(X);return P0(Z)}var t9={identify:(Z)=>n9(Z)&&Z>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(Z,X,Q)=>cX(Z,2,8,Q),stringify:(Z)=>o5(Z,8,"0o")},e9={identify:n9,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(Z,X,Q)=>cX(Z,0,10,Q),stringify:P0},Z8={identify:(Z)=>n9(Z)&&Z>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(Z,X,Q)=>cX(Z,2,16,Q),stringify:(Z)=>o5(Z,16,"0x")};var a5=[z1,F1,G2,A2,H6,t9,e9,Z8,r9,o9,a9];function n5(Z){return typeof Z==="bigint"||Number.isInteger(Z)}var X8=({value:Z})=>JSON.stringify(Z),x_=[{identify:(Z)=>typeof Z==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(Z)=>Z,stringify:X8},{identify:(Z)=>Z==null,createNode:()=>new b(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:X8},{identify:(Z)=>typeof Z==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(Z)=>Z==="true",stringify:X8},{identify:n5,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(Z,X,{intAsBigInt:Q})=>Q?BigInt(Z):parseInt(Z,10),stringify:({value:Z})=>n5(Z)?Z.toString():JSON.stringify(Z)},{identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(Z)=>parseFloat(Z),stringify:X8}],h_={default:!0,tag:"",test:/^/,resolve(Z,X){return X(`Unresolved plain scalar ${JSON.stringify(Z)}`),Z}},t5=[z1,F1].concat(x_,h_);var z6={identify:(Z)=>Z instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(Z,X){if(typeof atob==="function"){let Q=atob(Z.replace(/[\n\r]/g,"")),U=new Uint8Array(Q.length);for(let J=0;J<Q.length;++J)U[J]=Q.charCodeAt(J);return U}else return X("This environment does not support reading binary tags; either Buffer or atob is required"),Z},stringify({comment:Z,type:X,value:Q},U,J,$){if(!Q)return"";let W=Q,Y;if(typeof btoa==="function"){let G="";for(let _=0;_<W.length;++_)G+=String.fromCharCode(W[_]);Y=btoa(G)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(X??(X=b.BLOCK_LITERAL),X!==b.QUOTE_DOUBLE){let G=Math.max(U.options.lineWidth-U.indent.length,U.options.minContentWidth),_=Math.ceil(Y.length/G),L=Array(_);for(let V=0,q=0;V<_;++V,q+=G)L[V]=Y.substr(q,G);Y=L.join(X===b.BLOCK_LITERAL?`
97
+ `:" ")}return d1({comment:Z,type:X,value:Y},U,J,$)}};function iX(Z,X){if(X1(Z))for(let Q=0;Q<Z.items.length;++Q){let U=Z.items[Q];if(p(U))continue;else if(Z1(U)){if(U.items.length>1)X("Each pair must have its own sequence indicator");let J=U.items[0]||new $0(new b(null));if(U.commentBefore)J.key.commentBefore=J.key.commentBefore?`${U.commentBefore}
98
+ ${J.key.commentBefore}`:U.commentBefore;if(U.comment){let $=J.value??J.key;$.comment=$.comment?`${U.comment}
99
+ ${$.comment}`:U.comment}U=J}Z.items[Q]=p(U)?U:new $0(U)}else X("Expected a sequence for this tag");return Z}function sX(Z,X,Q){let{replacer:U}=Q,J=new D0(Z);J.tag="tag:yaml.org,2002:pairs";let $=0;if(X&&Symbol.iterator in Object(X))for(let W of X){if(typeof U==="function")W=U.call(X,String($++),W);let Y,G;if(Array.isArray(W))if(W.length===2)Y=W[0],G=W[1];else throw TypeError(`Expected [key, value] tuple: ${W}`);else if(W&&W instanceof Object){let _=Object.keys(W);if(_.length===1)Y=_[0],G=W[Y];else throw TypeError(`Expected tuple with one key, not ${_.length} keys`)}else Y=W;J.items.push($4(Y,G,Q))}return J}var F6={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:iX,createNode:sX};class W4 extends D0{constructor(){super();this.add=G0.prototype.add.bind(this),this.delete=G0.prototype.delete.bind(this),this.get=G0.prototype.get.bind(this),this.has=G0.prototype.has.bind(this),this.set=G0.prototype.set.bind(this),this.tag=W4.tag}toJSON(Z,X){if(!X)return super.toJSON(Z);let Q=new Map;if(X?.onCreate)X.onCreate(Q);for(let U of this.items){let J,$;if(p(U))J=F0(U.key,"",X),$=F0(U.value,J,X);else J=F0(U,"",X);if(Q.has(J))throw Error("Ordered maps must not include duplicate keys");Q.set(J,$)}return Q}static from(Z,X,Q){let U=sX(Z,X,Q),J=new this;return J.items=U.items,J}}W4.tag="tag:yaml.org,2002:omap";var B6={collection:"seq",identify:(Z)=>Z instanceof Map,nodeClass:W4,default:!1,tag:"tag:yaml.org,2002:omap",resolve(Z,X){let Q=iX(Z,X),U=[];for(let{key:J}of Q.items)if(v(J))if(U.includes(J.value))X(`Ordered maps must not include duplicate keys: ${J.value}`);else U.push(J.value);return Object.assign(new W4,Q)},createNode:(Z,X,Q)=>W4.from(Z,X,Q)};function e5({value:Z,source:X},Q){if(X&&(Z?rX:oX).test.test(X))return X;return Z?Q.options.trueStr:Q.options.falseStr}var rX={identify:(Z)=>Z===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new b(!0),stringify:e5},oX={identify:(Z)=>Z===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new b(!1),stringify:e5};var ZJ={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(Z)=>Z.slice(-3).toLowerCase()==="nan"?NaN:Z[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:P0},XJ={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(Z)=>parseFloat(Z.replace(/_/g,"")),stringify(Z){let X=Number(Z.value);return isFinite(X)?X.toExponential():P0(Z)}},QJ={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(Z){let X=new b(parseFloat(Z.replace(/_/g,""))),Q=Z.indexOf(".");if(Q!==-1){let U=Z.substring(Q+1).replace(/_/g,"");if(U[U.length-1]==="0")X.minFractionDigits=U.length}return X},stringify:P0};var M6=(Z)=>typeof Z==="bigint"||Number.isInteger(Z);function Q8(Z,X,Q,{intAsBigInt:U}){let J=Z[0];if(J==="-"||J==="+")X+=1;if(Z=Z.substring(X).replace(/_/g,""),U){switch(Q){case 2:Z=`0b${Z}`;break;case 8:Z=`0o${Z}`;break;case 16:Z=`0x${Z}`;break}let W=BigInt(Z);return J==="-"?BigInt(-1)*W:W}let $=parseInt(Z,Q);return J==="-"?-1*$:$}function aX(Z,X,Q){let{value:U}=Z;if(M6(U)){let J=U.toString(X);return U<0?"-"+Q+J.substr(1):Q+J}return P0(Z)}var UJ={identify:M6,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(Z,X,Q)=>Q8(Z,2,2,Q),stringify:(Z)=>aX(Z,2,"0b")},JJ={identify:M6,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(Z,X,Q)=>Q8(Z,1,8,Q),stringify:(Z)=>aX(Z,8,"0")},$J={identify:M6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(Z,X,Q)=>Q8(Z,0,10,Q),stringify:P0},WJ={identify:M6,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(Z,X,Q)=>Q8(Z,2,16,Q),stringify:(Z)=>aX(Z,16,"0x")};class Y4 extends G0{constructor(Z){super(Z);this.tag=Y4.tag}add(Z){let X;if(p(Z))X=Z;else if(Z&&typeof Z==="object"&&"key"in Z&&"value"in Z&&Z.value===null)X=new $0(Z.key,null);else X=new $0(Z,null);if(!Y2(this.items,X.key))this.items.push(X)}get(Z,X){let Q=Y2(this.items,Z);return!X&&p(Q)?v(Q.key)?Q.key.value:Q.key:Q}set(Z,X){if(typeof X!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof X}`);let Q=Y2(this.items,Z);if(Q&&!X)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&X)this.items.push(new $0(Z))}toJSON(Z,X){return super.toJSON(Z,X,Set)}toString(Z,X,Q){if(!Z)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},Z,{allNullValues:!0}),X,Q);else throw Error("Set items must all have null values")}static from(Z,X,Q){let{replacer:U}=Q,J=new this(Z);if(X&&Symbol.iterator in Object(X))for(let $ of X){if(typeof U==="function")$=U.call(X,$,$);J.items.push($4($,null,Q))}return J}}Y4.tag="tag:yaml.org,2002:set";var R6={collection:"map",identify:(Z)=>Z instanceof Set,nodeClass:Y4,default:!1,tag:"tag:yaml.org,2002:set",createNode:(Z,X,Q)=>Y4.from(Z,X,Q),resolve(Z,X){if(Z1(Z))if(Z.hasAllNullValues(!0))return Object.assign(new Y4,Z);else X("Set items must all have null values");else X("Expected a mapping for this tag");return Z}};function nX(Z,X){let Q=Z[0],U=Q==="-"||Q==="+"?Z.substring(1):Z,J=(W)=>X?BigInt(W):Number(W),$=U.replace(/_/g,"").split(":").reduce((W,Y)=>W*J(60)+J(Y),J(0));return Q==="-"?J(-1)*$:$}function YJ(Z){let{value:X}=Z,Q=(W)=>W;if(typeof X==="bigint")Q=(W)=>BigInt(W);else if(isNaN(X)||!isFinite(X))return P0(Z);let U="";if(X<0)U="-",X*=Q(-1);let J=Q(60),$=[X%J];if(X<60)$.unshift(0);else if(X=(X-$[0])/J,$.unshift(X%J),X>=60)X=(X-$[0])/J,$.unshift(X);return U+$.map((W)=>String(W).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var U8={identify:(Z)=>typeof Z==="bigint"||Number.isInteger(Z),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(Z,X,{intAsBigInt:Q})=>nX(Z,Q),stringify:YJ},J8={identify:(Z)=>typeof Z==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(Z)=>nX(Z,!1),stringify:YJ},G4={identify:(Z)=>Z instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(Z){let X=Z.match(G4.test);if(!X)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,U,J,$,W,Y]=X.map(Number),G=X[7]?Number((X[7]+"00").substr(1,3)):0,_=Date.UTC(Q,U-1,J,$||0,W||0,Y||0,G),L=X[8];if(L&&L!=="Z"){let V=nX(L,!1);if(Math.abs(V)<30)V*=60;_-=60000*V}return new Date(_)},stringify:({value:Z})=>Z?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var tX=[z1,F1,G2,A2,rX,oX,UJ,JJ,$J,WJ,ZJ,XJ,QJ,z6,H1,B6,F6,R6,U8,J8,G4];var GJ=new Map([["core",a5],["failsafe",[z1,F1,G2]],["json",t5],["yaml11",tX],["yaml-1.1",tX]]),_J={binary:z6,bool:H6,float:a9,floatExp:o9,floatNaN:r9,floatTime:J8,int:e9,intHex:Z8,intOct:t9,intTime:U8,map:z1,merge:H1,null:A2,omap:B6,pairs:F6,seq:F1,set:R6,timestamp:G4},LJ={"tag:yaml.org,2002:binary":z6,"tag:yaml.org,2002:merge":H1,"tag:yaml.org,2002:omap":B6,"tag:yaml.org,2002:pairs":F6,"tag:yaml.org,2002:set":R6,"tag:yaml.org,2002:timestamp":G4};function $8(Z,X,Q){let U=GJ.get(X);if(U&&!Z)return Q&&!U.includes(H1)?U.concat(H1):U.slice();let J=U;if(!J)if(Array.isArray(Z))J=[];else{let $=Array.from(GJ.keys()).filter((W)=>W!=="yaml11").map((W)=>JSON.stringify(W)).join(", ");throw Error(`Unknown schema "${X}"; use one of ${$} or define customTags array`)}if(Array.isArray(Z))for(let $ of Z)J=J.concat($);else if(typeof Z==="function")J=Z(J.slice());if(Q)J=J.concat(H1);return J.reduce(($,W)=>{let Y=typeof W==="string"?_J[W]:W;if(!Y){let G=JSON.stringify(W),_=Object.keys(_J).map((L)=>JSON.stringify(L)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${_}`)}if(!$.includes(Y))$.push(Y);return $},[])}var m_=(Z,X)=>Z.key<X.key?-1:Z.key>X.key?1:0;class _4{constructor({compat:Z,customTags:X,merge:Q,resolveKnownTags:U,schema:J,sortMapEntries:$,toStringDefaults:W}){this.compat=Array.isArray(Z)?$8(Z,"compat"):Z?$8(null,Z):null,this.name=typeof J==="string"&&J||"core",this.knownTags=U?LJ:{},this.tags=$8(X,this.name,Q),this.toStringOptions=W??null,Object.defineProperty(this,V1,{value:z1}),Object.defineProperty(this,p0,{value:G2}),Object.defineProperty(this,u1,{value:F1}),this.sortMapEntries=typeof $==="function"?$:$===!0?m_:null}clone(){let Z=Object.create(_4.prototype,Object.getOwnPropertyDescriptors(this));return Z.tags=this.tags.slice(),Z}}function VJ(Z,X){let Q=[],U=X.directives===!0;if(X.directives!==!1&&Z.directives){let G=Z.directives.toString(Z);if(G)Q.push(G),U=!0;else if(Z.directives.docStart)U=!0}if(U)Q.push("---");let J=u9(Z,X),{commentString:$}=J.options;if(Z.commentBefore){if(Q.length!==1)Q.unshift("");let G=$(Z.commentBefore);Q.unshift(Q1(G,""))}let W=!1,Y=null;if(Z.contents){if(l(Z.contents)){if(Z.contents.spaceBefore&&U)Q.push("");if(Z.contents.commentBefore){let L=$(Z.contents.commentBefore);Q.push(Q1(L,""))}J.forceBlockIndent=!!Z.comment,Y=Z.contents.comment}let G=Y?void 0:()=>W=!0,_=c1(Z.contents,J,()=>Y=null,G);if(Y)_+=A1(_,"",$(Y));if((_[0]==="|"||_[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${_}`;else Q.push(_)}else Q.push(c1(Z.contents,J));if(Z.directives?.docEnd)if(Z.comment){let G=$(Z.comment);if(G.includes(`
100
+ `))Q.push("..."),Q.push(Q1(G,""));else Q.push(`... ${G}`)}else Q.push("...");else{let G=Z.comment;if(G&&W)G=G.replace(/^\n+/,"");if(G){if((!W||Y)&&Q[Q.length-1]!=="")Q.push("");Q.push(Q1($(G),""))}}return Q.join(`
101
+ `)+`
102
+ `}class S1{constructor(Z,X,Q){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,C0,{value:f9});let U=null;if(typeof X==="function"||Array.isArray(X))U=X;else if(Q===void 0&&X)Q=X,X=void 0;let J=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=J;let{version:$}=J;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)$=this.directives.yaml.version}else this.directives=new M0({version:$});this.setSchema($,Q),this.contents=Z===void 0?null:this.createNode(Z,U,Q)}clone(){let Z=Object.create(S1.prototype,{[C0]:{value:f9}});if(Z.commentBefore=this.commentBefore,Z.comment=this.comment,Z.errors=this.errors.slice(),Z.warnings=this.warnings.slice(),Z.options=Object.assign({},this.options),this.directives)Z.directives=this.directives.clone();if(Z.schema=this.schema.clone(),Z.contents=l(this.contents)?this.contents.clone(Z.schema):this.contents,this.range)Z.range=this.range.slice();return Z}add(Z){if(L4(this.contents))this.contents.add(Z)}addIn(Z,X){if(L4(this.contents))this.contents.addIn(Z,X)}createAlias(Z,X){if(!Z.anchor){let Q=xX(this);Z.anchor=!X||Q.has(X)?hX(X||"a",Q):X}return new p1(Z.anchor)}createNode(Z,X,Q){let U=void 0;if(typeof X==="function")Z=X.call({"":Z},"",Z),U=X;else if(Array.isArray(X)){let z=(T)=>typeof T==="number"||T instanceof String||T instanceof Number,B=X.filter(z).map(String);if(B.length>0)X=X.concat(B);U=X}else if(Q===void 0&&X)Q=X,X=void 0;let{aliasDuplicateObjects:J,anchorPrefix:$,flow:W,keepUndefined:Y,onTagObj:G,tag:_}=Q??{},{onAnchor:L,setAnchors:V,sourceObjects:q}=p5(this,$||"a"),H={aliasDuplicateObjects:J??!0,keepUndefined:Y??!1,onAnchor:L,onTagObj:G,replacer:U,schema:this.schema,sourceObjects:q},F=l1(Z,_,H);if(W&&r(F))F.flow=!0;return V(),F}createPair(Z,X,Q={}){let U=this.createNode(Z,null,Q),J=this.createNode(X,null,Q);return new $0(U,J)}delete(Z){return L4(this.contents)?this.contents.delete(Z):!1}deleteIn(Z){if(U4(Z)){if(this.contents==null)return!1;return this.contents=null,!0}return L4(this.contents)?this.contents.deleteIn(Z):!1}get(Z,X){return r(this.contents)?this.contents.get(Z,X):void 0}getIn(Z,X){if(U4(Z))return!X&&v(this.contents)?this.contents.value:this.contents;return r(this.contents)?this.contents.getIn(Z,X):void 0}has(Z){return r(this.contents)?this.contents.has(Z):!1}hasIn(Z){if(U4(Z))return this.contents!==void 0;return r(this.contents)?this.contents.hasIn(Z):!1}set(Z,X){if(this.contents==null)this.contents=_6(this.schema,[Z],X);else if(L4(this.contents))this.contents.set(Z,X)}setIn(Z,X){if(U4(Z))this.contents=X;else if(this.contents==null)this.contents=_6(this.schema,Array.from(Z),X);else if(L4(this.contents))this.contents.setIn(Z,X)}setSchema(Z,X={}){if(typeof Z==="number")Z=String(Z);let Q;switch(Z){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new M0({version:"1.1"});Q={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=Z;else this.directives=new M0({version:Z});Q={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;Q=null;break;default:{let U=JSON.stringify(Z);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${U}`)}}if(X.schema instanceof Object)this.schema=X.schema;else if(Q)this.schema=new _4(Object.assign(Q,X));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:Z,jsonArg:X,mapAsMap:Q,maxAliasCount:U,onAnchor:J,reviver:$}={}){let W={anchors:new Map,doc:this,keep:!Z,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof U==="number"?U:100},Y=F0(this.contents,X??"",W);if(typeof J==="function")for(let{count:G,res:_}of W.anchors.values())J(_,G);return typeof $==="function"?W2($,{"":Y},"",Y):Y}toJSON(Z,X){return this.toJS({json:!0,jsonArg:Z,mapAsMap:!1,onAnchor:X})}toString(Z={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in Z&&(!Number.isInteger(Z.indent)||Number(Z.indent)<=0)){let X=JSON.stringify(Z.indent);throw Error(`"indent" option must be a positive integer, not ${X}`)}return VJ(this,Z)}}function L4(Z){if(r(Z))return!0;throw Error("Expected a YAML collection as document contents")}class O6 extends Error{constructor(Z,X,Q,U){super();this.name=Z,this.code=Q,this.message=U,this.pos=X}}class U1 extends O6{constructor(Z,X,Q){super("YAMLParseError",Z,X,Q)}}class K6 extends O6{constructor(Z,X,Q){super("YAMLWarning",Z,X,Q)}}var T6=(Z,X)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((Y)=>X.linePos(Y));let{line:U,col:J}=Q.linePos[0];Q.message+=` at line ${U}, column ${J}`;let $=J-1,W=Z.substring(X.lineStarts[U-1],X.lineStarts[U]).replace(/[\n\r]+$/,"");if($>=60&&W.length>80){let Y=Math.min($-39,W.length-79);W="…"+W.substring(Y),$-=Y-1}if(W.length>80)W=W.substring(0,79)+"…";if(U>1&&/^ *$/.test(W.substring(0,$))){let Y=Z.substring(X.lineStarts[U-2],X.lineStarts[U-1]);if(Y.length>80)Y=Y.substring(0,79)+`…
103
+ `;W=Y+W}if(/[^ ]/.test(W)){let Y=1,G=Q.linePos[1];if(G?.line===U&&G.col>J)Y=Math.max(1,Math.min(G.col-J,80-$));let _=" ".repeat($)+"^".repeat(Y);Q.message+=`:
104
+
105
+ ${W}
106
+ ${_}
107
+ `}};function C1(Z,{flow:X,indicator:Q,next:U,offset:J,onError:$,parentIndent:W,startOnNewline:Y}){let G=!1,_=Y,L=Y,V="",q="",H=!1,F=!1,z=null,B=null,T=null,D=null,K=null,P=null,S=null;for(let C of Z){if(F){if(C.type!=="space"&&C.type!=="newline"&&C.type!=="comma")$(C.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");F=!1}if(z){if(_&&C.type!=="comment"&&C.type!=="newline")$(z,"TAB_AS_INDENT","Tabs are not allowed as indentation");z=null}switch(C.type){case"space":if(!X&&(Q!=="doc-start"||U?.type!=="flow-collection")&&C.source.includes("\t"))z=C;L=!0;break;case"comment":{if(!L)$(C,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=C.source.substring(1)||" ";if(!V)V=h;else V+=q+h;q="",_=!1;break}case"newline":if(_){if(V)V+=C.source;else if(!P||Q!=="seq-item-ind")G=!0}else q+=C.source;if(_=!0,H=!0,B||T)D=C;L=!0;break;case"anchor":if(B)$(C,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(C.source.endsWith(":"))$(C.offset+C.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);B=C,S??(S=C.offset),_=!1,L=!1,F=!0;break;case"tag":{if(T)$(C,"MULTIPLE_TAGS","A node can have at most one tag");T=C,S??(S=C.offset),_=!1,L=!1,F=!0;break}case Q:if(B||T)$(C,"BAD_PROP_ORDER",`Anchors and tags must be after the ${C.source} indicator`);if(P)$(C,"UNEXPECTED_TOKEN",`Unexpected ${C.source} in ${X??"collection"}`);P=C,_=Q==="seq-item-ind"||Q==="explicit-key-ind",L=!1;break;case"comma":if(X){if(K)$(C,"UNEXPECTED_TOKEN",`Unexpected , in ${X}`);K=C,_=!1,L=!1;break}default:$(C,"UNEXPECTED_TOKEN",`Unexpected ${C.type} token`),_=!1,L=!1}}let N=Z[Z.length-1],x=N?N.offset+N.source.length:J;if(F&&U&&U.type!=="space"&&U.type!=="newline"&&U.type!=="comma"&&(U.type!=="scalar"||U.source!==""))$(U.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(z&&(_&&z.indent<=W||U?.type==="block-map"||U?.type==="block-seq"))$(z,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:K,found:P,spaceBefore:G,comment:V,hasNewline:H,anchor:B,tag:T,newlineAfterProp:D,end:x,start:S??x}}function _2(Z){if(!Z)return null;switch(Z.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(Z.source.includes(`
108
+ `))return!0;if(Z.end){for(let X of Z.end)if(X.type==="newline")return!0}return!1;case"flow-collection":for(let X of Z.items){for(let Q of X.start)if(Q.type==="newline")return!0;if(X.sep){for(let Q of X.sep)if(Q.type==="newline")return!0}if(_2(X.key)||_2(X.value))return!0}return!1;default:return!0}}function D6(Z,X,Q){if(X?.type==="flow-collection"){let U=X.end[0];if(U.indent===Z&&(U.source==="]"||U.source==="}")&&_2(X))Q(U,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function W8(Z,X,Q){let{uniqueKeys:U}=Z.options;if(U===!1)return!1;let J=typeof U==="function"?U:($,W)=>$===W||v($)&&v(W)&&$.value===W.value;return X.some(($)=>J($.key,Q))}var qJ="All mapping items must start at the same column";function HJ({composeNode:Z,composeEmptyNode:X},Q,U,J,$){let Y=new($?.nodeClass??G0)(Q.schema);if(Q.atRoot)Q.atRoot=!1;let G=U.offset,_=null;for(let L of U.items){let{start:V,key:q,sep:H,value:F}=L,z=C1(V,{indicator:"explicit-key-ind",next:q??H?.[0],offset:G,onError:J,parentIndent:U.indent,startOnNewline:!0}),B=!z.found;if(B){if(q){if(q.type==="block-seq")J(G,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in q&&q.indent!==U.indent)J(G,"BAD_INDENT",qJ)}if(!z.anchor&&!z.tag&&!H){if(_=z.end,z.comment)if(Y.comment)Y.comment+=`
109
+ `+z.comment;else Y.comment=z.comment;continue}if(z.newlineAfterProp||_2(q))J(q??V[V.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(z.found?.indent!==U.indent)J(G,"BAD_INDENT",qJ);Q.atKey=!0;let T=z.end,D=q?Z(Q,q,z,J):X(Q,T,V,null,z,J);if(Q.schema.compat)D6(U.indent,q,J);if(Q.atKey=!1,W8(Q,Y.items,D))J(T,"DUPLICATE_KEY","Map keys must be unique");let K=C1(H??[],{indicator:"map-value-ind",next:F,offset:D.range[2],onError:J,parentIndent:U.indent,startOnNewline:!q||q.type==="block-scalar"});if(G=K.end,K.found){if(B){if(F?.type==="block-map"&&!K.hasNewline)J(G,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&z.start<K.found.offset-1024)J(D.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let P=F?Z(Q,F,K,J):X(Q,G,H,null,K,J);if(Q.schema.compat)D6(U.indent,F,J);G=P.range[2];let S=new $0(D,P);if(Q.options.keepSourceTokens)S.srcToken=L;Y.items.push(S)}else{if(B)J(D.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(K.comment)if(D.comment)D.comment+=`
110
+ `+K.comment;else D.comment=K.comment;let P=new $0(D);if(Q.options.keepSourceTokens)P.srcToken=L;Y.items.push(P)}}if(_&&_<G)J(_,"IMPOSSIBLE","Map comment with trailing content");return Y.range=[U.offset,G,_??G],Y}function zJ({composeNode:Z,composeEmptyNode:X},Q,U,J,$){let Y=new($?.nodeClass??D0)(Q.schema);if(Q.atRoot)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let G=U.offset,_=null;for(let{start:L,value:V}of U.items){let q=C1(L,{indicator:"seq-item-ind",next:V,offset:G,onError:J,parentIndent:U.indent,startOnNewline:!0});if(!q.found)if(q.anchor||q.tag||V)if(V?.type==="block-seq")J(q.end,"BAD_INDENT","All sequence items must start at the same column");else J(G,"MISSING_CHAR","Sequence item without - indicator");else{if(_=q.end,q.comment)Y.comment=q.comment;continue}let H=V?Z(Q,V,q,J):X(Q,q.end,L,null,q,J);if(Q.schema.compat)D6(U.indent,V,J);G=H.range[2],Y.items.push(H)}return Y.range=[U.offset,G,_??G],Y}function N1(Z,X,Q,U){let J="";if(Z){let $=!1,W="";for(let Y of Z){let{source:G,type:_}=Y;switch(_){case"space":$=!0;break;case"comment":{if(Q&&!$)U(Y,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=G.substring(1)||" ";if(!J)J=L;else J+=W+L;W="";break}case"newline":if(J)W+=G;$=!0;break;default:U(Y,"UNEXPECTED_TOKEN",`Unexpected ${_} at node end`)}X+=G.length}}return{comment:J,offset:X}}var eX="Block collections are not allowed within flow collections",Z7=(Z)=>Z&&(Z.type==="block-map"||Z.type==="block-seq");function FJ({composeNode:Z,composeEmptyNode:X},Q,U,J,$){let W=U.start.source==="{",Y=W?"flow map":"flow sequence",_=new($?.nodeClass??(W?G0:D0))(Q.schema);_.flow=!0;let L=Q.atRoot;if(L)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let V=U.offset+U.start.source.length;for(let B=0;B<U.items.length;++B){let T=U.items[B],{start:D,key:K,sep:P,value:S}=T,N=C1(D,{flow:Y,indicator:"explicit-key-ind",next:K??P?.[0],offset:V,onError:J,parentIndent:U.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!P&&!S){if(B===0&&N.comma)J(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Y}`);else if(B<U.items.length-1)J(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${Y}`);if(N.comment)if(_.comment)_.comment+=`
111
+ `+N.comment;else _.comment=N.comment;V=N.end;continue}if(!W&&Q.options.strict&&_2(K))J(K,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(B===0){if(N.comma)J(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Y}`)}else{if(!N.comma)J(N.start,"MISSING_CHAR",`Missing , between ${Y} items`);if(N.comment){let x="";Z:for(let C of D)switch(C.type){case"comma":case"space":break;case"comment":x=C.source.substring(1);break Z;default:break Z}if(x){let C=_.items[_.items.length-1];if(p(C))C=C.value??C.key;if(C.comment)C.comment+=`
112
+ `+x;else C.comment=x;N.comment=N.comment.substring(x.length+1)}}}if(!W&&!P&&!N.found){let x=S?Z(Q,S,N,J):X(Q,N.end,P,null,N,J);if(_.items.push(x),V=x.range[2],Z7(S))J(x.range,"BLOCK_IN_FLOW",eX)}else{Q.atKey=!0;let x=N.end,C=K?Z(Q,K,N,J):X(Q,x,D,null,N,J);if(Z7(K))J(C.range,"BLOCK_IN_FLOW",eX);Q.atKey=!1;let h=C1(P??[],{flow:Y,indicator:"map-value-ind",next:S,offset:C.range[2],onError:J,parentIndent:U.indent,startOnNewline:!1});if(h.found){if(!W&&!N.found&&Q.options.strict){if(P)for(let n of P){if(n===h.found)break;if(n.type==="newline"){J(n,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(N.start<h.found.offset-1024)J(h.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(S)if("source"in S&&S.source?.[0]===":")J(S,"MISSING_CHAR",`Missing space after : in ${Y}`);else J(h.start,"MISSING_CHAR",`Missing , or : between ${Y} items`);let a=S?Z(Q,S,h,J):h.found?X(Q,h.end,P,null,h,J):null;if(a){if(Z7(S))J(a.range,"BLOCK_IN_FLOW",eX)}else if(h.comment)if(C.comment)C.comment+=`
113
+ `+h.comment;else C.comment=h.comment;let W0=new $0(C,a);if(Q.options.keepSourceTokens)W0.srcToken=T;if(W){let n=_;if(W8(Q,n.items,C))J(x,"DUPLICATE_KEY","Map keys must be unique");n.items.push(W0)}else{let n=new G0(Q.schema);n.flow=!0,n.items.push(W0);let B0=(a??C).range;n.range=[C.range[0],B0[1],B0[2]],_.items.push(n)}V=a?a.range[2]:h.end}}let q=W?"}":"]",[H,...F]=U.end,z=V;if(H?.source===q)z=H.offset+H.source.length;else{let B=Y[0].toUpperCase()+Y.substring(1),T=L?`${B} must end with a ${q}`:`${B} in block collection must be sufficiently indented and end with a ${q}`;if(J(V,L?"MISSING_CHAR":"BAD_INDENT",T),H&&H.source.length!==1)F.unshift(H)}if(F.length>0){let B=N1(F,z,Q.options.strict,J);if(B.comment)if(_.comment)_.comment+=`
114
+ `+B.comment;else _.comment=B.comment;_.range=[U.offset,z,B.offset]}else _.range=[U.offset,z,z];return _}function X7(Z,X,Q,U,J,$){let W=Q.type==="block-map"?HJ(Z,X,Q,U,$):Q.type==="block-seq"?zJ(Z,X,Q,U,$):FJ(Z,X,Q,U,$),Y=W.constructor;if(J==="!"||J===Y.tagName)return W.tag=Y.tagName,W;if(J)W.tag=J;return W}function BJ(Z,X,Q,U,J){let $=U.tag,W=!$?null:X.directives.tagName($.source,(q)=>J($,"TAG_RESOLVE_FAILED",q));if(Q.type==="block-seq"){let{anchor:q,newlineAfterProp:H}=U,F=q&&$?q.offset>$.offset?q:$:q??$;if(F&&(!H||H.offset<F.offset))J(F,"MISSING_CHAR","Missing newline after block sequence props")}let Y=Q.type==="block-map"?"map":Q.type==="block-seq"?"seq":Q.start.source==="{"?"map":"seq";if(!$||!W||W==="!"||W===G0.tagName&&Y==="map"||W===D0.tagName&&Y==="seq")return X7(Z,X,Q,J,W);let G=X.schema.tags.find((q)=>q.tag===W&&q.collection===Y);if(!G){let q=X.schema.knownTags[W];if(q?.collection===Y)X.schema.tags.push(Object.assign({},q,{default:!1})),G=q;else{if(q)J($,"BAD_COLLECTION_TYPE",`${q.tag} used for ${Y} collection, but expects ${q.collection??"scalar"}`,!0);else J($,"TAG_RESOLVE_FAILED",`Unresolved tag: ${W}`,!0);return X7(Z,X,Q,J,W)}}let _=X7(Z,X,Q,J,W,G),L=G.resolve?.(_,(q)=>J($,"TAG_RESOLVE_FAILED",q),X.options)??_,V=l(L)?L:new b(L);if(V.range=_.range,V.tag=W,G?.format)V.format=G.format;return V}function Y8(Z,X,Q){let U=X.offset,J=u_(X,Z.options.strict,Q);if(!J)return{value:"",type:null,comment:"",range:[U,U,U]};let $=J.mode===">"?b.BLOCK_FOLDED:b.BLOCK_LITERAL,W=X.source?p_(X.source):[],Y=W.length;for(let z=W.length-1;z>=0;--z){let B=W[z][1];if(B===""||B==="\r")Y=z;else break}if(Y===0){let z=J.chomp==="+"&&W.length>0?`
115
+ `.repeat(Math.max(1,W.length-1)):"",B=U+J.length;if(X.source)B+=X.source.length;return{value:z,type:$,comment:J.comment,range:[U,B,B]}}let G=X.indent+J.indent,_=X.offset+J.length,L=0;for(let z=0;z<Y;++z){let[B,T]=W[z];if(T===""||T==="\r"){if(J.indent===0&&B.length>G)G=B.length}else{if(B.length<G)Q(_+B.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(J.indent===0)G=B.length;if(L=z,G===0&&!Z.atRoot)Q(_,"BAD_INDENT","Block scalar values in collections must be indented");break}_+=B.length+T.length+1}for(let z=W.length-1;z>=Y;--z)if(W[z][0].length>G)Y=z+1;let V="",q="",H=!1;for(let z=0;z<L;++z)V+=W[z][0].slice(G)+`
116
+ `;for(let z=L;z<Y;++z){let[B,T]=W[z];_+=B.length+T.length+1;let D=T[T.length-1]==="\r";if(D)T=T.slice(0,-1);if(T&&B.length<G){let P=`Block scalar lines must not be less indented than their ${J.indent?"explicit indentation indicator":"first line"}`;Q(_-T.length-(D?2:1),"BAD_INDENT",P),B=""}if($===b.BLOCK_LITERAL)V+=q+B.slice(G)+T,q=`
117
+ `;else if(B.length>G||T[0]==="\t"){if(q===" ")q=`
118
+ `;else if(!H&&q===`
119
+ `)q=`
120
+
121
+ `;V+=q+B.slice(G)+T,q=`
122
+ `,H=!0}else if(T==="")if(q===`
123
+ `)V+=`
124
+ `;else q=`
125
+ `;else V+=q+T,q=" ",H=!1}switch(J.chomp){case"-":break;case"+":for(let z=Y;z<W.length;++z)V+=`
126
+ `+W[z][0].slice(G);if(V[V.length-1]!==`
127
+ `)V+=`
128
+ `;break;default:V+=`
129
+ `}let F=U+J.length+X.source.length;return{value:V,type:$,comment:J.comment,range:[U,F,F]}}function u_({offset:Z,props:X},Q,U){if(X[0].type!=="block-scalar-header")return U(X[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:J}=X[0],$=J[0],W=0,Y="",G=-1;for(let q=1;q<J.length;++q){let H=J[q];if(!Y&&(H==="-"||H==="+"))Y=H;else{let F=Number(H);if(!W&&F)W=F;else if(G===-1)G=Z+q}}if(G!==-1)U(G,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${J}`);let _=!1,L="",V=J.length;for(let q=1;q<X.length;++q){let H=X[q];switch(H.type){case"space":_=!0;case"newline":V+=H.source.length;break;case"comment":if(Q&&!_)U(H,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");V+=H.source.length,L=H.source.substring(1);break;case"error":U(H,"UNEXPECTED_TOKEN",H.message),V+=H.source.length;break;default:{let F=`Unexpected token in block scalar header: ${H.type}`;U(H,"UNEXPECTED_TOKEN",F);let z=H.source;if(z&&typeof z==="string")V+=z.length}}}return{mode:$,indent:W,chomp:Y,comment:L,length:V}}function p_(Z){let X=Z.split(/\n( *)/),Q=X[0],U=Q.match(/^( *)/),$=[U?.[1]?[U[1],Q.slice(U[1].length)]:["",Q]];for(let W=1;W<X.length;W+=2)$.push([X[W],X[W+1]]);return $}function G8(Z,X,Q){let{offset:U,type:J,source:$,end:W}=Z,Y,G,_=(q,H,F)=>Q(U+q,H,F);switch(J){case"scalar":Y=b.PLAIN,G=l_($,_);break;case"single-quoted-scalar":Y=b.QUOTE_SINGLE,G=d_($,_);break;case"double-quoted-scalar":Y=b.QUOTE_DOUBLE,G=c_($,_);break;default:return Q(Z,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${J}`),{value:"",type:null,comment:"",range:[U,U+$.length,U+$.length]}}let L=U+$.length,V=N1(W,L,X,Q);return{value:G,type:Y,comment:V.comment,range:[U,L,V.offset]}}function l_(Z,X){let Q="";switch(Z[0]){case"\t":Q="a tab character";break;case",":Q="flow indicator character ,";break;case"%":Q="directive indicator character %";break;case"|":case">":{Q=`block scalar indicator ${Z[0]}`;break}case"@":case"`":{Q=`reserved character ${Z[0]}`;break}}if(Q)X(0,"BAD_SCALAR_START",`Plain value cannot start with ${Q}`);return MJ(Z)}function d_(Z,X){if(Z[Z.length-1]!=="'"||Z.length===1)X(Z.length,"MISSING_CHAR","Missing closing 'quote");return MJ(Z.slice(1,-1)).replace(/''/g,"'")}function MJ(Z){let X,Q;try{X=new RegExp(`(.*?)(?<![ ])[ ]*\r?
130
+ `,"sy"),Q=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
131
+ `,"sy")}catch{X=/(.*?)[ \t]*\r?\n/sy,Q=/[ \t]*(.*?)[ \t]*\r?\n/sy}let U=X.exec(Z);if(!U)return Z;let J=U[1],$=" ",W=X.lastIndex;Q.lastIndex=W;while(U=Q.exec(Z)){if(U[1]==="")if($===`
132
+ `)J+=$;else $=`
133
+ `;else J+=$+U[1],$=" ";W=Q.lastIndex}let Y=/[ \t]*(.*)/sy;return Y.lastIndex=W,U=Y.exec(Z),J+$+(U?.[1]??"")}function c_(Z,X){let Q="";for(let U=1;U<Z.length-1;++U){let J=Z[U];if(J==="\r"&&Z[U+1]===`
134
+ `)continue;if(J===`
135
+ `){let{fold:$,offset:W}=i_(Z,U);Q+=$,U=W}else if(J==="\\"){let $=Z[++U],W=s_[$];if(W)Q+=W;else if($===`
136
+ `){$=Z[U+1];while($===" "||$==="\t")$=Z[++U+1]}else if($==="\r"&&Z[U+1]===`
137
+ `){$=Z[++U+1];while($===" "||$==="\t")$=Z[++U+1]}else if($==="x"||$==="u"||$==="U"){let Y={x:2,u:4,U:8}[$];Q+=r_(Z,U+1,Y,X),U+=Y}else{let Y=Z.substr(U-1,2);X(U-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Y}`),Q+=Y}}else if(J===" "||J==="\t"){let $=U,W=Z[U+1];while(W===" "||W==="\t")W=Z[++U+1];if(W!==`
138
+ `&&!(W==="\r"&&Z[U+2]===`
139
+ `))Q+=U>$?Z.slice($,U+1):J}else Q+=J}if(Z[Z.length-1]!=='"'||Z.length===1)X(Z.length,"MISSING_CHAR",'Missing closing "quote');return Q}function i_(Z,X){let Q="",U=Z[X+1];while(U===" "||U==="\t"||U===`
140
+ `||U==="\r"){if(U==="\r"&&Z[X+2]!==`
141
+ `)break;if(U===`
142
+ `)Q+=`
143
+ `;X+=1,U=Z[X+1]}if(!Q)Q=" ";return{fold:Q,offset:X}}var s_={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
144
+ `,r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function r_(Z,X,Q,U){let J=Z.substr(X,Q),W=J.length===Q&&/^[0-9a-fA-F]+$/.test(J)?parseInt(J,16):NaN;if(isNaN(W)){let Y=Z.substr(X-2,Q+2);return U(X-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Y}`),Y}return String.fromCodePoint(W)}function Q7(Z,X,Q,U){let{value:J,type:$,comment:W,range:Y}=X.type==="block-scalar"?Y8(Z,X,U):G8(X,Z.options.strict,U),G=Q?Z.directives.tagName(Q.source,(V)=>U(Q,"TAG_RESOLVE_FAILED",V)):null,_;if(Z.options.stringKeys&&Z.atKey)_=Z.schema[p0];else if(G)_=o_(Z.schema,J,G,Q,U);else if(X.type==="scalar")_=a_(Z,J,X,U);else _=Z.schema[p0];let L;try{let V=_.resolve(J,(q)=>U(Q??X,"TAG_RESOLVE_FAILED",q),Z.options);L=v(V)?V:new b(V)}catch(V){let q=V instanceof Error?V.message:String(V);U(Q??X,"TAG_RESOLVE_FAILED",q),L=new b(J)}if(L.range=Y,L.source=J,$)L.type=$;if(G)L.tag=G;if(_.format)L.format=_.format;if(W)L.comment=W;return L}function o_(Z,X,Q,U,J){if(Q==="!")return Z[p0];let $=[];for(let Y of Z.tags)if(!Y.collection&&Y.tag===Q)if(Y.default&&Y.test)$.push(Y);else return Y;for(let Y of $)if(Y.test?.test(X))return Y;let W=Z.knownTags[Q];if(W&&!W.collection)return Z.tags.push(Object.assign({},W,{default:!1,test:void 0})),W;return J(U,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),Z[p0]}function a_({atKey:Z,directives:X,schema:Q},U,J,$){let W=Q.tags.find((Y)=>(Y.default===!0||Z&&Y.default==="key")&&Y.test?.test(U))||Q[p0];if(Q.compat){let Y=Q.compat.find((G)=>G.default&&G.test?.test(U))??Q[p0];if(W.tag!==Y.tag){let G=X.tagString(W.tag),_=X.tagString(Y.tag),L=`Value may be parsed as either ${G} or ${_}`;$(J,"TAG_RESOLVE_FAILED",L,!0)}}return W}function RJ(Z,X,Q){if(X){Q??(Q=X.length);for(let U=Q-1;U>=0;--U){let J=X[U];switch(J.type){case"space":case"comment":case"newline":Z-=J.source.length;continue}J=X[++U];while(J?.type==="space")Z+=J.source.length,J=X[++U];break}}return Z}var n_={composeNode:U7,composeEmptyNode:_8};function U7(Z,X,Q,U){let J=Z.atKey,{spaceBefore:$,comment:W,anchor:Y,tag:G}=Q,_,L=!0;switch(X.type){case"alias":if(_=t_(Z,X,U),Y||G)U(X,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(_=Q7(Z,X,G,U),Y)_.anchor=Y.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":if(_=BJ(n_,Z,X,Q,U),Y)_.anchor=Y.source.substring(1);break;default:{let V=X.type==="error"?X.message:`Unsupported token (type: ${X.type})`;U(X,"UNEXPECTED_TOKEN",V),_=_8(Z,X.offset,void 0,null,Q,U),L=!1}}if(Y&&_.anchor==="")U(Y,"BAD_ALIAS","Anchor cannot be an empty string");if(J&&Z.options.stringKeys&&(!v(_)||typeof _.value!=="string"||_.tag&&_.tag!=="tag:yaml.org,2002:str"))U(G??X,"NON_STRING_KEY","With stringKeys, all keys must be strings");if($)_.spaceBefore=!0;if(W)if(X.type==="scalar"&&X.source==="")_.comment=W;else _.commentBefore=W;if(Z.options.keepSourceTokens&&L)_.srcToken=X;return _}function _8(Z,X,Q,U,{spaceBefore:J,comment:$,anchor:W,tag:Y,end:G},_){let L={type:"scalar",offset:RJ(X,Q,U),indent:-1,source:""},V=Q7(Z,L,Y,_);if(W){if(V.anchor=W.source.substring(1),V.anchor==="")_(W,"BAD_ALIAS","Anchor cannot be an empty string")}if(J)V.spaceBefore=!0;if($)V.comment=$,V.range[2]=G;return V}function t_({options:Z},{offset:X,source:Q,end:U},J){let $=new p1(Q.substring(1));if($.source==="")J(X,"BAD_ALIAS","Alias cannot be an empty string");if($.source.endsWith(":"))J(X+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let W=X+Q.length,Y=N1(U,W,Z.strict,J);if($.range=[X,W,Y.offset],Y.comment)$.comment=Y.comment;return $}function OJ(Z,X,{offset:Q,start:U,value:J,end:$},W){let Y=Object.assign({_directives:X},Z),G=new S1(void 0,Y),_={atKey:!1,atRoot:!0,directives:G.directives,options:G.options,schema:G.schema},L=C1(U,{indicator:"doc-start",next:J??$?.[0],offset:Q,onError:W,parentIndent:0,startOnNewline:!0});if(L.found){if(G.directives.docStart=!0,J&&(J.type==="block-map"||J.type==="block-seq")&&!L.hasNewline)W(L.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}G.contents=J?U7(_,J,L,W):_8(_,L.end,U,null,L,W);let V=G.contents.range[2],q=N1($,V,!1,W);if(q.comment)G.comment=q.comment;return G.range=[Q,V,q.offset],G}function P6(Z){if(typeof Z==="number")return[Z,Z+1];if(Array.isArray(Z))return Z.length===2?Z:[Z[0],Z[1]];let{offset:X,source:Q}=Z;return[X,X+(typeof Q==="string"?Q.length:1)]}function KJ(Z){let X="",Q=!1,U=!1;for(let J=0;J<Z.length;++J){let $=Z[J];switch($[0]){case"#":X+=(X===""?"":U?`
145
+
146
+ `:`
147
+ `)+($.substring(1)||" "),Q=!0,U=!1;break;case"%":if(Z[J+1]?.[0]!=="#")J+=1;Q=!1;break;default:if(!Q)U=!0;Q=!1}}return{comment:X,afterEmptyLine:U}}class V4{constructor(Z={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(X,Q,U,J)=>{let $=P6(X);if(J)this.warnings.push(new K6($,Q,U));else this.errors.push(new U1($,Q,U))},this.directives=new M0({version:Z.version||"1.2"}),this.options=Z}decorate(Z,X){let{comment:Q,afterEmptyLine:U}=KJ(this.prelude);if(Q){let J=Z.contents;if(X)Z.comment=Z.comment?`${Z.comment}
148
+ ${Q}`:Q;else if(U||Z.directives.docStart||!J)Z.commentBefore=Q;else if(r(J)&&!J.flow&&J.items.length>0){let $=J.items[0];if(p($))$=$.key;let W=$.commentBefore;$.commentBefore=W?`${Q}
149
+ ${W}`:Q}else{let $=J.commentBefore;J.commentBefore=$?`${Q}
150
+ ${$}`:Q}}if(X)Array.prototype.push.apply(Z.errors,this.errors),Array.prototype.push.apply(Z.warnings,this.warnings);else Z.errors=this.errors,Z.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:KJ(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(Z,X=!1,Q=-1){for(let U of Z)yield*this.next(U);yield*this.end(X,Q)}*next(Z){switch(Z.type){case"directive":this.directives.add(Z.source,(X,Q,U)=>{let J=P6(Z);J[0]+=X,this.onError(J,"BAD_DIRECTIVE",Q,U)}),this.prelude.push(Z.source),this.atDirectives=!0;break;case"document":{let X=OJ(this.options,this.directives,Z,this.onError);if(this.atDirectives&&!X.directives.docStart)this.onError(Z,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(X,!1),this.doc)yield this.doc;this.doc=X,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(Z.source);break;case"error":{let X=Z.source?`${Z.message}: ${JSON.stringify(Z.source)}`:Z.message,Q=new U1(P6(Z),"UNEXPECTED_TOKEN",X);if(this.atDirectives||!this.doc)this.errors.push(Q);else this.doc.errors.push(Q);break}case"doc-end":{if(!this.doc){this.errors.push(new U1(P6(Z),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let X=N1(Z.end,Z.offset+Z.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),X.comment){let Q=this.doc.comment;this.doc.comment=Q?`${Q}
151
+ ${X.comment}`:X.comment}this.doc.range[2]=X.offset;break}default:this.errors.push(new U1(P6(Z),"UNEXPECTED_TOKEN",`Unsupported token ${Z.type}`))}}*end(Z=!1,X=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(Z){let Q=Object.assign({_directives:this.directives},this.options),U=new S1(void 0,Q);if(this.atDirectives)this.onError(X,"MISSING_CHAR","Missing directives-end indicator line");U.range=[0,X,X],this.decorate(U,!1),yield U}}}var Y7={};f6(Y7,{visit:()=>L2,tokenType:()=>W7,stringify:()=>AJ,setScalarValue:()=>PJ,resolveAsScalar:()=>TJ,prettyToken:()=>UL,isScalar:()=>QL,isCollection:()=>XL,createScalarToken:()=>DJ,SCALAR:()=>q4,FLOW_END:()=>S6,DOCUMENT:()=>A6,BOM:()=>w6});function TJ(Z,X=!0,Q){if(Z){let U=(J,$,W)=>{let Y=typeof J==="number"?J:Array.isArray(J)?J[0]:J.offset;if(Q)Q(Y,$,W);else throw new U1([Y,Y+1],$,W)};switch(Z.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return G8(Z,X,U);case"block-scalar":return Y8({options:{strict:X}},Z,U)}}return null}function DJ(Z,X){let{implicitKey:Q=!1,indent:U,inFlow:J=!1,offset:$=-1,type:W="PLAIN"}=X,Y=d1({type:W,value:Z},{implicitKey:Q,indent:U>0?" ".repeat(U):"",inFlow:J,options:{blockQuote:!0,lineWidth:-1}}),G=X.end??[{type:"newline",offset:-1,indent:U,source:`
152
+ `}];switch(Y[0]){case"|":case">":{let _=Y.indexOf(`
153
+ `),L=Y.substring(0,_),V=Y.substring(_+1)+`
154
+ `,q=[{type:"block-scalar-header",offset:$,indent:U,source:L}];if(!wJ(q,G))q.push({type:"newline",offset:-1,indent:U,source:`
155
+ `});return{type:"block-scalar",offset:$,indent:U,props:q,source:V}}case'"':return{type:"double-quoted-scalar",offset:$,indent:U,source:Y,end:G};case"'":return{type:"single-quoted-scalar",offset:$,indent:U,source:Y,end:G};default:return{type:"scalar",offset:$,indent:U,source:Y,end:G}}}function PJ(Z,X,Q={}){let{afterKey:U=!1,implicitKey:J=!1,inFlow:$=!1,type:W}=Q,Y="indent"in Z?Z.indent:null;if(U&&typeof Y==="number")Y+=2;if(!W)switch(Z.type){case"single-quoted-scalar":W="QUOTE_SINGLE";break;case"double-quoted-scalar":W="QUOTE_DOUBLE";break;case"block-scalar":{let _=Z.props[0];if(_.type!=="block-scalar-header")throw Error("Invalid block scalar header");W=_.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:W="PLAIN"}let G=d1({type:W,value:X},{implicitKey:J||Y===null,indent:Y!==null&&Y>0?" ".repeat(Y):"",inFlow:$,options:{blockQuote:!0,lineWidth:-1}});switch(G[0]){case"|":case">":e_(Z,G);break;case'"':J7(Z,G,"double-quoted-scalar");break;case"'":J7(Z,G,"single-quoted-scalar");break;default:J7(Z,G,"scalar")}}function e_(Z,X){let Q=X.indexOf(`
156
+ `),U=X.substring(0,Q),J=X.substring(Q+1)+`
157
+ `;if(Z.type==="block-scalar"){let $=Z.props[0];if($.type!=="block-scalar-header")throw Error("Invalid block scalar header");$.source=U,Z.source=J}else{let{offset:$}=Z,W="indent"in Z?Z.indent:-1,Y=[{type:"block-scalar-header",offset:$,indent:W,source:U}];if(!wJ(Y,"end"in Z?Z.end:void 0))Y.push({type:"newline",offset:-1,indent:W,source:`
158
+ `});for(let G of Object.keys(Z))if(G!=="type"&&G!=="offset")delete Z[G];Object.assign(Z,{type:"block-scalar",indent:W,props:Y,source:J})}}function wJ(Z,X){if(X)for(let Q of X)switch(Q.type){case"space":case"comment":Z.push(Q);break;case"newline":return Z.push(Q),!0}return!1}function J7(Z,X,Q){switch(Z.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":Z.type=Q,Z.source=X;break;case"block-scalar":{let U=Z.props.slice(1),J=X.length;if(Z.props[0].type==="block-scalar-header")J-=Z.props[0].source.length;for(let $ of U)$.offset+=J;delete Z.props,Object.assign(Z,{type:Q,source:X,end:U});break}case"block-map":case"block-seq":{let J={type:"newline",offset:Z.offset+X.length,indent:Z.indent,source:`
159
+ `};delete Z.items,Object.assign(Z,{type:Q,source:X,end:[J]});break}default:{let U="indent"in Z?Z.indent:-1,J="end"in Z&&Array.isArray(Z.end)?Z.end.filter(($)=>$.type==="space"||$.type==="comment"||$.type==="newline"):[];for(let $ of Object.keys(Z))if($!=="type"&&$!=="offset")delete Z[$];Object.assign(Z,{type:Q,indent:U,source:X,end:J})}}}var AJ=(Z)=>("type"in Z)?V8(Z):L8(Z);function V8(Z){switch(Z.type){case"block-scalar":{let X="";for(let Q of Z.props)X+=V8(Q);return X+Z.source}case"block-map":case"block-seq":{let X="";for(let Q of Z.items)X+=L8(Q);return X}case"flow-collection":{let X=Z.start.source;for(let Q of Z.items)X+=L8(Q);for(let Q of Z.end)X+=Q.source;return X}case"document":{let X=L8(Z);if(Z.end)for(let Q of Z.end)X+=Q.source;return X}default:{let X=Z.source;if("end"in Z&&Z.end)for(let Q of Z.end)X+=Q.source;return X}}}function L8({start:Z,key:X,sep:Q,value:U}){let J="";for(let $ of Z)J+=$.source;if(X)J+=V8(X);if(Q)for(let $ of Q)J+=$.source;if(U)J+=V8(U);return J}var $7=Symbol("break visit"),ZL=Symbol("skip children"),SJ=Symbol("remove item");function L2(Z,X){if("type"in Z&&Z.type==="document")Z={start:Z.start,value:Z.value};CJ(Object.freeze([]),Z,X)}L2.BREAK=$7;L2.SKIP=ZL;L2.REMOVE=SJ;L2.itemAtPath=(Z,X)=>{let Q=Z;for(let[U,J]of X){let $=Q?.[U];if($&&"items"in $)Q=$.items[J];else return}return Q};L2.parentCollection=(Z,X)=>{let Q=L2.itemAtPath(Z,X.slice(0,-1)),U=X[X.length-1][0],J=Q?.[U];if(J&&"items"in J)return J;throw Error("Parent collection not found")};function CJ(Z,X,Q){let U=Q(X,Z);if(typeof U==="symbol")return U;for(let J of["key","value"]){let $=X[J];if($&&"items"in $){for(let W=0;W<$.items.length;++W){let Y=CJ(Object.freeze(Z.concat([[J,W]])),$.items[W],Q);if(typeof Y==="number")W=Y-1;else if(Y===$7)return $7;else if(Y===SJ)$.items.splice(W,1),W-=1}if(typeof U==="function"&&J==="key")U=U(X,Z)}}return typeof U==="function"?U(X,Z):U}var w6="\uFEFF",A6="\x02",S6="\x18",q4="\x1F",XL=(Z)=>!!Z&&("items"in Z),QL=(Z)=>!!Z&&(Z.type==="scalar"||Z.type==="single-quoted-scalar"||Z.type==="double-quoted-scalar"||Z.type==="block-scalar");function UL(Z){switch(Z){case w6:return"<BOM>";case A6:return"<DOC>";case S6:return"<FLOW_END>";case q4:return"<SCALAR>";default:return JSON.stringify(Z)}}function W7(Z){switch(Z){case w6:return"byte-order-mark";case A6:return"doc-mode";case S6:return"flow-error-end";case q4:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
160
+ `:case`\r
161
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(Z[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function B1(Z){switch(Z){case void 0:case" ":case`
162
+ `:case"\r":case"\t":return!0;default:return!1}}var NJ=new Set("0123456789ABCDEFabcdef"),JL=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),q8=new Set(",[]{}"),$L=new Set(` ,[]{}
163
+ \r `),G7=(Z)=>!Z||$L.has(Z);class C6{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(Z,X=!1){if(Z){if(typeof Z!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+Z:Z,this.lineEndPos=null}this.atEnd=!X;let Q=this.next??"stream";while(Q&&(X||this.hasChars(1)))Q=yield*this.parseNext(Q)}atLineEnd(){let Z=this.pos,X=this.buffer[Z];while(X===" "||X==="\t")X=this.buffer[++Z];if(!X||X==="#"||X===`
164
+ `)return!0;if(X==="\r")return this.buffer[Z+1]===`
165
+ `;return!1}charAt(Z){return this.buffer[this.pos+Z]}continueScalar(Z){let X=this.buffer[Z];if(this.indentNext>0){let Q=0;while(X===" ")X=this.buffer[++Q+Z];if(X==="\r"){let U=this.buffer[Q+Z+1];if(U===`
166
+ `||!U&&!this.atEnd)return Z+Q+1}return X===`
167
+ `||Q>=this.indentNext||!X&&!this.atEnd?Z+Q:-1}if(X==="-"||X==="."){let Q=this.buffer.substr(Z,3);if((Q==="---"||Q==="...")&&B1(this.buffer[Z+3]))return-1}return Z}getLine(){let Z=this.lineEndPos;if(typeof Z!=="number"||Z!==-1&&Z<this.pos)Z=this.buffer.indexOf(`
168
+ `,this.pos),this.lineEndPos=Z;if(Z===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[Z-1]==="\r")Z-=1;return this.buffer.substring(this.pos,Z)}hasChars(Z){return this.pos+Z<=this.buffer.length}setNext(Z){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=Z,null}peek(Z){return this.buffer.substr(this.pos,Z)}*parseNext(Z){switch(Z){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let Z=this.getLine();if(Z===null)return this.setNext("stream");if(Z[0]===w6)yield*this.pushCount(1),Z=Z.substring(1);if(Z[0]==="%"){let X=Z.length,Q=Z.indexOf("#");while(Q!==-1){let J=Z[Q-1];if(J===" "||J==="\t"){X=Q-1;break}else Q=Z.indexOf("#",Q+1)}while(!0){let J=Z[X-1];if(J===" "||J==="\t")X-=1;else break}let U=(yield*this.pushCount(X))+(yield*this.pushSpaces(!0));return yield*this.pushCount(Z.length-U),this.pushNewline(),"stream"}if(this.atLineEnd()){let X=yield*this.pushSpaces(!0);return yield*this.pushCount(Z.length-X),yield*this.pushNewline(),"stream"}return yield A6,yield*this.parseLineStart()}*parseLineStart(){let Z=this.charAt(0);if(!Z&&!this.atEnd)return this.setNext("line-start");if(Z==="-"||Z==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let X=this.peek(3);if((X==="---"||X==="...")&&B1(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,X==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!B1(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[Z,X]=this.peek(2);if(!X&&!this.atEnd)return this.setNext("block-start");if((Z==="-"||Z==="?"||Z===":")&&B1(X)){let Q=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=Q,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let Z=this.getLine();if(Z===null)return this.setNext("doc");let X=yield*this.pushIndicators();switch(Z[X]){case"#":yield*this.pushCount(Z.length-X);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(G7),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return X+=yield*this.parseBlockScalarHeader(),X+=yield*this.pushSpaces(!0),yield*this.pushCount(Z.length-X),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let Z,X,Q=-1;do{if(Z=yield*this.pushNewline(),Z>0)X=yield*this.pushSpaces(!1),this.indentValue=Q=X;else X=0;X+=yield*this.pushSpaces(!0)}while(Z+X>0);let U=this.getLine();if(U===null)return this.setNext("flow");if(Q!==-1&&Q<this.indentNext&&U[0]!=="#"||Q===0&&(U.startsWith("---")||U.startsWith("..."))&&B1(U[3])){if(!(Q===this.indentNext-1&&this.flowLevel===1&&(U[0]==="]"||U[0]==="}")))return this.flowLevel=0,yield S6,yield*this.parseLineStart()}let J=0;while(U[J]===",")J+=yield*this.pushCount(1),J+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(J+=yield*this.pushIndicators(),U[J]){case void 0:return"flow";case"#":return yield*this.pushCount(U.length-J),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(G7),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let $=this.charAt(1);if(this.flowKey||B1($)||$===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let Z=this.charAt(0),X=this.buffer.indexOf(Z,this.pos+1);if(Z==="'")while(X!==-1&&this.buffer[X+1]==="'")X=this.buffer.indexOf("'",X+2);else while(X!==-1){let J=0;while(this.buffer[X-1-J]==="\\")J+=1;if(J%2===0)break;X=this.buffer.indexOf('"',X+1)}let Q=this.buffer.substring(0,X),U=Q.indexOf(`
169
+ `,this.pos);if(U!==-1){while(U!==-1){let J=this.continueScalar(U+1);if(J===-1)break;U=Q.indexOf(`
170
+ `,J)}if(U!==-1)X=U-(Q[U-1]==="\r"?2:1)}if(X===-1){if(!this.atEnd)return this.setNext("quoted-scalar");X=this.buffer.length}return yield*this.pushToIndex(X+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let Z=this.pos;while(!0){let X=this.buffer[++Z];if(X==="+")this.blockScalarKeep=!0;else if(X>"0"&&X<="9")this.blockScalarIndent=Number(X)-1;else if(X!=="-")break}return yield*this.pushUntil((X)=>B1(X)||X==="#")}*parseBlockScalar(){let Z=this.pos-1,X=0,Q;Z:for(let J=this.pos;Q=this.buffer[J];++J)switch(Q){case" ":X+=1;break;case`
171
+ `:Z=J,X=0;break;case"\r":{let $=this.buffer[J+1];if(!$&&!this.atEnd)return this.setNext("block-scalar");if($===`
172
+ `)break}default:break Z}if(!Q&&!this.atEnd)return this.setNext("block-scalar");if(X>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=X;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let J=this.continueScalar(Z+1);if(J===-1)break;Z=this.buffer.indexOf(`
173
+ `,J)}while(Z!==-1);if(Z===-1){if(!this.atEnd)return this.setNext("block-scalar");Z=this.buffer.length}}let U=Z+1;Q=this.buffer[U];while(Q===" ")Q=this.buffer[++U];if(Q==="\t"){while(Q==="\t"||Q===" "||Q==="\r"||Q===`
174
+ `)Q=this.buffer[++U];Z=U-1}else if(!this.blockScalarKeep)do{let J=Z-1,$=this.buffer[J];if($==="\r")$=this.buffer[--J];let W=J;while($===" ")$=this.buffer[--J];if($===`
175
+ `&&J>=this.pos&&J+1+X>W)Z=J;else break}while(!0);return yield q4,yield*this.pushToIndex(Z+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let Z=this.flowLevel>0,X=this.pos-1,Q=this.pos-1,U;while(U=this.buffer[++Q])if(U===":"){let J=this.buffer[Q+1];if(B1(J)||Z&&q8.has(J))break;X=Q}else if(B1(U)){let J=this.buffer[Q+1];if(U==="\r")if(J===`
176
+ `)Q+=1,U=`
177
+ `,J=this.buffer[Q+1];else X=Q;if(J==="#"||Z&&q8.has(J))break;if(U===`
178
+ `){let $=this.continueScalar(Q+1);if($===-1)break;Q=Math.max(Q,$-2)}}else{if(Z&&q8.has(U))break;X=Q}if(!U&&!this.atEnd)return this.setNext("plain-scalar");return yield q4,yield*this.pushToIndex(X+1,!0),Z?"flow":"doc"}*pushCount(Z){if(Z>0)return yield this.buffer.substr(this.pos,Z),this.pos+=Z,Z;return 0}*pushToIndex(Z,X){let Q=this.buffer.slice(this.pos,Z);if(Q)return yield Q,this.pos+=Q.length,Q.length;else if(X)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(G7))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let Z=this.flowLevel>0,X=this.charAt(1);if(B1(X)||Z&&q8.has(X)){if(!Z)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;return(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let Z=this.pos+2,X=this.buffer[Z];while(!B1(X)&&X!==">")X=this.buffer[++Z];return yield*this.pushToIndex(X===">"?Z+1:Z,!1)}else{let Z=this.pos+1,X=this.buffer[Z];while(X)if(JL.has(X))X=this.buffer[++Z];else if(X==="%"&&NJ.has(this.buffer[Z+1])&&NJ.has(this.buffer[Z+2]))X=this.buffer[Z+=3];else break;return yield*this.pushToIndex(Z,!1)}}*pushNewline(){let Z=this.buffer[this.pos];if(Z===`
179
+ `)return yield*this.pushCount(1);else if(Z==="\r"&&this.charAt(1)===`
180
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces(Z){let X=this.pos-1,Q;do Q=this.buffer[++X];while(Q===" "||Z&&Q==="\t");let U=X-this.pos;if(U>0)yield this.buffer.substr(this.pos,U),this.pos=X;return U}*pushUntil(Z){let X=this.pos,Q=this.buffer[X];while(!Z(Q))Q=this.buffer[++X];return yield*this.pushToIndex(X,!1)}}class N6{constructor(){this.lineStarts=[],this.addNewLine=(Z)=>this.lineStarts.push(Z),this.linePos=(Z)=>{let X=0,Q=this.lineStarts.length;while(X<Q){let J=X+Q>>1;if(this.lineStarts[J]<Z)X=J+1;else Q=J}if(this.lineStarts[X]===Z)return{line:X+1,col:1};if(X===0)return{line:0,col:Z};let U=this.lineStarts[X-1];return{line:X,col:Z-U+1}}}}function V2(Z,X){for(let Q=0;Q<Z.length;++Q)if(Z[Q].type===X)return!0;return!1}function jJ(Z){for(let X=0;X<Z.length;++X)switch(Z[X].type){case"space":case"comment":case"newline":break;default:return X}return-1}function bJ(Z){switch(Z?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function H8(Z){switch(Z.type){case"document":return Z.start;case"block-map":{let X=Z.items[Z.items.length-1];return X.sep??X.start}case"block-seq":return Z.items[Z.items.length-1].start;default:return[]}}function H4(Z){if(Z.length===0)return[];let X=Z.length;Z:while(--X>=0)switch(Z[X].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break Z}while(Z[++X]?.type==="space");return Z.splice(X,Z.length)}function EJ(Z){if(Z.start.type==="flow-seq-start"){for(let X of Z.items)if(X.sep&&!X.value&&!V2(X.start,"explicit-key-ind")&&!V2(X.sep,"map-value-ind")){if(X.key)X.value=X.key;if(delete X.key,bJ(X.value))if(X.value.end)Array.prototype.push.apply(X.value.end,X.sep);else X.value.end=X.sep;else Array.prototype.push.apply(X.start,X.sep);delete X.sep}}}class z4{constructor(Z){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new C6,this.onNewLine=Z}*parse(Z,X=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let Q of this.lexer.lex(Z,X))yield*this.next(Q);if(!X)yield*this.end()}*next(Z){if(this.source=Z,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=Z.length;return}let X=W7(Z);if(!X){let Q=`Not a YAML token: ${Z}`;yield*this.pop({type:"error",offset:this.offset,message:Q,source:Z}),this.offset+=Z.length}else if(X==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=X,yield*this.step(),X){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+Z.length);break;case"space":if(this.atNewLine&&Z[0]===" ")this.indent+=Z.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=Z.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=Z.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let Z=this.peek(1);if(this.type==="doc-end"&&Z?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!Z)return yield*this.stream();switch(Z.type){case"document":return yield*this.document(Z);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(Z);case"block-scalar":return yield*this.blockScalar(Z);case"block-map":return yield*this.blockMap(Z);case"block-seq":return yield*this.blockSequence(Z);case"flow-collection":return yield*this.flowCollection(Z);case"doc-end":return yield*this.documentEnd(Z)}yield*this.pop()}peek(Z){return this.stack[this.stack.length-Z]}*pop(Z){let X=Z??this.stack.pop();if(!X)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield X;else{let Q=this.peek(1);if(X.type==="block-scalar")X.indent="indent"in Q?Q.indent:0;else if(X.type==="flow-collection"&&Q.type==="document")X.indent=0;if(X.type==="flow-collection")EJ(X);switch(Q.type){case"document":Q.value=X;break;case"block-scalar":Q.props.push(X);break;case"block-map":{let U=Q.items[Q.items.length-1];if(U.value){Q.items.push({start:[],key:X,sep:[]}),this.onKeyLine=!0;return}else if(U.sep)U.value=X;else{Object.assign(U,{key:X,sep:[]}),this.onKeyLine=!U.explicitKey;return}break}case"block-seq":{let U=Q.items[Q.items.length-1];if(U.value)Q.items.push({start:[],value:X});else U.value=X;break}case"flow-collection":{let U=Q.items[Q.items.length-1];if(!U||U.value)Q.items.push({start:[],key:X,sep:[]});else if(U.sep)U.value=X;else Object.assign(U,{key:X,sep:[]});return}default:yield*this.pop(),yield*this.pop(X)}if((Q.type==="document"||Q.type==="block-map"||Q.type==="block-seq")&&(X.type==="block-map"||X.type==="block-seq")){let U=X.items[X.items.length-1];if(U&&!U.sep&&!U.value&&U.start.length>0&&jJ(U.start)===-1&&(X.indent===0||U.start.every((J)=>J.type!=="comment"||J.indent<X.indent))){if(Q.type==="document")Q.end=U.start;else Q.items.push({start:U.start});X.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let Z={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")Z.start.push(this.sourceToken);this.stack.push(Z);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(Z){if(Z.value)return yield*this.lineEnd(Z);switch(this.type){case"doc-start":{if(jJ(Z.start)!==-1)yield*this.pop(),yield*this.step();else Z.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":Z.start.push(this.sourceToken);return}let X=this.startBlockValue(Z);if(X)this.stack.push(X);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(Z){if(this.type==="map-value-ind"){let X=H8(this.peek(2)),Q=H4(X),U;if(Z.end)U=Z.end,U.push(this.sourceToken),delete Z.end;else U=[this.sourceToken];let J={type:"block-map",offset:Z.offset,indent:Z.indent,items:[{start:Q,key:Z,sep:U}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=J}else yield*this.lineEnd(Z)}*blockScalar(Z){switch(this.type){case"space":case"comment":case"newline":Z.props.push(this.sourceToken);return;case"scalar":if(Z.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let X=this.source.indexOf(`
181
+ `)+1;while(X!==0)this.onNewLine(this.offset+X),X=this.source.indexOf(`
182
+ `,X)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(Z){let X=Z.items[Z.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,X.value){let Q="end"in X.value?X.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else Z.items.push({start:[this.sourceToken]})}else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"space":case"comment":if(X.value)Z.items.push({start:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else{if(this.atIndentedComment(X.start,Z.indent)){let U=Z.items[Z.items.length-2]?.value?.end;if(Array.isArray(U)){Array.prototype.push.apply(U,X.start),U.push(this.sourceToken),Z.items.pop();return}}X.start.push(this.sourceToken)}return}if(this.indent>=Z.indent){let Q=!this.onKeyLine&&this.indent===Z.indent,U=Q&&(X.sep||X.explicitKey)&&this.type!=="seq-item-ind",J=[];if(U&&X.sep&&!X.value){let $=[];for(let W=0;W<X.sep.length;++W){let Y=X.sep[W];switch(Y.type){case"newline":$.push(W);break;case"space":break;case"comment":if(Y.indent>Z.indent)$.length=0;break;default:$.length=0}}if($.length>=2)J=X.sep.splice($[1])}switch(this.type){case"anchor":case"tag":if(U||X.value)J.push(this.sourceToken),Z.items.push({start:J}),this.onKeyLine=!0;else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"explicit-key-ind":if(!X.sep&&!X.explicitKey)X.start.push(this.sourceToken),X.explicitKey=!0;else if(U||X.value)J.push(this.sourceToken),Z.items.push({start:J,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(X.explicitKey)if(!X.sep)if(V2(X.start,"newline"))Object.assign(X,{key:null,sep:[this.sourceToken]});else{let $=H4(X.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,key:null,sep:[this.sourceToken]}]})}else if(X.value)Z.items.push({start:[],key:null,sep:[this.sourceToken]});else if(V2(X.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:null,sep:[this.sourceToken]}]});else if(bJ(X.key)&&!V2(X.sep,"newline")){let $=H4(X.start),W=X.key,Y=X.sep;Y.push(this.sourceToken),delete X.key,delete X.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,key:W,sep:Y}]})}else if(J.length>0)X.sep=X.sep.concat(J,this.sourceToken);else X.sep.push(this.sourceToken);else if(!X.sep)Object.assign(X,{key:null,sep:[this.sourceToken]});else if(X.value||U)Z.items.push({start:J,key:null,sep:[this.sourceToken]});else if(V2(X.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else X.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let $=this.flowScalar(this.type);if(U||X.value)Z.items.push({start:J,key:$,sep:[]}),this.onKeyLine=!0;else if(X.sep)this.stack.push($);else Object.assign(X,{key:$,sep:[]}),this.onKeyLine=!0;return}default:{let $=this.startBlockValue(Z);if($){if($.type==="block-seq"){if(!X.explicitKey&&X.sep&&!V2(X.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(Q)Z.items.push({start:J});this.stack.push($);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(Z){let X=Z.items[Z.items.length-1];switch(this.type){case"newline":if(X.value){let Q="end"in X.value?X.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else Z.items.push({start:[this.sourceToken]})}else X.start.push(this.sourceToken);return;case"space":case"comment":if(X.value)Z.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(X.start,Z.indent)){let U=Z.items[Z.items.length-2]?.value?.end;if(Array.isArray(U)){Array.prototype.push.apply(U,X.start),U.push(this.sourceToken),Z.items.pop();return}}X.start.push(this.sourceToken)}return;case"anchor":case"tag":if(X.value||this.indent<=Z.indent)break;X.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==Z.indent)break;if(X.value||V2(X.start,"seq-item-ind"))Z.items.push({start:[this.sourceToken]});else X.start.push(this.sourceToken);return}if(this.indent>Z.indent){let Q=this.startBlockValue(Z);if(Q){this.stack.push(Q);return}}yield*this.pop(),yield*this.step()}*flowCollection(Z){let X=Z.items[Z.items.length-1];if(this.type==="flow-error-end"){let Q;do yield*this.pop(),Q=this.peek(1);while(Q?.type==="flow-collection")}else if(Z.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!X||X.sep)Z.items.push({start:[this.sourceToken]});else X.start.push(this.sourceToken);return;case"map-value-ind":if(!X||X.value)Z.items.push({start:[],key:null,sep:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else Object.assign(X,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!X||X.value)Z.items.push({start:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let U=this.flowScalar(this.type);if(!X||X.value)Z.items.push({start:[],key:U,sep:[]});else if(X.sep)this.stack.push(U);else Object.assign(X,{key:U,sep:[]});return}case"flow-map-end":case"flow-seq-end":Z.end.push(this.sourceToken);return}let Q=this.startBlockValue(Z);if(Q)this.stack.push(Q);else yield*this.pop(),yield*this.step()}else{let Q=this.peek(2);if(Q.type==="block-map"&&(this.type==="map-value-ind"&&Q.indent===Z.indent||this.type==="newline"&&!Q.items[Q.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Q.type!=="flow-collection"){let U=H8(Q),J=H4(U);EJ(Z);let $=Z.end.splice(1,Z.end.length);$.push(this.sourceToken);let W={type:"block-map",offset:Z.offset,indent:Z.indent,items:[{start:J,key:Z,sep:$}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}else yield*this.lineEnd(Z)}}flowScalar(Z){if(this.onNewLine){let X=this.source.indexOf(`
183
+ `)+1;while(X!==0)this.onNewLine(this.offset+X),X=this.source.indexOf(`
184
+ `,X)+1}return{type:Z,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(Z){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let X=H8(Z),Q=H4(X);return Q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let X=H8(Z),Q=H4(X);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(Z,X){if(this.type!=="comment")return!1;if(this.indent<=X)return!1;return Z.every((Q)=>Q.type==="newline"||Q.type==="space")}*documentEnd(Z){if(this.type!=="doc-mode"){if(Z.end)Z.end.push(this.sourceToken);else Z.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(Z){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(Z.end)Z.end.push(this.sourceToken);else Z.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}function IJ(Z){let X=Z.prettyErrors!==!1;return{lineCounter:Z.lineCounter||X&&new N6||null,prettyErrors:X}}function z8(Z,X={}){let{lineCounter:Q,prettyErrors:U}=IJ(X),J=new z4(Q?.addNewLine),$=new V4(X),W=Array.from($.compose(J.parse(Z)));if(U&&Q)for(let Y of W)Y.errors.forEach(T6(Z,Q)),Y.warnings.forEach(T6(Z,Q));if(W.length>0)return W;return Object.assign([],{empty:!0},$.streamInfo())}function _7(Z,X={}){let{lineCounter:Q,prettyErrors:U}=IJ(X),J=new z4(Q?.addNewLine),$=new V4(X),W=null;for(let Y of $.compose(J.parse(Z),!0,Z.length))if(!W)W=Y;else if(W.options.logLevel!=="silent"){W.errors.push(new U1(Y.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(U&&Q)W.errors.forEach(T6(Z,Q)),W.warnings.forEach(T6(Z,Q));return W}function F8(Z,X,Q){let U=void 0;if(typeof X==="function")U=X;else if(Q===void 0&&X&&typeof X==="object")Q=X;let J=_7(Z,Q);if(!J)return null;if(J.warnings.forEach(($)=>p9(J.options.logLevel,$)),J.errors.length>0)if(J.options.logLevel!=="silent")throw J.errors[0];else J.errors=[];return J.toJS(Object.assign({reviver:U},Q))}function fJ(Z,X,Q){let U=null;if(typeof X==="function"||Array.isArray(X))U=X;else if(Q===void 0&&X)Q=X;if(typeof Q==="string")Q=Q.length;if(typeof Q==="number"){let J=Math.round(Q);Q=J<1?void 0:J>8?{indent:8}:{indent:J}}if(Z===void 0){let{keepUndefined:J}=Q??X??{};if(!J)return}if(e0(Z)&&!U)return Z.toString(Q);return new S1(Z,U,Q).toString(Q)}var V7=L7;class GL{static toYaml(Z){let X=Array.isArray(Z)?Z:[Z];return V7.stringify(X)}static toJson(Z,X=!0){let Q=Array.isArray(Z)?Z:[Z];return JSON.stringify(Q,null,X?2:0)}static cleanRule(Z){let X={};if(X.id=Z.id,Z.name)X.name=Z.name;if(Z.description)X.description=Z.description;if(X.on=Z.on,Z.priority!==void 0&&Z.priority!==0)X.priority=Z.priority;if(Z.enabled!==void 0&&Z.enabled!==!0)X.enabled=Z.enabled;if(Z.cooldown!==void 0&&Z.cooldown!==0)X.cooldown=Z.cooldown;if(Z.tags&&Z.tags.length>0)X.tags=Z.tags;if(Z.if)X.if=Z.if;if(X.do=Z.do,Z.else)X.else=Z.else;return X}static toCleanYaml(Z){let Q=(Array.isArray(Z)?Z:[Z]).map((U)=>this.cleanRule(U));return V7.stringify(Q,{indent:2,lineWidth:0})}static toCleanJson(Z,X=!0){let U=(Array.isArray(Z)?Z:[Z]).map((J)=>this.cleanRule(J));return JSON.stringify(U,null,X?2:0)}static async saveToFile(Z,X){let Q=this.toYaml(Z);if(typeof process<"u"&&process.versions&&process.versions.node){let U=await import("fs/promises"),$=(await Promise.resolve().then(() => (rJ(),sJ))).dirname(X);await U.mkdir($,{recursive:!0}),await U.writeFile(X,Q,"utf8")}else throw Error("saveToFile is only supported in Node.js/Bun environments")}}var _L=["EQ","==","NEQ","!="],LL=["GT",">","GTE",">=","LT","<","LTE","<="],VL=["IN","NOT_IN","RANGE"],qL=["CONTAINS","NOT_CONTAINS","STARTS_WITH","ENDS_WITH"];var oJ=[..._L,...LL,...VL,...qL,"IS_EMPTY","HAS_KEY","MATCHES","SINCE","AFTER","BEFORE","UNTIL","RANGE"],aJ=["AND","OR"],nJ=["ALL","EITHER","SEQUENCE"];function N0(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function HL(Z){return typeof Z==="string"&&Z.length>0}function zL(Z){return typeof Z==="number"&&!isNaN(Z)}function FL(Z){return typeof Z==="boolean"}function q2(Z){return"operator"in Z&&"conditions"in Z&&(Z.operator==="AND"||Z.operator==="OR")}function H2(Z){return"field"in Z&&"operator"in Z}function H7(Z){return typeof Z==="object"&&Z!==null&&"mode"in Z&&"actions"in Z&&Array.isArray(Z.actions)}function M8(Z){return typeof Z==="object"&&Z!==null&&"if"in Z}function BL(Z){return typeof Z==="object"&&Z!==null&&"type"in Z}function z7(Z){return typeof Z==="string"&&nJ.includes(Z)}function ML(Z){return typeof Z==="string"&&aJ.includes(Z)}function RL(Z){return typeof Z==="string"&&wL(oJ,Z)}function j6(Z){return Z.type||"log"}function E6(Z){if(!Z.params)return"{}";return typeof Z.params==="string"?Z.params:JSON.stringify(Z.params)}function F4(Z){if(H2(Z))return Z.field||"data";return"data"}function B4(Z){if(H2(Z))return Z.operator||"EQ";if(q2(Z))return Z.operator==="OR"?"OR":"AND";return"EQ"}function M4(Z){if(H2(Z))return Z.value;return}function F7(Z=0){let X=Z;return()=>`node_${X++}`}function B7(){let Z=0;return()=>`edge_${Date.now()}_${Z++}`}function M7(Z=100,X=100,Q=300,U=150){return(J,$,W)=>({x:Z+J*Q,y:X+$*U-W*U/2})}function R4(Z){if(Z===void 0)return[];if(Array.isArray(Z))return Z;return[Z]}function OL(Z){if(!Z)return[];if(Array.isArray(Z))return Z;return[Z]}function KL(Z){if(!Z)return[];if(Array.isArray(Z))return Z;return[Z]}function TL(Z){return Z.replace(/\.(ya?ml)$/i,"")}function DL(Z){return{"==":"EQ","!=":"NEQ",">":"GT",">=":"GTE","<":"LT","<=":"LTE"}[Z]||Z}function PL(Z,X){if(!(X in Z)||Z[X]===void 0||Z[X]===null)throw Error(`Missing required field: ${X}`)}function wL(Z,X){return Z.includes(X)}function AL(Z,X,Q){let U=typeof Z;if(U!==X)throw Error(`Field "${Q}" expected type "${X}", got "${U}"`)}function SL(Z,X,Q){if(typeof Z!=="string"||!X.includes(Z))throw Error(`Field "${Q}" must be one of: ${X.join(", ")}`)}function b6(Z,X,Q,U){if(!N0(Z))throw Error(`Rule at index ${X} is not an object`);let J={...Z};if("actions"in J&&!("do"in J))J.do=J.actions,delete J.actions;if(!("enabled"in J))J.enabled=!0;if(!("priority"in J))J.priority=0;if(!J.id){if(U===!0&&Q){let $=Q.replace(/\.(ya?ml)$/i,"");J.id=$}else if(typeof U==="string")J.id=`${U}-${X}`}if("if"in J&&J.if!==void 0)J.if=R8(J.if);if("do"in J&&J.do!==void 0)J.do=Z$(J.do);if("else"in J&&J.else!==void 0)J.else=X$(J.else);return J}function R8(Z){if(!Z)return[];if(N0(Z))return tJ(Z);if(Array.isArray(Z))return Z.map((X,Q)=>{if(N0(X))return tJ(X);throw Error(`Invalid condition at index ${Q}: expected object`)});throw Error("Invalid condition format: expected object or array")}function tJ(Z){let X="operator"in Z&&(Z.operator==="AND"||Z.operator==="OR"),Q="conditions"in Z&&Array.isArray(Z.conditions);if(X&&Q){let W=Z.operator,Y=R8(Z.conditions);return{operator:W,conditions:Array.isArray(Y)?Y:[Y]}}let{field:U,operator:J,value:$}=Z;return{field:U||"data",operator:J||"EQ",value:$}}function Z$(Z){if(!Z)return[];if(N0(Z)&&"mode"in Z&&"actions"in Z)return S2(Z);if(N0(Z))return z2(Z);if(Array.isArray(Z))return Z.map((X,Q)=>{if(N0(X)){if("mode"in X&&"actions"in X)return S2(X);return z2(X)}throw Error(`Invalid action at index ${Q}: expected object`)});throw Error("Invalid do field format: expected object or array")}function X$(Z){if(!Z)return[];if(N0(Z)&&"mode"in Z&&"actions"in Z)return S2(Z);if(N0(Z))return z2(Z);if(Array.isArray(Z))return Z.map((X,Q)=>{if(N0(X)){if("mode"in X&&"actions"in X)return S2(X);return z2(X)}throw Error(`Invalid action at index ${Q}: expected object`)});throw Error("Invalid else field format: expected object or array")}function z2(Z){let X={...Z};if("do"in X&&!("then"in X))X.then=X.do,delete X.do;if("if"in X&&X.if!==void 0){let U={if:R8(X.if)};if("then"in X&&X.then!==void 0)U.then=eJ(X.then);if("else"in X&&X.else!==void 0)U.else=eJ(X.else);if("break"in X)U.break=X.break;if("continue"in X)U.continue=X.continue;return U}let Q={};if("type"in X)Q.type=X.type;if("params"in X)Q.params=X.params;if("run"in X)Q.run=X.run;if("delay"in X)Q.delay=X.delay;if("probability"in X)Q.probability=X.probability;if("name"in X)Q.name=X.name;if("break"in X)Q.break=X.break;if("continue"in X)Q.continue=X.continue;return Q}function eJ(Z){if(!Z)return[];if(N0(Z)&&"mode"in Z&&"actions"in Z)return S2(Z);if(N0(Z))return z2(Z);if(Array.isArray(Z)){let X=[];for(let Q=0;Q<Z.length;Q++){let U=Z[Q];if(N0(U))if("mode"in U&&"actions"in U){let J=S2(U);for(let $ of J.actions)X.push($)}else X.push(z2(U));else throw Error(`Invalid action in branch at index ${Q}: expected object`)}return X}throw Error("Invalid action branch format: expected object or array")}function S2(Z){let X=Z.mode||"ALL";if(!z7(X))throw Error(`Invalid execution mode: ${X}`);let Q=Z.actions;if(!Q||!Array.isArray(Q))throw Error("Action group must have an actions array");let U=Q.map((J,$)=>{if(N0(J)){if("mode"in J&&"actions"in J)return S2(J);return z2(J)}throw Error(`Invalid action in group at index ${$}: expected object`)});return{mode:X,actions:U}}function CL(Z,X,Q,U){let J=b6(Z,X,Q,U);if(!J.on)throw Error(`Rule at index ${X} missing required field: on`);return J}function NL(Z){let X=[];if(!Z.on)X.push("Missing required field: on");if(!Z.do&&Z.do!=="")X.push("Missing required field: do");if(Z.else&&!Z.if)X.push('Field "else" requires "if" to be present');return{valid:X.length===0,errors:X}}function Q$(Z,X,Q){return{id:X,type:f.EVENT,position:Q,data:{id:Z.id||"rule-1",name:Z.name||"Imported Rule",description:Z.description||"",event:Z.on||"",priority:Z.priority||0,enabled:Z.enabled!==!1,cooldown:Z.cooldown,tags:Z.tags}}}function U$(Z,X,Q){return{id:X,type:f.CONDITION_GROUP,position:Q,data:{operator:Z}}}function I6(Z,X,Q,U,J){return{id:U,type:f.CONDITION,position:J,data:{field:Z||"data",operator:X||"EQ",value:Q??""}}}function R7(Z,X,Q){return{id:X,type:f.DO,position:Q,data:{branchType:Z}}}function J$(Z,X,Q){let U,J,$,W,Y,G,_;if(M8(Z)){let V=Z.if;if(V){let z=(Array.isArray(V)?V:[V])[0];if(z&&H2(z))U=z.field,J=z.operator,$=z.value!==void 0?typeof z.value==="string"?z.value:JSON.stringify(z.value):void 0}let q=Z.then;if(q){let F=Array.isArray(q)?q:[q];if(F[0])W=j6(F[0]),Y=E6(F[0])}let H=Z.else;if(H){let F=Array.isArray(H)?H:[H];if(F[0])G=j6(F[0]),_=E6(F[0])}}let L={type:j6(Z),params:E6(Z)};if(U)L.conditionField=U;if(J)L.conditionOperator=J;if($!==void 0)L.conditionValue=$;if(W)L.thenType=W;if(Y)L.thenParams=Y;if(G)L.elseType=G;if(_)L.elseParams=_;return{id:X,type:f.ACTION,position:Q,data:L}}function $$(Z,X,Q){return{id:X,type:f.ACTION_GROUP,position:Q,data:{mode:Z||"SEQUENCE"}}}function J1(Z,X,Q,U,J){return{id:J?J():`edge_${Z}_${X}_${Date.now()}`,source:Z,target:X,sourceHandle:Q??null,targetHandle:U??null}}function jL(Z,X={}){let Q=[],U=[],J=[];if(!Z.id)J.push("Missing required field: id");if(!Z.on)J.push("Missing required field: on (event trigger)");if(!Z.do&&Z.do!=="")J.push("Missing required field: do (actions)");if(J.length>0)return{nodes:[],edges:[],valid:!1,errors:J};let $=X.startNodeId||"event-node",W=F7(0),Y=B7(),G=M7();try{let _=Q$(Z,$,X.startPosition||{x:100,y:300});Q.push(_);let L=R4(Z.if);if(L.length>0){let{conditionNodes:V,groupNodeId:q}=EL(L,Q,U,_.id,W,G),H=R4(Z.do);if(H.length>0){let z=V.length>0?V[V.length-1].id:q||_.id;O4(H,Q,U,z,W,Y,G,"do")}let F=R4(Z.else);if(F.length>0){let z=V.length>0?V[V.length-1].id:q||_.id;O4(F,Q,U,z,W,Y,G,"else")}}else{let V=R4(Z.do);if(V.length>0)O4(V,Q,U,_.id,W,Y,G,"do")}return{nodes:Q,edges:U,valid:!0,errors:[]}}catch(_){let L=_ instanceof Error?_.message:"Unknown error during conversion";return J.push(L),{nodes:Q,edges:U,valid:!1,errors:J}}}function EL(Z,X,Q,U,J,$){let W=[],Y,G=Z.length>1,_=Z.some(q2);if(G||_){Y=J();let L="AND",V=Z.find(q2);if(V&&q2(V))L=V.operator;let q=U$(L,Y,$(1,0,1));X.push(q),Q.push(J1(U,Y,null,w.CONDITION_GROUP_INPUT,void 0));let H=null;Z.forEach((F,z)=>{let B,T;if(q2(F)){if(F.conditions)F.conditions.forEach((D,K)=>{if(q2(D))return;if(B=J(),T=I6(F4(D),B4(D),M4(D),B,$(2,z*2+K,Z.length*2)),X.push(T),W.push(T),H)Q.push(J1(H,B,w.CONDITION_OUTPUT,w.CONDITION_INPUT,void 0));else Q.push(J1(Y,B,w.CONDITION_GROUP_OUTPUT,w.CONDITION_INPUT,void 0));H=B})}else{if(B=J(),T=I6(F4(F),B4(F),M4(F),B,$(2,z,Z.length)),X.push(T),W.push(T),H)Q.push(J1(H,B,w.CONDITION_OUTPUT,w.CONDITION_INPUT,void 0));else Q.push(J1(Y,B,w.CONDITION_GROUP_OUTPUT,w.CONDITION_INPUT,void 0));H=B}})}else{let L=J(),V=I6(F4(Z[0]),B4(Z[0]),M4(Z[0]),L,$(1,0,1));X.push(V),W.push(V),Q.push(J1(U,L,null,w.CONDITION_INPUT,void 0))}return{conditionNodes:W,groupNodeId:Y}}function O4(Z,X,Q,U,J,$,W,Y){Z.forEach((G,_)=>{if(H7(G)){let z=J(),B=X.find((P)=>P.id===U)?.position||{x:100,y:100},T=$$(G.mode,z,{x:B.x+300,y:B.y+_*75});X.push(T);let D=X.find((P)=>P.id===U),K;if(D?.type===f.EVENT)K=w.EVENT_OUTPUT;else if(D?.type===f.CONDITION)K=w.CONDITION_OUTPUT;else if(D?.type===f.CONDITION_GROUP)K=w.CONDITION_GROUP_OUTPUT;else if(D?.type===f.ACTION_GROUP)K=w.ACTION_GROUP_OUTPUT;else if(D?.type===f.DO)K=w.DO_OUTPUT;else K=Y===u0.ELSE?w.ELSE_OUTPUT:w.THEN_OUTPUT;Q.push(J1(U,z,K,w.ACTION_GROUP_INPUT,$)),O4(G.actions,X,Q,z,J,$,W,Y);return}if(M8(G)){let B=G.if,T=Array.isArray(B)?B[0]:B;if(T&&H2(T)){let D=J(),K=W(2,_,Z.length),P=I6(F4(T),B4(T),M4(T),D,{x:K.x+300,y:K.y});X.push(P);let S=X.find((h)=>h.id===U),N;if(S?.type===f.EVENT)N=w.EVENT_OUTPUT;else if(S?.type===f.ACTION_GROUP)N=w.ACTION_GROUP_CONDITION_OUTPUT;else if(S?.type===f.CONDITION)N=w.CONDITION_OUTPUT;else if(S?.type===f.DO)N=w.DO_OUTPUT;else N=Y===u0.ELSE?w.CONDITION_OUTPUT:w.CONDITION_OUTPUT;Q.push(J1(U,D,N,w.CONDITION_INPUT,$));let x=G.then;if(x){let h=J(),a=R7("do",h,{x:P.position.x+300,y:P.position.y-100});X.push(a),Q.push(J1(D,h,w.CONDITION_OUTPUT,w.DO_INPUT,$));let W0=Array.isArray(x)?x:[x];O4(W0,X,Q,h,J,$,(B0,j0,d0)=>{return{x:a.position.x+300,y:a.position.y-j0*150}},"do")}let C=G.else;if(C){let h=J(),a=R7("else",h,{x:P.position.x+300,y:P.position.y+100});X.push(a),Q.push(J1(D,h,w.CONDITION_OUTPUT,w.DO_INPUT,$));let W0=Array.isArray(C)?C:[C];O4(W0,X,Q,h,J,$,(B0,j0,d0)=>{return{x:a.position.x+300,y:a.position.y+j0*150}},"else")}}return}let L=J(),V=X.find((z)=>z.id===U)?.position||{x:700,y:100},q=J$(G,L,{x:V.x+300,y:V.y+_*150});X.push(q);let H=X.find((z)=>z.id===U),F;if(H?.type===f.EVENT)F=w.EVENT_OUTPUT;else if(H?.type===f.CONDITION)F=w.CONDITION_OUTPUT;else if(H?.type===f.CONDITION_GROUP)F=w.CONDITION_GROUP_OUTPUT;else if(H?.type===f.ACTION_GROUP)F=w.ACTION_GROUP_OUTPUT;else if(H?.type===f.DO)F=w.DO_OUTPUT;else F=Y===u0.ELSE?w.CONDITION_OUTPUT:w.CONDITION_OUTPUT;Q.push(J1(U,L,F,w.ACTION_INPUT,$))})}function W$(Z,X={}){let{autoId:Q=!1,filename:U,throwOnError:J=!1,multiDocument:$=!0}=X,W=[],Y=[];try{let _;if($){let V=z8(Z);for(let q of V)if(q.errors&&q.errors.length>0){let H=q.errors.map((F)=>F.message).join(", ");throw Error(`YAML syntax error: ${H}`)}_=V.map((q)=>q.toJS())}else{let V=F8(Z);_=Array.isArray(V)?[V]:[V]}let L=[];_.forEach((V)=>{if(Array.isArray(V))L.push(...V);else L.push(V)}),L.forEach((V,q)=>{try{let H;if(Q&&!U)H={...b6(V,q),id:`rule-${q}`};else H=b6(V,q,U,Q);let F=CX.validate(H);if(F.valid)Y.push(F.rule);else W.push({index:q,message:`Validation failed for rule at index ${q}`,issues:F.issues.map((z)=>({path:z.path,message:z.message,suggestion:z.suggestion}))})}catch(H){let F=H instanceof Error?H.message:`Unknown error at index ${q}`;W.push({index:q,message:F})}})}catch(_){let L=_ instanceof Error?_.message:"Unknown parsing error";W.push({index:-1,message:`Failed to parse YAML: ${L}`})}let G={rules:Y,errors:W,valid:W.length===0&&Y.length>0};if(J&&!G.valid){let _=G.errors.map((L)=>{let V=`Rule ${L.index}: ${L.message}`;if(L.issues)V+=`
185
+ Issues:
186
+ `+L.issues.map((q)=>` - [${q.path}] ${q.message}`).join(`
187
+ `);return V}).join(`
188
+ `);throw Error(`YAML parsing failed:
189
+ ${_}`)}return G}function Cj(Z,X={}){return W$(Z,{...X,multiDocument:!1})}function Nj(Z,X={}){let Q=W$(Z,{...X,throwOnError:!0});if(Q.rules.length===0)throw Error("No valid rules found in YAML");return Q.rules[0]}export{NL as validateRule,SL as validateFieldValue,AL as validateFieldType,jL as triggerRuleToNodes,PL as requireField,W$ as parseYamlRules,Nj as parseYamlRuleStrict,Cj as parseYamlRule,v5 as parseGraphToRules,kX as parseGraph,J6 as optimizeCondition,$6 as optimizeAction,CL as normalizeRuleAdvanced,b6 as normalizeRule,DL as normalizeOperator,X$ as normalizeElseField,Z$ as normalizeDoField,KL as normalizeConditionsUtils,R8 as normalizeConditions,OL as normalizeActions,z2 as normalizeAction,zL as isValidNumber,z7 as isValidExecutionMode,ML as isValidConditionOperator,RL as isValidComparisonOperator,H2 as isSimpleCondition,BL as isSimpleAction,N0 as isObject,HL as isNonEmptyString,q2 as isConditionGroup,FL as isBoolean,H7 as isActionGroup,M8 as hasConditionalExecution,M4 as getConditionValue,B4 as getConditionOperator,F4 as getConditionField,j6 as getActionType,E6 as getActionParams,TL as generateRuleIdFromFilename,yX as findTerminalActions,R4 as ensureArray,OP as defaultGetDoBranchType,A_ as defaultExtractEventData,M7 as createPositionCalculator,w_ as createParserContext,F7 as createNodeIdGenerator,B7 as createEdgeIdGenerator,b9 as collectDoActions,Q$ as buildEventNode,J1 as buildEdge,R7 as buildDoNode,I6 as buildConditionNode,U$ as buildConditionGroupNode,J$ as buildActionNode,$$ as buildActionGroupNode,CX as TriggerValidator,SX as TriggerUtils,ET as TriggerSystem,P_ as TriggerRuleSchema,U6 as TriggerEngine,K0 as StateManager,GL as RuleExporter,M_ as RuleEvents,w5 as RuleEngine,KD as RuleConditionSchema,gX as RuleBuilder,NX as ParamsBuilder,f as NodeType,n0 as MathFunctions,PD as InlineConditionalActionSchema,TX as InMemoryPersistence,w as HandleId,v0 as ExpressionEngine,B_ as Events,R_ as EventQueue,AX as ErrorMessages,U6 as Engine,A9 as DebugMessages,wX as ControlFlow,H_ as ContextKeys,O_ as ContextAdapter,C9 as ConditionalActionBuilder,RD as ConditionSchema,jX as ConditionOperator,OD as ConditionGroupSchema,$2 as ConditionBuilder,MD as ComparisonOperatorSchema,S0 as BuiltInAction,P5 as BrowserPersistence,u0 as BranchType,F_ as Actions,TD as ActionSchema,X6 as ActionRegistry,DD as ActionGroupSchema,W6 as ActionBuilder};
190
+
191
+ //# debugId=13640DDA9B8B57E764756E2164756E21