@ai-development-environment/server 0.0.70 → 0.0.71

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 (41) hide show
  1. package/package.json +1 -1
  2. package/standalone/.next/BUILD_ID +1 -1
  3. package/standalone/.next/build-manifest.json +3 -3
  4. package/standalone/.next/prerender-manifest.json +3 -3
  5. package/standalone/.next/server/app/[locale]/comments/page_client-reference-manifest.js +1 -1
  6. package/standalone/.next/server/app/[locale]/pull-requests/page_client-reference-manifest.js +1 -1
  7. package/standalone/.next/server/app/_global-error.html +1 -1
  8. package/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  10. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/standalone/.next/server/app/_not-found.html +1 -1
  15. package/standalone/.next/server/app/_not-found.rsc +1 -1
  16. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  17. package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  18. package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  19. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  20. package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  21. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  22. package/standalone/.next/server/chunks/_01qtprx._.js +1 -1
  23. package/standalone/.next/server/chunks/_0l44maw._.js +2 -2
  24. package/standalone/.next/server/chunks/_0zi1rzc._.js +1 -1
  25. package/standalone/.next/server/chunks/_1czfvql._.js +2 -2
  26. package/standalone/.next/server/chunks/_1gtcfbz._.js +1 -1
  27. package/standalone/.next/server/chunks/_1kemdff._.js +2 -2
  28. package/standalone/.next/server/chunks/_21blfei._.js +2 -2
  29. package/standalone/.next/server/chunks/ssr/_1zd970o._.js +1 -1
  30. package/standalone/.next/server/chunks/ssr/src_components_github_pull-requests-page_tsx_1il3ga-._.js +3 -3
  31. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  32. package/standalone/.next/server/pages/404.html +1 -1
  33. package/standalone/.next/server/pages/500.html +1 -1
  34. package/standalone/.next/server/server-reference-manifest.js +1 -1
  35. package/standalone/.next/server/server-reference-manifest.json +1 -1
  36. package/standalone/.next/static/chunks/{19dkpj43f8v40.js → 0y408zh4mof6_.js} +7 -7
  37. package/standalone/.next/static/chunks/{3_rbnqkar9gd5.js → 3eqo76t2qsipq.js} +1 -1
  38. package/standalone/package.json +6 -5
  39. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_buildManifest.js +0 -0
  40. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_clientMiddlewareManifest.js +0 -0
  41. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_ssgManifest.js +0 -0
@@ -47,7 +47,7 @@ ${i}
47
47
  ${i}
