@makaio/framework 1.0.0-dev-1781081952714 → 1.0.0-dev-1781260968078

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 (194) hide show
  1. package/README.md +29 -0
  2. package/dist/.makaio-build.json +2 -2
  3. package/dist/adapters/acp-client/index.d.mts +4 -4
  4. package/dist/adapters/config/index.d.mts +1 -1
  5. package/dist/adapters/config/index.mjs +1 -1
  6. package/dist/adapters/index.d.mts +1 -1
  7. package/dist/adapters/index.mjs +1 -1
  8. package/dist/adapters/node.mjs +1 -1
  9. package/dist/ajv-BA2z5ztb.mjs +8 -0
  10. package/dist/bus/index.d.mts +19 -19
  11. package/dist/bus/index.mjs +1 -1
  12. package/dist/client-BJVDImPV.d.mts +175 -0
  13. package/dist/clients/index.d.mts +105 -2
  14. package/dist/clients/index.mjs +2 -2
  15. package/dist/contracts/adapter/index.d.mts +2 -2
  16. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  17. package/dist/contracts/artifact/index.d.mts +1 -1
  18. package/dist/contracts/client/index.d.mts +1 -1
  19. package/dist/contracts/extension/index.d.mts +3 -3
  20. package/dist/contracts/extension/index.mjs +1 -1
  21. package/dist/contracts/facet/index.d.mts +1 -1
  22. package/dist/contracts/index.d.mts +741 -228
  23. package/dist/contracts/index.mjs +1 -1
  24. package/dist/contracts/materialization/index.d.mts +3 -3
  25. package/dist/contracts/session/index.d.mts +2 -2
  26. package/dist/{cursor-storage-C_WTAESV.mjs → cursor-storage-CmKjSvKY.mjs} +1 -1
  27. package/dist/{definition-DqJOg6Lv.d.mts → definition-SiimP25_.d.mts} +1 -1
  28. package/dist/{detached-extension-handle-CxEBQnSa.mjs → detached-extension-handle-Diiwgm13.mjs} +1 -1
  29. package/dist/drizzle/0001_messages_content_tsv.na.md +18 -0
  30. package/dist/drizzle/0012_legal_kate_bishop.sql +3 -0
  31. package/dist/drizzle/0013_eager_rhodey.sql +56 -0
  32. package/dist/drizzle/0014_fancy_ultimo.sql +1 -0
  33. package/dist/drizzle/meta/0012_snapshot.json +2934 -0
  34. package/dist/drizzle/meta/0013_snapshot.json +2954 -0
  35. package/dist/drizzle/meta/0014_snapshot.json +2959 -0
  36. package/dist/drizzle/meta/_journal.json +21 -0
  37. package/dist/drizzle-wjquQK2m.mjs +1 -0
  38. package/dist/esm-CQVFKEW5.mjs +1 -0
  39. package/dist/expression/index.d.mts +11 -2
  40. package/dist/expression/index.mjs +4 -4
  41. package/dist/extension-DfNcE0zm.mjs +1 -0
  42. package/dist/extension-ZBN4BGre.mjs +1 -0
  43. package/dist/{filesystem-service-DH9zlxyd.mjs → filesystem-service-BjfrUmGS.mjs} +1 -1
  44. package/dist/git/index.mjs +14 -14
  45. package/dist/{globby-4SrlyIlj.mjs → globby-BIH65cbN.mjs} +1 -1
  46. package/dist/handler-DSfSAlxx.mjs +1 -0
  47. package/dist/handlers-C8EtpSqK.mjs +41 -0
  48. package/dist/{index-BCKRUuI2.d.mts → index-B2xbnMZe.d.mts} +1 -1
  49. package/dist/{index-YDfOv0GT.d.mts → index-BDRKAxIV.d.mts} +160 -7
  50. package/dist/{index-CwKzQuIX.d.mts → index-BQiHs8EF.d.mts} +12 -12
  51. package/dist/{index-BheaEhyI.d.mts → index-BtztOqaF.d.mts} +6 -6
  52. package/dist/{index-BmV60tMf.d.mts → index-BvSyOgTY.d.mts} +1298 -30
  53. package/dist/{index-D6bw4qJp.d.mts → index-CARxIllg.d.mts} +98 -98
  54. package/dist/{index-Bibt5jAX.d.mts → index-CZ_TcT6J.d.mts} +8 -8
  55. package/dist/{index-CNOTkyGw.d.mts → index-Cb64d5c5.d.mts} +307 -383
  56. package/dist/{index-DETxgKS2.d.mts → index-CgjslA5-.d.mts} +88 -15
  57. package/dist/{index-C3zfJg6s.d.mts → index-D5CI1V5d.d.mts} +16 -16
  58. package/dist/{index-jlQ4IhR5.d.mts → index-DDQkhhRo.d.mts} +281 -273
  59. package/dist/{index-Db0uJ_Cg2.d.mts → index-DTdqGAfH2.d.mts} +18 -8
  60. package/dist/{index-Clut1ljB.d.mts → index-Drz_a7kW.d.mts} +1 -1
  61. package/dist/kernel/extension/index.d.mts +1 -1
  62. package/dist/kernel/extension/index.mjs +1 -1
  63. package/dist/kernel/index.d.mts +2 -2
  64. package/dist/kernel/index.mjs +1 -1
  65. package/dist/kernel/observability/index.d.mts +1 -1
  66. package/dist/{lib-B9kVK_1_.mjs → lib-CNOQJtgs.mjs} +1 -1
  67. package/dist/{lib-DPruLs5D.mjs → lib-Cq5R6Tx9.mjs} +19 -22
  68. package/dist/lib-nlcl5kRW.mjs +2 -0
  69. package/dist/{load-extensions-C-TqCwzL.mjs → load-extensions-wELQ4BBN.mjs} +1 -1
  70. package/dist/mcp-http-server/index.mjs +1 -1
  71. package/dist/{namespace-ByyuIFpL.d.mts → namespace-7tsuJhQ9.d.mts} +28 -28
  72. package/dist/{namespace-BlS_i9KT.d.mts → namespace-B73Sxj5L.d.mts} +1 -1
  73. package/dist/{namespace-aBIAWxY3.d.mts → namespace-Ba4bxtHQ.d.mts} +12 -12
  74. package/dist/{namespace-DBKWNrk7.d.mts → namespace-DDCjoQUj.d.mts} +3 -3
  75. package/dist/{namespace-Ds6HkJEU.d.mts → namespace-DRFJN-_z.d.mts} +134 -134
  76. package/dist/namespace-DwE2g8Wm.mjs +1 -0
  77. package/dist/{orchestrator-shared-FnWrPS09.mjs → orchestrator-shared-Dt4WDse7.mjs} +1 -1
  78. package/dist/{out-CvZYgczi.mjs → out-C1JFb2Bp.mjs} +1 -1
  79. package/dist/package-Be2Ez4vv.mjs +1 -0
  80. package/dist/package.json +1 -1
  81. package/dist/primitive-runtime-Xrc9xh6p.mjs +1 -0
  82. package/dist/registry-RG-bkw3c.mjs +146 -0
  83. package/dist/rules/index.mjs +1 -1
  84. package/dist/runtime-bun/index.mjs +1 -1
  85. package/dist/runtime-node/extension-validation.mjs +1 -1
  86. package/dist/runtime-node/index.d.mts +57 -36
  87. package/dist/runtime-node/index.mjs +26 -53
  88. package/dist/runtime-node/makaio-config.mjs +1 -1
  89. package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
  90. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  91. package/dist/{schema-CDL_pyyM.d.mts → schema-BNrM9LWb.d.mts} +216 -10
  92. package/dist/schema-BerZmr2q.mjs +1 -0
  93. package/dist/schema-BrnYlDwZ.mjs +1 -0
  94. package/dist/{schemas-t1VR6_b_.d.mts → schemas-CkOSG2eJ.d.mts} +3 -3
  95. package/dist/{schemas-Exixg77V2.d.mts → schemas-DAFYpgHk2.d.mts} +12 -12
  96. package/dist/{schemas-on3_N5HP.d.mts → schemas-Dv5FxHDT.d.mts} +134 -134
  97. package/dist/services/agent-runtime/index.d.mts +2 -2
  98. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  99. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  100. package/dist/services/filesystem/index.mjs +1 -1
  101. package/dist/services/filesystem/namespace.d.mts +6 -6
  102. package/dist/services/filesystem/schemas.d.mts +3 -3
  103. package/dist/services/git/namespace.d.mts +2 -2
  104. package/dist/services/git/schemas.d.mts +2 -2
  105. package/dist/services/harness/index.d.mts +29 -17
  106. package/dist/services/harness/index.mjs +1 -1
  107. package/dist/services/harness/storage/schema.d.mts +60 -16
  108. package/dist/services/harness/storage/schema.mjs +1 -1
  109. package/dist/services/index.d.mts +103 -103
  110. package/dist/services/index.mjs +1 -1
  111. package/dist/services/log-import/browser.d.mts +2 -2
  112. package/dist/services/log-import/index.d.mts +7 -12
  113. package/dist/services/log-import/index.mjs +2 -2
  114. package/dist/services/log-import/log-import.d.mts +1 -1
  115. package/dist/services/log-import/namespace.d.mts +2 -2
  116. package/dist/services/log-import/schemas.d.mts +1 -1
  117. package/dist/services/session/handlers/index.mjs +1 -1
  118. package/dist/services/session/index.d.mts +7 -7
  119. package/dist/services/session/index.mjs +1 -1
  120. package/dist/services/session/messages/namespace.d.mts +1 -1
  121. package/dist/services/session/messages/namespace.mjs +1 -1
  122. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  123. package/dist/services/session/session-events/namespace.d.mts +1 -1
  124. package/dist/services/session/session-events/namespace.mjs +1 -1
  125. package/dist/services/session/storage/namespace.d.mts +1 -1
  126. package/dist/services/session/storage/schema.d.mts +2 -2
  127. package/dist/services/session/storage/schema.mjs +1 -1
  128. package/dist/services/session/testing/index.d.mts +18 -2
  129. package/dist/services/session/testing/index.mjs +52 -3
  130. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  131. package/dist/services/session/turns/namespace.d.mts +1 -1
  132. package/dist/services/session/turns/namespace.mjs +1 -1
  133. package/dist/services/settings/namespace.d.mts +12 -12
  134. package/dist/services/subagent-template/index.d.mts +1 -1
  135. package/dist/services/subagent-template/schemas.d.mts +1 -1
  136. package/dist/services/tool-approval/index.mjs +1 -1
  137. package/dist/services/tools/index.mjs +1 -1
  138. package/dist/session-KnewDVxt.mjs +39 -0
  139. package/dist/{session-lineage-CKg6mErA.d.mts → session-lineage-CXzV_hAP.d.mts} +1 -1
  140. package/dist/{src-Dvp41Cg2.mjs → src-CBG3IHUl.mjs} +1 -1
  141. package/dist/storage/drizzle/client.d.mts +2 -78
  142. package/dist/storage/drizzle/client.mjs +1 -1
  143. package/dist/storage/drizzle/columns/postgres.d.mts +88 -0
  144. package/dist/storage/drizzle/columns/postgres.mjs +1 -0
  145. package/dist/storage/drizzle/columns/sqlite.d.mts +81 -0
  146. package/dist/storage/drizzle/columns/sqlite.mjs +1 -0
  147. package/dist/storage/drizzle/index.d.mts +976 -23
  148. package/dist/storage/drizzle/index.mjs +1 -1
  149. package/dist/storage/handlers/drizzle/index.d.mts +1 -1
  150. package/dist/storage/handlers/drizzle/index.mjs +1 -1
  151. package/dist/storage/handlers/index.d.mts +1 -1
  152. package/dist/storage/handlers/index.mjs +1 -1
  153. package/dist/style.css +540 -540
  154. package/dist/testing/drizzle-harness.d.mts +52 -6
  155. package/dist/testing/drizzle-harness.mjs +1 -1
  156. package/dist/testing/index.d.mts +34 -2
  157. package/dist/testing/index.mjs +1 -1
  158. package/dist/{tool-approval-service-BgNcJvKx.mjs → tool-approval-service-Cb2F1yT6.mjs} +1 -1
  159. package/dist/tools-D5DVHC-R.mjs +1 -0
  160. package/dist/{types-CmMesAgR.d.mts → types-BMpIa4fx.d.mts} +1 -1
  161. package/dist/{types-D0fPFh-D.d.mts → types-D5IMwOkJ.d.mts} +1 -1
  162. package/dist/{types-DiGqpZOD.d.mts → types-DLVitCZP.d.mts} +195 -195
  163. package/dist/ui-components/index.d.mts +1 -1
  164. package/dist/ui-components/index.mjs +2 -2
  165. package/dist/ui-hooks/index.d.mts +6 -6
  166. package/dist/ui-views/index.mjs +2 -2
  167. package/dist/workflow-engine/index.d.mts +492 -96
  168. package/dist/workflow-engine/index.mjs +1 -1
  169. package/dist/workflow-engine/package.mjs +1 -1
  170. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  171. package/dist/workflow-worker-CK9Sqj7D.mjs +1 -0
  172. package/package.json +40 -1
  173. package/dist/ajv-BJsabpMb.mjs +0 -8
  174. package/dist/drizzle-DpjZFY_j.mjs +0 -1
  175. package/dist/esm-BdLRFEUy.mjs +0 -3
  176. package/dist/extension--5Q190u_.mjs +0 -1
  177. package/dist/extension-DFIZ3FCJ.mjs +0 -1
  178. package/dist/fast-uri-BF2Xuiop.mjs +0 -1
  179. package/dist/handlers-Bev7-xjL.mjs +0 -41
  180. package/dist/lib-aRogYLqg.mjs +0 -5
  181. package/dist/namespace-CDiM5Bcr.mjs +0 -1
  182. package/dist/namespace-h0HIuqx0.mjs +0 -1
  183. package/dist/package-1DS4bXg5.mjs +0 -1
  184. package/dist/primitive-runtime-DcYYWy_6.mjs +0 -8
  185. package/dist/schema-DCJyzRHe.mjs +0 -1
  186. package/dist/schema-DOnJmAPw.mjs +0 -1
  187. package/dist/session-BnfsJoZi.mjs +0 -134
  188. package/dist/tools-DC4KrqI1.mjs +0 -1
  189. package/dist/types-BhXRffJ_.d.mts +0 -31
  190. package/dist/workflow-worker-DvP753UN.mjs +0 -1
  191. /package/dist/{cleanEnvForAdapter-BlpmyXYk.mjs → cleanEnvForAdapter-vZfPGi0X.mjs} +0 -0
  192. /package/dist/{create-static-mount-CFGo91CI.mjs → create-static-mount-BB1MIQ9J.mjs} +0 -0
  193. /package/dist/{jsonl-transport-BxNXizIm.mjs → jsonl-transport-C21tpVfe.mjs} +0 -0
  194. /package/dist/{src-Z3vAZJfw.mjs → src-DedDL9iv.mjs} +0 -0
