@ai-development-environment/server 0.0.30 → 0.0.31

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 (159) hide show
  1. package/package.json +1 -1
  2. package/standalone/.next/BUILD_ID +1 -1
  3. package/standalone/.next/app-path-routes-manifest.json +1 -0
  4. package/standalone/.next/build-manifest.json +3 -3
  5. package/standalone/.next/prerender-manifest.json +3 -3
  6. package/standalone/.next/routes-manifest.json +9 -0
  7. package/standalone/.next/server/app/[locale]/actions/page.js.nft.json +1 -1
  8. package/standalone/.next/server/app/[locale]/actions/page_client-reference-manifest.js +1 -1
  9. package/standalone/.next/server/app/[locale]/agents/[id]/page.js.nft.json +1 -1
  10. package/standalone/.next/server/app/[locale]/agents/[id]/page_client-reference-manifest.js +1 -1
  11. package/standalone/.next/server/app/[locale]/agents/page.js.nft.json +1 -1
  12. package/standalone/.next/server/app/[locale]/agents/page_client-reference-manifest.js +1 -1
  13. package/standalone/.next/server/app/[locale]/build-data/page.js.nft.json +1 -1
  14. package/standalone/.next/server/app/[locale]/build-data/page_client-reference-manifest.js +1 -1
  15. package/standalone/.next/server/app/[locale]/builds/[buildId]/coverage/page.js.nft.json +1 -1
  16. package/standalone/.next/server/app/[locale]/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
  17. package/standalone/.next/server/app/[locale]/builds/[buildId]/page.js.nft.json +1 -1
  18. package/standalone/.next/server/app/[locale]/builds/[buildId]/page_client-reference-manifest.js +1 -1
  19. package/standalone/.next/server/app/[locale]/builds/page.js.nft.json +1 -1
  20. package/standalone/.next/server/app/[locale]/builds/page_client-reference-manifest.js +1 -1
  21. package/standalone/.next/server/app/[locale]/codebases/[codebaseId]/page.js.nft.json +1 -1
  22. package/standalone/.next/server/app/[locale]/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
  23. package/standalone/.next/server/app/[locale]/codebases/page.js.nft.json +1 -1
  24. package/standalone/.next/server/app/[locale]/codebases/page_client-reference-manifest.js +1 -1
  25. package/standalone/.next/server/app/[locale]/codebases/repositories/[repositoryId]/page.js.nft.json +1 -1
  26. package/standalone/.next/server/app/[locale]/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
  27. package/standalone/.next/server/app/[locale]/comments/page.js.nft.json +1 -1
  28. package/standalone/.next/server/app/[locale]/comments/page_client-reference-manifest.js +1 -1
  29. package/standalone/.next/server/app/[locale]/jira/cache/page.js.nft.json +1 -1
  30. package/standalone/.next/server/app/[locale]/jira/cache/page_client-reference-manifest.js +1 -1
  31. package/standalone/.next/server/app/[locale]/jira/cache/tickets/[issueKey]/page.js.nft.json +1 -1
  32. package/standalone/.next/server/app/[locale]/jira/cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  33. package/standalone/.next/server/app/[locale]/jira/tickets/[issueKey]/page.js.nft.json +1 -1
  34. package/standalone/.next/server/app/[locale]/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  35. package/standalone/.next/server/app/[locale]/jira/tickets/page.js.nft.json +1 -1
  36. package/standalone/.next/server/app/[locale]/jira/tickets/page_client-reference-manifest.js +1 -1
  37. package/standalone/.next/server/app/[locale]/jobs/[jobId]/page.js.nft.json +1 -1
  38. package/standalone/.next/server/app/[locale]/jobs/[jobId]/page_client-reference-manifest.js +1 -1
  39. package/standalone/.next/server/app/[locale]/page.js.nft.json +1 -1
  40. package/standalone/.next/server/app/[locale]/page_client-reference-manifest.js +1 -1
  41. package/standalone/.next/server/app/[locale]/pull-requests/[owner]/[repository]/[number]/page.js.nft.json +1 -1
  42. package/standalone/.next/server/app/[locale]/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
  43. package/standalone/.next/server/app/[locale]/pull-requests/page.js.nft.json +1 -1
  44. package/standalone/.next/server/app/[locale]/pull-requests/page_client-reference-manifest.js +1 -1
  45. package/standalone/.next/server/app/[locale]/settings/page.js.nft.json +1 -1
  46. package/standalone/.next/server/app/[locale]/settings/page_client-reference-manifest.js +1 -1
  47. package/standalone/.next/server/app/[locale]/skills/[skillId]/page.js.nft.json +1 -1
  48. package/standalone/.next/server/app/[locale]/skills/[skillId]/page_client-reference-manifest.js +1 -1
  49. package/standalone/.next/server/app/[locale]/skills/groups/[groupId]/page.js.nft.json +1 -1
  50. package/standalone/.next/server/app/[locale]/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
  51. package/standalone/.next/server/app/[locale]/skills/groups/page.js.nft.json +1 -1
  52. package/standalone/.next/server/app/[locale]/skills/groups/page_client-reference-manifest.js +1 -1
  53. package/standalone/.next/server/app/[locale]/skills/page.js.nft.json +1 -1
  54. package/standalone/.next/server/app/[locale]/skills/page_client-reference-manifest.js +1 -1
  55. package/standalone/.next/server/app/[locale]/skills/sync/[runId]/page.js.nft.json +1 -1
  56. package/standalone/.next/server/app/[locale]/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
  57. package/standalone/.next/server/app/[locale]/tools/page.js.nft.json +1 -1
  58. package/standalone/.next/server/app/[locale]/tools/page_client-reference-manifest.js +1 -1
  59. package/standalone/.next/server/app/[locale]/usage/page.js.nft.json +1 -1
  60. package/standalone/.next/server/app/[locale]/usage/page_client-reference-manifest.js +1 -1
  61. package/standalone/.next/server/app/[locale]/worktrees/[worktreeId]/page.js.nft.json +1 -1
  62. package/standalone/.next/server/app/[locale]/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
  63. package/standalone/.next/server/app/[locale]/worktrees/page.js.nft.json +1 -1
  64. package/standalone/.next/server/app/[locale]/worktrees/page_client-reference-manifest.js +1 -1
  65. package/standalone/.next/server/app/_global-error.html +1 -1
  66. package/standalone/.next/server/app/_global-error.rsc +1 -1
  67. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  68. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  69. package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  70. package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  71. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  72. package/standalone/.next/server/app/_not-found.html +1 -1
  73. package/standalone/.next/server/app/_not-found.rsc +1 -1
  74. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  75. package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  76. package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  77. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  78. package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  79. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  80. package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js +1 -1
  81. package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
  82. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route/app-paths-manifest.json +3 -0
  83. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route/build-manifest.json +9 -0
  84. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route/server-reference-manifest.json +4 -0
  85. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js +11 -0
  86. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.map +5 -0
  87. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -0
  88. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route_client-reference-manifest.js +3 -0
  89. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/route.js +4 -3
  90. package/standalone/.next/server/app/api/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
  91. package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
  92. package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
  93. package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
  94. package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
  95. package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
  96. package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
  97. package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js +1 -1
  98. package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
  99. package/standalone/.next/server/app-paths-manifest.json +1 -0
  100. package/standalone/.next/server/chunks/07_e_builds_[buildId]_artifacts_[artifactId]_manifest_plist_route_actions_18mzaf3.js +3 -0
  101. package/standalone/.next/server/chunks/[root-of-the-server]__08mnmfs._.js +3 -0
  102. package/standalone/.next/server/chunks/[root-of-the-server]__0906ea6._.js +3 -0
  103. package/standalone/.next/server/chunks/{[root-of-the-server]__09skp6r._.js → [root-of-the-server]__0cz4ap5._.js} +1 -1
  104. package/standalone/.next/server/chunks/[root-of-the-server]__0nvcazp._.js +3 -0
  105. package/standalone/.next/server/chunks/{[root-of-the-server]__1wtng3p._.js → [root-of-the-server]__12807ia._.js} +1 -1
  106. package/standalone/.next/server/chunks/[root-of-the-server]__1csx222._.js +3 -0
  107. package/standalone/.next/server/chunks/{[root-of-the-server]__0zyqmd4._.js → [root-of-the-server]__1ix62p0._.js} +2 -2
  108. package/standalone/.next/server/chunks/[root-of-the-server]__1j-hk6b._.js +3 -0
  109. package/standalone/.next/server/chunks/{[root-of-the-server]__15aat79._.js → [root-of-the-server]__1j0u03u._.js} +1 -1
  110. package/standalone/.next/server/chunks/[root-of-the-server]__1qmvsu_._.js +3 -0
  111. package/standalone/.next/server/chunks/[root-of-the-server]__1w59u6o._.js +3 -0
  112. package/standalone/.next/server/chunks/{[root-of-the-server]__0-ypkf7._.js → [root-of-the-server]__1z-3x8k._.js} +1 -1
  113. package/standalone/.next/server/chunks/_0exkna-._.js +51 -1
  114. package/standalone/.next/server/chunks/_0jurkow._.js +1 -1
  115. package/standalone/.next/server/chunks/_0rx5rfm._.js +1 -1
  116. package/standalone/.next/server/chunks/_0tufgj0._.js +111 -61
  117. package/standalone/.next/server/chunks/_0w2eghf._.js +51 -1
  118. package/standalone/.next/server/chunks/_152rnkf._.js +3 -3
  119. package/standalone/.next/server/chunks/_16x77b_._.js +1 -1
  120. package/standalone/.next/server/chunks/_1dbqy8c._.js +3 -3
  121. package/standalone/.next/server/chunks/_1vrixpc._.js +3 -3
  122. package/standalone/.next/server/chunks/_1yfz-9u._.js +3 -3
  123. package/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_08x37wy.js +6 -0
  124. package/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0eghv0a.js +3 -0
  125. package/standalone/.next/server/chunks/ssr/[root-of-the-server]__08bbv6z._.js +1 -1
  126. package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ckj6wg._.js +1 -1
  127. package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0qy28ku._.js +3 -0
  128. package/standalone/.next/server/chunks/ssr/_0a1ligo._.js +1 -1
  129. package/standalone/.next/server/chunks/ssr/{_1n9rteq._.js → _1f5k6bj._.js} +2 -2
  130. package/standalone/.next/server/chunks/ssr/messages_de_json_[json]_cjs_1uig1ud._.js +1 -1
  131. package/standalone/.next/server/chunks/ssr/messages_en_json_[json]_cjs_206072-._.js +1 -1
  132. package/standalone/.next/server/chunks/ssr/messages_es_json_[json]_cjs_082yukd._.js +1 -1
  133. package/standalone/.next/server/chunks/ssr/messages_fr_json_[json]_cjs_0j6-w0i._.js +1 -1
  134. package/standalone/.next/server/chunks/ssr/src_components_builds_build-detail-page_tsx_0q1lvps._.js +20 -10
  135. package/standalone/.next/server/functions-config-manifest.json +4 -1
  136. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  137. package/standalone/.next/server/pages/404.html +1 -1
  138. package/standalone/.next/server/pages/500.html +1 -1
  139. package/standalone/.next/server/server-reference-manifest.js +1 -1
  140. package/standalone/.next/server/server-reference-manifest.json +1 -1
  141. package/standalone/.next/static/chunks/0hwbkceik59kx.js +35 -0
  142. package/standalone/.next/static/chunks/{1ut0xkaqsykm4.js → 0mq066ue0yufb.js} +1 -1
  143. package/standalone/.next/static/chunks/{041g9raf1naqv.js → 175269y15-grc.js} +1 -1
  144. package/standalone/.next/static/chunks/{3q0q6_ntq8aa5.js → 208k3moxxd_53.js} +1 -1
  145. package/standalone/.next/static/chunks/2zwijj9t6y7gn.js +7 -0
  146. package/standalone/.next/static/chunks/398uw5_4-ciaz.css +1 -0
  147. package/standalone/.next/static/chunks/{29zl8lgsa28tb.js → 3l2g83119oyl0.js} +1 -1
  148. package/standalone/src/services/builds/artifact-cache.test.ts +241 -0
  149. package/standalone/src/services/builds/artifact-cache.ts +235 -0
  150. package/standalone/src/services/builds/artifact-transfer.ts +2 -1
  151. package/standalone/src/services/builds/builds.service.ts +139 -56
  152. package/standalone/.next/server/chunks/[root-of-the-server]__02vqwey._.js +0 -3
  153. package/standalone/.next/server/chunks/[root-of-the-server]__0rwpsai._.js +0 -3
  154. package/standalone/.next/server/chunks/ssr/[root-of-the-server]__10-ftkj._.js +0 -3
  155. package/standalone/.next/static/chunks/3p7wbgo7qd6_m.css +0 -1
  156. package/standalone/.next/static/chunks/3vg6y29m047x9.js +0 -31
  157. /package/standalone/.next/static/{ePu377E66yy0icQx3ykQJ → sJ09NBDjsLncJEkHNWbdR}/_buildManifest.js +0 -0
  158. /package/standalone/.next/static/{ePu377E66yy0icQx3ykQJ → sJ09NBDjsLncJEkHNWbdR}/_clientMiddlewareManifest.js +0 -0
  159. /package/standalone/.next/static/{ePu377E66yy0icQx3ykQJ → sJ09NBDjsLncJEkHNWbdR}/_ssgManifest.js +0 -0
@@ -391,7 +391,7 @@ ${i}
391
391
  ${i}
392
392
  ~~~`}},ua=class{constructor(){(0,nT.__publicField)(this,"nodeType","blockquote")}toMarkdown(e,t){if(!e.content||0===e.content.length)return"> ";let r=e.content.map(r=>{let i=t.options.registry?.getNodeConverter(r.type);return i?i.toMarkdown(r,{...t,depth:t.depth+1,parent:e}):""}).join("\n").split("\n").map(e=>""===e.trim()?">":`> ${e}`);if(e.attrs&&Object.keys(e.attrs).length>0){let t=r.join("\n");return`${t}<!-- adf:blockquote attrs='${JSON.stringify(e.attrs)}' -->`}return r.join("\n")}},un=class{constructor(){(0,nT.__publicField)(this,"nodeType","rule")}toMarkdown(e,t){return"---"}},us=class{constructor(){(0,nT.__publicField)(this,"nodeType","hardBreak")}toMarkdown(e,t){return" \n"}},uo=class{constructor(){(0,nT.__publicField)(this,"nodeType","mention")}toMarkdown(e,t){let{id:r,text:i,userType:a}=e.attrs||{},n=`adf://mention/${r||"unknown"}`,s=i||`@${r||"unknown"}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:mention attrs='${JSON.stringify(e.attrs)}' -->`;return`[${s}](${n})${t}`}return`[${s}](${n})`}},ul=class{constructor(){(0,nT.__publicField)(this,"nodeType","date")}toMarkdown(e,t){let{timestamp:r}=e.attrs||{};if(!r)return"[Date]";let i=new Date(parseInt(r));if(isNaN(i.getTime())){if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:date attrs='${JSON.stringify(e.attrs)}' -->`;return`[Invalid Date]${t}`}return"[Invalid Date]"}let a=i.toISOString().split("T")[0];if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:date attrs='${JSON.stringify(e.attrs)}' -->`;return`${a}${t}`}return a}},uc=class{constructor(){(0,nT.__publicField)(this,"nodeType","emoji")}toMarkdown(e,t){let{shortName:r,text:i}=e.attrs||{};if(i){if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:emoji attrs='${JSON.stringify(e.attrs)}' -->`;return`${i}${t}`}return i}if(r){let t=r.startsWith(":")&&r.endsWith(":")?r:`:${r}:`;if(e.attrs&&Object.keys(e.attrs).length>0){let r=`<!-- adf:emoji attrs='${JSON.stringify(e.attrs)}' -->`;return`${t}${r}`}return t}return":emoji:"}},uu=class{constructor(){(0,nT.__publicField)(this,"nodeType","status")}toMarkdown(e,t){let{text:r,color:i}=e.attrs||{},a=r||"Status";return i&&"neutral"!==i?`{status:${a}|color:${i}}`:`{status:${a}}`}},ud=class{constructor(){(0,nT.__publicField)(this,"nodeType","inlineCard")}toMarkdown(e,t){let{url:r,data:i}=e.attrs||{};if(!r)return"[Card]";let a=i?.title||i?.name||"Card",n=`adf://card/${encodeURIComponent(r)}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:inlineCard attrs='${JSON.stringify(e.attrs)}' -->`;return`[${a}](${n})${t}`}return`[${a}](${n})`}},up=class{constructor(){(0,nT.__publicField)(this,"nodeType","mediaGroup")}toMarkdown(e,t){return(e.content||[]).map(e=>{let r=t.options.registry?.getNodeConverter(e.type);return r?r.toMarkdown(e,t):""}).filter(e=>e.length>0).join(" ")+"\n\n"}},um=class{constructor(){(0,nT.__publicField)(this,"nodeType","doc")}toMarkdown(e,t){let r=e.content||[];return t.convertChildren(r).trim()+"\n"}},uh=class{constructor(){(0,nT.__publicField)(this,"markType","strong")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`**${e}**<!-- adf:strong attrs='${JSON.stringify(t.attrs)}' -->`:`**${e}**`}},uf=class{constructor(){(0,nT.__publicField)(this,"markType","em")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`*${e}*<!-- adf:em attrs='${JSON.stringify(t.attrs)}' -->`:`*${e}*`}},ug=class{constructor(){(0,nT.__publicField)(this,"markType","code")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`\`${e}\`<!-- adf:code attrs='${JSON.stringify(t.attrs)}' -->`:`\`${e}\``}},uy=class{constructor(){(0,nT.__publicField)(this,"markType","link")}toMarkdown(e,t,r){let i;if(!t.attrs?.href)return e;let{href:a,title:n,...s}=t.attrs;return i=n?`[${e}](${a} "${n}")`:`[${e}](${a})`,Object.keys(s).length>0&&(i+=`<!-- adf:link attrs='${JSON.stringify(s)}' -->`),i}},uv=class{constructor(){(0,nT.__publicField)(this,"markType","strike")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`~~${e}~~<!-- adf:strike attrs='${JSON.stringify(t.attrs)}' -->`:`~~${e}~~`}},ub=class{constructor(){(0,nT.__publicField)(this,"markType","underline")}toMarkdown(e,t,r){let i=`<u>${e}</u>`;return t.attrs&&Object.keys(t.attrs).length>0?`${i}<!-- adf:underline attrs='${JSON.stringify(t.attrs)}' -->`:i}},uw=class{constructor(){(0,nT.__publicField)(this,"markType","textColor")}toMarkdown(e,t,r){if(!t.attrs?.color)return e;let{color:i,...a}=t.attrs,n=`<span style="color: ${i}">${e}</span>`;return Object.keys(a).length>0&&(n+=`<!-- adf:textColor attrs='${JSON.stringify(a)}' -->`),n}},ux=class{constructor(){(0,nT.__publicField)(this,"markType","backgroundColor")}toMarkdown(e,t,r){let{color:i}=t.attrs||{},a=`<mark style="background-color: ${i||"yellow"}">${e}</mark>`;if(t.attrs&&Object.keys(t.attrs).length>0){let e=`<!-- adf:backgroundColor attrs='${JSON.stringify(t.attrs)}' -->`;return`${a}${e}`}return a}},uk=class{constructor(){(0,nT.__publicField)(this,"markType","subsup")}toMarkdown(e,t,r){let i,{type:a}=t.attrs||{};if(i="sub"===a?`<sub>${e}</sub>`:`<sup>${e}</sup>`,t.attrs&&Object.keys(t.attrs).length>0){let e=`<!-- adf:subsup attrs='${JSON.stringify(t.attrs)}' -->`;return`${i}${e}`}return i}},u_=class{constructor(e={}){(0,nT.__publicField)(this,"registry"),(0,nT.__publicField)(this,"validator"),(0,nT.__publicField)(this,"options"),this.options={strict:!1,gfm:!0,frontmatter:!0,enableAdfExtensions:!0,maxDepth:5,enableLogging:!1,preserveWhitespace:!1,validateInput:!1,preserveUnknownNodes:!0,maxRetries:3,retryDelay:100,fallbackStrategy:"best-effort",...e},this.registry=new cA,this.validator=new cE,this.registerConverters()}convert(e){if(!e||"object"!=typeof e){if(this.options.strict)throw Error("Invalid ADF document: must be a non-null object");return""}if("doc"!==e.type&&this.options.strict)throw Error('Invalid ADF document: root node must be of type "doc"');try{let t=this.validator.validate(e);if(!t.valid&&this.options.strict)throw Error(`Invalid ADF structure: ${t.errors.map(e=>e.message).join(", ")}`);return this.convertAdfToMarkdown(e)}catch(e){if(this.options.strict)throw e;return this.options.enableLogging&&console.warn("ADF to Markdown conversion failed, returning empty string:",e),""}}convertWithValidation(e){let t=[],r=this.validator.validate(e);if(!r.valid){if(this.options.strict)throw Error(`Invalid ADF structure: ${r.errors.map(e=>e.message).join(", ")}`);t.push(...r.errors.map(e=>e.message))}try{return{markdown:this.convertAdfToMarkdown(e),warnings:t}}catch(e){if(this.options.strict)throw e;return t.push(`Conversion failed: ${e instanceof Error?e.message:"Unknown error"}`),{markdown:"",warnings:t}}}getStats(e){let t={nodeCount:0,hasAdfExtensions:!1,hasGfmFeatures:!1,supportedTypes:new Set,unsupportedTypes:new Set},r=e=>{t.nodeCount++;try{this.registry.getNodeConverter(e.type),t.supportedTypes.add(e.type)}catch{t.unsupportedTypes.add(e.type)}["panel","expand","mediaSingle","mediaGroup","mention","emoji","date","status"].includes(e.type)&&(t.hasAdfExtensions=!0),["table","tableRow","tableHeader","tableCell"].includes(e.type)&&(t.hasGfmFeatures=!0),e.content&&Array.isArray(e.content)&&e.content.forEach(r)};e.content&&e.content.forEach(r);let i=t.nodeCount<10?"simple":t.nodeCount<50?"moderate":"complex";return{nodeCount:t.nodeCount,hasAdfExtensions:t.hasAdfExtensions,hasGfmFeatures:t.hasGfmFeatures,complexity:i,supportedTypes:Array.from(t.supportedTypes),unsupportedTypes:Array.from(t.unsupportedTypes)}}registerConverters(){this.registry.registerNodes([new cY,new cX,new c0,new c1,new c4,new c3,new c2,new c6,new c9,new c8,new c5,new c7,new ue,new ut,new ur,new ui,new ua,new un,new us,new uo,new ul,new uc,new uu,new ud,new up,new um]),this.registry.registerMarks([new uh,new uf,new ug,new uy,new uv,new ub,new uw,new ux,new uk])}convertAdfToMarkdown(e){let t={convertChildren:e=>Array.isArray(e)?e.map(e=>{try{return this.registry.getNodeConverter(e.type).toMarkdown(e,t)}catch(t){return this.options.enableLogging&&console.warn(`Failed to convert node type "${e.type}":`,t),this.options.preserveUnknownNodes?`<!-- Unknown node: ${e.type} -->`:""}}).join(""):"",depth:0,options:{...this.options,registry:this.registry}};return e.content&&Array.isArray(e.content)?e.content.map(e=>{try{return this.registry.getNodeConverter(e.type).toMarkdown(e,t)}catch(t){return this.options.enableLogging&&console.warn(`Failed to convert node type "${e.type}":`,t),this.options.preserveUnknownNodes?`<!-- Unknown node: ${e.type} -->`:""}}).filter(e=>e.length>0).join("\n\n"):""}},u$=class{constructor(e={}){(0,nT.__publicField)(this,"options"),this.options={maxRetries:3,retryDelay:100,fallbackStrategy:"best-effort",onError:()=>{},onRecovery:()=>{},enableLogging:!1,...e}}async executeWithRecovery(e,t){let r,i={operation:"unknown",input:"",attempt:0,previousErrors:[],...t},a=[];for(let t=0;t<=this.options.maxRetries;t++){i.attempt=t;try{let r=await e();return t>0&&this.options.onRecovery&&this.options.onRecovery("retry-success",i),{success:!0,data:r,warnings:a}}catch(e){if(r=e,i.previousErrors.push(r),this.options.onError&&this.options.onError(r,i),this.options.enableLogging&&console.warn(`Attempt ${t+1} failed:`,r.message),this.isNonRetryableError(r))break;t<this.options.maxRetries&&await this.delay(this.options.retryDelay)}}return this.applyFallbackStrategy(r,i,a)}async recoverAdfToMarkdown(e,t,r){let i=[];try{if(e.content&&Array.isArray(e.content)){let t=[];for(let r of e.content)try{let e=await this.recoverNodeConversion(r,"adf-to-markdown");e.success&&e.data?t.push(e.data):(i.push(`Failed to convert node type: ${r.type}`),t.push(this.createNodeFallback(r,"markdown")))}catch(e){i.push(`Node conversion error: ${e}`),t.push(this.createNodeFallback(r,"markdown"))}let a=t.join("\n\n");return this.options.onRecovery&&this.options.onRecovery("node-by-node-recovery",r),{success:!0,data:a,strategy:"node-by-node-recovery",fallback:!0,warnings:i}}let t=this.createMinimalMarkdown(e);return i.push("Used minimal fallback conversion"),{success:!0,data:t,strategy:"minimal-fallback",fallback:!0,warnings:i}}catch(e){return{success:!1,error:e,warnings:i}}}async recoverMarkdownToAdf(e,t,r){let i=[];try{let t=this.splitMarkdownIntoSections(e),a=[];for(let e of t)try{let t=await this.parseMarkdownSection(e);t.success&&t.data?a.push(...t.data.content):(i.push(`Failed to parse section: ${e.substring(0,50)}...`),a.push(this.createTextFallback(e)))}catch(t){i.push(`Section parsing error: ${t}`),a.push(this.createTextFallback(e))}return this.options.onRecovery&&this.options.onRecovery("section-by-section-recovery",r),{success:!0,data:{version:1,type:"doc",content:a},strategy:"section-by-section-recovery",fallback:!0,warnings:i}}catch(r){let t={version:1,type:"doc",content:[this.createTextFallback(e)]};return i.push("Used text-only fallback conversion"),{success:!0,data:t,strategy:"text-fallback",fallback:!0,warnings:i}}}async applyFallbackStrategy(e,t,r){switch(this.options.fallbackStrategy){case"skip":return r.push("Operation skipped due to errors"),{success:!1,error:e,warnings:r};case"placeholder":let i=this.createPlaceholder(t);return r.push("Used placeholder due to errors"),{success:!0,data:i,strategy:"placeholder",fallback:!0,warnings:r};case"best-effort":return await this.attemptBestEffortRecovery(e,t,r);default:return{success:!1,error:e,warnings:r}}}async attemptBestEffortRecovery(e,t,r){try{if(t.operation.includes("adfToMarkdown"))return await this.recoverAdfToMarkdown(t.input,e,t);if(t.operation.includes("markdownToAdf"))return await this.recoverMarkdownToAdf(t.input,e,t);return r.push("Applied generic fallback recovery"),{success:!1,error:e,strategy:"generic-fallback",warnings:r}}catch(e){return{success:!1,error:e,warnings:r}}}isNonRetryableError(e){return e instanceof cR||e.message.includes("Invalid JSON")||e.message.includes("Syntax error")}delay(e){return new Promise(t=>setTimeout(t,e))}async recoverNodeConversion(e,t){try{if("adf-to-markdown"===t)return{success:!0,data:this.createNodeFallback(e,"markdown"),warnings:[]};return{success:!0,data:JSON.stringify(e),warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createNodeFallback(e,t){if("markdown"!==t)return JSON.stringify(e,null,2);switch(e.type){case"paragraph":return e.content?this.extractTextFromNodes(e.content):"[Paragraph]";case"heading":let r=e.attrs?.level||1,i=e.content?this.extractTextFromNodes(e.content):"[Heading]";return"#".repeat(r)+" "+i;case"codeBlock":return"```\n[Code Block]\n```";case"panel":return`> [${e.attrs?.panelType||"info"} panel]`;default:return`[${e.type}]`}}extractTextFromNodes(e){return e.map(e=>"text"===e.type&&e.text?e.text:e.content?this.extractTextFromNodes(e.content):"").join("")}createMinimalMarkdown(e){let t=e.content?e.content.map(e=>this.createNodeFallback(e,"markdown")).join("\n\n"):"[No content]";return`# Document
393
393
 
394
- ${t}`}splitMarkdownIntoSections(e){let t=e.split(/(?=^#{1,6}\s)|(?:\n\s*\n)/m).filter(e=>e.trim().length>0);return t.length>0?t:[e]}async parseMarkdownSection(e){try{let t=[this.createTextFallback(e)];return{success:!0,data:{version:1,type:"doc",content:t},warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createTextFallback(e){return{type:"paragraph",content:[{type:"text",text:e.trim()}]}}createPlaceholder(e){return e.operation.includes("adfToMarkdown")?`[Error converting ADF to Markdown: ${e.operation}]`:e.operation.includes("markdownToAdf")?{version:1,type:"doc",content:[{type:"paragraph",content:[{type:"text",text:`[Error converting Markdown to ADF: ${e.operation}]`}]}]}:`[Error in operation: ${e.operation}]`}},uI=class{constructor(e){(0,nT.__publicField)(this,"mdToAdfEngine"),(0,nT.__publicField)(this,"adfToMdEngine"),(0,nT.__publicField)(this,"options"),(0,nT.__publicField)(this,"errorRecovery"),(0,nT.__publicField)(this,"remarkProcessor"),(0,nT.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new cQ(this.options),this.adfToMdEngine=new u_(this.options),this.errorRecovery=new u$({maxRetries:e?.maxRetries||3,retryDelay:e?.retryDelay||100,fallbackStrategy:e?.fallbackStrategy||"best-effort",enableLogging:e?.enableLogging||!1,onError:e?.onError,onRecovery:e?.onRecovery}),this.remarkProcessor=nW().use(op).use(ll,["yaml"]).use(cg).use(cI,{strict:e?.strict||!1}).use(o6),this.registry=new cA,this.registerConverters()}catch(e){throw new cC("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new u_({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!r.success)throw r.error||Error("ADF to Markdown conversion failed");return r.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new cQ({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!r.success)throw r.error||Error("Markdown to ADF conversion failed");return r.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!r.success)throw r.error||Error("Async Markdown to ADF conversion failed");return r.data}async validateMarkdownAsync(e){let t=await this.mdToAdfEngine.validate(e);return{valid:t.valid,errors:t.errors.map(e=>({message:e})),warnings:t.warnings}}async getStats(e){return await this.mdToAdfEngine.getStats(e)}stringify(e,t){return this.adfToMarkdown(e,t)}async stringifyAsync(e,t){return this.adfToMarkdownWithRecovery(e,t)}validateAdf(e){return new cE().validate(e)}validateMarkdown(e){return new cT().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new cY,new cX,new c0,new c1,new c4,new c3,new c2,new c6,new c9,new c8,new c5,new c7,new ue,new ut,new ur,new ui,new ua,new un,new us,new uo,new ul,new uc,new uu,new ud,new up,new um]),this.registry.registerMarks([new uh,new uf,new ug,new uy,new uv,new ub,new uw,new ux,new uk])}convertAdfToMarkdown(e){return this.adfToMdEngine.convert(e)}convertMdastToAdf(e){return this.mdToAdfEngine.convert(e)}fallbackConversion(e){return this.mdToAdfEngine.convert(e)}countNodes(e){let t=0;for(let r of e)t++,r.content&&Array.isArray(r.content)&&(t+=this.countNodes(r.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},uS=e.i(378731);let uE=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function uT(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function uC(e,t){return uS.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,r)=>t?`[${r}](${t}/browse/${r})`:`**${r}**`))}let uR=new uI;function uP(e,t){if(null==e)return null;let r=function(e){if(uT(e))return"ADF";let t="string"==typeof e?e:"";return uE.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),a="ADF"===r?function(e){try{return uR.adfToMarkdown(e)}catch{return function e(t){return t&&"object"==typeof t?["string"==typeof t.text?t.text:"",...Array.isArray(t.content)?t.content.map(e).filter(Boolean):[]].filter(Boolean).join("\n"):""}(e)}}(e):"JIRA_WIKI"===r?uC(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:uS.default.to_jira(a)}}function uA(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?uC(t):t,i=uR.markdownToAdf(r);if(!uT(i))throw Error("The Jira text could not be converted to valid ADF");return i}let uD="default",uO=["summary","status","issuetype","priority","assignee","project","updated"],uj=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function uN(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function uq(e){return uN(e)?e:{}}function uU(e){return Array.isArray(e)?e:[]}function uL(e){return"string"==typeof e&&e.length>0?e:null}function uF(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function uM(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function uB(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function uz(e){return uU(uB(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function uK(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):uN(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function uG(e){if(!uN(e))return null;let t=e.status??uq(e.response).status;return"number"==typeof t?t:null}function uH(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function uZ(e){return uL(uq(uq(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function uV(e){let t=uq(e),r=uL(t.displayName);if(!r)return null;let i=uq(t.avatarUrls);return{accountId:uL(t.accountId),displayName:r,avatarUrl:uL(i["48x48"])??uL(i["32x32"])??uL(i["24x24"])}}function uJ(e){return uU(e).map(uq).map(e=>({id:uL(e.id),name:uL(e.name)??"Unknown"}))}function uW(e,t){let r=uq(e),i=uL(r.key);if(!i)return null;let a=uq(r.fields);return{relationship:t,key:i,summary:uL(a.summary)??i,status:uL(uq(a.status).name)}}function uQ(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function uY(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function uX(e){return 0===e.length?{source:"CACHE",stale:!1,fetchedAt:new Date(0).toISOString()}:{source:e.some(e=>"ERROR"===e.source)?"ERROR":e.some(e=>"LIVE"===e.source)?"LIVE":"CACHE",stale:e.some(e=>e.stale),fetchedAt:new Date(Math.max(...e.map(e=>e.fetchedAt.getTime()))).toISOString()}}function u0(e){let t=uq(e.fields),r=uq(t.status),i=uq(r.statusCategory),a=uq(t.assignee),n=uq(a.avatarUrls),s=uq(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:uL(t.summary)??o,statusId:uL(r.id)??uL(r.name)??"unknown",status:uL(r.name)??"Unknown",statusCategory:uL(i.key)??uL(i.name)??"unknown",issueType:uL(uq(t.issuetype).name),priority:uL(uq(t.priority).name),assignee:uL(a.displayName),assigneeAccountId:uL(a.accountId),assigneeAvatarUrl:uL(n["48x48"])??uL(n["32x32"]),projectKey:uL(s.key)??uZ(e),updatedAt:uL(t.updated)}}function u1(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let u4=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function u3(e){return u4.has(e)?e:"ALL"}class u2{inFlight=new Map;clients;lastPrunedAt=0;async getSettings(){let e=await (0,h.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:!!t.apiToken,cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,h.getPrismaClient)(),r=function(e){let t=new URL(e.trim());if("https:"!==t.protocol)throw Error("Jira Cloud site URL must use HTTPS");if(!t.hostname.toLowerCase().endsWith(".atlassian.net"))throw Error("Only Jira Cloud *.atlassian.net sites are supported");if(t.username||t.password||t.search||t.hash)throw Error("Jira site URL must not include credentials, query, or fragment");return t.origin}(e.siteUrl),i=e.email.trim();if(!/^\S+@\S+\.\S+$/.test(i))throw Error("A valid Jira email is required");let a=await t.jiraSettings.findUnique({where:{id:uD}}),n=e.apiToken?.trim()||a?.apiToken||null,s=!!(a?.siteUrl&&a.siteUrl!==r);if(s&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let o=a?.siteUrl!==r||a?.email!==i||a?.apiToken!==n;return await t.$transaction(async e=>{s&&await e.jiraProject.deleteMany(),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:uD},create:{id:uD,siteUrl:r,email:i,apiToken:n,cacheTtlSeconds:300},update:{siteUrl:r,email:i,apiToken:n}})}),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,h.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany(),e.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:300},update:{email:null,apiToken:null}})]),this.clients=void 0,this.getSettings()}async updateCacheTtl(e){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let t=await (0,h.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),this.getSettings()}async testConnection(){let e=await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",force:!0,allowStaleOnError:!1,fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}});if(e.stale)throw Error("Jira connection test failed because the live request failed");let t=uq(e.value);return{accountId:uL(t.accountId),displayName:uL(t.displayName)??"Jira user",emailAddress:uL(t.emailAddress),cache:uY(e)}}async listProjects(){let e=await (0,h.getPrismaClient)();return(await e.jiraProject.findMany({include:{sources:{orderBy:[{position:"asc"},{createdAt:"asc"}]}},orderBy:[{position:"asc"},{createdAt:"asc"}]})).map(e=>({id:e.id,jiraId:e.jiraId,key:e.key,name:e.name,avatarUrl:e.avatarUrl,position:e.position,ticketAssignmentFilter:u3(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:uz(e.completedStatusIdsJson),branchNamingScript:e.branchNamingScript??nI,sources:e.sources.map(uQ)}))}async projectStatuses(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!r)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:r.jiraId},requestSummary:`Statuses for project ${r.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(r.jiraId)}}),a=new Map;for(let e of uU(i.value).map(uq))for(let t of uU(e.statuses).map(uq)){let e=uL(t.id),r=uL(t.name);if(!e||!r||a.has(e))continue;let i=uq(t.statusCategory);a.set(e,{id:e,name:r,category:uL(i.key)??uL(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>u1(e.category)-u1(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!u4.has(e.ticketAssignmentFilter))throw Error("Invalid Jira ticket assignment filter");let t=[...new Set(e.completedStatusIds.map(e=>e.trim()).filter(Boolean))].slice(0,200),r=await (0,h.getPrismaClient)();return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t)}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,h.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await nE(t,i.key);return await r.jiraProject.update({where:{id:e},data:{branchNamingScript:a}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let r=await this.cachedCall({operation:"PROJECTS",params:{startAt:t,maxResults:100},requestSummary:`Visible projects from ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.searchProjects({startAt:t,maxResults:100,orderBy:"name"})},itemCount:e=>uU(uq(e).values).length}),i=uq(r.value),a=uU(i.values).map(uq);e.push(...a.flatMap(e=>{let t=uL(e.id),r=uL(e.key),i=uL(e.name);if(!t||!r||!i)return[];let a=uq(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:uL(a["48x48"])??uL(a["32x32"])}]}));let n=uF(i.total)??e.length;if(0===a.length||e.length>=n)break;t+=a.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let r=uq((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),i=uL(r.key),a=uL(r.name),n=uL(r.id);if(!i||!a||!n)throw Error("Jira returned an incomplete project");let s=uq(r.avatarUrls),o=await (0,h.getPrismaClient)(),l=await o.jiraProject.aggregate({_max:{position:!0}});return await o.jiraProject.create({data:{id:(0,d.randomUUID)(),jiraId:n,key:i,name:a,avatarUrl:uL(s["48x48"])??uL(s["32x32"]),position:(l._max.position??-1)+1,branchNamingScript:nI}}),this.listProjects()}async removeProject(e){let t=await (0,h.getPrismaClient)(),r=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:r}}}),await t.jiraProject.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async createSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,h.getPrismaClient)();if(!await i.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let a=await i.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await i.jiraSource.create({data:{id:(0,d.randomUUID)(),projectId:e.projectId,name:r,kind:e.kind,value:t.value,boardId:t.boardId,position:(a._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,h.getPrismaClient)();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:r,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await (0,h.getPrismaClient)();return await t.$transaction(async t=>{await t.jiraCacheEntry.deleteMany({where:{sourceId:e}}),await t.jiraSource.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async ticketBoard(e,t=!1){var r;let i,a,n,s=await (0,h.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l="BOARD"===o.kind?await this.loadBoardSource(uQ(o),t):await this.loadJqlSource(uQ(o),t),c={ticketAssignmentFilter:u3(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:uz(o.project.completedStatusIdsJson)},u="ALL"===c.ticketAssignmentFilter?null:await this.currentAccountId();return r={source:uQ(o),...l},i=c.hideCompletedTickets?new Set(c.completedStatusIds):new Set,a=new Set(r.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=r.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===c.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===c.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===u:null!==u&&e.assigneeAccountId===u&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))}}async ticket(e,t=!1){let r=uM(e),i=await this.cachedCall({operation:"ISSUE",params:{issueKey:r,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${r} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:r,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===i.source&&await this.storeDetail(i.entryId,i.value,i.fetchedAt);let a=[],n=[],s=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:r,startAt:s,maxResults:100},requestSummary:`Comments for ${r} from ${s}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:r,startAt:s,maxResults:100,orderBy:"created"})},itemCount:e=>uU(uq(e).comments).length});a.push(e);let i=uq(e.value),o=uU(i.comments);n.push(...o);let l=uF(i.total)??n.length;if(0===o.length||n.length>=l)break;s+=o.length}let o=new Date(Math.min(...a.map(e=>e.fetchedAt.getTime())));await this.storeComments(r,n,o,a.map(e=>e.entryId));let l=await this.requireCredentials();return this.normalizeTicketDetail(i.value,n,l.siteUrl,uY(i),uX(a))}async assignableUsers(e,t=""){let r=uM(e),i=t.trim().slice(0,100),a=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:r,query:i,maxResults:50},requestSummary:`Assignable users for ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:r,query:i,maxResults:50,recommend:!0})},itemCount:e=>uU(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),uU(a.value).map(uV).filter(e=>null!==e)}async ticketTransitions(e){let t=uM(e),r=await this.cachedCall({operation:"ISSUE_TRANSITIONS",params:{issueKey:t,expand:"transitions.fields"},requestSummary:`Available transitions for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getTransitions({issueIdOrKey:t,expand:"transitions.fields"})},itemCount:e=>uU(uq(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),uU(uq(r.value).transitions).map(uq).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=uL(e.id),r=uL(e.name);if(!t||!r)return[];let i=uq(e.to),a=uq(i.statusCategory),n=Object.entries(uq(e.fields)).filter(([,e])=>!0===uq(e).required).map(([e,t])=>uL(uq(t).name)??e);return[{id:t,name:r,toStatusId:uL(i.id),toStatus:uL(i.name)??r,toStatusCategory:uL(a.key)??uL(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=uM(e),r=await this.cachedCall({operation:"ISSUE_EDIT_META",params:{issueKey:t},requestSummary:`Editable fields for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getEditIssueMeta({issueIdOrKey:t})},itemCount:e=>Object.keys(uq(uq(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(uq(uq(r.value).fields)).map(([e,t])=>{let r=uq(t);return{id:e,name:uL(r.name)??e,required:!0===r.required,schemaType:uL(uq(r.schema).type),allowedValues:uU(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=uq(e),r=uL(t.name)??uL(t.value)??uL(t.displayName)??uL(t.key);return r?[{id:uL(t.id)??uL(t.accountId)??uL(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,r=0){let i=uM(e),a=this.validatePagination(t,r),n=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Changelog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>uU(uq(e).values).length});await this.linkCacheEntryToIssue(i,n.entryId);let s=uF(uq(n.value).total)??0,o=Math.min(a.limit,Math.max(0,s-a.offset)),l=Math.max(0,s-a.offset-o);if(0===o)return{...a,total:s,items:[],cache:uY(n)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:l,maxResults:o},requestSummary:`Changelog for ${i} from ${l}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:l,maxResults:o})},itemCount:e=>uU(uq(e).values).length});await this.linkCacheEntryToIssue(i,c.entryId);let u=uU(uq(c.value).values).map(uq).reverse().map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),createdAt:uL(e.created),items:uU(e.items).map(uq).map(e=>({field:uL(e.field)??"Field",fieldId:uL(e.fieldId),from:uL(e.fromString)??uL(e.from),to:uL(e.toString)??uL(e.to)}))}));return{...a,total:s,items:u,cache:uX([n,c])}}async ticketWorklogs(e,t=50,r=0){let i=uM(e),a=this.validatePagination(t,r),n=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Worklog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>uU(uq(e).worklogs).length});await this.linkCacheEntryToIssue(i,n.entryId);let s=uF(uq(n.value).total)??0,o=Math.min(a.limit,Math.max(0,s-a.offset)),l=Math.max(0,s-a.offset-o);if(0===o)return{...a,total:s,items:[],cache:uY(n)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:l,maxResults:o},requestSummary:`Worklogs for ${i} from ${l}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:l,maxResults:o})},itemCount:e=>uU(uq(e).worklogs).length});await this.linkCacheEntryToIssue(i,c.entryId);let u=await this.requireCredentials(),p=uU(uq(c.value).worklogs).map(uq).reverse().map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),comment:uP(e.comment??null,u.siteUrl),timeSpent:uL(e.timeSpent),timeSpentSeconds:uF(e.timeSpentSeconds),startedAt:uL(e.started),createdAt:uL(e.created),updatedAt:uL(e.updated)}));return{...a,total:s,items:p,cache:uX([n,c])}}async addComment(e,t){let r=uM(e);if(!t.value.trim())throw Error("Comment text is required");let i=uA(t);return this.mutateTicket(r,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:r,comment:i})})}async assignTicket(e,t){let r=uM(e),i=t?.trim()||null;return this.mutateTicket(r,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:r,accountId:i})})}async transitionTicket(e,t){let r=uM(e),i=(await this.ticketTransitions(r)).find(e=>e.id===t);if(!i)throw Error("The Jira transition is not available");if(i.requiredFields.length>0)throw Error(`This transition requires fields that must be completed in Jira: ${i.requiredFields.join(", ")}`);return this.mutateTicket(r,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:r,transition:{id:i.id}})})}async updateTicket(e){let t=uM(e.issueKey),r=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},a=e=>{let t=r.get(e);if(!t)throw Error(`${e} is not editable on this ticket`);return t},n=t=>Object.prototype.hasOwnProperty.call(e,t);if(n("summary")){a("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=a("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=uA(e.description))}if(n("priorityId")){let t=a("priority"),r=e.priorityId?.trim()||null;if(!r&&t.required)throw Error("Priority is required");if(r&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===r))throw Error("The selected priority is not available");i.priority=r?{id:r}:null}n("labels")&&(a("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let s=(t,r)=>{if(!n(t))return;let s=a(r),o=[...new Set(e[t]??[])];if(s.allowedValues.length>0&&o.some(e=>!s.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${s.name} value is not available`);i[r]=o.map(e=>({id:e}))};if(s("componentIds","components"),s("fixVersionIds","fixVersions"),s("affectedVersionIds","versions"),n("dueDate")){let t=a("duedate"),r=e.dueDate?.trim()||null;if(r&&!/^\d{4}-\d{2}-\d{2}$/.test(r))throw Error("Due date must use YYYY-MM-DD");if(!r&&t.required)throw Error("Due date is required");i.duedate=r}if(0===Object.keys(i).length)throw Error("At least one editable Jira field is required");return this.mutateTicket(t,"EDIT_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.editIssue({issueIdOrKey:t,fields:i})})}async branchTicket(e){let t=uM(e),r=t.replace(/-\d+$/,""),i=await (0,h.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{key:!0,branchNamingScript:!0}});if(!a)throw Error(`Jira project ${r} is not managed; add it in Manage Jira projects and sources`);let n=await this.cachedCall({operation:"ISSUE_BRANCH",params:{issueKey:t,fields:["summary","issuetype","project"]},requestSummary:`Branch details for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:t,fields:["summary","issuetype","project"],updateHistory:!1})}});await this.linkCacheEntryToIssue(t,n.entryId);let s=uq(n.value.fields);if((uL(uq(s.project).key)??uZ(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:uL(s.summary)??t,ticketType:uL(uq(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??nI}}async clearCache(){let e=await (0,h.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(uM(e)),!0}async invalidateIssueCaches(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0)}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,h.getPrismaClient)(),[a,n,s]=await Promise.all([i.jiraCachedTicket.findMany({take:r.limit,skip:r.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...r,total:n,items:a.map(e=>this.cachedTicketView(e,s.cacheTtlSeconds))}}async cachedTicket(e){let t=await (0,h.getPrismaClient)(),[r,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return r?{...this.cachedTicketView(r,i.cacheTtlSeconds),summaryData:uB(r.summaryJson),detailData:uB(r.detailJson),commentsData:uB(r.commentsJson),cacheEntries:r.cacheEntries.map(e=>({id:e.cacheEntry.id,operation:e.cacheEntry.operation,fetchedAt:e.cacheEntry.fetchedAt.toISOString()})).sort((e,t)=>t.fetchedAt.localeCompare(e.fetchedAt))}:null}async listApiCalls(e=50,t=0){let r=this.validatePagination(e,t);await this.pruneLogs();let i=await (0,h.getPrismaClient)(),[a,n]=await Promise.all([i.jiraApiCallLog.findMany({take:r.limit,skip:r.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...r,total:n,items:a.map(e=>({id:e.id,operation:e.operation,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,itemCount:e.itemCount,servedStale:e.servedStale,createdAt:e.createdAt.toISOString()}))}}async cacheMetrics(){await this.pruneLogs();let e=await (0,h.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-uj.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:uj.map(e=>this.metricWindow(e.window,r.filter(r=>r.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(r.map(e=>e.operation))].sort().map(e=>({operation:e,windows:uj.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,h.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:uD}});if(!t?.siteUrl||!t.email||!t.apiToken)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:t.apiToken,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,d.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let r={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new nv(r),agile:new iU(r)},this.clients}async currentAccountId(){let e=uL(uq((await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}})).value).accountId);if(!e)throw Error("Jira did not return the current user ID");return e}async linkCacheEntryToIssue(e,t){let r=await (0,h.getPrismaClient)();await r.$transaction(async r=>{await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,r){let i=await this.requireCredentials(),a=Date.now();try{await r(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-a})}catch(n){let r=uH(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:uG(n),error:r}),Error(r)}await this.invalidateIssueCaches(e);try{return await this.ticket(e,!0)}catch(e){throw Error(`Jira accepted the update, but refreshed ticket details could not be loaded: ${uH(e,i.apiToken)}`)}}cacheKey(e,t,r){return(0,d.createHash)("sha256").update(uK({siteUrl:e,operation:t,params:r})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),r=await (0,h.getPrismaClient)(),i=this.cacheKey(t.siteUrl,e.operation,e.params),a=Date.now(),n=await r.jiraCacheEntry.findUnique({where:{cacheKey:i}}),s=null!==n&&Date.now()-n.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&s)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-a,itemCount:e.itemCount?.(uB(n.responseJson))??null,sourceId:e.sourceId}),{value:uB(n.responseJson),source:"CACHE",stale:!1,fetchedAt:n.fetchedAt,entryId:n.id};let o=this.inFlight.get(i);if(o){let t=await o;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-a,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let l=(async()=>{try{let t=await e.fetcher(),n=new Date,s=await r.jiraCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,d.randomUUID)(),cacheKey:i,operation:e.operation,paramsJson:uK(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:uK(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-a,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:n,entryId:s.id}}catch(i){let r=null!==n&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-a,statusCode:uG(i),error:uH(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:uB(n.responseJson),source:"ERROR",stale:!0,fetchedAt:n.fetchedAt,entryId:n.id};throw Error(uH(i,t.apiToken))}})();this.inFlight.set(i,l);try{return await l}finally{this.inFlight.delete(i)}}async logCall(e){let t=await (0,h.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,d.randomUUID)(),operation:e.operation,requestSummary:e.requestSummary.slice(0,1e3),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error??null,itemCount:e.itemCount??null,servedStale:e.servedStale??!1,sourceId:e.sourceId??null}})}validateSourceName(e){let t=e.trim();if(!t||t.length>100)throw Error("Source name must be 1 to 100 characters");return t}async validateSource(e,t){let r=t.trim();if(!r)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:r},requestSummary:`Validate JQL: ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:r,maxResults:1,fields:["key"],failFast:!0})}}),{value:r,boardId:null};let i=function(e,t){let r=new URL(e.trim());if(r.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=r.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),a=r.searchParams.get("rapidView"),n=Number(i?.[1]??a);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:r.toString()}}(r,(await this.requireCredentials()).siteUrl);return await this.cachedCall({operation:"BOARD",params:{boardId:i.boardId},requestSummary:`Board ${i.boardId}`,fetcher:async()=>{let{agile:e}=await this.getClients();return e.board.getBoard({boardId:i.boardId})}}),{value:i.normalizedUrl,boardId:i.boardId}}async loadJqlSource(e,t){let r,i=[],a=[],n=[],s=!1;do{let o=Math.min(100,1e3-i.length),l=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:r??null,maxResults:o,fields:uO},requestSummary:`JQL ${e.name}${r?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:r,maxResults:o,fields:uO})},itemCount:e=>e.issues?.length??0});a.push(l);let c=l.value.issues??[];i.push(...c),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,c,l.fetchedAt),r=l.value.nextPageToken,i.length>=1e3&&r&&(s=!0)}while(r&&i.length<1e3)return this.buildBoardResult(i,a,n,s)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let r=await this.cachedCall({operation:"BOARD",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getBoard({boardId:e.boardId})}}),i=await this.cachedCall({operation:"BOARD_CONFIGURATION",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId} configuration`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getConfiguration({boardId:e.boardId})}}),a=[r,i],n=[],s=[],o=!1;if("scrum"===(uL(r.value.type)??"").toLowerCase()){let r=await this.cachedCall({operation:"SPRINTS",params:{boardId:e.boardId,state:"active"},requestSummary:`Active sprints for board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getAllSprints({boardId:e.boardId,state:"active",startAt:0,maxResults:100})},itemCount:e=>uU(e.values).length});a.push(r);let i=uU(r.value.values).map(uq);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=uF(r.id);if(!i||n.length>=1e3)continue;let l=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:uO}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...l.issues),a.push(...l.results),s.push(...l.warnings),o||=l.truncated}}else{let r=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,r)=>({boardId:e.boardId,startAt:t,maxResults:r,fields:uO}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...r.issues),a.push(...r.results),s.push(...r.warnings),o=r.truncated}let l=[...new Map(n.map(e=>[e.key??e.id,e])).values()],c=new Map;return uU(uq(i.value.columnConfig).columns).map(uq).forEach((e,t)=>{uU(e.statuses).map(uq).forEach(e=>{let r=uL(e.id);r&&c.set(r,t)})}),this.buildBoardResult(l,a,s,o,c)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],c=0,u=1/0,d=!1;for(;c<u&&s.length+n<1e3;){let d=i(c,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${c}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let m=p.value.issues??[];if(s.push(...m),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,m,p.fetchedAt),u=p.value.total??s.length,0===m.length)break;c+=m.length}return s.length+n>=1e3&&c<u&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(u0),s=[...new Map(n.map(e=>[e.status,e])).values()];return s.sort((e,t)=>{let r=a?.get(e.statusId),i=a?.get(t.statusId);return void 0!==r||void 0!==i?(r??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):u1(e.statusCategory)-u1(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:uX(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,h.getPrismaClient)();await i.$transaction(async i=>{for(let e of t)e.key&&await i.jiraCachedTicket.upsert({where:{issueKey:e.key},create:{issueKey:e.key,projectKey:uZ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:uZ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let a=[...new Set(t.map(e=>e.key).filter(Boolean))];a.length>0&&await i.jiraCacheEntryIssue.createMany({data:a.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,r){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await (0,h.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:uZ(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:uZ(t),detailJson:JSON.stringify(t),detailFetchedAt:r}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,r,i){let a=await (0,h.getPrismaClient)();await a.$transaction(async a=>{for(let n of(await a.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:r},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:r}}),i))await a.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,r,i,a){let n=u0(e),s=uq(e.fields),o=uq(e.names),l=uq(e.schema),c=[];for(let e of uU(s.issuelinks).map(uq)){let t=uq(e.type),r=uW(e.outwardIssue,uL(t.outward)??"relates to"),i=uW(e.inwardIssue,uL(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let u=uW(s.parent,"parent"),p=uU(s.subtasks).map(e=>uW(e,"subtask")).filter(e=>null!==e),m=uU(s.sprint).concat(uU(s.closedSprints)).map(uq).map(e=>uL(e.name)).filter(e=>!!e),h=t.map(uq).map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),body:e.body??null,content:uP(e.body??null,r),createdAt:uL(e.created),updatedAt:uL(e.updated)}));return{...n,jiraUrl:`${r}/browse/${n.key}`,description:s.description??null,descriptionContent:uP(s.description??null,r),reporter:uV(s.reporter),creator:uV(s.creator),labels:uU(s.labels).filter(e=>"string"==typeof e),components:uJ(s.components),fixVersions:uJ(s.fixVersions),affectedVersions:uJ(s.versions),sprintNames:[...new Set(m)],parent:u,subtasks:p,issueLinks:c,attachments:uU(s.attachment).map(uq).map(e=>({id:uL(e.id)??(0,d.randomUUID)(),filename:uL(e.filename)??"Attachment",contentUrl:uL(e.content),mimeType:uL(e.mimeType),size:uF(e.size),author:uV(e.author),createdAt:uL(e.created)})),comments:h,createdAt:uL(s.created),dueAt:uL(s.duedate),resolvedAt:uL(s.resolutiondate),timeTracking:s.timetracking??null,allFields:Object.entries(s).map(([e,t])=>{let i=uq(l[e]),a="string"==typeof t||uN(t)&&"doc"===t.type?uP(t,r):null;return{id:e,name:uL(o[e])??e,schemaType:uL(i.type),custom:!0===i.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:i,commentsCache:a}}cachedTicketView(e,t){let r=u0(uq(uB(e.detailJson)??uB(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",a=[e.summaryFetchedAt,e.detailFetchedAt,e.commentsFetchedAt].filter(e=>null!==e).some(e=>Date.now()-e.getTime()>=1e3*t);return{issueKey:e.issueKey,projectKey:e.projectKey,summary:r.summary,status:"Unknown"===r.status?null:r.status,coverage:i,stale:a,summaryFetchedAt:e.summaryFetchedAt?.toISOString()??null,detailFetchedAt:e.detailFetchedAt?.toISOString()??null,commentsFetchedAt:e.commentsFetchedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}validatePagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("Pagination limit must be from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Pagination offset must be non-negative");return{limit:e,offset:t}}metricWindow(e,t){return{window:e,total:t.length,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===t.length?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length)}}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,h.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}e.s(["JiraService",0,u2],126223),e.s([],151666)},396763,504173,925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(750227),o=e.i(119909);e.i(151666);var l=e.i(468399),c=e.i(984179);let u="default",d=["QUEUED","RUNNING"],p=["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"],m=new Set([o.WORKTREE_DIFF_JOB_KIND,o.WORKTREE_DIFF_ASSET_JOB_KIND]),h=["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],f={codebase:{include:{agent:!0,repository:{include:{projects:{where:{type:"IOS_APP"},include:{configurations:{select:{id:!0}}}}}},jobs:{where:{status:{in:d}},orderBy:{createdAt:"desc"},take:1}}},tags:{include:{tag:!0}},builds:{orderBy:{createdAt:"desc"},take:1,select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,finishedAt:!0,artifacts:{select:{id:!0,kind:!0}}}},_count:{select:{builds:{where:{status:{in:["QUEUED","PREPARING","RUNNING"]}}}}}};function g(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=a.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function y(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function v(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function b(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function w(e,t){if(!t)return e;let r=b(t);if(r!==b(e))return e;let i=r?s.win32:s.posix,a=i.relative(t,e);return i.isAbsolute(a)||".."===a||a.startsWith(`..${i.sep}`)?e:a||"."}function x(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||"Worktree job failed");let t=JSON.parse(e.resultJson);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Worktree job returned an invalid result");return t}e.s(["WorktreesService",0,class{agentControl;jiraService;gitHubService;skillsService;pullRequestCache;watchDemand;constructor(e,t,r,i){this.agentControl=e,this.jiraService=t,this.gitHubService=r,this.skillsService=i,this.pullRequestCache=new Map,this.watchDemand=new Map,this.agentControl.registerCompletionHandler(o.WORKTREE_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_BRANCH_JOB_KIND,e=>this.projectBranchOperation(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_MOVE_PUSH_JOB_KIND,e=>this.advanceMoveAfterPush(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_MOVE_CHECKOUT_JOB_KIND,e=>this.advanceMoveAfterCheckout(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_DELETE_JOB_KIND,e=>this.projectDeleteOperation(e))}async settings(){return(await (0,i.getPrismaClient)()).worktreeSettings.upsert({where:{id:u},create:{id:u,editorVariant:"CODE"},update:{}})}async saveSettings(e){if(!["CODE","CODE_INSIDERS","NONE"].includes(e))throw Error("Unknown editor setting");let t=await (0,i.getPrismaClient)(),r=await t.worktreeSettings.upsert({where:{id:u},create:{id:u,editorVariant:e},update:{editorVariant:e}});return this.publish(null,null),r}async requestRefresh(){let e=await (0,i.getPrismaClient)(),t=await e.codebase.findMany({select:{agentId:!0}});return this.agentControl.requestCodebaseReconcile(t.map(e=>e.agentId))}invalidatePullRequestsForOrigin(e){let t=e.toLowerCase();for(let e of this.pullRequestCache.keys())e.toLowerCase()===t&&this.pullRequestCache.delete(e)}async cleanupExpired(){let e=await (0,i.getPrismaClient)();await e.worktree.deleteMany({where:{missingAt:{lt:new Date(Date.now()-6048e5)}}})}view(e,t=""){let r=e.codebase.repository.jiraBranchRegex??t;return{...e,relativePath:w(e.folder,e.codebase.agent.baseRepoDirectory),tags:e.tags.map(e=>e.tag),activeJob:e.codebase.jobs.find(t=>t.worktreeId===e.id)??e.codebase.jobs[0]??null,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null,ticketKey:function(e,t){if(!e||!t)return null;try{let r=RegExp(t,"i").exec(e),i=(r?.[1]??r?.[0])?.trim();return i?i.toUpperCase():null}catch{return null}}(e.branch,String(r)),ticketTitle:null,ticketStatus:null,pullRequest:null,latestBuild:e.builds?.[0]?{...e.builds[0],outOfDate:(0,c.buildOutOfDate)({...e.builds[0],worktree:e})}:null}}async overview(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),[t,r,a,n,s,o]=await Promise.all([e.worktree.findMany({where:{missingAt:null},include:f,orderBy:[{codebase:{agent:{name:"asc"}}},{codebase:{repository:{name:"asc"}}},{primary:"desc"},{branch:"asc"},{folder:"asc"}]}),e.worktreeTag.findMany({orderBy:{name:"asc"}}),this.settings(),e.codebaseSettings.findUnique({where:{id:"default"}}),e.worktree.count({where:{missingAt:{not:null}}}),e.worktreeMove.findMany({where:{status:{in:p}},orderBy:{createdAt:"asc"}})]),l=n?.defaultJiraBranchRegex??"",c=t.map(e=>this.view(e,l)),u=[...new Set(c.map(e=>e.codebase.repository.canonicalOrigin))],d=new Map;await Promise.all(u.map(async e=>{let t=this.pullRequestCache.get(e);if(t&&t.expiresAt>Date.now())return void d.set(e,t.items);try{let t=await this.gitHubService.pullRequestsForOrigin(e);this.pullRequestCache.set(e,{items:t,expiresAt:Date.now()+6e4}),d.set(e,t)}catch{d.set(e,[])}}));let m=[...new Set(c.map(e=>e.ticketKey).filter(Boolean))],h=new Map;for(let e of(await Promise.all(m.map(async e=>{try{let t=await this.jiraService.cachedTicket(e)??await this.jiraService.ticket(e);h.set(e,{title:t.summary,status:t.status})}catch{}})),c))e.ticketTitle=e.ticketKey?h.get(e.ticketKey)?.title??null:null,e.ticketStatus=e.ticketKey?h.get(e.ticketKey)?.status??null:null,e.pullRequest=d.get(e.codebase.repository.canonicalOrigin)?.find(t=>t.headRefName===e.branch)??null;let g=new Map;for(let e of c){let t=e.codebase.agent,r=g.get(t.id);r||(r={agent:t,codebases:[],codebaseMap:new Map},g.set(t.id,r));let i=r.codebaseMap.get(e.codebase.id);i||(i={codebase:e.codebase,repository:e.codebase.repository,worktrees:[],iosBuildConfigured:e.codebase.repository.projects?.some(e=>e.configurations.length>0)??!1},r.codebaseMap.set(e.codebase.id,i),r.codebases.push(i)),i.worktrees.push(e)}return{agents:[...g.values()].map(e=>({agent:e.agent,codebases:e.codebases})),tags:r,settings:a,hiddenCount:s,activeMoves:o}}async hidden(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),t=await e.codebaseSettings.findUnique({where:{id:"default"}});return(await e.worktree.findMany({where:{missingAt:{not:null}},include:f,orderBy:{missingAt:"desc"}})).map(e=>this.view(e,t?.defaultJiraBranchRegex??""))}async report(e,r){let a=await (0,i.getPrismaClient)(),n=[],s=!1;for(let i of r.slice(0,100)){let r=(0,o.parseCodebaseWorktreeReport)(i),l=await a.codebase.findUnique({where:{id:r.codebaseId}});if(!l||l.agentId!==e)throw Error("Codebase not found for this agent");let c=r.worktrees.slice(0,1e3).map(e=>(0,o.parseWorktreeInventoryItem)(e)),u=await a.worktree.findMany({where:{codebaseId:l.id},select:{gitDirectory:!0,folder:!0,missingAt:!0}}),d=new Map(u.map(e=>[e.gitDirectory,e])),p=new Set(c.map(e=>e.gitDirectory));s||=c.some(e=>{let t=d.get(e.gitDirectory);return!t||t.folder!==e.folder||null!==t.missingAt})||r.complete&&u.some(e=>null===e.missingAt&&!p.has(e.gitDirectory)),await a.$transaction(async e=>{await e.codebase.update({where:{id:l.id},data:{defaultBranch:r.defaultBranch,localBranchesJson:JSON.stringify(r.localBranches),remoteBranchesJson:JSON.stringify(r.remoteBranches),...r.fetchedAt?{lastFetchedAt:new Date(r.fetchedAt)}:{},...r.fetchAttemptedAt?{lastFetchAttemptAt:new Date(r.fetchAttemptedAt),lastFetchError:r.fetchError}:r.fetchError?{lastFetchError:r.fetchError}:{}}});let i=[];for(let r of c){i.push(r.gitDirectory);let a=await e.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:l.id,gitDirectory:r.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:l.id,gitDirectory:r.gitDirectory,...this.inventoryData(r)},update:{}});await e.worktree.updateMany({where:{id:a.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.checkedAt)}}]},data:{...this.inventoryData(r),missingAt:null}}),n.push(a.id)}r.complete&&await e.worktree.updateMany({where:{codebaseId:l.id,missingAt:null,...i.length?{gitDirectory:{notIn:i}}:{}},data:{missingAt:new Date}})}),this.publish(null,l.id)}return await this.cleanupExpired(),s&&await this.skillsService?.requestAutoReconcile(),a.worktree.findMany({where:{id:{in:n}},include:f})}async reportActivity(e,t){let r=(0,o.parseWorktreeActivityReport)(t),a=await (0,i.getPrismaClient)(),s=await a.worktree.findFirst({where:{codebaseId:r.codebaseId,gitDirectory:r.gitDirectory,missingAt:null,codebase:{agentId:e}},select:{id:!0,codebaseId:!0}});if(!s)throw Error("Worktree activity source was not found");let l=void 0!==r.branch||void 0!==r.headSha||void 0!==r.upstream||void 0!==r.ahead||void 0!==r.behind||void 0!==r.syncState||void 0!==r.baseAhead||void 0!==r.baseBehind,c=!0;(l||void 0!==r.hasStagedChanges||void 0!==r.hasUnstagedChanges||void 0!==r.codeStateHash||void 0!==r.pushStatus)&&(c=(await a.worktree.updateMany({where:{id:s.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.observedAt)}}]},data:{...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},lastCheckedAt:new Date(r.observedAt),...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.codeStateHash?{}:{codeStateHash:r.codeStateHash},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus}}})).count>0)&&this.publish(s.id,s.codebaseId);let u={worktreeId:s.id,...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus},observedAt:r.observedAt};return this.watchDemand.has(s.id)&&c&&n.agentEventBus.publish((0,n.worktreeInspectionTopic)(s.id),{worktreeInspectionChanged:u}),u}inventoryData(e){return{folder:e.folder,relativePath:e.relativePath,primary:e.primary,branch:e.branch,headSha:e.headSha,codeStateHash:e.codeStateHash??null,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,baseAhead:e.baseAhead,baseBehind:e.baseBehind,hasStagedChanges:e.hasStagedChanges??!1,hasUnstagedChanges:e.hasUnstagedChanges??!1,pushStatus:e.pushStatus??"UNKNOWN",availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt)}}async updateBaseBranch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.findUnique({where:{id:e},include:{codebase:!0}});if(!a||a.missingAt)throw Error("Worktree not found");let n=t?.trim()||null;if(n&&!v(a.codebase.remoteBranchesJson).includes(n))throw Error("The selected origin branch is unavailable; fetch and try again");let s=await r.worktree.update({where:{id:e},data:{baseBranchOverride:n},include:f});return this.publish(e,a.codebaseId),await this.restartWatch(e),this.view(s)}requireColor(e){if(null===e||""===e)return null;if(!h.includes(e))throw Error("Unknown worktree color");return e}async updateHighlight(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.update({where:{id:e},data:{highlightColor:this.requireColor(t)},include:f});return this.publish(e,a.codebaseId),this.view(a)}async setTags(e,t){let r=await (0,i.getPrismaClient)(),a=[...new Set(t)].slice(0,100);if(await r.worktreeTag.count({where:{id:{in:a}}})!==a.length)throw Error("One or more tags were not found");await r.$transaction([r.worktreeTagAssignment.deleteMany({where:{worktreeId:e}}),...a.length?[r.worktreeTagAssignment.createMany({data:a.map(t=>({worktreeId:e,tagId:t}))})]:[]]);let n=await r.worktree.findUniqueOrThrow({where:{id:e},include:f});return this.publish(e,n.codebaseId),this.view(n)}async saveTag(e){let r=e.name.trim();if(!r||r.length>40)throw Error("Tag names must contain 1–40 characters");let a=this.requireColor(e.color),n=await (0,i.getPrismaClient)(),s=(await n.worktreeTag.findMany()).find(e=>e.name.toLocaleLowerCase()===r.toLocaleLowerCase());if(s&&s.id!==e.id)throw Error("Tag names must be unique");let o=e.id?await n.worktreeTag.update({where:{id:e.id},data:{name:r,color:a}}):await n.worktreeTag.create({data:{id:(0,t.randomUUID)(),name:r,color:a}});return this.publish(null,null),o}async deleteTag(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeTag.deleteMany({where:{id:e}});return r.count&&this.publish(null,null),r.count>0}async repositoryTakenBranches(e){let t=await (0,i.getPrismaClient)();return new Set((await t.codebase.findMany({where:{repositoryId:e},select:{localBranchesJson:!0,remoteBranchesJson:!0,worktrees:{where:{missingAt:null},select:{branch:!0}}}})).flatMap(e=>[...v(e.localBranchesJson),...v(e.remoteBranchesJson),...e.worktrees.flatMap(e=>e.branch?[e.branch]:[])]))}requireBaseBranch(e,t){let r=t.trim();if(!r||!v(e.remoteBranchesJson).includes(r))throw Error("The selected origin base branch is unavailable; fetch and try again");return r}async ticketBranch(e,t,r){let i=t?.trim()??"",a=await this.jiraService.branchTicket(i),n=await (0,l.jiraBranchCandidates)(a.branchNamingScript,{ticketKey:a.ticketKey,type:a.ticketType??"",title:a.ticketTitle}),s=await this.repositoryTakenBranches(e.repositoryId),o=n.filter(e=>e===r||!s.has(e));if(!o.length)throw Error("Every generated ticket branch name is already taken");return{ticket:a,candidates:o}}async previewTicketBranch(e){let t=await (0,i.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e.codebaseId},include:{agent:!0,repository:!0}});if(!r)throw Error("Codebase not found");let a=null;if(e.worktreeId){let r=await t.worktree.findFirst({where:{id:e.worktreeId,codebaseId:e.codebaseId,missingAt:null},select:{branch:!0}});if(!r)throw Error("Worktree not found for this codebase");a=r.branch}let{ticket:n,candidates:s}=await this.ticketBranch(r,e.ticketKey,a);return{ticketKey:n.ticketKey,ticketTitle:n.ticketTitle,ticketType:n.ticketType,projectKey:n.projectKey,branchName:s[0]}}async resolveBranchSelection(e,t,r){let a=this.requireBaseBranch(e,t.baseBranch);if("TICKET"===t.mode){let{candidates:i}=await this.ticketBranch(e,t.ticketKey,r?.branch??null);return{baseBranch:a,mode:"NEW",candidates:i}}let n=t.branchName?.trim()??"";if(!(0,o.validGitBranchName)(n))throw Error("Enter a valid Git branch name");if("NEW"===t.mode){if((await this.repositoryTakenBranches(e.repositoryId)).has(n))throw Error(`Branch ${n} is already taken`);return{baseBranch:a,mode:"NEW",candidates:[n]}}if("EXISTING"!==t.mode)throw Error("Unknown worktree branch mode");if(!new Set([...v(e.localBranchesJson),...v(e.remoteBranchesJson)]).has(n))throw Error(`Existing branch ${n} is unavailable; refresh and try again`);let s=await (0,i.getPrismaClient)();if(await s.worktree.findFirst({where:{codebaseId:e.id,branch:n,missingAt:null,...r?{id:{not:r.id}}:{}},select:{id:!0}}))throw Error(`Branch ${n} is checked out in another worktree`);return{baseBranch:a,mode:"EXISTING",candidates:[n]}}async createWorktree(e){let t=await this.requireRunnableCodebase(e.codebaseId),r=await this.resolveBranchSelection(t,e.selection,null);return this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:o.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.id,rootFolder:t.folder,folder:null,gitDirectory:null,expectedOrigin:t.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CREATE",mode:r.mode,candidates:r.candidates,stashOnFailure:!1},idempotencyKey:`worktree:branch:create:${e.requestId}:${t.id}`,timeoutSeconds:600})}async changeWorktreeBranch(e){let t=await this.requireRunnable(e.worktreeId,o.WORKTREE_BRANCH_JOB_KIND),r=await this.resolveBranchSelection(t.codebase,e.selection,{id:t.id,branch:t.branch});return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CHANGE",mode:r.mode,candidates:r.candidates,stashOnFailure:!!e.stashOnFailure},idempotencyKey:`worktree:branch:change:${e.requestId}:${t.id}`,timeoutSeconds:600})}async getMove(e){return(await (0,i.getPrismaClient)()).worktreeMove.findUnique({where:{id:e}})}async moveWorktree(e){let r,a=await (0,i.getPrismaClient)(),n=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(n)return n;let s=await this.requireRunnable(e.sourceWorktreeId,o.WORKTREE_MOVE_PUSH_JOB_KIND);if(!s.branch||!s.headSha)throw Error("A named source branch is required");if(s.hasStagedChanges||s.hasUnstagedChanges||"READY"!==s.pushStatus)throw Error("The source branch must be clean and safely pushable before moving");if(e.deleteSource&&s.primary)throw Error("The primary worktree cannot be deleted after moving");if(e.deleteSource&&!y(s.codebase.agent).includes(o.WORKTREE_DELETE_JOB_KIND))throw Error("Source agent must be updated to remove the old worktree");let l=await this.requireRunnableCodebase(e.targetCodebaseId,o.WORKTREE_MOVE_CHECKOUT_JOB_KIND);if(s.codebase.repositoryId!==l.repositoryId||s.codebase.agentId===l.agentId)throw Error("The destination must be the same repository on another agent");let c=e.targetWorktreeId?await a.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:l.id,missingAt:null,availability:"AVAILABLE"}}):null;if(e.targetWorktreeId&&!c)throw Error("Destination worktree not found");if(await a.worktree.findFirst({where:{codebaseId:l.id,branch:s.branch,missingAt:null,...c?{id:{not:c.id}}:{}},select:{id:!0}}))throw Error("The source branch is already checked out in another destination worktree");let u=l.defaultBranch??s.codebase.defaultBranch;if(!u)throw Error("The destination default branch is unavailable");let d=(0,t.randomUUID)();try{r=await a.worktreeMove.create({data:{id:d,requestId:e.requestId,sourceWorktreeId:s.id,sourceCodebaseId:s.codebaseId,targetCodebaseId:l.id,targetWorktreeId:c?.id??null,destinationMode:c?"EXISTING":"NEW",branch:s.branch,headSha:s.headSha,baseBranch:u,deleteSource:e.deleteSource,status:"PUSHING"}})}catch(r){let t=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(t)return t;throw r}try{let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:o.WORKTREE_MOVE_PUSH_JOB_KIND,payload:{moveId:r.id,codebaseId:s.codebaseId,folder:s.folder,gitDirectory:s.gitDirectory,expectedOrigin:s.codebase.repository.canonicalOrigin,branch:s.branch,expectedHeadSha:s.headSha},idempotencyKey:`worktree:move:push:${r.id}`,timeoutSeconds:600});return r=await a.worktreeMove.update({where:{id:r.id},data:{sourceJobId:e.id}}),this.publish(s.id,s.codebaseId),r}catch(e){throw await a.worktreeMove.update({where:{id:r.id},data:{status:"FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}}async retryWorktreeMoveWithStash(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("This move is not waiting for a stash decision");let a=await this.createMoveCheckoutJob(r,!0);if(1!==(await t.worktreeMove.updateMany({where:{id:e,status:"AWAITING_STASH"},data:{status:"CHECKING_OUT",targetJobId:a.id,error:null}})).count){let r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}});if("AWAITING_STASH"!==r.status)return r;throw Error("The move state changed; refresh and try again")}return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),t.worktreeMove.findUniqueOrThrow({where:{id:e}})}async cancelWorktreeMove(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("Only a move waiting for a stash decision can be cancelled");let a=await t.worktreeMove.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date}});return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),a}async deleteWorktree(e){let t=await this.requireRunnable(e.worktreeId,o.WORKTREE_DELETE_JOB_KIND);if(t.primary)throw Error("The primary worktree cannot be deleted");if(e.deleteRemoteBranch&&(!t.branch||t.branch===t.codebase.defaultBranch))throw Error("The default remote branch cannot be deleted");return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.WORKTREE_DELETE_JOB_KIND,payload:{moveId:null,codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,branch:t.branch,defaultBranch:t.codebase.defaultBranch,deleteRemoteBranch:e.deleteRemoteBranch,requireClean:!1,expectedHeadSha:null},idempotencyKey:`worktree:delete:${e.requestId}:${t.id}`,timeoutSeconds:600})}async inspect(e,t){let r=await this.requireRunnable(e,o.WORKTREE_INSPECT_JOB_KIND),a=await this.createSerializedDiffJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:o.WORKTREE_INSPECT_JOB_KIND,payload:this.payload(r),idempotencyKey:`worktree:inspect:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id),t=x(e).detail;if(!t||"object"!=typeof t)throw Error("Invalid worktree detail");let r=Array.isArray(t.changes)?t.changes.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?{...e,changeType:"string"==typeof e.changeType?e.changeType:"MODIFIED"}:e):[];return{...t,changes:r,branchChanges:Array.isArray(t.branchChanges)?t.branchChanges:[],branchChangesTruncated:!0===t.branchChangesTruncated}}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async inspectDiff(e,t,r){let a=await this.requireRunnable(e,o.WORKTREE_DIFF_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedDiffJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DIFF_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path??null,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:null,side:null},idempotencyKey:`worktree:diff:${r}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(s.id),t=x(e).diff;if(!t||"object"!=typeof t)throw Error("Invalid worktree diff result");return t}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async prepareDiffAsset(e,t,r){let a=await this.requireRunnable(e,o.WORKTREE_DIFF_ASSET_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedDiffJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DIFF_ASSET_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:r,side:t.side},idempotencyKey:`worktree:diff-asset:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"});try{x(await this.waitForJob(s.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async diffAssetAgentId(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}});return r?.codebase.agentId??null}async runOperation(e,t,r){if(!o.WORKTREE_OPERATIONS.includes(t))throw Error("Unknown worktree operation");let i=await this.requireRunnable(e,o.WORKTREE_OPERATION_JOB_KIND),a=await this.settings();return this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:o.WORKTREE_OPERATION_JOB_KIND,payload:{...this.payload(i),operation:t,..."OPEN_EDITOR"===t?{editorVariant:a.editorVariant}:{}},idempotencyKey:`worktree:operation:${r}:${e}`,timeoutSeconds:"OPEN_EDITOR"===t?30:600})}payload(e){return{codebaseId:e.codebaseId,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async createSerializedDiffJob(e){let t=await (0,i.getPrismaClient)(),r=Date.now()+3e4;for(;Date.now()<r;){let i=await t.agentJob.findFirst({where:{codebaseId:e.codebaseId,status:{in:d}},select:{id:!0,idempotencyKey:!0,kind:!0}});if(i){if(i.idempotencyKey===e.idempotencyKey)return this.agentControl.createJob(e);if(!m.has(i.kind))throw Error("Another operation is active for this codebase");await this.waitForSerializedDiffJob(i.id,r);continue}try{return await this.agentControl.createJob(e)}catch(e){if(!function(e){if(!e||"object"!=typeof e||"P2002"!==e.code)return!1;let t=e.meta?.target;return Array.isArray(t)?t.includes("codebaseId"):"string"==typeof t&&t.includes("codebaseId")}(e))throw e}}throw Error("Another diff request is still active for this codebase")}async waitForSerializedDiffJob(e,t){let r=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e));try{for(;Date.now()<t;){let i=await this.agentControl.getJob(e);if(!i||!d.includes(i.status))return;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(0,t-Date.now())))])}throw Error("Another diff request is still active for this codebase")}finally{await r.return?.()}}async requireRunnable(e,t,r=!1){let a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!n||n.missingAt||"AVAILABLE"!==n.availability)throw Error("Worktree is unavailable");if(!g(n.codebase.agent))throw Error("Agent is offline");if(!y(n.codebase.agent).includes(t))throw Error("Agent must be updated to use worktrees");if(!r){let[e,t]=await Promise.all([a.agentJob.findFirst({where:{codebaseId:n.codebaseId,status:{in:d}}}),a.worktreeMove.findFirst({where:{status:{in:p},OR:[{sourceCodebaseId:n.codebaseId},{targetCodebaseId:n.codebaseId}]}})]);if(e||t)throw Error("Another operation is active for this codebase")}return n}async requireRunnableCodebase(e,t=o.WORKTREE_BRANCH_JOB_KIND){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0}});if(!a||"AVAILABLE"!==a.availability)throw Error("Codebase is unavailable");if(!g(a.agent))throw Error("Agent is offline");if(!y(a.agent).includes(t))throw Error("Agent must be updated to create or change worktrees");let[n,s]=await Promise.all([r.agentJob.findFirst({where:{codebaseId:e,status:{in:d}}}),r.worktreeMove.findFirst({where:{status:{in:p},OR:[{sourceCodebaseId:e},{targetCodebaseId:e}]}})]);if(n||s)throw Error("Another operation is active for this codebase");return a}async purge(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.deleteMany({where:{id:e,missingAt:{not:null}}});return r.count&&this.publish(e,null),r.count>0}async purgeAll(){let e=await (0,i.getPrismaClient)(),t=await e.worktree.deleteMany({where:{missingAt:{not:null}}});return t.count&&this.publish(null,null),t.count}subscribe(){return n.agentEventBus.iterate(n.WORKTREE_CHANGED_TOPIC)}async *subscribeInspection(e){let t=n.agentEventBus.iterate((0,n.worktreeInspectionTopic)(e)),r=!1;try{for await(let i of(await this.acquireWatch(e),r=!0,t))yield i}finally{await t.return?.(),r&&await this.releaseWatch(e)}}async acquireWatch(e){let r=this.watchDemand.get(e);if(r){r.subscribers+=1,await r.started;return}let i=await this.requireRunnable(e,o.WORKTREE_WATCH_JOB_KIND,!0),a=(0,t.randomUUID)(),n=this.payload(i),s={subscribers:1,watchId:a,agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:n,started:Promise.resolve()};s.started=this.runWatchAction(s,"START"),this.watchDemand.set(e,s);try{await s.started}catch(t){throw this.watchDemand.get(e)===s&&this.watchDemand.delete(e),t}}async releaseWatch(e){let t=this.watchDemand.get(e);if(t&&(t.subscribers-=1,!(t.subscribers>0))){this.watchDemand.delete(e);try{await t.started,await this.runWatchAction(t,"STOP")}catch(e){console.error("Could not stop worktree watcher:",e instanceof Error?e.message:e)}}}async runWatchAction(e,t){let r=await this.agentControl.createJob({agentId:e.agentId,worktreeId:e.worktreeId,kind:o.WORKTREE_WATCH_JOB_KIND,payload:{...e.payload,action:t,watchId:e.watchId},idempotencyKey:`worktree:watch:${t}:${e.watchId}`,timeoutSeconds:30,visibility:"SYSTEM"});try{x(await this.waitForJob(r.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async restartWatch(e){let r=this.watchDemand.get(e);if(r)try{if(await r.started,this.watchDemand.get(e)!==r||(await this.runWatchAction(r,"STOP"),this.watchDemand.get(e)!==r))return;let i=await this.requireRunnable(e,o.WORKTREE_WATCH_JOB_KIND,!0),a={subscribers:r.subscribers,watchId:(0,t.randomUUID)(),agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:this.payload(i),started:Promise.resolve()};a.started=this.runWatchAction(a,"START"),this.watchDemand.set(e,a),await a.started}catch(e){console.error("Could not restart worktree watcher:",e instanceof Error?e.message:e)}}publish(e,t){n.agentEventBus.publish(n.WORKTREE_CHANGED_TOPIC,{worktreeOverviewChanged:{worktreeId:e,codebaseId:t}})}moveIdFromJob(e){let t=JSON.parse(e.payloadJson);if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.moveId)throw Error("Move job is missing its workflow identifier");return String(t.moveId)}async failMove(e,t,r){let a=await (0,i.getPrismaClient)();(await a.worktreeMove.updateMany({where:{id:e,status:t},data:{status:"FAILED",error:r,finishedAt:new Date}})).count&&this.publish(null,null)}async createMoveCheckoutJob(e,t){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e.targetCodebaseId},include:{agent:!0,repository:!0}});if(!a)throw Error("Destination codebase no longer exists");if(!g(a.agent))throw Error("Destination agent is offline");if(!y(a.agent).includes(o.WORKTREE_MOVE_CHECKOUT_JOB_KIND))throw Error("Destination agent must be updated to move worktrees");let n=e.targetWorktreeId?await r.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:a.id,missingAt:null,availability:"AVAILABLE"}}):null;if("EXISTING"===e.destinationMode&&!n)throw Error("Destination worktree is no longer available");return this.agentControl.createJob({agentId:a.agentId,codebaseId:a.id,worktreeId:n?.id??null,kind:o.WORKTREE_MOVE_CHECKOUT_JOB_KIND,payload:{moveId:e.id,codebaseId:a.id,rootFolder:a.folder,folder:n?.folder??null,gitDirectory:n?.gitDirectory??null,expectedOrigin:a.repository.canonicalOrigin,branch:e.branch,expectedHeadSha:e.headSha,baseBranch:e.baseBranch,mode:e.destinationMode,stashOnFailure:t},idempotencyKey:`worktree:move:checkout:${e.id}:${t?"stash":"initial"}`,timeoutSeconds:600})}async advanceMoveAfterPush(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||"PUSHING"!==a.status||a.sourceJobId&&a.sourceJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,"PUSHING",e.error||"Could not push the source branch");let n=x(e);if(n.headSha!==a.headSha||n.branch!==a.branch)return void await this.failMove(a.id,"PUSHING","The source push returned an unexpected branch");try{let e=await this.createMoveCheckoutJob(a,!1);await r.worktreeMove.updateMany({where:{id:a.id,status:"PUSHING"},data:{status:"CHECKING_OUT",targetJobId:e.id}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId)}catch(e){await this.failMove(a.id,"PUSHING",e instanceof Error?e.message:String(e))}}async projectMoveDestination(e,r){let a=(0,o.parseWorktreeInventoryItem)(r),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.targetCodebaseId},select:{localBranchesJson:!0}});if(!s)throw Error("Destination codebase no longer exists");let l=new Set(v(s.localBranchesJson));a.branch&&l.add(a.branch);let c=e.targetWorktreeId;return await n.$transaction(async r=>{if(await r.codebase.update({where:{id:e.targetCodebaseId},data:{localBranchesJson:JSON.stringify([...l].sort((e,t)=>e.localeCompare(t)))}}),c){if(1!==(await r.worktree.updateMany({where:{id:c,codebaseId:e.targetCodebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:e.baseBranch,missingAt:null}})).count)throw Error("Destination worktree no longer exists")}else c=(await r.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:e.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:e.baseBranch,missingAt:null}})).id;await r.worktreeMove.update({where:{id:e.id},data:{targetWorktreeId:c}})}),this.publish(c??null,e.targetCodebaseId),await this.skillsService?.requestAutoReconcile(),c}async scheduleMoveCleanup(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}}),a=await t.worktree.findUnique({where:{id:r.sourceWorktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||a.primary){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:"Destination is ready, but the source worktree could not be removed",finishedAt:new Date}}),this.publish(r.sourceWorktreeId,r.sourceCodebaseId);return}try{let e=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DELETE_JOB_KIND,payload:{moveId:r.id,codebaseId:a.codebaseId,rootFolder:a.codebase.folder,folder:a.folder,gitDirectory:a.gitDirectory,expectedOrigin:a.codebase.repository.canonicalOrigin,branch:a.branch,defaultBranch:a.codebase.defaultBranch,deleteRemoteBranch:!1,requireClean:!0,expectedHeadSha:r.headSha},idempotencyKey:`worktree:move:cleanup:${r.id}`,timeoutSeconds:600});await t.worktreeMove.updateMany({where:{id:r.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"CLEANING_UP",cleanupJobId:e.id}}),this.publish(a.id,a.codebaseId)}catch(e){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e instanceof Error?e.message:String(e),finishedAt:new Date}}),this.publish(a.id,a.codebaseId)}}async advanceMoveAfterCheckout(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||!["PUSHING","CHECKING_OUT","AWAITING_STASH"].includes(a.status)||a.targetJobId&&a.targetJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,a.status,e.error||"Could not check out the destination branch");let n=x(e);if("NEEDS_STASH"===n.outcome){await r.worktreeMove.updateMany({where:{id:a.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"AWAITING_STASH",error:"string"==typeof n.message?n.message:"Destination changes block the branch switch"}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId);return}"CHECKED_OUT"===n.outcome&&n.worktree?(await this.projectMoveDestination(a,n.worktree),a.deleteSource?await this.scheduleMoveCleanup(a.id):(await r.worktreeMove.update({where:{id:a.id},data:{status:"SUCCEEDED",error:null,finishedAt:new Date}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId))):await this.failMove(a.id,a.status,"Destination checkout returned an invalid result")}async projectDeleteOperation(e){let t=JSON.parse(e.payloadJson),r=t&&"object"==typeof t&&!Array.isArray(t)&&"string"==typeof t.moveId?String(t.moveId):null,a=await (0,i.getPrismaClient)();if(r){let t=await a.worktreeMove.findUnique({where:{id:r}});if(!t||!["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"].includes(t.status)||t.cleanupJobId&&t.cleanupJobId!==e.id)return;if("SUCCEEDED"!==e.status){await a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e.error||"Destination is ready, but the source worktree was retained",finishedAt:new Date}}),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}await a.$transaction([a.worktree.deleteMany({where:{id:t.sourceWorktreeId}}),a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED",finishedAt:new Date}})]),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}if("SUCCEEDED"!==e.status||!e.worktreeId)return;let n=await a.worktree.findUnique({where:{id:e.worktreeId},select:{codebaseId:!0}});await a.worktree.deleteMany({where:{id:e.worktreeId}}),this.publish(e.worktreeId,n?.codebaseId??null)}async projectOperation(e){if(!e.worktreeId||"SUCCEEDED"!==e.status||!e.resultJson)return;let t=x({...e,error:null});if(!t.worktree)return;let r=(0,o.parseWorktreeInventoryItem)(t.worktree),a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e.worktreeId}});if(!n)return;let s=new Date(r.checkedAt);(await a.worktree.updateMany({where:{id:n.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:s}}]},data:{branch:r.branch,headSha:r.headSha,upstream:r.upstream,ahead:r.ahead,behind:r.behind,syncState:r.syncState,baseAhead:r.baseAhead,baseBehind:r.baseBehind,hasStagedChanges:r.hasStagedChanges??!1,hasUnstagedChanges:r.hasUnstagedChanges??!1,pushStatus:r.pushStatus??"UNKNOWN",availability:r.availability,statusError:r.error,lastCheckedAt:s}})).count>0&&this.publish(n.id,n.codebaseId)}async projectBranchOperation(e){if(!e.codebaseId||"SUCCEEDED"!==e.status||!e.resultJson)return;let r=x({...e,error:null});if(!r.worktree||"string"!=typeof r.baseBranch)return;let a=(0,o.parseWorktreeInventoryItem)(r.worktree),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.codebaseId},select:{localBranchesJson:!0}});if(!s)return;let l=new Set(v(s.localBranchesJson));a.branch&&l.add(a.branch);let c=e.worktreeId;await n.$transaction(async i=>{if(await i.codebase.update({where:{id:e.codebaseId},data:{localBranchesJson:JSON.stringify([...l].sort((e,t)=>e.localeCompare(t)))}}),e.worktreeId){if(1!==(await i.worktree.updateMany({where:{id:e.worktreeId,codebaseId:e.codebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:r.baseBranch,missingAt:null}})).count)throw Error("Worktree no longer exists");return}c=(await i.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.codebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.codebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:r.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:r.baseBranch,missingAt:null}})).id}),this.publish(c??null,e.codebaseId),await this.skillsService?.requestAutoReconcile(),e.worktreeId&&await this.restartWatch(e.worktreeId)}async waitForJob(e){let t=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e)),r=Date.now()+3e4;try{for(;Date.now()<r;){let i=await this.agentControl.getJob(e);if(!i)throw Error("Worktree job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(i.status))return i;await Promise.race([t.next(),new Promise(e=>setTimeout(e,r-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}},"worktreeDisplayPath",0,w],504173);let k=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),_={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function $(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=a.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function I(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function S(e){return null===e?null:JSON.parse(e)}function E(e){return(0,r.buildDataTargetsPayload)(S(e.payloadJson)).targets.map(e=>e.path)}function T(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function C(e,t,r){try{for(let i of E(t)){let a=e.get(R(t.agentId,i));a&&(a.error=r)}}catch{}}function R(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_DELETE_JOB_KIND),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:$(e)?I(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,r,a){let n=[...new Set(t)];if(!n.length)throw Error("Select at least one Derived Data entry");let s=new Map(e.entries.map(e=>[e.id,e])),o=n.map(e=>{let t=s.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t}),l=new Map;for(let e of o){let t=l.get(e.agent.id)??[];t.push(e),l.set(e.agent.id,t)}let c=await (0,i.getPrismaClient)(),u=[];for(let[e,t]of l){let r=t[0].agent,i=await c.agent.findUnique({where:{id:e}});if(!i||!$(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!I(i).includes(a))throw Error(`${r.name} must be updated before this operation can run`);u.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of u)await this.agentControlService.createJob({agentId:t,kind:a,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${a}:${e.id}:${r}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"})}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:_})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(S(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>k.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),s=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let e of s){let t=o.get(e.codebase.agentId)??[];t.push(e),o.set(e.codebase.agentId,t)}let l=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(S(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(o.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=R(t.agentId,r.path);l.set(a,{id:a,name:r.name,status:"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?w(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(S(i.resultJson)).sizes){let t=l.get(R(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){C(l,i,T(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(S(i.resultJson)).deleted){let r=R(i.agentId,e.path),a=l.get(r);a&&(e.deleted&&!t?l.delete(r):a.error=e.error)}}catch(e){C(l,i,T(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of E(i)){let t=l.get(R(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&k.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of E(i)){let t=l.get(R(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}return[...l.values()].sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||e.name.localeCompare(t.name))}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.buildDataCollectionId||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(S(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=T(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=await this.loadCollection(e.buildDataCollectionId);if(!s)return;let o=new Map((await this.entries(s,!0)).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e]));try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=o.get(i.path);if(!a)continue;let n=a.worktreeId?(await r.worktree.findUnique({where:{id:a.worktreeId},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:a.agent.id,agentName:a.agent.name,folderName:a.name,worktreeId:n,worktreePath:a.worktreePath,source:"USER",jobId:e.id,targetKey:a.id}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}],925991),e.s([],396763)},224174,669602,190714,e=>{"use strict";var t=e.i(666680),r=e.i(750227),i=e.i(807055),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983),o=e.i(971619);let l=new Set(["smartphone","hammer","play","test-tube","archive","rocket"]),c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),u=["QUEUED","PREPARING","RUNNING"];function d(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function p(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function m(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function h(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=n.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function f(e){return m(d(e.capabilitiesJson,[]))}function g(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function y(e){return`${e.type}:${e.id}`}function v(e){if(e.codebaseId)return e.codebaseId;let t=d(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function b(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let w={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:u}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"}},exports:{orderBy:{createdAt:"desc"}}};e.s(["BuildsService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(i.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e))}publish(e){s.agentEventBus.publish((0,s.buildTopic)(e),{buildChanged:{id:e}}),s.agentEventBus.publish(s.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}})}async requireWorktree(e,t){let r=await (0,a.getPrismaClient)(),i=await r.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt||"AVAILABLE"!==i.availability)throw Error("Worktree is unavailable");if(!h(i.codebase.agent))throw Error("Agent is offline");if(!f(i.codebase.agent).includes(t))throw Error("Agent must be updated to use iOS builds");return i}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let r=await (0,a.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!i)throw Error("Codebase not found");return r.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:i.repositoryId,type:"IOS_APP"}},create:{id:(0,t.randomUUID)(),repositoryId:i.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,a.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),n=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:n}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let r=await this.ensureProject(e.codebaseId),n=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),s=g(e.name,"Configuration name"),o=g(e.scheme,"Scheme",256),c=g(e.buildConfiguration,"Xcode configuration",256);if(!i.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let u=e.iconKey?.trim()||null;if(u&&!l.has(u))throw Error("Icon is invalid");let d=(0,i.parseBuildAdvancedSettings)(e.advancedSettings??i.DEFAULT_BUILD_ADVANCED_SETTINGS),p=await (0,a.getPrismaClient)(),m=e.id?await p.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!m||m.projectId!==r.id))throw Error("Build configuration not found");let h=await p.buildSource.upsert({where:{projectId_relativePath:{projectId:r.id,relativePath:n.relativePath}},create:{id:(0,t.randomUUID)(),projectId:r.id,kind:n.kind,relativePath:n.relativePath},update:{kind:n.kind}}),f=m?.id??(0,t.randomUUID)();return p.buildConfiguration.upsert({where:{id:f},create:{id:f,projectId:r.id,sourceId:h.id,name:s,iconKey:u,scheme:o,buildConfiguration:c,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d)},update:{sourceId:h.id,name:s,iconKey:u,scheme:o,buildConfiguration:c,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d)},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,a.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:u}}}))throw Error("Configuration has an active build");return 1===(await t.buildConfiguration.deleteMany({where:{id:e}})).count}async scripts(){return(await (0,a.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let r=g(e.name,"Script name"),n=e.preBuildScript?.trim()||null,s=e.postBuildScript?.trim()||null;if(!n&&!s)throw Error("A pre-build or post-build script is required");let o=e.timeoutSeconds??300;if(!Number.isInteger(o)||o<1||o>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!i.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,a.getPrismaClient)(),c=e.id??(0,t.randomUUID)();return l.buildScript.upsert({where:{id:c},create:{id:c,name:r,preBuildScript:n,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior},update:{name:r,preBuildScript:n,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,a.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,a.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let n=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:n},deletedAt:null}})).length!==n.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),n.length&&await e.codebaseRepositoryBuildScript.createMany({data:n.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=s.agentEventBus.iterate((0,s.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(c.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return p(d(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,i.IOS_SOURCE_DISCOVER_JOB_KIND),n=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:i.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,a.getPrismaClient)();await e.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async reparse(e,r,n){let s=await this.requireWorktree(r,i.IOS_SOURCE_PARSE_JOB_KIND),o=await (0,a.getPrismaClient)(),l=await o.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==s.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let c=`worktree:${s.id}`,u=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}}}),d=new Date;await o.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},create:{id:(0,t.randomUUID)(),sourceId:l.sourceId,scopeKey:c,codebaseId:s.codebaseId,worktreeId:s.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let p=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(s),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${n}:${l.id}:${s.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(p.id)),t=m(e.schemes),r=m(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(m(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:s.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},data:{status:"ERROR",error:e,stale:!!u?.lastParsedAt}})}finally{await o.agentJob.deleteMany({where:{id:p.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_SOURCE_PARSE_JOB_KIND),r=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),n=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return{source:r,schemes:m(e.schemes),configurations:m(e.configurations),testPlans:m(e.testPlans),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,a.getPrismaClient)();await e.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_DESTINATIONS_JOB_KIND),r=await (0,a.getPrismaClient)(),n=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!n||n.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let s=e.action??n.defaultAction;if(!i.BUILD_ACTIONS.includes(s))throw Error("Build action is invalid");let o=function(e){if(!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(e))return[];let t={type:"PHYSICAL_DEVICE",id:"generic-ios",name:"Any Physical iOS Device",platform:"iOS",osVersion:null,state:null,generic:!0};return"ARCHIVE"===e?[t]:[{type:"SIMULATOR",id:"generic-ios-simulator",name:"Any iOS Simulator",platform:"iOS Simulator",osVersion:null,state:null,generic:!0},t]}(s);if("ARCHIVE"===s)return o;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:n.source.kind,relativePath:n.source.relativePath},scheme:n.scheme,configuration:n.buildConfiguration,action:s},idempotencyKey:`ios:destinations:${e.requestId}:${n.id}:${t.id}:${s}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return Array.isArray(e.destinations)?e.destinations:[]}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async destinationsForBuild(e,t){let r=await (0,a.getPrismaClient)(),n=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!n||"SUCCEEDED"!==n.status||!n.worktreeId||!n.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=await this.requireWorktree(n.worktreeId,i.IOS_RUN_DESTINATIONS_JOB_KIND);if(n.agentId!==s.codebase.agentId||n.codebaseId!==s.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(s),destinationType:n.destinationType},idempotencyKey:`ios:build-destinations:${g(t,"Request ID",200)}:${n.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,i.parseBuildDestination)(e)).filter(e=>e.type===n.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async startBuild(e){let n=g(e.requestId,"Request ID",200),s=`${e.worktreeId}:${n}`,l=await (0,a.getPrismaClient)(),c=await l.build.findUnique({where:{requestKey:s},include:w});if(c)return c;let u=await this.requireWorktree(e.worktreeId,i.IOS_BUILD_JOB_KIND);if(e.worktreeCoverage&&!f(u.codebase.agent).includes(i.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let m=await l.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!m||m.source.project.repositoryId!==u.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let h=await l.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:m.sourceId,scopeKey:`worktree:${u.id}`}}}),y=e.action??m.defaultAction;if(!i.BUILD_ACTIONS.includes(y))throw Error("Build action is invalid");let v=(0,i.parseBuildDestination)(e.destination);if(!i.BUILD_DESTINATION_TYPES.includes(v.type))throw Error("Destination is invalid");if("ARCHIVE"===y&&("PHYSICAL_DEVICE"!==v.type||!v.generic))throw Error("Archive builds require the generic physical iOS destination");if(v.generic&&!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(y))throw Error("This build action requires a concrete destination");let b=p(d(m.advancedSettingsJson,{}),"saved advanced settings"),x=e.advancedSettings?p(e.advancedSettings,"advanced settings override"):{},k=(0,i.parseBuildAdvancedSettings)({...b,...x,buildSettingOverrides:{...p(b.buildSettingOverrides??{},"saved overrides"),...p(x.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===y){if(!k.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await l.build.findUnique({where:{id:k.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==u.codebase.agentId||e.worktreeId!==u.id||e.configurationId!==m.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==v.type)throw Error("The prior Build for Testing result uses a different destination type");let t=p(d(e.snapshotJson,{}),"prior Build for Testing snapshot"),a=p(t.configuration??{},"prior Build for Testing configuration snapshot"),n=(0,i.parseBuildAdvancedSettings)(a.advancedSettings??{});if(k.testPlan&&n.testPlan&&k.testPlan!==n.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let s=k.testPlan??n.testPlan??null,o=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),c=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(o.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let h=o[0];if(h||1!==c.length||(h=c[0]),!h&&c.length>1&&s&&(h=c.find(e=>p(d(e.metadataJson,{}),"test-run artifact metadata").testPlan===s||e.relativePath.endsWith(`/${s}.xctestrun`)||e.relativePath===`${s}.xctestrun`)),!h&&c.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let f=h?.relativePath??"test-products.xctestproducts",g=(0,r.resolve)(e.artifactDirectory),y=(0,r.resolve)(g,f),b=(0,r.relative)(g,y);if(!b||b.startsWith("..")||(0,r.isAbsolute)(b))throw Error("The prior Build for Testing artifact path is invalid");k={...k,testPlan:s,priorTestProductsPath:f.endsWith(".xctestproducts")?y:null,priorXctestrunPath:f.endsWith(".xctestrun")?y:null}}let _=await l.codebaseRepositoryBuildScript.findMany({where:{repositoryId:u.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),$=new Set(e.scriptIds??[]);if([...$].some(e=>!_.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let I=_.filter(e=>$.has(e.scriptId)),S=(0,t.randomUUID)(),E=(0,o.effectiveBuildsDirectory)(u.codebase.agent);if(!E)throw Error("The agent builds directory is unavailable");let T=(0,r.join)(E,S),C={kind:m.source.kind,relativePath:m.source.relativePath},R=function(e){var t;let i=e.advancedSettings,a="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...a?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,r.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!a&&("RESOLVED_ONLY"===i.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===i.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===i.packageResolution&&n.push("-disableAutomaticPackageResolution"),i.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==i.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===i.signingStyle?"Automatic":"Manual"}`),i.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${i.developmentTeam}`),i.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${i.codeSignIdentity}`),i.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${i.provisioningProfileSpecifier}`),i.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${i.productBundleIdentifier}`),i.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),i.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),i.testPlan&&n.push("-testPlan",i.testPlan),i.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==i.parallelTesting&&n.push("-parallel-testing-enabled",i.parallelTesting?"YES":"NO"),null!==i.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(i.parallelTestingWorkers)),i.onlyTesting))n.push(`-only-testing:${e}`);for(let e of i.skipTesting)n.push(`-skip-testing:${e}`);if(!a)for(let[e,t]of Object.entries(i.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,r.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,r.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&i.priorTestProductsPath&&n.push("-testProductsPath",i.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!i.priorTestProductsPath&&i.priorXctestrunPath&&n.push("-xctestrun",i.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:u.folder,source:C,scheme:m.scheme,configuration:m.buildConfiguration,destination:v,action:y,advancedSettings:k,artifactDirectory:T}),P=I.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),A={repository:{id:u.codebase.repository.id,name:u.codebase.repository.name,canonicalOrigin:u.codebase.repository.canonicalOrigin},codebase:{id:u.codebase.id,folder:u.codebase.folder},worktree:{id:u.id,folder:u.folder,branch:u.branch,headSha:u.headSha,codeStateHash:u.codeStateHash,hasStagedChanges:u.hasStagedChanges,hasUnstagedChanges:u.hasUnstagedChanges},agent:{id:u.codebase.agent.id,name:u.codebase.agent.name,hostname:u.codebase.agent.hostname},configuration:{id:m.id,name:m.name,iconKey:m.iconKey,source:C,scheme:m.scheme,buildConfiguration:m.buildConfiguration,action:y,advancedSettings:k,parse:h?{status:h.status,schemes:d(h.schemesJson,[]),configurations:d(h.configurationsJson,[]),testPlans:d(h.testPlansJson,[]),headSha:h.headSha,xcodeVersion:h.xcodeVersion,parsedAt:h.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:v,scripts:P,worktreeCoverage:!0===e.worktreeCoverage};await l.build.create({data:{id:S,requestKey:s,requestId:n,agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,configurationId:m.id,status:"QUEUED",action:y,destinationType:v.type,destinationJson:JSON.stringify(v),snapshotJson:JSON.stringify(A),commandSummary:R,artifactDirectory:T,scriptExecutions:{create:P.flatMap(e=>[...e.preBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});try{let t=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:i.IOS_BUILD_JOB_KIND,payload:{...this.identity(u),buildId:S,artifactDirectory:T,source:C,scheme:m.scheme,configuration:m.buildConfiguration,action:y,destination:v,advancedSettings:k,scripts:P,worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${n}:${u.id}`,timeoutSeconds:604800});await l.build.update({where:{id:S},data:{jobId:t.id}})}catch(e){throw await l.build.update({where:{id:S},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(S),l.build.findUniqueOrThrow({where:{id:S},include:w})}async rebuildBuild(e,t){let r=await (0,a.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!i)throw Error("Build not found");let n=p(d(i.snapshotJson,{}),"build snapshot"),s=p(n.worktree??{},"build worktree snapshot"),o=p(n.configuration??{},"build configuration snapshot"),l=Array.isArray(n.scripts)?n.scripts:[],c=i.worktreeId??("string"==typeof s.id?s.id:null),u=i.configurationId??("string"==typeof o.id?o.id:null);if(!c||!u)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:u,destination:d(i.destinationJson,{}),scriptIds:l.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:i.action,advancedSettings:o.advancedSettings,requestId:t})}async startWorktreeCoverage(e){let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=p(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async generateReport(e,r,n){let s=await (0,a.getPrismaClient)(),o=await s.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:r}},include:{artifact:!0}});if(o?.status==="READY")return o;let l=await s.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(u.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!h(l.agent))throw Error("Build agent is offline");let c="TEST_RESULTS"===r?i.IOS_TEST_RESULTS_JOB_KIND:i.IOS_COVERAGE_REPORT_JOB_KIND;if(!f(l.agent).includes(c))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===r&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let d=await s.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:r}},create:{id:(0,t.randomUUID)(),buildId:e,kind:r,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let p=v(l),m=await this.agentControl.createJob({agentId:l.agentId,codebaseId:p,worktreeId:l.worktreeId,kind:c,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:p,reportKind:r,source:"MANUAL"},idempotencyKey:`ios:report:${r}:${g(n,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(m.id,17e4),s.buildReport.findUniqueOrThrow({where:{id:d.id},include:{artifact:!0}})}finally{await s.agentJob.deleteMany({where:{id:m.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,a.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:u}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,a.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,a.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,a.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:w});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,a.getPrismaClient)()).build.findUnique({where:{id:e},include:w})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let n=await (0,a.getPrismaClient)(),s=await n.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:u}},select:{id:!0}},exports:{where:{status:{in:u}},select:{id:!0}}}});if(s.some(e=>u.includes(e.status)))throw Error("Running builds cannot be deleted");if(s.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of s){if(!(0,r.isAbsolute)(e.artifactDirectory)||(0,r.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=v(e);if(!e.agent||!f(e.agent).includes(i.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:i.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let o=await n.build.deleteMany({where:{id:{in:s.map(e=>e.id)}}});for(let e of s)this.publish(e.id);return o.count}async prepareArtifactDownload(e,t,r){let n=await (0,a.getPrismaClient)(),s=await n.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!s)throw Error("Build artifact not found");let{build:o}=s;if(!o.agentId||!o.agent)throw Error("The build agent is no longer available");if(!h(o.agent))throw Error("Build agent is offline");if(!f(o.agent).includes(i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let l=v(o),c=await this.agentControl.createJob({agentId:o.agentId,codebaseId:l,worktreeId:o.worktreeId,kind:i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:o.id,artifactDirectory:o.artifactDirectory,artifactRelativePath:s.relativePath,uploadId:r,codebaseId:l},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:180,visibility:"SYSTEM"});try{this.result(await this.waitForJob(c.id,17e4))}finally{await n.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async logs(e,t=null,r=1e3){let i=await (0,a.getPrismaClient)(),n=t?await i.buildLogEvent.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0}}):null;if(t&&!n)throw Error("Build log cursor not found");return i.buildLogEvent.findMany({where:{buildId:e,...n?{OR:[{createdAt:{gt:n.createdAt}},{createdAt:n.createdAt,id:{gt:n.id}}]}:{}},orderBy:[{createdAt:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,a.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return u.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,a.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!u.includes(i.status))return i;let n=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),n}async appendLogs(e,r,i){let n=await (0,a.getPrismaClient)(),o=await n.build.findUnique({where:{id:r}});if(!o||o.agentId!==e)throw Error("Build not found for agent");let l=i.slice(0,200).map(e=>({id:(0,t.randomUUID)(),buildId:r,scope:g(e.scope,"Log scope",40),scopeId:g(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:g(e.phase,"Log phase",80),level:g(e.level,"Log level",20),stream:g(e.stream,"Log stream",20),message:e.message.replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]").slice(0,64e3),createdAt:new Date(e.createdAt)}));for(let e of l){if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(Number.isNaN(e.createdAt.valueOf()))throw Error("Log date is invalid");await n.buildLogEvent.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}}),s.agentEventBus.publish((0,s.buildLogTopic)(r),{buildLogAdded:e})}return l}async runBuild(e){let r=await (0,a.getPrismaClient)(),n=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!n||"SUCCEEDED"!==n.status||!n.worktree)throw Error("A successful build is required");let s=n.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!s)throw Error("Build does not contain a runnable app");let o=g(String(p(d(s.metadataJson,{}),"runnable metadata").bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(i.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==n.destinationType))throw Error("Run destinations must match the build destination type");let c=await this.destinationsForBuild(n.id,`${g(e.requestId,"Request ID",200)}:preflight`),u=l.map(e=>c.find(t=>t.type===e.type&&t.id===e.id));if(u.some(e=>!e))throw Error("A selected run destination is no longer available");l=u;let m=await this.requireWorktree(n.worktree.id,i.IOS_DEPLOY_JOB_KIND),h=(0,t.randomUUID)(),f=[];for(let i of l){let a=await r.buildDeployment.findUnique({where:{buildId_requestId_destinationKey:{buildId:n.id,requestId:e.requestId,destinationKey:y(i)}}});f.push(a??await r.buildDeployment.create({data:{id:(0,t.randomUUID)(),buildId:n.id,batchId:h,requestId:e.requestId,destinationJson:JSON.stringify(i),destinationKey:y(i),commandSummary:"SIMULATOR"===i.type?`open -a Simulator --args -CurrentDeviceUDID ${i.id}; xcrun simctl install/launch ${i.id}`:`xcrun devicectl device install/process launch --device ${i.id}`}}))}let v=await this.agentControl.createJob({agentId:m.codebase.agentId,codebaseId:m.codebaseId,worktreeId:m.id,kind:i.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(m),buildId:n.id,artifactDirectory:n.artifactDirectory,artifactRelativePath:s.relativePath,bundleIdentifier:o,deployments:f.map((e,t)=>({id:e.id,destination:l[t]}))},idempotencyKey:`ios:deploy:${n.id}:${e.requestId}`,timeoutSeconds:3600});return await r.buildDeployment.updateMany({where:{id:{in:f.map(e=>e.id)}},data:{jobId:v.id}}),this.publish(n.id),r.buildDeployment.findMany({where:{id:{in:f.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let r=await (0,a.getPrismaClient)(),n=await r.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(n)return n;let s=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!s||"SUCCEEDED"!==s.status||!s.worktree)throw Error("A successful archive build is required");let o=s.artifacts.find(e=>"ARCHIVE"===e.kind);if(!o)throw Error("Build does not contain an archive");let l=(0,i.parseBuildExportSettings)(e.settings),c=await this.requireWorktree(s.worktree.id,i.IOS_EXPORT_JOB_KIND),u=(0,t.randomUUID)(),d=await r.buildExport.create({data:{id:u,buildId:s.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(o.relativePath)} -exportPath exports/${u}`}}),p=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:i.IOS_EXPORT_JOB_KIND,payload:{...this.identity(c),buildId:s.id,exportId:u,artifactDirectory:s.artifactDirectory,archiveRelativePath:o.relativePath,settings:l},idempotencyKey:`ios:export:${s.id}:${e.requestId}`,timeoutSeconds:3600}),m=await r.buildExport.update({where:{id:d.id},data:{jobId:p.id}});return this.publish(s.id),m}async upsertReportProjection(e,r,i,a){let n=p(i,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?p(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:r,relativePath:o.relativePath}}}):null,c="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:s}},create:{id:(0,t.randomUUID)(),buildId:r,artifactId:l?.id??null,kind:s,source:a,status:c,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:c,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let r=await (0,a.getPrismaClient)(),i=await r.build.findFirst({where:{jobId:e.id}});if(!i)return;let n=p(d(e.resultJson,{}),"build result"),s="CANCELLED"===i.status?"CANCELLED":b(e.status),o="string"==typeof n.sourceStateHash?n.sourceStateHash:null,l="string"==typeof n.finalStateHash?n.finalStateHash:null,c="string"==typeof n.codeStateObservedAt&&Number.isFinite(Date.parse(n.codeStateObservedAt))?new Date(n.codeStateObservedAt):new Date,u=l?c:new Date,m=i.snapshotJson;if(o){let e=p(d(i.snapshotJson,{}),"build snapshot"),t=p(e.worktree??{},"build worktree snapshot");m=JSON.stringify({...e,worktree:{...t,codeStateHash:o}})}await r.$transaction(async r=>{if(await r.build.update({where:{id:i.id},data:{status:s,errorCode:"string"==typeof n.errorCode?n.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===s?"XCODEBUILD_FAILED":i.errorCode,error:e.error??("string"==typeof n.error?n.error:i.error),startedAt:i.startedAt??new Date,finishedAt:u,snapshotJson:m}}),i.worktreeId&&l&&await r.worktree.updateMany({where:{id:i.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:c}}]},data:{codeStateHash:l,lastCheckedAt:c}}),Array.isArray(n.artifacts))for(let e of n.artifacts){let a=p(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),buildId:i.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(n.scriptExecutions))for(let e of n.scriptExecutions){let t=p(e,"script execution");"string"==typeof t.phase&&"number"==typeof t.position&&await r.buildScriptExecution.updateMany({where:{buildId:i.id,phase:t.phase,position:t.position},data:{status:"string"==typeof t.status?t.status:"FAILED",exitCode:"number"==typeof t.exitCode?t.exitCode:null,durationMs:"number"==typeof t.durationMs?t.durationMs:null,causedBuildFailure:!0===t.causedBuildFailure,outputRelativePath:"string"==typeof t.outputRelativePath?t.outputRelativePath:null,error:"string"==typeof t.error?t.error:null}})}if(Array.isArray(n.reports))for(let e of n.reports){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(r,i.id,e,"CODE_COVERAGE"===t.kind?"WORKTREE":"AUTOMATIC")}}),this.publish(i.id)}async projectGeneratedReportCompletion(e){let r=p(d(e.payloadJson,{}),"build report payload");if("string"!=typeof r.buildId)return;let i=r.buildId,n=p(d(e.resultJson,{}),"build report result"),s=await (0,a.getPrismaClient)();await s.$transaction(async a=>{if(Array.isArray(n.artifacts))for(let e of n.artifacts){let r=p(e,"build report artifact");"string"==typeof r.relativePath&&"string"==typeof r.kind&&await a.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i,relativePath:r.relativePath}},create:{id:(0,t.randomUUID)(),buildId:i,kind:r.kind,relativePath:r.relativePath,sizeBytes:"number"==typeof r.sizeBytes?r.sizeBytes:null,checksum:"string"==typeof r.checksum?r.checksum:null,metadataJson:JSON.stringify(r.metadata&&"object"==typeof r.metadata?r.metadata:{})},update:{}})}if(n.report&&"object"==typeof n.report)await this.upsertReportProjection(a,i,n.report,"WORKTREE"===r.source?"WORKTREE":"MANUAL");else{let n="CODE_COVERAGE"===r.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await a.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:n}},create:{id:(0,t.randomUUID)(),buildId:i,kind:n,source:"WORKTREE"===r.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(i)}async projectDeploymentCompletion(e){let t=await (0,a.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=p(d(e.resultJson,{}),"deployment result"),n=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=n.map(e=>p(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:b(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let r=await (0,a.getPrismaClient)(),i=await r.buildExport.findFirst({where:{jobId:e.id}});if(!i)return;let n=p(d(e.resultJson,{}),"export result");await r.buildExport.update({where:{id:i.id},data:{status:b(e.status),error:e.error??("string"==typeof n.error?n.error:null),outputRelativePath:"string"==typeof n.outputRelativePath?n.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof n.outputRelativePath&&await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.buildId,relativePath:n.outputRelativePath}},create:{id:(0,t.randomUUID)(),buildId:i.buildId,kind:"EXPORT",relativePath:n.outputRelativePath,sizeBytes:"number"==typeof n.sizeBytes?n.sizeBytes:null,metadataJson:JSON.stringify({exportId:i.id})},update:{}}),this.publish(i.buildId)}}],669602);var x=e.i(907855);let k=x.object({status:x.string().optional(),codebaseId:x.string().optional(),worktreeId:x.string().optional(),first:x.number().int().min(1).max(200).default(50),after:x.string().optional()}),_=x.object({builds:x.array(x.unknown()),nextCursor:x.string().nullable()}),$=x.object({buildId:x.string().min(1),afterLogId:x.string().min(1).nullable().default(null),logLimit:x.number().int().min(1).max(5e3).default(1e3)}),I=x.object({build:x.unknown(),logs:x.array(x.unknown())}),S=x.object({worktreeId:x.string().min(1)}),E=x.object({project:x.unknown().nullable()}),T=x.union([x.object({buildId:x.string().min(1),requestId:x.string().min(1)}),x.object({worktreeId:x.string().min(1),configurationId:x.string().min(1),action:x.string().optional(),requestId:x.string().min(1)})]),C=x.object({destinations:x.array(x.unknown())}),R=x.object({worktreeId:x.string().min(1),configurationId:x.string().min(1),destination:x.record(x.string(),x.unknown()),scriptIds:x.array(x.string()).default([]),action:x.string().optional(),advancedSettings:x.record(x.string(),x.unknown()).optional(),requestId:x.string().min(1)}),P=x.object({build:x.unknown()}),A=x.object({buildId:x.string().min(1),requestId:x.string().min(1)}),D=x.object({build:x.unknown()}),O=x.object({buildId:x.string().min(1),destinations:x.array(x.record(x.string(),x.unknown())).min(1),requestId:x.string().min(1)}),j=x.object({deployments:x.array(x.unknown())}),N=x.object({buildId:x.string().min(1),settings:x.record(x.string(),x.unknown()),requestId:x.string().min(1)}),q=x.object({export:x.unknown()});e.s(["CancelBuildToolInputSchema",0,A,"CancelBuildToolOutputSchema",0,D,"ExportBuildToolInputSchema",0,N,"ExportBuildToolOutputSchema",0,q,"GetBuildConfigurationsInputSchema",0,S,"GetBuildConfigurationsOutputSchema",0,E,"GetBuildDestinationsInputSchema",0,T,"GetBuildDestinationsOutputSchema",0,C,"GetBuildInputSchema",0,$,"GetBuildOutputSchema",0,I,"GetBuildsInputSchema",0,k,"GetBuildsOutputSchema",0,_,"RunBuildToolInputSchema",0,O,"RunBuildToolOutputSchema",0,j,"StartBuildToolInputSchema",0,R,"StartBuildToolOutputSchema",0,P],190714),e.s([],224174)},952128,187963,117958,514849,e=>{"use strict";let t;var r,i,a,n,s,o,l,c=e.i(243783);e.s(["PrismaService",0,class{async healthCheck(){try{let e=await (0,c.getPrismaClient)();return await e.$queryRawUnsafe("SELECT 1"),!0}catch(e){return console.error("Database health check failed:",e),!1}}}],187963),e.s([],952128),(r=n||(n={})).assertEqual=e=>{},r.assertIs=function(e){},r.assertNever=function(e){throw Error()},r.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},r.getValidEnumValues=e=>{let t=r.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),i={};for(let r of t)i[r]=e[r];return r.objectValues(i)},r.objectValues=e=>r.objectKeys(e).map(function(t){return e[t]}),r.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},r.find=(e,t)=>{for(let r of e)if(t(r))return r},r.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,r.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},r.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(s||(s={})).mergeShapes=(e,t)=>({...e,...t});let u=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return u.undefined;case"string":return u.string;case"number":return Number.isNaN(e)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":if(Array.isArray(e))return u.array;if(null===e)return u.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return u.promise;if("u">typeof Map&&e instanceof Map)return u.map;if("u">typeof Set&&e instanceof Set)return u.set;if("u">typeof Date&&e instanceof Date)return u.date;return u.object;default:return u.unknown}},p=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class m extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},i=e=>{for(let a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(i);else if("invalid_return_type"===a.code)i(a.returnTypeError);else if("invalid_arguments"===a.code)i(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,i=0;for(;i<a.path.length;){let r=a.path[i];i===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(this),r}static assert(e){if(!(e instanceof m))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];t[r]=t[r]||[],t[r].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}m.create=e=>new m(e);let h=(e,t)=>{let r;switch(e.code){case p.invalid_type:r=e.received===u.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case p.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case p.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};(i=o||(o={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},i.toString=e=>"string"==typeof e?e:e?.message;let f=e=>{let{data:t,path:r,errorMaps:i,issueData:a}=e,n=[...r,...a.path||[]],s={...a,path:n};if(void 0!==a.message)return{...a,path:n,message:a.message};let o="";for(let e of i.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...a,path:n,message:o}};function g(e,t){let r=f({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,h,void 0].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if("aborted"===i.status)return v;"dirty"===i.status&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,i=await e.value;r.push({key:t,value:i})}return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:t,value:a}=i;if("aborted"===t.status||"aborted"===a.status)return v;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==a.value||i.alwaysSet)&&(r[t.value]=a.value)}return{status:e.value,value:r}}}let v=Object.freeze({status:"aborted"}),b=e=>({status:"dirty",value:e}),w=e=>({status:"valid",value:e}),x=e=>"u">typeof Promise&&e instanceof Promise;class k{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let _=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new m(e.common.issues);return this._error=t,this._error}}};function $(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:a}=e;if(t&&(r||i))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:a}:{errorMap:(t,a)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??a.defaultError}:void 0===a.data?{message:n??i??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:n??r??a.defaultError}},description:a}}class I{get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(x(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parseSync({data:e,path:r.path,parent:r});return _(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parse({data:e,path:r.path,parent:r});return _(r,await (x(i)?i:Promise.resolve(i)))}refine(e,t){return this._refinement((r,i)=>{let a=e(r),n=()=>i.addIssue({code:p.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&a instanceof Promise?a.then(e=>!!e||(n(),!1)):!!a||(n(),!1)})}refinement(e,t){return this._refinement((r,i)=>!!e(r)||(i.addIssue("function"==typeof t?t(r,i):t),!1))}_refinement(e){return new ev({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ew.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return ey.create(this,this._def)}or(e){return ei.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ev({...$(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ex({...$(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:l.ZodDefault})}brand(){return new e$({typeName:l.ZodBranded,type:this,...$(this._def)})}catch(e){return new ek({...$(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:l.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eI.create(this,e)}readonly(){return eS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let S=/^c[^\s-]{8,}$/i,E=/^[0-9a-z]+$/,T=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,R=/^[a-z0-9_-]{21}$/i,P=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,O=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,j=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,N=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,F="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",M=RegExp(`^${F}$`);function B(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class z extends I{_parse(e){var r,i,a,s;let o;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.string,received:t.parsedType}),v}let l=new y;for(let c of this._def.checks)if("min"===c.kind)e.data.length<c.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),l.dirty());else if("max"===c.kind)e.data.length>c.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),l.dirty());else if("length"===c.kind){let t=e.data.length>c.value,r=e.data.length<c.value;(t||r)&&(o=this._getOrReturnCtx(e,o),t?g(o,{code:p.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}):r&&g(o,{code:p.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}),l.dirty())}else if("email"===c.kind)D.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"email",code:p.invalid_string,message:c.message}),l.dirty());else if("emoji"===c.kind)t||(t=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),t.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"emoji",code:p.invalid_string,message:c.message}),l.dirty());else if("uuid"===c.kind)C.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"uuid",code:p.invalid_string,message:c.message}),l.dirty());else if("nanoid"===c.kind)R.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"nanoid",code:p.invalid_string,message:c.message}),l.dirty());else if("cuid"===c.kind)S.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid",code:p.invalid_string,message:c.message}),l.dirty());else if("cuid2"===c.kind)E.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid2",code:p.invalid_string,message:c.message}),l.dirty());else if("ulid"===c.kind)T.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"ulid",code:p.invalid_string,message:c.message}),l.dirty());else if("url"===c.kind)try{new URL(e.data)}catch{g(o=this._getOrReturnCtx(e,o),{validation:"url",code:p.invalid_string,message:c.message}),l.dirty()}else"regex"===c.kind?(c.regex.lastIndex=0,c.regex.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"regex",code:p.invalid_string,message:c.message}),l.dirty())):"trim"===c.kind?e.data=e.data.trim():"includes"===c.kind?e.data.includes(c.value,c.position)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{includes:c.value,position:c.position},message:c.message}),l.dirty()):"toLowerCase"===c.kind?e.data=e.data.toLowerCase():"toUpperCase"===c.kind?e.data=e.data.toUpperCase():"startsWith"===c.kind?e.data.startsWith(c.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{startsWith:c.value},message:c.message}),l.dirty()):"endsWith"===c.kind?e.data.endsWith(c.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{endsWith:c.value},message:c.message}),l.dirty()):"datetime"===c.kind?(function(e){let t=`${F}T${B(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(c).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"datetime",message:c.message}),l.dirty()):"date"===c.kind?M.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"date",message:c.message}),l.dirty()):"time"===c.kind?RegExp(`^${B(c)}$`).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"time",message:c.message}),l.dirty()):"duration"===c.kind?A.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"duration",code:p.invalid_string,message:c.message}),l.dirty()):"ip"===c.kind?(r=e.data,!(("v4"===(i=c.version)||!i)&&O.test(r)||("v6"===i||!i)&&N.test(r))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"ip",code:p.invalid_string,message:c.message}),l.dirty())):"jwt"===c.kind?!function(e,t){if(!P.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(i));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)return!1;return!0}catch{return!1}}(e.data,c.alg)&&(g(o=this._getOrReturnCtx(e,o),{validation:"jwt",code:p.invalid_string,message:c.message}),l.dirty()):"cidr"===c.kind?(a=e.data,!(("v4"===(s=c.version)||!s)&&j.test(a)||("v6"===s||!s)&&q.test(a))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"cidr",code:p.invalid_string,message:c.message}),l.dirty())):"base64"===c.kind?U.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64",code:p.invalid_string,message:c.message}),l.dirty()):"base64url"===c.kind?L.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64url",code:p.invalid_string,message:c.message}),l.dirty()):n.assertNever(c);return{status:l.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:p.invalid_string,...o.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}z.create=e=>new z({checks:[],typeName:l.ZodString,coerce:e?.coerce??!1,...$(e)});class K extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==u.number){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.number,received:t.parsedType}),v}let r=new y;for(let i of this._def.checks)"int"===i.kind?n.isInteger(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"multipleOf"===i.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,a=r>i?r:i;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(e.data,i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.not_finite,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new K({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}K.create=e=>new K({checks:[],typeName:l.ZodNumber,coerce:e?.coerce||!1,...$(e)});class G extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==u.bigint)return this._getInvalidInput(e);let r=new y;for(let i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}G.create=e=>new G({checks:[],typeName:l.ZodBigInt,coerce:e?.coerce??!1,...$(e)});class H extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.boolean,received:t.parsedType}),v}return w(e.data)}}H.create=e=>new H({typeName:l.ZodBoolean,coerce:e?.coerce||!1,...$(e)});class Z extends I{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.date,received:t.parsedType}),v}if(Number.isNaN(e.data.getTime()))return g(this._getOrReturnCtx(e),{code:p.invalid_date}),v;let r=new y;for(let i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):n.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Z.create=e=>new Z({checks:[],coerce:e?.coerce||!1,typeName:l.ZodDate,...$(e)});class V extends I{_parse(e){if(this._getType(e)!==u.symbol){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.symbol,received:t.parsedType}),v}return w(e.data)}}V.create=e=>new V({typeName:l.ZodSymbol,...$(e)});class J extends I{_parse(e){if(this._getType(e)!==u.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.undefined,received:t.parsedType}),v}return w(e.data)}}J.create=e=>new J({typeName:l.ZodUndefined,...$(e)});class W extends I{_parse(e){if(this._getType(e)!==u.null){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.null,received:t.parsedType}),v}return w(e.data)}}W.create=e=>new W({typeName:l.ZodNull,...$(e)});class Q extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return w(e.data)}}Q.create=e=>new Q({typeName:l.ZodAny,...$(e)});class Y extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return w(e.data)}}Y.create=e=>new Y({typeName:l.ZodUnknown,...$(e)});class X extends I{_parse(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.never,received:t.parsedType}),v}}X.create=e=>new X({typeName:l.ZodNever,...$(e)});class ee extends I{_parse(e){if(this._getType(e)!==u.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.void,received:t.parsedType}),v}return w(e.data)}}ee.create=e=>new ee({typeName:l.ZodVoid,...$(e)});class et extends I{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==u.array)return g(t,{code:p.invalid_type,expected:u.array,received:t.parsedType}),v;if(null!==i.exactLength){let e=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(e||a)&&(g(t,{code:e?p.too_big:p.too_small,minimum:a?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(g(t,{code:p.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(g(t,{code:p.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>i.type._parseAsync(new k(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));let a=[...t.data].map((e,r)=>i.type._parseSync(new k(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new et({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new et({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new et({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...$(t)});class er extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.object,received:t.parsedType}),v}let{status:t,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof X&&"strip"===this._def.unknownKeys))for(let e in r.data)a.includes(e)||n.push(e);let s=[];for(let e of a){let t=i[e],a=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new k(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof X){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(g(r,{code:p.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let i=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new k(r,i,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,i=await t.value;e.push({key:r,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new er({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new er({...this._def,unknownKeys:"strip"})}passthrough(){return new er({...this._def,unknownKeys:"passthrough"})}extend(e){return new er({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new er({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:l.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new er({...this._def,catchall:e})}pick(e){let t={};for(let r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}omit(e){let t={};for(let r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof er){let r={};for(let i in t.shape){let a=t.shape[i];r[i]=eb.create(e(a))}return new er({...t._def,shape:()=>r})}if(t instanceof et)return new et({...t._def,type:e(t.element)});if(t instanceof eb)return eb.create(e(t.unwrap()));if(t instanceof ew)return ew.create(e(t.unwrap()));if(t instanceof eo)return eo.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of n.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new er({...this._def,shape:()=>t})}required(e){let t={};for(let r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new er({...this._def,shape:()=>t})}keyof(){return eh(n.objectKeys(this.shape))}}er.create=(e,t)=>new er({shape:()=>e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...$(t)}),er.strictCreate=(e,t)=>new er({shape:()=>e,unknownKeys:"strict",catchall:X.create(),typeName:l.ZodObject,...$(t)}),er.lazycreate=(e,t)=>new er({shape:e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...$(t)});class ei extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new m(e.ctx.common.issues));return g(t,{code:p.invalid_union,unionErrors:r}),v});{let e,i=[];for(let a of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&i.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let a=i.map(e=>new m(e));return g(t,{code:p.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}}ei.create=(e,t)=>new ei({options:e,typeName:l.ZodUnion,...$(t)});let ea=e=>{if(e instanceof ep)return ea(e.schema);if(e instanceof ev)return ea(e.innerType());if(e instanceof em)return[e.value];if(e instanceof ef)return e.options;if(e instanceof eg)return n.objectValues(e.enum);else if(e instanceof ex)return ea(e._def.innerType);else if(e instanceof J)return[void 0];else if(e instanceof W)return[null];else if(e instanceof eb)return[void 0,...ea(e.unwrap())];else if(e instanceof ew)return[null,...ea(e.unwrap())];else if(e instanceof e$)return ea(e.unwrap());else if(e instanceof eS)return ea(e.unwrap());else if(e instanceof ek)return ea(e._def.innerType);else return[]};class en extends I{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return g(t,{code:p.invalid_type,expected:u.object,received:t.parsedType}),v;let r=this.discriminator,i=t.data[r],a=this.optionsMap.get(i);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let r of t){let t=ea(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of t){if(i.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new en({typeName:l.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...$(r)})}}class es extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(e,i)=>{if("aborted"===e.status||"aborted"===i.status)return v;let a=function e(t,r){let i=d(t),a=d(r);if(t===r)return{valid:!0,data:t};if(i===u.object&&a===u.object){let i=n.objectKeys(r),a=n.objectKeys(t).filter(e=>-1!==i.indexOf(e)),s={...t,...r};for(let i of a){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1};s[i]=a.data}return{valid:!0,data:s}}if(i===u.array&&a===u.array){if(t.length!==r.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i.push(n.data)}return{valid:!0,data:i}}if(i===u.date&&a===u.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,i.value);return a.valid?(("dirty"===e.status||"dirty"===i.status)&&t.dirty(),{status:t.value,value:a.data}):(g(r,{code:p.invalid_intersection_types}),v)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>i(e,t)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:l.ZodIntersection,...$(r)});class eo extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.array)return g(r,{code:p.invalid_type,expected:u.array,received:r.parsedType}),v;if(r.data.length<this._def.items.length)return g(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((e,t)=>{let i=this._def.items[t]||this._def.rest;return i?i._parse(new k(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(i).then(e=>y.mergeArray(t,e)):y.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new eo({...this._def,rest:e})}}eo.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new eo({items:e,typeName:l.ZodTuple,rest:null,...$(t)})};class el extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.object)return g(r,{code:p.invalid_type,expected:u.object,received:r.parsedType}),v;let i=[],a=this._def.keyType,n=this._def.valueType;for(let e in r.data)i.push({key:a._parse(new k(r,e,r.path,e)),value:n._parse(new k(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?y.mergeObjectAsync(t,i):y.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return new el(t instanceof I?{keyType:e,valueType:t,typeName:l.ZodRecord,...$(r)}:{keyType:z.create(),valueType:e,typeName:l.ZodRecord,...$(t)})}}class ec extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.map)return g(r,{code:p.invalid_type,expected:u.map,received:r.parsedType}),v;let i=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:i._parse(new k(r,e,r.path,[n,"key"])),value:a._parse(new k(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let i=await r.key,a=await r.value;if("aborted"===i.status||"aborted"===a.status)return v;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let i=r.key,a=r.value;if("aborted"===i.status||"aborted"===a.status)return v;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}}}}ec.create=(e,t,r)=>new ec({valueType:t,keyType:e,typeName:l.ZodMap,...$(r)});class eu extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.set)return g(r,{code:p.invalid_type,expected:u.set,received:r.parsedType}),v;let i=this._def;null!==i.minSize&&r.data.size<i.minSize.value&&(g(r,{code:p.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&r.data.size>i.maxSize.value&&(g(r,{code:p.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let a=this._def.valueType;function n(e){let r=new Set;for(let i of e){if("aborted"===i.status)return v;"dirty"===i.status&&t.dirty(),r.add(i.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>a._parse(new k(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new eu({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new eu({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}eu.create=(e,t)=>new eu({valueType:e,minSize:null,maxSize:null,typeName:l.ZodSet,...$(t)});class ed extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return g(t,{code:p.invalid_type,expected:u.function,received:t.parsedType}),v;function r(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h,h].filter(e=>!!e),issueData:{code:p.invalid_arguments,argumentsError:r}})}function i(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h,h].filter(e=>!!e),issueData:{code:p.invalid_return_type,returnTypeError:r}})}let a={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof ey){let e=this;return w(async function(...t){let s=new m([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,a).catch(e=>{throw s.addIssue(i(l,e)),s})})}{let e=this;return w(function(...t){let s=e._def.args.safeParse(t,a);if(!s.success)throw new m([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,a);if(!l.success)throw new m([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ed({...this._def,args:eo.create(e).rest(Y.create())})}returns(e){return new ed({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ed({args:e||eo.create([]).rest(Y.create()),returns:t||Y.create(),typeName:l.ZodFunction,...$(r)})}}class ep extends I{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ep.create=(e,t)=>new ep({getter:e,typeName:l.ZodLazy,...$(t)});class em extends I{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}function eh(e,t){return new ef({values:e,typeName:l.ZodEnum,...$(t)})}em.create=(e,t)=>new em({value:e,typeName:l.ZodLiteral,...$(t)});class ef extends I{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{expected:n.joinValues(r),received:t.parsedType,code:p.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{received:t.data,code:p.invalid_enum_value,options:r}),v}return w(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ef.create(e,{...this._def,...t})}exclude(e,t=this._def){return ef.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ef.create=eh;class eg extends I{_parse(e){let t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==u.string&&r.parsedType!==u.number){let e=n.objectValues(t);return g(r,{expected:n.joinValues(e),received:r.parsedType,code:p.invalid_type}),v}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=n.objectValues(t);return g(r,{received:r.data,code:p.invalid_enum_value,options:e}),v}return w(e.data)}get enum(){return this._def.values}}eg.create=(e,t)=>new eg({values:e,typeName:l.ZodNativeEnum,...$(t)});class ey extends I{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==u.promise&&!1===t.common.async?(g(t,{code:p.invalid_type,expected:u.promise,received:t.parsedType}),v):w((t.parsedType===u.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ey.create=(e,t)=>new ey({type:e,typeName:l.ZodPromise,...$(t)});class ev extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{g(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return v;let i=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===i.status?v:"dirty"===i.status||"dirty"===t.value?b(i.value):i});{if("aborted"===t.value)return v;let i=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===i.status?v:"dirty"===i.status||"dirty"===t.value?b(i.value):i}}if("refinement"===i.type){let e=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?v:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===i.status?v:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}}if("transform"===i.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?v:Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return v;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}n.assertNever(i)}}ev.create=(e,t,r)=>new ev({schema:e,typeName:l.ZodEffects,effect:t,...$(r)}),ev.createWithPreprocess=(e,t,r)=>new ev({schema:t,effect:{type:"preprocess",transform:e},typeName:l.ZodEffects,...$(r)});class eb extends I{_parse(e){return this._getType(e)===u.undefined?w(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:l.ZodOptional,...$(t)});class ew extends I{_parse(e){return this._getType(e)===u.null?w(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ew.create=(e,t)=>new ew({innerType:e,typeName:l.ZodNullable,...$(t)});class ex extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===u.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ex.create=(e,t)=>new ex({innerType:e,typeName:l.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...$(t)});class ek extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return x(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:l.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...$(t)});class e_ extends I{_parse(e){if(this._getType(e)!==u.nan){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.nan,received:t.parsedType}),v}return{status:"valid",value:e.data}}}e_.create=e=>new e_({typeName:l.ZodNaN,...$(e)}),Symbol("zod_brand");class e$ extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eI extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),b(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eI({in:e,out:t,typeName:l.ZodPipeline})}}class eS extends I{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return x(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:l.ZodReadonly,...$(t)}),er.lazycreate,(a=l||(l={})).ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly",z.create,K.create,e_.create,G.create,H.create,Z.create,V.create,J.create,W.create,Q.create,Y.create,X.create,ee.create,et.create;let eE=er.create;er.strictCreate,ei.create,en.create,es.create,eo.create,el.create,ec.create,eu.create,ed.create,ep.create,em.create,ef.create,eg.create,ey.create,ev.create,eb.create,ew.create,ev.createWithPreprocess,eI.create,e.s(["ZodFirstPartyTypeKind",0,l,"object",0,eE],117958);var eT=e.i(127438),eC=e.i(639510),eR=e.i(486618),eP=e.i(862061);e.i(467662),e.i(236608);var eA=e.i(715143);let eD=eT.$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");eC.$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>eA.parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>eA.safeParse(e,t,r),e.parseAsync=async(t,r)=>eA.parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>eA.safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,r)=>eR.clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.apply=t=>t(e)}),eO=eT.$constructor("ZodMiniString",(e,t)=>{eC.$ZodString.init(e,t),eD.init(e,t)}),ej=((e,t)=>{eC.$ZodStringFormat.init(e,t),eO.init(e,t)},eT.$constructor("ZodMiniObject",(e,t)=>{eC.$ZodObject.init(e,t),eD.init(e,t),eR.defineLazy(e,"shape",()=>t.shape)}));function eN(e,t){return new ej({type:"object",shape:e??{},...eR.normalizeParams(t)})}function eq(e){return!!e._zod}function eU(e){let t=Object.values(e);if(0===t.length)return eN({});let r=t.every(eq),i=t.every(e=>!eq(e));if(r)return eN(e);if(i)return eE(e);throw Error("Mixed Zod versions detected in object shape.")}async function eL(e,t){return eq(e)?await eA.safeParseAsync(e,t):await e.safeParseAsync(t)}eP.describe,eP.meta,e.s(["getLiteralValue",0,function(e){if(eq(e)){let t=e._zod?.def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(void 0!==r)return r},"getObjectShape",0,function(e){let t;if(e&&(t=eq(e)?e._zod?.def?.shape:e.shape)){if("function"==typeof t)try{return t()}catch{return}return t}},"getParseErrorMessage",0,function(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{}}return String(e)},"getSchemaDescription",0,function(e){return e.description},"isSchemaOptional",0,function(e){return eq(e)?e._zod?.def?.type==="optional":"function"==typeof e.isOptional?e.isOptional():e._def?.typeName==="ZodOptional"},"isZ4Schema",0,eq,"normalizeObjectSchema",0,function(e){if(e){if("object"==typeof e&&!e._def&&!e._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return eU(e)}if(eq(e)){let t=e._zod?.def;if(t&&("object"===t.type||void 0!==t.shape))return e}else if(void 0!==e.shape)return e}},"objectFromShape",0,eU,"safeParse",0,function(e,t){return eq(e)?eA.safeParse(e,t):e.safeParse(t)},"safeParseAsync",0,eL],514849)},556690,e=>{"use strict";var t,r,i=e.i(907855),a=e.i(551047),a=a;let n="2025-11-25",s=[n,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],o="io.modelcontextprotocol/related-task",l=i.custom(e=>null!==e&&("object"==typeof e||"function"==typeof e)),c=i.union([i.string(),i.number().int()]),u=i.string();i.looseObject({ttl:i.number().optional(),pollInterval:i.number().optional()});let d=i.object({ttl:i.number().optional()}),p=i.object({taskId:i.string()}),m=i.looseObject({progressToken:c.optional(),[o]:p.optional()}),h=i.object({_meta:m.optional()}),f=h.extend({task:d.optional()}),g=i.object({method:i.string(),params:h.loose().optional()}),y=i.object({_meta:m.optional()}),v=i.object({method:i.string(),params:y.loose().optional()}),b=i.looseObject({_meta:m.optional()}),w=i.union([i.string(),i.number().int()]),x=i.object({jsonrpc:i.literal("2.0"),id:w,...g.shape}).strict(),k=i.object({jsonrpc:i.literal("2.0"),...v.shape}).strict(),_=i.object({jsonrpc:i.literal("2.0"),id:w,result:b}).strict();(t=r||(r={}))[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired";let $=i.object({jsonrpc:i.literal("2.0"),id:w.optional(),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()})}).strict(),I=i.union([x,k,_,$]);i.union([_,$]);let S=b.strict(),E=y.extend({requestId:w.optional(),reason:i.string().optional()}),T=v.extend({method:i.literal("notifications/cancelled"),params:E}),C=i.object({src:i.string(),mimeType:i.string().optional(),sizes:i.array(i.string()).optional(),theme:i.enum(["light","dark"]).optional()}),R=i.object({icons:i.array(C).optional()}),P=i.object({name:i.string(),title:i.string().optional()}),A=P.extend({...P.shape,...R.shape,version:i.string(),websiteUrl:i.string().optional(),description:i.string().optional()}),D=i.intersection(i.object({applyDefaults:i.boolean().optional()}),i.record(i.string(),i.unknown())),O=i.preprocess(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,i.intersection(i.object({form:D.optional(),url:l.optional()}),i.record(i.string(),i.unknown()).optional())),j=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({sampling:i.looseObject({createMessage:l.optional()}).optional(),elicitation:i.looseObject({create:l.optional()}).optional()}).optional()}),N=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({tools:i.looseObject({call:l.optional()}).optional()}).optional()}),q=i.object({experimental:i.record(i.string(),l).optional(),sampling:i.object({context:l.optional(),tools:l.optional()}).optional(),elicitation:O.optional(),roots:i.object({listChanged:i.boolean().optional()}).optional(),tasks:j.optional(),extensions:i.record(i.string(),l).optional()}),U=h.extend({protocolVersion:i.string(),capabilities:q,clientInfo:A}),L=g.extend({method:i.literal("initialize"),params:U}),F=i.object({experimental:i.record(i.string(),l).optional(),logging:l.optional(),completions:l.optional(),prompts:i.object({listChanged:i.boolean().optional()}).optional(),resources:i.object({subscribe:i.boolean().optional(),listChanged:i.boolean().optional()}).optional(),tools:i.object({listChanged:i.boolean().optional()}).optional(),tasks:N.optional(),extensions:i.record(i.string(),l).optional()}),M=b.extend({protocolVersion:i.string(),capabilities:F,serverInfo:A,instructions:i.string().optional()}),B=v.extend({method:i.literal("notifications/initialized"),params:y.optional()}),z=g.extend({method:i.literal("ping"),params:h.optional()}),K=i.object({progress:i.number(),total:i.optional(i.number()),message:i.optional(i.string())}),G=i.object({...y.shape,...K.shape,progressToken:c}),H=v.extend({method:i.literal("notifications/progress"),params:G}),Z=h.extend({cursor:u.optional()}),V=g.extend({params:Z.optional()}),J=b.extend({nextCursor:u.optional()}),W=i.enum(["working","input_required","completed","failed","cancelled"]),Q=i.object({taskId:i.string(),status:W,ttl:i.union([i.number(),i.null()]),createdAt:i.string(),lastUpdatedAt:i.string(),pollInterval:i.optional(i.number()),statusMessage:i.optional(i.string())}),Y=b.extend({task:Q}),X=y.merge(Q),ee=v.extend({method:i.literal("notifications/tasks/status"),params:X}),et=g.extend({method:i.literal("tasks/get"),params:h.extend({taskId:i.string()})}),er=b.merge(Q),ei=g.extend({method:i.literal("tasks/result"),params:h.extend({taskId:i.string()})});b.loose();let ea=V.extend({method:i.literal("tasks/list")}),en=J.extend({tasks:i.array(Q)}),es=g.extend({method:i.literal("tasks/cancel"),params:h.extend({taskId:i.string()})}),eo=b.merge(Q),el=i.object({uri:i.string(),mimeType:i.optional(i.string()),_meta:i.record(i.string(),i.unknown()).optional()}),ec=el.extend({text:i.string()}),eu=i.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=el.extend({blob:eu}),ep=i.enum(["user","assistant"]),em=i.object({audience:i.array(ep).optional(),priority:i.number().min(0).max(1).optional(),lastModified:a.datetime({offset:!0}).optional()}),eh=i.object({...P.shape,...R.shape,uri:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),size:i.optional(i.number()),annotations:em.optional(),_meta:i.optional(i.looseObject({}))}),ef=i.object({...P.shape,...R.shape,uriTemplate:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),annotations:em.optional(),_meta:i.optional(i.looseObject({}))}),eg=V.extend({method:i.literal("resources/list")}),ey=J.extend({resources:i.array(eh)}),ev=V.extend({method:i.literal("resources/templates/list")}),eb=J.extend({resourceTemplates:i.array(ef)}),ew=h.extend({uri:i.string()}),ex=g.extend({method:i.literal("resources/read"),params:ew}),ek=b.extend({contents:i.array(i.union([ec,ed]))}),e_=v.extend({method:i.literal("notifications/resources/list_changed"),params:y.optional()}),e$=g.extend({method:i.literal("resources/subscribe"),params:ew}),eI=g.extend({method:i.literal("resources/unsubscribe"),params:ew}),eS=y.extend({uri:i.string()}),eE=v.extend({method:i.literal("notifications/resources/updated"),params:eS}),eT=i.object({name:i.string(),description:i.optional(i.string()),required:i.optional(i.boolean())}),eC=i.object({...P.shape,...R.shape,description:i.optional(i.string()),arguments:i.optional(i.array(eT)),_meta:i.optional(i.looseObject({}))}),eR=V.extend({method:i.literal("prompts/list")}),eP=J.extend({prompts:i.array(eC)}),eA=h.extend({name:i.string(),arguments:i.record(i.string(),i.string()).optional()}),eD=g.extend({method:i.literal("prompts/get"),params:eA}),eO=i.object({type:i.literal("text"),text:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),ej=i.object({type:i.literal("image"),data:eu,mimeType:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eN=i.object({type:i.literal("audio"),data:eu,mimeType:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eq=i.object({type:i.literal("tool_use"),name:i.string(),id:i.string(),input:i.record(i.string(),i.unknown()),_meta:i.record(i.string(),i.unknown()).optional()}),eU=i.object({type:i.literal("resource"),resource:i.union([ec,ed]),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eL=eh.extend({type:i.literal("resource_link")}),eF=i.union([eO,ej,eN,eL,eU]),eM=i.object({role:ep,content:eF}),eB=b.extend({description:i.string().optional(),messages:i.array(eM)}),ez=v.extend({method:i.literal("notifications/prompts/list_changed"),params:y.optional()}),eK=i.object({title:i.string().optional(),readOnlyHint:i.boolean().optional(),destructiveHint:i.boolean().optional(),idempotentHint:i.boolean().optional(),openWorldHint:i.boolean().optional()}),eG=i.object({taskSupport:i.enum(["required","optional","forbidden"]).optional()}),eH=i.object({...P.shape,...R.shape,description:i.string().optional(),inputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()),outputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()).optional(),annotations:eK.optional(),execution:eG.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eZ=V.extend({method:i.literal("tools/list")}),eV=J.extend({tools:i.array(eH)}),eJ=b.extend({content:i.array(eF).default([]),structuredContent:i.record(i.string(),i.unknown()).optional(),isError:i.boolean().optional()});eJ.or(b.extend({toolResult:i.unknown()}));let eW=f.extend({name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),eQ=g.extend({method:i.literal("tools/call"),params:eW}),eY=v.extend({method:i.literal("notifications/tools/list_changed"),params:y.optional()}),eX=i.object({autoRefresh:i.boolean().default(!0),debounceMs:i.number().int().nonnegative().default(300)}),e0=i.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),e1=h.extend({level:e0}),e4=g.extend({method:i.literal("logging/setLevel"),params:e1}),e3=y.extend({level:e0,logger:i.string().optional(),data:i.unknown()}),e2=v.extend({method:i.literal("notifications/message"),params:e3}),e6=i.object({name:i.string().optional()}),e9=i.object({hints:i.array(e6).optional(),costPriority:i.number().min(0).max(1).optional(),speedPriority:i.number().min(0).max(1).optional(),intelligencePriority:i.number().min(0).max(1).optional()}),e8=i.object({mode:i.enum(["auto","required","none"]).optional()}),e5=i.object({type:i.literal("tool_result"),toolUseId:i.string().describe("The unique identifier for the corresponding tool call."),content:i.array(eF).default([]),structuredContent:i.object({}).loose().optional(),isError:i.boolean().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e7=i.discriminatedUnion("type",[eO,ej,eN]),te=i.discriminatedUnion("type",[eO,ej,eN,eq,e5]),tt=i.object({role:ep,content:i.union([te,i.array(te)]),_meta:i.record(i.string(),i.unknown()).optional()}),tr=f.extend({messages:i.array(tt),modelPreferences:e9.optional(),systemPrompt:i.string().optional(),includeContext:i.enum(["none","thisServer","allServers"]).optional(),temperature:i.number().optional(),maxTokens:i.number().int(),stopSequences:i.array(i.string()).optional(),metadata:l.optional(),tools:i.array(eH).optional(),toolChoice:e8.optional()}),ti=g.extend({method:i.literal("sampling/createMessage"),params:tr}),ta=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens"]).or(i.string())),role:ep,content:e7}),tn=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(i.string())),role:ep,content:i.union([te,i.array(te)])}),ts=i.object({type:i.literal("boolean"),title:i.string().optional(),description:i.string().optional(),default:i.boolean().optional()}),to=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),minLength:i.number().optional(),maxLength:i.number().optional(),format:i.enum(["email","uri","date","date-time"]).optional(),default:i.string().optional()}),tl=i.object({type:i.enum(["number","integer"]),title:i.string().optional(),description:i.string().optional(),minimum:i.number().optional(),maximum:i.number().optional(),default:i.number().optional()}),tc=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),default:i.string().optional()}),tu=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),oneOf:i.array(i.object({const:i.string(),title:i.string()})),default:i.string().optional()}),td=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),enumNames:i.array(i.string()).optional(),default:i.string().optional()}),tp=i.union([tc,tu]),tm=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({type:i.literal("string"),enum:i.array(i.string())}),default:i.array(i.string()).optional()}),th=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({anyOf:i.array(i.object({const:i.string(),title:i.string()}))}),default:i.array(i.string()).optional()}),tf=i.union([tm,th]),tg=i.union([td,tp,tf]),ty=i.union([tg,ts,to,tl]),tv=f.extend({mode:i.literal("form").optional(),message:i.string(),requestedSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),ty),required:i.array(i.string()).optional()})}),tb=f.extend({mode:i.literal("url"),message:i.string(),elicitationId:i.string(),url:i.string().url()}),tw=i.union([tv,tb]),tx=g.extend({method:i.literal("elicitation/create"),params:tw}),tk=y.extend({elicitationId:i.string()}),t_=v.extend({method:i.literal("notifications/elicitation/complete"),params:tk}),t$=b.extend({action:i.enum(["accept","decline","cancel"]),content:i.preprocess(e=>null===e?void 0:e,i.record(i.string(),i.union([i.string(),i.number(),i.boolean(),i.array(i.string())])).optional())}),tI=i.object({type:i.literal("ref/resource"),uri:i.string()}),tS=i.object({type:i.literal("ref/prompt"),name:i.string()}),tE=h.extend({ref:i.union([tS,tI]),argument:i.object({name:i.string(),value:i.string()}),context:i.object({arguments:i.record(i.string(),i.string()).optional()}).optional()}),tT=g.extend({method:i.literal("completion/complete"),params:tE}),tC=b.extend({completion:i.looseObject({values:i.array(i.string()).max(100),total:i.optional(i.number().int()),hasMore:i.optional(i.boolean())})}),tR=i.object({uri:i.string().startsWith("file://"),name:i.string().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),tP=g.extend({method:i.literal("roots/list"),params:h.optional()}),tA=b.extend({roots:i.array(tR)}),tD=v.extend({method:i.literal("notifications/roots/list_changed"),params:y.optional()});i.union([z,L,tT,e4,eD,eR,eg,ev,ex,e$,eI,eQ,eZ,et,ei,ea,es]),i.union([T,H,B,tD,ee]),i.union([S,ta,tn,t$,tA,er,en,Y]),i.union([z,ti,tx,tP,et,ei,ea,es]),i.union([T,H,e2,eE,e_,eY,ez,ee,t_]),i.union([S,M,tC,eB,eP,ey,eb,ek,eJ,eV,er,en,Y]);class tO extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,i){return e===r.UrlElicitationRequired&&i&&i.elicitations?new tj(i.elicitations,t):new tO(e,t,i)}}class tj extends tO{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(r.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}e.s(["CallToolRequestSchema",0,eQ,"CallToolResultSchema",0,eJ,"CancelTaskRequestSchema",0,es,"CancelTaskResultSchema",0,eo,"CancelledNotificationSchema",0,T,"CompleteRequestSchema",0,tT,"CompleteResultSchema",0,tC,"CreateMessageRequestSchema",0,ti,"CreateMessageResultSchema",0,ta,"CreateMessageResultWithToolsSchema",0,tn,"CreateTaskResultSchema",0,Y,"DEFAULT_NEGOTIATED_PROTOCOL_VERSION",0,"2025-03-26","ElicitRequestSchema",0,tx,"ElicitResultSchema",0,t$,"EmptyResultSchema",0,S,"ErrorCode",0,r,"GetPromptRequestSchema",0,eD,"GetPromptResultSchema",0,eB,"GetTaskPayloadRequestSchema",0,ei,"GetTaskRequestSchema",0,et,"GetTaskResultSchema",0,er,"InitializeRequestSchema",0,L,"InitializeResultSchema",0,M,"InitializedNotificationSchema",0,B,"JSONRPCMessageSchema",0,I,"LATEST_PROTOCOL_VERSION",0,n,"ListChangedOptionsBaseSchema",0,eX,"ListPromptsRequestSchema",0,eR,"ListPromptsResultSchema",0,eP,"ListResourceTemplatesRequestSchema",0,ev,"ListResourceTemplatesResultSchema",0,eb,"ListResourcesRequestSchema",0,eg,"ListResourcesResultSchema",0,ey,"ListRootsResultSchema",0,tA,"ListTasksRequestSchema",0,ea,"ListTasksResultSchema",0,en,"ListToolsRequestSchema",0,eZ,"ListToolsResultSchema",0,eV,"LoggingLevelSchema",0,e0,"McpError",0,tO,"PingRequestSchema",0,z,"ProgressNotificationSchema",0,H,"PromptListChangedNotificationSchema",0,ez,"RELATED_TASK_META_KEY",0,o,"ReadResourceRequestSchema",0,ex,"ReadResourceResultSchema",0,ek,"ResourceListChangedNotificationSchema",0,e_,"SUPPORTED_PROTOCOL_VERSIONS",0,s,"SetLevelRequestSchema",0,e4,"TaskStatusNotificationSchema",0,ee,"ToolListChangedNotificationSchema",0,eY,"assertCompleteRequestPrompt",0,function(e){if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)},"assertCompleteRequestResourceTemplate",0,function(e){if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)},"isInitializeRequest",0,e=>L.safeParse(e).success,"isInitializedNotification",0,e=>B.safeParse(e).success,"isJSONRPCErrorResponse",0,e=>$.safeParse(e).success,"isJSONRPCNotification",0,e=>k.safeParse(e).success,"isJSONRPCRequest",0,e=>x.safeParse(e).success,"isJSONRPCResultResponse",0,e=>_.safeParse(e).success,"isTaskAugmentedRequestParams",0,e=>f.safeParse(e).success],556690)},729677,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.regexpCode=r.getEsmExportName=r.getProperty=r.safeStringify=r.stringify=r.strConcat=r.addCodeArg=r.str=r._=r.nil=r._Code=r.Name=r.IDENTIFIER=r._CodeOrName=void 0;class i{}r._CodeOrName=i,r.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class a extends i{constructor(e){if(super(),!r.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}r.Name=a;class n extends i{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return""===e||'""'===e}get str(){var e;return null!=(e=this._str)?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!=(e=this._names)?e:this._names=this._items.reduce((e,t)=>(t instanceof a&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){let r=[e[0]],i=0;for(;i<t.length;)c(r,t[i]),r.push(e[++i]);return new n(r)}r._Code=n,r.nil=new n(""),r._=s;let o=new n("+");function l(e,...t){let r=[u(e[0])],i=0;for(;i<t.length;)r.push(o),c(r,t[i]),r.push(o,u(e[++i]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===o){var r,i;let n=(r=e[t-1],'""'===(i=e[t+1])?r:'""'===r?i:"string"==typeof r?i instanceof a||'"'!==r[r.length-1]?void 0:"string"!=typeof i?`${r.slice(0,-1)}${i}"`:'"'===i[0]?r.slice(0,-1)+i.slice(1):void 0:"string"!=typeof i||'"'!==i[0]||r instanceof a?void 0:`"${r}${i.slice(1)}`);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(r),new n(r)}function c(e,t){var r;t instanceof n?e.push(...t._items):t instanceof a?e.push(t):e.push("number"==typeof(r=t)||"boolean"==typeof r||null===r?r:u(Array.isArray(r)?r.join(","):r))}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}r.str=l,r.addCodeArg=c,r.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:l`${e}${t}`},r.stringify=function(e){return new n(u(e))},r.safeStringify=u,r.getProperty=function(e){return"string"==typeof e&&r.IDENTIFIER.test(e)?new n(`.${e}`):s`[${e}]`},r.getEsmExportName=function(e){if("string"==typeof e&&r.IDENTIFIER.test(e))return new n(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},r.regexpCode=function(e){return new n(e.toString())}},738478,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.ValueScope=r.ValueScopeName=r.Scope=r.varKinds=r.UsedValueState=void 0;let n=e.r(729677);class s extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}(a=i||(r.UsedValueState=i={}))[a.Started=0]="Started",a[a.Completed=1]="Completed",r.varKinds={const:new n.Name("const"),let:new n.Name("let"),var:new n.Name("var")};class o{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof n.Name?e:this.name(e)}name(e){return new n.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if((null==(r=null==(t=this._parent)?void 0:t._prefixes)?void 0:r.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}}}r.Scope=o;class l extends n.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0,n._)`.${new n.Name(t)}[${r}]`}}r.ValueScopeName=l;let c=(0,n._)`\n`;r.ValueScope=class extends o{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:n.nil}}get(){return this._scope}name(e){return new l(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,n=null!=(r=t.key)?r:t.ref,s=this._values[a];if(s){let e=s.get(n);if(e)return e}else s=this._values[a]=new Map;s.set(n,i);let o=this._scope[a]||(this._scope[a]=[]),l=o.length;return o[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw Error(`CodeGen: name "${t}" has no value`);return(0,n._)`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,t,a={},o){let l=n.nil;for(let c in e){let u=e[c];if(!u)continue;let d=a[c]=a[c]||new Map;u.forEach(e=>{if(d.has(e))return;d.set(e,i.Started);let a=t(e);if(a){let t=this.opts.es5?r.varKinds.var:r.varKinds.const;l=(0,n._)`${l}${t} ${e} = ${a};${this.opts._n}`}else if(a=null==o?void 0:o(e))l=(0,n._)`${l}${a}${this.opts._n}`;else throw new s(e);d.set(e,i.Completed)})}return l}}},847550,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.or=r.and=r.not=r.CodeGen=r.operators=r.varKinds=r.ValueScopeName=r.ValueScope=r.Scope=r.Name=r.regexpCode=r.stringify=r.getProperty=r.nil=r.strConcat=r.str=r._=void 0;let i=e.r(729677),a=e.r(738478);var n=e.r(729677);Object.defineProperty(r,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(r,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(r,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(r,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(r,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(r,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(r,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(r,"Name",{enumerable:!0,get:function(){return n.Name}});var s=e.r(738478);Object.defineProperty(r,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(r,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(r,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(r,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),r.operators={GT:new i._Code(">"),GTE:new i._Code(">="),LT:new i._Code("<"),LTE:new i._Code("<="),EQ:new i._Code("==="),NEQ:new i._Code("!=="),NOT:new i._Code("!"),OR:new i._Code("||"),AND:new i._Code("&&"),ADD:new i._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class l extends o{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?a.varKinds.var:this.varKind,i=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=P(this.rhs,e,t)),this}get names(){return this.rhs instanceof i._CodeOrName?this.rhs.names:{}}}class c extends o{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof i.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=P(this.rhs,e,t),this}get names(){return R(this.lhs instanceof i.Name?{}:{...this.lhs.names},this.rhs)}}class u extends c{constructor(e,t,r,i){super(e,r,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class d extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class p extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){let t=this.label?` ${this.label}`:"";return`break${t};`+e}}class m extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends o{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=P(this.code,e,t),this}get names(){return this.code instanceof i._CodeOrName?this.code.names:{}}}class f extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(function(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}(e,a.names),r.splice(i,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>C(e,t.names),{})}}class g extends f{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class y extends f{}class v extends g{}v.kind="else";class b extends g{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 e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){let e=t.optimizeNodes();t=this.else=Array.isArray(e)?new v(e):e}return t?!1===e?t instanceof b?t:t.nodes:this.nodes.length?this:new b(A(e),t instanceof b?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null==(r=this.else)?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=P(this.condition,e,t),this}get names(){let e=super.names;return R(e,this.condition),this.else&&C(e,this.else.names),e}}b.kind="if";class w extends g{}w.kind="for";class x extends w{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=P(this.iteration,e,t),this}get names(){return C(super.names,this.iteration.names)}}class k extends w{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?a.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=R(super.names,this.from);return R(e,this.to)}}class _ extends w{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i}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=P(this.iterable,e,t),this}get names(){return C(super.names,this.iterable.names)}}class $ extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){let t=this.async?"async ":"";return`${t}function ${this.name}(${this.args})`+super.render(e)}}$.kind="func";class I extends f{render(e){return"return "+super.render(e)}}I.kind="return";class S extends g{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(),null==(e=this.catch)||e.optimizeNodes(),null==(t=this.finally)||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),null==(r=this.catch)||r.optimizeNames(e,t),null==(i=this.finally)||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&C(e,this.catch.names),this.finally&&C(e,this.finally.names),e}}class E extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}E.kind="catch";class T extends g{render(e){return"finally"+super.render(e)}}function C(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function R(e,t){return t instanceof i._CodeOrName?C(e,t.names):e}function P(e,t,r){var a;if(e instanceof i.Name)return n(e);if(!((a=e)instanceof i._Code&&a._items.some(e=>e instanceof i.Name&&1===t[e.str]&&void 0!==r[e.str])))return e;return new i._Code(e._items.reduce((e,t)=>(t instanceof i.Name&&(t=n(t)),t instanceof i._Code?e.push(...t._items):e.push(t),e),[]));function n(e){let i=r[e.str];return void 0===i||1!==t[e.str]?e:(delete t[e.str],i)}}function A(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:(0,i._)`!${N(e)}`}T.kind="finally",r.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new a.Scope({parent:e}),this._nodes=[new y]}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 r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}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,r,i){let a=this._scope.toName(t);return void 0!==r&&i&&(this._constants[a.str]=r),this._leafNode(new l(e,a,r)),a}const(e,t,r){return this._def(a.varKinds.const,e,t,r)}let(e,t,r){return this._def(a.varKinds.let,e,t,r)}var(e,t,r){return this._def(a.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new c(e,t,r))}add(e,t){return this._leafNode(new u(e,r.operators.ADD,t))}code(e){return"function"==typeof e?e():e!==i.nil&&this._leafNode(new h(e)),this}object(...e){let t=["{"];for(let[r,a]of e)t.length>1&&t.push(","),t.push(r),(r!==a||this.opts.es5)&&(t.push(":"),(0,i.addCodeArg)(t,a));return t.push("}"),new i._Code(t)}if(e,t,r){if(this._blockNode(new b(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new b(e))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(b,v)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new x(e),t)}forRange(e,t,r,i,n=this.opts.es5?a.varKinds.var:a.varKinds.let){let s=this._scope.toName(e);return this._for(new k(n,s,t,r),()=>i(s))}forOf(e,t,r,n=a.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let e=t instanceof i.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,i._)`${e}.length`,t=>{this.var(s,(0,i._)`${e}[${t}]`),r(s)})}return this._for(new _("of",n,s,t),()=>r(s))}forIn(e,t,r,n=this.opts.es5?a.varKinds.var:a.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,i._)`Object.keys(${t})`,r);let s=this._scope.toName(e);return this._for(new _("in",n,s,t),()=>r(s))}endFor(){return this._endBlockNode(w)}label(e){return this._leafNode(new d(e))}break(e){return this._leafNode(new p(e))}return(e){let t=new I;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(I)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new S;if(this._blockNode(i),this.code(e),t){let e=this.name("e");this._currNode=i.catch=new E(e),t(e)}return r&&(this._currNode=i.finally=new T,this.code(r)),this._endBlockNode(E,T)}throw(e){return this._leafNode(new m(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(void 0===t)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=i.nil,r,a){return this._blockNode(new $(e,t,r)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode($)}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 r=this._currNode;if(r instanceof e||t&&r 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 b))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}},r.not=A;let D=j(r.operators.AND);r.and=function(...e){return e.reduce(D)};let O=j(r.operators.OR);function j(e){return(t,r)=>t===i.nil?r:r===i.nil?t:(0,i._)`${N(t)} ${e} ${N(r)}`}function N(e){return e instanceof i.Name?e:(0,i._)`(${e})`}r.or=function(...e){return e.reduce(O)}},303581,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.checkStrictMode=r.getErrorPath=r.Type=r.useFunc=r.setEvaluated=r.evaluatedPropsToName=r.mergeEvaluated=r.eachItem=r.unescapeJsonPointer=r.escapeJsonPointer=r.escapeFragment=r.unescapeFragment=r.schemaRefOrVal=r.schemaHasRulesButRef=r.schemaHasRules=r.checkUnknownRules=r.alwaysValidSchema=r.toHash=void 0;let n=e.r(847550),s=e.r(729677);function o(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema||"boolean"==typeof t)return;let a=i.RULES.keywords;for(let r in t)a[r]||f(e,`unknown keyword: "${r}"`)}function l(e,t){if("boolean"==typeof e)return!e;for(let r in e)if(t[r])return!0;return!1}function c(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(a,s,o,l)=>{let c=void 0===o?s:o instanceof n.Name?(s instanceof n.Name?e(a,s,o):t(a,s,o),o):s instanceof n.Name?(t(a,o,s),s):r(s,o);return l!==n.Name||c instanceof n.Name?c:i(a,c)}}function p(e,t){if(!0===t)return e.var("props",!0);let r=e.var("props",(0,n._)`{}`);return void 0!==t&&m(e,r,t),r}function m(e,t,r){Object.keys(r).forEach(r=>e.assign((0,n._)`${t}${(0,n.getProperty)(r)}`,!0))}r.toHash=function(e){let t={};for(let r of e)t[r]=!0;return t},r.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(o(e,t),!l(t,e.self.RULES.all))},r.checkUnknownRules=o,r.schemaHasRules=l,r.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(let r in e)if("$ref"!==r&&t.all[r])return!0;return!1},r.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,i,a){if(!a){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return(0,n._)`${r}`}return(0,n._)`${e}${t}${(0,n.getProperty)(i)}`},r.unescapeFragment=function(e){return u(decodeURIComponent(e))},r.escapeFragment=function(e){return encodeURIComponent(c(e))},r.escapeJsonPointer=c,r.unescapeJsonPointer=u,r.eachItem=function(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)},r.mergeEvaluated={props:d({mergeNames:(e,t,r)=>e.if((0,n._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,n._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,n._)`${r} || {}`).code((0,n._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,n._)`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,(0,n._)`${r} || {}`),m(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:p}),items:d({mergeNames:(e,t,r)=>e.if((0,n._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,n._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,n._)`${r} !== true`,()=>e.assign(r,!0===t||(0,n._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},r.evaluatedPropsToName=p,r.setEvaluated=m;let h={};function f(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw Error(t);e.self.logger.warn(t)}}r.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:h[t.code]||(h[t.code]=new s._Code(t.code))})},(a=i||(r.Type=i={}))[a.Num=0]="Num",a[a.Str=1]="Str",r.getErrorPath=function(e,t,r){if(e instanceof n.Name){let a=t===i.Num;return r?a?(0,n._)`"[" + ${e} + "]"`:(0,n._)`"['" + ${e} + "']"`:a?(0,n._)`"/" + ${e}`:(0,n._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,n.getProperty)(e).toString():"/"+c(e)},r.checkStrictMode=f},424819,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550);r.default={data:new i.Name("data"),valCxt:new i.Name("valCxt"),instancePath:new i.Name("instancePath"),parentData:new i.Name("parentData"),parentDataProperty:new i.Name("parentDataProperty"),rootData:new i.Name("rootData"),dynamicAnchors:new i.Name("dynamicAnchors"),vErrors:new i.Name("vErrors"),errors:new i.Name("errors"),this:new i.Name("this"),self:new i.Name("self"),scope:new i.Name("scope"),json:new i.Name("json"),jsonPos:new i.Name("jsonPos"),jsonLen:new i.Name("jsonLen"),jsonPart:new i.Name("jsonPart")}},703402,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.extendErrors=r.resetErrorsCount=r.reportExtraError=r.reportError=r.keyword$DataError=r.keywordError=void 0;let i=e.r(847550),a=e.r(303581),n=e.r(424819);function s(e,t){let r=e.const("err",t);e.if((0,i._)`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,(0,i._)`[${r}]`),(0,i._)`${n.default.vErrors}.push(${r})`),e.code((0,i._)`${n.default.errors}++`)}function o(e,t){let{gen:r,validateName:a,schemaEnv:n}=e;n.$async?r.throw((0,i._)`new ${e.ValidationError}(${t})`):(r.assign((0,i._)`${a}.errors`,t),r.return(!1))}r.keywordError={message:({keyword:e})=>(0,i.str)`must pass "${e}" keyword validation`},r.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,i.str)`"${e}" keyword must be ${t} ($data)`:(0,i.str)`"${e}" keyword is invalid ($data)`},r.reportError=function(e,t=r.keywordError,a,n){let{it:l}=e,{gen:u,compositeRule:d,allErrors:p}=l,m=c(e,t,a);(null!=n?n:d||p)?s(u,m):o(l,(0,i._)`[${m}]`)},r.reportExtraError=function(e,t=r.keywordError,i){let{it:a}=e,{gen:l,compositeRule:u,allErrors:d}=a;s(l,c(e,t,i)),u||d||o(a,n.default.vErrors)},r.resetErrorsCount=function(e,t){e.assign(n.default.errors,t),e.if((0,i._)`${n.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,i._)`${n.default.vErrors}.length`,t),()=>e.assign(n.default.vErrors,null)))},r.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:a,errsCount:s,it:o}){if(void 0===s)throw Error("ajv implementation error");let l=e.name("err");e.forRange("i",s,n.default.errors,s=>{e.const(l,(0,i._)`${n.default.vErrors}[${s}]`),e.if((0,i._)`${l}.instancePath === undefined`,()=>e.assign((0,i._)`${l}.instancePath`,(0,i.strConcat)(n.default.instancePath,o.errorPath))),e.assign((0,i._)`${l}.schemaPath`,(0,i.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,i._)`${l}.schema`,r),e.assign((0,i._)`${l}.data`,a))})};let l={keyword:new i.Name("keyword"),schemaPath:new i.Name("schemaPath"),params:new i.Name("params"),propertyName:new i.Name("propertyName"),message:new i.Name("message"),schema:new i.Name("schema"),parentSchema:new i.Name("parentSchema")};function c(e,t,r){let{createErrors:s}=e.it;return!1===s?(0,i._)`{}`:function(e,t,r={}){let{gen:s,it:o}=e,c=[function({errorPath:e},{instancePath:t}){let r=t?(0,i.str)`${e}${(0,a.getErrorPath)(t,a.Type.Str)}`:e;return[n.default.instancePath,(0,i.strConcat)(n.default.instancePath,r)]}(o,r),function({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let s=n?t:(0,i.str)`${t}/${e}`;return r&&(s=(0,i.str)`${s}${(0,a.getErrorPath)(r,a.Type.Str)}`),[l.schemaPath,s]}(e,r)];return function(e,{params:t,message:r},a){let{keyword:s,data:o,schemaValue:c,it:u}=e,{opts:d,propertyName:p,topSchemaRef:m,schemaPath:h}=u;a.push([l.keyword,s],[l.params,"function"==typeof t?t(e):t||(0,i._)`{}`]),d.messages&&a.push([l.message,"function"==typeof r?r(e):r]),d.verbose&&a.push([l.schema,c],[l.parentSchema,(0,i._)`${m}${h}`],[n.default.data,o]),p&&a.push([l.propertyName,p])}(e,t,c),s.object(...c)}(e,t,r)}},666703,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.boolOrEmptySchema=r.topBoolOrEmptySchema=void 0;let i=e.r(703402),a=e.r(847550),n=e.r(424819),s={message:"boolean schema is false"};function o(e,t){let{gen:r,data:a}=e;(0,i.reportError)({gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},s,void 0,t)}r.topBoolOrEmptySchema=function(e){let{gen:t,schema:r,validateName:i}=e;!1===r?o(e,!1):"object"==typeof r&&!0===r.$async?t.return(n.default.data):(t.assign((0,a._)`${i}.errors`,null),t.return(!0))},r.boolOrEmptySchema=function(e,t){let{gen:r,schema:i}=e;!1===i?(r.var(t,!1),o(e)):r.var(t,!0)}},991127,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getRules=r.isJSONType=void 0;let i=new Set(["string","number","integer","boolean","null","object","array"]);r.isJSONType=function(e){return"string"==typeof e&&i.has(e)},r.getRules=function(){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:{}}}},79932,(e,t,r)=>{"use strict";function i(e,t){return t.rules.some(t=>a(e,t))}function a(e,t){var r;return void 0!==e[t.keyword]||(null==(r=t.definition.implements)?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(r,"__esModule",{value:!0}),r.shouldUseRule=r.shouldUseGroup=r.schemaHasRulesForType=void 0,r.schemaHasRulesForType=function({schema:e,self:t},r){let a=t.RULES.types[r];return a&&!0!==a&&i(e,a)},r.shouldUseGroup=i,r.shouldUseRule=a},580581,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.reportTypeError=r.checkDataTypes=r.checkDataType=r.coerceAndCheckDataType=r.getJSONTypes=r.getSchemaTypes=r.DataType=void 0;let n=e.r(991127),s=e.r(79932),o=e.r(703402),l=e.r(847550),c=e.r(303581);function u(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(n.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}(a=i||(r.DataType=i={}))[a.Correct=0]="Correct",a[a.Wrong=1]="Wrong",r.getSchemaTypes=function(e){let t=u(e.type);if(t.includes("null")){if(!1===e.nullable)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},r.getJSONTypes=u,r.coerceAndCheckDataType=function(e,t){var r,a;let{gen:n,data:o,opts:c}=e,u=(r=t,(a=c.coerceTypes)?r.filter(e=>d.has(e)||"array"===a&&"array"===e):[]),p=t.length>0&&!(0===u.length&&1===t.length&&(0,s.schemaHasRulesForType)(e,t[0]));if(p){let r=m(t,o,c.strictNumbers,i.Wrong);n.if(r,()=>{u.length?function(e,t,r){let{gen:i,data:a,opts:n}=e,s=i.let("dataType",(0,l._)`typeof ${a}`),o=i.let("coerced",(0,l._)`undefined`);for(let e of("array"===n.coerceTypes&&i.if((0,l._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>i.assign(a,(0,l._)`${a}[0]`).assign(s,(0,l._)`typeof ${a}`).if(m(t,a,n.strictNumbers),()=>i.assign(o,a))),i.if((0,l._)`${o} !== undefined`),r))(d.has(e)||"array"===e&&"array"===n.coerceTypes)&&function(e){switch(e){case"string":i.elseIf((0,l._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0,l._)`"" + ${a}`).elseIf((0,l._)`${a} === null`).assign(o,(0,l._)`""`);return;case"number":i.elseIf((0,l._)`${s} == "boolean" || ${a} === null
394
+ ${t}`}splitMarkdownIntoSections(e){let t=e.split(/(?=^#{1,6}\s)|(?:\n\s*\n)/m).filter(e=>e.trim().length>0);return t.length>0?t:[e]}async parseMarkdownSection(e){try{let t=[this.createTextFallback(e)];return{success:!0,data:{version:1,type:"doc",content:t},warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createTextFallback(e){return{type:"paragraph",content:[{type:"text",text:e.trim()}]}}createPlaceholder(e){return e.operation.includes("adfToMarkdown")?`[Error converting ADF to Markdown: ${e.operation}]`:e.operation.includes("markdownToAdf")?{version:1,type:"doc",content:[{type:"paragraph",content:[{type:"text",text:`[Error converting Markdown to ADF: ${e.operation}]`}]}]}:`[Error in operation: ${e.operation}]`}},uI=class{constructor(e){(0,nT.__publicField)(this,"mdToAdfEngine"),(0,nT.__publicField)(this,"adfToMdEngine"),(0,nT.__publicField)(this,"options"),(0,nT.__publicField)(this,"errorRecovery"),(0,nT.__publicField)(this,"remarkProcessor"),(0,nT.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new cQ(this.options),this.adfToMdEngine=new u_(this.options),this.errorRecovery=new u$({maxRetries:e?.maxRetries||3,retryDelay:e?.retryDelay||100,fallbackStrategy:e?.fallbackStrategy||"best-effort",enableLogging:e?.enableLogging||!1,onError:e?.onError,onRecovery:e?.onRecovery}),this.remarkProcessor=nW().use(op).use(ll,["yaml"]).use(cg).use(cI,{strict:e?.strict||!1}).use(o6),this.registry=new cA,this.registerConverters()}catch(e){throw new cC("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new u_({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!r.success)throw r.error||Error("ADF to Markdown conversion failed");return r.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new cQ({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!r.success)throw r.error||Error("Markdown to ADF conversion failed");return r.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!r.success)throw r.error||Error("Async Markdown to ADF conversion failed");return r.data}async validateMarkdownAsync(e){let t=await this.mdToAdfEngine.validate(e);return{valid:t.valid,errors:t.errors.map(e=>({message:e})),warnings:t.warnings}}async getStats(e){return await this.mdToAdfEngine.getStats(e)}stringify(e,t){return this.adfToMarkdown(e,t)}async stringifyAsync(e,t){return this.adfToMarkdownWithRecovery(e,t)}validateAdf(e){return new cE().validate(e)}validateMarkdown(e){return new cT().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new cY,new cX,new c0,new c1,new c4,new c3,new c2,new c6,new c9,new c8,new c5,new c7,new ue,new ut,new ur,new ui,new ua,new un,new us,new uo,new ul,new uc,new uu,new ud,new up,new um]),this.registry.registerMarks([new uh,new uf,new ug,new uy,new uv,new ub,new uw,new ux,new uk])}convertAdfToMarkdown(e){return this.adfToMdEngine.convert(e)}convertMdastToAdf(e){return this.mdToAdfEngine.convert(e)}fallbackConversion(e){return this.mdToAdfEngine.convert(e)}countNodes(e){let t=0;for(let r of e)t++,r.content&&Array.isArray(r.content)&&(t+=this.countNodes(r.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},uS=e.i(378731);let uE=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function uT(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function uC(e,t){return uS.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,r)=>t?`[${r}](${t}/browse/${r})`:`**${r}**`))}let uR=new uI;function uP(e,t){if(null==e)return null;let r=function(e){if(uT(e))return"ADF";let t="string"==typeof e?e:"";return uE.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),a="ADF"===r?function(e){try{return uR.adfToMarkdown(e)}catch{return function e(t){return t&&"object"==typeof t?["string"==typeof t.text?t.text:"",...Array.isArray(t.content)?t.content.map(e).filter(Boolean):[]].filter(Boolean).join("\n"):""}(e)}}(e):"JIRA_WIKI"===r?uC(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:uS.default.to_jira(a)}}function uA(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?uC(t):t,i=uR.markdownToAdf(r);if(!uT(i))throw Error("The Jira text could not be converted to valid ADF");return i}let uD="default",uO=["summary","status","issuetype","priority","assignee","project","updated"],uj=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function uN(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function uq(e){return uN(e)?e:{}}function uU(e){return Array.isArray(e)?e:[]}function uL(e){return"string"==typeof e&&e.length>0?e:null}function uF(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function uM(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function uB(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function uz(e){return uU(uB(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function uK(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):uN(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function uG(e){if(!uN(e))return null;let t=e.status??uq(e.response).status;return"number"==typeof t?t:null}function uH(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function uZ(e){return uL(uq(uq(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function uV(e){let t=uq(e),r=uL(t.displayName);if(!r)return null;let i=uq(t.avatarUrls);return{accountId:uL(t.accountId),displayName:r,avatarUrl:uL(i["48x48"])??uL(i["32x32"])??uL(i["24x24"])}}function uJ(e){return uU(e).map(uq).map(e=>({id:uL(e.id),name:uL(e.name)??"Unknown"}))}function uW(e,t){let r=uq(e),i=uL(r.key);if(!i)return null;let a=uq(r.fields);return{relationship:t,key:i,summary:uL(a.summary)??i,status:uL(uq(a.status).name)}}function uQ(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function uY(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function uX(e){return 0===e.length?{source:"CACHE",stale:!1,fetchedAt:new Date(0).toISOString()}:{source:e.some(e=>"ERROR"===e.source)?"ERROR":e.some(e=>"LIVE"===e.source)?"LIVE":"CACHE",stale:e.some(e=>e.stale),fetchedAt:new Date(Math.max(...e.map(e=>e.fetchedAt.getTime()))).toISOString()}}function u0(e){let t=uq(e.fields),r=uq(t.status),i=uq(r.statusCategory),a=uq(t.assignee),n=uq(a.avatarUrls),s=uq(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:uL(t.summary)??o,statusId:uL(r.id)??uL(r.name)??"unknown",status:uL(r.name)??"Unknown",statusCategory:uL(i.key)??uL(i.name)??"unknown",issueType:uL(uq(t.issuetype).name),priority:uL(uq(t.priority).name),assignee:uL(a.displayName),assigneeAccountId:uL(a.accountId),assigneeAvatarUrl:uL(n["48x48"])??uL(n["32x32"]),projectKey:uL(s.key)??uZ(e),updatedAt:uL(t.updated)}}function u1(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let u4=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function u3(e){return u4.has(e)?e:"ALL"}class u2{inFlight=new Map;clients;lastPrunedAt=0;async getSettings(){let e=await (0,h.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:!!t.apiToken,cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,h.getPrismaClient)(),r=function(e){let t=new URL(e.trim());if("https:"!==t.protocol)throw Error("Jira Cloud site URL must use HTTPS");if(!t.hostname.toLowerCase().endsWith(".atlassian.net"))throw Error("Only Jira Cloud *.atlassian.net sites are supported");if(t.username||t.password||t.search||t.hash)throw Error("Jira site URL must not include credentials, query, or fragment");return t.origin}(e.siteUrl),i=e.email.trim();if(!/^\S+@\S+\.\S+$/.test(i))throw Error("A valid Jira email is required");let a=await t.jiraSettings.findUnique({where:{id:uD}}),n=e.apiToken?.trim()||a?.apiToken||null,s=!!(a?.siteUrl&&a.siteUrl!==r);if(s&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let o=a?.siteUrl!==r||a?.email!==i||a?.apiToken!==n;return await t.$transaction(async e=>{s&&await e.jiraProject.deleteMany(),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:uD},create:{id:uD,siteUrl:r,email:i,apiToken:n,cacheTtlSeconds:300},update:{siteUrl:r,email:i,apiToken:n}})}),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,h.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany(),e.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:300},update:{email:null,apiToken:null}})]),this.clients=void 0,this.getSettings()}async updateCacheTtl(e){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let t=await (0,h.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:uD},create:{id:uD,cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),this.getSettings()}async testConnection(){let e=await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",force:!0,allowStaleOnError:!1,fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}});if(e.stale)throw Error("Jira connection test failed because the live request failed");let t=uq(e.value);return{accountId:uL(t.accountId),displayName:uL(t.displayName)??"Jira user",emailAddress:uL(t.emailAddress),cache:uY(e)}}async listProjects(){let e=await (0,h.getPrismaClient)();return(await e.jiraProject.findMany({include:{sources:{orderBy:[{position:"asc"},{createdAt:"asc"}]}},orderBy:[{position:"asc"},{createdAt:"asc"}]})).map(e=>({id:e.id,jiraId:e.jiraId,key:e.key,name:e.name,avatarUrl:e.avatarUrl,position:e.position,ticketAssignmentFilter:u3(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:uz(e.completedStatusIdsJson),branchNamingScript:e.branchNamingScript??nI,sources:e.sources.map(uQ)}))}async projectStatuses(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!r)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:r.jiraId},requestSummary:`Statuses for project ${r.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(r.jiraId)}}),a=new Map;for(let e of uU(i.value).map(uq))for(let t of uU(e.statuses).map(uq)){let e=uL(t.id),r=uL(t.name);if(!e||!r||a.has(e))continue;let i=uq(t.statusCategory);a.set(e,{id:e,name:r,category:uL(i.key)??uL(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>u1(e.category)-u1(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!u4.has(e.ticketAssignmentFilter))throw Error("Invalid Jira ticket assignment filter");let t=[...new Set(e.completedStatusIds.map(e=>e.trim()).filter(Boolean))].slice(0,200),r=await (0,h.getPrismaClient)();return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t)}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,h.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await nE(t,i.key);return await r.jiraProject.update({where:{id:e},data:{branchNamingScript:a}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let r=await this.cachedCall({operation:"PROJECTS",params:{startAt:t,maxResults:100},requestSummary:`Visible projects from ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.searchProjects({startAt:t,maxResults:100,orderBy:"name"})},itemCount:e=>uU(uq(e).values).length}),i=uq(r.value),a=uU(i.values).map(uq);e.push(...a.flatMap(e=>{let t=uL(e.id),r=uL(e.key),i=uL(e.name);if(!t||!r||!i)return[];let a=uq(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:uL(a["48x48"])??uL(a["32x32"])}]}));let n=uF(i.total)??e.length;if(0===a.length||e.length>=n)break;t+=a.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let r=uq((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),i=uL(r.key),a=uL(r.name),n=uL(r.id);if(!i||!a||!n)throw Error("Jira returned an incomplete project");let s=uq(r.avatarUrls),o=await (0,h.getPrismaClient)(),l=await o.jiraProject.aggregate({_max:{position:!0}});return await o.jiraProject.create({data:{id:(0,d.randomUUID)(),jiraId:n,key:i,name:a,avatarUrl:uL(s["48x48"])??uL(s["32x32"]),position:(l._max.position??-1)+1,branchNamingScript:nI}}),this.listProjects()}async removeProject(e){let t=await (0,h.getPrismaClient)(),r=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:r}}}),await t.jiraProject.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async createSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,h.getPrismaClient)();if(!await i.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let a=await i.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await i.jiraSource.create({data:{id:(0,d.randomUUID)(),projectId:e.projectId,name:r,kind:e.kind,value:t.value,boardId:t.boardId,position:(a._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,h.getPrismaClient)();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:r,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await (0,h.getPrismaClient)();return await t.$transaction(async t=>{await t.jiraCacheEntry.deleteMany({where:{sourceId:e}}),await t.jiraSource.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async ticketBoard(e,t=!1){var r;let i,a,n,s=await (0,h.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l="BOARD"===o.kind?await this.loadBoardSource(uQ(o),t):await this.loadJqlSource(uQ(o),t),c={ticketAssignmentFilter:u3(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:uz(o.project.completedStatusIdsJson)},u="ALL"===c.ticketAssignmentFilter?null:await this.currentAccountId();return r={source:uQ(o),...l},i=c.hideCompletedTickets?new Set(c.completedStatusIds):new Set,a=new Set(r.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=r.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===c.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===c.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===u:null!==u&&e.assigneeAccountId===u&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))}}async ticket(e,t=!1){let r=uM(e),i=await this.cachedCall({operation:"ISSUE",params:{issueKey:r,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${r} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:r,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===i.source&&await this.storeDetail(i.entryId,i.value,i.fetchedAt);let a=[],n=[],s=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:r,startAt:s,maxResults:100},requestSummary:`Comments for ${r} from ${s}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:r,startAt:s,maxResults:100,orderBy:"created"})},itemCount:e=>uU(uq(e).comments).length});a.push(e);let i=uq(e.value),o=uU(i.comments);n.push(...o);let l=uF(i.total)??n.length;if(0===o.length||n.length>=l)break;s+=o.length}let o=new Date(Math.min(...a.map(e=>e.fetchedAt.getTime())));await this.storeComments(r,n,o,a.map(e=>e.entryId));let l=await this.requireCredentials();return this.normalizeTicketDetail(i.value,n,l.siteUrl,uY(i),uX(a))}async assignableUsers(e,t=""){let r=uM(e),i=t.trim().slice(0,100),a=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:r,query:i,maxResults:50},requestSummary:`Assignable users for ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:r,query:i,maxResults:50,recommend:!0})},itemCount:e=>uU(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),uU(a.value).map(uV).filter(e=>null!==e)}async ticketTransitions(e){let t=uM(e),r=await this.cachedCall({operation:"ISSUE_TRANSITIONS",params:{issueKey:t,expand:"transitions.fields"},requestSummary:`Available transitions for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getTransitions({issueIdOrKey:t,expand:"transitions.fields"})},itemCount:e=>uU(uq(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),uU(uq(r.value).transitions).map(uq).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=uL(e.id),r=uL(e.name);if(!t||!r)return[];let i=uq(e.to),a=uq(i.statusCategory),n=Object.entries(uq(e.fields)).filter(([,e])=>!0===uq(e).required).map(([e,t])=>uL(uq(t).name)??e);return[{id:t,name:r,toStatusId:uL(i.id),toStatus:uL(i.name)??r,toStatusCategory:uL(a.key)??uL(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=uM(e),r=await this.cachedCall({operation:"ISSUE_EDIT_META",params:{issueKey:t},requestSummary:`Editable fields for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getEditIssueMeta({issueIdOrKey:t})},itemCount:e=>Object.keys(uq(uq(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(uq(uq(r.value).fields)).map(([e,t])=>{let r=uq(t);return{id:e,name:uL(r.name)??e,required:!0===r.required,schemaType:uL(uq(r.schema).type),allowedValues:uU(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=uq(e),r=uL(t.name)??uL(t.value)??uL(t.displayName)??uL(t.key);return r?[{id:uL(t.id)??uL(t.accountId)??uL(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,r=0){let i=uM(e),a=this.validatePagination(t,r),n=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Changelog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>uU(uq(e).values).length});await this.linkCacheEntryToIssue(i,n.entryId);let s=uF(uq(n.value).total)??0,o=Math.min(a.limit,Math.max(0,s-a.offset)),l=Math.max(0,s-a.offset-o);if(0===o)return{...a,total:s,items:[],cache:uY(n)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:l,maxResults:o},requestSummary:`Changelog for ${i} from ${l}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:l,maxResults:o})},itemCount:e=>uU(uq(e).values).length});await this.linkCacheEntryToIssue(i,c.entryId);let u=uU(uq(c.value).values).map(uq).reverse().map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),createdAt:uL(e.created),items:uU(e.items).map(uq).map(e=>({field:uL(e.field)??"Field",fieldId:uL(e.fieldId),from:uL(e.fromString)??uL(e.from),to:uL(e.toString)??uL(e.to)}))}));return{...a,total:s,items:u,cache:uX([n,c])}}async ticketWorklogs(e,t=50,r=0){let i=uM(e),a=this.validatePagination(t,r),n=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Worklog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>uU(uq(e).worklogs).length});await this.linkCacheEntryToIssue(i,n.entryId);let s=uF(uq(n.value).total)??0,o=Math.min(a.limit,Math.max(0,s-a.offset)),l=Math.max(0,s-a.offset-o);if(0===o)return{...a,total:s,items:[],cache:uY(n)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:l,maxResults:o},requestSummary:`Worklogs for ${i} from ${l}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:l,maxResults:o})},itemCount:e=>uU(uq(e).worklogs).length});await this.linkCacheEntryToIssue(i,c.entryId);let u=await this.requireCredentials(),p=uU(uq(c.value).worklogs).map(uq).reverse().map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),comment:uP(e.comment??null,u.siteUrl),timeSpent:uL(e.timeSpent),timeSpentSeconds:uF(e.timeSpentSeconds),startedAt:uL(e.started),createdAt:uL(e.created),updatedAt:uL(e.updated)}));return{...a,total:s,items:p,cache:uX([n,c])}}async addComment(e,t){let r=uM(e);if(!t.value.trim())throw Error("Comment text is required");let i=uA(t);return this.mutateTicket(r,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:r,comment:i})})}async assignTicket(e,t){let r=uM(e),i=t?.trim()||null;return this.mutateTicket(r,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:r,accountId:i})})}async transitionTicket(e,t){let r=uM(e),i=(await this.ticketTransitions(r)).find(e=>e.id===t);if(!i)throw Error("The Jira transition is not available");if(i.requiredFields.length>0)throw Error(`This transition requires fields that must be completed in Jira: ${i.requiredFields.join(", ")}`);return this.mutateTicket(r,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:r,transition:{id:i.id}})})}async updateTicket(e){let t=uM(e.issueKey),r=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},a=e=>{let t=r.get(e);if(!t)throw Error(`${e} is not editable on this ticket`);return t},n=t=>Object.prototype.hasOwnProperty.call(e,t);if(n("summary")){a("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=a("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=uA(e.description))}if(n("priorityId")){let t=a("priority"),r=e.priorityId?.trim()||null;if(!r&&t.required)throw Error("Priority is required");if(r&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===r))throw Error("The selected priority is not available");i.priority=r?{id:r}:null}n("labels")&&(a("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let s=(t,r)=>{if(!n(t))return;let s=a(r),o=[...new Set(e[t]??[])];if(s.allowedValues.length>0&&o.some(e=>!s.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${s.name} value is not available`);i[r]=o.map(e=>({id:e}))};if(s("componentIds","components"),s("fixVersionIds","fixVersions"),s("affectedVersionIds","versions"),n("dueDate")){let t=a("duedate"),r=e.dueDate?.trim()||null;if(r&&!/^\d{4}-\d{2}-\d{2}$/.test(r))throw Error("Due date must use YYYY-MM-DD");if(!r&&t.required)throw Error("Due date is required");i.duedate=r}if(0===Object.keys(i).length)throw Error("At least one editable Jira field is required");return this.mutateTicket(t,"EDIT_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.editIssue({issueIdOrKey:t,fields:i})})}async branchTicket(e){let t=uM(e),r=t.replace(/-\d+$/,""),i=await (0,h.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{key:!0,branchNamingScript:!0}});if(!a)throw Error(`Jira project ${r} is not managed; add it in Manage Jira projects and sources`);let n=await this.cachedCall({operation:"ISSUE_BRANCH",params:{issueKey:t,fields:["summary","issuetype","project"]},requestSummary:`Branch details for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:t,fields:["summary","issuetype","project"],updateHistory:!1})}});await this.linkCacheEntryToIssue(t,n.entryId);let s=uq(n.value.fields);if((uL(uq(s.project).key)??uZ(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:uL(s.summary)??t,ticketType:uL(uq(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??nI}}async clearCache(){let e=await (0,h.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(uM(e)),!0}async invalidateIssueCaches(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e){let t=await (0,h.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0)}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,h.getPrismaClient)(),[a,n,s]=await Promise.all([i.jiraCachedTicket.findMany({take:r.limit,skip:r.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...r,total:n,items:a.map(e=>this.cachedTicketView(e,s.cacheTtlSeconds))}}async cachedTicket(e){let t=await (0,h.getPrismaClient)(),[r,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return r?{...this.cachedTicketView(r,i.cacheTtlSeconds),summaryData:uB(r.summaryJson),detailData:uB(r.detailJson),commentsData:uB(r.commentsJson),cacheEntries:r.cacheEntries.map(e=>({id:e.cacheEntry.id,operation:e.cacheEntry.operation,fetchedAt:e.cacheEntry.fetchedAt.toISOString()})).sort((e,t)=>t.fetchedAt.localeCompare(e.fetchedAt))}:null}async listApiCalls(e=50,t=0){let r=this.validatePagination(e,t);await this.pruneLogs();let i=await (0,h.getPrismaClient)(),[a,n]=await Promise.all([i.jiraApiCallLog.findMany({take:r.limit,skip:r.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...r,total:n,items:a.map(e=>({id:e.id,operation:e.operation,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,itemCount:e.itemCount,servedStale:e.servedStale,createdAt:e.createdAt.toISOString()}))}}async cacheMetrics(){await this.pruneLogs();let e=await (0,h.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-uj.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:uj.map(e=>this.metricWindow(e.window,r.filter(r=>r.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(r.map(e=>e.operation))].sort().map(e=>({operation:e,windows:uj.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,h.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:uD}});if(!t?.siteUrl||!t.email||!t.apiToken)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:t.apiToken,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,d.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let r={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new nv(r),agile:new iU(r)},this.clients}async currentAccountId(){let e=uL(uq((await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}})).value).accountId);if(!e)throw Error("Jira did not return the current user ID");return e}async linkCacheEntryToIssue(e,t){let r=await (0,h.getPrismaClient)();await r.$transaction(async r=>{await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,r){let i=await this.requireCredentials(),a=Date.now();try{await r(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-a})}catch(n){let r=uH(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:uG(n),error:r}),Error(r)}await this.invalidateIssueCaches(e);try{return await this.ticket(e,!0)}catch(e){throw Error(`Jira accepted the update, but refreshed ticket details could not be loaded: ${uH(e,i.apiToken)}`)}}cacheKey(e,t,r){return(0,d.createHash)("sha256").update(uK({siteUrl:e,operation:t,params:r})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),r=await (0,h.getPrismaClient)(),i=this.cacheKey(t.siteUrl,e.operation,e.params),a=Date.now(),n=await r.jiraCacheEntry.findUnique({where:{cacheKey:i}}),s=null!==n&&Date.now()-n.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&s)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-a,itemCount:e.itemCount?.(uB(n.responseJson))??null,sourceId:e.sourceId}),{value:uB(n.responseJson),source:"CACHE",stale:!1,fetchedAt:n.fetchedAt,entryId:n.id};let o=this.inFlight.get(i);if(o){let t=await o;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-a,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let l=(async()=>{try{let t=await e.fetcher(),n=new Date,s=await r.jiraCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,d.randomUUID)(),cacheKey:i,operation:e.operation,paramsJson:uK(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:uK(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-a,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:n,entryId:s.id}}catch(i){let r=null!==n&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-a,statusCode:uG(i),error:uH(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:uB(n.responseJson),source:"ERROR",stale:!0,fetchedAt:n.fetchedAt,entryId:n.id};throw Error(uH(i,t.apiToken))}})();this.inFlight.set(i,l);try{return await l}finally{this.inFlight.delete(i)}}async logCall(e){let t=await (0,h.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,d.randomUUID)(),operation:e.operation,requestSummary:e.requestSummary.slice(0,1e3),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error??null,itemCount:e.itemCount??null,servedStale:e.servedStale??!1,sourceId:e.sourceId??null}})}validateSourceName(e){let t=e.trim();if(!t||t.length>100)throw Error("Source name must be 1 to 100 characters");return t}async validateSource(e,t){let r=t.trim();if(!r)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:r},requestSummary:`Validate JQL: ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:r,maxResults:1,fields:["key"],failFast:!0})}}),{value:r,boardId:null};let i=function(e,t){let r=new URL(e.trim());if(r.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=r.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),a=r.searchParams.get("rapidView"),n=Number(i?.[1]??a);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:r.toString()}}(r,(await this.requireCredentials()).siteUrl);return await this.cachedCall({operation:"BOARD",params:{boardId:i.boardId},requestSummary:`Board ${i.boardId}`,fetcher:async()=>{let{agile:e}=await this.getClients();return e.board.getBoard({boardId:i.boardId})}}),{value:i.normalizedUrl,boardId:i.boardId}}async loadJqlSource(e,t){let r,i=[],a=[],n=[],s=!1;do{let o=Math.min(100,1e3-i.length),l=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:r??null,maxResults:o,fields:uO},requestSummary:`JQL ${e.name}${r?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:r,maxResults:o,fields:uO})},itemCount:e=>e.issues?.length??0});a.push(l);let c=l.value.issues??[];i.push(...c),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,c,l.fetchedAt),r=l.value.nextPageToken,i.length>=1e3&&r&&(s=!0)}while(r&&i.length<1e3)return this.buildBoardResult(i,a,n,s)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let r=await this.cachedCall({operation:"BOARD",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getBoard({boardId:e.boardId})}}),i=await this.cachedCall({operation:"BOARD_CONFIGURATION",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId} configuration`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getConfiguration({boardId:e.boardId})}}),a=[r,i],n=[],s=[],o=!1;if("scrum"===(uL(r.value.type)??"").toLowerCase()){let r=await this.cachedCall({operation:"SPRINTS",params:{boardId:e.boardId,state:"active"},requestSummary:`Active sprints for board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getAllSprints({boardId:e.boardId,state:"active",startAt:0,maxResults:100})},itemCount:e=>uU(e.values).length});a.push(r);let i=uU(r.value.values).map(uq);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=uF(r.id);if(!i||n.length>=1e3)continue;let l=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:uO}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...l.issues),a.push(...l.results),s.push(...l.warnings),o||=l.truncated}}else{let r=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,r)=>({boardId:e.boardId,startAt:t,maxResults:r,fields:uO}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...r.issues),a.push(...r.results),s.push(...r.warnings),o=r.truncated}let l=[...new Map(n.map(e=>[e.key??e.id,e])).values()],c=new Map;return uU(uq(i.value.columnConfig).columns).map(uq).forEach((e,t)=>{uU(e.statuses).map(uq).forEach(e=>{let r=uL(e.id);r&&c.set(r,t)})}),this.buildBoardResult(l,a,s,o,c)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],c=0,u=1/0,d=!1;for(;c<u&&s.length+n<1e3;){let d=i(c,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${c}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let m=p.value.issues??[];if(s.push(...m),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,m,p.fetchedAt),u=p.value.total??s.length,0===m.length)break;c+=m.length}return s.length+n>=1e3&&c<u&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(u0),s=[...new Map(n.map(e=>[e.status,e])).values()];return s.sort((e,t)=>{let r=a?.get(e.statusId),i=a?.get(t.statusId);return void 0!==r||void 0!==i?(r??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):u1(e.statusCategory)-u1(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:uX(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,h.getPrismaClient)();await i.$transaction(async i=>{for(let e of t)e.key&&await i.jiraCachedTicket.upsert({where:{issueKey:e.key},create:{issueKey:e.key,projectKey:uZ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:uZ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let a=[...new Set(t.map(e=>e.key).filter(Boolean))];a.length>0&&await i.jiraCacheEntryIssue.createMany({data:a.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,r){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await (0,h.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:uZ(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:uZ(t),detailJson:JSON.stringify(t),detailFetchedAt:r}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,r,i){let a=await (0,h.getPrismaClient)();await a.$transaction(async a=>{for(let n of(await a.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:r},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:r}}),i))await a.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,r,i,a){let n=u0(e),s=uq(e.fields),o=uq(e.names),l=uq(e.schema),c=[];for(let e of uU(s.issuelinks).map(uq)){let t=uq(e.type),r=uW(e.outwardIssue,uL(t.outward)??"relates to"),i=uW(e.inwardIssue,uL(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let u=uW(s.parent,"parent"),p=uU(s.subtasks).map(e=>uW(e,"subtask")).filter(e=>null!==e),m=uU(s.sprint).concat(uU(s.closedSprints)).map(uq).map(e=>uL(e.name)).filter(e=>!!e),h=t.map(uq).map(e=>({id:uL(e.id)??(0,d.randomUUID)(),author:uV(e.author),body:e.body??null,content:uP(e.body??null,r),createdAt:uL(e.created),updatedAt:uL(e.updated)}));return{...n,jiraUrl:`${r}/browse/${n.key}`,description:s.description??null,descriptionContent:uP(s.description??null,r),reporter:uV(s.reporter),creator:uV(s.creator),labels:uU(s.labels).filter(e=>"string"==typeof e),components:uJ(s.components),fixVersions:uJ(s.fixVersions),affectedVersions:uJ(s.versions),sprintNames:[...new Set(m)],parent:u,subtasks:p,issueLinks:c,attachments:uU(s.attachment).map(uq).map(e=>({id:uL(e.id)??(0,d.randomUUID)(),filename:uL(e.filename)??"Attachment",contentUrl:uL(e.content),mimeType:uL(e.mimeType),size:uF(e.size),author:uV(e.author),createdAt:uL(e.created)})),comments:h,createdAt:uL(s.created),dueAt:uL(s.duedate),resolvedAt:uL(s.resolutiondate),timeTracking:s.timetracking??null,allFields:Object.entries(s).map(([e,t])=>{let i=uq(l[e]),a="string"==typeof t||uN(t)&&"doc"===t.type?uP(t,r):null;return{id:e,name:uL(o[e])??e,schemaType:uL(i.type),custom:!0===i.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:i,commentsCache:a}}cachedTicketView(e,t){let r=u0(uq(uB(e.detailJson)??uB(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",a=[e.summaryFetchedAt,e.detailFetchedAt,e.commentsFetchedAt].filter(e=>null!==e).some(e=>Date.now()-e.getTime()>=1e3*t);return{issueKey:e.issueKey,projectKey:e.projectKey,summary:r.summary,status:"Unknown"===r.status?null:r.status,coverage:i,stale:a,summaryFetchedAt:e.summaryFetchedAt?.toISOString()??null,detailFetchedAt:e.detailFetchedAt?.toISOString()??null,commentsFetchedAt:e.commentsFetchedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}validatePagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("Pagination limit must be from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Pagination offset must be non-negative");return{limit:e,offset:t}}metricWindow(e,t){return{window:e,total:t.length,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===t.length?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length)}}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,h.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}e.s(["JiraService",0,u2],126223),e.s([],151666)},396763,504173,925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(750227),o=e.i(119909);e.i(151666);var l=e.i(468399),c=e.i(984179);let u="default",d=["QUEUED","RUNNING"],p=["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"],m=new Set([o.WORKTREE_DIFF_JOB_KIND,o.WORKTREE_DIFF_ASSET_JOB_KIND]),h=["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],f={codebase:{include:{agent:!0,repository:{include:{projects:{where:{type:"IOS_APP"},include:{configurations:{select:{id:!0}}}}}},jobs:{where:{status:{in:d}},orderBy:{createdAt:"desc"},take:1}}},tags:{include:{tag:!0}},builds:{orderBy:{createdAt:"desc"},take:1,select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,finishedAt:!0,artifacts:{select:{id:!0,kind:!0}}}},_count:{select:{builds:{where:{status:{in:["QUEUED","PREPARING","RUNNING"]}}}}}};function g(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=a.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function y(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function v(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function b(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function w(e,t){if(!t)return e;let r=b(t);if(r!==b(e))return e;let i=r?s.win32:s.posix,a=i.relative(t,e);return i.isAbsolute(a)||".."===a||a.startsWith(`..${i.sep}`)?e:a||"."}function x(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||"Worktree job failed");let t=JSON.parse(e.resultJson);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Worktree job returned an invalid result");return t}e.s(["WorktreesService",0,class{agentControl;jiraService;gitHubService;skillsService;pullRequestCache;watchDemand;constructor(e,t,r,i){this.agentControl=e,this.jiraService=t,this.gitHubService=r,this.skillsService=i,this.pullRequestCache=new Map,this.watchDemand=new Map,this.agentControl.registerCompletionHandler(o.WORKTREE_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_BRANCH_JOB_KIND,e=>this.projectBranchOperation(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_MOVE_PUSH_JOB_KIND,e=>this.advanceMoveAfterPush(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_MOVE_CHECKOUT_JOB_KIND,e=>this.advanceMoveAfterCheckout(e)),this.agentControl.registerCompletionHandler(o.WORKTREE_DELETE_JOB_KIND,e=>this.projectDeleteOperation(e))}async settings(){return(await (0,i.getPrismaClient)()).worktreeSettings.upsert({where:{id:u},create:{id:u,editorVariant:"CODE"},update:{}})}async saveSettings(e){if(!["CODE","CODE_INSIDERS","NONE"].includes(e))throw Error("Unknown editor setting");let t=await (0,i.getPrismaClient)(),r=await t.worktreeSettings.upsert({where:{id:u},create:{id:u,editorVariant:e},update:{editorVariant:e}});return this.publish(null,null),r}async requestRefresh(){let e=await (0,i.getPrismaClient)(),t=await e.codebase.findMany({select:{agentId:!0}});return this.agentControl.requestCodebaseReconcile(t.map(e=>e.agentId))}invalidatePullRequestsForOrigin(e){let t=e.toLowerCase();for(let e of this.pullRequestCache.keys())e.toLowerCase()===t&&this.pullRequestCache.delete(e)}async cleanupExpired(){let e=await (0,i.getPrismaClient)();await e.worktree.deleteMany({where:{missingAt:{lt:new Date(Date.now()-6048e5)}}})}view(e,t=""){let r=e.codebase.repository.jiraBranchRegex??t;return{...e,relativePath:w(e.folder,e.codebase.agent.baseRepoDirectory),tags:e.tags.map(e=>e.tag),activeJob:e.codebase.jobs.find(t=>t.worktreeId===e.id)??e.codebase.jobs[0]??null,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null,ticketKey:function(e,t){if(!e||!t)return null;try{let r=RegExp(t,"i").exec(e),i=(r?.[1]??r?.[0])?.trim();return i?i.toUpperCase():null}catch{return null}}(e.branch,String(r)),ticketTitle:null,ticketStatus:null,pullRequest:null,latestBuild:e.builds?.[0]?{...e.builds[0],outOfDate:(0,c.buildOutOfDate)({...e.builds[0],worktree:e})}:null}}async overview(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),[t,r,a,n,s,o]=await Promise.all([e.worktree.findMany({where:{missingAt:null},include:f,orderBy:[{codebase:{agent:{name:"asc"}}},{codebase:{repository:{name:"asc"}}},{primary:"desc"},{branch:"asc"},{folder:"asc"}]}),e.worktreeTag.findMany({orderBy:{name:"asc"}}),this.settings(),e.codebaseSettings.findUnique({where:{id:"default"}}),e.worktree.count({where:{missingAt:{not:null}}}),e.worktreeMove.findMany({where:{status:{in:p}},orderBy:{createdAt:"asc"}})]),l=n?.defaultJiraBranchRegex??"",c=t.map(e=>this.view(e,l)),u=[...new Set(c.map(e=>e.codebase.repository.canonicalOrigin))],d=new Map;await Promise.all(u.map(async e=>{let t=this.pullRequestCache.get(e);if(t&&t.expiresAt>Date.now())return void d.set(e,t.items);try{let t=await this.gitHubService.pullRequestsForOrigin(e);this.pullRequestCache.set(e,{items:t,expiresAt:Date.now()+6e4}),d.set(e,t)}catch{d.set(e,[])}}));let m=[...new Set(c.map(e=>e.ticketKey).filter(Boolean))],h=new Map;for(let e of(await Promise.all(m.map(async e=>{try{let t=await this.jiraService.cachedTicket(e)??await this.jiraService.ticket(e);h.set(e,{title:t.summary,status:t.status})}catch{}})),c))e.ticketTitle=e.ticketKey?h.get(e.ticketKey)?.title??null:null,e.ticketStatus=e.ticketKey?h.get(e.ticketKey)?.status??null:null,e.pullRequest=d.get(e.codebase.repository.canonicalOrigin)?.find(t=>t.headRefName===e.branch)??null;let g=new Map;for(let e of c){let t=e.codebase.agent,r=g.get(t.id);r||(r={agent:t,codebases:[],codebaseMap:new Map},g.set(t.id,r));let i=r.codebaseMap.get(e.codebase.id);i||(i={codebase:e.codebase,repository:e.codebase.repository,worktrees:[],iosBuildConfigured:e.codebase.repository.projects?.some(e=>e.configurations.length>0)??!1},r.codebaseMap.set(e.codebase.id,i),r.codebases.push(i)),i.worktrees.push(e)}return{agents:[...g.values()].map(e=>({agent:e.agent,codebases:e.codebases})),tags:r,settings:a,hiddenCount:s,activeMoves:o}}async hidden(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),t=await e.codebaseSettings.findUnique({where:{id:"default"}});return(await e.worktree.findMany({where:{missingAt:{not:null}},include:f,orderBy:{missingAt:"desc"}})).map(e=>this.view(e,t?.defaultJiraBranchRegex??""))}async report(e,r){let a=await (0,i.getPrismaClient)(),n=[],s=!1;for(let i of r.slice(0,100)){let r=(0,o.parseCodebaseWorktreeReport)(i),l=await a.codebase.findUnique({where:{id:r.codebaseId}});if(!l||l.agentId!==e)throw Error("Codebase not found for this agent");let c=r.worktrees.slice(0,1e3).map(e=>(0,o.parseWorktreeInventoryItem)(e)),u=await a.worktree.findMany({where:{codebaseId:l.id},select:{gitDirectory:!0,folder:!0,missingAt:!0}}),d=new Map(u.map(e=>[e.gitDirectory,e])),p=new Set(c.map(e=>e.gitDirectory));s||=c.some(e=>{let t=d.get(e.gitDirectory);return!t||t.folder!==e.folder||null!==t.missingAt})||r.complete&&u.some(e=>null===e.missingAt&&!p.has(e.gitDirectory)),await a.$transaction(async e=>{await e.codebase.update({where:{id:l.id},data:{defaultBranch:r.defaultBranch,localBranchesJson:JSON.stringify(r.localBranches),remoteBranchesJson:JSON.stringify(r.remoteBranches),...r.fetchedAt?{lastFetchedAt:new Date(r.fetchedAt)}:{},...r.fetchAttemptedAt?{lastFetchAttemptAt:new Date(r.fetchAttemptedAt),lastFetchError:r.fetchError}:r.fetchError?{lastFetchError:r.fetchError}:{}}});let i=[];for(let r of c){i.push(r.gitDirectory);let a=await e.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:l.id,gitDirectory:r.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:l.id,gitDirectory:r.gitDirectory,...this.inventoryData(r)},update:{}});await e.worktree.updateMany({where:{id:a.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.checkedAt)}}]},data:{...this.inventoryData(r),missingAt:null}}),n.push(a.id)}r.complete&&await e.worktree.updateMany({where:{codebaseId:l.id,missingAt:null,...i.length?{gitDirectory:{notIn:i}}:{}},data:{missingAt:new Date}})}),this.publish(null,l.id)}return await this.cleanupExpired(),s&&await this.skillsService?.requestAutoReconcile(),a.worktree.findMany({where:{id:{in:n}},include:f})}async reportActivity(e,t){let r=(0,o.parseWorktreeActivityReport)(t),a=await (0,i.getPrismaClient)(),s=await a.worktree.findFirst({where:{codebaseId:r.codebaseId,gitDirectory:r.gitDirectory,missingAt:null,codebase:{agentId:e}},select:{id:!0,codebaseId:!0}});if(!s)throw Error("Worktree activity source was not found");let l=void 0!==r.branch||void 0!==r.headSha||void 0!==r.upstream||void 0!==r.ahead||void 0!==r.behind||void 0!==r.syncState||void 0!==r.baseAhead||void 0!==r.baseBehind,c=!0;(l||void 0!==r.hasStagedChanges||void 0!==r.hasUnstagedChanges||void 0!==r.codeStateHash||void 0!==r.pushStatus)&&(c=(await a.worktree.updateMany({where:{id:s.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.observedAt)}}]},data:{...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},lastCheckedAt:new Date(r.observedAt),...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.codeStateHash?{}:{codeStateHash:r.codeStateHash},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus}}})).count>0)&&this.publish(s.id,s.codebaseId);let u={worktreeId:s.id,...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus},observedAt:r.observedAt};return this.watchDemand.has(s.id)&&c&&n.agentEventBus.publish((0,n.worktreeInspectionTopic)(s.id),{worktreeInspectionChanged:u}),u}inventoryData(e){return{folder:e.folder,relativePath:e.relativePath,primary:e.primary,branch:e.branch,headSha:e.headSha,codeStateHash:e.codeStateHash??null,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,baseAhead:e.baseAhead,baseBehind:e.baseBehind,hasStagedChanges:e.hasStagedChanges??!1,hasUnstagedChanges:e.hasUnstagedChanges??!1,pushStatus:e.pushStatus??"UNKNOWN",availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt)}}async updateBaseBranch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.findUnique({where:{id:e},include:{codebase:!0}});if(!a||a.missingAt)throw Error("Worktree not found");let n=t?.trim()||null;if(n&&!v(a.codebase.remoteBranchesJson).includes(n))throw Error("The selected origin branch is unavailable; fetch and try again");let s=await r.worktree.update({where:{id:e},data:{baseBranchOverride:n},include:f});return this.publish(e,a.codebaseId),await this.restartWatch(e),this.view(s)}requireColor(e){if(null===e||""===e)return null;if(!h.includes(e))throw Error("Unknown worktree color");return e}async updateHighlight(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.update({where:{id:e},data:{highlightColor:this.requireColor(t)},include:f});return this.publish(e,a.codebaseId),this.view(a)}async setTags(e,t){let r=await (0,i.getPrismaClient)(),a=[...new Set(t)].slice(0,100);if(await r.worktreeTag.count({where:{id:{in:a}}})!==a.length)throw Error("One or more tags were not found");await r.$transaction([r.worktreeTagAssignment.deleteMany({where:{worktreeId:e}}),...a.length?[r.worktreeTagAssignment.createMany({data:a.map(t=>({worktreeId:e,tagId:t}))})]:[]]);let n=await r.worktree.findUniqueOrThrow({where:{id:e},include:f});return this.publish(e,n.codebaseId),this.view(n)}async saveTag(e){let r=e.name.trim();if(!r||r.length>40)throw Error("Tag names must contain 1–40 characters");let a=this.requireColor(e.color),n=await (0,i.getPrismaClient)(),s=(await n.worktreeTag.findMany()).find(e=>e.name.toLocaleLowerCase()===r.toLocaleLowerCase());if(s&&s.id!==e.id)throw Error("Tag names must be unique");let o=e.id?await n.worktreeTag.update({where:{id:e.id},data:{name:r,color:a}}):await n.worktreeTag.create({data:{id:(0,t.randomUUID)(),name:r,color:a}});return this.publish(null,null),o}async deleteTag(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeTag.deleteMany({where:{id:e}});return r.count&&this.publish(null,null),r.count>0}async repositoryTakenBranches(e){let t=await (0,i.getPrismaClient)();return new Set((await t.codebase.findMany({where:{repositoryId:e},select:{localBranchesJson:!0,remoteBranchesJson:!0,worktrees:{where:{missingAt:null},select:{branch:!0}}}})).flatMap(e=>[...v(e.localBranchesJson),...v(e.remoteBranchesJson),...e.worktrees.flatMap(e=>e.branch?[e.branch]:[])]))}requireBaseBranch(e,t){let r=t.trim();if(!r||!v(e.remoteBranchesJson).includes(r))throw Error("The selected origin base branch is unavailable; fetch and try again");return r}async ticketBranch(e,t,r){let i=t?.trim()??"",a=await this.jiraService.branchTicket(i),n=await (0,l.jiraBranchCandidates)(a.branchNamingScript,{ticketKey:a.ticketKey,type:a.ticketType??"",title:a.ticketTitle}),s=await this.repositoryTakenBranches(e.repositoryId),o=n.filter(e=>e===r||!s.has(e));if(!o.length)throw Error("Every generated ticket branch name is already taken");return{ticket:a,candidates:o}}async previewTicketBranch(e){let t=await (0,i.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e.codebaseId},include:{agent:!0,repository:!0}});if(!r)throw Error("Codebase not found");let a=null;if(e.worktreeId){let r=await t.worktree.findFirst({where:{id:e.worktreeId,codebaseId:e.codebaseId,missingAt:null},select:{branch:!0}});if(!r)throw Error("Worktree not found for this codebase");a=r.branch}let{ticket:n,candidates:s}=await this.ticketBranch(r,e.ticketKey,a);return{ticketKey:n.ticketKey,ticketTitle:n.ticketTitle,ticketType:n.ticketType,projectKey:n.projectKey,branchName:s[0]}}async resolveBranchSelection(e,t,r){let a=this.requireBaseBranch(e,t.baseBranch);if("TICKET"===t.mode){let{candidates:i}=await this.ticketBranch(e,t.ticketKey,r?.branch??null);return{baseBranch:a,mode:"NEW",candidates:i}}let n=t.branchName?.trim()??"";if(!(0,o.validGitBranchName)(n))throw Error("Enter a valid Git branch name");if("NEW"===t.mode){if((await this.repositoryTakenBranches(e.repositoryId)).has(n))throw Error(`Branch ${n} is already taken`);return{baseBranch:a,mode:"NEW",candidates:[n]}}if("EXISTING"!==t.mode)throw Error("Unknown worktree branch mode");if(!new Set([...v(e.localBranchesJson),...v(e.remoteBranchesJson)]).has(n))throw Error(`Existing branch ${n} is unavailable; refresh and try again`);let s=await (0,i.getPrismaClient)();if(await s.worktree.findFirst({where:{codebaseId:e.id,branch:n,missingAt:null,...r?{id:{not:r.id}}:{}},select:{id:!0}}))throw Error(`Branch ${n} is checked out in another worktree`);return{baseBranch:a,mode:"EXISTING",candidates:[n]}}async createWorktree(e){let t=await this.requireRunnableCodebase(e.codebaseId),r=await this.resolveBranchSelection(t,e.selection,null);return this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:o.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.id,rootFolder:t.folder,folder:null,gitDirectory:null,expectedOrigin:t.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CREATE",mode:r.mode,candidates:r.candidates,stashOnFailure:!1},idempotencyKey:`worktree:branch:create:${e.requestId}:${t.id}`,timeoutSeconds:600})}async changeWorktreeBranch(e){let t=await this.requireRunnable(e.worktreeId,o.WORKTREE_BRANCH_JOB_KIND),r=await this.resolveBranchSelection(t.codebase,e.selection,{id:t.id,branch:t.branch});return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CHANGE",mode:r.mode,candidates:r.candidates,stashOnFailure:!!e.stashOnFailure},idempotencyKey:`worktree:branch:change:${e.requestId}:${t.id}`,timeoutSeconds:600})}async getMove(e){return(await (0,i.getPrismaClient)()).worktreeMove.findUnique({where:{id:e}})}async moveWorktree(e){let r,a=await (0,i.getPrismaClient)(),n=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(n)return n;let s=await this.requireRunnable(e.sourceWorktreeId,o.WORKTREE_MOVE_PUSH_JOB_KIND);if(!s.branch||!s.headSha)throw Error("A named source branch is required");if(s.hasStagedChanges||s.hasUnstagedChanges||"READY"!==s.pushStatus)throw Error("The source branch must be clean and safely pushable before moving");if(e.deleteSource&&s.primary)throw Error("The primary worktree cannot be deleted after moving");if(e.deleteSource&&!y(s.codebase.agent).includes(o.WORKTREE_DELETE_JOB_KIND))throw Error("Source agent must be updated to remove the old worktree");let l=await this.requireRunnableCodebase(e.targetCodebaseId,o.WORKTREE_MOVE_CHECKOUT_JOB_KIND);if(s.codebase.repositoryId!==l.repositoryId||s.codebase.agentId===l.agentId)throw Error("The destination must be the same repository on another agent");let c=e.targetWorktreeId?await a.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:l.id,missingAt:null,availability:"AVAILABLE"}}):null;if(e.targetWorktreeId&&!c)throw Error("Destination worktree not found");if(await a.worktree.findFirst({where:{codebaseId:l.id,branch:s.branch,missingAt:null,...c?{id:{not:c.id}}:{}},select:{id:!0}}))throw Error("The source branch is already checked out in another destination worktree");let u=l.defaultBranch??s.codebase.defaultBranch;if(!u)throw Error("The destination default branch is unavailable");let d=(0,t.randomUUID)();try{r=await a.worktreeMove.create({data:{id:d,requestId:e.requestId,sourceWorktreeId:s.id,sourceCodebaseId:s.codebaseId,targetCodebaseId:l.id,targetWorktreeId:c?.id??null,destinationMode:c?"EXISTING":"NEW",branch:s.branch,headSha:s.headSha,baseBranch:u,deleteSource:e.deleteSource,status:"PUSHING"}})}catch(r){let t=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(t)return t;throw r}try{let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:o.WORKTREE_MOVE_PUSH_JOB_KIND,payload:{moveId:r.id,codebaseId:s.codebaseId,folder:s.folder,gitDirectory:s.gitDirectory,expectedOrigin:s.codebase.repository.canonicalOrigin,branch:s.branch,expectedHeadSha:s.headSha},idempotencyKey:`worktree:move:push:${r.id}`,timeoutSeconds:600});return r=await a.worktreeMove.update({where:{id:r.id},data:{sourceJobId:e.id}}),this.publish(s.id,s.codebaseId),r}catch(e){throw await a.worktreeMove.update({where:{id:r.id},data:{status:"FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}}async retryWorktreeMoveWithStash(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("This move is not waiting for a stash decision");let a=await this.createMoveCheckoutJob(r,!0);if(1!==(await t.worktreeMove.updateMany({where:{id:e,status:"AWAITING_STASH"},data:{status:"CHECKING_OUT",targetJobId:a.id,error:null}})).count){let r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}});if("AWAITING_STASH"!==r.status)return r;throw Error("The move state changed; refresh and try again")}return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),t.worktreeMove.findUniqueOrThrow({where:{id:e}})}async cancelWorktreeMove(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("Only a move waiting for a stash decision can be cancelled");let a=await t.worktreeMove.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date}});return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),a}async deleteWorktree(e){let t=await this.requireRunnable(e.worktreeId,o.WORKTREE_DELETE_JOB_KIND);if(t.primary)throw Error("The primary worktree cannot be deleted");if(e.deleteRemoteBranch&&(!t.branch||t.branch===t.codebase.defaultBranch))throw Error("The default remote branch cannot be deleted");return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.WORKTREE_DELETE_JOB_KIND,payload:{moveId:null,codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,branch:t.branch,defaultBranch:t.codebase.defaultBranch,deleteRemoteBranch:e.deleteRemoteBranch,requireClean:!1,expectedHeadSha:null},idempotencyKey:`worktree:delete:${e.requestId}:${t.id}`,timeoutSeconds:600})}async inspect(e,t){let r=await this.requireRunnable(e,o.WORKTREE_INSPECT_JOB_KIND),a=await this.createSerializedDiffJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:o.WORKTREE_INSPECT_JOB_KIND,payload:this.payload(r),idempotencyKey:`worktree:inspect:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id),t=x(e).detail;if(!t||"object"!=typeof t)throw Error("Invalid worktree detail");let r=Array.isArray(t.changes)?t.changes.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?{...e,changeType:"string"==typeof e.changeType?e.changeType:"MODIFIED"}:e):[];return{...t,changes:r,branchChanges:Array.isArray(t.branchChanges)?t.branchChanges:[],branchChangesTruncated:!0===t.branchChangesTruncated}}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async inspectDiff(e,t,r){let a=await this.requireRunnable(e,o.WORKTREE_DIFF_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedDiffJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DIFF_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path??null,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:null,side:null},idempotencyKey:`worktree:diff:${r}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(s.id),t=x(e).diff;if(!t||"object"!=typeof t)throw Error("Invalid worktree diff result");return t}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async prepareDiffAsset(e,t,r){let a=await this.requireRunnable(e,o.WORKTREE_DIFF_ASSET_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedDiffJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DIFF_ASSET_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:r,side:t.side},idempotencyKey:`worktree:diff-asset:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"});try{x(await this.waitForJob(s.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async diffAssetAgentId(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}});return r?.codebase.agentId??null}async runOperation(e,t,r){if(!o.WORKTREE_OPERATIONS.includes(t))throw Error("Unknown worktree operation");let i=await this.requireRunnable(e,o.WORKTREE_OPERATION_JOB_KIND),a=await this.settings();return this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:o.WORKTREE_OPERATION_JOB_KIND,payload:{...this.payload(i),operation:t,..."OPEN_EDITOR"===t?{editorVariant:a.editorVariant}:{}},idempotencyKey:`worktree:operation:${r}:${e}`,timeoutSeconds:"OPEN_EDITOR"===t?30:600})}payload(e){return{codebaseId:e.codebaseId,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async createSerializedDiffJob(e){let t=await (0,i.getPrismaClient)(),r=Date.now()+3e4;for(;Date.now()<r;){let i=await t.agentJob.findFirst({where:{codebaseId:e.codebaseId,status:{in:d}},select:{id:!0,idempotencyKey:!0,kind:!0}});if(i){if(i.idempotencyKey===e.idempotencyKey)return this.agentControl.createJob(e);if(!m.has(i.kind))throw Error("Another operation is active for this codebase");await this.waitForSerializedDiffJob(i.id,r);continue}try{return await this.agentControl.createJob(e)}catch(e){if(!function(e){if(!e||"object"!=typeof e||"P2002"!==e.code)return!1;let t=e.meta?.target;return Array.isArray(t)?t.includes("codebaseId"):"string"==typeof t&&t.includes("codebaseId")}(e))throw e}}throw Error("Another diff request is still active for this codebase")}async waitForSerializedDiffJob(e,t){let r=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e));try{for(;Date.now()<t;){let i=await this.agentControl.getJob(e);if(!i||!d.includes(i.status))return;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(0,t-Date.now())))])}throw Error("Another diff request is still active for this codebase")}finally{await r.return?.()}}async requireRunnable(e,t,r=!1){let a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!n||n.missingAt||"AVAILABLE"!==n.availability)throw Error("Worktree is unavailable");if(!g(n.codebase.agent))throw Error("Agent is offline");if(!y(n.codebase.agent).includes(t))throw Error("Agent must be updated to use worktrees");if(!r){let[e,t]=await Promise.all([a.agentJob.findFirst({where:{codebaseId:n.codebaseId,status:{in:d}}}),a.worktreeMove.findFirst({where:{status:{in:p},OR:[{sourceCodebaseId:n.codebaseId},{targetCodebaseId:n.codebaseId}]}})]);if(e||t)throw Error("Another operation is active for this codebase")}return n}async requireRunnableCodebase(e,t=o.WORKTREE_BRANCH_JOB_KIND){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0}});if(!a||"AVAILABLE"!==a.availability)throw Error("Codebase is unavailable");if(!g(a.agent))throw Error("Agent is offline");if(!y(a.agent).includes(t))throw Error("Agent must be updated to create or change worktrees");let[n,s]=await Promise.all([r.agentJob.findFirst({where:{codebaseId:e,status:{in:d}}}),r.worktreeMove.findFirst({where:{status:{in:p},OR:[{sourceCodebaseId:e},{targetCodebaseId:e}]}})]);if(n||s)throw Error("Another operation is active for this codebase");return a}async purge(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.deleteMany({where:{id:e,missingAt:{not:null}}});return r.count&&this.publish(e,null),r.count>0}async purgeAll(){let e=await (0,i.getPrismaClient)(),t=await e.worktree.deleteMany({where:{missingAt:{not:null}}});return t.count&&this.publish(null,null),t.count}subscribe(){return n.agentEventBus.iterate(n.WORKTREE_CHANGED_TOPIC)}async *subscribeInspection(e){let t=n.agentEventBus.iterate((0,n.worktreeInspectionTopic)(e)),r=!1;try{for await(let i of(await this.acquireWatch(e),r=!0,t))yield i}finally{await t.return?.(),r&&await this.releaseWatch(e)}}async acquireWatch(e){let r=this.watchDemand.get(e);if(r){r.subscribers+=1,await r.started;return}let i=await this.requireRunnable(e,o.WORKTREE_WATCH_JOB_KIND,!0),a=(0,t.randomUUID)(),n=this.payload(i),s={subscribers:1,watchId:a,agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:n,started:Promise.resolve()};s.started=this.runWatchAction(s,"START"),this.watchDemand.set(e,s);try{await s.started}catch(t){throw this.watchDemand.get(e)===s&&this.watchDemand.delete(e),t}}async releaseWatch(e){let t=this.watchDemand.get(e);if(t&&(t.subscribers-=1,!(t.subscribers>0))){this.watchDemand.delete(e);try{await t.started,await this.runWatchAction(t,"STOP")}catch(e){console.error("Could not stop worktree watcher:",e instanceof Error?e.message:e)}}}async runWatchAction(e,t){let r=await this.agentControl.createJob({agentId:e.agentId,worktreeId:e.worktreeId,kind:o.WORKTREE_WATCH_JOB_KIND,payload:{...e.payload,action:t,watchId:e.watchId},idempotencyKey:`worktree:watch:${t}:${e.watchId}`,timeoutSeconds:30,visibility:"SYSTEM"});try{x(await this.waitForJob(r.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async restartWatch(e){let r=this.watchDemand.get(e);if(r)try{if(await r.started,this.watchDemand.get(e)!==r||(await this.runWatchAction(r,"STOP"),this.watchDemand.get(e)!==r))return;let i=await this.requireRunnable(e,o.WORKTREE_WATCH_JOB_KIND,!0),a={subscribers:r.subscribers,watchId:(0,t.randomUUID)(),agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:this.payload(i),started:Promise.resolve()};a.started=this.runWatchAction(a,"START"),this.watchDemand.set(e,a),await a.started}catch(e){console.error("Could not restart worktree watcher:",e instanceof Error?e.message:e)}}publish(e,t){n.agentEventBus.publish(n.WORKTREE_CHANGED_TOPIC,{worktreeOverviewChanged:{worktreeId:e,codebaseId:t}})}moveIdFromJob(e){let t=JSON.parse(e.payloadJson);if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.moveId)throw Error("Move job is missing its workflow identifier");return String(t.moveId)}async failMove(e,t,r){let a=await (0,i.getPrismaClient)();(await a.worktreeMove.updateMany({where:{id:e,status:t},data:{status:"FAILED",error:r,finishedAt:new Date}})).count&&this.publish(null,null)}async createMoveCheckoutJob(e,t){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e.targetCodebaseId},include:{agent:!0,repository:!0}});if(!a)throw Error("Destination codebase no longer exists");if(!g(a.agent))throw Error("Destination agent is offline");if(!y(a.agent).includes(o.WORKTREE_MOVE_CHECKOUT_JOB_KIND))throw Error("Destination agent must be updated to move worktrees");let n=e.targetWorktreeId?await r.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:a.id,missingAt:null,availability:"AVAILABLE"}}):null;if("EXISTING"===e.destinationMode&&!n)throw Error("Destination worktree is no longer available");return this.agentControl.createJob({agentId:a.agentId,codebaseId:a.id,worktreeId:n?.id??null,kind:o.WORKTREE_MOVE_CHECKOUT_JOB_KIND,payload:{moveId:e.id,codebaseId:a.id,rootFolder:a.folder,folder:n?.folder??null,gitDirectory:n?.gitDirectory??null,expectedOrigin:a.repository.canonicalOrigin,branch:e.branch,expectedHeadSha:e.headSha,baseBranch:e.baseBranch,mode:e.destinationMode,stashOnFailure:t},idempotencyKey:`worktree:move:checkout:${e.id}:${t?"stash":"initial"}`,timeoutSeconds:600})}async advanceMoveAfterPush(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||"PUSHING"!==a.status||a.sourceJobId&&a.sourceJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,"PUSHING",e.error||"Could not push the source branch");let n=x(e);if(n.headSha!==a.headSha||n.branch!==a.branch)return void await this.failMove(a.id,"PUSHING","The source push returned an unexpected branch");try{let e=await this.createMoveCheckoutJob(a,!1);await r.worktreeMove.updateMany({where:{id:a.id,status:"PUSHING"},data:{status:"CHECKING_OUT",targetJobId:e.id}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId)}catch(e){await this.failMove(a.id,"PUSHING",e instanceof Error?e.message:String(e))}}async projectMoveDestination(e,r){let a=(0,o.parseWorktreeInventoryItem)(r),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.targetCodebaseId},select:{localBranchesJson:!0}});if(!s)throw Error("Destination codebase no longer exists");let l=new Set(v(s.localBranchesJson));a.branch&&l.add(a.branch);let c=e.targetWorktreeId;return await n.$transaction(async r=>{if(await r.codebase.update({where:{id:e.targetCodebaseId},data:{localBranchesJson:JSON.stringify([...l].sort((e,t)=>e.localeCompare(t)))}}),c){if(1!==(await r.worktree.updateMany({where:{id:c,codebaseId:e.targetCodebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:e.baseBranch,missingAt:null}})).count)throw Error("Destination worktree no longer exists")}else c=(await r.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:e.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:e.baseBranch,missingAt:null}})).id;await r.worktreeMove.update({where:{id:e.id},data:{targetWorktreeId:c}})}),this.publish(c??null,e.targetCodebaseId),await this.skillsService?.requestAutoReconcile(),c}async scheduleMoveCleanup(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}}),a=await t.worktree.findUnique({where:{id:r.sourceWorktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||a.primary){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:"Destination is ready, but the source worktree could not be removed",finishedAt:new Date}}),this.publish(r.sourceWorktreeId,r.sourceCodebaseId);return}try{let e=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:o.WORKTREE_DELETE_JOB_KIND,payload:{moveId:r.id,codebaseId:a.codebaseId,rootFolder:a.codebase.folder,folder:a.folder,gitDirectory:a.gitDirectory,expectedOrigin:a.codebase.repository.canonicalOrigin,branch:a.branch,defaultBranch:a.codebase.defaultBranch,deleteRemoteBranch:!1,requireClean:!0,expectedHeadSha:r.headSha},idempotencyKey:`worktree:move:cleanup:${r.id}`,timeoutSeconds:600});await t.worktreeMove.updateMany({where:{id:r.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"CLEANING_UP",cleanupJobId:e.id}}),this.publish(a.id,a.codebaseId)}catch(e){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e instanceof Error?e.message:String(e),finishedAt:new Date}}),this.publish(a.id,a.codebaseId)}}async advanceMoveAfterCheckout(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||!["PUSHING","CHECKING_OUT","AWAITING_STASH"].includes(a.status)||a.targetJobId&&a.targetJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,a.status,e.error||"Could not check out the destination branch");let n=x(e);if("NEEDS_STASH"===n.outcome){await r.worktreeMove.updateMany({where:{id:a.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"AWAITING_STASH",error:"string"==typeof n.message?n.message:"Destination changes block the branch switch"}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId);return}"CHECKED_OUT"===n.outcome&&n.worktree?(await this.projectMoveDestination(a,n.worktree),a.deleteSource?await this.scheduleMoveCleanup(a.id):(await r.worktreeMove.update({where:{id:a.id},data:{status:"SUCCEEDED",error:null,finishedAt:new Date}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId))):await this.failMove(a.id,a.status,"Destination checkout returned an invalid result")}async projectDeleteOperation(e){let t=JSON.parse(e.payloadJson),r=t&&"object"==typeof t&&!Array.isArray(t)&&"string"==typeof t.moveId?String(t.moveId):null,a=await (0,i.getPrismaClient)();if(r){let t=await a.worktreeMove.findUnique({where:{id:r}});if(!t||!["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"].includes(t.status)||t.cleanupJobId&&t.cleanupJobId!==e.id)return;if("SUCCEEDED"!==e.status){await a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e.error||"Destination is ready, but the source worktree was retained",finishedAt:new Date}}),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}await a.$transaction([a.worktree.deleteMany({where:{id:t.sourceWorktreeId}}),a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED",finishedAt:new Date}})]),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}if("SUCCEEDED"!==e.status||!e.worktreeId)return;let n=await a.worktree.findUnique({where:{id:e.worktreeId},select:{codebaseId:!0}});await a.worktree.deleteMany({where:{id:e.worktreeId}}),this.publish(e.worktreeId,n?.codebaseId??null)}async projectOperation(e){if(!e.worktreeId||"SUCCEEDED"!==e.status||!e.resultJson)return;let t=x({...e,error:null});if(!t.worktree)return;let r=(0,o.parseWorktreeInventoryItem)(t.worktree),a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e.worktreeId}});if(!n)return;let s=new Date(r.checkedAt);(await a.worktree.updateMany({where:{id:n.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:s}}]},data:{branch:r.branch,headSha:r.headSha,upstream:r.upstream,ahead:r.ahead,behind:r.behind,syncState:r.syncState,baseAhead:r.baseAhead,baseBehind:r.baseBehind,hasStagedChanges:r.hasStagedChanges??!1,hasUnstagedChanges:r.hasUnstagedChanges??!1,pushStatus:r.pushStatus??"UNKNOWN",availability:r.availability,statusError:r.error,lastCheckedAt:s}})).count>0&&this.publish(n.id,n.codebaseId)}async projectBranchOperation(e){if(!e.codebaseId||"SUCCEEDED"!==e.status||!e.resultJson)return;let r=x({...e,error:null});if(!r.worktree||"string"!=typeof r.baseBranch)return;let a=(0,o.parseWorktreeInventoryItem)(r.worktree),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.codebaseId},select:{localBranchesJson:!0}});if(!s)return;let l=new Set(v(s.localBranchesJson));a.branch&&l.add(a.branch);let c=e.worktreeId;await n.$transaction(async i=>{if(await i.codebase.update({where:{id:e.codebaseId},data:{localBranchesJson:JSON.stringify([...l].sort((e,t)=>e.localeCompare(t)))}}),e.worktreeId){if(1!==(await i.worktree.updateMany({where:{id:e.worktreeId,codebaseId:e.codebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:r.baseBranch,missingAt:null}})).count)throw Error("Worktree no longer exists");return}c=(await i.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.codebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.codebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:r.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:r.baseBranch,missingAt:null}})).id}),this.publish(c??null,e.codebaseId),await this.skillsService?.requestAutoReconcile(),e.worktreeId&&await this.restartWatch(e.worktreeId)}async waitForJob(e){let t=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e)),r=Date.now()+3e4;try{for(;Date.now()<r;){let i=await this.agentControl.getJob(e);if(!i)throw Error("Worktree job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(i.status))return i;await Promise.race([t.next(),new Promise(e=>setTimeout(e,r-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}},"worktreeDisplayPath",0,w],504173);let k=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),_={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function $(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=a.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function I(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function S(e){return null===e?null:JSON.parse(e)}function E(e){return(0,r.buildDataTargetsPayload)(S(e.payloadJson)).targets.map(e=>e.path)}function T(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function C(e,t,r){try{for(let i of E(t)){let a=e.get(R(t.agentId,i));a&&(a.error=r)}}catch{}}function R(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_DELETE_JOB_KIND),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:$(e)?I(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,r,a){let n=[...new Set(t)];if(!n.length)throw Error("Select at least one Derived Data entry");let s=new Map(e.entries.map(e=>[e.id,e])),o=n.map(e=>{let t=s.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t}),l=new Map;for(let e of o){let t=l.get(e.agent.id)??[];t.push(e),l.set(e.agent.id,t)}let c=await (0,i.getPrismaClient)(),u=[];for(let[e,t]of l){let r=t[0].agent,i=await c.agent.findUnique({where:{id:e}});if(!i||!$(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!I(i).includes(a))throw Error(`${r.name} must be updated before this operation can run`);u.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of u)await this.agentControlService.createJob({agentId:t,kind:a,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${a}:${e.id}:${r}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"})}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:_})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(S(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>k.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),s=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let e of s){let t=o.get(e.codebase.agentId)??[];t.push(e),o.set(e.codebase.agentId,t)}let l=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(S(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(o.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=R(t.agentId,r.path);l.set(a,{id:a,name:r.name,status:"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?w(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(S(i.resultJson)).sizes){let t=l.get(R(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){C(l,i,T(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(S(i.resultJson)).deleted){let r=R(i.agentId,e.path),a=l.get(r);a&&(e.deleted&&!t?l.delete(r):a.error=e.error)}}catch(e){C(l,i,T(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of E(i)){let t=l.get(R(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&k.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of E(i)){let t=l.get(R(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}return[...l.values()].sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||e.name.localeCompare(t.name))}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.buildDataCollectionId||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(S(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=T(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=await this.loadCollection(e.buildDataCollectionId);if(!s)return;let o=new Map((await this.entries(s,!0)).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e]));try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=o.get(i.path);if(!a)continue;let n=a.worktreeId?(await r.worktree.findUnique({where:{id:a.worktreeId},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:a.agent.id,agentName:a.agent.name,folderName:a.name,worktreeId:n,worktreePath:a.worktreePath,source:"USER",jobId:e.id,targetKey:a.id}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}],925991),e.s([],396763)},224174,669602,190714,e=>{"use strict";var t=e.i(666680),r=e.i(750227),i=e.i(807055),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983),o=e.i(971619);let l=new Set(["smartphone","hammer","play","test-tube","archive","rocket"]),c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),u=["QUEUED","PREPARING","RUNNING"];function d(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function p(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function m(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function h(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=n.AGENT_ONLINE_WINDOW_MS&&null===e.disconnectedAt}function f(e){return m(d(e.capabilitiesJson,[]))}function g(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function y(e){return`${e.type}:${e.id}`}function v(e){if(e.codebaseId)return e.codebaseId;let t=d(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function b(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let w={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:u}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"}},exports:{orderBy:{createdAt:"desc"}}};e.s(["BuildsService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(i.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e))}publish(e){s.agentEventBus.publish((0,s.buildTopic)(e),{buildChanged:{id:e}}),s.agentEventBus.publish(s.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}})}async requireWorktree(e,t){let r=await (0,a.getPrismaClient)(),i=await r.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt||"AVAILABLE"!==i.availability)throw Error("Worktree is unavailable");if(!h(i.codebase.agent))throw Error("Agent is offline");if(!f(i.codebase.agent).includes(t))throw Error("Agent must be updated to use iOS builds");return i}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let r=await (0,a.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!i)throw Error("Codebase not found");return r.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:i.repositoryId,type:"IOS_APP"}},create:{id:(0,t.randomUUID)(),repositoryId:i.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,a.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),n=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:n}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let r=await this.ensureProject(e.codebaseId),n=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),s=g(e.name,"Configuration name"),o=g(e.scheme,"Scheme",256),c=g(e.buildConfiguration,"Xcode configuration",256);if(!i.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let u=e.iconKey?.trim()||null;if(u&&!l.has(u))throw Error("Icon is invalid");let d=(0,i.parseBuildAdvancedSettings)(e.advancedSettings??i.DEFAULT_BUILD_ADVANCED_SETTINGS),p=await (0,a.getPrismaClient)(),m=e.id?await p.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!m||m.projectId!==r.id))throw Error("Build configuration not found");let h=await p.buildSource.upsert({where:{projectId_relativePath:{projectId:r.id,relativePath:n.relativePath}},create:{id:(0,t.randomUUID)(),projectId:r.id,kind:n.kind,relativePath:n.relativePath},update:{kind:n.kind}}),f=m?.id??(0,t.randomUUID)();return p.buildConfiguration.upsert({where:{id:f},create:{id:f,projectId:r.id,sourceId:h.id,name:s,iconKey:u,scheme:o,buildConfiguration:c,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d)},update:{sourceId:h.id,name:s,iconKey:u,scheme:o,buildConfiguration:c,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d)},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,a.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:u}}}))throw Error("Configuration has an active build");return 1===(await t.buildConfiguration.deleteMany({where:{id:e}})).count}async scripts(){return(await (0,a.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let r=g(e.name,"Script name"),n=e.preBuildScript?.trim()||null,s=e.postBuildScript?.trim()||null;if(!n&&!s)throw Error("A pre-build or post-build script is required");let o=e.timeoutSeconds??300;if(!Number.isInteger(o)||o<1||o>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!i.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,a.getPrismaClient)(),c=e.id??(0,t.randomUUID)();return l.buildScript.upsert({where:{id:c},create:{id:c,name:r,preBuildScript:n,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior},update:{name:r,preBuildScript:n,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,a.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,a.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let n=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:n},deletedAt:null}})).length!==n.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),n.length&&await e.codebaseRepositoryBuildScript.createMany({data:n.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=s.agentEventBus.iterate((0,s.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(c.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return p(d(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,i.IOS_SOURCE_DISCOVER_JOB_KIND),n=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:i.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,a.getPrismaClient)();await e.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async reparse(e,r,n){let s=await this.requireWorktree(r,i.IOS_SOURCE_PARSE_JOB_KIND),o=await (0,a.getPrismaClient)(),l=await o.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==s.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let c=`worktree:${s.id}`,u=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}}}),d=new Date;await o.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},create:{id:(0,t.randomUUID)(),sourceId:l.sourceId,scopeKey:c,codebaseId:s.codebaseId,worktreeId:s.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let p=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(s),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${n}:${l.id}:${s.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(p.id)),t=m(e.schemes),r=m(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(m(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:s.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:c}},data:{status:"ERROR",error:e,stale:!!u?.lastParsedAt}})}finally{await o.agentJob.deleteMany({where:{id:p.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_SOURCE_PARSE_JOB_KIND),r=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),n=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return{source:r,schemes:m(e.schemes),configurations:m(e.configurations),testPlans:m(e.testPlans),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,a.getPrismaClient)();await e.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_DESTINATIONS_JOB_KIND),r=await (0,a.getPrismaClient)(),n=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!n||n.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let s=e.action??n.defaultAction;if(!i.BUILD_ACTIONS.includes(s))throw Error("Build action is invalid");let o=function(e){if(!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(e))return[];let t={type:"PHYSICAL_DEVICE",id:"generic-ios",name:"Any Physical iOS Device",platform:"iOS",osVersion:null,state:null,generic:!0};return"ARCHIVE"===e?[t]:[{type:"SIMULATOR",id:"generic-ios-simulator",name:"Any iOS Simulator",platform:"iOS Simulator",osVersion:null,state:null,generic:!0},t]}(s);if("ARCHIVE"===s)return o;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:n.source.kind,relativePath:n.source.relativePath},scheme:n.scheme,configuration:n.buildConfiguration,action:s},idempotencyKey:`ios:destinations:${e.requestId}:${n.id}:${t.id}:${s}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return Array.isArray(e.destinations)?e.destinations:[]}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let t=await (0,a.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0}}),n=r?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!r||"SUCCEEDED"!==r.status||!r.worktreeId)throw Error("A successful archive build is required");if(!n)throw Error("Build does not contain an archive");let s=await this.requireWorktree(r.worktreeId,i.IOS_SIGNING_INSPECT_JOB_KIND),o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:r.id,codebaseId:s.codebaseId,artifactDirectory:r.artifactDirectory,archiveRelativePath:n.relativePath},idempotencyKey:`ios:signing:${r.id}:${n.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await t.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async destinationsForBuild(e,t){let r=await (0,a.getPrismaClient)(),n=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!n||"SUCCEEDED"!==n.status||!n.worktreeId||!n.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=await this.requireWorktree(n.worktreeId,i.IOS_RUN_DESTINATIONS_JOB_KIND);if(n.agentId!==s.codebase.agentId||n.codebaseId!==s.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(s),destinationType:n.destinationType},idempotencyKey:`ios:build-destinations:${g(t,"Request ID",200)}:${n.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,i.parseBuildDestination)(e)).filter(e=>e.type===n.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async startBuild(e){let n=g(e.requestId,"Request ID",200),s=`${e.worktreeId}:${n}`,l=await (0,a.getPrismaClient)(),c=await l.build.findUnique({where:{requestKey:s},include:w});if(c)return c;let u=await this.requireWorktree(e.worktreeId,i.IOS_BUILD_JOB_KIND);if(e.worktreeCoverage&&!f(u.codebase.agent).includes(i.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let m=await l.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!m||m.source.project.repositoryId!==u.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let h=await l.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:m.sourceId,scopeKey:`worktree:${u.id}`}}}),y=e.action??m.defaultAction;if(!i.BUILD_ACTIONS.includes(y))throw Error("Build action is invalid");let v=(0,i.parseBuildDestination)(e.destination);if(!i.BUILD_DESTINATION_TYPES.includes(v.type))throw Error("Destination is invalid");if("ARCHIVE"===y&&("PHYSICAL_DEVICE"!==v.type||!v.generic))throw Error("Archive builds require the generic physical iOS destination");if(v.generic&&!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(y))throw Error("This build action requires a concrete destination");let b=p(d(m.advancedSettingsJson,{}),"saved advanced settings"),x=e.advancedSettings?p(e.advancedSettings,"advanced settings override"):{},k=(0,i.parseBuildAdvancedSettings)({...b,...x,buildSettingOverrides:{...p(b.buildSettingOverrides??{},"saved overrides"),...p(x.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===y){if(!k.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await l.build.findUnique({where:{id:k.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==u.codebase.agentId||e.worktreeId!==u.id||e.configurationId!==m.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==v.type)throw Error("The prior Build for Testing result uses a different destination type");let t=p(d(e.snapshotJson,{}),"prior Build for Testing snapshot"),a=p(t.configuration??{},"prior Build for Testing configuration snapshot"),n=(0,i.parseBuildAdvancedSettings)(a.advancedSettings??{});if(k.testPlan&&n.testPlan&&k.testPlan!==n.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let s=k.testPlan??n.testPlan??null,o=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),c=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(o.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let h=o[0];if(h||1!==c.length||(h=c[0]),!h&&c.length>1&&s&&(h=c.find(e=>p(d(e.metadataJson,{}),"test-run artifact metadata").testPlan===s||e.relativePath.endsWith(`/${s}.xctestrun`)||e.relativePath===`${s}.xctestrun`)),!h&&c.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let f=h?.relativePath??"test-products.xctestproducts",g=(0,r.resolve)(e.artifactDirectory),y=(0,r.resolve)(g,f),b=(0,r.relative)(g,y);if(!b||b.startsWith("..")||(0,r.isAbsolute)(b))throw Error("The prior Build for Testing artifact path is invalid");k={...k,testPlan:s,priorTestProductsPath:f.endsWith(".xctestproducts")?y:null,priorXctestrunPath:f.endsWith(".xctestrun")?y:null}}let _=await l.codebaseRepositoryBuildScript.findMany({where:{repositoryId:u.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),$=new Set(e.scriptIds??[]);if([...$].some(e=>!_.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let I=_.filter(e=>$.has(e.scriptId)),S=(0,t.randomUUID)(),E=(0,o.effectiveBuildsDirectory)(u.codebase.agent);if(!E)throw Error("The agent builds directory is unavailable");let T=(0,r.join)(E,S),C={kind:m.source.kind,relativePath:m.source.relativePath},R=function(e){var t;let i=e.advancedSettings,a="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...a?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,r.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!a&&("RESOLVED_ONLY"===i.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===i.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===i.packageResolution&&n.push("-disableAutomaticPackageResolution"),i.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==i.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===i.signingStyle?"Automatic":"Manual"}`),i.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${i.developmentTeam}`),i.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${i.codeSignIdentity}`),i.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${i.provisioningProfileSpecifier}`),i.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${i.productBundleIdentifier}`),i.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),i.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),i.testPlan&&n.push("-testPlan",i.testPlan),i.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==i.parallelTesting&&n.push("-parallel-testing-enabled",i.parallelTesting?"YES":"NO"),null!==i.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(i.parallelTestingWorkers)),i.onlyTesting))n.push(`-only-testing:${e}`);for(let e of i.skipTesting)n.push(`-skip-testing:${e}`);if(!a)for(let[e,t]of Object.entries(i.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,r.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,r.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&i.priorTestProductsPath&&n.push("-testProductsPath",i.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!i.priorTestProductsPath&&i.priorXctestrunPath&&n.push("-xctestrun",i.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:u.folder,source:C,scheme:m.scheme,configuration:m.buildConfiguration,destination:v,action:y,advancedSettings:k,artifactDirectory:T}),P=I.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),A={repository:{id:u.codebase.repository.id,name:u.codebase.repository.name,canonicalOrigin:u.codebase.repository.canonicalOrigin},codebase:{id:u.codebase.id,folder:u.codebase.folder},worktree:{id:u.id,folder:u.folder,branch:u.branch,headSha:u.headSha,codeStateHash:u.codeStateHash,hasStagedChanges:u.hasStagedChanges,hasUnstagedChanges:u.hasUnstagedChanges},agent:{id:u.codebase.agent.id,name:u.codebase.agent.name,hostname:u.codebase.agent.hostname},configuration:{id:m.id,name:m.name,iconKey:m.iconKey,source:C,scheme:m.scheme,buildConfiguration:m.buildConfiguration,action:y,advancedSettings:k,parse:h?{status:h.status,schemes:d(h.schemesJson,[]),configurations:d(h.configurationsJson,[]),testPlans:d(h.testPlansJson,[]),headSha:h.headSha,xcodeVersion:h.xcodeVersion,parsedAt:h.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:v,scripts:P,worktreeCoverage:!0===e.worktreeCoverage};await l.build.create({data:{id:S,requestKey:s,requestId:n,agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,configurationId:m.id,status:"QUEUED",action:y,destinationType:v.type,destinationJson:JSON.stringify(v),snapshotJson:JSON.stringify(A),commandSummary:R,artifactDirectory:T,scriptExecutions:{create:P.flatMap(e=>[...e.preBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});try{let t=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:i.IOS_BUILD_JOB_KIND,payload:{...this.identity(u),buildId:S,artifactDirectory:T,source:C,scheme:m.scheme,configuration:m.buildConfiguration,action:y,destination:v,advancedSettings:k,scripts:P,worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${n}:${u.id}`,timeoutSeconds:604800});await l.build.update({where:{id:S},data:{jobId:t.id}})}catch(e){throw await l.build.update({where:{id:S},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(S),l.build.findUniqueOrThrow({where:{id:S},include:w})}async rebuildBuild(e,t){let r=await (0,a.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!i)throw Error("Build not found");let n=p(d(i.snapshotJson,{}),"build snapshot"),s=p(n.worktree??{},"build worktree snapshot"),o=p(n.configuration??{},"build configuration snapshot"),l=Array.isArray(n.scripts)?n.scripts:[],c=i.worktreeId??("string"==typeof s.id?s.id:null),u=i.configurationId??("string"==typeof o.id?o.id:null);if(!c||!u)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:u,destination:d(i.destinationJson,{}),scriptIds:l.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:i.action,advancedSettings:o.advancedSettings,requestId:t})}async startWorktreeCoverage(e){let t=await (0,a.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=p(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async generateReport(e,r,n){let s=await (0,a.getPrismaClient)(),o=await s.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:r}},include:{artifact:!0}});if(o?.status==="READY")return o;let l=await s.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(u.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!h(l.agent))throw Error("Build agent is offline");let c="TEST_RESULTS"===r?i.IOS_TEST_RESULTS_JOB_KIND:i.IOS_COVERAGE_REPORT_JOB_KIND;if(!f(l.agent).includes(c))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===r&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let d=await s.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:r}},create:{id:(0,t.randomUUID)(),buildId:e,kind:r,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let p=v(l),m=await this.agentControl.createJob({agentId:l.agentId,codebaseId:p,worktreeId:l.worktreeId,kind:c,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:p,reportKind:r,source:"MANUAL"},idempotencyKey:`ios:report:${r}:${g(n,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(m.id,17e4),s.buildReport.findUniqueOrThrow({where:{id:d.id},include:{artifact:!0}})}finally{await s.agentJob.deleteMany({where:{id:m.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,a.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:u}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,a.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,a.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,a.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:w});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,a.getPrismaClient)()).build.findUnique({where:{id:e},include:w})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let n=await (0,a.getPrismaClient)(),s=await n.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:u}},select:{id:!0}},exports:{where:{status:{in:u}},select:{id:!0}}}});if(s.some(e=>u.includes(e.status)))throw Error("Running builds cannot be deleted");if(s.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of s){if(!(0,r.isAbsolute)(e.artifactDirectory)||(0,r.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=v(e);if(!e.agent||!f(e.agent).includes(i.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:i.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let o=await n.build.deleteMany({where:{id:{in:s.map(e=>e.id)}}});for(let e of s)this.publish(e.id);return o.count}async artifactForInstall(e,t){let r=await (0,a.getPrismaClient)(),i=await r.buildArtifact.findFirst({where:{id:t,buildId:e}});return i?{id:i.id,kind:i.kind,relativePath:i.relativePath,sizeBytes:i.sizeBytes,checksum:i.checksum,createdAt:i.createdAt.toISOString(),metadata:p(d(i.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,t,r,n=17e4){let s=await (0,a.getPrismaClient)(),o=await s.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!o)throw Error("Build artifact not found");let{build:l}=o;if(!l.agentId||!l.agent)throw Error("The build agent is no longer available");if(!h(l.agent))throw Error("Build agent is offline");if(!f(l.agent).includes(i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let c=v(l),u=await this.agentControl.createJob({agentId:l.agentId,codebaseId:c,worktreeId:l.worktreeId,kind:i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:l.id,artifactDirectory:l.artifactDirectory,artifactRelativePath:o.relativePath,uploadId:r,codebaseId:c},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:Math.ceil(n/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(u.id,n))}finally{await s.agentJob.deleteMany({where:{id:u.id,visibility:"SYSTEM"}})}}async logs(e,t=null,r=1e3){let i=await (0,a.getPrismaClient)(),n=t?await i.buildLogEvent.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0}}):null;if(t&&!n)throw Error("Build log cursor not found");return i.buildLogEvent.findMany({where:{buildId:e,...n?{OR:[{createdAt:{gt:n.createdAt}},{createdAt:n.createdAt,id:{gt:n.id}}]}:{}},orderBy:[{createdAt:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,a.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return u.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,a.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!u.includes(i.status))return i;let n=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),n}async appendLogs(e,r,i){let n=await (0,a.getPrismaClient)(),o=await n.build.findUnique({where:{id:r}});if(!o||o.agentId!==e)throw Error("Build not found for agent");let l=i.slice(0,200).map(e=>({id:(0,t.randomUUID)(),buildId:r,scope:g(e.scope,"Log scope",40),scopeId:g(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:g(e.phase,"Log phase",80),level:g(e.level,"Log level",20),stream:g(e.stream,"Log stream",20),message:e.message.replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]").slice(0,64e3),createdAt:new Date(e.createdAt)}));for(let e of l){if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(Number.isNaN(e.createdAt.valueOf()))throw Error("Log date is invalid");await n.buildLogEvent.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}}),s.agentEventBus.publish((0,s.buildLogTopic)(r),{buildLogAdded:e})}return l}async runBuild(e){let r=await (0,a.getPrismaClient)(),n=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!n||"SUCCEEDED"!==n.status||!n.worktree)throw Error("A successful build is required");let s=n.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!s)throw Error("Build does not contain a runnable app");let o=g(String(p(d(s.metadataJson,{}),"runnable metadata").bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(i.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==n.destinationType))throw Error("Run destinations must match the build destination type");let c=await this.destinationsForBuild(n.id,`${g(e.requestId,"Request ID",200)}:preflight`),u=l.map(e=>c.find(t=>t.type===e.type&&t.id===e.id));if(u.some(e=>!e))throw Error("A selected run destination is no longer available");l=u;let m=await this.requireWorktree(n.worktree.id,i.IOS_DEPLOY_JOB_KIND),h=(0,t.randomUUID)(),f=[];for(let i of l){let a=await r.buildDeployment.findUnique({where:{buildId_requestId_destinationKey:{buildId:n.id,requestId:e.requestId,destinationKey:y(i)}}});f.push(a??await r.buildDeployment.create({data:{id:(0,t.randomUUID)(),buildId:n.id,batchId:h,requestId:e.requestId,destinationJson:JSON.stringify(i),destinationKey:y(i),commandSummary:"SIMULATOR"===i.type?`open -a Simulator --args -CurrentDeviceUDID ${i.id}; xcrun simctl install/launch ${i.id}`:`xcrun devicectl device install/process launch --device ${i.id}`}}))}let v=await this.agentControl.createJob({agentId:m.codebase.agentId,codebaseId:m.codebaseId,worktreeId:m.id,kind:i.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(m),buildId:n.id,artifactDirectory:n.artifactDirectory,artifactRelativePath:s.relativePath,bundleIdentifier:o,deployments:f.map((e,t)=>({id:e.id,destination:l[t]}))},idempotencyKey:`ios:deploy:${n.id}:${e.requestId}`,timeoutSeconds:3600});return await r.buildDeployment.updateMany({where:{id:{in:f.map(e=>e.id)}},data:{jobId:v.id}}),this.publish(n.id),r.buildDeployment.findMany({where:{id:{in:f.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let r=await (0,a.getPrismaClient)(),n=await r.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(n)return n;let s=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!s||"SUCCEEDED"!==s.status||!s.worktree)throw Error("A successful archive build is required");let o=s.artifacts.find(e=>"ARCHIVE"===e.kind);if(!o)throw Error("Build does not contain an archive");let l=(0,i.parseBuildExportSettings)(e.settings),c=await this.requireWorktree(s.worktree.id,i.IOS_EXPORT_JOB_KIND),u=(0,t.randomUUID)(),d=await r.buildExport.create({data:{id:u,buildId:s.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(o.relativePath)} -exportPath exports/${u}`}}),p=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:i.IOS_EXPORT_JOB_KIND,payload:{...this.identity(c),buildId:s.id,exportId:u,artifactDirectory:s.artifactDirectory,archiveRelativePath:o.relativePath,settings:l},idempotencyKey:`ios:export:${s.id}:${e.requestId}`,timeoutSeconds:3600}),m=await r.buildExport.update({where:{id:d.id},data:{jobId:p.id}});return this.publish(s.id),m}async upsertArtifacts(e,r,a){for(let n of(0,i.parseBuildArtifactSnapshots)(a)){let i={kind:n.kind,sizeBytes:n.sizeBytes,checksum:n.checksum,metadataJson:JSON.stringify(n.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r,relativePath:n.relativePath}},create:{id:(0,t.randomUUID)(),buildId:r,relativePath:n.relativePath,...i},update:i})}}async upsertReportProjection(e,r,i,a){let n=p(i,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?p(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:r,relativePath:o.relativePath}}}):null,c="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:s}},create:{id:(0,t.randomUUID)(),buildId:r,artifactId:l?.id??null,kind:s,source:a,status:c,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:c,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let r=await (0,a.getPrismaClient)(),i=await r.build.findFirst({where:{jobId:e.id}});if(!i)return;let n=p(d(e.resultJson,{}),"build result"),s="CANCELLED"===i.status?"CANCELLED":b(e.status),o="string"==typeof n.sourceStateHash?n.sourceStateHash:null,l="string"==typeof n.finalStateHash?n.finalStateHash:null,c="string"==typeof n.codeStateObservedAt&&Number.isFinite(Date.parse(n.codeStateObservedAt))?new Date(n.codeStateObservedAt):new Date,u=l?c:new Date,m=i.snapshotJson;if(o){let e=p(d(i.snapshotJson,{}),"build snapshot"),t=p(e.worktree??{},"build worktree snapshot");m=JSON.stringify({...e,worktree:{...t,codeStateHash:o}})}await r.$transaction(async r=>{if(await r.build.update({where:{id:i.id},data:{status:s,errorCode:"string"==typeof n.errorCode?n.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===s?"XCODEBUILD_FAILED":i.errorCode,error:e.error??("string"==typeof n.error?n.error:i.error),startedAt:i.startedAt??new Date,finishedAt:u,snapshotJson:m}}),i.worktreeId&&l&&await r.worktree.updateMany({where:{id:i.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:c}}]},data:{codeStateHash:l,lastCheckedAt:c}}),Array.isArray(n.artifacts))for(let e of n.artifacts){let a=p(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),buildId:i.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(n.scriptExecutions))for(let e of n.scriptExecutions){let t=p(e,"script execution");"string"==typeof t.phase&&"number"==typeof t.position&&await r.buildScriptExecution.updateMany({where:{buildId:i.id,phase:t.phase,position:t.position},data:{status:"string"==typeof t.status?t.status:"FAILED",exitCode:"number"==typeof t.exitCode?t.exitCode:null,durationMs:"number"==typeof t.durationMs?t.durationMs:null,causedBuildFailure:!0===t.causedBuildFailure,outputRelativePath:"string"==typeof t.outputRelativePath?t.outputRelativePath:null,error:"string"==typeof t.error?t.error:null}})}if(Array.isArray(n.reports))for(let e of n.reports){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(r,i.id,e,"CODE_COVERAGE"===t.kind?"WORKTREE":"AUTOMATIC")}}),this.publish(i.id)}async projectGeneratedReportCompletion(e){let r=p(d(e.payloadJson,{}),"build report payload");if("string"!=typeof r.buildId)return;let i=r.buildId,n=p(d(e.resultJson,{}),"build report result"),s=await (0,a.getPrismaClient)();await s.$transaction(async a=>{if(await this.upsertArtifacts(a,i,n.artifacts),n.report&&"object"==typeof n.report)await this.upsertReportProjection(a,i,n.report,"WORKTREE"===r.source?"WORKTREE":"MANUAL");else{let n="CODE_COVERAGE"===r.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await a.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:n}},create:{id:(0,t.randomUUID)(),buildId:i,kind:n,source:"WORKTREE"===r.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(i)}async projectDeploymentCompletion(e){let t=await (0,a.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=p(d(e.resultJson,{}),"deployment result"),n=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=n.map(e=>p(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:b(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let r=await (0,a.getPrismaClient)(),i=await r.buildExport.findFirst({where:{jobId:e.id}});if(!i)return;let n=p(d(e.resultJson,{}),"export result");if(await r.buildExport.update({where:{id:i.id},data:{status:b(e.status),error:e.error??("string"==typeof n.error?n.error:null),outputRelativePath:"string"==typeof n.outputRelativePath?n.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof n.outputRelativePath){let e=n.outputRelativePath;await r.$transaction(async r=>{await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.buildId,relativePath:e}},create:{id:(0,t.randomUUID)(),buildId:i.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof n.sizeBytes?n.sizeBytes:null,metadataJson:JSON.stringify({exportId:i.id})},update:{}}),await this.upsertArtifacts(r,i.buildId,n.artifacts)})}this.publish(i.buildId)}}],669602);var x=e.i(907855);let k=x.object({status:x.string().optional(),codebaseId:x.string().optional(),worktreeId:x.string().optional(),first:x.number().int().min(1).max(200).default(50),after:x.string().optional()}),_=x.object({builds:x.array(x.unknown()),nextCursor:x.string().nullable()}),$=x.object({buildId:x.string().min(1),afterLogId:x.string().min(1).nullable().default(null),logLimit:x.number().int().min(1).max(5e3).default(1e3)}),I=x.object({build:x.unknown(),logs:x.array(x.unknown())}),S=x.object({worktreeId:x.string().min(1)}),E=x.object({project:x.unknown().nullable()}),T=x.union([x.object({buildId:x.string().min(1),requestId:x.string().min(1)}),x.object({worktreeId:x.string().min(1),configurationId:x.string().min(1),action:x.string().optional(),requestId:x.string().min(1)})]),C=x.object({destinations:x.array(x.unknown())}),R=x.object({worktreeId:x.string().min(1),configurationId:x.string().min(1),destination:x.record(x.string(),x.unknown()),scriptIds:x.array(x.string()).default([]),action:x.string().optional(),advancedSettings:x.record(x.string(),x.unknown()).optional(),requestId:x.string().min(1)}),P=x.object({build:x.unknown()}),A=x.object({buildId:x.string().min(1),requestId:x.string().min(1)}),D=x.object({build:x.unknown()}),O=x.object({buildId:x.string().min(1),destinations:x.array(x.record(x.string(),x.unknown())).min(1),requestId:x.string().min(1)}),j=x.object({deployments:x.array(x.unknown())}),N=x.object({buildId:x.string().min(1),settings:x.record(x.string(),x.unknown()),requestId:x.string().min(1)}),q=x.object({export:x.unknown()});e.s(["CancelBuildToolInputSchema",0,A,"CancelBuildToolOutputSchema",0,D,"ExportBuildToolInputSchema",0,N,"ExportBuildToolOutputSchema",0,q,"GetBuildConfigurationsInputSchema",0,S,"GetBuildConfigurationsOutputSchema",0,E,"GetBuildDestinationsInputSchema",0,T,"GetBuildDestinationsOutputSchema",0,C,"GetBuildInputSchema",0,$,"GetBuildOutputSchema",0,I,"GetBuildsInputSchema",0,k,"GetBuildsOutputSchema",0,_,"RunBuildToolInputSchema",0,O,"RunBuildToolOutputSchema",0,j,"StartBuildToolInputSchema",0,R,"StartBuildToolOutputSchema",0,P],190714),e.s([],224174)},952128,187963,117958,514849,e=>{"use strict";let t;var r,i,a,n,s,o,l,c=e.i(243783);e.s(["PrismaService",0,class{async healthCheck(){try{let e=await (0,c.getPrismaClient)();return await e.$queryRawUnsafe("SELECT 1"),!0}catch(e){return console.error("Database health check failed:",e),!1}}}],187963),e.s([],952128),(r=n||(n={})).assertEqual=e=>{},r.assertIs=function(e){},r.assertNever=function(e){throw Error()},r.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},r.getValidEnumValues=e=>{let t=r.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),i={};for(let r of t)i[r]=e[r];return r.objectValues(i)},r.objectValues=e=>r.objectKeys(e).map(function(t){return e[t]}),r.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},r.find=(e,t)=>{for(let r of e)if(t(r))return r},r.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,r.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},r.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(s||(s={})).mergeShapes=(e,t)=>({...e,...t});let u=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return u.undefined;case"string":return u.string;case"number":return Number.isNaN(e)?u.nan:u.number;case"boolean":return u.boolean;case"function":return u.function;case"bigint":return u.bigint;case"symbol":return u.symbol;case"object":if(Array.isArray(e))return u.array;if(null===e)return u.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return u.promise;if("u">typeof Map&&e instanceof Map)return u.map;if("u">typeof Set&&e instanceof Set)return u.set;if("u">typeof Date&&e instanceof Date)return u.date;return u.object;default:return u.unknown}},p=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class m extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},i=e=>{for(let a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(i);else if("invalid_return_type"===a.code)i(a.returnTypeError);else if("invalid_arguments"===a.code)i(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,i=0;for(;i<a.path.length;){let r=a.path[i];i===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(this),r}static assert(e){if(!(e instanceof m))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];t[r]=t[r]||[],t[r].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}m.create=e=>new m(e);let h=(e,t)=>{let r;switch(e.code){case p.invalid_type:r=e.received===u.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case p.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case p.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};(i=o||(o={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},i.toString=e=>"string"==typeof e?e:e?.message;let f=e=>{let{data:t,path:r,errorMaps:i,issueData:a}=e,n=[...r,...a.path||[]],s={...a,path:n};if(void 0!==a.message)return{...a,path:n,message:a.message};let o="";for(let e of i.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...a,path:n,message:o}};function g(e,t){let r=f({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,h,void 0].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if("aborted"===i.status)return v;"dirty"===i.status&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,i=await e.value;r.push({key:t,value:i})}return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:t,value:a}=i;if("aborted"===t.status||"aborted"===a.status)return v;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==a.value||i.alwaysSet)&&(r[t.value]=a.value)}return{status:e.value,value:r}}}let v=Object.freeze({status:"aborted"}),b=e=>({status:"dirty",value:e}),w=e=>({status:"valid",value:e}),x=e=>"u">typeof Promise&&e instanceof Promise;class k{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let _=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new m(e.common.issues);return this._error=t,this._error}}};function $(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:a}=e;if(t&&(r||i))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:a}:{errorMap:(t,a)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??a.defaultError}:void 0===a.data?{message:n??i??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:n??r??a.defaultError}},description:a}}class I{get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(x(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parseSync({data:e,path:r.path,parent:r});return _(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parse({data:e,path:r.path,parent:r});return _(r,await (x(i)?i:Promise.resolve(i)))}refine(e,t){return this._refinement((r,i)=>{let a=e(r),n=()=>i.addIssue({code:p.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&a instanceof Promise?a.then(e=>!!e||(n(),!1)):!!a||(n(),!1)})}refinement(e,t){return this._refinement((r,i)=>!!e(r)||(i.addIssue("function"==typeof t?t(r,i):t),!1))}_refinement(e){return new ev({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ew.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return ey.create(this,this._def)}or(e){return ei.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ev({...$(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ex({...$(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:l.ZodDefault})}brand(){return new e$({typeName:l.ZodBranded,type:this,...$(this._def)})}catch(e){return new ek({...$(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:l.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eI.create(this,e)}readonly(){return eS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let S=/^c[^\s-]{8,}$/i,E=/^[0-9a-z]+$/,T=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,R=/^[a-z0-9_-]{21}$/i,P=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,O=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,j=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,N=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,F="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",M=RegExp(`^${F}$`);function B(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class z extends I{_parse(e){var r,i,a,s;let o;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.string,received:t.parsedType}),v}let l=new y;for(let c of this._def.checks)if("min"===c.kind)e.data.length<c.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),l.dirty());else if("max"===c.kind)e.data.length>c.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),l.dirty());else if("length"===c.kind){let t=e.data.length>c.value,r=e.data.length<c.value;(t||r)&&(o=this._getOrReturnCtx(e,o),t?g(o,{code:p.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}):r&&g(o,{code:p.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}),l.dirty())}else if("email"===c.kind)D.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"email",code:p.invalid_string,message:c.message}),l.dirty());else if("emoji"===c.kind)t||(t=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),t.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"emoji",code:p.invalid_string,message:c.message}),l.dirty());else if("uuid"===c.kind)C.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"uuid",code:p.invalid_string,message:c.message}),l.dirty());else if("nanoid"===c.kind)R.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"nanoid",code:p.invalid_string,message:c.message}),l.dirty());else if("cuid"===c.kind)S.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid",code:p.invalid_string,message:c.message}),l.dirty());else if("cuid2"===c.kind)E.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid2",code:p.invalid_string,message:c.message}),l.dirty());else if("ulid"===c.kind)T.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"ulid",code:p.invalid_string,message:c.message}),l.dirty());else if("url"===c.kind)try{new URL(e.data)}catch{g(o=this._getOrReturnCtx(e,o),{validation:"url",code:p.invalid_string,message:c.message}),l.dirty()}else"regex"===c.kind?(c.regex.lastIndex=0,c.regex.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"regex",code:p.invalid_string,message:c.message}),l.dirty())):"trim"===c.kind?e.data=e.data.trim():"includes"===c.kind?e.data.includes(c.value,c.position)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{includes:c.value,position:c.position},message:c.message}),l.dirty()):"toLowerCase"===c.kind?e.data=e.data.toLowerCase():"toUpperCase"===c.kind?e.data=e.data.toUpperCase():"startsWith"===c.kind?e.data.startsWith(c.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{startsWith:c.value},message:c.message}),l.dirty()):"endsWith"===c.kind?e.data.endsWith(c.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{endsWith:c.value},message:c.message}),l.dirty()):"datetime"===c.kind?(function(e){let t=`${F}T${B(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(c).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"datetime",message:c.message}),l.dirty()):"date"===c.kind?M.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"date",message:c.message}),l.dirty()):"time"===c.kind?RegExp(`^${B(c)}$`).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"time",message:c.message}),l.dirty()):"duration"===c.kind?A.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"duration",code:p.invalid_string,message:c.message}),l.dirty()):"ip"===c.kind?(r=e.data,!(("v4"===(i=c.version)||!i)&&O.test(r)||("v6"===i||!i)&&N.test(r))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"ip",code:p.invalid_string,message:c.message}),l.dirty())):"jwt"===c.kind?!function(e,t){if(!P.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(i));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)return!1;return!0}catch{return!1}}(e.data,c.alg)&&(g(o=this._getOrReturnCtx(e,o),{validation:"jwt",code:p.invalid_string,message:c.message}),l.dirty()):"cidr"===c.kind?(a=e.data,!(("v4"===(s=c.version)||!s)&&j.test(a)||("v6"===s||!s)&&q.test(a))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"cidr",code:p.invalid_string,message:c.message}),l.dirty())):"base64"===c.kind?U.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64",code:p.invalid_string,message:c.message}),l.dirty()):"base64url"===c.kind?L.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64url",code:p.invalid_string,message:c.message}),l.dirty()):n.assertNever(c);return{status:l.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:p.invalid_string,...o.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}z.create=e=>new z({checks:[],typeName:l.ZodString,coerce:e?.coerce??!1,...$(e)});class K extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==u.number){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.number,received:t.parsedType}),v}let r=new y;for(let i of this._def.checks)"int"===i.kind?n.isInteger(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"multipleOf"===i.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,a=r>i?r:i;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(e.data,i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.not_finite,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new K({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}K.create=e=>new K({checks:[],typeName:l.ZodNumber,coerce:e?.coerce||!1,...$(e)});class G extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==u.bigint)return this._getInvalidInput(e);let r=new y;for(let i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}G.create=e=>new G({checks:[],typeName:l.ZodBigInt,coerce:e?.coerce??!1,...$(e)});class H extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.boolean,received:t.parsedType}),v}return w(e.data)}}H.create=e=>new H({typeName:l.ZodBoolean,coerce:e?.coerce||!1,...$(e)});class Z extends I{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.date,received:t.parsedType}),v}if(Number.isNaN(e.data.getTime()))return g(this._getOrReturnCtx(e),{code:p.invalid_date}),v;let r=new y;for(let i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):n.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Z.create=e=>new Z({checks:[],coerce:e?.coerce||!1,typeName:l.ZodDate,...$(e)});class V extends I{_parse(e){if(this._getType(e)!==u.symbol){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.symbol,received:t.parsedType}),v}return w(e.data)}}V.create=e=>new V({typeName:l.ZodSymbol,...$(e)});class J extends I{_parse(e){if(this._getType(e)!==u.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.undefined,received:t.parsedType}),v}return w(e.data)}}J.create=e=>new J({typeName:l.ZodUndefined,...$(e)});class W extends I{_parse(e){if(this._getType(e)!==u.null){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.null,received:t.parsedType}),v}return w(e.data)}}W.create=e=>new W({typeName:l.ZodNull,...$(e)});class Q extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return w(e.data)}}Q.create=e=>new Q({typeName:l.ZodAny,...$(e)});class Y extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return w(e.data)}}Y.create=e=>new Y({typeName:l.ZodUnknown,...$(e)});class X extends I{_parse(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.never,received:t.parsedType}),v}}X.create=e=>new X({typeName:l.ZodNever,...$(e)});class ee extends I{_parse(e){if(this._getType(e)!==u.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.void,received:t.parsedType}),v}return w(e.data)}}ee.create=e=>new ee({typeName:l.ZodVoid,...$(e)});class et extends I{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==u.array)return g(t,{code:p.invalid_type,expected:u.array,received:t.parsedType}),v;if(null!==i.exactLength){let e=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(e||a)&&(g(t,{code:e?p.too_big:p.too_small,minimum:a?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(g(t,{code:p.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(g(t,{code:p.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>i.type._parseAsync(new k(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));let a=[...t.data].map((e,r)=>i.type._parseSync(new k(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new et({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new et({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new et({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...$(t)});class er extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.object,received:t.parsedType}),v}let{status:t,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof X&&"strip"===this._def.unknownKeys))for(let e in r.data)a.includes(e)||n.push(e);let s=[];for(let e of a){let t=i[e],a=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new k(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof X){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(g(r,{code:p.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let i=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new k(r,i,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,i=await t.value;e.push({key:r,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new er({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new er({...this._def,unknownKeys:"strip"})}passthrough(){return new er({...this._def,unknownKeys:"passthrough"})}extend(e){return new er({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new er({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:l.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new er({...this._def,catchall:e})}pick(e){let t={};for(let r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}omit(e){let t={};for(let r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof er){let r={};for(let i in t.shape){let a=t.shape[i];r[i]=eb.create(e(a))}return new er({...t._def,shape:()=>r})}if(t instanceof et)return new et({...t._def,type:e(t.element)});if(t instanceof eb)return eb.create(e(t.unwrap()));if(t instanceof ew)return ew.create(e(t.unwrap()));if(t instanceof eo)return eo.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of n.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new er({...this._def,shape:()=>t})}required(e){let t={};for(let r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new er({...this._def,shape:()=>t})}keyof(){return eh(n.objectKeys(this.shape))}}er.create=(e,t)=>new er({shape:()=>e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...$(t)}),er.strictCreate=(e,t)=>new er({shape:()=>e,unknownKeys:"strict",catchall:X.create(),typeName:l.ZodObject,...$(t)}),er.lazycreate=(e,t)=>new er({shape:e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...$(t)});class ei extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new m(e.ctx.common.issues));return g(t,{code:p.invalid_union,unionErrors:r}),v});{let e,i=[];for(let a of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&i.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let a=i.map(e=>new m(e));return g(t,{code:p.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}}ei.create=(e,t)=>new ei({options:e,typeName:l.ZodUnion,...$(t)});let ea=e=>{if(e instanceof ep)return ea(e.schema);if(e instanceof ev)return ea(e.innerType());if(e instanceof em)return[e.value];if(e instanceof ef)return e.options;if(e instanceof eg)return n.objectValues(e.enum);else if(e instanceof ex)return ea(e._def.innerType);else if(e instanceof J)return[void 0];else if(e instanceof W)return[null];else if(e instanceof eb)return[void 0,...ea(e.unwrap())];else if(e instanceof ew)return[null,...ea(e.unwrap())];else if(e instanceof e$)return ea(e.unwrap());else if(e instanceof eS)return ea(e.unwrap());else if(e instanceof ek)return ea(e._def.innerType);else return[]};class en extends I{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return g(t,{code:p.invalid_type,expected:u.object,received:t.parsedType}),v;let r=this.discriminator,i=t.data[r],a=this.optionsMap.get(i);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let r of t){let t=ea(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of t){if(i.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new en({typeName:l.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...$(r)})}}class es extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(e,i)=>{if("aborted"===e.status||"aborted"===i.status)return v;let a=function e(t,r){let i=d(t),a=d(r);if(t===r)return{valid:!0,data:t};if(i===u.object&&a===u.object){let i=n.objectKeys(r),a=n.objectKeys(t).filter(e=>-1!==i.indexOf(e)),s={...t,...r};for(let i of a){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1};s[i]=a.data}return{valid:!0,data:s}}if(i===u.array&&a===u.array){if(t.length!==r.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i.push(n.data)}return{valid:!0,data:i}}if(i===u.date&&a===u.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,i.value);return a.valid?(("dirty"===e.status||"dirty"===i.status)&&t.dirty(),{status:t.value,value:a.data}):(g(r,{code:p.invalid_intersection_types}),v)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>i(e,t)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:l.ZodIntersection,...$(r)});class eo extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.array)return g(r,{code:p.invalid_type,expected:u.array,received:r.parsedType}),v;if(r.data.length<this._def.items.length)return g(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((e,t)=>{let i=this._def.items[t]||this._def.rest;return i?i._parse(new k(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(i).then(e=>y.mergeArray(t,e)):y.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new eo({...this._def,rest:e})}}eo.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new eo({items:e,typeName:l.ZodTuple,rest:null,...$(t)})};class el extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.object)return g(r,{code:p.invalid_type,expected:u.object,received:r.parsedType}),v;let i=[],a=this._def.keyType,n=this._def.valueType;for(let e in r.data)i.push({key:a._parse(new k(r,e,r.path,e)),value:n._parse(new k(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?y.mergeObjectAsync(t,i):y.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return new el(t instanceof I?{keyType:e,valueType:t,typeName:l.ZodRecord,...$(r)}:{keyType:z.create(),valueType:e,typeName:l.ZodRecord,...$(t)})}}class ec extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.map)return g(r,{code:p.invalid_type,expected:u.map,received:r.parsedType}),v;let i=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:i._parse(new k(r,e,r.path,[n,"key"])),value:a._parse(new k(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let i=await r.key,a=await r.value;if("aborted"===i.status||"aborted"===a.status)return v;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let i=r.key,a=r.value;if("aborted"===i.status||"aborted"===a.status)return v;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}}}}ec.create=(e,t,r)=>new ec({valueType:t,keyType:e,typeName:l.ZodMap,...$(r)});class eu extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==u.set)return g(r,{code:p.invalid_type,expected:u.set,received:r.parsedType}),v;let i=this._def;null!==i.minSize&&r.data.size<i.minSize.value&&(g(r,{code:p.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&r.data.size>i.maxSize.value&&(g(r,{code:p.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let a=this._def.valueType;function n(e){let r=new Set;for(let i of e){if("aborted"===i.status)return v;"dirty"===i.status&&t.dirty(),r.add(i.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>a._parse(new k(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new eu({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new eu({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}eu.create=(e,t)=>new eu({valueType:e,minSize:null,maxSize:null,typeName:l.ZodSet,...$(t)});class ed extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return g(t,{code:p.invalid_type,expected:u.function,received:t.parsedType}),v;function r(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h,h].filter(e=>!!e),issueData:{code:p.invalid_arguments,argumentsError:r}})}function i(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h,h].filter(e=>!!e),issueData:{code:p.invalid_return_type,returnTypeError:r}})}let a={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof ey){let e=this;return w(async function(...t){let s=new m([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,a).catch(e=>{throw s.addIssue(i(l,e)),s})})}{let e=this;return w(function(...t){let s=e._def.args.safeParse(t,a);if(!s.success)throw new m([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,a);if(!l.success)throw new m([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ed({...this._def,args:eo.create(e).rest(Y.create())})}returns(e){return new ed({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ed({args:e||eo.create([]).rest(Y.create()),returns:t||Y.create(),typeName:l.ZodFunction,...$(r)})}}class ep extends I{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ep.create=(e,t)=>new ep({getter:e,typeName:l.ZodLazy,...$(t)});class em extends I{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}function eh(e,t){return new ef({values:e,typeName:l.ZodEnum,...$(t)})}em.create=(e,t)=>new em({value:e,typeName:l.ZodLiteral,...$(t)});class ef extends I{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{expected:n.joinValues(r),received:t.parsedType,code:p.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{received:t.data,code:p.invalid_enum_value,options:r}),v}return w(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ef.create(e,{...this._def,...t})}exclude(e,t=this._def){return ef.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ef.create=eh;class eg extends I{_parse(e){let t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==u.string&&r.parsedType!==u.number){let e=n.objectValues(t);return g(r,{expected:n.joinValues(e),received:r.parsedType,code:p.invalid_type}),v}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=n.objectValues(t);return g(r,{received:r.data,code:p.invalid_enum_value,options:e}),v}return w(e.data)}get enum(){return this._def.values}}eg.create=(e,t)=>new eg({values:e,typeName:l.ZodNativeEnum,...$(t)});class ey extends I{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==u.promise&&!1===t.common.async?(g(t,{code:p.invalid_type,expected:u.promise,received:t.parsedType}),v):w((t.parsedType===u.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ey.create=(e,t)=>new ey({type:e,typeName:l.ZodPromise,...$(t)});class ev extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{g(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return v;let i=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===i.status?v:"dirty"===i.status||"dirty"===t.value?b(i.value):i});{if("aborted"===t.value)return v;let i=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===i.status?v:"dirty"===i.status||"dirty"===t.value?b(i.value):i}}if("refinement"===i.type){let e=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?v:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===i.status?v:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}}if("transform"===i.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?v:Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return v;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}n.assertNever(i)}}ev.create=(e,t,r)=>new ev({schema:e,typeName:l.ZodEffects,effect:t,...$(r)}),ev.createWithPreprocess=(e,t,r)=>new ev({schema:t,effect:{type:"preprocess",transform:e},typeName:l.ZodEffects,...$(r)});class eb extends I{_parse(e){return this._getType(e)===u.undefined?w(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:l.ZodOptional,...$(t)});class ew extends I{_parse(e){return this._getType(e)===u.null?w(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ew.create=(e,t)=>new ew({innerType:e,typeName:l.ZodNullable,...$(t)});class ex extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===u.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ex.create=(e,t)=>new ex({innerType:e,typeName:l.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...$(t)});class ek extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return x(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:l.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...$(t)});class e_ extends I{_parse(e){if(this._getType(e)!==u.nan){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:u.nan,received:t.parsedType}),v}return{status:"valid",value:e.data}}}e_.create=e=>new e_({typeName:l.ZodNaN,...$(e)}),Symbol("zod_brand");class e$ extends I{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eI extends I{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),b(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eI({in:e,out:t,typeName:l.ZodPipeline})}}class eS extends I{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return x(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:l.ZodReadonly,...$(t)}),er.lazycreate,(a=l||(l={})).ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly",z.create,K.create,e_.create,G.create,H.create,Z.create,V.create,J.create,W.create,Q.create,Y.create,X.create,ee.create,et.create;let eE=er.create;er.strictCreate,ei.create,en.create,es.create,eo.create,el.create,ec.create,eu.create,ed.create,ep.create,em.create,ef.create,eg.create,ey.create,ev.create,eb.create,ew.create,ev.createWithPreprocess,eI.create,e.s(["ZodFirstPartyTypeKind",0,l,"object",0,eE],117958);var eT=e.i(127438),eC=e.i(639510),eR=e.i(486618),eP=e.i(862061);e.i(467662),e.i(236608);var eA=e.i(715143);let eD=eT.$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");eC.$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>eA.parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>eA.safeParse(e,t,r),e.parseAsync=async(t,r)=>eA.parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>eA.safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,r)=>eR.clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.apply=t=>t(e)}),eO=eT.$constructor("ZodMiniString",(e,t)=>{eC.$ZodString.init(e,t),eD.init(e,t)}),ej=((e,t)=>{eC.$ZodStringFormat.init(e,t),eO.init(e,t)},eT.$constructor("ZodMiniObject",(e,t)=>{eC.$ZodObject.init(e,t),eD.init(e,t),eR.defineLazy(e,"shape",()=>t.shape)}));function eN(e,t){return new ej({type:"object",shape:e??{},...eR.normalizeParams(t)})}function eq(e){return!!e._zod}function eU(e){let t=Object.values(e);if(0===t.length)return eN({});let r=t.every(eq),i=t.every(e=>!eq(e));if(r)return eN(e);if(i)return eE(e);throw Error("Mixed Zod versions detected in object shape.")}async function eL(e,t){return eq(e)?await eA.safeParseAsync(e,t):await e.safeParseAsync(t)}eP.describe,eP.meta,e.s(["getLiteralValue",0,function(e){if(eq(e)){let t=e._zod?.def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(void 0!==r)return r},"getObjectShape",0,function(e){let t;if(e&&(t=eq(e)?e._zod?.def?.shape:e.shape)){if("function"==typeof t)try{return t()}catch{return}return t}},"getParseErrorMessage",0,function(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{}}return String(e)},"getSchemaDescription",0,function(e){return e.description},"isSchemaOptional",0,function(e){return eq(e)?e._zod?.def?.type==="optional":"function"==typeof e.isOptional?e.isOptional():e._def?.typeName==="ZodOptional"},"isZ4Schema",0,eq,"normalizeObjectSchema",0,function(e){if(e){if("object"==typeof e&&!e._def&&!e._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return eU(e)}if(eq(e)){let t=e._zod?.def;if(t&&("object"===t.type||void 0!==t.shape))return e}else if(void 0!==e.shape)return e}},"objectFromShape",0,eU,"safeParse",0,function(e,t){return eq(e)?eA.safeParse(e,t):e.safeParse(t)},"safeParseAsync",0,eL],514849)},556690,e=>{"use strict";var t,r,i=e.i(907855),a=e.i(551047),a=a;let n="2025-11-25",s=[n,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],o="io.modelcontextprotocol/related-task",l=i.custom(e=>null!==e&&("object"==typeof e||"function"==typeof e)),c=i.union([i.string(),i.number().int()]),u=i.string();i.looseObject({ttl:i.number().optional(),pollInterval:i.number().optional()});let d=i.object({ttl:i.number().optional()}),p=i.object({taskId:i.string()}),m=i.looseObject({progressToken:c.optional(),[o]:p.optional()}),h=i.object({_meta:m.optional()}),f=h.extend({task:d.optional()}),g=i.object({method:i.string(),params:h.loose().optional()}),y=i.object({_meta:m.optional()}),v=i.object({method:i.string(),params:y.loose().optional()}),b=i.looseObject({_meta:m.optional()}),w=i.union([i.string(),i.number().int()]),x=i.object({jsonrpc:i.literal("2.0"),id:w,...g.shape}).strict(),k=i.object({jsonrpc:i.literal("2.0"),...v.shape}).strict(),_=i.object({jsonrpc:i.literal("2.0"),id:w,result:b}).strict();(t=r||(r={}))[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired";let $=i.object({jsonrpc:i.literal("2.0"),id:w.optional(),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()})}).strict(),I=i.union([x,k,_,$]);i.union([_,$]);let S=b.strict(),E=y.extend({requestId:w.optional(),reason:i.string().optional()}),T=v.extend({method:i.literal("notifications/cancelled"),params:E}),C=i.object({src:i.string(),mimeType:i.string().optional(),sizes:i.array(i.string()).optional(),theme:i.enum(["light","dark"]).optional()}),R=i.object({icons:i.array(C).optional()}),P=i.object({name:i.string(),title:i.string().optional()}),A=P.extend({...P.shape,...R.shape,version:i.string(),websiteUrl:i.string().optional(),description:i.string().optional()}),D=i.intersection(i.object({applyDefaults:i.boolean().optional()}),i.record(i.string(),i.unknown())),O=i.preprocess(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,i.intersection(i.object({form:D.optional(),url:l.optional()}),i.record(i.string(),i.unknown()).optional())),j=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({sampling:i.looseObject({createMessage:l.optional()}).optional(),elicitation:i.looseObject({create:l.optional()}).optional()}).optional()}),N=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({tools:i.looseObject({call:l.optional()}).optional()}).optional()}),q=i.object({experimental:i.record(i.string(),l).optional(),sampling:i.object({context:l.optional(),tools:l.optional()}).optional(),elicitation:O.optional(),roots:i.object({listChanged:i.boolean().optional()}).optional(),tasks:j.optional(),extensions:i.record(i.string(),l).optional()}),U=h.extend({protocolVersion:i.string(),capabilities:q,clientInfo:A}),L=g.extend({method:i.literal("initialize"),params:U}),F=i.object({experimental:i.record(i.string(),l).optional(),logging:l.optional(),completions:l.optional(),prompts:i.object({listChanged:i.boolean().optional()}).optional(),resources:i.object({subscribe:i.boolean().optional(),listChanged:i.boolean().optional()}).optional(),tools:i.object({listChanged:i.boolean().optional()}).optional(),tasks:N.optional(),extensions:i.record(i.string(),l).optional()}),M=b.extend({protocolVersion:i.string(),capabilities:F,serverInfo:A,instructions:i.string().optional()}),B=v.extend({method:i.literal("notifications/initialized"),params:y.optional()}),z=g.extend({method:i.literal("ping"),params:h.optional()}),K=i.object({progress:i.number(),total:i.optional(i.number()),message:i.optional(i.string())}),G=i.object({...y.shape,...K.shape,progressToken:c}),H=v.extend({method:i.literal("notifications/progress"),params:G}),Z=h.extend({cursor:u.optional()}),V=g.extend({params:Z.optional()}),J=b.extend({nextCursor:u.optional()}),W=i.enum(["working","input_required","completed","failed","cancelled"]),Q=i.object({taskId:i.string(),status:W,ttl:i.union([i.number(),i.null()]),createdAt:i.string(),lastUpdatedAt:i.string(),pollInterval:i.optional(i.number()),statusMessage:i.optional(i.string())}),Y=b.extend({task:Q}),X=y.merge(Q),ee=v.extend({method:i.literal("notifications/tasks/status"),params:X}),et=g.extend({method:i.literal("tasks/get"),params:h.extend({taskId:i.string()})}),er=b.merge(Q),ei=g.extend({method:i.literal("tasks/result"),params:h.extend({taskId:i.string()})});b.loose();let ea=V.extend({method:i.literal("tasks/list")}),en=J.extend({tasks:i.array(Q)}),es=g.extend({method:i.literal("tasks/cancel"),params:h.extend({taskId:i.string()})}),eo=b.merge(Q),el=i.object({uri:i.string(),mimeType:i.optional(i.string()),_meta:i.record(i.string(),i.unknown()).optional()}),ec=el.extend({text:i.string()}),eu=i.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=el.extend({blob:eu}),ep=i.enum(["user","assistant"]),em=i.object({audience:i.array(ep).optional(),priority:i.number().min(0).max(1).optional(),lastModified:a.datetime({offset:!0}).optional()}),eh=i.object({...P.shape,...R.shape,uri:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),size:i.optional(i.number()),annotations:em.optional(),_meta:i.optional(i.looseObject({}))}),ef=i.object({...P.shape,...R.shape,uriTemplate:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),annotations:em.optional(),_meta:i.optional(i.looseObject({}))}),eg=V.extend({method:i.literal("resources/list")}),ey=J.extend({resources:i.array(eh)}),ev=V.extend({method:i.literal("resources/templates/list")}),eb=J.extend({resourceTemplates:i.array(ef)}),ew=h.extend({uri:i.string()}),ex=g.extend({method:i.literal("resources/read"),params:ew}),ek=b.extend({contents:i.array(i.union([ec,ed]))}),e_=v.extend({method:i.literal("notifications/resources/list_changed"),params:y.optional()}),e$=g.extend({method:i.literal("resources/subscribe"),params:ew}),eI=g.extend({method:i.literal("resources/unsubscribe"),params:ew}),eS=y.extend({uri:i.string()}),eE=v.extend({method:i.literal("notifications/resources/updated"),params:eS}),eT=i.object({name:i.string(),description:i.optional(i.string()),required:i.optional(i.boolean())}),eC=i.object({...P.shape,...R.shape,description:i.optional(i.string()),arguments:i.optional(i.array(eT)),_meta:i.optional(i.looseObject({}))}),eR=V.extend({method:i.literal("prompts/list")}),eP=J.extend({prompts:i.array(eC)}),eA=h.extend({name:i.string(),arguments:i.record(i.string(),i.string()).optional()}),eD=g.extend({method:i.literal("prompts/get"),params:eA}),eO=i.object({type:i.literal("text"),text:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),ej=i.object({type:i.literal("image"),data:eu,mimeType:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eN=i.object({type:i.literal("audio"),data:eu,mimeType:i.string(),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eq=i.object({type:i.literal("tool_use"),name:i.string(),id:i.string(),input:i.record(i.string(),i.unknown()),_meta:i.record(i.string(),i.unknown()).optional()}),eU=i.object({type:i.literal("resource"),resource:i.union([ec,ed]),annotations:em.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eL=eh.extend({type:i.literal("resource_link")}),eF=i.union([eO,ej,eN,eL,eU]),eM=i.object({role:ep,content:eF}),eB=b.extend({description:i.string().optional(),messages:i.array(eM)}),ez=v.extend({method:i.literal("notifications/prompts/list_changed"),params:y.optional()}),eK=i.object({title:i.string().optional(),readOnlyHint:i.boolean().optional(),destructiveHint:i.boolean().optional(),idempotentHint:i.boolean().optional(),openWorldHint:i.boolean().optional()}),eG=i.object({taskSupport:i.enum(["required","optional","forbidden"]).optional()}),eH=i.object({...P.shape,...R.shape,description:i.string().optional(),inputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()),outputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()).optional(),annotations:eK.optional(),execution:eG.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eZ=V.extend({method:i.literal("tools/list")}),eV=J.extend({tools:i.array(eH)}),eJ=b.extend({content:i.array(eF).default([]),structuredContent:i.record(i.string(),i.unknown()).optional(),isError:i.boolean().optional()});eJ.or(b.extend({toolResult:i.unknown()}));let eW=f.extend({name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),eQ=g.extend({method:i.literal("tools/call"),params:eW}),eY=v.extend({method:i.literal("notifications/tools/list_changed"),params:y.optional()}),eX=i.object({autoRefresh:i.boolean().default(!0),debounceMs:i.number().int().nonnegative().default(300)}),e0=i.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),e1=h.extend({level:e0}),e4=g.extend({method:i.literal("logging/setLevel"),params:e1}),e3=y.extend({level:e0,logger:i.string().optional(),data:i.unknown()}),e2=v.extend({method:i.literal("notifications/message"),params:e3}),e6=i.object({name:i.string().optional()}),e9=i.object({hints:i.array(e6).optional(),costPriority:i.number().min(0).max(1).optional(),speedPriority:i.number().min(0).max(1).optional(),intelligencePriority:i.number().min(0).max(1).optional()}),e8=i.object({mode:i.enum(["auto","required","none"]).optional()}),e5=i.object({type:i.literal("tool_result"),toolUseId:i.string().describe("The unique identifier for the corresponding tool call."),content:i.array(eF).default([]),structuredContent:i.object({}).loose().optional(),isError:i.boolean().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e7=i.discriminatedUnion("type",[eO,ej,eN]),te=i.discriminatedUnion("type",[eO,ej,eN,eq,e5]),tt=i.object({role:ep,content:i.union([te,i.array(te)]),_meta:i.record(i.string(),i.unknown()).optional()}),tr=f.extend({messages:i.array(tt),modelPreferences:e9.optional(),systemPrompt:i.string().optional(),includeContext:i.enum(["none","thisServer","allServers"]).optional(),temperature:i.number().optional(),maxTokens:i.number().int(),stopSequences:i.array(i.string()).optional(),metadata:l.optional(),tools:i.array(eH).optional(),toolChoice:e8.optional()}),ti=g.extend({method:i.literal("sampling/createMessage"),params:tr}),ta=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens"]).or(i.string())),role:ep,content:e7}),tn=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(i.string())),role:ep,content:i.union([te,i.array(te)])}),ts=i.object({type:i.literal("boolean"),title:i.string().optional(),description:i.string().optional(),default:i.boolean().optional()}),to=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),minLength:i.number().optional(),maxLength:i.number().optional(),format:i.enum(["email","uri","date","date-time"]).optional(),default:i.string().optional()}),tl=i.object({type:i.enum(["number","integer"]),title:i.string().optional(),description:i.string().optional(),minimum:i.number().optional(),maximum:i.number().optional(),default:i.number().optional()}),tc=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),default:i.string().optional()}),tu=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),oneOf:i.array(i.object({const:i.string(),title:i.string()})),default:i.string().optional()}),td=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),enumNames:i.array(i.string()).optional(),default:i.string().optional()}),tp=i.union([tc,tu]),tm=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({type:i.literal("string"),enum:i.array(i.string())}),default:i.array(i.string()).optional()}),th=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({anyOf:i.array(i.object({const:i.string(),title:i.string()}))}),default:i.array(i.string()).optional()}),tf=i.union([tm,th]),tg=i.union([td,tp,tf]),ty=i.union([tg,ts,to,tl]),tv=f.extend({mode:i.literal("form").optional(),message:i.string(),requestedSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),ty),required:i.array(i.string()).optional()})}),tb=f.extend({mode:i.literal("url"),message:i.string(),elicitationId:i.string(),url:i.string().url()}),tw=i.union([tv,tb]),tx=g.extend({method:i.literal("elicitation/create"),params:tw}),tk=y.extend({elicitationId:i.string()}),t_=v.extend({method:i.literal("notifications/elicitation/complete"),params:tk}),t$=b.extend({action:i.enum(["accept","decline","cancel"]),content:i.preprocess(e=>null===e?void 0:e,i.record(i.string(),i.union([i.string(),i.number(),i.boolean(),i.array(i.string())])).optional())}),tI=i.object({type:i.literal("ref/resource"),uri:i.string()}),tS=i.object({type:i.literal("ref/prompt"),name:i.string()}),tE=h.extend({ref:i.union([tS,tI]),argument:i.object({name:i.string(),value:i.string()}),context:i.object({arguments:i.record(i.string(),i.string()).optional()}).optional()}),tT=g.extend({method:i.literal("completion/complete"),params:tE}),tC=b.extend({completion:i.looseObject({values:i.array(i.string()).max(100),total:i.optional(i.number().int()),hasMore:i.optional(i.boolean())})}),tR=i.object({uri:i.string().startsWith("file://"),name:i.string().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),tP=g.extend({method:i.literal("roots/list"),params:h.optional()}),tA=b.extend({roots:i.array(tR)}),tD=v.extend({method:i.literal("notifications/roots/list_changed"),params:y.optional()});i.union([z,L,tT,e4,eD,eR,eg,ev,ex,e$,eI,eQ,eZ,et,ei,ea,es]),i.union([T,H,B,tD,ee]),i.union([S,ta,tn,t$,tA,er,en,Y]),i.union([z,ti,tx,tP,et,ei,ea,es]),i.union([T,H,e2,eE,e_,eY,ez,ee,t_]),i.union([S,M,tC,eB,eP,ey,eb,ek,eJ,eV,er,en,Y]);class tO extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,i){return e===r.UrlElicitationRequired&&i&&i.elicitations?new tj(i.elicitations,t):new tO(e,t,i)}}class tj extends tO{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(r.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}e.s(["CallToolRequestSchema",0,eQ,"CallToolResultSchema",0,eJ,"CancelTaskRequestSchema",0,es,"CancelTaskResultSchema",0,eo,"CancelledNotificationSchema",0,T,"CompleteRequestSchema",0,tT,"CompleteResultSchema",0,tC,"CreateMessageRequestSchema",0,ti,"CreateMessageResultSchema",0,ta,"CreateMessageResultWithToolsSchema",0,tn,"CreateTaskResultSchema",0,Y,"DEFAULT_NEGOTIATED_PROTOCOL_VERSION",0,"2025-03-26","ElicitRequestSchema",0,tx,"ElicitResultSchema",0,t$,"EmptyResultSchema",0,S,"ErrorCode",0,r,"GetPromptRequestSchema",0,eD,"GetPromptResultSchema",0,eB,"GetTaskPayloadRequestSchema",0,ei,"GetTaskRequestSchema",0,et,"GetTaskResultSchema",0,er,"InitializeRequestSchema",0,L,"InitializeResultSchema",0,M,"InitializedNotificationSchema",0,B,"JSONRPCMessageSchema",0,I,"LATEST_PROTOCOL_VERSION",0,n,"ListChangedOptionsBaseSchema",0,eX,"ListPromptsRequestSchema",0,eR,"ListPromptsResultSchema",0,eP,"ListResourceTemplatesRequestSchema",0,ev,"ListResourceTemplatesResultSchema",0,eb,"ListResourcesRequestSchema",0,eg,"ListResourcesResultSchema",0,ey,"ListRootsResultSchema",0,tA,"ListTasksRequestSchema",0,ea,"ListTasksResultSchema",0,en,"ListToolsRequestSchema",0,eZ,"ListToolsResultSchema",0,eV,"LoggingLevelSchema",0,e0,"McpError",0,tO,"PingRequestSchema",0,z,"ProgressNotificationSchema",0,H,"PromptListChangedNotificationSchema",0,ez,"RELATED_TASK_META_KEY",0,o,"ReadResourceRequestSchema",0,ex,"ReadResourceResultSchema",0,ek,"ResourceListChangedNotificationSchema",0,e_,"SUPPORTED_PROTOCOL_VERSIONS",0,s,"SetLevelRequestSchema",0,e4,"TaskStatusNotificationSchema",0,ee,"ToolListChangedNotificationSchema",0,eY,"assertCompleteRequestPrompt",0,function(e){if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)},"assertCompleteRequestResourceTemplate",0,function(e){if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)},"isInitializeRequest",0,e=>L.safeParse(e).success,"isInitializedNotification",0,e=>B.safeParse(e).success,"isJSONRPCErrorResponse",0,e=>$.safeParse(e).success,"isJSONRPCNotification",0,e=>k.safeParse(e).success,"isJSONRPCRequest",0,e=>x.safeParse(e).success,"isJSONRPCResultResponse",0,e=>_.safeParse(e).success,"isTaskAugmentedRequestParams",0,e=>f.safeParse(e).success],556690)},729677,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.regexpCode=r.getEsmExportName=r.getProperty=r.safeStringify=r.stringify=r.strConcat=r.addCodeArg=r.str=r._=r.nil=r._Code=r.Name=r.IDENTIFIER=r._CodeOrName=void 0;class i{}r._CodeOrName=i,r.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class a extends i{constructor(e){if(super(),!r.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}r.Name=a;class n extends i{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return""===e||'""'===e}get str(){var e;return null!=(e=this._str)?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!=(e=this._names)?e:this._names=this._items.reduce((e,t)=>(t instanceof a&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){let r=[e[0]],i=0;for(;i<t.length;)c(r,t[i]),r.push(e[++i]);return new n(r)}r._Code=n,r.nil=new n(""),r._=s;let o=new n("+");function l(e,...t){let r=[u(e[0])],i=0;for(;i<t.length;)r.push(o),c(r,t[i]),r.push(o,u(e[++i]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===o){var r,i;let n=(r=e[t-1],'""'===(i=e[t+1])?r:'""'===r?i:"string"==typeof r?i instanceof a||'"'!==r[r.length-1]?void 0:"string"!=typeof i?`${r.slice(0,-1)}${i}"`:'"'===i[0]?r.slice(0,-1)+i.slice(1):void 0:"string"!=typeof i||'"'!==i[0]||r instanceof a?void 0:`"${r}${i.slice(1)}`);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(r),new n(r)}function c(e,t){var r;t instanceof n?e.push(...t._items):t instanceof a?e.push(t):e.push("number"==typeof(r=t)||"boolean"==typeof r||null===r?r:u(Array.isArray(r)?r.join(","):r))}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}r.str=l,r.addCodeArg=c,r.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:l`${e}${t}`},r.stringify=function(e){return new n(u(e))},r.safeStringify=u,r.getProperty=function(e){return"string"==typeof e&&r.IDENTIFIER.test(e)?new n(`.${e}`):s`[${e}]`},r.getEsmExportName=function(e){if("string"==typeof e&&r.IDENTIFIER.test(e))return new n(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},r.regexpCode=function(e){return new n(e.toString())}},738478,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.ValueScope=r.ValueScopeName=r.Scope=r.varKinds=r.UsedValueState=void 0;let n=e.r(729677);class s extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}(a=i||(r.UsedValueState=i={}))[a.Started=0]="Started",a[a.Completed=1]="Completed",r.varKinds={const:new n.Name("const"),let:new n.Name("let"),var:new n.Name("var")};class o{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof n.Name?e:this.name(e)}name(e){return new n.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if((null==(r=null==(t=this._parent)?void 0:t._prefixes)?void 0:r.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}}}r.Scope=o;class l extends n.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0,n._)`.${new n.Name(t)}[${r}]`}}r.ValueScopeName=l;let c=(0,n._)`\n`;r.ValueScope=class extends o{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:n.nil}}get(){return this._scope}name(e){return new l(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,n=null!=(r=t.key)?r:t.ref,s=this._values[a];if(s){let e=s.get(n);if(e)return e}else s=this._values[a]=new Map;s.set(n,i);let o=this._scope[a]||(this._scope[a]=[]),l=o.length;return o[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw Error(`CodeGen: name "${t}" has no value`);return(0,n._)`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,t,a={},o){let l=n.nil;for(let c in e){let u=e[c];if(!u)continue;let d=a[c]=a[c]||new Map;u.forEach(e=>{if(d.has(e))return;d.set(e,i.Started);let a=t(e);if(a){let t=this.opts.es5?r.varKinds.var:r.varKinds.const;l=(0,n._)`${l}${t} ${e} = ${a};${this.opts._n}`}else if(a=null==o?void 0:o(e))l=(0,n._)`${l}${a}${this.opts._n}`;else throw new s(e);d.set(e,i.Completed)})}return l}}},847550,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.or=r.and=r.not=r.CodeGen=r.operators=r.varKinds=r.ValueScopeName=r.ValueScope=r.Scope=r.Name=r.regexpCode=r.stringify=r.getProperty=r.nil=r.strConcat=r.str=r._=void 0;let i=e.r(729677),a=e.r(738478);var n=e.r(729677);Object.defineProperty(r,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(r,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(r,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(r,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(r,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(r,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(r,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(r,"Name",{enumerable:!0,get:function(){return n.Name}});var s=e.r(738478);Object.defineProperty(r,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(r,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(r,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(r,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),r.operators={GT:new i._Code(">"),GTE:new i._Code(">="),LT:new i._Code("<"),LTE:new i._Code("<="),EQ:new i._Code("==="),NEQ:new i._Code("!=="),NOT:new i._Code("!"),OR:new i._Code("||"),AND:new i._Code("&&"),ADD:new i._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class l extends o{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?a.varKinds.var:this.varKind,i=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=P(this.rhs,e,t)),this}get names(){return this.rhs instanceof i._CodeOrName?this.rhs.names:{}}}class c extends o{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof i.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=P(this.rhs,e,t),this}get names(){return R(this.lhs instanceof i.Name?{}:{...this.lhs.names},this.rhs)}}class u extends c{constructor(e,t,r,i){super(e,r,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class d extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class p extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){let t=this.label?` ${this.label}`:"";return`break${t};`+e}}class m extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends o{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=P(this.code,e,t),this}get names(){return this.code instanceof i._CodeOrName?this.code.names:{}}}class f extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(function(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}(e,a.names),r.splice(i,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>C(e,t.names),{})}}class g extends f{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class y extends f{}class v extends g{}v.kind="else";class b extends g{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 e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){let e=t.optimizeNodes();t=this.else=Array.isArray(e)?new v(e):e}return t?!1===e?t instanceof b?t:t.nodes:this.nodes.length?this:new b(A(e),t instanceof b?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null==(r=this.else)?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=P(this.condition,e,t),this}get names(){let e=super.names;return R(e,this.condition),this.else&&C(e,this.else.names),e}}b.kind="if";class w extends g{}w.kind="for";class x extends w{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=P(this.iteration,e,t),this}get names(){return C(super.names,this.iteration.names)}}class k extends w{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?a.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=R(super.names,this.from);return R(e,this.to)}}class _ extends w{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i}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=P(this.iterable,e,t),this}get names(){return C(super.names,this.iterable.names)}}class $ extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){let t=this.async?"async ":"";return`${t}function ${this.name}(${this.args})`+super.render(e)}}$.kind="func";class I extends f{render(e){return"return "+super.render(e)}}I.kind="return";class S extends g{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(),null==(e=this.catch)||e.optimizeNodes(),null==(t=this.finally)||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),null==(r=this.catch)||r.optimizeNames(e,t),null==(i=this.finally)||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&C(e,this.catch.names),this.finally&&C(e,this.finally.names),e}}class E extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}E.kind="catch";class T extends g{render(e){return"finally"+super.render(e)}}function C(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function R(e,t){return t instanceof i._CodeOrName?C(e,t.names):e}function P(e,t,r){var a;if(e instanceof i.Name)return n(e);if(!((a=e)instanceof i._Code&&a._items.some(e=>e instanceof i.Name&&1===t[e.str]&&void 0!==r[e.str])))return e;return new i._Code(e._items.reduce((e,t)=>(t instanceof i.Name&&(t=n(t)),t instanceof i._Code?e.push(...t._items):e.push(t),e),[]));function n(e){let i=r[e.str];return void 0===i||1!==t[e.str]?e:(delete t[e.str],i)}}function A(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:(0,i._)`!${N(e)}`}T.kind="finally",r.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new a.Scope({parent:e}),this._nodes=[new y]}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 r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}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,r,i){let a=this._scope.toName(t);return void 0!==r&&i&&(this._constants[a.str]=r),this._leafNode(new l(e,a,r)),a}const(e,t,r){return this._def(a.varKinds.const,e,t,r)}let(e,t,r){return this._def(a.varKinds.let,e,t,r)}var(e,t,r){return this._def(a.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new c(e,t,r))}add(e,t){return this._leafNode(new u(e,r.operators.ADD,t))}code(e){return"function"==typeof e?e():e!==i.nil&&this._leafNode(new h(e)),this}object(...e){let t=["{"];for(let[r,a]of e)t.length>1&&t.push(","),t.push(r),(r!==a||this.opts.es5)&&(t.push(":"),(0,i.addCodeArg)(t,a));return t.push("}"),new i._Code(t)}if(e,t,r){if(this._blockNode(new b(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new b(e))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(b,v)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new x(e),t)}forRange(e,t,r,i,n=this.opts.es5?a.varKinds.var:a.varKinds.let){let s=this._scope.toName(e);return this._for(new k(n,s,t,r),()=>i(s))}forOf(e,t,r,n=a.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let e=t instanceof i.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,i._)`${e}.length`,t=>{this.var(s,(0,i._)`${e}[${t}]`),r(s)})}return this._for(new _("of",n,s,t),()=>r(s))}forIn(e,t,r,n=this.opts.es5?a.varKinds.var:a.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,i._)`Object.keys(${t})`,r);let s=this._scope.toName(e);return this._for(new _("in",n,s,t),()=>r(s))}endFor(){return this._endBlockNode(w)}label(e){return this._leafNode(new d(e))}break(e){return this._leafNode(new p(e))}return(e){let t=new I;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(I)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new S;if(this._blockNode(i),this.code(e),t){let e=this.name("e");this._currNode=i.catch=new E(e),t(e)}return r&&(this._currNode=i.finally=new T,this.code(r)),this._endBlockNode(E,T)}throw(e){return this._leafNode(new m(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(void 0===t)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=i.nil,r,a){return this._blockNode(new $(e,t,r)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode($)}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 r=this._currNode;if(r instanceof e||t&&r 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 b))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}},r.not=A;let D=j(r.operators.AND);r.and=function(...e){return e.reduce(D)};let O=j(r.operators.OR);function j(e){return(t,r)=>t===i.nil?r:r===i.nil?t:(0,i._)`${N(t)} ${e} ${N(r)}`}function N(e){return e instanceof i.Name?e:(0,i._)`(${e})`}r.or=function(...e){return e.reduce(O)}},303581,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.checkStrictMode=r.getErrorPath=r.Type=r.useFunc=r.setEvaluated=r.evaluatedPropsToName=r.mergeEvaluated=r.eachItem=r.unescapeJsonPointer=r.escapeJsonPointer=r.escapeFragment=r.unescapeFragment=r.schemaRefOrVal=r.schemaHasRulesButRef=r.schemaHasRules=r.checkUnknownRules=r.alwaysValidSchema=r.toHash=void 0;let n=e.r(847550),s=e.r(729677);function o(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema||"boolean"==typeof t)return;let a=i.RULES.keywords;for(let r in t)a[r]||f(e,`unknown keyword: "${r}"`)}function l(e,t){if("boolean"==typeof e)return!e;for(let r in e)if(t[r])return!0;return!1}function c(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(a,s,o,l)=>{let c=void 0===o?s:o instanceof n.Name?(s instanceof n.Name?e(a,s,o):t(a,s,o),o):s instanceof n.Name?(t(a,o,s),s):r(s,o);return l!==n.Name||c instanceof n.Name?c:i(a,c)}}function p(e,t){if(!0===t)return e.var("props",!0);let r=e.var("props",(0,n._)`{}`);return void 0!==t&&m(e,r,t),r}function m(e,t,r){Object.keys(r).forEach(r=>e.assign((0,n._)`${t}${(0,n.getProperty)(r)}`,!0))}r.toHash=function(e){let t={};for(let r of e)t[r]=!0;return t},r.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(o(e,t),!l(t,e.self.RULES.all))},r.checkUnknownRules=o,r.schemaHasRules=l,r.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(let r in e)if("$ref"!==r&&t.all[r])return!0;return!1},r.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,i,a){if(!a){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return(0,n._)`${r}`}return(0,n._)`${e}${t}${(0,n.getProperty)(i)}`},r.unescapeFragment=function(e){return u(decodeURIComponent(e))},r.escapeFragment=function(e){return encodeURIComponent(c(e))},r.escapeJsonPointer=c,r.unescapeJsonPointer=u,r.eachItem=function(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)},r.mergeEvaluated={props:d({mergeNames:(e,t,r)=>e.if((0,n._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,n._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,n._)`${r} || {}`).code((0,n._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,n._)`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,(0,n._)`${r} || {}`),m(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:p}),items:d({mergeNames:(e,t,r)=>e.if((0,n._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,n._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,n._)`${r} !== true`,()=>e.assign(r,!0===t||(0,n._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},r.evaluatedPropsToName=p,r.setEvaluated=m;let h={};function f(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw Error(t);e.self.logger.warn(t)}}r.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:h[t.code]||(h[t.code]=new s._Code(t.code))})},(a=i||(r.Type=i={}))[a.Num=0]="Num",a[a.Str=1]="Str",r.getErrorPath=function(e,t,r){if(e instanceof n.Name){let a=t===i.Num;return r?a?(0,n._)`"[" + ${e} + "]"`:(0,n._)`"['" + ${e} + "']"`:a?(0,n._)`"/" + ${e}`:(0,n._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,n.getProperty)(e).toString():"/"+c(e)},r.checkStrictMode=f},424819,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550);r.default={data:new i.Name("data"),valCxt:new i.Name("valCxt"),instancePath:new i.Name("instancePath"),parentData:new i.Name("parentData"),parentDataProperty:new i.Name("parentDataProperty"),rootData:new i.Name("rootData"),dynamicAnchors:new i.Name("dynamicAnchors"),vErrors:new i.Name("vErrors"),errors:new i.Name("errors"),this:new i.Name("this"),self:new i.Name("self"),scope:new i.Name("scope"),json:new i.Name("json"),jsonPos:new i.Name("jsonPos"),jsonLen:new i.Name("jsonLen"),jsonPart:new i.Name("jsonPart")}},703402,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.extendErrors=r.resetErrorsCount=r.reportExtraError=r.reportError=r.keyword$DataError=r.keywordError=void 0;let i=e.r(847550),a=e.r(303581),n=e.r(424819);function s(e,t){let r=e.const("err",t);e.if((0,i._)`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,(0,i._)`[${r}]`),(0,i._)`${n.default.vErrors}.push(${r})`),e.code((0,i._)`${n.default.errors}++`)}function o(e,t){let{gen:r,validateName:a,schemaEnv:n}=e;n.$async?r.throw((0,i._)`new ${e.ValidationError}(${t})`):(r.assign((0,i._)`${a}.errors`,t),r.return(!1))}r.keywordError={message:({keyword:e})=>(0,i.str)`must pass "${e}" keyword validation`},r.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,i.str)`"${e}" keyword must be ${t} ($data)`:(0,i.str)`"${e}" keyword is invalid ($data)`},r.reportError=function(e,t=r.keywordError,a,n){let{it:l}=e,{gen:u,compositeRule:d,allErrors:p}=l,m=c(e,t,a);(null!=n?n:d||p)?s(u,m):o(l,(0,i._)`[${m}]`)},r.reportExtraError=function(e,t=r.keywordError,i){let{it:a}=e,{gen:l,compositeRule:u,allErrors:d}=a;s(l,c(e,t,i)),u||d||o(a,n.default.vErrors)},r.resetErrorsCount=function(e,t){e.assign(n.default.errors,t),e.if((0,i._)`${n.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,i._)`${n.default.vErrors}.length`,t),()=>e.assign(n.default.vErrors,null)))},r.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:a,errsCount:s,it:o}){if(void 0===s)throw Error("ajv implementation error");let l=e.name("err");e.forRange("i",s,n.default.errors,s=>{e.const(l,(0,i._)`${n.default.vErrors}[${s}]`),e.if((0,i._)`${l}.instancePath === undefined`,()=>e.assign((0,i._)`${l}.instancePath`,(0,i.strConcat)(n.default.instancePath,o.errorPath))),e.assign((0,i._)`${l}.schemaPath`,(0,i.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,i._)`${l}.schema`,r),e.assign((0,i._)`${l}.data`,a))})};let l={keyword:new i.Name("keyword"),schemaPath:new i.Name("schemaPath"),params:new i.Name("params"),propertyName:new i.Name("propertyName"),message:new i.Name("message"),schema:new i.Name("schema"),parentSchema:new i.Name("parentSchema")};function c(e,t,r){let{createErrors:s}=e.it;return!1===s?(0,i._)`{}`:function(e,t,r={}){let{gen:s,it:o}=e,c=[function({errorPath:e},{instancePath:t}){let r=t?(0,i.str)`${e}${(0,a.getErrorPath)(t,a.Type.Str)}`:e;return[n.default.instancePath,(0,i.strConcat)(n.default.instancePath,r)]}(o,r),function({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let s=n?t:(0,i.str)`${t}/${e}`;return r&&(s=(0,i.str)`${s}${(0,a.getErrorPath)(r,a.Type.Str)}`),[l.schemaPath,s]}(e,r)];return function(e,{params:t,message:r},a){let{keyword:s,data:o,schemaValue:c,it:u}=e,{opts:d,propertyName:p,topSchemaRef:m,schemaPath:h}=u;a.push([l.keyword,s],[l.params,"function"==typeof t?t(e):t||(0,i._)`{}`]),d.messages&&a.push([l.message,"function"==typeof r?r(e):r]),d.verbose&&a.push([l.schema,c],[l.parentSchema,(0,i._)`${m}${h}`],[n.default.data,o]),p&&a.push([l.propertyName,p])}(e,t,c),s.object(...c)}(e,t,r)}},666703,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.boolOrEmptySchema=r.topBoolOrEmptySchema=void 0;let i=e.r(703402),a=e.r(847550),n=e.r(424819),s={message:"boolean schema is false"};function o(e,t){let{gen:r,data:a}=e;(0,i.reportError)({gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},s,void 0,t)}r.topBoolOrEmptySchema=function(e){let{gen:t,schema:r,validateName:i}=e;!1===r?o(e,!1):"object"==typeof r&&!0===r.$async?t.return(n.default.data):(t.assign((0,a._)`${i}.errors`,null),t.return(!0))},r.boolOrEmptySchema=function(e,t){let{gen:r,schema:i}=e;!1===i?(r.var(t,!1),o(e)):r.var(t,!0)}},991127,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getRules=r.isJSONType=void 0;let i=new Set(["string","number","integer","boolean","null","object","array"]);r.isJSONType=function(e){return"string"==typeof e&&i.has(e)},r.getRules=function(){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:{}}}},79932,(e,t,r)=>{"use strict";function i(e,t){return t.rules.some(t=>a(e,t))}function a(e,t){var r;return void 0!==e[t.keyword]||(null==(r=t.definition.implements)?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(r,"__esModule",{value:!0}),r.shouldUseRule=r.shouldUseGroup=r.schemaHasRulesForType=void 0,r.schemaHasRulesForType=function({schema:e,self:t},r){let a=t.RULES.types[r];return a&&!0!==a&&i(e,a)},r.shouldUseGroup=i,r.shouldUseRule=a},580581,(e,t,r)=>{"use strict";var i,a;Object.defineProperty(r,"__esModule",{value:!0}),r.reportTypeError=r.checkDataTypes=r.checkDataType=r.coerceAndCheckDataType=r.getJSONTypes=r.getSchemaTypes=r.DataType=void 0;let n=e.r(991127),s=e.r(79932),o=e.r(703402),l=e.r(847550),c=e.r(303581);function u(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(n.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}(a=i||(r.DataType=i={}))[a.Correct=0]="Correct",a[a.Wrong=1]="Wrong",r.getSchemaTypes=function(e){let t=u(e.type);if(t.includes("null")){if(!1===e.nullable)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},r.getJSONTypes=u,r.coerceAndCheckDataType=function(e,t){var r,a;let{gen:n,data:o,opts:c}=e,u=(r=t,(a=c.coerceTypes)?r.filter(e=>d.has(e)||"array"===a&&"array"===e):[]),p=t.length>0&&!(0===u.length&&1===t.length&&(0,s.schemaHasRulesForType)(e,t[0]));if(p){let r=m(t,o,c.strictNumbers,i.Wrong);n.if(r,()=>{u.length?function(e,t,r){let{gen:i,data:a,opts:n}=e,s=i.let("dataType",(0,l._)`typeof ${a}`),o=i.let("coerced",(0,l._)`undefined`);for(let e of("array"===n.coerceTypes&&i.if((0,l._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>i.assign(a,(0,l._)`${a}[0]`).assign(s,(0,l._)`typeof ${a}`).if(m(t,a,n.strictNumbers),()=>i.assign(o,a))),i.if((0,l._)`${o} !== undefined`),r))(d.has(e)||"array"===e&&"array"===n.coerceTypes)&&function(e){switch(e){case"string":i.elseIf((0,l._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0,l._)`"" + ${a}`).elseIf((0,l._)`${a} === null`).assign(o,(0,l._)`""`);return;case"number":i.elseIf((0,l._)`${s} == "boolean" || ${a} === null
395
395
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(o,(0,l._)`+${a}`);return;case"integer":i.elseIf((0,l._)`${s} === "boolean" || ${a} === null
396
396
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(o,(0,l._)`+${a}`);return;case"boolean":i.elseIf((0,l._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(o,!1).elseIf((0,l._)`${a} === "true" || ${a} === 1`).assign(o,!0);return;case"null":i.elseIf((0,l._)`${a} === "" || ${a} === 0 || ${a} === false`),i.assign(o,null);return;case"array":i.elseIf((0,l._)`${s} === "string" || ${s} === "number"
397
397
  || ${s} === "boolean" || ${a} === null`).assign(o,(0,l._)`[${a}]`)}}(e);i.else(),f(e),i.endIf(),i.if((0,l._)`${o} !== undefined`,()=>{i.assign(a,o),function({gen:e,parentData:t,parentDataProperty:r},i){e.if((0,l._)`${t} !== undefined`,()=>e.assign((0,l._)`${t}[${r}]`,i))}(e,o)})}(e,t,u):f(e)})}return p};let d=new Set(["string","number","integer","boolean","null"]);function p(e,t,r,a=i.Correct){let n,s=a===i.Correct?l.operators.EQ:l.operators.NEQ;switch(e){case"null":return(0,l._)`${t} ${s} null`;case"array":n=(0,l._)`Array.isArray(${t})`;break;case"object":n=(0,l._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":n=o((0,l._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":n=o();break;default:return(0,l._)`typeof ${t} ${s} ${e}`}return a===i.Correct?n:(0,l.not)(n);function o(e=l.nil){return(0,l.and)((0,l._)`typeof ${t} == "number"`,e,r?(0,l._)`isFinite(${t})`:l.nil)}}function m(e,t,r,i){let a;if(1===e.length)return p(e[0],t,r,i);let n=(0,c.toHash)(e);if(n.array&&n.object){let e=(0,l._)`typeof ${t} != "object"`;a=n.null?e:(0,l._)`!${t} || ${e}`,delete n.null,delete n.array,delete n.object}else a=l.nil;for(let e in n.number&&delete n.integer,n)a=(0,l.and)(a,p(e,t,r,i));return a}r.checkDataType=p,r.checkDataTypes=m;let h={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?(0,l._)`{type: ${e}}`:(0,l._)`{type: ${t}}`};function f(e){let t=function(e){let{gen:t,data:r,schema:i}=e,a=(0,c.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:a,schemaValue:a,parentSchema:i,params:{},it:e}}(e);(0,o.reportError)(t,h)}r.reportTypeError=f},931212,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.assignDefaults=void 0;let i=e.r(847550),a=e.r(303581);function n(e,t,r){let{gen:n,compositeRule:s,data:o,opts:l}=e;if(void 0===r)return;let c=(0,i._)`${o}${(0,i.getProperty)(t)}`;if(s)return void(0,a.checkStrictMode)(e,`default is ignored for: ${c}`);let u=(0,i._)`${c} === undefined`;"empty"===l.useDefaults&&(u=(0,i._)`${u} || ${c} === null || ${c} === ""`),n.if(u,(0,i._)`${c} = ${(0,i.stringify)(r)}`)}r.assignDefaults=function(e,t){let{properties:r,items:i}=e.schema;if("object"===t&&r)for(let t in r)n(e,t,r[t].default);else"array"===t&&Array.isArray(i)&&i.forEach((t,r)=>n(e,r,t.default))}},899803,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateUnion=r.validateArray=r.usePattern=r.callValidateCode=r.schemaProperties=r.allSchemaProperties=r.noPropertyInData=r.propertyInData=r.isOwnProperty=r.hasPropFunc=r.reportMissingProp=r.checkMissingProp=r.checkReportMissingProp=void 0;let i=e.r(847550),a=e.r(303581),n=e.r(424819),s=e.r(303581);function o(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,i._)`Object.prototype.hasOwnProperty`})}function l(e,t,r){return(0,i._)`${o(e)}.call(${t}, ${r})`}function c(e,t,r,a){let n=(0,i._)`${t}${(0,i.getProperty)(r)} === undefined`;return a?(0,i.or)(n,(0,i.not)(l(e,t,r))):n}function u(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}r.checkReportMissingProp=function(e,t){let{gen:r,data:a,it:n}=e;r.if(c(r,a,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:(0,i._)`${t}`},!0),e.error()})},r.checkMissingProp=function({gen:e,data:t,it:{opts:r}},a,n){return(0,i.or)(...a.map(a=>(0,i.and)(c(e,t,a,r.ownProperties),(0,i._)`${n} = ${a}`)))},r.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},r.hasPropFunc=o,r.isOwnProperty=l,r.propertyInData=function(e,t,r,a){let n=(0,i._)`${t}${(0,i.getProperty)(r)} !== undefined`;return a?(0,i._)`${n} && ${l(e,t,r)}`:n},r.noPropertyInData=c,r.allSchemaProperties=u,r.schemaProperties=function(e,t){return u(t).filter(r=>!(0,a.alwaysValidSchema)(e,t[r]))},r.callValidateCode=function({schemaCode:e,data:t,it:{gen:r,topSchemaRef:a,schemaPath:s,errorPath:o},it:l},c,u,d){let p=d?(0,i._)`${e}, ${t}, ${a}${s}`:t,m=[[n.default.instancePath,(0,i.strConcat)(n.default.instancePath,o)],[n.default.parentData,l.parentData],[n.default.parentDataProperty,l.parentDataProperty],[n.default.rootData,n.default.rootData]];l.opts.dynamicRef&&m.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let h=(0,i._)`${p}, ${r.object(...m)}`;return u!==i.nil?(0,i._)`${c}.call(${u}, ${h})`:(0,i._)`${c}(${h})`};let d=(0,i._)`new RegExp`;r.usePattern=function({gen:e,it:{opts:t}},r){let a=t.unicodeRegExp?"u":"",{regExp:n}=t.code,o=n(r,a);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,i._)`${"new RegExp"===n.code?d:(0,s.useFunc)(e,n)}(${r}, ${a})`})},r.validateArray=function(e){let{gen:t,data:r,keyword:n,it:s}=e,o=t.name("valid");if(s.allErrors){let e=t.let("valid",!0);return l(()=>t.assign(e,!1)),e}return t.var(o,!0),l(()=>t.break()),o;function l(s){let l=t.const("len",(0,i._)`${r}.length`);t.forRange("i",0,l,r=>{e.subschema({keyword:n,dataProp:r,dataPropType:a.Type.Num},o),t.if((0,i.not)(o),s)})}},r.validateUnion=function(e){let{gen:t,schema:r,keyword:n,it:s}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(e=>(0,a.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;let o=t.let("valid",!1),l=t.name("_valid");t.block(()=>r.forEach((r,a)=>{let s=e.subschema({keyword:n,schemaProp:a,compositeRule:!0},l);t.assign(o,(0,i._)`${o} || ${l}`),e.mergeValidEvaluated(s,l)||t.if((0,i.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}},407777,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateKeywordUsage=r.validSchemaType=r.funcKeywordCode=r.macroKeywordCode=void 0;let i=e.r(847550),a=e.r(424819),n=e.r(899803),s=e.r(703402);function o(e){let{gen:t,data:r,it:a}=e;t.if(a.parentData,()=>t.assign(r,(0,i._)`${a.parentData}[${a.parentDataProperty}]`))}function l(e,t,r){if(void 0===r)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,i.stringify)(r)})}r.macroKeywordCode=function(e,t){let{gen:r,keyword:a,schema:n,parentSchema:s,it:o}=e,c=t.macro.call(o.self,n,s,o),u=l(r,a,c);!1!==o.opts.validateSchema&&o.self.validateSchema(c,!0);let d=r.name("valid");e.subschema({schema:c,schemaPath:i.nil,errSchemaPath:`${o.errSchemaPath}/${a}`,topSchemaRef:u,compositeRule:!0},d),e.pass(d,()=>e.error(!0))},r.funcKeywordCode=function(e,t){var r;let{gen:c,keyword:u,schema:d,parentSchema:p,$data:m,it:h}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}(h,t);let f=l(c,u,!m&&t.compile?t.compile.call(h.self,d,p,h):t.validate),g=c.let("valid");function y(r=t.async?(0,i._)`await `:i.nil){let s=h.opts.passContext?a.default.this:a.default.self,o=!("compile"in t&&!m||!1===t.schema);c.assign(g,(0,i._)`${r}${(0,n.callValidateCode)(e,f,s,o)}`,t.modifying)}function v(e){var r;c.if((0,i.not)(null!=(r=t.valid)?r:g),e)}e.block$data(g,function(){if(!1===t.errors)y(),t.modifying&&o(e),v(()=>e.error());else{let r,n,l=t.async?(r=c.let("ruleErrs",null),c.try(()=>y((0,i._)`await `),e=>c.assign(g,!1).if((0,i._)`${e} instanceof ${h.ValidationError}`,()=>c.assign(r,(0,i._)`${e}.errors`),()=>c.throw(e))),r):(n=(0,i._)`${f}.errors`,c.assign(n,null),y(i.nil),n);t.modifying&&o(e),v(()=>(function(e,t){let{gen:r}=e;r.if((0,i._)`Array.isArray(${t})`,()=>{r.assign(a.default.vErrors,(0,i._)`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`).assign(a.default.errors,(0,i._)`${a.default.vErrors}.length`),(0,s.extendErrors)(e)},()=>e.error())})(e,l))}}),e.ok(null!=(r=t.valid)?r:g)},r.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},r.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:i},a,n){if(Array.isArray(a.keyword)?!a.keyword.includes(n):a.keyword!==n)throw Error("ajv implementation error");let s=a.dependencies;if(null==s?void 0:s.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${n}: ${s.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[n])){let e=`keyword "${n}" value is invalid at path "${i}": `+r.errorsText(a.validateSchema.errors);if("log"===t.validateSchema)r.logger.error(e);else throw Error(e)}}},936577,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.extendSubschemaMode=r.extendSubschemaData=r.getSubschema=void 0;let i=e.r(847550),a=e.r(303581);r.getSubschema=function(e,{keyword:t,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:l}){if(void 0!==t&&void 0!==n)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){let n=e.schema[t];return void 0===r?{schema:n,schemaPath:(0,i._)`${e.schemaPath}${(0,i.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:n[r],schemaPath:(0,i._)`${e.schemaPath}${(0,i.getProperty)(t)}${(0,i.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,a.escapeFragment)(r)}`}}if(void 0!==n){if(void 0===s||void 0===o||void 0===l)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:l,errSchemaPath:o}}throw Error('either "keyword" or "schema" must be passed')},r.extendSubschemaData=function(e,t,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:l}){if(void 0!==s&&void 0!==r)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(void 0!==r){let{errorPath:s,dataPathArr:o,opts:l}=t;u(c.let("data",(0,i._)`${t.data}${(0,i.getProperty)(r)}`,!0)),e.errorPath=(0,i.str)`${s}${(0,a.getErrorPath)(r,n,l.jsPropertySyntax)}`,e.parentDataProperty=(0,i._)`${r}`,e.dataPathArr=[...o,e.parentDataProperty]}function u(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}void 0!==s&&(u(s instanceof i.Name?s:c.let("data",s,!0)),void 0!==l&&(e.propertyName=l)),o&&(e.dataTypes=o)},r.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:a,allErrors:n}){void 0!==i&&(e.compositeRule=i),void 0!==a&&(e.createErrors=a),void 0!==n&&(e.allErrors=n),e.jtdDiscriminator=t,e.jtdMetadata=r}},986317,(e,t,r)=>{"use strict";var i=t.exports=function(e,t,r){"function"==typeof t&&(r=t,t={});var a="function"==typeof(r=t.cb||r)?r:r.pre||function(){};!function e(t,r,a,n,s,o,l,c,u,d){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var p in r(n,s,o,l,c,u,d),n){var m=n[p];if(Array.isArray(m)){if(p in i.arrayKeywords)for(var h=0;h<m.length;h++)e(t,r,a,m[h],s+"/"+p+"/"+h,o,s,p,n,h)}else if(p in i.propsKeywords){if(m&&"object"==typeof m)for(var f in m)e(t,r,a,m[f],s+"/"+p+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),o,s,p,n,f)}else(p in i.keywords||t.allKeys&&!(p in i.skipKeywords))&&e(t,r,a,m,s+"/"+p,o,s,p,n)}a(n,s,o,l,c,u,d)}}(t,a,r.post||function(){},e,"",e)};i.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},i.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},i.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},i.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},786181,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getSchemaRefs=r.resolveUrl=r.normalizeId=r._getFullPath=r.getFullPath=r.inlineRef=void 0;let i=e.r(303581),a=e.r(140804),n=e.r(986317),s=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);r.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!function e(t){for(let r in t){if(o.has(r))return!0;let i=t[r];if(Array.isArray(i)&&i.some(e)||"object"==typeof i&&e(i))return!0}return!1}(e):!!t&&function e(t){let r=0;for(let a in t)if("$ref"===a||(r++,!s.has(a)&&("object"==typeof t[a]&&(0,i.eachItem)(t[a],t=>r+=e(t)),r===1/0)))return 1/0;return r}(e)<=t)};let o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function l(e,t="",r){!1!==r&&(t=d(t));let i=e.parse(t);return c(e,i)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}r.getFullPath=l,r._getFullPath=c;let u=/#\/?$/;function d(e){return e?e.replace(u,""):""}r.normalizeId=d,r.resolveUrl=function(e,t,r){return r=d(r),e.resolve(t,r)};let p=/^[a-z_][-a-z0-9._]*$/i;r.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};let{schemaId:r,uriResolver:i}=this.opts,s=d(e[r]||t),o={"":s},c=l(i,s,!1),u={},m=new Set;return n(e,{allKeys:!0},(e,t,i,a)=>{if(void 0===a)return;let n=c+t,s=o[a];function l(t){let r=this.opts.uriResolver.resolve;if(t=d(s?r(s,t):t),m.has(t))throw f(t);m.add(t);let i=this.refs[t];return"string"==typeof i&&(i=this.refs[i]),"object"==typeof i?h(e,i.schema,t):t!==d(n)&&("#"===t[0]?(h(e,u[t],t),u[t]=e):this.refs[t]=n),t}function g(e){if("string"==typeof e){if(!p.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[r]&&(s=l.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),o[t]=s}),u;function h(e,t,r){if(void 0!==t&&!a(e,t))throw f(r)}function f(e){return Error(`reference "${e}" resolves to more than one schema`)}}},448546,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.getData=r.KeywordCxt=r.validateFunctionCode=void 0;let i=e.r(666703),a=e.r(580581),n=e.r(79932),s=e.r(580581),o=e.r(931212),l=e.r(407777),c=e.r(936577),u=e.r(847550),d=e.r(424819),p=e.r(786181),m=e.r(303581),h=e.r(703402);function f({gen:e,validateName:t,schema:r,schemaEnv:i,opts:a},n){var s;a.code.es5?e.func(t,(0,u._)`${d.default.data}, ${d.default.valCxt}`,i.$async,()=>{var t,i;e.code((0,u._)`"use strict"; ${g(r,a)}`),t=e,i=a,t.if(d.default.valCxt,()=>{t.var(d.default.instancePath,(0,u._)`${d.default.valCxt}.${d.default.instancePath}`),t.var(d.default.parentData,(0,u._)`${d.default.valCxt}.${d.default.parentData}`),t.var(d.default.parentDataProperty,(0,u._)`${d.default.valCxt}.${d.default.parentDataProperty}`),t.var(d.default.rootData,(0,u._)`${d.default.valCxt}.${d.default.rootData}`),i.dynamicRef&&t.var(d.default.dynamicAnchors,(0,u._)`${d.default.valCxt}.${d.default.dynamicAnchors}`)},()=>{t.var(d.default.instancePath,(0,u._)`""`),t.var(d.default.parentData,(0,u._)`undefined`),t.var(d.default.parentDataProperty,(0,u._)`undefined`),t.var(d.default.rootData,d.default.data),i.dynamicRef&&t.var(d.default.dynamicAnchors,(0,u._)`{}`)}),e.code(n)}):e.func(t,(0,u._)`${d.default.data}, ${(s=a,(0,u._)`{${d.default.instancePath}="", ${d.default.parentData}, ${d.default.parentDataProperty}, ${d.default.rootData}=${d.default.data}${s.dynamicRef?(0,u._)`, ${d.default.dynamicAnchors}={}`:u.nil}}={}`)}`,i.$async,()=>e.code(g(r,a)).code(n))}function g(e,t){let r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,u._)`/*# sourceURL=${r} */`:u.nil}function y({schema:e,self:t}){if("boolean"==typeof e)return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function v(e){return"boolean"!=typeof e.schema}function b(e){(0,m.checkUnknownRules)(e),function(e){let{schema:t,errSchemaPath:r,opts:i,self:a}=e;t.$ref&&i.ignoreKeywordsWithRef&&(0,m.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function w(e,t){if(e.opts.jtd)return k(e,[],!1,t);let r=(0,a.getSchemaTypes)(e.schema),i=(0,a.coerceAndCheckDataType)(e,r);k(e,r,!i,t)}function x({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:a}){let n=r.$comment;if(!0===a.$comment)e.code((0,u._)`${d.default.self}.logger.log(${n})`);else if("function"==typeof a.$comment){let r=(0,u.str)`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,u._)`${d.default.self}.opts.$comment(${n}, ${r}, ${a}.schema)`)}}function k(e,t,r,i){var a,o,l,c;let{gen:p,schema:h,data:f,allErrors:g,opts:y,self:v}=e,{RULES:b}=v;if(h.$ref&&(y.ignoreKeywordsWithRef||!(0,m.schemaHasRulesButRef)(h,b)))return void p.block(()=>E(e,"$ref",b.all.$ref.definition));function w(a){(0,n.shouldUseGroup)(h,a)&&(a.type?(p.if((0,s.checkDataType)(a.type,f,y.strictNumbers)),_(e,a),1===t.length&&t[0]===a.type&&r&&(p.else(),(0,s.reportTypeError)(e)),p.endIf()):_(e,a),g||p.if((0,u._)`${d.default.errors} === ${i||0}`))}y.jtd||(a=e,o=t,!a.schemaEnv.meta&&a.opts.strictTypes&&(function(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{$(e.dataTypes,t)||I(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){let r=[];for(let i of e.dataTypes)$(t,i)?r.push(i):t.includes("integer")&&"number"===i&&r.push("integer");e.dataTypes=r}(e,t)}}(a,o),a.opts.allowUnionTypes||(l=a,(c=o).length>1&&!(2===c.length&&c.includes("null"))&&I(l,"use allowUnionTypes to allow union type keyword")),function(e,t){let r=e.self.RULES.all;for(let i in r){let a=r[i];if("object"==typeof a&&(0,n.shouldUseRule)(e.schema,a)){let{type:r}=a.definition;r.length&&!r.some(e=>{var r,i;return r=t,i=e,r.includes(i)||"number"===i&&r.includes("integer")})&&I(e,`missing type "${r.join(",")}" for keyword "${i}"`)}}}(a,a.dataTypes))),p.block(()=>{for(let e of b.rules)w(e);w(b.post)})}function _(e,t){let{gen:r,schema:i,opts:{useDefaults:a}}=e;a&&(0,o.assignDefaults)(e,t.type),r.block(()=>{for(let r of t.rules)(0,n.shouldUseRule)(i,r)&&E(e,r.keyword,r.definition,t.type)})}function $(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function I(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,m.checkStrictMode)(e,t,e.opts.strictTypes)}r.validateFunctionCode=function(e){v(e)&&(b(e),y(e))?function(e){let{schema:t,opts:r,gen:i}=e;f(e,()=>{r.$comment&&t.$comment&&x(e),function(e){let{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,m.checkStrictMode)(e,"default is ignored in the schema root")}(e),i.let(d.default.vErrors,null),i.let(d.default.errors,0),r.unevaluated&&function(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,u._)`${r}.evaluated`),t.if((0,u._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,u._)`${e.evaluated}.props`,(0,u._)`undefined`)),t.if((0,u._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,u._)`${e.evaluated}.items`,(0,u._)`undefined`))}(e),w(e),function(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:a,opts:n}=e;r.$async?t.if((0,u._)`${d.default.errors} === 0`,()=>t.return(d.default.data),()=>t.throw((0,u._)`new ${a}(${d.default.vErrors})`)):(t.assign((0,u._)`${i}.errors`,d.default.vErrors),n.unevaluated&&function({gen:e,evaluated:t,props:r,items:i}){r instanceof u.Name&&e.assign((0,u._)`${t}.props`,r),i instanceof u.Name&&e.assign((0,u._)`${t}.items`,i)}(e),t.return((0,u._)`${d.default.errors} === 0`))}(e)})}(e):f(e,()=>(0,i.topBoolOrEmptySchema)(e))};class S{constructor(e,t,r){if((0,l.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,m.schemaRefOrVal)(e,this.schema,r,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",R(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,l.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",d.default.errors))}result(e,t,r){this.failResult((0,u.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():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,u.not)(e),void 0,t)}fail(e){if(void 0===e){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,u._)`${t} !== undefined && (${(0,u.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?h.reportExtraError:h.reportError)(this,this.def.error,t)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,h.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,r=u.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=u.nil,t=u.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:n}=this;r.if((0,u.or)((0,u._)`${i} === undefined`,t)),e!==u.nil&&r.assign(e,!0),(a.length||n.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==u.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return(0,u.or)(function(){if(r.length){if(!(t instanceof u.Name))throw Error("ajv implementation error");let e=Array.isArray(r)?r:[r];return(0,u._)`${(0,s.checkDataTypes)(e,t,a.opts.strictNumbers,s.DataType.Wrong)}`}return u.nil}(),function(){if(i.validateSchema){let r=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,u._)`!${r}(${t})`}return u.nil}())}subschema(e,t){let r=(0,c.getSubschema)(this.it,e);(0,c.extendSubschemaData)(r,this.it,e),(0,c.extendSubschemaMode)(r,e);let a={...this.it,...r,items:void 0,props:void 0};return!function(e,t){if(v(e)&&(b(e),y(e)))return function(e,t){var r;let i,{schema:a,gen:n,opts:s}=e;s.$comment&&a.$comment&&x(e),(i=(r=e).schema[r.opts.schemaId])&&(r.baseId=(0,p.resolveUrl)(r.opts.uriResolver,r.baseId,i)),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}(e);let o=n.const("_errs",d.default.errors);w(e,o),n.var(t,(0,u._)`${o} === ${d.default.errors}`)}(e,t);(0,i.boolOrEmptySchema)(e,t)}(a,t),a}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=m.mergeEvaluated.props(i,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=m.mergeEvaluated.items(i,e.items,r.items,t)))}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return i.if(t,()=>this.mergeEvaluated(e,u.Name)),!0}}function E(e,t,r,i){let a=new S(e,r,t);"code"in r?r.code(a,i):a.$data&&r.validate?(0,l.funcKeywordCode)(a,r):"macro"in r?(0,l.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,l.funcKeywordCode)(a,r)}r.KeywordCxt=S;let T=/^\/(?:[^~]|~0|~1)*$/,C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function R(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let a,n;if(""===e)return d.default.rootData;if("/"===e[0]){if(!T.test(e))throw Error(`Invalid JSON-pointer: ${e}`);a=e,n=d.default.rootData}else{let s=C.exec(e);if(!s)throw Error(`Invalid JSON-pointer: ${e}`);let l=+s[1];if("#"===(a=s[2])){if(l>=t)throw Error(o("property/index",l));return i[t-l]}if(l>t)throw Error(o("data",l));if(n=r[t-l],!a)return n}let s=n;for(let e of a.split("/"))e&&(n=(0,u._)`${n}${(0,u.getProperty)((0,m.unescapeJsonPointer)(e))}`,s=(0,u._)`${s} && ${n}`);return s;function o(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}r.getData=R},60201,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}},864592,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(786181);r.default=class extends Error{constructor(e,t,r,a){super(a||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,i.resolveUrl)(e,t,r),this.missingSchema=(0,i.normalizeId)((0,i.getFullPath)(e,this.missingRef))}}},106981,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.resolveSchema=r.getCompilingSchema=r.resolveRef=r.compileSchema=r.SchemaEnv=void 0;let i=e.r(847550),a=e.r(60201),n=e.r(424819),s=e.r(786181),o=e.r(303581),l=e.r(448546);class c{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!=(t=e.baseId)?t:(0,s.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function u(e){let t,r,o=p.call(this,e);if(o)return o;let c=(0,s.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:u,lines:d}=this.opts.code,{ownProperties:m}=this.opts,h=new i.CodeGen(this.scope,{es5:u,lines:d,ownProperties:m});e.$async&&(t=h.scopeValue("Error",{ref:a.default,code:(0,i._)`require("ajv/dist/runtime/validation_error").default`}));let f=h.scopeName("validate");e.validateName=f;let g={gen:h,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[i.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:h.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,i.stringify)(e.schema)}:{ref:e.schema}),validateName:f,ValidationError:t,schema:e.schema,schemaEnv:e,rootId:c,baseId:e.baseId||c,schemaPath:i.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,i._)`""`,opts:this.opts,self:this};try{this._compilations.add(e),(0,l.validateFunctionCode)(g),h.optimize(this.opts.code.optimize);let t=h.toString();r=`${h.scopeRefs(n.default.scope)}return ${t}`,this.opts.code.process&&(r=this.opts.code.process(r,e));let a=Function(`${n.default.self}`,`${n.default.scope}`,r)(this,this.scope.get());if(this.scope.value(f,{ref:a}),a.errors=null,a.schema=e.schema,a.schemaEnv=e,e.$async&&(a.$async=!0),!0===this.opts.code.source&&(a.source={validateName:f,validateCode:t,scopeValues:h._values}),this.opts.unevaluated){let{props:e,items:t}=g;a.evaluated={props:e instanceof i.Name?void 0:e,items:t instanceof i.Name?void 0:t,dynamicProps:e instanceof i.Name,dynamicItems:t instanceof i.Name},a.source&&(a.source.evaluated=(0,i.stringify)(a.evaluated))}return e.validate=a,e}catch(t){throw delete e.validate,delete e.validateName,r&&this.logger.error("Error compiling schema, function code:",r),t}finally{this._compilations.delete(e)}}function d(e){return(0,s.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:u.call(this,e)}function p(e){for(let i of this._compilations){var t,r;if(t=i,r=e,t.schema===r.schema&&t.root===r.root&&t.baseId===r.baseId)return i}}function m(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||h.call(this,e,t)}function h(e,t){let r=this.opts.uriResolver.parse(t),i=(0,s._getFullPath)(this.opts.uriResolver,r),a=(0,s.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===a)return g.call(this,r,e);let n=(0,s.normalizeId)(i),o=this.refs[n]||this.schemas[n];if("string"==typeof o){let t=h.call(this,e,o);if("object"!=typeof(null==t?void 0:t.schema))return;return g.call(this,r,t)}if("object"==typeof(null==o?void 0:o.schema)){if(o.validate||u.call(this,o),n===(0,s.normalizeId)(t)){let{schema:t}=o,{schemaId:r}=this.opts,i=t[r];return i&&(a=(0,s.resolveUrl)(this.opts.uriResolver,a,i)),new c({schema:t,schemaId:r,root:e,baseId:a})}return g.call(this,r,o)}}r.SchemaEnv=c,r.compileSchema=u,r.resolveRef=function(e,t,r){var i;r=(0,s.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let n=m.call(this,e,r);if(void 0===n){let a=null==(i=e.localRefs)?void 0:i[r],{schemaId:s}=this.opts;a&&(n=new c({schema:a,schemaId:s,root:e,baseId:t}))}if(void 0!==n)return e.refs[r]=d.call(this,n)},r.getCompilingSchema=p,r.resolveSchema=h;let f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function g(e,{baseId:t,schema:r,root:i}){var a;let n;if((null==(a=e.fragment)?void 0:a[0])!=="/")return;for(let i of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;let e=r[(0,o.unescapeFragment)(i)];if(void 0===e)return;let a="object"==typeof(r=e)&&r[this.opts.schemaId];!f.has(i)&&a&&(t=(0,s.resolveUrl)(this.opts.uriResolver,t,a))}if("boolean"!=typeof r&&r.$ref&&!(0,o.schemaHasRulesButRef)(r,this.RULES)){let e=(0,s.resolveUrl)(this.opts.uriResolver,t,r.$ref);n=h.call(this,i,e)}let{schemaId:l}=this.opts;if((n=n||new c({schema:r,schemaId:l,root:i,baseId:t})).schema!==n.root.schema)return n}},739499,(e,t,r)=>{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}},353634,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(804957);i.code='require("ajv/dist/runtime/uri").default',r.default=i},159949,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.CodeGen=r.Name=r.nil=r.stringify=r.str=r._=r.KeywordCxt=void 0;var i=e.r(448546);Object.defineProperty(r,"KeywordCxt",{enumerable:!0,get:function(){return i.KeywordCxt}});var a=e.r(847550);Object.defineProperty(r,"_",{enumerable:!0,get:function(){return a._}}),Object.defineProperty(r,"str",{enumerable:!0,get:function(){return a.str}}),Object.defineProperty(r,"stringify",{enumerable:!0,get:function(){return a.stringify}}),Object.defineProperty(r,"nil",{enumerable:!0,get:function(){return a.nil}}),Object.defineProperty(r,"Name",{enumerable:!0,get:function(){return a.Name}}),Object.defineProperty(r,"CodeGen",{enumerable:!0,get:function(){return a.CodeGen}});let n=e.r(60201),s=e.r(864592),o=e.r(991127),l=e.r(106981),c=e.r(847550),u=e.r(786181),d=e.r(580581),p=e.r(303581),m=e.r(739499),h=e.r(353634),f=(e,t)=>new RegExp(e,t);f.code="new RegExp";let g=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={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."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};class w{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,...function(e){var t,r,i,a,n,s,o,l,c,u,d,p,m,g,y,v,b,w,x,k,_,$,I,S,E;let T=e.strict,C=null==(t=e.code)?void 0:t.optimize,R=!0===C||void 0===C?1:C||0,P=null!=(i=null==(r=e.code)?void 0:r.regExp)?i:f,A=null!=(a=e.uriResolver)?a:h.default;return{strictSchema:null==(s=null!=(n=e.strictSchema)?n:T)||s,strictNumbers:null==(l=null!=(o=e.strictNumbers)?o:T)||l,strictTypes:null!=(u=null!=(c=e.strictTypes)?c:T)?u:"log",strictTuples:null!=(p=null!=(d=e.strictTuples)?d:T)?p:"log",strictRequired:null!=(g=null!=(m=e.strictRequired)?m:T)&&g,code:e.code?{...e.code,optimize:R,regExp:P}:{optimize:R,regExp:P},loopRequired:null!=(y=e.loopRequired)?y:200,loopEnum:null!=(v=e.loopEnum)?v:200,meta:null==(b=e.meta)||b,messages:null==(w=e.messages)||w,inlineRefs:null==(x=e.inlineRefs)||x,schemaId:null!=(k=e.schemaId)?k:"$id",addUsedSchema:null==(_=e.addUsedSchema)||_,validateSchema:null==($=e.validateSchema)||$,validateFormats:null==(I=e.validateFormats)||I,unicodeRegExp:null==(S=e.unicodeRegExp)||S,int32range:null==(E=e.int32range)||E,uriResolver:A}}(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:y,es5:t,lines:r}),this.logger=function(e){if(!1===e)return E;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}(e.logger);const i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),x.call(this,v,e,"NOT SUPPORTED"),x.call(this,b,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&I.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),_.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=m;"id"===r&&((i={...m}).id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);return"$async"in r||(this.errors=r.errors),i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(e,t){await a.call(this,e.$schema);let r=this._addSchema(e,t);return r.validate||n.call(this,r)}async function a(e){e&&!this.getSchema(e)&&await i.call(this,{$ref:e},!0)}async function n(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return o.call(this,t),await l.call(this,t.missingSchema),n.call(this,e)}}function o({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function l(e){let r=await c.call(this,e);this.refs[e]||await a.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function c(e){let t=this._loading[e];if(t)return t;try{return await (this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,i=this.opts.validateSchema){let a;if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,r,i);return this}if("object"==typeof e){let{schemaId:t}=this.opts;if(void 0!==(a=e[t])&&"string"!=typeof a)throw Error(`schema ${t} must be string`)}return t=(0,u.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){let r;if("boolean"==typeof e)return!0;if(void 0!==(r=e.$schema)&&"string"!=typeof r)throw Error("$schema must be a string");if(!(r=r||this.opts.defaultMeta||this.defaultMeta()))return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(r,e);if(!i&&t){let e="schema is invalid: "+this.errorsText();if("log"===this.opts.validateSchema)this.logger.error(e);else throw Error(e)}return i}getSchema(e){let t;for(;"string"==typeof(t=k.call(this,e));)e=t;if(void 0===t){let{schemaId:r}=this.opts,i=new l.SchemaEnv({schema:{},schemaId:r});if(!(t=l.resolveSchema.call(this,i,e)))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=k.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{this._cache.delete(e);let t=e[this.opts.schemaId];return t&&(t=(0,u.normalizeId)(t),delete this.schemas[t],delete this.refs[t]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else if("object"==typeof e&&void 0===t){if(Array.isArray(r=(t=e).keyword)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(C.call(this,r,t),!t)return(0,p.eachItem)(r,e=>R.call(this,e)),this;A.call(this,t);let i={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,p.eachItem)(r,0===i.type.length?e=>R.call(this,e,i):e=>i.type.forEach(t=>R.call(this,e,i,t))),this}getKeyword(e){let t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;for(let r of(delete t.keywords[e],delete t.all[e],t.rules)){let t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){let r=this.RULES.all;for(let i of(e=JSON.parse(JSON.stringify(e)),t)){let t=i.split("/").slice(1),a=e;for(let e of t)a=a[e];for(let e in r){let t=r[e];if("object"!=typeof t)continue;let{$data:i}=t.definition,n=a[e];i&&n&&(a[e]=O(n))}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];(!t||t.test(r))&&("string"==typeof i?delete e[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[r]))}}_addSchema(e,t,r,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let n,{schemaId:s}=this.opts;if("object"==typeof e)n=e[s];else if(this.opts.jtd)throw Error("schema must be object");else if("boolean"!=typeof e)throw Error("schema must be object or boolean");let o=this._cache.get(e);if(void 0!==o)return o;r=(0,u.normalizeId)(n||r);let c=u.getSchemaRefs.call(this,e,r);return o=new l.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:r,localRefs:c}),this._cache.set(o.schema,o),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=o),i&&this.validateSchema(e,!0),o}_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):l.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{l.compileSchema.call(this,e)}finally{this.opts=t}}}function x(e,t,r,i="error"){for(let a in e)a in t&&this.logger[i](`${r}: option ${a}. ${e[a]}`)}function k(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function _(){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 $(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function I(e){if(Array.isArray(e))return void this.addVocabulary(e);for(let t in this.logger.warn("keywords option as map is deprecated, pass array"),e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function S(){let e={...this.opts};for(let t of g)delete e[t];return e}w.ValidationError=n.default,w.MissingRefError=s.default,r.default=w;let E={log(){},warn(){},error(){}},T=/^[a-z_$][a-z0-9_$:-]*$/i;function C(e,t){let{RULES:r}=this;if((0,p.eachItem)(e,e=>{if(r.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!T.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 R(e,t,r){var i;let a=null==t?void 0:t.post;if(r&&a)throw Error('keyword with "post" flag cannot have "type"');let{RULES:n}=this,s=a?n.post:n.rules.find(({type:e})=>e===r);if(s||(s={type:r,rules:[]},n.rules.push(s)),n.keywords[e]=!0,!t)return;let o={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?P.call(this,s,o,t.before):s.rules.push(o),n.all[e]=o,null==(i=t.implements)||i.forEach(e=>this.addKeyword(e))}function P(e,t,r){let i=e.rules.findIndex(e=>e.keyword===r);i>=0?e.rules.splice(i,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function A(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=O(t)),e.validateSchema=this.compile(t,!0))}let D={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function O(e){return{anyOf:[e,D]}}},127296,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}}},418593,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.callRef=r.getValidate=void 0;let i=e.r(864592),a=e.r(899803),n=e.r(847550),s=e.r(424819),o=e.r(106981),l=e.r(303581);function c(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,n._)`${r.scopeValue("wrapper",{ref:t})}.validate`}function u(e,t,r,i){let{gen:o,it:c}=e,{allErrors:u,schemaEnv:d,opts:p}=c,m=p.passContext?s.default.this:n.nil;function h(e){let t=(0,n._)`${e}.errors`;o.assign(s.default.vErrors,(0,n._)`${s.default.vErrors} === null ? ${t} : ${s.default.vErrors}.concat(${t})`),o.assign(s.default.errors,(0,n._)`${s.default.vErrors}.length`)}function f(e){var t;if(!c.opts.unevaluated)return;let i=null==(t=null==r?void 0:r.validate)?void 0:t.evaluated;if(!0!==c.props)if(i&&!i.dynamicProps)void 0!==i.props&&(c.props=l.mergeEvaluated.props(o,i.props,c.props));else{let t=o.var("props",(0,n._)`${e}.evaluated.props`);c.props=l.mergeEvaluated.props(o,t,c.props,n.Name)}if(!0!==c.items)if(i&&!i.dynamicItems)void 0!==i.items&&(c.items=l.mergeEvaluated.items(o,i.items,c.items));else{let t=o.var("items",(0,n._)`${e}.evaluated.items`);c.items=l.mergeEvaluated.items(o,t,c.items,n.Name)}}i?function(){if(!d.$async)throw Error("async schema referenced by sync schema");let r=o.let("valid");o.try(()=>{o.code((0,n._)`await ${(0,a.callValidateCode)(e,t,m)}`),f(t),u||o.assign(r,!0)},e=>{o.if((0,n._)`!(${e} instanceof ${c.ValidationError})`,()=>o.throw(e)),h(e),u||o.assign(r,!1)}),e.ok(r)}():e.result((0,a.callValidateCode)(e,t,m),()=>f(t),()=>h(t))}r.getValidate=c,r.callRef=u,r.default={keyword:"$ref",schemaType:"string",code(e){var t,r;let a,s,l,d,{gen:p,schema:m,it:h}=e,{baseId:f,schemaEnv:g,validateName:y,opts:v,self:b}=h,{root:w}=g;if(("#"===m||"#/"===m)&&f===w.baseId){if(g===w)return u(e,y,g,g.$async);let t=p.scopeValue("root",{ref:w});return u(e,(0,n._)`${t}.validate`,w,w.$async)}let x=o.resolveRef.call(b,w,f,m);if(void 0===x)throw new i.default(h.opts.uriResolver,f,m);return x instanceof o.SchemaEnv?(a=c(e,t=x),void u(e,a,t,t.$async)):(r=x,s=p.scopeValue("schema",!0===v.code.source?{ref:r,code:(0,n.stringify)(r)}:{ref:r}),l=p.name("valid"),d=e.subschema({schema:r,dataTypes:[],schemaPath:n.nil,topSchemaRef:s,errSchemaPath:m},l),void(e.mergeEvaluated(d),e.ok(l)))}}},531442,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(127296),a=e.r(418593);r.default=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",i.default,a.default]},43884,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=i.operators,n={maximum:{okStr:"<=",ok:a.LTE,fail:a.GT},minimum:{okStr:">=",ok:a.GTE,fail:a.LT},exclusiveMaximum:{okStr:"<",ok:a.LT,fail:a.GTE},exclusiveMinimum:{okStr:">",ok:a.GT,fail:a.LTE}};r.default={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,i.str)`must be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,i._)`{comparison: ${n[e].okStr}, limit: ${t}}`},code(e){let{keyword:t,data:r,schemaCode:a}=e;e.fail$data((0,i._)`${r} ${n[t].fail} ${a} || isNaN(${r})`)}}},141432,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550);r.default={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>(0,i.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,i._)`{multipleOf: ${e}}`},code(e){let{gen:t,data:r,schemaCode:a,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),l=s?(0,i._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,i._)`${o} !== parseInt(${o})`;e.fail$data((0,i._)`(${a} === 0 || (${o} = ${r}/${a}, ${l}))`)}}},105028,(e,t,r)=>{"use strict";function i(e){let t,r=e.length,i=0,a=0;for(;a<r;)i++,(t=e.charCodeAt(a++))>=55296&&t<=56319&&a<r&&(64512&(t=e.charCodeAt(a)))==56320&&a++;return i}Object.defineProperty(r,"__esModule",{value:!0}),r.default=i,i.code='require("ajv/dist/runtime/ucs2length").default'},933076,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=e.r(303581),n=e.r(105028);r.default={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,i.str)`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>(0,i._)`{limit: ${e}}`},code(e){let{keyword:t,data:r,schemaCode:s,it:o}=e,l="maxLength"===t?i.operators.GT:i.operators.LT,c=!1===o.opts.unicode?(0,i._)`${r}.length`:(0,i._)`${(0,a.useFunc)(e.gen,n.default)}(${r})`;e.fail$data((0,i._)`${c} ${l} ${s}`)}}},719924,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(899803),a=e.r(303581),n=e.r(847550);r.default={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>(0,n.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,n._)`{pattern: ${e}}`},code(e){let{gen:t,data:r,$data:s,schema:o,schemaCode:l,it:c}=e,u=c.opts.unicodeRegExp?"u":"";if(s){let{regExp:i}=c.opts.code,s="new RegExp"===i.code?(0,n._)`new RegExp`:(0,a.useFunc)(t,i),o=t.let("valid");t.try(()=>t.assign(o,(0,n._)`${s}(${l}, ${u}).test(${r})`),()=>t.assign(o,!1)),e.fail$data((0,n._)`!${o}`)}else{let t=(0,i.usePattern)(e,o);e.fail$data((0,n._)`!${t}.test(${r})`)}}}},353744,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550);r.default={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,i.str)`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>(0,i._)`{limit: ${e}}`},code(e){let{keyword:t,data:r,schemaCode:a}=e,n="maxProperties"===t?i.operators.GT:i.operators.LT;e.fail$data((0,i._)`Object.keys(${r}).length ${n} ${a}`)}}},844738,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(899803),a=e.r(847550),n=e.r(303581);r.default={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>(0,a.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,a._)`{missingProperty: ${e}}`},code(e){let{gen:t,schema:r,schemaCode:s,data:o,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===r.length)return;let d=r.length>=u.loopRequired;if(c.allErrors?function(){if(d||l)e.block$data(a.nil,p);else for(let t of r)(0,i.checkReportMissingProp)(e,t)}():function(){let n=t.let("missing");if(d||l){let r=t.let("valid",!0);e.block$data(r,()=>{var l,c;return l=n,c=r,void(e.setParams({missingProperty:l}),t.forOf(l,s,()=>{t.assign(c,(0,i.propertyInData)(t,o,l,u.ownProperties)),t.if((0,a.not)(c),()=>{e.error(),t.break()})},a.nil))}),e.ok(r)}else t.if((0,i.checkMissingProp)(e,r,n)),(0,i.reportMissingProp)(e,n),t.else()}(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:i}=e.it;for(let e of r)if((null==t?void 0:t[e])===void 0&&!i.has(e)){let t=c.schemaEnv.baseId+c.errSchemaPath,r=`required property "${e}" is not defined at "${t}" (strictRequired)`;(0,n.checkStrictMode)(c,r,c.opts.strictRequired)}}function p(){t.forOf("prop",s,r=>{e.setParams({missingProperty:r}),t.if((0,i.noPropertyInData)(t,o,r,u.ownProperties),()=>e.error())})}}}},703884,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550);r.default={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,i.str)`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>(0,i._)`{limit: ${e}}`},code(e){let{keyword:t,data:r,schemaCode:a}=e,n="maxItems"===t?i.operators.GT:i.operators.LT;e.fail$data((0,i._)`${r}.length ${n} ${a}`)}}},197554,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(140804);i.code='require("ajv/dist/runtime/equal").default',r.default=i},18729,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(580581),a=e.r(847550),n=e.r(303581),s=e.r(197554);r.default={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>(0,a.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,a._)`{i: ${e}, j: ${t}}`},code(e){let{gen:t,data:r,$data:o,schema:l,parentSchema:c,schemaCode:u,it:d}=e;if(!o&&!l)return;let p=t.let("valid"),m=c.items?(0,i.getSchemaTypes)(c.items):[];e.block$data(p,function(){let o=t.let("i",(0,a._)`${r}.length`),l=t.let("j");e.setParams({i:o,j:l}),t.assign(p,!0),t.if((0,a._)`${o} > 1`,()=>(m.length>0&&!m.some(e=>"object"===e||"array"===e)?function(n,s){let o=t.name("item"),l=(0,i.checkDataTypes)(m,o,d.opts.strictNumbers,i.DataType.Wrong),c=t.const("indices",(0,a._)`{}`);t.for((0,a._)`;${n}--;`,()=>{t.let(o,(0,a._)`${r}[${n}]`),t.if(l,(0,a._)`continue`),m.length>1&&t.if((0,a._)`typeof ${o} == "string"`,(0,a._)`${o} += "_"`),t.if((0,a._)`typeof ${c}[${o}] == "number"`,()=>{t.assign(s,(0,a._)`${c}[${o}]`),e.error(),t.assign(p,!1).break()}).code((0,a._)`${c}[${o}] = ${n}`)})}:function(i,o){let l=(0,n.useFunc)(t,s.default),c=t.name("outer");t.label(c).for((0,a._)`;${i}--;`,()=>t.for((0,a._)`${o} = ${i}; ${o}--;`,()=>t.if((0,a._)`${l}(${r}[${i}], ${r}[${o}])`,()=>{e.error(),t.assign(p,!1).break(c)})))})(o,l))},(0,a._)`${u} === false`),e.ok(p)}}},155266,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=e.r(303581),n=e.r(197554);r.default={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>(0,i._)`{allowedValue: ${e}}`},code(e){let{gen:t,data:r,$data:s,schemaCode:o,schema:l}=e;s||l&&"object"==typeof l?e.fail$data((0,i._)`!${(0,a.useFunc)(t,n.default)}(${r}, ${o})`):e.fail((0,i._)`${l} !== ${r}`)}}},943835,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=e.r(303581),n=e.r(197554);r.default={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,i._)`{allowedValues: ${e}}`},code(e){let t,r,{gen:s,data:o,$data:l,schema:c,schemaCode:u,it:d}=e;if(!l&&0===c.length)throw Error("enum must have non-empty array");let p=c.length>=d.opts.loopEnum,m=()=>null!=t?t:t=(0,a.useFunc)(s,n.default);if(p||l)r=s.let("valid"),e.block$data(r,function(){s.assign(r,!1),s.forOf("v",u,e=>s.if((0,i._)`${m()}(${o}, ${e})`,()=>s.assign(r,!0).break()))});else{if(!Array.isArray(c))throw Error("ajv implementation error");let e=s.const("vSchema",u);r=(0,i.or)(...c.map((t,r)=>{var a,n;let s;return a=e,"object"==typeof(s=c[n=r])&&null!==s?(0,i._)`${m()}(${o}, ${a}[${n}])`:(0,i._)`${o} === ${s}`}))}e.pass(r)}}},207881,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(43884),a=e.r(141432),n=e.r(933076),s=e.r(719924),o=e.r(353744),l=e.r(844738),c=e.r(703884),u=e.r(18729),d=e.r(155266),p=e.r(943835);r.default=[i.default,a.default,n.default,s.default,o.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},d.default,p.default]},377129,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateAdditionalItems=void 0;let i=e.r(847550),a=e.r(303581);function n(e,t){let{gen:r,schema:n,data:s,keyword:o,it:l}=e;l.items=!0;let c=r.const("len",(0,i._)`${s}.length`);if(!1===n)e.setParams({len:t.length}),e.pass((0,i._)`${c} <= ${t.length}`);else if("object"==typeof n&&!(0,a.alwaysValidSchema)(l,n)){let n=r.var("valid",(0,i._)`${c} <= ${t.length}`);r.if((0,i.not)(n),()=>{var s;return s=n,void r.forRange("i",t.length,c,t=>{e.subschema({keyword:o,dataProp:t,dataPropType:a.Type.Num},s),l.allErrors||r.if((0,i.not)(s),()=>r.break())})}),e.ok(n)}}r.validateAdditionalItems=n,r.default={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,i.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,i._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:i}=t;Array.isArray(i)?n(e,i):(0,a.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}}},687976,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateTuple=void 0;let i=e.r(847550),a=e.r(303581),n=e.r(899803);function s(e,t,r=e.schema){let{gen:n,parentSchema:o,data:l,keyword:c,it:u}=e;(function(e){let{opts:i,errSchemaPath:n}=u,s=r.length,o=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(i.strictTuples&&!o){let e=`"${c}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${n}"`;(0,a.checkStrictMode)(u,e,i.strictTuples)}})(o),u.opts.unevaluated&&r.length&&!0!==u.items&&(u.items=a.mergeEvaluated.items(n,r.length,u.items));let d=n.name("valid"),p=n.const("len",(0,i._)`${l}.length`);r.forEach((t,r)=>{(0,a.alwaysValidSchema)(u,t)||(n.if((0,i._)`${p} > ${r}`,()=>e.subschema({keyword:c,schemaProp:r,dataProp:r},d)),e.ok(d))})}r.validateTuple=s,r.default={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return s(e,"additionalItems",t);r.items=!0,(0,a.alwaysValidSchema)(r,t)||e.ok((0,n.validateArray)(e))}}},891678,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(687976);r.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,i.validateTuple)(e,"items")}},864285,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=e.r(303581),n=e.r(899803),s=e.r(377129);r.default={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,i.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,i._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:o}=r;i.items=!0,(0,a.alwaysValidSchema)(i,t)||(o?(0,s.validateAdditionalItems)(e,o):e.ok((0,n.validateArray)(e)))}}},439254,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let i=e.r(847550),a=e.r(303581);r.default={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?(0,i.str)`must contain at least ${e} valid item(s)`:(0,i.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?(0,i._)`{minContains: ${e}}`:(0,i._)`{minContains: ${e}, maxContains: ${t}}`},code(e){let t,r,{gen:n,schema:s,parentSchema:o,data:l,it:c}=e,{minContains:u,maxContains:d}=o;c.opts.next?(t=void 0===u?1:u,r=d):t=1;let p=n.const("len",(0,i._)`${l}.length`);if(e.setParams({min:t,max:r}),void 0===r&&0===t)return void(0,a.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==r&&t>r){(0,a.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,a.alwaysValidSchema)(c,s)){let a=(0,i._)`${p} >= ${t}`;void 0!==r&&(a=(0,i._)`${a} && ${p} <= ${r}`),e.pass(a);return}c.items=!0;let m=n.name("valid");function h(){let e=n.name("_valid"),a=n.let("count",0);f(e,()=>n.if(e,()=>{var e;return e=a,void(n.code((0,i._)`${e}++`),void 0===r?n.if((0,i._)`${e} >= ${t}`,()=>n.assign(m,!0).break()):(n.if((0,i._)`${e} > ${r}`,()=>n.assign(m,!1).break()),1===t?n.assign(m,!0):n.if((0,i._)`${e} >= ${t}`,()=>n.assign(m,!0))))}))}function f(t,r){n.forRange("i",0,p,i=>{e.subschema({keyword:"contains",dataProp:i,dataPropType:a.Type.Num,compositeRule:!0},t),r()})}void 0===r&&1===t?f(m,()=>n.if(m,()=>n.break())):0===t?(n.let(m,!0),void 0!==r&&n.if((0,i._)`${l}.length > 0`,h)):(n.let(m,!1),h()),e.result(m,()=>e.reset())}}},34366,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.validateSchemaDeps=r.validatePropertyDeps=r.error=void 0;let i=e.r(847550),a=e.r(303581),n=e.r(899803);r.error={message:({params:{property:e,depsCount:t,deps:r}})=>(0,i.str)`must have ${1===t?"property":"properties"} ${r} when property ${e} is present`,params:({params:{property:e,depsCount:t,deps:r,missingProperty:a}})=>(0,i._)`{property: ${e},