48
48
  ~~~`}},sE=class{constructor(){(0,tG.__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")}},sI=class{constructor(){(0,tG.__publicField)(this,"nodeType","rule")}toMarkdown(e,t){return"---"}},sx=class{constructor(){(0,tG.__publicField)(this,"nodeType","hardBreak")}toMarkdown(e,t){return" \n"}},sA=class{constructor(){(0,tG.__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})`}},s_=class{constructor(){(0,tG.__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}},sC=class{constructor(){(0,tG.__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:"}},sR=class{constructor(){(0,tG.__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}}`}},sT=class{constructor(){(0,tG.__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})`}},sD=class{constructor(){(0,tG.__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"}},sN=class{constructor(){(0,tG.__publicField)(this,"nodeType","doc")}toMarkdown(e,t){let r=e.content||[];return t.convertChildren(r).trim()+"\n"}},sO=class{constructor(){(0,tG.__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}**`}},sP=class{constructor(){(0,tG.__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}*`}},s$=class{constructor(){(0,tG.__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}\``}},sU=class{constructor(){(0,tG.__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}},sB=class{constructor(){(0,tG.__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}~~`}},sj=class{constructor(){(0,tG.__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}},sL=class{constructor(){(0,tG.__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}},sq=class{constructor(){(0,tG.__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}},sM=class{constructor(){(0,tG.__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}},sF=class{constructor(e={}){(0,tG.__publicField)(this,"registry"),(0,tG.__publicField)(this,"validator"),(0,tG.__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 nY,this.validator=new nH,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 so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}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"):""}},sK=class{constructor(e={}){(0,tG.__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 nz||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
49
49
 
50
- ${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}]`}},sV=class{constructor(e){(0,tG.__publicField)(this,"mdToAdfEngine"),(0,tG.__publicField)(this,"adfToMdEngine"),(0,tG.__publicField)(this,"options"),(0,tG.__publicField)(this,"errorRecovery"),(0,tG.__publicField)(this,"remarkProcessor"),(0,tG.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new ss(this.options),this.adfToMdEngine=new sF(this.options),this.errorRecovery=new sK({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=ri().use(iD).use(a_,["yaml"]).use(n$).use(nV,{strict:e?.strict||!1}).use(am),this.registry=new nY,this.registerConverters()}catch(e){throw new nJ("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new sF({...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 ss({...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 nH().validate(e)}validateMarkdown(e){return new nW().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}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{}}},sG=e.i(378731);let sH=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function sW(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function sJ(e,t){return sG.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 sz=new sV;function sZ(e,t){if(null==e)return null;let r=function(e){if(sW(e))return"ADF";let t="string"==typeof e?e:"";return sH.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 sz.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?sJ(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:sG.default.to_jira(a)}}function sY(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?sJ(t):t,i=sz.markdownToAdf(r);if(!sW(i))throw Error("The Jira text could not be converted to valid ADF");return i}let sQ="default",sX=["summary","status","issuetype","priority","assignee","project","updated"],s0=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function s1(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function s2(e){return s1(e)?e:{}}function s3(e){return Array.isArray(e)?e:[]}function s4(e){return"string"==typeof e&&e.length>0?e:null}function s6(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function s8(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function s5(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function s9(e){return s3(s5(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function s7(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):s1(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function oe(e){if(!s1(e))return null;let t=e.status??s2(e.response).status;return"number"==typeof t?t:null}function ot(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function or(e){return s4(s2(s2(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function oi(e){let t=s2(e),r=s4(t.displayName);if(!r)return null;let i=s2(t.avatarUrls);return{accountId:s4(t.accountId),displayName:r,avatarUrl:s4(i["48x48"])??s4(i["32x32"])??s4(i["24x24"])}}function oa(e){return s3(e).map(s2).map(e=>({id:s4(e.id),name:s4(e.name)??"Unknown"}))}function on(e,t){let r=s2(e),i=s4(r.key);if(!i)return null;let a=s2(r.fields);return{relationship:t,key:i,summary:s4(a.summary)??i,status:s4(s2(a.status).name)}}function os(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function oo(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function ol(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 ou(e){let t=s2(e.fields),r=s2(t.status),i=s2(r.statusCategory),a=s2(t.assignee),n=s2(a.avatarUrls),s=s2(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:s4(t.summary)??o,statusId:s4(r.id)??s4(r.name)??"unknown",status:s4(r.name)??"Unknown",statusCategory:s4(i.key)??s4(i.name)??"unknown",issueType:s4(s2(t.issuetype).name),priority:s4(s2(t.priority).name),assignee:s4(a.displayName),assigneeAccountId:s4(a.accountId),assigneeAvatarUrl:s4(n["48x48"])??s4(n["32x32"]),projectKey:s4(s.key)??or(e),updatedAt:s4(t.updated)}}function oc(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let od=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function op(e){return od.has(e)?e:"ALL"}e.s(["JiraService",0,class{credentials;workflowEvents;inFlight;clients;lastPrunedAt;constructor(e=new tO.CredentialService,t){this.credentials=e,this.workflowEvents=t,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let r=e.comments.at(-1)??null,i={ticket:{key:e.key,title:e.summary,type:e.issueType,status:e.status,statusId:e.statusId,statusCategory:e.statusCategory,assignee:e.assignee,assigneeAccountId:e.assigneeAccountId,labels:e.labels,sprintNames:e.sprintNames,activeSprintNames:e.activeSprintNames,closedSprintNames:e.closedSprintNames,url:e.jiraUrl},comment:r?{id:r.id,body:r.content?.rawText??"",author:r.author}:null,...void 0!==t?{changelog:t}:{}},a=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,s=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",r?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",r?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&s.push(["JIRA_ASSIGNED_SELF",n]),t?.items.length){let e=new Set(t.items.flatMap(e=>[e.fieldId,e.field].filter(e=>!!e).map(e=>e.trim().toLowerCase()))),r=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&r.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&r.add("JIRA_LABEL"),e.has("assignee")&&r.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(r.add("JIRA_SPRINT_STARTED"),r.add("JIRA_SPRINT_ENDED")),s=s.filter(([e])=>r.has(e))}await Promise.allSettled(s.map(([t,r])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${a}`,payload:{...i,sessionData:i,cursorValue:r}})))}async getSettings(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,tD.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:sQ}}),n=e.apiToken?.trim()||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||!!n,l=async e=>{s&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,siteUrl:r,email:i,cacheTtlSeconds:300},update:s?{siteUrl:r,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:r,email:i}})};return n?await this.credentials.setText(tN.CREDENTIALS.jiraApiToken,n,l):await t.$transaction(l),s&&await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ},select:{siteUrl:!0,email:!0,webhookId:!0}}),r=await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&r)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==oe(e))throw e}return await this.credentials.deleteMany([tN.CREDENTIALS.jiraApiToken,tN.CREDENTIALS.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{email:null,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql: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,tD.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,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=s2(e.value);return{accountId:s4(t.accountId),displayName:s4(t.displayName)??"Jira user",emailAddress:s4(t.emailAddress),cache:oo(e)}}async listProjects(){let e=await (0,tD.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:op(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:s9(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??tF,sources:e.sources.map(os)}))}async projectStatuses(e){let t=await (0,tD.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 s3(i.value).map(s2))for(let t of s3(e.statuses).map(s2)){let e=s4(t.id),r=s4(t.name);if(!e||!r||a.has(e))continue;let i=s2(t.statusCategory);a.set(e,{id:e,name:r,category:s4(i.key)??s4(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>oc(e.category)-oc(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!od.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,tD.getPrismaClient)(),i=void 0===e.doneStatusId?void 0:e.doneStatusId?.trim()||null;if(i&&!(await this.projectStatuses(e.projectId)).some(e=>e.id===i))throw Error("The selected Jira done status is not available");return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t),...void 0===i?{}:{doneStatusId:i}}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await tV(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=>s3(s2(e).values).length}),i=s2(r.value),a=s3(i.values).map(s2);e.push(...a.flatMap(e=>{let t=s4(e.id),r=s4(e.key),i=s4(e.name);if(!t||!r||!i)return[];let a=s2(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:s4(a["48x48"])??s4(a["32x32"])}]}));let n=s6(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 i=s2((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),a=s4(i.key),n=s4(i.name),s=s4(i.id);if(!a||!n||!s)throw Error("Jira returned an incomplete project");let o=s2(i.avatarUrls),l=await (0,tD.getPrismaClient)(),u=await l.jiraProject.aggregate({_max:{position:!0}});return await l.jiraProject.create({data:{id:(0,r.randomUUID)(),jiraId:s,key:a,name:n,avatarUrl:s4(o["48x48"])??s4(o["32x32"]),position:(u._max.position??-1)+1,branchNamingScript:tF}}),this.listProjects()}async removeProject(e){let t=await (0,tD.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),i=this.validateSourceName(e.name),a=await (0,tD.getPrismaClient)();if(!await a.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let n=await a.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await a.jiraSource.create({data:{id:(0,r.randomUUID)(),projectId:e.projectId,name:i,kind:e.kind,value:t.value,boardId:t.boardId,position:(n._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,tD.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,tD.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,tD.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l=await s.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),u=new Set(l?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===o.kind?await this.loadBoardSource(os(o),t):await this.loadJqlSource(os(o),t),d={ticketAssignmentFilter:op(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:s9(o.project.completedStatusIdsJson)},p="ALL"===d.ticketAssignmentFilter?null:await this.currentAccountId(),h=(r={source:os(o),...c},i=d.hideCompletedTickets?new Set(d.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"===d.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===d.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===p:null!==p&&e.assigneeAccountId===p&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))});return this.workflowEvents&&l&&await Promise.allSettled(h.tickets.filter(({key:e})=>!u.has(e)).map(t=>{let r={ticket:{key:t.key,title:t.summary,type:t.issueType,status:t.status,statusId:t.statusId,statusCategory:t.statusCategory,assignee:t.assignee}};return this.workflowEvents.record({kind:"JIRA_SOURCE_NEW_TICKET",subjectKey:`${e}:${t.key}`,dedupeKey:`jira-source-new:${e}:${t.key}:${h.cache.fetchedAt}`,payload:{...r,sessionData:r,source:{id:e,name:o.name,kind:o.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,r){let i=s8(e),a=await this.cachedCall({operation:"ISSUE",params:{issueKey:i,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${i} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:i,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===a.source&&await this.storeDetail(a.entryId,a.value,a.fetchedAt);let n=[],s=[],o=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:o,maxResults:100},requestSummary:`Comments for ${i} from ${o}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:o,maxResults:100,orderBy:"created"})},itemCount:e=>s3(s2(e).comments).length});n.push(e);let r=s2(e.value),a=s3(r.comments);s.push(...a);let l=s6(r.total)??s.length;if(0===a.length||s.length>=l)break;o+=a.length}let l=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,s,l,n.map(e=>e.entryId));let u=await this.requireCredentials(),c=this.normalizeTicketDetail(a.value,s,u.siteUrl,oo(a),ol(n));return await this.recordTicketWorkflowEvents(c,r),c}async assignableUsers(e,t=""){let r=s8(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=>s3(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),s3(a.value).map(oi).filter(e=>null!==e)}async ticketTransitions(e){let t=s8(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=>s3(s2(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),s3(s2(r.value).transitions).map(s2).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=s4(e.id),r=s4(e.name);if(!t||!r)return[];let i=s2(e.to),a=s2(i.statusCategory),n=Object.entries(s2(e.fields)).filter(([,e])=>!0===s2(e).required).map(([e,t])=>s4(s2(t).name)??e);return[{id:t,name:r,toStatusId:s4(i.id),toStatus:s4(i.name)??r,toStatusCategory:s4(a.key)??s4(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=s8(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(s2(s2(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(s2(s2(r.value).fields)).map(([e,t])=>{let r=s2(t);return{id:e,name:s4(r.name)??e,required:!0===r.required,schemaType:s4(s2(r.schema).type),allowedValues:s3(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=s2(e),r=s4(t.name)??s4(t.value)??s4(t.displayName)??s4(t.key);return r?[{id:s4(t.id)??s4(t.accountId)??s4(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Changelog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Changelog for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=s3(s2(c.value).values).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),createdAt:s4(e.created),items:s3(e.items).map(s2).map(e=>({field:s4(e.field)??"Field",fieldId:s4(e.fieldId),from:s4(e.fromString)??s4(e.from),to:s4(e.toString)??s4(e.to)}))}));return{...n,total:o,items:d,cache:ol([s,c])}}async ticketWorklogs(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Worklog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Worklogs for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=await this.requireCredentials(),p=s3(s2(c.value).worklogs).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),comment:sZ(e.comment??null,d.siteUrl),timeSpent:s4(e.timeSpent),timeSpentSeconds:s6(e.timeSpentSeconds),startedAt:s4(e.started),createdAt:s4(e.created),updatedAt:s4(e.updated)})),h=p[0];if(this.workflowEvents&&h){let e={ticket:{key:a},worklog:{id:h.id,author:h.author,timeSpent:h.timeSpent,timeSpentSeconds:h.timeSpentSeconds,startedAt:h.startedAt,updatedAt:h.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:a,dedupeKey:`jira-worklog:${a}:${h.id}:${c.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:h.id}})}return{...n,total:o,items:p,cache:ol([s,c])}}async addComment(e,t){let r=s8(e);if(!t.value.trim())throw Error("Comment text is required");let i=sY(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=s8(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=s8(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 transitionTicketToConfiguredDone(e){let t=s8(e),r=t.split("-")[0]??"",i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{doneStatusId:!0}});if(!a?.doneStatusId)throw Error(`Configure a done status for Jira project ${r} before using this option`);let n=await this.ticket(t);if(n.statusId===a.doneStatusId)return n;let s=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===a.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!s)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,s.id)}async updateTicket(e){let t=s8(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=sY(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 createTicket(e){let t=e.projectKey.trim().toUpperCase(),r=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!r||!i)throw Error("Project, issue type, and summary are required");let{version3:a}=await this.getClients(),n=await a.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:r},summary:i,...e.description?{description:sY(e.description)}:{}}});if(!n.key)throw Error("Jira did not return the created issue key");return this.ticket(n.key,!0)}async addWorklog(e){let t=s8(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:r}=await this.getClients();return await r.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:sY(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=s8(e.inwardIssueKey),r=s8(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:a}=await this.getClients();return await a.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:r}}),this.ticket(t,!0)}async branchTicket(e){let t=s8(e),r=t.replace(/-\d+$/,""),i=await (0,tD.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=s2(n.value.fields);if((s4(s2(s.project).key)??or(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:s4(s.summary)??t,ticketType:s4(s2(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??tF}}async clearCache(){let e=await (0,tD.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await (0,tD.getPrismaClient)();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(s8(e)),!0}async invalidateIssueCaches(e){let t=await (0,tD.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,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await r.jiraCacheEntry.deleteMany({where:{id:{in:i.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0,t)}async resolveIssueKeys(e){let t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===t.length)return[];let{version3:r}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>r.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=s4(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return s8(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),r=[],i=0;for(;r.length<1e3;){let a=Math.min(100,1e3-r.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:a,fields:["key"]}),s=n.issues??[];r.push(...s.flatMap(e=>{let t=s4(e.key);return t?[s8(t)]:[]}));let o=void 0===n.total?s.length<a:i+s.length>=n.total;if(0===s.length||o)break;i+=s.length}let a=[],n=[...new Set(r)];for(let e=0;e<n.length;e+=5)a.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return a}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,tD.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,tD.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:s5(r.summaryJson),detailData:s5(r.detailJson),commentsData:s5(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,tD.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,tD.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-s0.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:s0.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:s0.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let r=await this.credentials.getText(tN.CREDENTIALS.jiraApiToken);if(!r)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:r,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,r.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let i={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new tT(i),agile:new q(i)},this.clients}async webhookApiRequest(e,t,r){let i,a=await this.requireCredentials(),n=Buffer.from(`${a.email}:${a.apiToken}`).toString("base64");try{i=await fetch(`${a.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===r?void 0:JSON.stringify(r),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(ot(e,a.apiToken))}let s=await i.text();if(!i.ok){let e=s.trim().slice(0,300)||i.statusText;throw Object.assign(Error(ot(`Jira rejected the webhook request with ${i.status}: ${e}`,a.apiToken)),{status:i.status})}if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}async currentAccountId(){let e=s4(s2((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,tD.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=ot(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:oe(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: ${ot(e,i.apiToken)}`)}}cacheKey(e,t,i){return(0,r.createHash)("sha256").update(s7({siteUrl:e,operation:t,params:i})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),i=await (0,tD.getPrismaClient)(),a=this.cacheKey(t.siteUrl,e.operation,e.params),n=Date.now(),s=await i.jiraCacheEntry.findUnique({where:{cacheKey:a}}),o=null!==s&&Date.now()-s.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&o)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(s5(s.responseJson))??null,sourceId:e.sourceId}),{value:s5(s.responseJson),source:"CACHE",stale:!1,fetchedAt:s.fetchedAt,entryId:s.id};let l=this.inFlight.get(a);if(l){let t=await l;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let u=(async()=>{try{let t=await e.fetcher(),s=new Date,o=await i.jiraCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,r.randomUUID)(),cacheKey:a,operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:s,entryId:o.id}}catch(i){let r=null!==s&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-n,statusCode:oe(i),error:ot(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:s5(s.responseJson),source:"ERROR",stale:!0,fetchedAt:s.fetchedAt,entryId:s.id};throw Error(ot(i,t.apiToken))}})();this.inFlight.set(a,u);try{return await u}finally{this.inFlight.delete(a)}}async logCall(e){let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,r.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:sX},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:sX})},itemCount:e=>e.issues?.length??0});a.push(l);let u=l.value.issues??[];i.push(...u),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,u,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"===(s4(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=>s3(e.values).length});a.push(r);let i=s3(r.value.values).map(s2);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=s6(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:sX}),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:sX}),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()],u=new Map;return s3(s2(i.value.columnConfig).columns).map(s2).forEach((e,t)=>{s3(e.statuses).map(s2).forEach(e=>{let r=s4(e.id);r&&u.set(r,t)})}),this.buildBoardResult(l,a,s,o,u)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],u=0,c=1/0,d=!1;for(;u<c&&s.length+n<1e3;){let d=i(u,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${u}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let h=p.value.issues??[];if(s.push(...h),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,h,p.fetchedAt),c=p.value.total??s.length,0===h.length)break;u+=h.length}return s.length+n>=1e3&&u<c&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(ou),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):oc(e.statusCategory)-oc(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:ol(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,tD.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:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:or(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,tD.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:or(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,tD.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,i,a,n){let s=ou(e),o=s2(e.fields),l=s2(e.names),u=s2(e.schema),c=[];for(let e of s3(o.issuelinks).map(s2)){let t=s2(e.type),r=on(e.outwardIssue,s4(t.outward)??"relates to"),i=on(e.inwardIssue,s4(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let d=on(o.parent,"parent"),p=s3(o.subtasks).map(e=>on(e,"subtask")).filter(e=>null!==e),h=s3(o.sprint).map(s2),m=s3(o.closedSprints).map(s2),f=h.filter(e=>{let t=s4(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>s4(e.name)).filter(e=>!!e),g=m.concat(h.filter(e=>s4(e.state)?.toLowerCase()==="closed")).map(e=>s4(e.name)).filter(e=>!!e),y=f.concat(g),w=t.map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),body:e.body??null,content:sZ(e.body??null,i),createdAt:s4(e.created),updatedAt:s4(e.updated)}));return{...s,jiraUrl:`${i}/browse/${s.key}`,description:o.description??null,descriptionContent:sZ(o.description??null,i),reporter:oi(o.reporter),creator:oi(o.creator),labels:s3(o.labels).filter(e=>"string"==typeof e),components:oa(o.components),fixVersions:oa(o.fixVersions),affectedVersions:oa(o.versions),sprintNames:[...new Set(y)],activeSprintNames:[...new Set(f)],closedSprintNames:[...new Set(g)],parent:d,subtasks:p,issueLinks:c,attachments:s3(o.attachment).map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),filename:s4(e.filename)??"Attachment",contentUrl:s4(e.content),mimeType:s4(e.mimeType),size:s6(e.size),author:oi(e.author),createdAt:s4(e.created)})),comments:w,createdAt:s4(o.created),dueAt:s4(o.duedate),resolvedAt:s4(o.resolutiondate),timeTracking:o.timetracking??null,allFields:Object.entries(o).map(([e,t])=>{let r=s2(u[e]),a="string"==typeof t||s1(t)&&"doc"===t.type?sZ(t,i):null;return{id:e,name:s4(l[e])??e,schemaType:s4(r.type),custom:!0===r.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:a,commentsCache:n}}cachedTicketView(e,t){let r=ou(s2(s5(e.detailJson)??s5(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,tD.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],126223);var oh=e.i(661983);let om="default",of=/^[A-Z][A-Z0-9_]*-\d+$/,og=new Set(["jira:issue_created","jira:issue_updated","comment_created","comment_updated","comment_deleted","worklog_created","worklog_updated","worklog_deleted","jira:worklog_updated","attachment_created","attachment_deleted","issuelink_created","issuelink_deleted","sprint_started","sprint_closed"]),oy={"jira:issue_created":"JIRA_ISSUE_CREATED","jira:issue_deleted":"JIRA_ISSUE_DELETED",comment_created:"JIRA_ISSUE_COMMAND",attachment_created:"JIRA_ATTACHMENT_ADDED",issuelink_created:"JIRA_ISSUE_LINKED"},ow="/api/public/jira/webhook",ob="/rest/webhooks/1.0/webhook",ov=new Set(["localhost","0.0.0.0","::1","[::1]",""]),ok=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class oS extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function oE(e){return"string"==typeof e&&e.trim()?e.trim():null}function oI(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function ox(e){let t=oA(e);if(!t)return null;let r=Array.isArray(t.items)?t.items:[];return{id:oI(t.id),items:r.map(oA).filter(e=>null!==e).map(e=>({field:oE(e.field)??oE(e.fieldId)??"Field",fieldId:oE(e.fieldId),fieldType:oE(e.fieldtype)??oE(e.fieldType),from:oI(e.from),fromString:oI(e.fromString),to:oI(e.to),toString:oI(e.toString)}))}}function oA(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function o_(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function oC(e){let t=oA(e);return t?{accountId:oE(t.accountId),displayName:oE(t.displayName)}:null}function oR(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return ox(JSON.parse(e))}catch{return null}}(e.changelogJson),retryCount:e.retryCount,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null}}e.s(["JiraWebhookRequestError",0,oS,"JiraWebhookService",0,class{jira;credentials;workflowEvents;constructor(e,t,r){this.jira=e,this.credentials=t,this.workflowEvents=r}async webhooksEnabled(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret)}async getWebhookSettings(){let e=await (0,tD.getPrismaClient)(),[t,r,i]=await Promise.all([e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{}}),this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&r,secretConfigured:r,registered:!!t.webhookId,registrationId:t.webhookId??null,registeredUrl:t.webhookUrl??null,jql:t.webhookJql??null,configuredAt:t.webhookConfiguredAt?.toISOString()??null,lastReceivedAt:i?.receivedAt.toISOString()??null,lastOutcome:i?.outcome??null,lastError:i?.error??null}}async enableWebhook(){let e=(0,r.randomBytes)(32).toString("base64url");return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date},update:{webhookEnabled:!0,webhookConfiguredAt:new Date}})}),{settings:await this.getWebhookSettings(),secret:e}}async registerWebhook(e){let t=function(e){let t;try{t=new URL(e.trim())}catch{throw Error("Enter the public URL of this server")}if("https:"!==t.protocol&&"http:"!==t.protocol)throw Error("The webhook URL must use HTTP or HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("The webhook URL must not include credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ov.has(r)||r.endsWith(".local")||r.endsWith(".localhost")||/^127\./.test(r)||/^10\./.test(r)||/^192\.168\./.test(r)||/^172\.(1[6-9]|2\d|3[01])\./.test(r))throw Error(`Jira cannot reach ${t.host}. Expose this server publicly, or set PUBLIC_BASE_URL to its public address.`);let i=t.pathname.replace(/\/+$/,"");if(!i)return`${t.origin}${ow}`;if(i.endsWith(ow))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${ow}`)}(e.url),i=e.jql?.trim()||null,a=(0,r.randomBytes)(32).toString("base64url"),n=await (0,tD.getPrismaClient)(),s=await n.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}}),o=await this.writeToJira({webhookId:s?.webhookId??null,url:t,jql:i,secret:a});return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,a,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i}})}),{settings:await this.getWebhookSettings(),secret:a}}async rotateSecret(){if(!await this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0,webhookUrl:!0,webhookJql:!0}});return t?.webhookId&&t.webhookUrl?this.registerWebhook({url:t.webhookUrl,jql:t.webhookJql}):this.enableWebhook()}async disableWebhook(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,r,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...ok],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${ob}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==o_(e))throw e}}let a=await this.jira.webhookApiRequest("POST",ob,i),n=(t=oE(a?.self),(r=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(r):null);if(!n)throw Error("Jira did not return the ID of the new webhook");return n}async deleteFromJira(e){try{await this.jira.webhookApiRequest("DELETE",`${ob}/${encodeURIComponent(e)}`)}catch(e){if(404!==o_(e))throw e}}async deliveries(e=50,t=0){if(!Number.isInteger(e)||e<1||e>100)throw Error("Limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Offset must be a non-negative integer");let r=await this.webhooksEnabled();if(!r)return{enabled:r,items:[],total:0,limit:e,offset:t};let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:r,items:a.map(oR),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await (0,tD.getPrismaClient)();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await (0,tD.getPrismaClient)();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,i,a,n,s,o;let l,u,c=await this.credentials.getText(tN.CREDENTIALS.jiraWebhookSecret);if(!c)throw new oS("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new oS("Jira webhook signature is missing",401);if(t=`sha256=${(0,r.createHmac)("sha256",c).update(e.body).digest("hex")}`,i=e.signature,l=Buffer.from(t),u=Buffer.from(i),!(l.length===u.length&&(0,r.timingSafeEqual)(l,u)))throw new oS("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new oS("Jira delivery ID is missing",400);let d=await (0,tD.getPrismaClient)(),p=e.deliveryId.trim(),h=Number.parseInt(e.retryCount??"",10),m=Number.isInteger(h)?h:null;try{await d.jiraWebhookDelivery.create({data:{deliveryId:p,event:"unknown",outcome:"RECEIVED",retryCount:m}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await d.jiraWebhookDelivery.updateMany({where:{deliveryId:p,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:m,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return await this.prune().catch(()=>void 0),{outcome:"DUPLICATE",event:null,issueKey:null,triggersRecorded:0}}let f=async(e,t=null)=>{let r=await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{outcome:e,error:t,processedAt:new Date}});oh.agentEventBus.publish(oh.JIRA_WEBHOOK_DELIVERY_TOPIC,{jiraWebhookDeliveryChanged:oR(r)})};try{let t,r,i,l,u,c;try{let r=JSON.parse(Buffer.from(e.body).toString("utf8")),i=oA(r);if(!i)throw Error("Payload is not an object");t=i}catch{throw new oS("Jira webhook payload is invalid JSON",400)}let h=oE(t.webhookEvent),g=(a=t,r=oA(a.issue),(i=oE(r?.key)?.toUpperCase()??null)&&of.test(i)?i:null),y=(n=t,l=oA(n.issue),u=oA(l?.fields),c=oA(u?.project)??oA(n.project),oE(c?.key)?.toUpperCase()??null),w=ox(t.changelog);if(await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{event:h??"unknown",issueKey:g,projectKey:y,changelogJson:w?JSON.stringify(w):null}}),!h)return await f("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};if(!(og.has(h)||"jira:issue_deleted"===h))return await f("IGNORED",`Unhandled Jira event ${h}`),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let b=g?[g]:[];if("issuelink_created"===h||"issuelink_deleted"===h){let e,r,i=(s=t,e=oA(s.issueLink),[oI(e?.sourceIssueId),oI(e?.destinationIssueId)].filter((e,t,r)=>!!(e&&r.indexOf(e)===t)));if(0===i.length)return await f("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};y=(g=(b=await this.jira.resolveIssueKeys(i))[0]??null)?y??((r=(o=g).lastIndexOf("-"))>0?o.slice(0,r):null):y,await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{issueKey:g,projectKey:y}})}let v="sprint_started"===h||"sprint_closed"===h;if(!v&&!g)return await f("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let k=[];if("jira:issue_deleted"===h)await this.jira.deleteCachedTicket(g),k.push({key:g,projectKey:y});else if(v){let e=function(e){let t=oI(oA(e.sprint)?.id);if(!t)return null;let r=Number(t);return Number.isSafeInteger(r)&&r>0?r:null}(t);if(!e)return await f("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let r=await this.jira.refreshSprintTickets(e);k.push(...r.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===h){let e=await this.jira.refreshCachedTicket(g,w);k.push({key:e.key,projectKey:e.projectKey})}else if(og.has(h)){let e=await Promise.all(b.map(e=>this.jira.refreshCachedTicket(e)));k.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let S=g?await this.recordWebhookTrigger({event:h,deliveryId:p,issueKey:g,projectKey:y,retries:m,payload:t}):0;for(let e of k)oh.agentEventBus.publish(oh.JIRA_TICKET_CHANGED_TOPIC,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:h}});return await f("PROCESSED"),{outcome:"PROCESSED",event:h,issueKey:g,triggersRecorded:S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await f("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=oy[e.event];if(!t)return 0;let{payload:r}=e,i=oA(r.issue),a=oA(i?.fields),n=oA(r.comment),s=oA(r.attachment),o=oA(r.issueLink),l=oA(a?.status),u=ox(r.changelog),c={ticket:{key:e.issueKey,title:oE(a?.summary),type:oE(oA(a?.issuetype)?.name),status:oE(l?.name),statusId:oE(l?.id),statusCategory:oE(oA(l?.statusCategory)?.key),assignee:oE(oA(a?.assignee)?.displayName),assigneeAccountId:oE(oA(a?.assignee)?.accountId),labels:Array.isArray(a?.labels)?a.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:oE(n.id),body:oE(n.body)??"",author:oC(n.author)}:null,attachment:s?{id:oE(s.id),filename:oE(s.filename),mimeType:oE(s.mimeType),author:oC(s.author)}:null,link:o?{id:oE(o.id),type:oE(oA(o.issueLinkType)?.name),sourceIssueId:oE(o.sourceIssueId),destinationIssueId:oE(o.destinationIssueId)}:null,user:oC(r.user),changelog:u};return+!!await this.workflowEvents.record({kind:t,subjectKey:e.issueKey,dedupeKey:`jira-webhook-trigger:${e.deliveryId}:${t}`,payload:{...c,sessionData:c,cursorValue:`${e.deliveryId}:${t}`,webhook:{event:e.event,deliveryId:e.deliveryId,retryCount:e.retries}}})}},"subscribeJiraTicketChanges",0,function(){return oh.agentEventBus.iterate(oh.JIRA_TICKET_CHANGED_TOPIC)},"subscribeJiraWebhookDeliveries",0,function(){return oh.agentEventBus.iterate(oh.JIRA_WEBHOOK_DELIVERY_TOPIC)}],642983),e.s([],151666)},107058,963910,112627,695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(582482);var i=e.i(318905),a=e.i(91022),n=e.i(397554),s=e.i(827957);function o(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function l(e){let t=o(e.get("x-ratelimit-limit")),r=o(e.get("x-ratelimit-remaining")),i=o(e.get("x-ratelimit-used")),a=o(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===r||null===i||null===a||!n)return null;let s=new Date(1e3*a);return Number.isFinite(s.getTime())?{limit:t,remaining:r,used:i,resetAt:s,resource:n}:null}async function u(e,t){let i=l(t.headers);if(!i)return null;try{let t=await (0,r.getPrismaClient)(),a=`${e}:${i.resource}`,n=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:i.resource}},create:{id:a,authentication:e,observedAt:n,...i},update:{observedAt:n,...i}})}catch{}return i}async function c(){let e=await (0,r.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}let d="actions.cancelWorkflowRun",p="actions.dispatchWorkflow",h="actions.forceCancelWorkflowRun",m="actions.getJobForWorkflowRun",f="actions.getWorkflowRun",g="actions.getWorkflowRunAttempt",y="actions.listJobsForWorkflowRun",w="actions.listJobsForWorkflowRunAttempt",b="actions.listRepoWorkflows",v="actions.listWorkflowRuns",k="actions.listWorkflowRunsForRepo",S="actions.reRunJobForWorkflowRun",E="actions.reRunWorkflow",I="actions.reRunWorkflowFailedJobs",x="apps.createInstallationAccessToken",A="apps.getAuthenticated",_="apps.getInstallation",C="apps.updateWebhookConfigForApp",R="repos.listPullRequestsAssociatedWithCommit",T="users.listEmailsForAuthenticatedUser";class D extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let N=new Map,O=new Map;function P(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D(r,`${t} must be a positive integer`);return i}function $(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:P(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:P(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function U(e){try{let t=await (0,n.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new s.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function B(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function j(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function L(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),u=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:l(n.headers)})).catch(()=>void 0),n}async function q(e){try{return await e.json()}catch{return null}}function M(e){return e.headers.get("x-github-request-id")}function F(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function K(e,t){let r=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:j(`Bearer ${t}`)},_,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new D("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function V(e,t){let r=await L(`${e.apiBaseUrl}/app`,{headers:j(`Bearer ${t}`)},A,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function G(e){let t=$(e),r=await U(t),i=await V(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function H(e,t,r){let i=r??await U(e),a=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:j(`Bearer ${i}`)},x,e,t),n=await q(a),s=M(a);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new D("GITHUB_APP_REQUEST_FAILED",F(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new D("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function W(e,t){let r=B(e),i=N.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=O.get(r);if(a)return a;let n=H(e,t).then(e=>(N.set(r,e),e)).finally(()=>O.delete(r));return O.set(r,n),n}function J(){N.clear(),O.clear()}async function z(e,t,r){let i=$(e),a=await W(i,r),n=await t(a.token);return 401===n.status&&(N.delete(B(i)),a=await W(i,r),n=await t(a.token)),{response:n,token:a.token}}async function Z(e,t,r,i){let{response:a,token:n}=await z(e,a=>L(e.graphqlUrl,{method:"POST",headers:{...j(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await q(a),o=M(a),u=l(a.headers);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,u);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||F(s,a.status,[n]);throw new D("GITHUB_APP_REQUEST_FAILED",F({message:t},a.status,[n,e.privateKey]),o,a.status,u)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:u}}async function Y(e){let t=$(e),r=await U(t),[i,a]=await Promise.all([K(t,r),V(t,r)]),n=await H(t,"GITHUB_SETTINGS",r);N.set(B(t),n);let s=await Z(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function Q(e,t){let r=$(e),i=await U(r),a=await L(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...j(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},C,r,"GITHUB_SETTINGS"),n=M(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new D("GITHUB_APP_REQUEST_FAILED",F(await q(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function X(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},E,e,t.requestSource),t.requestSource),n=M(i);if(401===i.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function ee(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},I,e,t.requestSource),t.requestSource),n=M(i);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function et(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?h:d,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await z(e,r=>L(a,{method:"POST",headers:j(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=M(n);if(401===n.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await q(n);throw new D(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":F(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function er(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await z(e,r=>L(n,{headers:j(`Bearer ${r}`)},y,e,t.requestSource),t.requestSource),l=M(s);if(401===s.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await q(s);if(!s.ok||!u||"object"!=typeof u)throw new D("GITHUB_APP_REQUEST_FAILED",F(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function ei(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await z(e,r=>L(i,{headers:j(`Bearer ${r}`)},m,e,t.requestSource),t.requestSource),n=M(a.response);if(401===a.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await q(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new D(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":F(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new D("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new D("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await z(e,r=>L(`${i}/rerun`,{method:"POST",headers:j(`Bearer ${r}`)},S,e,t.requestSource),t.requestSource),l=M(o.response);if(401===o.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await q(o.response);throw new D(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":F(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let ea=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),en=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),es=["COMPLETED","EXHAUSTED","STOPPED"],eo={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},el="server:github-auto-retry";function eu(e){return e.toISOString()}function ec(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:eu(e.updatedAt)})),createdAt:eu(e.createdAt),updatedAt:eu(e.updatedAt)}}class ed{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:el,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(el,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(el,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(el,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(ec)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=en.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":ea.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:es}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||eo[e.scope]>eo[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(en.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>ea.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>es.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.i(805422);var ep=e.i(661983);let eh={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},em=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),ef=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),eg=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function ey(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>em.has(e))?"FAILURE":e.some(e=>ef.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>eg.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function ew(e,t){let r=(t||e||"NONE").toUpperCase();return ek(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"}function eb(e){return ef.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function ev(e,t,r){let i=e.runAttempt??0,a=t.runAttempt??0;if(a!==i)return a>i;let n=e.githubUpdatedAt?.getTime()??0,s=t.githubUpdatedAt?.getTime()??0;if(s!==n)return s>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let o="MUTATION"===e.source?eh.LEGACY:eh[e.source],l=eh[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=eb(e.status),i=eb(t.status);if(i!==r)return i>r}return l===o||l>o}function ek(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function eS(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function eE(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function eI(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function ex(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function eA(e){return{id:e.githubPipelineId,name:e.name,status:ek(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:eE(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function e_(e,t){return{...eA(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function eC(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:eS(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(eA).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function eR(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function eT(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(eR).sort((e,t)=>e.localeCompare(t))})}class eD{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?eC(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(eC)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>e_(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let l=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===l.length)return e_({...o.snapshot,records:[o]},o);let u=eE(o.jobsJson),c=new Map(u.map(e=>[e.id,e])),d=l.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=eI(e.status),n=eI(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(c.get(e.id),e)),p="WEBHOOK"===a?[...new Map([...u,...d].map(e=>[e.id,e])).values()]:d,h=ek(o.status)?o.status:"NONE",m="REST"===a&&l.length>0?ey(l.map(e=>e.status),null):"NONE",f=("ERROR"===m||"FAILURE"===m||"SUCCESS"===m)&&o.snapshot.graphqlRollupStatus===m?m:h;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...eA(o),status:f,source:a,jobs:p,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...eA(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let i=e.repositoryGithubId.trim(),a=e.headSha.trim();if(!i||!a)throw Error("GitHub repository ID and head SHA are required");let n=new Date,s=e.sourceFetchedAt??n,o=await (0,r.getPrismaClient)(),l=await o.$transaction(async r=>{let o=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:i,headSha:a}},create:{id:(0,t.randomUUID)(),repositoryGithubId:i,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:a,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:n},update:{lastObservedAt:n},include:{records:!0}}),l=eT(o),u=!!(e.completeGraphqlRollup&&(!o.lastGraphqlSyncAt||s.getTime()>=o.lastGraphqlSyncAt.getTime())),c=new Set,d=null;for(let i of e.pipelines){let e=function(e){var t;return(t={id:e.id,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,statusContext:e.statusContext}).checkSuiteId?`CHECK_SUITE:${t.checkSuiteId}`:t.workflowRunId?`WORKFLOW_RUN:${t.workflowRunId}`:t.statusContext?`STATUS_CONTEXT:${t.statusContext}`:`PIPELINE:${t.id}`}(i),a=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}})).filter(t=>t.identityKey===e||i.checkSuiteId&&t.checkSuiteId===i.checkSuiteId||i.workflowRunId&&t.workflowRunId===i.workflowRunId),l=a[0]??null;for(let e of a.slice(1))l&&ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:ex(e.source),status:ek(e.status)?e.status:"NONE"},n)&&(l=e);for(let e of a)l&&e.id!==l.id&&(0===eE(l.jobsJson).length&&eE(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),d=l.id);let p=i.sourceFetchedAt??s,h=i.githubUpdatedAt??null,m=void 0===i.runAttempt?l?.runAttempt??null:i.runAttempt,f=void 0!==i.jobs?JSON.stringify(i.jobs):l&&(m??0)<=(l.runAttempt??0)?l.jobsJson:"[]",g=!!u||(!1===i.isCurrent?l?.isCurrent??!1:i.isCurrent??l?.isCurrent??!0);if(l){c.add(l.id);let t=eR(l),a=ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:m,githubUpdatedAt:h,source:i.source,status:i.status},n),s=!!(!a&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>n.getTime()&&"MUTATION"!==i.source);t!==eR(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:a?{identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:void 0===i.url?l.url:i.url,checkSuiteId:void 0===i.checkSuiteId?l.checkSuiteId:i.checkSuiteId,workflowRunId:void 0===i.workflowRunId?l.workflowRunId:i.workflowRunId,workflowId:void 0===i.workflowId?l.workflowId:i.workflowId,runNumber:void 0===i.runNumber?l.runNumber:i.runNumber,runAttempt:m,canRetry:void 0===i.canRetry?l.canRetry:i.canRetry,retryUnavailableReason:void 0===i.retryUnavailableReason?l.retryUnavailableReason:i.retryUnavailableReason,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:void 0===i.optimisticUntil?l.optimisticUntil:i.optimisticUntil,isCurrent:g}:{lastObservedAt:n,...void 0!==i.jobs&&!s?{jobsJson:f}:{},...u?{isCurrent:!0}:{}}}))&&(d=l.id)}else d=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:o.id,identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:i.url??null,checkSuiteId:i.checkSuiteId??null,workflowRunId:i.workflowRunId??null,workflowId:i.workflowId??null,runNumber:i.runNumber??null,runAttempt:m,canRetry:i.canRetry??!1,retryUnavailableReason:i.retryUnavailableReason??null,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:i.optimisticUntil??null,isCurrent:g}})).id;c.add(l.id)}if(u)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id,isCurrent:!0}})))!c.has(e.id)&&e.sourceFetchedAt.getTime()<=s.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=n.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),d??=e.id);let p=await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}}),h=u?e.graphqlRollupStatus??null:o.graphqlRollupStatus,m=ey(p.filter(e=>e.isCurrent).map(e=>ek(e.status)?e.status:"NONE"),h&&eS(h)?h:null),f=l!==eT(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:m,graphqlRollupStatus:h,lastGraphqlSyncAt:u?s:o.lastGraphqlSyncAt,lastObservedAt:n},include:{records:!0}}))||null!==d;f&&(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{revision:{increment:1}},include:{records:!0}}));let g=o,y=d?g.records.find(e=>e.id===d)??null:null;return{changed:f,change:{snapshot:eC(g),changedPipeline:y?e_(g,y):null}}});return l.changed&&ep.agentEventBus.publish(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:l.change}),this.pruneIfNeeded().catch(()=>void 0),l.change}subscribe(){return ep.agentEventBus.iterate(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}e.s(["GitHubPipelineStatusService",0,eD],963910);let eN=/^[_A-Za-z][_0-9A-Za-z]*$/,eO=new Map([["GitHubWorktreePullRequestStatuses",60]]),eP=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function e$(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let eU=/(?:authorization|password|private.?key|secret|token)$/i;function eB(e,t=""){return eU.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>eB(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,eB(t,e)])):e}function ej(e){try{return JSON.parse(e)}catch{return null}}function eL(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}class eq{inFlight=new Map;cacheWrites=new Set;cacheGeneration=0;lastPrunedAt=0;cacheKey(e){return(0,t.createHash)("sha256").update(e$({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,r.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await (0,r.getPrismaClient)(),[i,a]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let i=this.cacheGeneration,a=await (0,r.getPrismaClient)(),n=this.cacheKey(e),s=this.inFlightKey(n,e,i),o=Date.now(),[l,u,c]=await Promise.all([a.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:n}}),this.effectiveTtlSeconds(e.operation),a.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(i!==this.cacheGeneration)return this.query(e);let d=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&d)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{data:ej(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let p=this.inFlight.get(s);if(p){let t=await p;return i!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(c?.remaining===0&&c.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${c.resetAt.toISOString()}`,r=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:r,pointCost:0,pointsAvoided:r?l.pointCost??0:0,rateLimit:{limit:c.limit,remaining:c.remaining,used:c.used,resetAt:c.resetAt,resource:c.resource}}).catch(()=>void 0),i!==this.cacheGeneration)return this.query(e);if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let h=(async()=>{try{let r=await e.fetcher(),s=new Date,l=null;if(i===this.cacheGeneration){let i=a.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:n},create:{id:(0,t.randomUUID)(),cacheKey:n,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost}});this.cacheWrites.add(i);try{l=await i}finally{this.cacheWrites.delete(i)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:s,entryId:i===this.cacheGeneration?l?.id??null:null,pointCost:r.pointCost}}catch(a){let t=eL(a),r=i===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:r,pointsAvoided:r?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),i!==this.cacheGeneration)throw a;if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(s,h);try{return await h}finally{this.inFlight.get(s)===h&&this.inFlight.delete(s)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=eL(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,t){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,r.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await (0,r.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:eO.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,r.getPrismaClient)(),[t,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...eO.keys(),...t.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let i=e.trim();if(!eN.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(t)||t<1||t>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,r.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:eO.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(eO.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,r.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let t=await (0,r.getPrismaClient)();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:i}=this.beginInvalidation();await Promise.allSettled(t);let a=await (0,r.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,r.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await (0,r.getPrismaClient)();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let i=this.pagination(e,t),a=await (0,r.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:ej(i.variablesJson),response:ej(i.responseJson)}}async calls(e=50,t=0,i={}){let a=this.pagination(e,t);await this.pruneLogs();let n=await (0,r.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:ej(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,r.getPrismaClient)(),t=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-eP.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=eP.map(e=>this.metricWindow(e.window,i.filter(r=>r.createdAt.getTime()>=t-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=t-r.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,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===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=eB(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){await this.pruneLogs();let i=await (0,r.getPrismaClient)();await i.gitHubApiCallLog.create({data:{id:(0,t.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:e$(eB(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let eM=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),eF=process.env.GITHUB_GRAPHQL_URL||`${eM}/graphql`;var eK=e.i(995702),eV=e.i(151112),eG=e.i(312851);let eH="_adeRateLimit";function eW(e){let t=(0,eV.parse)(e),r=t.definitions.filter(e=>e.kind===eK.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,eG.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:eK.Kind.FIELD,alias:{kind:eK.Kind.NAME,value:eH},name:{kind:eK.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:eK.Kind.SELECTION_SET,selections:[{kind:eK.Kind.FIELD,name:{kind:eK.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,eG.print)(s)}}function eJ(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[eH],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(eH in e))return{data:e,pointCost:r};let i={...e};return delete i[eH],{data:i,pointCost:r}}let ez="default",eZ="default",eY=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,eQ=["workflow_run","workflow_job","check_run","check_suite","status"];function eX(e){return"read"===e||"write"===e}function e0(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),eX(e.actionsPermission)||t.push("grant Actions read permission"),eX(e.checksPermission)||t.push("grant Checks read permission"),eX(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),eQ))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function e1(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class e2 extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let e3=`
50
+ ${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}]`}},sV=class{constructor(e){(0,tG.__publicField)(this,"mdToAdfEngine"),(0,tG.__publicField)(this,"adfToMdEngine"),(0,tG.__publicField)(this,"options"),(0,tG.__publicField)(this,"errorRecovery"),(0,tG.__publicField)(this,"remarkProcessor"),(0,tG.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new ss(this.options),this.adfToMdEngine=new sF(this.options),this.errorRecovery=new sK({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=ri().use(iD).use(a_,["yaml"]).use(n$).use(nV,{strict:e?.strict||!1}).use(am),this.registry=new nY,this.registerConverters()}catch(e){throw new nJ("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new sF({...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 ss({...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 nH().validate(e)}validateMarkdown(e){return new nW().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}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{}}},sG=e.i(378731);let sH=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function sW(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function sJ(e,t){return sG.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 sz=new sV;function sZ(e,t){if(null==e)return null;let r=function(e){if(sW(e))return"ADF";let t="string"==typeof e?e:"";return sH.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 sz.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?sJ(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:sG.default.to_jira(a)}}function sY(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?sJ(t):t,i=sz.markdownToAdf(r);if(!sW(i))throw Error("The Jira text could not be converted to valid ADF");return i}let sQ="default",sX=["summary","status","issuetype","priority","assignee","project","updated"],s0=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function s1(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function s2(e){return s1(e)?e:{}}function s3(e){return Array.isArray(e)?e:[]}function s4(e){return"string"==typeof e&&e.length>0?e:null}function s6(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function s8(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function s5(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function s9(e){return s3(s5(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function s7(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):s1(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function oe(e){if(!s1(e))return null;let t=e.status??s2(e.response).status;return"number"==typeof t?t:null}function ot(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function or(e){return s4(s2(s2(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function oi(e){let t=s2(e),r=s4(t.displayName);if(!r)return null;let i=s2(t.avatarUrls);return{accountId:s4(t.accountId),displayName:r,avatarUrl:s4(i["48x48"])??s4(i["32x32"])??s4(i["24x24"])}}function oa(e){return s3(e).map(s2).map(e=>({id:s4(e.id),name:s4(e.name)??"Unknown"}))}function on(e,t){let r=s2(e),i=s4(r.key);if(!i)return null;let a=s2(r.fields);return{relationship:t,key:i,summary:s4(a.summary)??i,status:s4(s2(a.status).name)}}function os(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function oo(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function ol(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 ou(e){let t=s2(e.fields),r=s2(t.status),i=s2(r.statusCategory),a=s2(t.assignee),n=s2(a.avatarUrls),s=s2(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:s4(t.summary)??o,statusId:s4(r.id)??s4(r.name)??"unknown",status:s4(r.name)??"Unknown",statusCategory:s4(i.key)??s4(i.name)??"unknown",issueType:s4(s2(t.issuetype).name),priority:s4(s2(t.priority).name),assignee:s4(a.displayName),assigneeAccountId:s4(a.accountId),assigneeAvatarUrl:s4(n["48x48"])??s4(n["32x32"]),projectKey:s4(s.key)??or(e),updatedAt:s4(t.updated)}}function oc(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let od=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function op(e){return od.has(e)?e:"ALL"}e.s(["JiraService",0,class{credentials;workflowEvents;recordCallLogs;inFlight;clients;lastPrunedAt;constructor(e=new tO.CredentialService,t,r="true"!==process.env.JIRA_CACHE_LOGGING_DISABLED){this.credentials=e,this.workflowEvents=t,this.recordCallLogs=r,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let r=e.comments.at(-1)??null,i={ticket:{key:e.key,title:e.summary,type:e.issueType,status:e.status,statusId:e.statusId,statusCategory:e.statusCategory,assignee:e.assignee,assigneeAccountId:e.assigneeAccountId,labels:e.labels,sprintNames:e.sprintNames,activeSprintNames:e.activeSprintNames,closedSprintNames:e.closedSprintNames,url:e.jiraUrl},comment:r?{id:r.id,body:r.content?.rawText??"",author:r.author}:null,...void 0!==t?{changelog:t}:{}},a=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,s=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",r?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",r?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&s.push(["JIRA_ASSIGNED_SELF",n]),t?.items.length){let e=new Set(t.items.flatMap(e=>[e.fieldId,e.field].filter(e=>!!e).map(e=>e.trim().toLowerCase()))),r=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&r.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&r.add("JIRA_LABEL"),e.has("assignee")&&r.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(r.add("JIRA_SPRINT_STARTED"),r.add("JIRA_SPRINT_ENDED")),s=s.filter(([e])=>r.has(e))}await Promise.allSettled(s.map(([t,r])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${a}`,payload:{...i,sessionData:i,cursorValue:r}})))}async getSettings(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,tD.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:sQ}}),n=e.apiToken?.trim()||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||!!n,l=async e=>{s&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,siteUrl:r,email:i,cacheTtlSeconds:300},update:s?{siteUrl:r,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:r,email:i}})};return n?await this.credentials.setText(tN.CREDENTIALS.jiraApiToken,n,l):await t.$transaction(l),s&&await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ},select:{siteUrl:!0,email:!0,webhookId:!0}}),r=await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&r)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==oe(e))throw e}return await this.credentials.deleteMany([tN.CREDENTIALS.jiraApiToken,tN.CREDENTIALS.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{email:null,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql: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,tD.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,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=s2(e.value);return{accountId:s4(t.accountId),displayName:s4(t.displayName)??"Jira user",emailAddress:s4(t.emailAddress),cache:oo(e)}}async listProjects(){let e=await (0,tD.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:op(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:s9(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??tF,sources:e.sources.map(os)}))}async projectStatuses(e){let t=await (0,tD.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 s3(i.value).map(s2))for(let t of s3(e.statuses).map(s2)){let e=s4(t.id),r=s4(t.name);if(!e||!r||a.has(e))continue;let i=s2(t.statusCategory);a.set(e,{id:e,name:r,category:s4(i.key)??s4(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>oc(e.category)-oc(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!od.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,tD.getPrismaClient)(),i=void 0===e.doneStatusId?void 0:e.doneStatusId?.trim()||null;if(i&&!(await this.projectStatuses(e.projectId)).some(e=>e.id===i))throw Error("The selected Jira done status is not available");return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t),...void 0===i?{}:{doneStatusId:i}}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await tV(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=>s3(s2(e).values).length}),i=s2(r.value),a=s3(i.values).map(s2);e.push(...a.flatMap(e=>{let t=s4(e.id),r=s4(e.key),i=s4(e.name);if(!t||!r||!i)return[];let a=s2(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:s4(a["48x48"])??s4(a["32x32"])}]}));let n=s6(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 i=s2((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),a=s4(i.key),n=s4(i.name),s=s4(i.id);if(!a||!n||!s)throw Error("Jira returned an incomplete project");let o=s2(i.avatarUrls),l=await (0,tD.getPrismaClient)(),u=await l.jiraProject.aggregate({_max:{position:!0}});return await l.jiraProject.create({data:{id:(0,r.randomUUID)(),jiraId:s,key:a,name:n,avatarUrl:s4(o["48x48"])??s4(o["32x32"]),position:(u._max.position??-1)+1,branchNamingScript:tF}}),this.listProjects()}async removeProject(e){let t=await (0,tD.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),i=this.validateSourceName(e.name),a=await (0,tD.getPrismaClient)();if(!await a.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let n=await a.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await a.jiraSource.create({data:{id:(0,r.randomUUID)(),projectId:e.projectId,name:i,kind:e.kind,value:t.value,boardId:t.boardId,position:(n._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,tD.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,tD.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,tD.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l=await s.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),u=new Set(l?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===o.kind?await this.loadBoardSource(os(o),t):await this.loadJqlSource(os(o),t),d={ticketAssignmentFilter:op(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:s9(o.project.completedStatusIdsJson)},p="ALL"===d.ticketAssignmentFilter?null:await this.currentAccountId(),h=(r={source:os(o),...c},i=d.hideCompletedTickets?new Set(d.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"===d.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===d.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===p:null!==p&&e.assigneeAccountId===p&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))});return this.workflowEvents&&l&&await Promise.allSettled(h.tickets.filter(({key:e})=>!u.has(e)).map(t=>{let r={ticket:{key:t.key,title:t.summary,type:t.issueType,status:t.status,statusId:t.statusId,statusCategory:t.statusCategory,assignee:t.assignee}};return this.workflowEvents.record({kind:"JIRA_SOURCE_NEW_TICKET",subjectKey:`${e}:${t.key}`,dedupeKey:`jira-source-new:${e}:${t.key}:${h.cache.fetchedAt}`,payload:{...r,sessionData:r,source:{id:e,name:o.name,kind:o.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,r){let i=s8(e),a=await this.cachedCall({operation:"ISSUE",params:{issueKey:i,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${i} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:i,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===a.source&&await this.storeDetail(a.entryId,a.value,a.fetchedAt);let n=[],s=[],o=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:o,maxResults:100},requestSummary:`Comments for ${i} from ${o}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:o,maxResults:100,orderBy:"created"})},itemCount:e=>s3(s2(e).comments).length});n.push(e);let r=s2(e.value),a=s3(r.comments);s.push(...a);let l=s6(r.total)??s.length;if(0===a.length||s.length>=l)break;o+=a.length}let l=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,s,l,n.map(e=>e.entryId));let u=await this.requireCredentials(),c=this.normalizeTicketDetail(a.value,s,u.siteUrl,oo(a),ol(n));return await this.recordTicketWorkflowEvents(c,r),c}async assignableUsers(e,t=""){let r=s8(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=>s3(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),s3(a.value).map(oi).filter(e=>null!==e)}async ticketTransitions(e){let t=s8(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=>s3(s2(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),s3(s2(r.value).transitions).map(s2).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=s4(e.id),r=s4(e.name);if(!t||!r)return[];let i=s2(e.to),a=s2(i.statusCategory),n=Object.entries(s2(e.fields)).filter(([,e])=>!0===s2(e).required).map(([e,t])=>s4(s2(t).name)??e);return[{id:t,name:r,toStatusId:s4(i.id),toStatus:s4(i.name)??r,toStatusCategory:s4(a.key)??s4(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=s8(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(s2(s2(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(s2(s2(r.value).fields)).map(([e,t])=>{let r=s2(t);return{id:e,name:s4(r.name)??e,required:!0===r.required,schemaType:s4(s2(r.schema).type),allowedValues:s3(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=s2(e),r=s4(t.name)??s4(t.value)??s4(t.displayName)??s4(t.key);return r?[{id:s4(t.id)??s4(t.accountId)??s4(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Changelog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Changelog for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=s3(s2(c.value).values).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),createdAt:s4(e.created),items:s3(e.items).map(s2).map(e=>({field:s4(e.field)??"Field",fieldId:s4(e.fieldId),from:s4(e.fromString)??s4(e.from),to:s4(e.toString)??s4(e.to)}))}));return{...n,total:o,items:d,cache:ol([s,c])}}async ticketWorklogs(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Worklog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Worklogs for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=await this.requireCredentials(),p=s3(s2(c.value).worklogs).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),comment:sZ(e.comment??null,d.siteUrl),timeSpent:s4(e.timeSpent),timeSpentSeconds:s6(e.timeSpentSeconds),startedAt:s4(e.started),createdAt:s4(e.created),updatedAt:s4(e.updated)})),h=p[0];if(this.workflowEvents&&h){let e={ticket:{key:a},worklog:{id:h.id,author:h.author,timeSpent:h.timeSpent,timeSpentSeconds:h.timeSpentSeconds,startedAt:h.startedAt,updatedAt:h.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:a,dedupeKey:`jira-worklog:${a}:${h.id}:${c.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:h.id}})}return{...n,total:o,items:p,cache:ol([s,c])}}async addComment(e,t){let r=s8(e);if(!t.value.trim())throw Error("Comment text is required");let i=sY(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=s8(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=s8(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 transitionTicketToConfiguredDone(e){let t=s8(e),r=t.split("-")[0]??"",i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{doneStatusId:!0}});if(!a?.doneStatusId)throw Error(`Configure a done status for Jira project ${r} before using this option`);let n=await this.ticket(t);if(n.statusId===a.doneStatusId)return n;let s=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===a.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!s)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,s.id)}async updateTicket(e){let t=s8(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=sY(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 createTicket(e){let t=e.projectKey.trim().toUpperCase(),r=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!r||!i)throw Error("Project, issue type, and summary are required");let{version3:a}=await this.getClients(),n=await a.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:r},summary:i,...e.description?{description:sY(e.description)}:{}}});if(!n.key)throw Error("Jira did not return the created issue key");return this.ticket(n.key,!0)}async addWorklog(e){let t=s8(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:r}=await this.getClients();return await r.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:sY(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=s8(e.inwardIssueKey),r=s8(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:a}=await this.getClients();return await a.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:r}}),this.ticket(t,!0)}async branchTicket(e){let t=s8(e),r=t.replace(/-\d+$/,""),i=await (0,tD.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=s2(n.value.fields);if((s4(s2(s.project).key)??or(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:s4(s.summary)??t,ticketType:s4(s2(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??tF}}async clearCache(){let e=await (0,tD.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await (0,tD.getPrismaClient)();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(s8(e)),!0}async invalidateIssueCaches(e){let t=await (0,tD.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,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await r.jiraCacheEntry.deleteMany({where:{id:{in:i.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0,t)}async resolveIssueKeys(e){let t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===t.length)return[];let{version3:r}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>r.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=s4(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return s8(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),r=[],i=0;for(;r.length<1e3;){let a=Math.min(100,1e3-r.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:a,fields:["key"]}),s=n.issues??[];r.push(...s.flatMap(e=>{let t=s4(e.key);return t?[s8(t)]:[]}));let o=void 0===n.total?s.length<a:i+s.length>=n.total;if(0===s.length||o)break;i+=s.length}let a=[],n=[...new Set(r)];for(let e=0;e<n.length;e+=5)a.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return a}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,tD.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,tD.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:s5(r.summaryJson),detailData:s5(r.detailJson),commentsData:s5(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,tD.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,tD.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-s0.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:s0.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:s0.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let r=await this.credentials.getText(tN.CREDENTIALS.jiraApiToken);if(!r)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:r,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,r.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let i={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new tT(i),agile:new q(i)},this.clients}async webhookApiRequest(e,t,r){let i,a=await this.requireCredentials(),n=Buffer.from(`${a.email}:${a.apiToken}`).toString("base64");try{i=await fetch(`${a.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===r?void 0:JSON.stringify(r),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(ot(e,a.apiToken))}let s=await i.text();if(!i.ok){let e=s.trim().slice(0,300)||i.statusText;throw Object.assign(Error(ot(`Jira rejected the webhook request with ${i.status}: ${e}`,a.apiToken)),{status:i.status})}if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}async currentAccountId(){let e=s4(s2((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,tD.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=ot(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:oe(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: ${ot(e,i.apiToken)}`)}}cacheKey(e,t,i){return(0,r.createHash)("sha256").update(s7({siteUrl:e,operation:t,params:i})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),i=await (0,tD.getPrismaClient)(),a=this.cacheKey(t.siteUrl,e.operation,e.params),n=Date.now(),s=await i.jiraCacheEntry.findUnique({where:{cacheKey:a}}),o=null!==s&&Date.now()-s.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&o)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(s5(s.responseJson))??null,sourceId:e.sourceId}),{value:s5(s.responseJson),source:"CACHE",stale:!1,fetchedAt:s.fetchedAt,entryId:s.id};let l=this.inFlight.get(a);if(l){let t=await l;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let u=(async()=>{try{let t=await e.fetcher(),s=new Date,o=await i.jiraCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,r.randomUUID)(),cacheKey:a,operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:s,entryId:o.id}}catch(i){let r=null!==s&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-n,statusCode:oe(i),error:ot(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:s5(s.responseJson),source:"ERROR",stale:!0,fetchedAt:s.fetchedAt,entryId:s.id};throw Error(ot(i,t.apiToken))}})();this.inFlight.set(a,u);try{return await u}finally{this.inFlight.delete(a)}}async logCall(e){if(!this.recordCallLogs)return;let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,r.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:sX},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:sX})},itemCount:e=>e.issues?.length??0});a.push(l);let u=l.value.issues??[];i.push(...u),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,u,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"===(s4(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=>s3(e.values).length});a.push(r);let i=s3(r.value.values).map(s2);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=s6(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:sX}),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:sX}),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()],u=new Map;return s3(s2(i.value.columnConfig).columns).map(s2).forEach((e,t)=>{s3(e.statuses).map(s2).forEach(e=>{let r=s4(e.id);r&&u.set(r,t)})}),this.buildBoardResult(l,a,s,o,u)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],u=0,c=1/0,d=!1;for(;u<c&&s.length+n<1e3;){let d=i(u,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${u}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let h=p.value.issues??[];if(s.push(...h),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,h,p.fetchedAt),c=p.value.total??s.length,0===h.length)break;u+=h.length}return s.length+n>=1e3&&u<c&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(ou),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):oc(e.statusCategory)-oc(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:ol(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,tD.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:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:or(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,tD.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:or(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,tD.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,i,a,n){let s=ou(e),o=s2(e.fields),l=s2(e.names),u=s2(e.schema),c=[];for(let e of s3(o.issuelinks).map(s2)){let t=s2(e.type),r=on(e.outwardIssue,s4(t.outward)??"relates to"),i=on(e.inwardIssue,s4(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let d=on(o.parent,"parent"),p=s3(o.subtasks).map(e=>on(e,"subtask")).filter(e=>null!==e),h=s3(o.sprint).map(s2),m=s3(o.closedSprints).map(s2),f=h.filter(e=>{let t=s4(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>s4(e.name)).filter(e=>!!e),g=m.concat(h.filter(e=>s4(e.state)?.toLowerCase()==="closed")).map(e=>s4(e.name)).filter(e=>!!e),y=f.concat(g),w=t.map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),body:e.body??null,content:sZ(e.body??null,i),createdAt:s4(e.created),updatedAt:s4(e.updated)}));return{...s,jiraUrl:`${i}/browse/${s.key}`,description:o.description??null,descriptionContent:sZ(o.description??null,i),reporter:oi(o.reporter),creator:oi(o.creator),labels:s3(o.labels).filter(e=>"string"==typeof e),components:oa(o.components),fixVersions:oa(o.fixVersions),affectedVersions:oa(o.versions),sprintNames:[...new Set(y)],activeSprintNames:[...new Set(f)],closedSprintNames:[...new Set(g)],parent:d,subtasks:p,issueLinks:c,attachments:s3(o.attachment).map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),filename:s4(e.filename)??"Attachment",contentUrl:s4(e.content),mimeType:s4(e.mimeType),size:s6(e.size),author:oi(e.author),createdAt:s4(e.created)})),comments:w,createdAt:s4(o.created),dueAt:s4(o.duedate),resolvedAt:s4(o.resolutiondate),timeTracking:o.timetracking??null,allFields:Object.entries(o).map(([e,t])=>{let r=s2(u[e]),a="string"==typeof t||s1(t)&&"doc"===t.type?sZ(t,i):null;return{id:e,name:s4(l[e])??e,schemaType:s4(r.type),custom:!0===r.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:a,commentsCache:n}}cachedTicketView(e,t){let r=ou(s2(s5(e.detailJson)??s5(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,tD.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],126223);var oh=e.i(661983);let om="default",of=/^[A-Z][A-Z0-9_]*-\d+$/,og=new Set(["jira:issue_created","jira:issue_updated","comment_created","comment_updated","comment_deleted","worklog_created","worklog_updated","worklog_deleted","jira:worklog_updated","attachment_created","attachment_deleted","issuelink_created","issuelink_deleted","sprint_started","sprint_closed"]),oy={"jira:issue_created":"JIRA_ISSUE_CREATED","jira:issue_deleted":"JIRA_ISSUE_DELETED",comment_created:"JIRA_ISSUE_COMMAND",attachment_created:"JIRA_ATTACHMENT_ADDED",issuelink_created:"JIRA_ISSUE_LINKED"},ow="/api/public/jira/webhook",ob="/rest/webhooks/1.0/webhook",ov=new Set(["localhost","0.0.0.0","::1","[::1]",""]),ok=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class oS extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function oE(e){return"string"==typeof e&&e.trim()?e.trim():null}function oI(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function ox(e){let t=oA(e);if(!t)return null;let r=Array.isArray(t.items)?t.items:[];return{id:oI(t.id),items:r.map(oA).filter(e=>null!==e).map(e=>({field:oE(e.field)??oE(e.fieldId)??"Field",fieldId:oE(e.fieldId),fieldType:oE(e.fieldtype)??oE(e.fieldType),from:oI(e.from),fromString:oI(e.fromString),to:oI(e.to),toString:oI(e.toString)}))}}function oA(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function o_(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function oC(e){let t=oA(e);return t?{accountId:oE(t.accountId),displayName:oE(t.displayName)}:null}function oR(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return ox(JSON.parse(e))}catch{return null}}(e.changelogJson),retryCount:e.retryCount,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null}}e.s(["JiraWebhookRequestError",0,oS,"JiraWebhookService",0,class{jira;credentials;workflowEvents;constructor(e,t,r){this.jira=e,this.credentials=t,this.workflowEvents=r}async webhooksEnabled(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret)}async getWebhookSettings(){let e=await (0,tD.getPrismaClient)(),[t,r,i]=await Promise.all([e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{}}),this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&r,secretConfigured:r,registered:!!t.webhookId,registrationId:t.webhookId??null,registeredUrl:t.webhookUrl??null,jql:t.webhookJql??null,configuredAt:t.webhookConfiguredAt?.toISOString()??null,lastReceivedAt:i?.receivedAt.toISOString()??null,lastOutcome:i?.outcome??null,lastError:i?.error??null}}async enableWebhook(){let e=(0,r.randomBytes)(32).toString("base64url");return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date},update:{webhookEnabled:!0,webhookConfiguredAt:new Date}})}),{settings:await this.getWebhookSettings(),secret:e}}async registerWebhook(e){let t=function(e){let t;try{t=new URL(e.trim())}catch{throw Error("Enter the public URL of this server")}if("https:"!==t.protocol&&"http:"!==t.protocol)throw Error("The webhook URL must use HTTP or HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("The webhook URL must not include credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ov.has(r)||r.endsWith(".local")||r.endsWith(".localhost")||/^127\./.test(r)||/^10\./.test(r)||/^192\.168\./.test(r)||/^172\.(1[6-9]|2\d|3[01])\./.test(r))throw Error(`Jira cannot reach ${t.host}. Expose this server publicly, or set PUBLIC_BASE_URL to its public address.`);let i=t.pathname.replace(/\/+$/,"");if(!i)return`${t.origin}${ow}`;if(i.endsWith(ow))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${ow}`)}(e.url),i=e.jql?.trim()||null,a=(0,r.randomBytes)(32).toString("base64url"),n=await (0,tD.getPrismaClient)(),s=await n.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}}),o=await this.writeToJira({webhookId:s?.webhookId??null,url:t,jql:i,secret:a});return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,a,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i}})}),{settings:await this.getWebhookSettings(),secret:a}}async rotateSecret(){if(!await this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0,webhookUrl:!0,webhookJql:!0}});return t?.webhookId&&t.webhookUrl?this.registerWebhook({url:t.webhookUrl,jql:t.webhookJql}):this.enableWebhook()}async disableWebhook(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,r,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...ok],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${ob}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==o_(e))throw e}}let a=await this.jira.webhookApiRequest("POST",ob,i),n=(t=oE(a?.self),(r=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(r):null);if(!n)throw Error("Jira did not return the ID of the new webhook");return n}async deleteFromJira(e){try{await this.jira.webhookApiRequest("DELETE",`${ob}/${encodeURIComponent(e)}`)}catch(e){if(404!==o_(e))throw e}}async deliveries(e=50,t=0){if(!Number.isInteger(e)||e<1||e>100)throw Error("Limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Offset must be a non-negative integer");let r=await this.webhooksEnabled();if(!r)return{enabled:r,items:[],total:0,limit:e,offset:t};let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:r,items:a.map(oR),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await (0,tD.getPrismaClient)();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await (0,tD.getPrismaClient)();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,i,a,n,s,o;let l,u,c=await this.credentials.getText(tN.CREDENTIALS.jiraWebhookSecret);if(!c)throw new oS("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new oS("Jira webhook signature is missing",401);if(t=`sha256=${(0,r.createHmac)("sha256",c).update(e.body).digest("hex")}`,i=e.signature,l=Buffer.from(t),u=Buffer.from(i),!(l.length===u.length&&(0,r.timingSafeEqual)(l,u)))throw new oS("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new oS("Jira delivery ID is missing",400);let d=await (0,tD.getPrismaClient)(),p=e.deliveryId.trim(),h=Number.parseInt(e.retryCount??"",10),m=Number.isInteger(h)?h:null;try{await d.jiraWebhookDelivery.create({data:{deliveryId:p,event:"unknown",outcome:"RECEIVED",retryCount:m}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await d.jiraWebhookDelivery.updateMany({where:{deliveryId:p,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:m,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return await this.prune().catch(()=>void 0),{outcome:"DUPLICATE",event:null,issueKey:null,triggersRecorded:0}}let f=async(e,t=null)=>{let r=await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{outcome:e,error:t,processedAt:new Date}});oh.agentEventBus.publish(oh.JIRA_WEBHOOK_DELIVERY_TOPIC,{jiraWebhookDeliveryChanged:oR(r)})};try{let t,r,i,l,u,c;try{let r=JSON.parse(Buffer.from(e.body).toString("utf8")),i=oA(r);if(!i)throw Error("Payload is not an object");t=i}catch{throw new oS("Jira webhook payload is invalid JSON",400)}let h=oE(t.webhookEvent),g=(a=t,r=oA(a.issue),(i=oE(r?.key)?.toUpperCase()??null)&&of.test(i)?i:null),y=(n=t,l=oA(n.issue),u=oA(l?.fields),c=oA(u?.project)??oA(n.project),oE(c?.key)?.toUpperCase()??null),w=ox(t.changelog);if(await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{event:h??"unknown",issueKey:g,projectKey:y,changelogJson:w?JSON.stringify(w):null}}),!h)return await f("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};if(!(og.has(h)||"jira:issue_deleted"===h))return await f("IGNORED",`Unhandled Jira event ${h}`),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let b=g?[g]:[];if("issuelink_created"===h||"issuelink_deleted"===h){let e,r,i=(s=t,e=oA(s.issueLink),[oI(e?.sourceIssueId),oI(e?.destinationIssueId)].filter((e,t,r)=>!!(e&&r.indexOf(e)===t)));if(0===i.length)return await f("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};y=(g=(b=await this.jira.resolveIssueKeys(i))[0]??null)?y??((r=(o=g).lastIndexOf("-"))>0?o.slice(0,r):null):y,await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{issueKey:g,projectKey:y}})}let v="sprint_started"===h||"sprint_closed"===h;if(!v&&!g)return await f("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let k=[];if("jira:issue_deleted"===h)await this.jira.deleteCachedTicket(g),k.push({key:g,projectKey:y});else if(v){let e=function(e){let t=oI(oA(e.sprint)?.id);if(!t)return null;let r=Number(t);return Number.isSafeInteger(r)&&r>0?r:null}(t);if(!e)return await f("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let r=await this.jira.refreshSprintTickets(e);k.push(...r.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===h){let e=await this.jira.refreshCachedTicket(g,w);k.push({key:e.key,projectKey:e.projectKey})}else if(og.has(h)){let e=await Promise.all(b.map(e=>this.jira.refreshCachedTicket(e)));k.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let S=g?await this.recordWebhookTrigger({event:h,deliveryId:p,issueKey:g,projectKey:y,retries:m,payload:t}):0;for(let e of k)oh.agentEventBus.publish(oh.JIRA_TICKET_CHANGED_TOPIC,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:h}});return await f("PROCESSED"),{outcome:"PROCESSED",event:h,issueKey:g,triggersRecorded:S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await f("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=oy[e.event];if(!t)return 0;let{payload:r}=e,i=oA(r.issue),a=oA(i?.fields),n=oA(r.comment),s=oA(r.attachment),o=oA(r.issueLink),l=oA(a?.status),u=ox(r.changelog),c={ticket:{key:e.issueKey,title:oE(a?.summary),type:oE(oA(a?.issuetype)?.name),status:oE(l?.name),statusId:oE(l?.id),statusCategory:oE(oA(l?.statusCategory)?.key),assignee:oE(oA(a?.assignee)?.displayName),assigneeAccountId:oE(oA(a?.assignee)?.accountId),labels:Array.isArray(a?.labels)?a.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:oE(n.id),body:oE(n.body)??"",author:oC(n.author)}:null,attachment:s?{id:oE(s.id),filename:oE(s.filename),mimeType:oE(s.mimeType),author:oC(s.author)}:null,link:o?{id:oE(o.id),type:oE(oA(o.issueLinkType)?.name),sourceIssueId:oE(o.sourceIssueId),destinationIssueId:oE(o.destinationIssueId)}:null,user:oC(r.user),changelog:u};return+!!await this.workflowEvents.record({kind:t,subjectKey:e.issueKey,dedupeKey:`jira-webhook-trigger:${e.deliveryId}:${t}`,payload:{...c,sessionData:c,cursorValue:`${e.deliveryId}:${t}`,webhook:{event:e.event,deliveryId:e.deliveryId,retryCount:e.retries}}})}},"subscribeJiraTicketChanges",0,function(){return oh.agentEventBus.iterate(oh.JIRA_TICKET_CHANGED_TOPIC)},"subscribeJiraWebhookDeliveries",0,function(){return oh.agentEventBus.iterate(oh.JIRA_WEBHOOK_DELIVERY_TOPIC)}],642983),e.s([],151666)},107058,963910,112627,695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(582482);var i=e.i(318905),a=e.i(91022),n=e.i(397554),s=e.i(827957);function o(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function l(e){let t=o(e.get("x-ratelimit-limit")),r=o(e.get("x-ratelimit-remaining")),i=o(e.get("x-ratelimit-used")),a=o(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===r||null===i||null===a||!n)return null;let s=new Date(1e3*a);return Number.isFinite(s.getTime())?{limit:t,remaining:r,used:i,resetAt:s,resource:n}:null}async function u(e,t){let i=l(t.headers);if(!i)return null;try{let t=await (0,r.getPrismaClient)(),a=`${e}:${i.resource}`,n=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:i.resource}},create:{id:a,authentication:e,observedAt:n,...i},update:{observedAt:n,...i}})}catch{}return i}async function c(){let e=await (0,r.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}let d="actions.cancelWorkflowRun",p="actions.dispatchWorkflow",h="actions.forceCancelWorkflowRun",m="actions.getJobForWorkflowRun",f="actions.getWorkflowRun",g="actions.getWorkflowRunAttempt",y="actions.listJobsForWorkflowRun",w="actions.listJobsForWorkflowRunAttempt",b="actions.listRepoWorkflows",v="actions.listWorkflowRuns",k="actions.listWorkflowRunsForRepo",S="actions.reRunJobForWorkflowRun",E="actions.reRunWorkflow",I="actions.reRunWorkflowFailedJobs",x="apps.createInstallationAccessToken",A="apps.getAuthenticated",_="apps.getInstallation",C="apps.updateWebhookConfigForApp",R="repos.listPullRequestsAssociatedWithCommit",T="users.listEmailsForAuthenticatedUser";class D extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let N=new Map,O=new Map;function P(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D(r,`${t} must be a positive integer`);return i}function $(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:P(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:P(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function U(e){try{let t=await (0,n.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new s.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function B(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function j(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function L(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),u=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:l(n.headers)})).catch(()=>void 0),n}async function q(e){try{return await e.json()}catch{return null}}function M(e){return e.headers.get("x-github-request-id")}function F(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function K(e,t){let r=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:j(`Bearer ${t}`)},_,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new D("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function V(e,t){let r=await L(`${e.apiBaseUrl}/app`,{headers:j(`Bearer ${t}`)},A,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function G(e){let t=$(e),r=await U(t),i=await V(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function H(e,t,r){let i=r??await U(e),a=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:j(`Bearer ${i}`)},x,e,t),n=await q(a),s=M(a);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new D("GITHUB_APP_REQUEST_FAILED",F(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new D("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function W(e,t){let r=B(e),i=N.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=O.get(r);if(a)return a;let n=H(e,t).then(e=>(N.set(r,e),e)).finally(()=>O.delete(r));return O.set(r,n),n}function J(){N.clear(),O.clear()}async function z(e,t,r){let i=$(e),a=await W(i,r),n=await t(a.token);return 401===n.status&&(N.delete(B(i)),a=await W(i,r),n=await t(a.token)),{response:n,token:a.token}}async function Z(e,t,r,i){let{response:a,token:n}=await z(e,a=>L(e.graphqlUrl,{method:"POST",headers:{...j(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await q(a),o=M(a),u=l(a.headers);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,u);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||F(s,a.status,[n]);throw new D("GITHUB_APP_REQUEST_FAILED",F({message:t},a.status,[n,e.privateKey]),o,a.status,u)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:u}}async function Y(e){let t=$(e),r=await U(t),[i,a]=await Promise.all([K(t,r),V(t,r)]),n=await H(t,"GITHUB_SETTINGS",r);N.set(B(t),n);let s=await Z(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function Q(e,t){let r=$(e),i=await U(r),a=await L(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...j(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},C,r,"GITHUB_SETTINGS"),n=M(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new D("GITHUB_APP_REQUEST_FAILED",F(await q(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function X(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},E,e,t.requestSource),t.requestSource),n=M(i);if(401===i.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function ee(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},I,e,t.requestSource),t.requestSource),n=M(i);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function et(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?h:d,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await z(e,r=>L(a,{method:"POST",headers:j(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=M(n);if(401===n.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await q(n);throw new D(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":F(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function er(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await z(e,r=>L(n,{headers:j(`Bearer ${r}`)},y,e,t.requestSource),t.requestSource),l=M(s);if(401===s.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await q(s);if(!s.ok||!u||"object"!=typeof u)throw new D("GITHUB_APP_REQUEST_FAILED",F(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function ei(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await z(e,r=>L(i,{headers:j(`Bearer ${r}`)},m,e,t.requestSource),t.requestSource),n=M(a.response);if(401===a.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await q(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new D(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":F(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new D("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new D("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await z(e,r=>L(`${i}/rerun`,{method:"POST",headers:j(`Bearer ${r}`)},S,e,t.requestSource),t.requestSource),l=M(o.response);if(401===o.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await q(o.response);throw new D(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":F(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let ea=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),en=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),es=["COMPLETED","EXHAUSTED","STOPPED"],eo={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},el="server:github-auto-retry";function eu(e){return e.toISOString()}function ec(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:eu(e.updatedAt)})),createdAt:eu(e.createdAt),updatedAt:eu(e.updatedAt)}}class ed{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:el,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(el,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(el,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(el,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(ec)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=en.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":ea.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:es}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||eo[e.scope]>eo[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(en.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>ea.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>es.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.i(805422);var ep=e.i(661983);let eh={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},em=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),ef=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),eg=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function ey(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>em.has(e))?"FAILURE":e.some(e=>ef.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>eg.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function ew(e,t){let r=(t||e||"NONE").toUpperCase();return ek(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"}function eb(e){return ef.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function ev(e,t,r){let i=e.runAttempt??0,a=t.runAttempt??0;if(a!==i)return a>i;let n=e.githubUpdatedAt?.getTime()??0,s=t.githubUpdatedAt?.getTime()??0;if(s!==n)return s>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let o="MUTATION"===e.source?eh.LEGACY:eh[e.source],l=eh[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=eb(e.status),i=eb(t.status);if(i!==r)return i>r}return l===o||l>o}function ek(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function eS(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function eE(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function eI(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function ex(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function eA(e){return{id:e.githubPipelineId,name:e.name,status:ek(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:eE(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function e_(e,t){return{...eA(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function eC(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:eS(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(eA).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function eR(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function eT(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(eR).sort((e,t)=>e.localeCompare(t))})}class eD{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?eC(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(eC)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>e_(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let l=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===l.length)return e_({...o.snapshot,records:[o]},o);let u=eE(o.jobsJson),c=new Map(u.map(e=>[e.id,e])),d=l.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=eI(e.status),n=eI(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(c.get(e.id),e)),p="WEBHOOK"===a?[...new Map([...u,...d].map(e=>[e.id,e])).values()]:d,h=ek(o.status)?o.status:"NONE",m="REST"===a&&l.length>0?ey(l.map(e=>e.status),null):"NONE",f=("ERROR"===m||"FAILURE"===m||"SUCCESS"===m)&&o.snapshot.graphqlRollupStatus===m?m:h;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...eA(o),status:f,source:a,jobs:p,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...eA(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let i=e.repositoryGithubId.trim(),a=e.headSha.trim();if(!i||!a)throw Error("GitHub repository ID and head SHA are required");let n=new Date,s=e.sourceFetchedAt??n,o=await (0,r.getPrismaClient)(),l=await o.$transaction(async r=>{let o=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:i,headSha:a}},create:{id:(0,t.randomUUID)(),repositoryGithubId:i,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:a,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:n},update:{lastObservedAt:n},include:{records:!0}}),l=eT(o),u=!!(e.completeGraphqlRollup&&(!o.lastGraphqlSyncAt||s.getTime()>=o.lastGraphqlSyncAt.getTime())),c=new Set,d=null;for(let i of e.pipelines){let e=function(e){var t;return(t={id:e.id,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,statusContext:e.statusContext}).checkSuiteId?`CHECK_SUITE:${t.checkSuiteId}`:t.workflowRunId?`WORKFLOW_RUN:${t.workflowRunId}`:t.statusContext?`STATUS_CONTEXT:${t.statusContext}`:`PIPELINE:${t.id}`}(i),a=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}})).filter(t=>t.identityKey===e||i.checkSuiteId&&t.checkSuiteId===i.checkSuiteId||i.workflowRunId&&t.workflowRunId===i.workflowRunId),l=a[0]??null;for(let e of a.slice(1))l&&ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:ex(e.source),status:ek(e.status)?e.status:"NONE"},n)&&(l=e);for(let e of a)l&&e.id!==l.id&&(0===eE(l.jobsJson).length&&eE(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),d=l.id);let p=i.sourceFetchedAt??s,h=i.githubUpdatedAt??null,m=void 0===i.runAttempt?l?.runAttempt??null:i.runAttempt,f=void 0!==i.jobs?JSON.stringify(i.jobs):l&&(m??0)<=(l.runAttempt??0)?l.jobsJson:"[]",g=!!u||(!1===i.isCurrent?l?.isCurrent??!1:i.isCurrent??l?.isCurrent??!0);if(l){c.add(l.id);let t=eR(l),a=ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:m,githubUpdatedAt:h,source:i.source,status:i.status},n),s=!!(!a&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>n.getTime()&&"MUTATION"!==i.source);t!==eR(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:a?{identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:void 0===i.url?l.url:i.url,checkSuiteId:void 0===i.checkSuiteId?l.checkSuiteId:i.checkSuiteId,workflowRunId:void 0===i.workflowRunId?l.workflowRunId:i.workflowRunId,workflowId:void 0===i.workflowId?l.workflowId:i.workflowId,runNumber:void 0===i.runNumber?l.runNumber:i.runNumber,runAttempt:m,canRetry:void 0===i.canRetry?l.canRetry:i.canRetry,retryUnavailableReason:void 0===i.retryUnavailableReason?l.retryUnavailableReason:i.retryUnavailableReason,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:void 0===i.optimisticUntil?l.optimisticUntil:i.optimisticUntil,isCurrent:g}:{lastObservedAt:n,...void 0!==i.jobs&&!s?{jobsJson:f}:{},...u?{isCurrent:!0}:{}}}))&&(d=l.id)}else d=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:o.id,identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:i.url??null,checkSuiteId:i.checkSuiteId??null,workflowRunId:i.workflowRunId??null,workflowId:i.workflowId??null,runNumber:i.runNumber??null,runAttempt:m,canRetry:i.canRetry??!1,retryUnavailableReason:i.retryUnavailableReason??null,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:i.optimisticUntil??null,isCurrent:g}})).id;c.add(l.id)}if(u)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id,isCurrent:!0}})))!c.has(e.id)&&e.sourceFetchedAt.getTime()<=s.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=n.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),d??=e.id);let p=await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}}),h=u?e.graphqlRollupStatus??null:o.graphqlRollupStatus,m=ey(p.filter(e=>e.isCurrent).map(e=>ek(e.status)?e.status:"NONE"),h&&eS(h)?h:null),f=l!==eT(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:m,graphqlRollupStatus:h,lastGraphqlSyncAt:u?s:o.lastGraphqlSyncAt,lastObservedAt:n},include:{records:!0}}))||null!==d;f&&(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{revision:{increment:1}},include:{records:!0}}));let g=o,y=d?g.records.find(e=>e.id===d)??null:null;return{changed:f,change:{snapshot:eC(g),changedPipeline:y?e_(g,y):null}}});return l.changed&&ep.agentEventBus.publish(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:l.change}),this.pruneIfNeeded().catch(()=>void 0),l.change}subscribe(){return ep.agentEventBus.iterate(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}e.s(["GitHubPipelineStatusService",0,eD],963910);let eN=/^[_A-Za-z][_0-9A-Za-z]*$/,eO=new Map([["GitHubWorktreePullRequestStatuses",60]]),eP=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function e$(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let eU=/(?:authorization|password|private.?key|secret|token)$/i;function eB(e,t=""){return eU.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>eB(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,eB(t,e)])):e}function ej(e){try{return JSON.parse(e)}catch{return null}}function eL(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}class eq{recordCallLogs;inFlight;cacheWrites;cacheGeneration;lastPrunedAt;constructor(e="true"!==process.env.GITHUB_CACHE_LOGGING_DISABLED){this.recordCallLogs=e,this.inFlight=new Map,this.cacheWrites=new Set,this.cacheGeneration=0,this.lastPrunedAt=0}cacheKey(e){return(0,t.createHash)("sha256").update(e$({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,r.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await (0,r.getPrismaClient)(),[i,a]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let i=this.cacheGeneration,a=await (0,r.getPrismaClient)(),n=this.cacheKey(e),s=this.inFlightKey(n,e,i),o=Date.now(),[l,u,c]=await Promise.all([a.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:n}}),this.effectiveTtlSeconds(e.operation),a.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(i!==this.cacheGeneration)return this.query(e);let d=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&d)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{data:ej(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let p=this.inFlight.get(s);if(p){let t=await p;return i!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(c?.remaining===0&&c.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${c.resetAt.toISOString()}`,r=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:r,pointCost:0,pointsAvoided:r?l.pointCost??0:0,rateLimit:{limit:c.limit,remaining:c.remaining,used:c.used,resetAt:c.resetAt,resource:c.resource}}).catch(()=>void 0),i!==this.cacheGeneration)return this.query(e);if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let h=(async()=>{try{let r=await e.fetcher(),s=new Date,l=null;if(i===this.cacheGeneration){let i=a.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:n},create:{id:(0,t.randomUUID)(),cacheKey:n,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost}});this.cacheWrites.add(i);try{l=await i}finally{this.cacheWrites.delete(i)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:s,entryId:i===this.cacheGeneration?l?.id??null:null,pointCost:r.pointCost}}catch(a){let t=eL(a),r=i===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:r,pointsAvoided:r?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),i!==this.cacheGeneration)throw a;if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(s,h);try{return await h}finally{this.inFlight.get(s)===h&&this.inFlight.delete(s)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=eL(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,t){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,r.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await (0,r.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:eO.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,r.getPrismaClient)(),[t,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...eO.keys(),...t.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let i=e.trim();if(!eN.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(t)||t<1||t>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,r.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:eO.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(eO.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,r.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let t=await (0,r.getPrismaClient)();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:i}=this.beginInvalidation();await Promise.allSettled(t);let a=await (0,r.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,r.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await (0,r.getPrismaClient)();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let i=this.pagination(e,t),a=await (0,r.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:ej(i.variablesJson),response:ej(i.responseJson)}}async calls(e=50,t=0,i={}){let a=this.pagination(e,t);await this.pruneLogs();let n=await (0,r.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:ej(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,r.getPrismaClient)(),t=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-eP.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=eP.map(e=>this.metricWindow(e.window,i.filter(r=>r.createdAt.getTime()>=t-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=t-r.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,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===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=eB(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){if(!this.recordCallLogs)return;await this.pruneLogs();let i=await (0,r.getPrismaClient)();await i.gitHubApiCallLog.create({data:{id:(0,t.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:e$(eB(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let eM=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),eF=process.env.GITHUB_GRAPHQL_URL||`${eM}/graphql`;var eK=e.i(995702),eV=e.i(151112),eG=e.i(312851);let eH="_adeRateLimit";function eW(e){let t=(0,eV.parse)(e),r=t.definitions.filter(e=>e.kind===eK.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,eG.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:eK.Kind.FIELD,alias:{kind:eK.Kind.NAME,value:eH},name:{kind:eK.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:eK.Kind.SELECTION_SET,selections:[{kind:eK.Kind.FIELD,name:{kind:eK.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,eG.print)(s)}}function eJ(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[eH],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(eH in e))return{data:e,pointCost:r};let i={...e};return delete i[eH],{data:i,pointCost:r}}let ez="default",eZ="default",eY=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,eQ=["workflow_run","workflow_job","check_run","check_suite","status"];function eX(e){return"read"===e||"write"===e}function e0(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),eX(e.actionsPermission)||t.push("grant Actions read permission"),eX(e.checksPermission)||t.push("grant Checks read permission"),eX(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),eQ))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function e1(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class e2 extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let e3=`
51
51
  __typename
52
52
  ... on CheckRun {
53
53
  id