@@ -1 +0,0 @@
1
- import{harnessDefinitions as e}from"./services/harness/storage/schema.mjs";import{z as t}from"zod";import{ApprovalPolicySchema as n,HarnessDefinitionBaseSchema as r,HarnessDefinitionSchema as i}from"@makaio/framework/contracts";import{createStorageNamespaceDefinition as a}from"@makaio/framework/storage";const o=t.object({enabled:t.array(t.string()),disabled:t.array(t.string())}),s=r.omit({createdAt:!0,updatedAt:!0,approvalPolicy:!0,isDefault:!0,enabled:!0,nativeTools:!0,registryTools:!0,skills:!0}).extend({approvalPolicy:n,isDefault:t.boolean(),enabled:t.boolean(),nativeTools:o,registryTools:o,skills:o.optional()}).strict().refine(e=>!!e.adapterName||!!e.clientId,{message:`At least one of adapterName or clientId must be set`}),c=t.object({adapterName:t.string().optional(),clientId:t.string().optional(),name:t.string().optional()}),l=a(`harness`,{schemas:{get:{request:t.object({id:t.string()}),response:t.object({harness:i.nullable()})},set:{request:t.object({harness:s}),response:t.object({id:t.string()})},delete:{request:t.object({id:t.string()}),response:t.object({deleted:t.boolean()})},list:{request:c,response:t.object({harnesses:t.array(i)})}},extensions:{drizzle:{harnessDefinitions:e}}}),u=l.subjects;export{u as n,l as t};
@@ -1 +0,0 @@
1
- import{sessions as e}from"./services/session/storage/schema.mjs";import{t}from"./schema-DCJyzRHe.mjs";import{SessionEventStorageNamespace as n,SessionEventStorageSubjects as r}from"@makaio/framework/contracts";import{index as i,integer as a,sqliteTable as o,text as s}from"drizzle-orm/sqlite-core";const c=o(`session_events`,{id:a(`id`).primaryKey({autoIncrement:!0}),sessionId:s(`session_id`).notNull().references(()=>e.sessionId,{onDelete:`cascade`}),eventId:s(`event_id`).notNull().unique(),timestamp:a(`timestamp`).notNull(),type:s(`type`).notNull(),agentId:s(`agent_id`),adapterId:s(`adapter_id`),originatingMessageId:s(`originating_message_id`),messageId:s(`message_id`).references(()=>t.messageId,{onDelete:`cascade`}),turnId:s(`turn_id`),contentText:s(`content_text`),payload:s(`payload`).notNull()},e=>[i(`idx_events_session_ts`).on(e.sessionId,e.timestamp),i(`idx_events_session_type`).on(e.sessionId,e.type),i(`idx_events_turn`).on(e.turnId),i(`idx_events_originating_message`).on(e.originatingMessageId)]),l={...n,extensions:{drizzle:{sessionEvents:c}}};export{r as n,c as r,l as t};
@@ -1 +0,0 @@
1
- import{C as e,S as t,T as n,_ as r,a as i,b as a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,n as m,o as h,p as g,t as _,u as v,v as y,w as b,x,y as S}from"./primitive-runtime-DcYYWy_6.mjs";import{isAbsolute as C,resolve as w}from"node:path";import{matchesFilter as ee,matchesSubscription as te}from"@makaio/framework/bus";import{ArtifactSubjects as ne,EXECUTION_LIST_DEFAULT_LIMIT as re,EXECUTION_LIST_MAX_LIMIT as ie,EXECUTION_LIST_MIN_LIMIT as ae,ExecutionHintsSchema as oe,JsonValueSchema as se,SessionSubjects as T,WORKFLOW_CANCELLED_REASON as E,WorkerNodeSubjects as ce,WorkflowNamespace as le,WorkflowSubjects as D,WorkflowWorkerSourceSchema as ue,createWorkflowCancelSubject as de,dep as fe,extensionToken as pe}from"@makaio/framework/contracts";import{BaseService as me}from"@makaio/framework/service-base";import{and as O,asc as k,count as he,desc as A,eq as j,getTableColumns as ge,isNotNull as _e,lt as ve,or as ye,sql as M,sum as N}from"drizzle-orm";import{executeTransaction as P,registerDrizzleHandlers as be}from"@makaio/framework/storage/drizzle";import{compile as xe}from"@makaio/framework/expression";import*as Se from"node:os";import{SessionToken as Ce}from"@makaio/framework/services";function F(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function I(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function we(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=F(t);return[j(e.scopeType,n),j(e.scopeKind,r),j(e.scopeId,i)]}function L(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:I(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function Te(e,t){let n=F(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Ee(e,t){let r=ge(p),i=e.on(g.get,async e=>{let n=await t.select().from(p).where(j(p.id,e.payload.id)).limit(1);e.setResult({workflow:n[0]?L(n[0]):null})}),a=e.on(g.set,async i=>{let a=i.payload.workflow,o=Date.now(),s=Te(a,o),c=await t.insert(p).values(s).onConflictDoNothing({target:p.id}).returning();if(c.length>0){await e.emit(n.definition.created,L(c[0])),i.setResult({id:a.id});return}let[l]=await t.update(p).set({name:s.name,root:s.root,updatedAt:o,createdAt:M`COALESCE(${r.createdAt}, ${o})`,description:s.description===null?M`${r.description}`:s.description,inputSchema:s.inputSchema===null?M`${r.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?M`${r.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?M`${r.outputSchema}`:s.outputSchema,artifact:s.artifact===null?M`${r.artifact}`:s.artifact,triggers:s.triggers===null?M`${r.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?M`${r.canvasLayout}`:s.canvasLayout,source:s.source===null?M`${r.source}`:s.source,executionHints:s.executionHints===null?M`${r.executionHints}`:s.executionHints,...F(a.scope)}).where(j(p.id,a.id)).returning();l&&await e.emit(n.definition.updated,L(l)),i.setResult({id:a.id})}),o=e.on(g.delete,async r=>{let i=(await t.delete(p).where(j(p.id,r.payload.id)).returning()).length>0;i&&await e.emit(n.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),s=e.on(g.list,async e=>{let n=e.payload,r=n.scope?we(p,n.scope):[],i=r.length>0?await t.select().from(p).where(O(...r)):await t.select().from(p);e.setResult({workflows:i.map(L)})});return()=>{i(),a(),o(),s()}}function De(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function Oe(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function ke(e,t){let n=e.on(g.setFrame,async e=>{let{executionId:n,frame:r}=e.payload,i=Oe(n,r);await t.insert(u).values(i).onConflictDoUpdate({target:u.frameId,set:i}),e.setResult({frameId:r.frameId})}),r=e.on(g.getFrame,async e=>{let n=await t.select().from(u).where(j(u.frameId,e.payload.frameId)).limit(1);e.setResult({frame:n[0]?De(n[0]):null})}),i=e.on(g.listFrames,async e=>{let n=await t.select().from(u).where(j(u.executionId,e.payload.executionId)).orderBy(k(u.startedAt),k(u.frameId));e.setResult({frames:n.map(De)})});return()=>{n(),r(),i()}}function Ae(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function R(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function z(e){return{id:Ae(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function je(e,t){let n=e.on(g.setGateInstance,async e=>{let n=e.payload.gate,r=z(n);await t.insert(y).values(r).onConflictDoUpdate({target:y.id,set:r}),e.setResult({id:r.id})}),i=e.on(g.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,r=z(n),i=await t.update(y).set(r).where(O(j(y.id,r.id),j(y.status,`waiting`))).returning({id:y.id});e.setResult({accepted:i.length===1})}),a=e.on(g.getGateInstance,async e=>{let{executionId:n,nodeId:r,frameId:i}=e.payload,a=[j(y.executionId,n),j(y.nodeId,r)];i!==void 0&&a.push(j(y.frameId,i));let o=await t.select().from(y).where(O(...a)).limit(1);e.setResult({gate:o[0]?R(o[0]):null})}),o=e.on(g.listGateInstances,async e=>{let n=await t.select().from(y).where(j(y.executionId,e.payload.executionId));e.setResult({gates:n.map(R)})}),s=e.on(g.listPausedGateTimeouts,async e=>{let n=await t.select({gate:y}).from(y).innerJoin(r,j(y.executionId,r.id)).where(O(j(y.status,`waiting`),j(r.status,`paused`),_e(y.timeoutMs)));e.setResult({gates:n.map(e=>R(e.gate))})});return()=>{n(),i(),a(),o(),s()}}function Me(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function Ne(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Pe(e,t){let n=e.on(g.setSpan,async e=>{let{span:n}=e.payload;await t.insert(a).values(n).onConflictDoUpdate({target:[a.executionId,a.frameId],set:n}),e.setResult({id:`${n.executionId}:${n.frameId}`})}),r=e.on(g.listSpans,async e=>{let n=await t.select().from(a).where(j(a.executionId,e.payload.executionId)).orderBy(k(a.startedAt),k(a.stepId),k(a.frameId));e.setResult({spans:n.map(Me)})}),i=e.on(g.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(l).values(n).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),o=e.on(g.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:r}=e.payload;if(n===void 0&&r===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let i=[...n===void 0?[]:[j(l.sourceExecutionId,n)],...r===void 0?[]:[j(l.targetExecutionId,r)]],a=t.select().from(l).where(O(...i));e.setResult({links:(await a).map(Ne)})});return()=>{n(),r(),i(),o()}}function Fe(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function Ie(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function Le(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Ie(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:I(e),...e.executionHints===null?{}:{executionHints:e.executionHints},...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Re(e){let t=Fe(e.source),n=F(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,artifactRef:e.artifactRef??null,executionHints:e.executionHints??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy}}async function ze(e,t){let n=Re(t);await e.insert(S).values(n).onConflictDoUpdate({target:S.executionId,set:n})}function Be(e,t){let n=e.on(g.setRunContext,async e=>{let n=e.payload.runContext;await ze(t,n),e.setResult({executionId:n.executionId})}),r=e.on(g.getRunContext,async e=>{let{executionId:n}=e.payload,r=await t.select().from(S).where(j(S.executionId,n)),i=r[0]?Le(r[0]):null;e.setResult({runContext:i})});return()=>{n(),r()}}function Ve(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function B(e,t){await e.insert(b).values(t).onConflictDoUpdate({target:b.executionId,set:t})}async function V(e,t){let n=await e.select().from(b).where(j(b.executionId,t)).limit(1);return n[0]?Ve(n[0]):null}async function He(e,t={}){let{workflowId:n,status:r,limit:i=50,offset:a=0}=t,o=[...n===void 0?[]:[j(b.workflowId,n)],...r===void 0?[]:[j(b.status,r)]],s=o.length>0?O(...o):void 0,[c,l]=await Promise.all([e.select().from(b).where(s).orderBy(A(b.startedAt)).limit(i).offset(a),e.select({count:he()}).from(b).where(s)]);return{items:c.map(Ve),total:l[0]?.count??0}}async function H(e,n){await e.insert(t).values(n).onConflictDoUpdate({target:t.frameId,set:n})}async function U(e,n){return(await e.select().from(t).where(j(t.frameId,n)).limit(1))[0]??null}async function Ue(e,t){await e.insert(x).values(t).onConflictDoUpdate({target:x.id,set:t})}function We(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function W(t,n){await t.insert(e).values(n).onConflictDoUpdate({target:e.id,set:n})}async function Ge(t,n){return(await t.select().from(e).where(j(e.id,n)).limit(1))[0]??null}function Ke(e,t,n){return`${e}:${t}:${n}`}async function qe(e,n){let[r]=await e.select({totalInputTokens:N(t.inputTokens),totalOutputTokens:N(t.outputTokens),totalEstimatedCost:N(t.estimatedCost)}).from(t).where(j(t.executionId,n));return{totalInputTokens:r?.totalInputTokens===null?0:Number(r?.totalInputTokens),totalOutputTokens:r?.totalOutputTokens===null?0:Number(r?.totalOutputTokens),totalEstimatedCost:r?.totalEstimatedCost===null?0:Number(r?.totalEstimatedCost)}}async function Je(e,t,n,r,i){let a=await U(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(ne.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}const Ye={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};async function Xe(e,t,n){await B(t,{executionId:n.executionId,workflowId:n.workflowId,workflowName:null,status:`running`,startedAt:n.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),await K(e,n.executionId)}async function Ze(e,t,n){let r=n.completedAt??Date.now(),i=await V(t,n.executionId);await B(t,{executionId:n.executionId,workflowId:i?.workflowId??n.executionId,workflowName:i?.workflowName??null,status:`completed`,startedAt:i?.startedAt??r-n.totalDuration,completedAt:r,durationMs:n.totalDuration,totalInputTokens:i?.totalInputTokens??null,totalOutputTokens:i?.totalOutputTokens??null,totalEstimatedCost:i?.totalEstimatedCost??null,error:null,failedNodeId:null}),await K(e,n.executionId)}async function Qe(e,t,n,r,i,a,o){let s=await V(t,n),c=s?.startedAt??o;await B(t,{executionId:n,workflowId:s?.workflowId??n,workflowName:s?.workflowName??null,status:r,startedAt:c,completedAt:o,durationMs:o-c,totalInputTokens:s?.totalInputTokens??null,totalOutputTokens:s?.totalOutputTokens??null,totalEstimatedCost:s?.totalEstimatedCost??null,error:i,failedNodeId:a}),await K(e,n)}function $e(e,t){return[e.on(n.execution.started,async n=>{let{executionId:r}=n.payload;await G(`execution.started[${r}]`,()=>Xe(e,t,n.payload))}),e.on(n.execution.completed,async n=>{let{executionId:r}=n.payload;await G(`execution.completed[${r}]`,()=>Ze(e,t,n.payload))}),e.on(n.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await G(`execution.failed[${r}]`,()=>Qe(e,t,r,`failed`,i,a??null,o))}),e.on(n.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await G(`execution.cancelled[${r}]`,()=>Qe(e,t,r,`cancelled`,null,null,i))})]}async function et(e,t,n){let r=await qe(t,n);if(r.totalInputTokens>0||r.totalOutputTokens>0||r.totalEstimatedCost>0){let e=await V(t,n);e&&await B(t,{executionId:n,workflowId:e.workflowId,workflowName:e.workflowName??null,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??null,durationMs:e.durationMs??null,totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost,error:e.error??null,failedNodeId:e.failedNodeId??null})}}function tt(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function nt(e,t,n,r,i,a,o){let s=o??Date.now();await H(t,{frameId:r,executionId:n,...tt(await U(t,r),i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await et(e,t,n),await K(e,n)}async function rt(e,t,n,r,i,a,o,s){let c=s??Date.now();await H(t,{frameId:r,executionId:n,...tt(await U(t,r),i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await K(e,n)}function it(e,t){return[e.on(n.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await G(`frame.started[${i}]`,async()=>{await H(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await K(e,r)})}),e.on(n.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await G(`frame.completed[${i}]`,()=>nt(e,t,r,i,a,o,s))}),e.on(n.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await G(`frame.failed[${i}]`,()=>rt(e,t,r,i,a,o,s,c))})]}function at(e,t){return[e.on(n.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await G(`gate.suspended[${i}]`,async()=>{await W(t,{id:Ke(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await K(e,r)})}),e.on(n.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await G(`gate.resumed[${i}]`,async()=>{let n=Ke(r,a,i),s=await Ge(t,n),c=Date.now();await W(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await K(e,r)})}),e.on(n.gate.resolved,async n=>ot(n.payload,e,t)),e.on(n.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await G(`artifact.updated[${r}:${i}]`,async()=>{let n=await Je(e,t,i,a,o);if(n===null)return;let s=Date.now();await Ue(t,{id:We(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await K(e,r)})})]}async function ot(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await G(`gate.resolved[${i}]`,async()=>{let s=Ke(r,a,i),c=await Ge(n,s),l=Date.now();await W(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Ye[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await K(t,r)})}function st(e,t){let r=[...$e(e,t),...it(e,t),...at(e,t),e.on(n.worklog.get,async e=>{let{executionId:n}=e.payload,r=await V(t,n);e.setResult({summary:r})}),e.on(n.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await He(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)})];return()=>{for(let e of r)e()}}async function G(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function K(e,t){try{await e.emit(n.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}function ct(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,scope:I(e)}}function lt(e){let t=F(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,...t}}function ut(e,t,n,i){let a=[...e?[j(r.workflowId,e)]:[],...n?[j(r.status,n)]:[]];if(t&&a.push(...we(r,t)),i){let e=ye(ve(r.startedAt,i.startedAt),O(j(r.startedAt,i.startedAt),ve(r.id,i.id)));e&&a.push(e)}return a}async function dt(e,t,n){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);let i=lt(t);await P(e,async e=>{await e.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),await ze(e,n)})}async function ft(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let i=lt(t),a=z(n);await P(e,async e=>{await e.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),await e.insert(y).values(a).onConflictDoUpdate({target:y.id,set:a})})}async function pt(e,t,n,i){return P(e,async e=>{if((await e.select().from(r).where(j(r.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let a=(await e.select().from(y).where(O(j(y.executionId,t),j(y.status,`waiting`)))).map(e=>({...R(e),status:`cancelled`,resolvedAt:n}));await e.update(r).set({status:`cancelled`,completedAt:n,reason:i??null}).where(j(r.id,t));for(let t of a){let n=z(t);await e.update(y).set(n).where(j(y.id,n.id))}return{cancelled:!0,gates:a}})}async function mt(e,t,n,i,a,o){return P(e,async e=>{if((await e.select({id:r.id}).from(r).where(j(r.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),i!==void 0&&(s.error=i),a!==void 0&&(s.reason=a),o!==void 0&&(s.completedAt=o),Object.keys(s).length>0&&await e.update(r).set(s).where(j(r.id,t)),!0})}function ht(e,t){let n=e.on(g.getExecution,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(j(r.id,n));e.setResult({execution:i[0]?ct(i[0]):null})}),i=e.on(g.setExecution,async e=>{let n=e.payload.execution,i=lt(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:n.id})}),a=e.on(g.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await dt(t,n,r),e.setResult({id:n.id,executionId:n.id})}),o=e.on(g.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await ft(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(g.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await mt(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(g.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await pt(t,n,r,i))}),l=e.on(g.listExecutions,async e=>{let{workflowId:n,scope:i,status:a,limit:o,cursor:s}=e.payload;if(n===void 0&&i===void 0)throw Error(`Either workflowId or scope is required to list executions.`);let c=ut(n,i,a,s),l=o??re;if(!Number.isInteger(l)||l<ae||l>ie)throw Error(`Execution list limit must be an integer between ${ae} and ${ie}.`);let u=await t.select().from(r).where(O(...c)).orderBy(A(r.startedAt),A(r.id)).limit(l);e.setResult({executions:u.map(ct)})});return()=>{n(),i(),a(),o(),s(),c(),l()}}function q(e,t,n){let r=Ee(e,t),i=ht(e,t),a=ke(e,t),o=je(e,t),s=Pe(e,t),c=Be(e,t),l=st(e,t);return()=>{r(),i(),a(),o(),s(),c(),l()}}function gt(e,t){if(e.origin.local)return!0;let n=e.transport?.peer;return n?.authenticated!==!0||n.id!==t?!1:n.kind===`workflow-execution`?!0:n.kind===`e2e`&&n.encrypted===!0}function _t(e){return[e.on(n.getDefinition,async t=>{let n=await e.request(g.get,{id:t.payload.id});t.setResult(n)}),e.on(n.setDefinition,async t=>{let n=await e.request(g.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(n.deleteDefinition,async t=>{let n=await e.request(g.delete,{id:t.payload.id});t.setResult(n)}),e.on(n.listDefinitions,async t=>{let n=await e.request(g.list,t.payload);t.setResult(n)}),e.on(n.getExecution,async t=>{let n=await e.request(g.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(n.listExecutions,async t=>{let n=await e.request(g.listExecutions,t.payload);t.setResult(n)}),e.on(n.listSpans,async t=>{let n=await e.request(g.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(n.listGateInstances,async t=>{let n=await e.request(g.listGateInstances,{executionId:t.payload.executionId});t.setResult(n)}),e.on(n.getRunContext,async t=>{let{executionId:n}=t.payload;if(!gt(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(g.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)})]}function vt(e,t){return[e.on(n.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}const yt=[`darwin`,`linux`,`win32`];function bt(e){return yt.find(t=>t===e)??`linux`}function xt(e,t){return t}function St(e,t){return{...t}}function Ct(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:E}async function wt(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return;let i=e.buildFinalizerDeps(),{execution:a}=await i.bus.request(g.getExecution,{executionId:t});a?.status===`running`&&(r.execution=a,await o(i,t,Ct(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function Tt(e,t){if(t.pausedAtGateId===void 0||t.pausedAtFrameId===void 0)throw Error(`Paused runner result for '${t.executionId}' is missing gate identity`);let{bus:r}=e.buildFinalizerDeps(),{execution:i}=await r.request(g.getExecution,{executionId:t.executionId});if(i?.status!==`running`){let n=e.activeExecutions.get(t.executionId);n!==void 0&&i?.status===`paused`&&(n.execution.status=`paused`,e.activeExecutions.delete(t.executionId));return}let a={...i,status:`paused`};await r.request(g.setExecution,{execution:a});let o=e.activeExecutions.get(t.executionId);o!==void 0&&(o.execution=a),await r.emit(n.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId}),e.activeExecutions.delete(t.executionId)}async function Et(e,t){let n=e.activeExecutions.get(t.executionId);if(!n||n.execution.status!==`running`)return;let r=e.buildFinalizerDeps(),{execution:i}=await r.bus.request(g.getExecution,{executionId:t.executionId});if(i?.status===`running`){if(n.execution=i,t.status===`completed`){await v(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await o(r,t.executionId,t.reason??E);return}if(t.status===`failed`){await f(r,n.execution,t.executionId,t.error);return}}}function Dt(e,t){let{executionId:n,workflowId:r,filePath:i,coordinatorSessionId:a,sanitizedTriggerPayload:o,scope:s,workspaceRoot:c}=t,{workflowRunner:l,workflowAbortControllers:u,executionTasks:d,activeExecutions:p,config:m}=e,h=new AbortController;u.set(n,h);let g={source:{kind:`path`,path:i},executionId:n,workflowId:r,triggerPayload:o,inputs:{},config:{},scope:s,busUrl:m.busUrl,busAuth:m.busAuth,context:e.resolveWorkflowContext(c),env:m.platformDefaults.env??{},coordinatorSessionId:a,cancelSubject:`workflow.${n}.cancel`,suspensionStrategy:`wait-in-process`};return Promise.resolve().then(()=>l.run(g,h.signal)).then(async t=>{if(t.status===`paused`){await Tt(e,t);return}await Et(e,t)}).catch(async t=>{if(h.signal.aborted){await wt(e,n,h.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner cancellation for ${n}:`,e)});return}let r=p.get(n);if(r){let i=t instanceof Error?t.message:String(t);await f(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner boot failure for ${n}:`,e)})}}).finally(()=>{u.delete(n),d.delete(n),p.delete(n)})}function Ot(e,t){let{config:n}=e;return{source:t.source,...t.source.kind===`definition`?{definition:t.workflow}:{},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`}}function kt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=Ot(e,t),l=t.dispatchMetadata===void 0?void 0:{dispatchMetadata:t.dispatchMetadata};return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{if(t.status===`paused`){await Tt(e,t);return}await Et(e,t)}).catch(async t=>{if(s.signal.aborted){await wt(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await f(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function At(e,t,n={}){let r=jt(e,n);return{executionId:e.executionId,workflowId:e.workflowId,workflow:t,source:e.source,coordinatorSessionId:e.coordinatorSessionId,sanitizedTriggerPayload:e.triggerPayload,boundInputs:e.inputs,boundConfig:e.config??{},...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},scope:e.scope,workspaceRoot:e.context.repoPath,suspensionStrategy:e.suspensionStrategy,...r===void 0?{}:{dispatchMetadata:r}}}function jt(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const Mt=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function Nt(e){if(!e)return;let t={remainingBytes:65536},n={},r=Object.entries(e).slice(0,100);for(let[e,i]of r){if(t.remainingBytes<=0)break;let r=Pt(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function Pt(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if(Mt.test(e))return r.remainingBytes-=10,`[REDACTED]`;if(t===null)return r.remainingBytes-=4,null;if(typeof t==`string`){let e=t.slice(0,2e3);return r.remainingBytes-=e.length,e}if(typeof t==`number`||typeof t==`boolean`)return r.remainingBytes-=String(t).length,t;if(Array.isArray(t)){let i=[];for(let a of t.slice(0,100)){if(r.remainingBytes<=0)break;let t=Pt(e,a,n+1,r);t!==void 0&&i.push(t)}return i}if(typeof t==`object`){let e={},i=Object.entries(t).slice(0,100);for(let[t,a]of i){if(r.remainingBytes<=0)break;let i=Pt(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}function Ft(e,t,n){let r=t?.requirements?.capabilities??[];if(r.length!==0)return{run:(t,i)=>e.request(ce.dispatch,{config:t,requirements:{customCapabilities:r},...n===void 0?{}:{metadata:n}},{signal:i})}}function It(e,t){let n=Ft(e.bus,t.executionHints,t.dispatchMetadata);return n===void 0?e.workflowRunner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):kt(e.buildRunnerTaskDeps(e.workflowRunner),t):kt(e.buildRunnerTaskDeps(n),t)}async function Lt(e,t){try{await e.emit(n.execution.started,t)}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function Rt(e,t){await e.request(T.close,{sessionId:t}).catch(e=>{console.error(`[WorkflowExecutor] Failed to close coordinator session "${t}" after launch failure:`,e)})}function zt(e,t,n,r,i,a,o,s,c){let l={id:t,workflowId:n.id,coordinatorSessionId:r,status:`running`,inputs:i,config:a,startedAt:Date.now(),triggerPayload:o,scope:s};return e.set(t,{execution:l,workflow:n,runContext:c,runtimeHandlers:new Map}),l}async function Bt(e,t,n){await e.request(g.setExecutionStart,{execution:t,runContext:n})}function Vt(e,t){let n=e?.source;if(n===void 0)return;let r=ue.parse(n);return r.kind===`path`&&!C(r.path)?{...r,path:w(t,r.path)}:r}function Ht(e,t,n){return Vt(t,n)??{kind:`definition`,workflowId:e}}async function Ut(e,t,n,r){return e.set(t,n),await r,t}async function Wt(e,t){let{workflow:n}=await e.request(g.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}function Gt(e,t){if(e===void 0&&t===void 0)return;let n=[...new Set([...e?.capabilities??[],...t?.capabilities??[]])];return{...e,...t,...n.length>0&&{capabilities:n}}}function Kt(e,t){if(e===void 0&&t===void 0)return;let n=Gt(e?.requirements,t?.requirements),r=e?.providers!==void 0||t?.providers!==void 0?{...e?.providers,...t?.providers}:void 0;return{...e,...t,...n!==void 0&&{requirements:n},...r!==void 0&&{providers:r}}}function qt(e){return{...e,input:e.input===void 0?{}:e.input,config:e.config??{}}}async function Jt(e,t,n,r){let{sessionId:i}=await e.request(T.create,{parentSessionId:t,branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function Yt(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{input:o,config:s,parentSessionId:c,triggerPayload:l,artifactRef:u,executionHints:d,scopeOverride:f}=qt(n),p=await Wt(r,t),m=h(`wfx`),g=Nt(l),_=xt(p,o),v=St(p,s),y=f??p.scope,b=Kt(p.executionHints,d),x=await e.resolveExecutionWorkspaceRoot(c),S=Ht(t,b,x),C=await Jt(r,c,p.name,x),w=!1;try{let n=e.buildRunContext({executionId:m,workflowId:t,coordinatorSessionId:C,source:S,...S.kind===`definition`?{definitionSnapshot:p}:{},inputs:_,config:v,scope:y,triggerPayload:g??{},...u===void 0?{}:{artifactRef:u},...b===void 0?{}:{executionHints:b},workspaceRoot:x}),o=zt(i,m,p,C,_,v,g,y,n);await Bt(r,o,n);let s=o.startedAt,c=Lt(r,{executionId:m,workflowId:t,coordinatorSessionId:C,startedAt:s}),l=It(e,{executionId:m,workflowId:t,workflow:p,source:S,coordinatorSessionId:C,sanitizedTriggerPayload:g??{},boundInputs:_,boundConfig:v,scope:y,...u===void 0?{}:{artifactRef:u},...b===void 0?{}:{executionHints:b},workspaceRoot:x,suspensionStrategy:n.suspensionStrategy});return w=!0,Ut(a,m,l,c)}catch(e){throw w||(i.delete(m),a.delete(m),await Rt(r,C)),e}}function Xt(e,t,n,r,i){e.set(t.id,{execution:t,workflow:{id:t.workflowId,name:n,scope:r,root:{id:`${t.workflowId}-root`,type:`sequence`,nodes:[]}},runContext:i,runtimeHandlers:new Map})}async function Zt(e,t,n={}){let{bus:r,config:i,activeExecutions:a,executionTasks:o}=e,{triggerPayload:s,scopeOverride:c}=n,l=h(`wfx`),u=Nt(s),d=c??{type:`global`},f=i.platformDefaults.cwd,{sessionId:p}=await r.request(T.create,{branchKind:`coordinator`,title:`Workflow: ${t}`,targetWorkingDirectory:f}),m=l,g={id:l,workflowId:m,coordinatorSessionId:p,status:`running`,inputs:{},config:{},startedAt:Date.now(),triggerPayload:u,scope:d},_=!1;try{let{workflowRunner:n}=e;if(n===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);let i=e.buildRunContext({executionId:l,workflowId:m,coordinatorSessionId:p,source:{kind:`path`,path:t},inputs:{},config:{},scope:d,triggerPayload:u??{},workspaceRoot:f});await Bt(r,g,i),Xt(a,g,t,d,i);let s=Lt(r,{executionId:l,workflowId:m,coordinatorSessionId:p,startedAt:g.startedAt}),c=Dt(e.buildRunnerTaskDeps(n),{executionId:l,workflowId:m,filePath:t,coordinatorSessionId:p,sanitizedTriggerPayload:u??{},scope:d,workspaceRoot:f});return _=!0,Ut(o,l,c,s)}catch(e){throw _||(a.delete(l),o.delete(l),await Rt(r,p)),e}}var Qt=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(g.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:n}=await this.bus.request(g.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function $t(e){if(e!==void 0)return se.parse(e)}function en(e){if(e!==void 0)return oe.parse(e)}function tn(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${Se.homedir()}/.makaio`,os:bt(process.platform),arch:process.arch}}function nn(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{packages:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,context:tn(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function rn(e){return e?.status===`paused`}function an(e){return e?.status===`waiting`}async function on(e,t,n,r,i,a,o){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(g.restorePausedGateResumeState,{execution:i,gate:a})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function sn(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(g.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function cn(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function ln(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(g.getGateInstance,t);return an(n)?n:null}let{gates:n}=await e.request(g.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}var un=class extends me{static storage={drizzle:q};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...s,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new Qt(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of _t(this.bus))this.addCleanup(e);for(let e of vt(this.bus,()=>this.triggerTypeRegistry))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await o(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>tn(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(T.get,{sessionId:e});return t?.targetWorkingDirectory??this.config.platformDefaults.cwd}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>nn(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(n.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload,l=typeof r==`object`&&r&&!Array.isArray(r)?r:{};try{let r=await Yt(this.buildStartDeps(),t,{input:$t(n),config:l,parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:en(c),scopeOverride:s});e.setResult({executionId:r})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(n.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,triggerPayload:n,scope:r}=e.payload;try{let i=await Zt(this.buildStartDeps(),t,{triggerPayload:n,scopeOverride:r});e.setResult({executionId:i})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(n.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(de(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??E);let i=await o(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await o(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(n.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a}=e.payload,o=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a});e.setResult({accepted:o})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(n.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(n.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(g.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(cn(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let n=new AbortController;this.workflowAbortControllers.set(e,n);try{let r;try{let a=await d({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),o=new i(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,a,{context:t.runContext.context,env:t.runContext.env}),s=o.buildExpressionContext();r=await _(t.workflow.root,o,s)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await o(this.buildFinalizerDeps(),e,E);return}let i=r instanceof Error?r.message:String(r);await f(this.buildFinalizerDeps(),t.execution,e,i);return}let a=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await o(a,e,E):r.status===`failed`?await f(a,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(g.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await v(a,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{execution:t}=await this.bus.request(g.getExecution,{executionId:e.executionId});if(!rn(t))return!1;let n=await ln(this.bus,{executionId:e.executionId,nodeId:e.gateId,frameId:e.frameId});if(n===null||!m(e.gateId,n.schema,e.resumeData).valid)return!1;let{runContext:r}=await this.bus.request(g.getRunContext,{executionId:e.executionId});if(r===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e.executionId}`);await sn(this.bus,r);let i=e.action===`reject`?`rejected`:`resumed`,{accepted:a}=await this.bus.request(g.resolveWaitingGateInstance,{gate:{...n,status:i,resumeData:e.resumeData,resolvedAt:Date.now()}});if(!a)return!1;try{await this.resumePausedExecution(t.id)}catch(r){throw await on(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,t,n,e.gateId),r}return this.gateTimeoutScheduler.clear(e.executionId,e.gateId,n.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(g.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let n=t.definitionSnapshot??(await this.bus.request(g.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:r}=await this.bus.request(g.getExecution,{executionId:e});if(r===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(r.status!==`paused`)return!1;await sn(this.bus,t),await this.bus.request(g.setExecution,{execution:{...r,status:`running`}}),this.activeExecutions.set(e,{execution:{...r,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map});let i=At(t,n,{resume:!0}),a=It(this.buildStartDeps(),i).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,a),!0}};function dn(e,t){try{return xe(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function fn(e){let t=e.indexOf(`.`),n=e.indexOf(`:`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function pn(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var mn=class{bus;cleanupFns=[];initialized=!1;triggerIndex=new Map;subscribedNamespaces=new Set;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(D.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(D.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(D.definition.deleted,e=>{this.removeWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),!1)}getTestState(){return{initialized:this.initialized,cleanupFns:[...this.cleanupFns],subscribedNamespaces:new Set(this.subscribedNamespaces)}}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(g.list,{});for(let t of e)this.indexWorkflow(t)}indexWorkflow(e){let t=e.triggers??[],n=[];for(let r of t){if(r.type!==`bus-event`)continue;let t=typeof r.filterExpression==`string`?dn(r.filterExpression,e.id):void 0;typeof r.filterExpression==`string`&&t===void 0||(n.push({workflowId:e.id,subject:r.subject,filter:r.filter,compiledFilterExpr:t}),this.ensureNamespaceSubscribed(fn(r.subject)))}n.length>0&&this.triggerIndex.set(e.id,n)}removeWorkflow(e){this.triggerIndex.delete(e)}ensureNamespaceSubscribed(e){if(this.subscribedNamespaces.has(e))return;let t=pn(e),n=this.bus.on(t,e=>{if(e.isRequest)return;let t=typeof e.payload==`object`&&e.payload!==null?e.payload:{};this.handleBusEvent(e.subject,t)});this.cleanupFns.push(n),this.subscribedNamespaces.add(e)}handleBusEvent(e,t){for(let n of this.triggerIndex.values())for(let r of n)if(te(e,r.subject)&&!(r.filter&&!ee(t,r.filter))){if(r.compiledFilterExpr){let n;try{n=r.compiledFilterExpr.evalSync({payload:t})}catch(n){console.error(`[BusEventTriggerEvaluator] filterExpression eval failed for workflow "${r.workflowId}" on subject "${e}" payload keys: [${Object.keys(t).join(`, `)}]`,n);continue}if(!n)continue}this.bus.request(D.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function J(e,t,n,r,i,a,o,s){return J.fromTZ(J.tp(e,t,n,r,i,a,o),s)}J.fromTZISO=(e,t,n)=>J.fromTZ(gn(e,t),n),J.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=hn(e.tz,n),i=new Date(n.getTime()-r),a=hn(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=hn(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},J.toTZ=function(e,t){let n=e.toLocaleString(`en-US`,{timeZone:t}).replace(/[\u202f]/,` `),r=new Date(n);return{y:r.getFullYear(),m:r.getMonth()+1,d:r.getDate(),h:r.getHours(),i:r.getMinutes(),s:r.getSeconds(),tz:t}},J.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function hn(e,t=new Date){let n=t.toLocaleString(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).split(` `).slice(-1)[0],r=t.toLocaleString(`en-US`).replace(/[\u202f]/,` `);return Date.parse(`${r} GMT`)-Date.parse(`${r} ${n}`)}function gn(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`minitz: Invalid ISO8601 passed to parser.`);let r=e.substring(9);return e.includes(`Z`)||r.includes(`-`)||r.includes(`+`)?J.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):J.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}J.minitz=J;var _n=32,Y=31|_n,vn=[1,2,4,8,16],yn=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(e,t){this.pattern=e,this.timezone=t,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.replace(/\s+/g,` `).split(` `);if(e.length<5||e.length>6)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five or six space separated parts are required.`);if(e.length===5&&e.unshift(`0`),e[3].indexOf(`L`)>=0&&(e[3]=e[3].replace(`L`,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.replaceAlphaDays(e[5])),e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0){let t=new Z(new Date,this.timezone).getDate(!0);e[0]=e[0].replace(`?`,t.getSeconds().toString()),e[1]=e[1].replace(`?`,t.getMinutes().toString()),e[2]=e[2].replace(`?`,t.getHours().toString()),this.starDOM||(e[3]=e[3].replace(`?`,t.getDate().toString())),e[4]=e[4].replace(`?`,(t.getMonth()+1).toString()),this.starDOW||(e[5]=e[5].replace(`?`,t.getDay().toString()))}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1),this.partToArray(`dayOfWeek`,e[5],0,Y),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth;if(t===``&&!a)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let o=t.split(`,`);if(o.length>1)for(let t=0;t<o.length;t++)this.partToArray(e,o[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=parseInt(i[0],10)+n;if(isNaN(a))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,a,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`&&(t<0||t>=12))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t);this[e][t]=n}handleRangeWithStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);if(isNaN(l))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(u))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(isNaN(d))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(d===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(d>this[t].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[t].length+`)`);if(l>u)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}return[n,r]}handleRange(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;if(isNaN(o))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(o>s)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);a[0]===``&&(a[0]=`*`);let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(s===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(s>this[t].length)throw TypeError(`CronPattern: Syntax error, max steps for part is (`+this[t].length+`)`);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();return t===`@yearly`||t===`@annually`?`0 0 1 1 *`:t===`@monthly`?`0 0 1 * *`:t===`@weekly`?`0 0 * * 0`:t===`@daily`?`0 0 * * *`:t===`@hourly`?`0 * * * *`:e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|_n;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|vn[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},bn=[31,28,31,30,31,30,31,31,30,31,30,31],X=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Z=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t===void 0)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&Y&&vn[a-1]&r)return!0;if(r&_n){let r=new Date(Date.UTC(e,t+1,0)).getUTCDate();for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else{let t=J.toTZ(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.day>bn[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=J.fromTZISO(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(J.fromTZISO(e,this.tz))}findNext(e,t,n,r){let i=this[t],a;n.lastDayOfMonth&&(a=this.month===1?new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate():bn[this.month]);let o=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let s=this[t]+r;s<n[t].length;s++){let c=n[t][s];if(t===`day`&&n.lastDayOfMonth&&s-r==a&&(c=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(o+(s-r-1))%7];if(t&&t&Y)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,s-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);e.legacyMode&&!n.starDOM?c||=t:c&&=t}if(c)return this[t]=s-r,i===this[t]?1:2}return 3}recurse(e,t,n){let r=this.findNext(t,X[n][0],e,X[n][2]);if(r>1){let i=n+1;for(;i<X.length;)this[X[i][0]]=-X[i][2],i++;if(r===3)return this[X[n][1]]++,this[X[n][0]]=-X[n][2],this.apply(),this.recurse(e,t,0);if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=X.length?this:this.year>=3e3?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):J.fromTZ(J.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xn(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode=e.legacyMode===void 0?!0:e.legacyMode,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.startAt&&=new Z(e.startAt,e.timezone),e.stopAt&&=new Z(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);return e}function Q(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function Sn(e){return Q(e)}function Cn(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var wn=30*1e3,$=[],Tn=class{name;options;_states;fn;constructor(e,t,n){let r,i;if(Q(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(Q(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=xn(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new yn(`* * * * *`)},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Z(e,this.options.timezone||this.options.utcOffset):this._states.pattern=new yn(e,this.options.timezone),this.name){if($.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);$.push(this)}return i!==void 0&&Sn(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?t.getDate(!1):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=[],r=t||this._states.currentRun||void 0;for(;e--&&(r=this.nextRun(r));)n.push(r);return n}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Z||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Z(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=$.indexOf(this);e>=0&&$.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>wn&&(t=wn),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&Cn(this._states.currentTimeout),this)}async _trigger(e){if(this._states.blocking=!0,this._states.currentRun=new Z(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){Q(this.options.catch)&&this.options.catch(e,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Z(e,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&Q(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Z(e,this.options.timezone||this.options.utcOffset),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Z(e,this.options.timezone||this.options.utcOffset);return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_calculatePreviousRun(e,t){let n=new Z(void 0,this.options.timezone||this.options.utcOffset),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Z(r,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function En(e,t){return`${e}:${t}`}function Dn(e){return e??`UTC`}var On=class{bus;cleanupFns=[];initialized=!1;jobs=new Map;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(D.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(D.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(D.definition.deleted,e=>{this.unscheduleWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),!1)}activeJobCount(){return this.jobs.size}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(g.list,{});for(let t of e)this.scheduleWorkflow(t)}scheduleWorkflow(e){if(e.scope.type===`global`)return;let t=e.triggers??[];for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==`cron`)continue;let i=En(e.id,n);this.stopJob(i);try{let t=Dn(r.timezone),a=new Tn(r.schedule,{timezone:t},()=>{this.fireTrigger(e.id,n)});this.jobs.set(i,{workflowId:e.id,triggerIndex:n,job:a})}catch(t){console.warn(`[CronTriggerEvaluator] Skipping invalid cron trigger key="${i}" workflowId="${e.id}" triggerIndex=${n} schedule="${r.schedule}" timezone="${r.timezone??`UTC`}"`,t)}}}unscheduleWorkflow(e){for(let[t,n]of this.jobs)n.workflowId===e&&(n.job.stop(),this.jobs.delete(t))}stopJob(e){let t=this.jobs.get(e);t&&(t.job.stop(),this.jobs.delete(e))}stopAllJobs(){for(let e of this.jobs.values())e.job.stop();this.jobs.clear()}fireTrigger(e,t){this.bus.request(D.start,{workflowId:e,triggerPayload:{firedAt:Date.now(),triggerIndex:t}}).catch(n=>{console.error(`[CronTriggerEvaluator] Failed to start workflow "${e}" for cron trigger index ${t}:`,n)})}},kn=class extends me{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new un(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new mn(e),this.cronTriggerEvaluator=new On(e)}get executor(){return this.workflowExecutor}get cronTriggers(){return this.cronTriggerEvaluator}setTriggerTypeRegistry(e){this.workflowExecutor.setTriggerTypeRegistry(e)}getTriggerTypeRegistry(){return this.workflowExecutor.getTriggerTypeRegistry()}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.busEventTriggerEvaluator.init(),await this.cronTriggerEvaluator.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.cronTriggerEvaluator.destroy(),()=>this.busEventTriggerEvaluator.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const An=pe(`makaio.workflow-engine`);function jn(e){return{name:An.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[fe(Ce.name)],critical:!0,namespaces:[le,c],storage:{registerHandlers:be(q)},create:t=>new kn(t.bus,e)}}const Mn=jn();export{un as a,kn as i,jn as n,q as o,Mn as r,An as t};
@@ -1,8 +0,0 @@
1
- import{o as e,t}from"./chunk-DTipWd-i.mjs";import{n,r,t as i}from"./fast-uri-BF2Xuiop.mjs";import{z as a}from"zod";import{execFile as o}from"node:child_process";import{isAbsolute as s,relative as c,resolve as l}from"node:path";import{realpathSync as u}from"node:fs";import{localSubject as d}from"@makaio/framework/core";import{NoHandlerError as f}from"@makaio/framework/bus";import{ArtifactSubjects as p,ExecutionLinkSchema as m,ExecutionListQuerySchema as h,ExecutionStatusSchema as g,SpanRecordSchema as _,SubagentSubjects as v,WorkflowDefinitionSchema as y,WorkflowExecutionSchema as b,WorkflowFrameStateSchema as x,WorkflowGateInstanceSchema as S,WorkflowListQuerySchema as C,WorkflowRunContextSchema as w,WorkflowSchemas as T,WorkflowSubjects as E,WorkflowSubjects as D,createStepCancelSubject as O}from"@makaio/framework/contracts";import{index as k,integer as A,primaryKey as j,real as M,sqliteTable as N,text as P,uniqueIndex as ee}from"drizzle-orm/sqlite-core";import{sql as F}from"drizzle-orm";import{createStorageNamespaceDefinition as I}from"@makaio/framework/storage";import{evaluateSync as L,resolveTemplate as R}from"@makaio/framework/expression";import*as te from"node:os";function ne(){return{scopeType:P(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().$type(),scopeKind:P(`scope_kind`).notNull().default(``),scopeId:P(`scope_id`).notNull().default(``)}}const z=N(`workflow_definitions`,{id:P(`id`).primaryKey(),name:P(`name`).notNull(),description:P(`description`),root:P(`root`,{mode:`json`}).$type().notNull(),inputSchema:P(`input_schema`,{mode:`json`}).$type(),configSchema:P(`config_schema`,{mode:`json`}).$type(),outputSchema:P(`output_schema`,{mode:`json`}).$type(),artifact:P(`artifact`,{mode:`json`}).$type(),triggers:P(`triggers`,{mode:`json`}).$type(),...ne(),createdAt:A(`created_at`).notNull(),updatedAt:A(`updated_at`).notNull(),canvasLayout:P(`canvas_layout`,{mode:`json`}).$type(),source:P(`source`,{mode:`json`}).$type(),executionHints:P(`execution_hints`,{mode:`json`}).$type()},e=>[ee(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),k(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)]),B=N(`workflow_executions`,{id:P(`id`).primaryKey(),workflowId:P(`workflow_id`).notNull(),coordinatorSessionId:P(`coordinator_session_id`),status:P(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),inputs:P(`inputs`,{mode:`json`}).$type(),error:P(`error`),reason:P(`reason`),startedAt:A(`started_at`).notNull(),completedAt:A(`completed_at`),triggerPayload:P(`trigger_payload`,{mode:`json`}).$type(),...ne()},e=>[k(`idx_workflow_executions_status`).on(e.status),k(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),k(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt)]),re=N(`workflow_execution_frames`,{frameId:P(`frame_id`).primaryKey(),executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),nodeId:P(`node_id`).notNull(),nodeType:P(`node_type`).notNull().$type(),path:P(`path`,{mode:`json`}).$type().notNull(),parentFrameId:P(`parent_frame_id`),status:P(`status`).notNull().default(`pending`).$type(),attempt:A(`attempt`).notNull().default(0),iteration:A(`iteration`),branchKey:P(`branch_key`),output:P(`output`,{mode:`json`}).$type(),outputPresent:A(`output_present`,{mode:`boolean`}).notNull().default(!1),error:P(`error`),startedAt:A(`started_at`),completedAt:A(`completed_at`)},e=>[k(`idx_workflow_execution_frames_execution`).on(e.executionId),k(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)]),ie=N(`workflow_gate_instances`,{id:P(`id`).primaryKey(),executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),nodeId:P(`node_id`).notNull(),frameId:P(`frame_id`).notNull(),schema:P(`schema`,{mode:`json`}).$type().notNull(),prompt:P(`prompt`),status:P(`status`).notNull().default(`waiting`).$type(),autoAction:P(`auto_action`,{enum:[`approve`,`reject`]}).notNull().default(`reject`),timeoutMs:A(`timeout_ms`),resumeData:P(`resume_data`,{mode:`json`}).$type(),resumeDataPresent:A(`resume_data_present`,{mode:`boolean`}).notNull().default(!1),createdAt:A(`created_at`).notNull(),resolvedAt:A(`resolved_at`)},e=>[k(`idx_workflow_gate_instances_execution`).on(e.executionId),k(`idx_workflow_gate_instances_frame`).on(e.frameId)]),ae=N(`workflow_step_spans`,{executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),frameId:P(`frame_id`).notNull(),stepId:P(`step_id`).notNull(),stepType:P(`step_type`).notNull(),status:P(`status`).$type().notNull(),startedAt:A(`started_at`),completedAt:A(`completed_at`),durationMs:A(`duration_ms`),inputTokens:A(`input_tokens`),outputTokens:A(`output_tokens`),estimatedCost:M(`estimated_cost`),toolCallCount:A(`tool_call_count`),input:P(`input`),output:P(`output`)},e=>[j({columns:[e.executionId,e.frameId]}),k(`idx_workflow_step_spans_status`).on(e.status)]),oe=N(`workflow_execution_links`,{sourceExecutionId:P(`source_execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),targetExecutionId:P(`target_execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),linkType:P(`link_type`).$type().notNull(),metadata:P(`metadata`,{mode:`json`}).$type()},e=>[j({columns:[e.sourceExecutionId,e.targetExecutionId]}),k(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]),se=N(`workflow_run_contexts`,{executionId:P(`execution_id`).primaryKey(),workflowId:P(`workflow_id`).notNull(),coordinatorSessionId:P(`coordinator_session_id`).notNull(),sourceKind:P(`source_kind`).notNull(),sourcePath:P(`source_path`),sourceFilename:P(`source_filename`),sourceCode:P(`source_code`),definitionSnapshot:P(`definition_snapshot`,{mode:`json`}).$type(),workerManifest:P(`worker_manifest`,{mode:`json`}).$type().notNull(),inputs:P(`inputs`,{mode:`json`}).$type(),config:P(`config`,{mode:`json`}).$type().notNull().default(F`'{}'`),triggerPayload:P(`trigger_payload`,{mode:`json`}).$type().notNull(),artifactRef:P(`artifact_ref`,{mode:`json`}).$type(),executionHints:P(`execution_hints`,{mode:`json`}).$type(),dispatchMetadata:P(`dispatch_metadata`,{mode:`json`}).$type(),scopeType:P(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().default(`global`).$type(),scopeKind:P(`scope_kind`).notNull().default(``),scopeId:P(`scope_id`).notNull().default(``),cancelSubject:P(`cancel_subject`).notNull(),context:P(`context`,{mode:`json`}).$type().notNull(),env:P(`env`,{mode:`json`}).$type().notNull(),createdAt:A(`created_at`).notNull(),suspensionStrategy:P(`suspension_strategy`).$type()},e=>[k(`idx_run_contexts_workflow`).on(e.workflowId)]),ce=N(`worklog_summaries`,{executionId:P(`execution_id`).primaryKey(),workflowId:P(`workflow_id`).notNull(),workflowName:P(`workflow_name`),status:P(`status`,{enum:[`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]}).notNull(),startedAt:A(`started_at`).notNull(),completedAt:A(`completed_at`),durationMs:A(`duration_ms`),totalInputTokens:A(`total_input_tokens`),totalOutputTokens:A(`total_output_tokens`),totalEstimatedCost:M(`total_estimated_cost`),error:P(`error`),failedNodeId:P(`failed_node_id`)},e=>[k(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),k(`idx_worklog_summaries_status`).on(e.status)]),le=N(`worklog_frame_entries`,{frameId:P(`frame_id`).primaryKey(),executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),nodeId:P(`node_id`).notNull(),nodeType:P(`node_type`).notNull().$type(),path:P(`path`,{mode:`json`}).$type().notNull(),status:P(`status`,{enum:[`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]}).notNull(),attempt:A(`attempt`).notNull().default(0),iteration:A(`iteration`),branchKey:P(`branch_key`),startedAt:A(`started_at`),completedAt:A(`completed_at`),durationMs:A(`duration_ms`),inputTokens:A(`input_tokens`),outputTokens:A(`output_tokens`),estimatedCost:M(`estimated_cost`),error:P(`error`)},e=>[k(`idx_worklog_frame_entries_execution`).on(e.executionId)]),ue=N(`worklog_artifact_writes`,{id:P(`id`).primaryKey(),executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),frameId:P(`frame_id`).notNull(),nodeId:P(`node_id`).notNull(),artifact:P(`artifact`,{mode:`json`}).$type().notNull(),revision:P(`revision`),writtenAt:A(`written_at`).notNull()},e=>[k(`idx_worklog_artifact_writes_execution`).on(e.executionId)]),de=N(`worklog_gate_events`,{id:P(`id`).primaryKey(),executionId:P(`execution_id`).notNull().references(()=>B.id,{onDelete:`cascade`}),nodeId:P(`node_id`).notNull(),frameId:P(`frame_id`).notNull(),status:P(`status`,{enum:[`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]}).notNull().$type(),prompt:P(`prompt`),openedAt:A(`opened_at`).notNull(),resolvedAt:A(`resolved_at`),resumeData:P(`resume_data`,{mode:`json`}).$type()},e=>[k(`idx_worklog_gate_events_execution`).on(e.executionId),k(`idx_worklog_gate_events_status`).on(e.status)]),fe=a.object({sourceExecutionId:a.string().min(1).optional(),targetExecutionId:a.string().min(1).optional()}).refine(e=>e.sourceExecutionId!==void 0||e.targetExecutionId!==void 0,{message:`Either sourceExecutionId or targetExecutionId is required.`}),pe=a.object({executionId:a.string().min(1),status:g.optional(),error:a.string().nullable().optional(),reason:a.string().nullable().optional(),completedAt:a.number().nullable().optional()}),me=I(`workflow`,{schemas:{get:{request:a.object({id:a.string()}),response:a.object({workflow:y.nullable()})},set:{request:a.object({workflow:y}),response:a.object({id:a.string()})},delete:{request:a.object({id:a.string()}),response:a.object({deleted:a.boolean()})},list:{request:C,response:a.object({workflows:a.array(y)})},getExecution:{request:a.object({executionId:a.string()}),response:a.object({execution:b.nullable()})},setExecution:{request:a.object({execution:b}),response:a.object({id:a.string()})},setExecutionStart:{request:a.object({execution:b,runContext:w}),response:a.object({id:a.string(),executionId:a.string()})},updateExecution:{request:pe,response:a.object({success:a.boolean()})},cancelPausedExecution:{request:a.object({executionId:a.string().min(1),completedAt:a.number(),reason:a.string().optional()}),response:a.object({cancelled:a.boolean(),gates:a.array(S.extend({status:a.literal(`cancelled`)}))})},listExecutions:{request:h,response:a.object({executions:a.array(b)})},setFrame:{request:a.object({executionId:a.string().min(1),frame:x}),response:a.object({frameId:a.string()})},getFrame:{request:a.object({frameId:a.string().min(1)}),response:a.object({frame:x.nullable()})},listFrames:{request:a.object({executionId:a.string().min(1)}),response:a.object({frames:a.array(x)})},setGateInstance:{request:a.object({gate:S}),response:a.object({id:a.string()})},resolveWaitingGateInstance:{request:a.object({gate:S.extend({status:a.enum([`resumed`,`rejected`])})}),response:a.object({accepted:a.boolean()})},restorePausedGateResumeState:{request:a.object({execution:b.extend({status:a.literal(`paused`)}),gate:S.extend({status:a.literal(`waiting`)})}),response:a.object({executionId:a.string(),gateId:a.string()})},getGateInstance:{request:a.object({executionId:a.string().min(1),nodeId:a.string().min(1),frameId:a.string().min(1).optional()}),response:a.object({gate:S.nullable()})},listGateInstances:{request:a.object({executionId:a.string().min(1)}),response:a.object({gates:a.array(S)})},listPausedGateTimeouts:d({request:a.object({}),response:a.object({gates:a.array(S)})}),setSpan:{request:a.object({span:_}),response:a.object({id:a.string()})},listSpans:{request:a.object({executionId:a.string()}),response:a.object({spans:a.array(_)})},setExecutionLink:{request:a.object({link:m}),response:a.object({id:a.string()})},listExecutionLinks:{request:fe,response:a.object({links:a.array(m)})},setRunContext:d({request:a.object({runContext:w}),response:a.object({executionId:a.string()})}),getRunContext:d({request:a.object({executionId:a.string().min(1)}),response:a.object({runContext:w.nullable()})})},extensions:{drizzle:{workflowDefinitions:z,workflowExecutions:B,workflowExecutionFrames:re,workflowGateInstances:ie,workflowStepSpans:ae,workflowExecutionLinks:oe,workflowRunContexts:se,worklogSummaries:ce,worklogFrameEntries:le,worklogArtifactWrites:ue,worklogGateEvents:de}}}),V=me.subjects,he={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4};async function ge(e,t,n){if(!(await e.request(V.updateExecution,{executionId:t.id,status:n.status,error:n.error,reason:n.reason,completedAt:n.completedAt})).success)throw Error(`Workflow execution not found: ${t.id}`)}async function _e(e,t,n,r){t.status=`completed`,t.completedAt=Date.now();try{await ge(e.bus,t,{status:t.status,completedAt:t.completedAt}),await e.bus.emit(D.execution.completed,{executionId:n,workflowId:t.workflowId,totalDuration:t.completedAt-r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}async function ve(e,t,n,r,i){t.status=`failed`,t.error=r,t.completedAt=Date.now();try{await ge(e.bus,t,{status:t.status,error:t.error,completedAt:t.completedAt});try{await i?.()}catch(e){console.error(`[WorkflowFinalizer] Failed to run failure pre-emit hook:`,e)}await e.bus.emit(D.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:t.completedAt})}finally{e.activeExecutions.delete(n)}}function ye(e,t,n){let{activeRunnerSteps:r,bus:i}=e,a=`${t}:`;for(let[e,o]of r){if(!e.startsWith(a))continue;let r=e.slice(a.length);o.controller.abort(),i.emit(O(o.cancelSubject),{executionId:t,stepId:r,reason:n}).catch(t=>{console.error(`[WorkflowFinalizer] Failed to emit cancellation for ${e}:`,t)})}}async function be(e,t,n){let r=await e.bus.request(V.getExecution,{executionId:t});if(r.execution==null)return!1;let i=r.execution.workflowId;if(i===void 0)throw Error(`Paused execution ${t} is missing stored workflowId`);let a=Date.now(),{cancelled:o,gates:s}=await e.bus.request(V.cancelPausedExecution,{executionId:t,completedAt:a,reason:n});if(!o)return!1;for(let n of s)await e.bus.emit(D.gate.resolved,{executionId:t,stepId:n.nodeId,stepType:`gate`,frameId:n.frameId,source:`cancelled`}).catch(e=>{console.error(`[WorkflowFinalizer] Failed to emit cancelled gate resolution for ${n.frameId}:`,e)});return await e.bus.emit(D.execution.cancelled,{executionId:t,workflowId:i,reason:n,completedAt:a}),e.activeExecutions.delete(t),!0}async function xe(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return be(e,t,n);let{execution:i}=r;i.status=`cancelled`,i.reason=n,i.completedAt=Date.now();try{for(let[n,r]of e.shellAbortControllers)n.startsWith(`${t}:`)&&(r.abort(),e.shellAbortControllers.delete(n));ye(e,t,n),await ge(e.bus,i,{status:i.status,reason:n,completedAt:i.completedAt}),await e.bus.emit(D.execution.cancelled,{executionId:t,workflowId:i.workflowId,reason:n,completedAt:i.completedAt})}finally{e.activeExecutions.delete(t)}return!0}function Se(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ce(e,t,n){let r=e?R(e,n):t,i=l(t),a=l(s(r)?r:l(t,r)),o,d;try{o=u(i),d=u(a)}catch{return null}let f=c(process.platform===`win32`?o.toLowerCase():o,process.platform===`win32`?d.toLowerCase():d);return f===``||!f.startsWith(`..`)&&!s(f)?d:null}function we(e){return e instanceof Error&&(`code`in e||`killed`in e)}function Te(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function Ee(e){let{command:t,cwd:n,env:r,timeoutMs:i,signal:a}=e,s=Te(t);if(s===null)return Promise.reject(Error(`Shell step command is empty`));let c=t.slice(1);return new Promise((e,t)=>{let l=null,u=!1,d=o(s,c,{cwd:n,env:{...process.env,...r},timeout:0,maxBuffer:10*1024*1024,shell:!1},(n,r,i)=>{n?t(Object.assign(n,{stdout:r,stderr:i,aborted:u})):e({stdout:r,stderr:i})}),f=()=>{d.exitCode===null&&(d.kill(`SIGTERM`),l=setTimeout(()=>{d.exitCode===null&&d.kill(`SIGKILL`)},5e3))},p=setTimeout(()=>{f()},i);if(d.on(`close`,()=>{clearTimeout(p),l!==null&&clearTimeout(l)}),a){let e=()=>{u=!0,f()};a.aborted?e():(a.addEventListener(`abort`,e,{once:!0}),d.on(`close`,()=>a.removeEventListener(`abort`,e)))}})}async function De(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=Ce(t.cwd,n,r);if(a===null)return{status:`failed`,error:`Shell step cwd '${t.cwd}' is outside workspace root '${n}'`};let o=t.command.map(e=>R(e,r));if(Te(o)===null)return{status:`failed`,error:`Shell step command is empty`};let s=Object.fromEntries(Object.entries(t.env??{}).map(([e,t])=>[e,R(t,r)])),c=t.timeoutMs??3e5;try{let{stdout:e}=await Ee({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!we(e))return{status:`failed`,error:String(e)};let t=e.aborted===!0,n=!t&&(e.killed===!0||e.signal!=null);return{status:`failed`,error:t?`Command cancelled`:n?`Command timed out after ${c}ms`:e.stderr?.trim()||e.stdout?.trim()||e.message}}}function Oe(e){let t={};for(let[n,r]of Object.entries(e))r.status===`completed`?t[n]={status:`completed`,output:r.output}:r.status===`skipped`&&(t[n]={status:`skipped`});return t}function H(e){let t={...e,input:e.inputs,steps:e.frames};return{...t,ctx:t}}function ke(){return{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${te.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:{}}}function Ae(e){return{...e,path:[...e.path]}}function je(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function Me(e,t){let n=je(t.nodeType);if(n===void 0||t.status!==`running`&&t.status!==`completed`&&t.status!==`failed`&&t.status!==`skipped`)return;let r=t.startedAt!==void 0&&t.completedAt!==void 0?Math.max(0,t.completedAt-t.startedAt):void 0;return{executionId:e,frameId:t.frameId,stepId:t.nodeId,stepType:n,status:t.status,...t.startedAt===void 0?{}:{startedAt:t.startedAt},...t.completedAt===void 0?{}:{completedAt:t.completedAt},...r===void 0?{}:{durationMs:r},...t.output===void 0?{}:{output:JSON.stringify(t.output)}}}var Ne=class e{executionId;workflowId;definition;execution;runtimeHandlers;bus;signal;frameRegistry;framePersistenceTasks=new Map;artifactBinding;constructor(e,t,n,r,i,a,o,s,c,l=ke(),u={}){this.executionId=e,this.workflowId=t,this.definition=n,this.execution=r,this.runtimeHandlers=i,this.bus=a,this.signal=o,this.frameRegistry=s??new Map,this.artifactBinding=c,this.platformContext=l.context,this.env=l.env,this.suspensionStrategy=u.suspensionStrategy??`wait-in-process`,this.resumeFrames=u.resumeFrames}platformContext;env;suspensionStrategy;resumeFrames;withSignal(t){return new e(this.executionId,this.workflowId,this.definition,this.execution,this.runtimeHandlers,this.bus,t,this.frameRegistry,this.artifactBinding,{context:this.platformContext,env:this.env},{suspensionStrategy:this.suspensionStrategy,resumeFrames:this.resumeFrames})}buildExpressionContext(){return{inputs:this.execution.inputs,config:this.execution.config??{},trigger:this.execution.triggerPayload??{},frames:{},previousSteps:{}}}createFrame(e){let t=Se(`frm`),n=[...e.path,t],r={frameId:t,nodeId:e.nodeId,nodeType:e.nodeType,path:n,parentFrameId:e.parentFrameId,status:`pending`,attempt:0,iteration:e.iteration,branchKey:e.branchKey};return this.frameRegistry.set(t,r),this.persistFrame(r).catch(()=>void 0),r}async persistFrame(e,t={}){let n=t.requireFrameStorage===!0||this.suspensionStrategy!==`wait-in-process`,r=Ae(e),i=Me(this.executionId,r),a=(this.framePersistenceTasks.get(e.frameId)??Promise.resolve()).catch(()=>void 0).then(async()=>{n?await this.bus.request(V.setFrame,{executionId:this.executionId,frame:r}):await this.bus.requestOptional(V.setFrame,{executionId:this.executionId,frame:r}),i!==void 0&&await this.bus.requestOptional(V.setSpan,{span:i})}).catch(t=>{if(n)throw t;console.warn(`[RuntimeContext] Failed to persist frame ${e.frameId}:`,t)});this.framePersistenceTasks.set(e.frameId,a);try{await a}finally{this.framePersistenceTasks.get(e.frameId)===a&&this.framePersistenceTasks.delete(e.frameId)}}async updateFrame(e,t,n={}){let r=this.frameRegistry.get(e);if(!r)throw Error(`Frame not found: ${e}`);Object.assign(r,t),await this.persistFrame(r,n)}getFrame(e){return this.frameRegistry.get(e)}getFramesByNodeId(e){let t=[];for(let n of this.frameRegistry.values())n.nodeId===e&&t.push(n);return t.sort((e,t)=>(e.startedAt??0)-(t.startedAt??0))}async emitFrameStarted(e){try{await this.bus.emit(D.frame.started,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId,startedAt:e.startedAt})}catch(t){console.error(`[RuntimeContext] frame.started observer failed for ${e.frameId}:`,t)}}async emitFrameCompleted(e,t){try{await this.bus.emit(D.frame.completed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,output:e.output,duration:t,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.completed observer failed for ${e.frameId}:`,t)}}async emitFrameFailed(e,t,n){try{await this.bus.emit(D.frame.failed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,error:t,duration:n,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.failed observer failed for ${e.frameId}:`,t)}}};function Pe(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function Fe(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,context:n.context,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function Ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Le(e){if(e!=null){if(Ie(e)&&typeof e.kind==`string`&&typeof e.id==`string`)return{kind:e.kind,id:e.id};throw Error(`Artifact resolve expression must return an object with string kind and id fields.`)}}function Re(e){if(e!==void 0){if(Ie(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function ze(e){let{bindingOptions:t,binding:n,existingArtifactRef:r,executionId:i,scope:a,initialData:o,bus:s}=e,c=null;if(r!==void 0){let e=await s.request(p.query,{kind:r.kind,ids:[r.id],currentOnly:!0});if(e.artifacts.length>0)c=e.artifacts[0];else return}else c=(await s.request(p.create,{kind:n.kind,schemaVersion:n.schemaVersion,scope:a??n.scope,data:o??{},relations:[],actor:Pe(i)})).artifact;return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function Be(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=Fe(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:Le(L(o.resolve,s))),l=c===void 0&&o.create!==void 0?Re(L(o.create,s)):void 0,u=await ze({bindingOptions:{kind:o.kind,schemaVersion:o.schemaVersion,scope:o.scope,...o.resolve===void 0?{}:{resolve:o.resolve},...o.create===void 0?{}:{create:o.create},...o.statusPath===void 0?{}:{statusPath:o.statusPath},...i===void 0?{}:{schema:i}},binding:o,existingArtifactRef:c,executionId:n.id,scope:o.scope,initialData:l,bus:a});if(u===void 0)throw Error(`Workflow artifact binding could not be resolved for the configured artifact reference.`);return u}const Ve=new WeakMap;function He(e,t){let n=(Ve.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return Ve.set(e,n.then(()=>void 0,()=>void 0)),n}function Ue(e,t){switch(t.operation){case`set`:return t.data;case`merge`:return{...e,...t.data};case`append`:{let n={...e};for(let[r,i]of Object.entries(t.data)){let t=e[r];Array.isArray(t)&&Array.isArray(i)?n[r]=[...t,...i]:n[r]=i}return n}}}function We(e,t,n){let[r,...i]=t;if(i.length===0)return{...e,[r]:n};let a=e[r]!==null&&typeof e[r]==`object`&&!Array.isArray(e[r])?e[r]:{};return{...e,[r]:We(a,i,n)}}function Ge(e,t,n){return We(e,t.startsWith(`/`)?t.slice(1).split(`/`):t.split(`.`),n)}function Ke(e,t,n){if(n===`set`||n===`functional`)return[];let r=[];for(let n of Object.keys(t))e[n]!==t[n]&&r.push(`/${n}`);return r}async function qe(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=Ue(e,t),r=Ke(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function Je(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>He(r,async()=>{let a=r.current,{nextData:o,operationLabel:s,changedPaths:c}=await qe(a.data,e);if(r.zodSchema!==void 0){let e=r.zodSchema.safeParse(o);if(!e.success)throw Error(`Artifact data validation failed: ${e.error.message}`)}let l=await i.request(p.revise,{previous:{refClass:`artifact`,kind:a.kind,id:a.id,revision:a.revision},revision:{kind:a.kind,schemaVersion:r.schemaVersion,scope:a.scope,data:o,relations:a.relations,actor:Pe(t)}});r.current=l.artifact;let u=l.artifact.revision;return i.emit(E.artifact.updated,{executionId:t,frameId:n,artifactRef:{kind:l.artifact.kind,id:l.artifact.id},paths:c,operation:s,revision:u}).catch(e=>{console.error(`[ArtifactContext] Failed to emit artifact.updated event:`,e)}),u});return{data:a,updateArtifact:o,updateStatus:async e=>{if(r.statusPath===void 0)throw Error(`updateStatus() called but no statusPath is configured on the artifact binding. Set statusPath in the .artifact() builder call to use updateStatus().`);let t=r.statusPath;return o(n=>Ge(n,t,e))}}}async function Ye(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(D.resolveRole,{roleId:e.roleId});if(!r.handled)return{status:`failed`,error:e.unresolvedRoleError};let i=R(e.prompt,H(n));return Xe({...e,task:i,resolvedConfig:r.data},t)}async function Xe(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=await t.bus.requestOptional(v.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:tt(e.task,e.resolvedConfig,e.outputSchema)});if(!n.handled)return{status:`failed`,error:e.unavailableRuntimeError};let r=await Ze(e,t,n.data.subagentId,{attempts:5}),i=await nt(e,t,n.data.subagentId);return i===`aborted`?{status:`cancelled`}:(r||await Ze(e,t,n.data.subagentId,{attempts:1}),i.handled?t.signal.aborted||i.data.status===`cancelled`?{status:`cancelled`}:i.data.status===`completed`?{status:`completed`,output:i.data.result??null}:{status:`failed`,error:`${e.nodeLabel} '${e.nodeId}' subagent ${i.data.status}: ${i.data.error??`no result`}`}:{status:`failed`,error:e.unavailableAwaitError})}async function Ze(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await Qe(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(D.frame.sessionLinked,{executionId:t.executionId,frameId:e.frameId,sessionId:i}),!0)}catch(t){return console.warn(`[workflow-engine] Failed to emit frame.sessionLinked for frame '${e.frameId}' and subagent '${n}'`,t),!1}}async function Qe(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await $e(e,t);if(i===void 0||!i.handled)return;if(i.data.childSessionId!==void 0)return i.data.childSessionId;if(r<n-1&&!await et(e.signal,20))return}}async function $e(e,t){try{return await e.bus.requestOptional(v.getStatus,{subagentId:t},{timeout:25,signal:e.signal})}catch{return}}function et(e,t){return e.aborted?Promise.resolve(!1):new Promise(n=>{let r,i=t=>{r!==void 0&&(clearTimeout(r),r=void 0),e.removeEventListener(`abort`,a),n(t)},a=()=>i(!1);r=setTimeout(()=>i(!0),t),e.addEventListener(`abort`,a,{once:!0}),e.aborted&&i(!1)})}function tt(e,t,n){return{task:e,adapterName:t.adapterName,...t.model===void 0?{}:{model:t.model},...t.harnessId===void 0?{}:{harnessId:t.harnessId},...t.systemPrompt===void 0?{}:{systemPrompt:t.systemPrompt},...t.contextMode===void 0?{}:{contextMode:t.contextMode},...t.providerContext===void 0?{}:{providerContext:t.providerContext},...n===void 0?{}:{responseSchema:n}}}async function nt(e,t,n){if(t.signal.aborted)return await rt(e,t,n),`aborted`;let r=t.bus.requestOptional(v.await,{subagentId:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});if(t.signal.aborted)return await rt(e,t,n),`aborted`;let i,a=new Promise(e=>{i=()=>e(`aborted`),t.signal.addEventListener(`abort`,i,{once:!0})}),o=await Promise.race([r,a]);return i!==void 0&&t.signal.removeEventListener(`abort`,i),o===`aborted`&&await rt(e,t,n),o}async function rt(e,t,n){try{await t.bus.requestOptional(v.kill,{subagentId:n,reason:`Workflow execution '${t.executionId}' cancelled ${e.cancellationLabel} '${e.nodeId}'`})}catch(t){console.warn(`[workflow-engine] Best-effort subagent kill failed for '${n}' (${e.cancellationLabel} '${e.nodeId}')`,t)}}async function it(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=Oe(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return at(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?Je({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0;async function s(n){if(r===void 0){console.warn(`[station-node] updateProgress called without frameId for node '${e.id}'; skipping emit`);return}let i=T[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(D.execution.progress,i)}catch(t){console.error(`[station-node] execution.progress observer failed for ${e.id}:`,t)}}let c;try{c=await a({...t.platformContext,env:t.env,executionId:t.executionId,workflowId:t.workflowId,inputs:t.execution.inputs,config:t.execution.config??{},trigger:t.execution.triggerPayload??{},previousSteps:i,...n.item!==void 0&&{item:n.item},...n.index!==void 0&&{index:n.index},...n.previous!==void 0&&{previous:n.previous},signal:t.signal,...o!==void 0&&{artifact:o},bus:t.bus,updateProgress:s})}catch(e){return{status:`failed`,error:e instanceof Error?e.message:String(e)}}return{status:`completed`,output:c}}async function at(e,t,n,r){if(e.role===void 0)return{status:`failed`,error:`No handler registered for station node '${e.id}'`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return Ye({nodeId:e.id,nodeLabel:`Station node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unresolvedRoleError:`No runtime handler registered for station node '${e.id}', and role '${e.role}' could not be resolved`,unavailableRuntimeError:`Subagent runtime is not available for station node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await station node '${e.id}'`,cancellationLabel:`station`,...r===void 0?{}:{frameId:r}},t,n)}async function ot(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(D.resolveAgent,{agentId:e.agentId});if(!i.handled)return{status:`failed`,error:`Agent '${e.agentId}' could not be resolved for delegate-agent node '${e.id}'`};if(t.signal.aborted)return{status:`cancelled`};let a=ct(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return Xe({nodeId:e.id,nodeLabel:`Delegate-agent node`,task:a.task,resolvedConfig:i.data,...o===void 0?{}:{outputSchema:o},unavailableRuntimeError:`Subagent runtime is not available for delegate-agent node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-agent node '${e.id}'`,cancellationLabel:`delegate-agent`,...r===void 0?{}:{frameId:r}},t)}async function st(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return Ye({nodeId:e.id,nodeLabel:`Delegate-role node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unresolvedRoleError:`Role '${e.role}' could not be resolved for delegate-role node '${e.id}'`,unavailableRuntimeError:`Subagent runtime is not available for delegate-role node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-role node '${e.id}'`,cancellationLabel:`delegate-role`,...r===void 0?{}:{frameId:r}},t,n)}function ct(e,t){try{let n=H(t);return{status:`completed`,task:lt(e.inputExpression===void 0?n:L(e.inputExpression,n))}}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`delegate-agent node '${e.id}': input expression evaluation failed: ${n}`}}}function lt(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function ut(e,t,n,r){try{let i=L(n,H(r));return Array.isArray(i)?i:{status:`failed`,error:`${t} node '${e}': collection expression did not resolve to an array (got ${typeof i})`}}catch(n){return{status:`failed`,error:`${t} node '${e}': collection expression evaluation failed: ${n instanceof Error?n.message:String(n)}`}}}function dt(e,t,n){for(let r of[...e.nodes].reverse()){let e=n.getFramesByNodeId(r.id);for(let n of e)if(n.parentFrameId===t&&n.status===`completed`)return n.output}}function ft(e,t,n){return dt(e.body,t,n)}function pt(e){if(e.length===0)return;let t=new Map,n=new Map;for(let r of e){n.set(r.frameId,r);let e=t.get(r.nodeId)??[];e.push(r),t.set(r.nodeId,e)}return{byNodeId:t,byFrameId:n}}const mt=new Set([`completed`,`skipped`,`waiting`]);function ht(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??mt;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function U(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:Oe(r),output:n.status===`completed`?n.output:e.output}}function gt(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const _t=new Set([`completed`,`running`]);function vt(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function yt(e,t,n,r,i,a,o=`all-settled`){if(t.signal.aborted)return{status:`cancelled`};let s=Object.entries(e.branches);if(s.length===0)return{status:`completed`,output:St({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?gt(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:gt(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>bt(s,c,e,p,n,r,i,a,{outerSignal:t.signal,pauseSignal:o===`fail-fast`||u?l.signal:void 0}));if(o===`all-settled`){let e=await Promise.all(u?m.map(e=>e.then(e=>(e.status===`paused`&&l.abort(),e))):m),t=e.find(e=>e.status===`paused`);return t===void 0?{status:`completed`,output:St(Ct(s,e),o)}:t}let h=await xt(s,m,c,l);return h.type===`cancelled`?{status:`cancelled`}:h.type===`paused`?h.outcome:h.type===`failed`?{status:`failed`,error:h.error}:{status:`completed`,output:St(Ct(s,h.outcomes),o)}}async function bt(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=ht(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:_t});if(l?.status===`completed`)return{status:`completed`,...l.output===void 0?{}:{output:l.output}};let u=l??r.createFrame({nodeId:n.id,nodeType:`parallel`,path:s,parentFrameId:o,branchKey:e});if(r.signal.aborted)return vt(u,c)||await $(u,r),{status:`cancelled`};l===void 0&&await tr(u,r);let d;try{d=await a(t,r,i,u.frameId,u.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(u,r,t),{status:`failed`,error:t}}switch(d.status){case`completed`:{let e=dt(t,u.frameId,r);return await Z(u,r,e),{status:`completed`,output:e}}case`skipped`:return await Z(u,r),{status:`completed`};case`cancelled`:return vt(u,c)||await $(u,r),{status:`cancelled`};case`paused`:return d;case`failed`:return await Q(u,r,d.error),{status:`failed`,error:d.error}}}async function xt(e,t,n,r){let i,a,o=t.map(e=>e.then(e=>(e.status===`failed`&&i===void 0?(i=e.error,n.abort()):e.status===`paused`&&a===void 0&&(a=e,r.abort()),e),e=>{let t=e instanceof Error?e.message:String(e);return i===void 0&&(i=t,n.abort()),{status:`failed`,error:t}})),s=await Promise.all(o);return a===void 0?s.some(e=>e.status===`cancelled`)&&i===void 0?{type:`cancelled`}:i===void 0?{type:`completed`,outcomes:s}:{type:`failed`,error:i}:{type:`paused`,outcome:a}}function St(e,t){return{mode:t,branches:e}}function Ct(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=wt(a)}return n}function wt(e){switch(e.status){case`completed`:return{status:`fulfilled`,...e.output===void 0?{}:{value:e.output}};case`skipped`:return{status:`fulfilled`,value:null};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:e.pausedAtGateId,pausedAtFrameId:e.pausedAtFrameId};case`failed`:return{status:`rejected`,reason:e.error}}}var Tt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Et=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Tt();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),W=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Tt(),n=Et();var r=Tt();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=Et();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function D(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?D(e,n.names):e}function k(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function A(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function j(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${I(e)}`}e.not=j;let M=F(e.operators.AND);function N(...e){return e.reduce(M)}e.and=N;let P=F(e.operators.OR);function ee(...e){return e.reduce(P)}e.or=ee;function F(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${I(n)} ${e} ${I(r)}`}function I(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=W(),n=Tt();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),K=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Dt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=K();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Ot=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Dt(),n=W(),r=K(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),kt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),At=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),jt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=kt(),n=At(),r=Dt(),i=W(),a=G();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
3
- || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
4
- || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
5
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Mt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),q=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=W(),n=G(),r=K(),i=G();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Nt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=K(),r=q(),i=Dt();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Pt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Ft=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),i=r(),a=n(),o=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function s(e,t=!0){return typeof e==`boolean`?!0:t===!0?!l(e):t?u(e)<=t:!1}e.inlineRef=s;let c=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function l(e){for(let t in e){if(c.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(l)||typeof n==`object`&&l(n))return!0}return!1}function u(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!o.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=u(e)),n===1/0)))return 1/0;return n}function d(e,t=``,n){return n!==!1&&(t=m(t)),f(e,e.parse(t))}e.getFullPath=d;function f(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=f;let p=/#\/?$/;function m(e){return e?e.replace(p,``):``}e.normalizeId=m;function h(e,t,n){return n=m(n),e.resolve(t,n)}e.resolveUrl=h;let g=/^[a-z_][-a-z0-9._]*$/i;function _(e,t){if(typeof e==`boolean`)return{};let{schemaId:n,uriResolver:r}=this.opts,o=m(e[n]||t),s={"":o},c=d(r,o,!1),l={},u=new Set;return a(e,{allKeys:!0},(e,t,r,i)=>{if(i===void 0)return;let a=c+t,o=s[i];typeof e[n]==`string`&&(o=d.call(this,e[n])),h.call(this,e.$anchor),h.call(this,e.$dynamicAnchor),s[t]=o;function d(t){let n=this.opts.uriResolver.resolve;if(t=m(o?n(o,t):t),u.has(t))throw p(t);u.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?f(e,r.schema,t):t!==m(a)&&(t[0]===`#`?(f(e,l[t],t),l[t]=e):this.refs[t]=a),t}function h(e){if(typeof e==`string`){if(!g.test(e))throw Error(`invalid anchor "${e}"`);d.call(this,`#${e}`)}}}),l;function f(e,t,n){if(t!==void 0&&!i(e,t))throw p(n)}function p(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=_})),It=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ot(),n=jt(),r=At(),i=jt(),a=Mt(),o=Nt(),s=Pt(),c=W(),l=K(),u=Ft(),d=G(),f=Dt();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return N(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);N(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&M(e),t.return((0,c._)`${l.default.errors} === 0`))}function M({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function N(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>re(e,`$ref`,h.all.$ref.definition));return}p.jtd||ee(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),P(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):P(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function P(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&re(e,n.keyword,n.definition,t.type)})}function ee(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(F(e,t),e.opts.allowUnionTypes||I(e,t),L(e,e.dataTypes))}function F(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{te(e.dataTypes,t)||z(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),ne(e,t)}}function I(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&z(e,`use allowUnionTypes to allow union type keyword`)}function L(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>R(t,e))&&z(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function R(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function te(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function ne(e,t){let n=[];for(let r of e.dataTypes)te(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function z(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var B=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,oe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=B;function re(e,t,n,r){let i=new B(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ie=/^\/(?:[^~]|~0|~1)*$/,ae=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ie.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ae.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=oe})),Lt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Rt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ft();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),zt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=Lt(),r=K(),i=Ft(),a=G(),o=It();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Bt=t(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Vt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=i();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Ht=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=It();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Lt(),i=Rt(),a=kt(),o=zt(),s=W(),c=Ft(),l=jt(),u=G(),d=Bt(),f=Vt(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=D(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(k.call(this,n,t),!t)return(0,u.eachItem)(n,e=>A.call(this,e)),this;M.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>A.call(this,e,r):e=>r.type.forEach(t=>A.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=P(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function D(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let O=/^[a-z_$][a-z0-9_$:-]*$/i;function k(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!O.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function A(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?j.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function j(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=P(t)),e.validateSchema=this.compile(t,!0))}let N={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function P(e){return{anyOf:[e,N]}}})),Ut=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Wt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Rt(),n=q(),r=W(),i=K(),a=zt(),o=G(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Gt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ut(),n=Wt();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Kt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),qt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),Jt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),Yt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=Jt();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),Xt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=q(),n=G(),r=W();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),Zt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),Qt=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=q(),n=W(),r=G();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),$t=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),en=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=r();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),tn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jt(),n=W(),r=G(),i=en();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),nn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=en();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),rn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=en();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),an=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Kt(),n=qt(),r=Yt(),i=Xt(),a=Zt(),o=Qt(),s=$t(),c=tn(),l=nn(),u=rn();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),on=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),sn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=q(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),cn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=sn();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),ln=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r=q(),i=on();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),un=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),dn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=q();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
6
- missingProperty: ${i},
7
- depsCount: ${n},
8
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),fn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),pn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=q(),n=W(),r=K(),i=G();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),mn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=It(),n=q(),r=G(),i=pn();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),hn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=q(),n=W(),r=G(),i=G();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),gn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),_n=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:q().validateUnion,error:{message:`must match a schema in anyOf`}}})),vn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),yn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),bn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=G(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),xn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=G();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Sn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=on(),n=cn(),r=sn(),i=ln(),a=un(),o=dn(),s=fn(),c=pn(),l=mn(),u=hn(),d=gn(),f=_n(),p=vn(),m=yn(),h=bn(),g=xn();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Cn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),wn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Cn().default]})),Tn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),En=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gt(),n=an(),r=Sn(),i=wn(),a=Tn();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Dn=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),On=t((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=W(),n=Dn(),r=zt(),i=Rt(),a=G();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),kn=t(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}}));const An=new(e(t(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Ht(),r=En(),i=On(),a=kn(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=It();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Lt();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Rt();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})}))(),1)).default({allErrors:!0,strict:!1});function jn(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:An.compile(t)}}catch(t){return{status:`failed`,error:`Gate '${e}' has an invalid resumeSchema: ${t instanceof Error?t.message:String(t)}`}}}function Mn(e,t){return e===void 0||e(t)?{valid:!0}:{valid:!1,error:Pn(e.errors??[])}}function Nn(e,t,n){let r=jn(e,t);return r.status===`failed`?{valid:!1,error:r.error}:Mn(r.validator,n)}function Pn(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}const Fn={action:`approve`,source:`timeout`};async function In(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=Bn();o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),e.reject(`timed-out`))},r),a.push(e.promise)}try{let e=await Promise.race(a);return n.removeEventListener(`abort`,i),o!==void 0&&clearTimeout(o),{action:e.action,resumeData:e.resumeData,timedOut:!1,wasCancelled:!1}}catch(e){return o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i),e===`timed-out`?{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1}:{action:`reject`,resumeData:null,timedOut:!1,wasCancelled:!0}}}async function Ln(e,t,n,r,i,a){let o={required:e.suspensionStrategy!==`wait-in-process`};if(a.timedOut){let a=Date.now();if(r.autoAction===`approve`){let s=Mn(i,Fn);return s.valid?(await J(e,{...r,status:`resumed`,resumeData:Fn,resolvedAt:a},o),await Y(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:Fn}}):(await J(e,{...r,status:`timed-out`,resolvedAt:a},o),await Y(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' auto-approve timeout resume data does not match resumeSchema: ${s.error}`})}return await J(e,{...r,status:`timed-out`,resolvedAt:a},o),await Y(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}if(a.wasCancelled||e.signal.aborted)return await J(e,{...r,status:`cancelled`,resolvedAt:Date.now()},o),await Y(e,t.id,n,{source:`cancelled`}),{status:`cancelled`};let s=Date.now();await J(e,{...r,status:a.action===`reject`?`rejected`:`resumed`,resumeData:a.resumeData,resolvedAt:s},o);try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await Y(e,t.id,n,{action:a.action,source:`user`})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function Rn(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await Un(t,e,r);if(n!==void 0)return n}let a=jn(e.id,e.resumeSchema);return a.status===`failed`?{status:`failed`,error:a.error}:zn(t,e,n,r,i,a.validator)}async function zn(e,t,n,r,i,a){let o=R(t.prompt,H(n)),s={executionId:e.executionId,nodeId:t.id,frameId:r,schema:i,prompt:o,status:`waiting`,autoAction:t.autoAction,timeoutMs:t.timeoutMs,createdAt:Date.now()},c=e.suspensionStrategy!==`wait-in-process`;if(await J(e,s,{required:c}),await e.updateFrame(r,{status:`waiting`},{requireFrameStorage:c}),c)return await Vn(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let l={value:!0},u=Bn(),d=e.bus.on(D.gate.respond,async n=>{let{executionId:i,gateId:o,frameId:s,action:c,resumeData:d}=n.payload;if(i!==e.executionId||o!==t.id||s!==void 0&&s!==r){try{await n.next()}catch(e){if(e instanceof f)n.setResult({accepted:!1});else throw e}return}if(!l.value){n.setResult({accepted:!1});return}if(!Mn(a,d).valid){n.setResult({accepted:!1});return}l.value=!1,n.setResult({accepted:!0}),u.resolve({action:c,resumeData:d})});await Vn(e,t,r,i,o,s.createdAt);let p=await In(u,l,e.signal,t.timeoutMs);return d(),Ln(e,t,r,s,a,p)}function Bn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}async function Vn(e,t,n,r,i,a){try{await e.bus.emit(D.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.title!==void 0&&{title:t.title},autoAction:t.autoAction,timeoutMs:t.timeoutMs,openedAt:a})}catch(e){console.error(`[GateNode] gate.suspended emit failed for '${t.id}':`,e)}}async function Hn(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(V.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(V.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function Un(e,t,n){let r=await Hn(e,t.id,n);if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData!==void 0){let i=Nn(t.id,r.schema,r.resumeData);if(!i.valid)return{status:`failed`,error:`Gate '${t.id}' persisted resumeData is invalid: ${i.error}`};try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:r.resumeData})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return await Y(e,t.id,n,{action:r.status===`rejected`?`reject`:`approve`,source:`user`}),{status:`completed`,output:{resumeData:r.resumeData}}}if(r?.status===`waiting`){if(r.timeoutMs!==null&&Date.now()>=r.createdAt+r.timeoutMs){let i=jn(t.id,r.schema);return i.status===`failed`?{status:`failed`,error:i.error}:Ln(e,t,n,r,i.validator,{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1})}return{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}}if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData===void 0)return{status:`failed`,error:`Gate '${t.id}' has status '${r.status}' but resumeData is missing — cannot reconstruct output`};if(r!==null)return{status:`failed`,error:`Gate '${t.id}' cannot resume from status '${r.status}'`}}async function J(e,t,n={}){try{n.required===!0?await e.bus.request(V.setGateInstance,{gate:t}):await e.bus.requestOptional(V.setGateInstance,{gate:t})}catch(e){if(n.required===!0)throw e;console.warn(`[GateNode] Failed to upsert gate instance for '${t.nodeId}':`,e)}}async function Y(e,t,n,r){try{await e.bus.emit(D.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[GateNode] gate.resolved emit failed for '${t}':`,e)}}function X(e){return{status:`fulfilled`,...e===void 0?{}:{value:e}}}const Wn=new Set([`completed`,`running`]);function Gn(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function Kn(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=ut(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Xn([])};let c=await qn(s,e,t,n,r,i,a,e.concurrency!==void 0&&e.concurrency>0?e.concurrency:0);if(t.signal.aborted&&c.every(e=>e.status===`cancelled`))return{status:`cancelled`};let l=c.find(e=>e.status===`paused`);return l===void 0?{status:`completed`,output:Xn(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function qn(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?gt(n.signal,c.signal):n.signal,d=u===n.signal?n:n.withSignal(u),f={outerSignal:n.signal,...l?{pauseSignal:c.signal}:{}};if(s===0){let n=e.map((e,n)=>Yn(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>Jn(e,c)):n)}let p=Array(e.length);for(let n=0;n<e.length;n+=s){if(d.signal.aborted){for(let t=n;t<e.length;t++)p[t]={status:`cancelled`};break}let u=Math.min(n+s,e.length),m=[];for(let s=n;s<u;s++)m.push(Yn(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>Jn(e,c)):m);for(let e=0;e<h.length;e++)p[n+e]=h[e];if(h.some(e=>e.status===`paused`)){for(let t=u;t<e.length;t++)p[t]={status:`cancelled`};break}}return p}function Jn(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function Yn(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=ht(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:Wn});if(u?.status===`completed`)return X(u.output);let d=u??r.createFrame({nodeId:n.id,nodeType:`iterate`,path:s,parentFrameId:o,iteration:t});if(r.signal.aborted)return Gn(d,c)||await $(d,r),{status:`cancelled`};u===void 0&&await tr(d,r);let f;try{f=await a(n.body,r,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,r,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=ft(n,d.frameId,r);return await Z(d,r,e),X(e)}case`skipped`:return await Z(d,r),X();case`cancelled`:return Gn(d,c)||await $(d,r),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,r,f.error),{status:`rejected`,reason:f.error}}}function Xn(e){return{items:e}}const Zn=new Set([`completed`,`running`]);async function Qn(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=ut(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:er([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await $n(u,o,l,e,t,n,r,i,a);switch(c.push(d),d.status){case`fulfilled`:l=d.value;break;case`rejected`:return{status:`failed`,error:d.reason};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:d.pausedAtGateId,pausedAtFrameId:d.pausedAtFrameId}}}return{status:`completed`,output:er(c)}}async function $n(e,t,n,r,i,a,o,s,c){if(i.signal.aborted)return{status:`cancelled`};let l={...a,item:e,index:t,...n!==void 0&&{previous:n}},u=ht(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:Zn});if(u?.status===`completed`)return X(u.output);let d=u??i.createFrame({nodeId:r.id,nodeType:`iterate-chain`,path:c,parentFrameId:s,iteration:t});if(i.signal.aborted)return await $(d,i),{status:`cancelled`};u===void 0&&await tr(d,i);let f;try{f=await o(r.body,i,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,i,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=ft(r,d.frameId,i);return await Z(d,i,e),X(e)}case`skipped`:return await Z(d,i),X();case`cancelled`:return await $(d,i),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,i,f.error),{status:`rejected`,reason:f.error}}}function er(e){return{items:e}}async function tr(e,t){e.status=`running`,e.startedAt=Date.now(),await t.persistFrame(e),await t.emitFrameStarted(e)}async function Z(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`completed`,e.output=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameCompleted(e,i)}async function Q(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`failed`,e.error=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameFailed(e,n,i)}async function nr(e,t){e.status=`skipped`,e.completedAt=Date.now(),await t.persistFrame(e)}async function $(e,t){e.status=`cancelled`,e.completedAt=Date.now(),await t.persistFrame(e)}function rr(e,t){return!!L(e,H(t))}async function ir(e,t,n,r,i,a=[]){if(t.signal.aborted)return{status:`cancelled`};switch(e.type){case`sequence`:return r(e,t,n,i,a);case`station`:return it(e,t,n,i);case`delegate-agent`:return ot(e,t,n,i);case`delegate-role`:return st(e,t,n,i);case`parallel`:return yt(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return Rn(e,t,n,i??``);case`iterate`:return Kn(e,t,n,r,i??``,a);case`iterate-chain`:return Qn(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const ar=new Set([`completed`,`skipped`,`waiting`,`running`]);function or(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`}function sr(e,t,n){return ht(e.resumeFrames,t.id,{parentFrameId:n,...or(t)?{statuses:ar}:{}})}function cr(e,t,n){if(n?.status===`completed`)return U(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return U(e,t.id,{status:`skipped`})}async function lr(e,t,n,r,i,a,o){try{return{result:rr(e,i)}}catch(e){let i=e instanceof Error?e.message:String(e);return await Q(r.createFrame({nodeId:n.id,nodeType:n.type,path:a,parentFrameId:o}),r,`'${t}' condition evaluation failed: ${i}`),{status:`failed`,error:`'${t}' condition evaluation failed for '${n.id}': ${i}`}}}async function ur(e,t,n,r,i,a){let o=a??t.createFrame({nodeId:e.id,nodeType:e.type,path:r,parentFrameId:i});if(t.signal.aborted)return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};a===void 0&&await tr(o,t);let s;try{s=await ir(e,t,n,dr,o.frameId,o.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Q(o,t,r),{updatedCtx:n,outcome:{status:`failed`,error:r}}}switch(s.status){case`completed`:return await Z(o,t,s.output),{updatedCtx:U(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await nr(o,t),{updatedCtx:U(n,e.id,{status:`skipped`})};case`cancelled`:return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};case`paused`:return{updatedCtx:n,outcome:s};case`failed`:return await Q(o,t,s.error),{updatedCtx:n,outcome:{status:`failed`,error:s.error}}}}async function dr(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=sr(t,n,r),o=cr(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await lr(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await nr(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=U(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await lr(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await nr(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=U(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||e?.status===`running`&&or(n)?e:void 0,{updatedCtx:c,outcome:l}=await ur(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}export{de as C,le as S,D as T,B as _,Ne as a,ae as b,xe as c,he as d,me as f,oe as g,re as h,Be as i,ve as l,z as m,Nn as n,Se as o,V as p,pt as r,De as s,dr as t,_e as u,ie as v,ce as w,ue as x,se as y};
@@ -1 +0,0 @@
1
- import{sessions as e}from"./services/session/storage/schema.mjs";import{t}from"./schema-DOnJmAPw.mjs";import{index as n,integer as r,sqliteTable as i,text as a}from"drizzle-orm/sqlite-core";const o=i(`messages`,{messageId:a(`message_id`).primaryKey(),turnId:a(`turn_id`).references(()=>t.turnId,{onDelete:`cascade`}),sessionId:a(`session_id`).notNull().references(()=>e.sessionId,{onDelete:`cascade`}),role:a(`role`,{enum:[`user`,`assistant`]}).notNull(),contentText:a(`content_text`).notNull(),blocks:a(`blocks`).notNull().default(`[]`),agentId:a(`agent_id`),adapterSessionId:a(`adapter_session_id`),adapterMessageId:a(`adapter_message_id`),timestamp:r(`timestamp`).notNull(),editOf:a(`edit_of`).references(()=>o.messageId),origin:a(`origin`,{enum:[`voice`,`text`,`compact`]})},e=>[n(`idx_messages_session`).on(e.sessionId,e.timestamp),n(`idx_messages_turn`).on(e.turnId,e.timestamp),n(`idx_messages_agent`).on(e.agentId,e.timestamp),n(`idx_messages_adapter_message_id`).on(e.adapterMessageId)]);export{o as t};
@@ -1 +0,0 @@
1
- import{sessions as e}from"./services/session/storage/schema.mjs";import{index as t,integer as n,sqliteTable as r,text as i,uniqueIndex as a}from"drizzle-orm/sqlite-core";const o=r(`turns`,{turnId:i(`turn_id`).primaryKey(),sessionId:i(`session_id`).notNull().references(()=>e.sessionId,{onDelete:`cascade`}),turnNumber:n(`turn_number`).notNull(),startedAt:n(`started_at`).notNull(),completedAt:n(`completed_at`),status:i(`status`,{enum:[`active`,`completed`,`error`]}).notNull(),error:i(`error`),usage:i(`usage`)},e=>[t(`idx_turns_session`).on(e.sessionId,e.startedAt),a(`uniq_turns_session_number`).on(e.sessionId,e.turnNumber)]);export{o as t};