@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.
- package/package.json +1 -1
- package/standalone/.next/BUILD_ID +1 -1
- package/standalone/.next/build-manifest.json +3 -3
- package/standalone/.next/prerender-manifest.json +3 -3
- package/standalone/.next/server/app/[locale]/comments/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/pull-requests/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/_global-error.html +1 -1
- package/standalone/.next/server/app/_global-error.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.html +1 -1
- package/standalone/.next/server/app/_not-found.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/chunks/_01qtprx._.js +1 -1
- package/standalone/.next/server/chunks/_0l44maw._.js +2 -2
- package/standalone/.next/server/chunks/_0zi1rzc._.js +1 -1
- package/standalone/.next/server/chunks/_1czfvql._.js +2 -2
- package/standalone/.next/server/chunks/_1gtcfbz._.js +1 -1
- package/standalone/.next/server/chunks/_1kemdff._.js +2 -2
- package/standalone/.next/server/chunks/_21blfei._.js +2 -2
- package/standalone/.next/server/chunks/ssr/_1zd970o._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_github_pull-requests-page_tsx_1il3ga-._.js +3 -3
- package/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/standalone/.next/server/pages/404.html +1 -1
- package/standalone/.next/server/pages/500.html +1 -1
- package/standalone/.next/server/server-reference-manifest.js +1 -1
- package/standalone/.next/server/server-reference-manifest.json +1 -1
- package/standalone/.next/static/chunks/{19dkpj43f8v40.js → 0y408zh4mof6_.js} +7 -7
- package/standalone/.next/static/chunks/{3_rbnqkar9gd5.js → 3eqo76t2qsipq.js} +1 -1
- package/standalone/package.json +6 -5
- /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_buildManifest.js +0 -0
- /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_clientMiddlewareManifest.js +0 -0
- /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_ssgManifest.js +0 -0
|
@@ -11965,7 +11965,7 @@ ${i}
|
|
|
11965
11965
|
${i}
|
|
11966
11966
|
~~~`}},kH=class{constructor(){(0,wi.__publicField)(this,"nodeType","blockquote")}toMarkdown(e,t){if(!e.content||0===e.content.length)return"> ";let A=e.content.map(A=>{let i=t.options.registry?.getNodeConverter(A.type);return i?i.toMarkdown(A,{...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=A.join("\n");return`${t}<!-- adf:blockquote attrs='${JSON.stringify(e.attrs)}' -->`}return A.join("\n")}},kY=class{constructor(){(0,wi.__publicField)(this,"nodeType","rule")}toMarkdown(e,t){return"---"}},kq=class{constructor(){(0,wi.__publicField)(this,"nodeType","hardBreak")}toMarkdown(e,t){return" \n"}},kj=class{constructor(){(0,wi.__publicField)(this,"nodeType","mention")}toMarkdown(e,t){let{id:A,text:i,userType:r}=e.attrs||{},n=`adf://mention/${A||"unknown"}`,a=i||`@${A||"unknown"}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:mention attrs='${JSON.stringify(e.attrs)}' -->`;return`[${a}](${n})${t}`}return`[${a}](${n})`}},kK=class{constructor(){(0,wi.__publicField)(this,"nodeType","date")}toMarkdown(e,t){let{timestamp:A}=e.attrs||{};if(!A)return"[Date]";let i=new Date(parseInt(A));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 r=i.toISOString().split("T")[0];if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:date attrs='${JSON.stringify(e.attrs)}' -->`;return`${r}${t}`}return r}},kV=class{constructor(){(0,wi.__publicField)(this,"nodeType","emoji")}toMarkdown(e,t){let{shortName:A,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(A){let t=A.startsWith(":")&&A.endsWith(":")?A:`:${A}:`;if(e.attrs&&Object.keys(e.attrs).length>0){let A=`<!-- adf:emoji attrs='${JSON.stringify(e.attrs)}' -->`;return`${t}${A}`}return t}return":emoji:"}},k$=class{constructor(){(0,wi.__publicField)(this,"nodeType","status")}toMarkdown(e,t){let{text:A,color:i}=e.attrs||{},r=A||"Status";return i&&"neutral"!==i?`{status:${r}|color:${i}}`:`{status:${r}}`}},kW=class{constructor(){(0,wi.__publicField)(this,"nodeType","inlineCard")}toMarkdown(e,t){let{url:A,data:i}=e.attrs||{};if(!A)return"[Card]";let r=i?.title||i?.name||"Card",n=`adf://card/${encodeURIComponent(A)}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:inlineCard attrs='${JSON.stringify(e.attrs)}' -->`;return`[${r}](${n})${t}`}return`[${r}](${n})`}},kZ=class{constructor(){(0,wi.__publicField)(this,"nodeType","mediaGroup")}toMarkdown(e,t){return(e.content||[]).map(e=>{let A=t.options.registry?.getNodeConverter(e.type);return A?A.toMarkdown(e,t):""}).filter(e=>e.length>0).join(" ")+"\n\n"}},kz=class{constructor(){(0,wi.__publicField)(this,"nodeType","doc")}toMarkdown(e,t){let A=e.content||[];return t.convertChildren(A).trim()+"\n"}},kX=class{constructor(){(0,wi.__publicField)(this,"markType","strong")}toMarkdown(e,t,A){return t.attrs&&Object.keys(t.attrs).length>0?`**${e}**<!-- adf:strong attrs='${JSON.stringify(t.attrs)}' -->`:`**${e}**`}},k0=class{constructor(){(0,wi.__publicField)(this,"markType","em")}toMarkdown(e,t,A){return t.attrs&&Object.keys(t.attrs).length>0?`*${e}*<!-- adf:em attrs='${JSON.stringify(t.attrs)}' -->`:`*${e}*`}},k1=class{constructor(){(0,wi.__publicField)(this,"markType","code")}toMarkdown(e,t,A){return t.attrs&&Object.keys(t.attrs).length>0?`\`${e}\`<!-- adf:code attrs='${JSON.stringify(t.attrs)}' -->`:`\`${e}\``}},k4=class{constructor(){(0,wi.__publicField)(this,"markType","link")}toMarkdown(e,t,A){let i;if(!t.attrs?.href)return e;let{href:r,title:n,...a}=t.attrs;return i=n?`[${e}](${r} "${n}")`:`[${e}](${r})`,Object.keys(a).length>0&&(i+=`<!-- adf:link attrs='${JSON.stringify(a)}' -->`),i}},k8=class{constructor(){(0,wi.__publicField)(this,"markType","strike")}toMarkdown(e,t,A){return t.attrs&&Object.keys(t.attrs).length>0?`~~${e}~~<!-- adf:strike attrs='${JSON.stringify(t.attrs)}' -->`:`~~${e}~~`}},k2=class{constructor(){(0,wi.__publicField)(this,"markType","underline")}toMarkdown(e,t,A){let i=`<u>${e}</u>`;return t.attrs&&Object.keys(t.attrs).length>0?`${i}<!-- adf:underline attrs='${JSON.stringify(t.attrs)}' -->`:i}},k6=class{constructor(){(0,wi.__publicField)(this,"markType","textColor")}toMarkdown(e,t,A){if(!t.attrs?.color)return e;let{color:i,...r}=t.attrs,n=`<span style="color: ${i}">${e}</span>`;return Object.keys(r).length>0&&(n+=`<!-- adf:textColor attrs='${JSON.stringify(r)}' -->`),n}},k3=class{constructor(){(0,wi.__publicField)(this,"markType","backgroundColor")}toMarkdown(e,t,A){let{color:i}=t.attrs||{},r=`<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`${r}${e}`}return r}},k5=class{constructor(){(0,wi.__publicField)(this,"markType","subsup")}toMarkdown(e,t,A){let i,{type:r}=t.attrs||{};if(i="sub"===r?`<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}},k9=class{constructor(e={}){(0,wi.__publicField)(this,"registry"),(0,wi.__publicField)(this,"validator"),(0,wi.__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 ks,this.validator=new kA,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=[],A=this.validator.validate(e);if(!A.valid){if(this.options.strict)throw Error(`Invalid ADF structure: ${A.errors.map(e=>e.message).join(", ")}`);t.push(...A.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},A=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(A)};e.content&&e.content.forEach(A);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 kk,new kS,new kD,new kR,new kU,new kT,new kF,new kx,new kO,new kN,new kM,new kG,new k_,new kJ,new kL,new kP,new kH,new kY,new kq,new kj,new kK,new kV,new k$,new kW,new kZ,new kz]),this.registry.registerMarks([new kX,new k0,new k1,new k4,new k8,new k2,new k6,new k3,new k5])}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"):""}},k7=class{constructor(e={}){(0,wi.__publicField)(this,"options"),this.options={maxRetries:3,retryDelay:100,fallbackStrategy:"best-effort",onError:()=>{},onRecovery:()=>{},enableLogging:!1,...e}}async executeWithRecovery(e,t){let A,i={operation:"unknown",input:"",attempt:0,previousErrors:[],...t},r=[];for(let t=0;t<=this.options.maxRetries;t++){i.attempt=t;try{let A=await e();return t>0&&this.options.onRecovery&&this.options.onRecovery("retry-success",i),{success:!0,data:A,warnings:r}}catch(e){if(A=e,i.previousErrors.push(A),this.options.onError&&this.options.onError(A,i),this.options.enableLogging&&console.warn(`Attempt ${t+1} failed:`,A.message),this.isNonRetryableError(A))break;t<this.options.maxRetries&&await this.delay(this.options.retryDelay)}}return this.applyFallbackStrategy(A,i,r)}async recoverAdfToMarkdown(e,t,A){let i=[];try{if(e.content&&Array.isArray(e.content)){let t=[];for(let A of e.content)try{let e=await this.recoverNodeConversion(A,"adf-to-markdown");e.success&&e.data?t.push(e.data):(i.push(`Failed to convert node type: ${A.type}`),t.push(this.createNodeFallback(A,"markdown")))}catch(e){i.push(`Node conversion error: ${e}`),t.push(this.createNodeFallback(A,"markdown"))}let r=t.join("\n\n");return this.options.onRecovery&&this.options.onRecovery("node-by-node-recovery",A),{success:!0,data:r,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,A){let i=[];try{let t=this.splitMarkdownIntoSections(e),r=[];for(let e of t)try{let t=await this.parseMarkdownSection(e);t.success&&t.data?r.push(...t.data.content):(i.push(`Failed to parse section: ${e.substring(0,50)}...`),r.push(this.createTextFallback(e)))}catch(t){i.push(`Section parsing error: ${t}`),r.push(this.createTextFallback(e))}return this.options.onRecovery&&this.options.onRecovery("section-by-section-recovery",A),{success:!0,data:{version:1,type:"doc",content:r},strategy:"section-by-section-recovery",fallback:!0,warnings:i}}catch(A){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,A){switch(this.options.fallbackStrategy){case"skip":return A.push("Operation skipped due to errors"),{success:!1,error:e,warnings:A};case"placeholder":let i=this.createPlaceholder(t);return A.push("Used placeholder due to errors"),{success:!0,data:i,strategy:"placeholder",fallback:!0,warnings:A};case"best-effort":return await this.attemptBestEffortRecovery(e,t,A);default:return{success:!1,error:e,warnings:A}}}async attemptBestEffortRecovery(e,t,A){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 A.push("Applied generic fallback recovery"),{success:!1,error:e,strategy:"generic-fallback",warnings:A}}catch(e){return{success:!1,error:e,warnings:A}}}isNonRetryableError(e){return e instanceof kn||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 A=e.attrs?.level||1,i=e.content?this.extractTextFromNodes(e.content):"[Heading]";return"#".repeat(A)+" "+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
|
|
11967
11967
|
|
|
11968
|
-
${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}]`}},Se=class{constructor(e){(0,wi.__publicField)(this,"mdToAdfEngine"),(0,wi.__publicField)(this,"adfToMdEngine"),(0,wi.__publicField)(this,"options"),(0,wi.__publicField)(this,"errorRecovery"),(0,wi.__publicField)(this,"remarkProcessor"),(0,wi.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new kv(this.options),this.adfToMdEngine=new k9(this.options),this.errorRecovery=new k7({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=wb().use(BZ).use(bK,["yaml"]).use(v1).use(ke,{strict:e?.strict||!1}).use(bx),this.registry=new ks,this.registerConverters()}catch(e){throw new kr("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new k9({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!A.success)throw A.error||Error("ADF to Markdown conversion failed");return A.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new kv({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!A.success)throw A.error||Error("Markdown to ADF conversion failed");return A.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!A.success)throw A.error||Error("Async Markdown to ADF conversion failed");return A.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 kA().validate(e)}validateMarkdown(e){return new ki().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new kk,new kS,new kD,new kR,new kU,new kT,new kF,new kx,new kO,new kN,new kM,new kG,new k_,new kJ,new kL,new kP,new kH,new kY,new kq,new kj,new kK,new kV,new k$,new kW,new kZ,new kz]),this.registry.registerMarks([new kX,new k0,new k1,new k4,new k8,new k2,new k6,new k3,new k5])}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 A of e)t++,A.content&&Array.isArray(A.content)&&(t+=this.countNodes(A.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},St=e.i(436057);let SA=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function Si(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function Sr(e,t){return St.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,A)=>t?`[${A}](${t}/browse/${A})`:`**${A}**`))}let Sn=new Se;function Sa(e,t){if(null==e)return null;let A=function(e){if(Si(e))return"ADF";let t="string"==typeof e?e:"";return SA.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),r="ADF"===A?function(e){try{return Sn.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"===A?Sr(i,t):i;return{format:A,raw:e,rawText:i,markdown:r,wikiMarkup:"JIRA_WIKI"===A?i:St.default.to_jira(r)}}function Ss(e){let t=e.value.trim(),A="JIRA_WIKI"===e.format?Sr(t):t,i=Sn.markdownToAdf(A);if(!Si(i))throw Error("The Jira text could not be converted to valid ADF");return i}let So="default",Sl=["summary","status","issuetype","priority","assignee","project","updated"],Sc=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function Su(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Sd(e){return Su(e)?e:{}}function Sh(e){return Array.isArray(e)?e:[]}function Sp(e){return"string"==typeof e&&e.length>0?e:null}function Sg(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Sm(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function Sf(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function SI(e){return Sh(Sf(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function SC(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):Su(t)?Object.fromEntries(Object.keys(t).sort().map(A=>[A,e(t[A])])):t}(e))}function SE(e){if(!Su(e))return null;let t=e.status??Sd(e.response).status;return"number"==typeof t?t:null}function Sy(e,t){let A=e instanceof Error?e.message:String(e);return(t?A.replaceAll(t,"[REDACTED]"):A).slice(0,1e3)}function SQ(e){return Sp(Sd(Sd(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function Sw(e){let t=Sd(e),A=Sp(t.displayName);if(!A)return null;let i=Sd(t.avatarUrls);return{accountId:Sp(t.accountId),displayName:A,avatarUrl:Sp(i["48x48"])??Sp(i["32x32"])??Sp(i["24x24"])}}function SB(e){return Sh(e).map(Sd).map(e=>({id:Sp(e.id),name:Sp(e.name)??"Unknown"}))}function Sb(e,t){let A=Sd(e),i=Sp(A.key);if(!i)return null;let r=Sd(A.fields);return{relationship:t,key:i,summary:Sp(r.summary)??i,status:Sp(Sd(r.status).name)}}function Sv(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function Sk(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function SS(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 SD(e){let t=Sd(e.fields),A=Sd(t.status),i=Sd(A.statusCategory),r=Sd(t.assignee),n=Sd(r.avatarUrls),a=Sd(t.project),s=e.key??"UNKNOWN";return{id:e.id??s,key:s,summary:Sp(t.summary)??s,statusId:Sp(A.id)??Sp(A.name)??"unknown",status:Sp(A.name)??"Unknown",statusCategory:Sp(i.key)??Sp(i.name)??"unknown",issueType:Sp(Sd(t.issuetype).name),priority:Sp(Sd(t.priority).name),assignee:Sp(r.displayName),assigneeAccountId:Sp(r.accountId),assigneeAvatarUrl:Sp(n["48x48"])??Sp(n["32x32"]),projectKey:Sp(a.key)??SQ(e),updatedAt:Sp(t.updated)}}function SR(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let SU=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function ST(e){return SU.has(e)?e:"ALL"}class SF{credentials;workflowEvents;inFlight;clients;lastPrunedAt;constructor(e=new Q8,t){this.credentials=e,this.workflowEvents=t,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let A=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:A?{id:A.id,body:A.content?.rawText??"",author:A.author}:null,...void 0!==t?{changelog:t}:{}},r=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,a=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",A?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",A?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&a.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()))),A=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&A.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&A.add("JIRA_LABEL"),e.has("assignee")&&A.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(A.add("JIRA_SPRINT_STARTED"),A.add("JIRA_SPRINT_ENDED")),a=a.filter(([e])=>A.has(e))}await Promise.allSettled(a.map(([t,A])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${r}`,payload:{...i,sessionData:i,cursorValue:A}})))}async getSettings(){let e=await aE(),t=await e.jiraSettings.upsert({where:{id:So},create:{id:So,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(Qj.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await aE(),A=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 r=await t.jiraSettings.findUnique({where:{id:So}}),n=e.apiToken?.trim()||null,a=!!(r?.siteUrl&&r.siteUrl!==A);if(a&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let s=r?.siteUrl!==A||r?.email!==i||!!n,o=async e=>{a&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),s&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:So},create:{id:So,siteUrl:A,email:i,cacheTtlSeconds:300},update:a?{siteUrl:A,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:A,email:i}})};return n?await this.credentials.setText(Qj.jiraApiToken,n,o):await t.$transaction(o),a&&await this.credentials.delete(Qj.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:So},select:{siteUrl:!0,email:!0,webhookId:!0}}),A=await this.credentials.isConfigured(Qj.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&A)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==SE(e))throw e}return await this.credentials.deleteMany([Qj.jiraApiToken,Qj.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:So},create:{id:So,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 aE();return await t.jiraSettings.upsert({where:{id:So},create:{id:So,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=Sd(e.value);return{accountId:Sp(t.accountId),displayName:Sp(t.displayName)??"Jira user",emailAddress:Sp(t.emailAddress),cache:Sk(e)}}async listProjects(){let e=await aE();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:ST(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:SI(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??we,sources:e.sources.map(Sv)}))}async projectStatuses(e){let t=await aE(),A=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!A)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:A.jiraId},requestSummary:`Statuses for project ${A.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(A.jiraId)}}),r=new Map;for(let e of Sh(i.value).map(Sd))for(let t of Sh(e.statuses).map(Sd)){let e=Sp(t.id),A=Sp(t.name);if(!e||!A||r.has(e))continue;let i=Sd(t.statusCategory);r.set(e,{id:e,name:A,category:Sp(i.key)??Sp(i.name)??"unknown"})}return[...r.values()].sort((e,t)=>SR(e.category)-SR(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!SU.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),A=await aE(),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 A.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 A=await aE(),i=await A.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let r=await wA(t,i.key);return await A.jiraProject.update({where:{id:e},data:{branchNamingScript:r}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let A=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=>Sh(Sd(e).values).length}),i=Sd(A.value),r=Sh(i.values).map(Sd);e.push(...r.flatMap(e=>{let t=Sp(e.id),A=Sp(e.key),i=Sp(e.name);if(!t||!A||!i)return[];let r=Sd(e.avatarUrls);return[{jiraId:t,key:A,name:i,avatarUrl:Sp(r["48x48"])??Sp(r["32x32"])}]}));let n=Sg(i.total)??e.length;if(0===r.length||e.length>=n)break;t+=r.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let A=Sd((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),i=Sp(A.key),r=Sp(A.name),n=Sp(A.id);if(!i||!r||!n)throw Error("Jira returned an incomplete project");let a=Sd(A.avatarUrls),s=await aE(),o=await s.jiraProject.aggregate({_max:{position:!0}});return await s.jiraProject.create({data:{id:(0,AB.randomUUID)(),jiraId:n,key:i,name:r,avatarUrl:Sp(a["48x48"])??Sp(a["32x32"]),position:(o._max.position??-1)+1,branchNamingScript:we}}),this.listProjects()}async removeProject(e){let t=await aE(),A=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{A.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:A}}}),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),A=this.validateSourceName(e.name),i=await aE();if(!await i.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let r=await i.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await i.jiraSource.create({data:{id:(0,AB.randomUUID)(),projectId:e.projectId,name:A,kind:e.kind,value:t.value,boardId:t.boardId,position:(r._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),A=this.validateSourceName(e.name),i=await aE();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:A,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await aE();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 A;let i,r,n,a=await aE(),s=await a.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!s)throw Error("Jira source not found");let o=await a.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),l=new Set(o?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===s.kind?await this.loadBoardSource(Sv(s),t):await this.loadJqlSource(Sv(s),t),u={ticketAssignmentFilter:ST(s.project.ticketAssignmentFilter),hideCompletedTickets:s.project.hideCompletedTickets,completedStatusIds:SI(s.project.completedStatusIdsJson)},d="ALL"===u.ticketAssignmentFilter?null:await this.currentAccountId(),h=(A={source:Sv(s),...c},i=u.hideCompletedTickets?new Set(u.completedStatusIds):new Set,r=new Set(A.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=A.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===u.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===u.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===d:null!==d&&e.assigneeAccountId===d&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...A,tickets:n,statusOrder:A.statusOrder.filter(e=>!r.has(e))});return this.workflowEvents&&o&&await Promise.allSettled(h.tickets.filter(({key:e})=>!l.has(e)).map(t=>{let A={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:{...A,sessionData:A,source:{id:e,name:s.name,kind:s.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,A){let i=Sm(e),r=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"===r.source&&await this.storeDetail(r.entryId,r.value,r.fetchedAt);let n=[],a=[],s=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:s,maxResults:100},requestSummary:`Comments for ${i} from ${s}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:s,maxResults:100,orderBy:"created"})},itemCount:e=>Sh(Sd(e).comments).length});n.push(e);let A=Sd(e.value),r=Sh(A.comments);a.push(...r);let o=Sg(A.total)??a.length;if(0===r.length||a.length>=o)break;s+=r.length}let o=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,a,o,n.map(e=>e.entryId));let l=await this.requireCredentials(),c=this.normalizeTicketDetail(r.value,a,l.siteUrl,Sk(r),SS(n));return await this.recordTicketWorkflowEvents(c,A),c}async assignableUsers(e,t=""){let A=Sm(e),i=t.trim().slice(0,100),r=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:A,query:i,maxResults:50},requestSummary:`Assignable users for ${A}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:A,query:i,maxResults:50,recommend:!0})},itemCount:e=>Sh(e).length});return await this.linkCacheEntryToIssue(A,r.entryId),Sh(r.value).map(Sw).filter(e=>null!==e)}async ticketTransitions(e){let t=Sm(e),A=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=>Sh(Sd(e).transitions).length});return await this.linkCacheEntryToIssue(t,A.entryId),Sh(Sd(A.value).transitions).map(Sd).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=Sp(e.id),A=Sp(e.name);if(!t||!A)return[];let i=Sd(e.to),r=Sd(i.statusCategory),n=Object.entries(Sd(e.fields)).filter(([,e])=>!0===Sd(e).required).map(([e,t])=>Sp(Sd(t).name)??e);return[{id:t,name:A,toStatusId:Sp(i.id),toStatus:Sp(i.name)??A,toStatusCategory:Sp(r.key)??Sp(r.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=Sm(e),A=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(Sd(Sd(e).fields)).length});return await this.linkCacheEntryToIssue(t,A.entryId),Object.entries(Sd(Sd(A.value).fields)).map(([e,t])=>{let A=Sd(t);return{id:e,name:Sp(A.name)??e,required:!0===A.required,schemaType:Sp(Sd(A.schema).type),allowedValues:Sh(A.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=Sd(e),A=Sp(t.name)??Sp(t.value)??Sp(t.displayName)??Sp(t.key);return A?[{id:Sp(t.id)??Sp(t.accountId)??Sp(t.value)??A,name:A}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,A=0){let i=Sm(e),r=this.validatePagination(t,A),n=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Changelog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>Sh(Sd(e).values).length});await this.linkCacheEntryToIssue(i,n.entryId);let a=Sg(Sd(n.value).total)??0,s=Math.min(r.limit,Math.max(0,a-r.offset)),o=Math.max(0,a-r.offset-s);if(0===s)return{...r,total:a,items:[],cache:Sk(n)};let l=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:o,maxResults:s},requestSummary:`Changelog for ${i} from ${o}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:o,maxResults:s})},itemCount:e=>Sh(Sd(e).values).length});await this.linkCacheEntryToIssue(i,l.entryId);let c=Sh(Sd(l.value).values).map(Sd).reverse().map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),createdAt:Sp(e.created),items:Sh(e.items).map(Sd).map(e=>({field:Sp(e.field)??"Field",fieldId:Sp(e.fieldId),from:Sp(e.fromString)??Sp(e.from),to:Sp(e.toString)??Sp(e.to)}))}));return{...r,total:a,items:c,cache:SS([n,l])}}async ticketWorklogs(e,t=50,A=0){let i=Sm(e),r=this.validatePagination(t,A),n=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Worklog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>Sh(Sd(e).worklogs).length});await this.linkCacheEntryToIssue(i,n.entryId);let a=Sg(Sd(n.value).total)??0,s=Math.min(r.limit,Math.max(0,a-r.offset)),o=Math.max(0,a-r.offset-s);if(0===s)return{...r,total:a,items:[],cache:Sk(n)};let l=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:o,maxResults:s},requestSummary:`Worklogs for ${i} from ${o}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:o,maxResults:s})},itemCount:e=>Sh(Sd(e).worklogs).length});await this.linkCacheEntryToIssue(i,l.entryId);let c=await this.requireCredentials(),u=Sh(Sd(l.value).worklogs).map(Sd).reverse().map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),comment:Sa(e.comment??null,c.siteUrl),timeSpent:Sp(e.timeSpent),timeSpentSeconds:Sg(e.timeSpentSeconds),startedAt:Sp(e.started),createdAt:Sp(e.created),updatedAt:Sp(e.updated)})),d=u[0];if(this.workflowEvents&&d){let e={ticket:{key:i},worklog:{id:d.id,author:d.author,timeSpent:d.timeSpent,timeSpentSeconds:d.timeSpentSeconds,startedAt:d.startedAt,updatedAt:d.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:i,dedupeKey:`jira-worklog:${i}:${d.id}:${l.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:d.id}})}return{...r,total:a,items:u,cache:SS([n,l])}}async addComment(e,t){let A=Sm(e);if(!t.value.trim())throw Error("Comment text is required");let i=Ss(t);return this.mutateTicket(A,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:A,comment:i})})}async assignTicket(e,t){let A=Sm(e),i=t?.trim()||null;return this.mutateTicket(A,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:A,accountId:i})})}async transitionTicket(e,t){let A=Sm(e),i=(await this.ticketTransitions(A)).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(A,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:A,transition:{id:i.id}})})}async transitionTicketToConfiguredDone(e){let t=Sm(e),A=t.split("-")[0]??"",i=await aE(),r=await i.jiraProject.findUnique({where:{key:A},select:{doneStatusId:!0}});if(!r?.doneStatusId)throw Error(`Configure a done status for Jira project ${A} before using this option`);let n=await this.ticket(t);if(n.statusId===r.doneStatusId)return n;let a=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===r.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!a)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,a.id)}async updateTicket(e){let t=Sm(e.issueKey),A=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},r=e=>{let t=A.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")){r("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=r("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=Ss(e.description))}if(n("priorityId")){let t=r("priority"),A=e.priorityId?.trim()||null;if(!A&&t.required)throw Error("Priority is required");if(A&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===A))throw Error("The selected priority is not available");i.priority=A?{id:A}:null}n("labels")&&(r("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let a=(t,A)=>{if(!n(t))return;let a=r(A),s=[...new Set(e[t]??[])];if(a.allowedValues.length>0&&s.some(e=>!a.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${a.name} value is not available`);i[A]=s.map(e=>({id:e}))};if(a("componentIds","components"),a("fixVersionIds","fixVersions"),a("affectedVersionIds","versions"),n("dueDate")){let t=r("duedate"),A=e.dueDate?.trim()||null;if(A&&!/^\d{4}-\d{2}-\d{2}$/.test(A))throw Error("Due date must use YYYY-MM-DD");if(!A&&t.required)throw Error("Due date is required");i.duedate=A}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(),A=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!A||!i)throw Error("Project, issue type, and summary are required");let{version3:r}=await this.getClients(),n=await r.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:A},summary:i,...e.description?{description:Ss(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=Sm(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:A}=await this.getClients();return await A.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:Ss(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=Sm(e.inwardIssueKey),A=Sm(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:r}=await this.getClients();return await r.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:A}}),this.ticket(t,!0)}async branchTicket(e){let t=Sm(e),A=t.replace(/-\d+$/,""),i=await aE(),r=await i.jiraProject.findUnique({where:{key:A},select:{key:!0,branchNamingScript:!0}});if(!r)throw Error(`Jira project ${A} 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 a=Sd(n.value.fields);if((Sp(Sd(a.project).key)??SQ(n.value))!==r.key)throw Error(`Jira ticket ${t} does not belong to project ${r.key}`);return{ticketKey:n.value.key??t,ticketTitle:Sp(a.summary)??t,ticketType:Sp(Sd(a.issuetype).name),projectKey:r.key,branchNamingScript:r.branchNamingScript??we}}async clearCache(){let e=await aE();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await aE();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(Sm(e)),!0}async invalidateIssueCaches(e){let t=await aE(),A=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{A.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:A.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e,t){let A=await aE(),i=await A.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await A.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:A}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>A.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=Sp(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return Sm(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),A=[],i=0;for(;A.length<1e3;){let r=Math.min(100,1e3-A.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:r,fields:["key"]}),a=n.issues??[];A.push(...a.flatMap(e=>{let t=Sp(e.key);return t?[Sm(t)]:[]}));let s=void 0===n.total?a.length<r:i+a.length>=n.total;if(0===a.length||s)break;i+=a.length}let r=[],n=[...new Set(A)];for(let e=0;e<n.length;e+=5)r.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return r}async listCachedTickets(e=50,t=0){let A=this.validatePagination(e,t),i=await aE(),[r,n,a]=await Promise.all([i.jiraCachedTicket.findMany({take:A.limit,skip:A.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...A,total:n,items:r.map(e=>this.cachedTicketView(e,a.cacheTtlSeconds))}}async cachedTicket(e){let t=await aE(),[A,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return A?{...this.cachedTicketView(A,i.cacheTtlSeconds),summaryData:Sf(A.summaryJson),detailData:Sf(A.detailJson),commentsData:Sf(A.commentsJson),cacheEntries:A.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 A=this.validatePagination(e,t);await this.pruneLogs();let i=await aE(),[r,n]=await Promise.all([i.jiraApiCallLog.findMany({take:A.limit,skip:A.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...A,total:n,items:r.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 aE(),t=Date.now(),A=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-Sc.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:Sc.map(e=>this.metricWindow(e.window,A.filter(A=>A.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(A.map(e=>e.operation))].sort().map(e=>({operation:e,windows:Sc.map(i=>this.metricWindow(i.window,A.filter(A=>A.operation===e&&A.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:So}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let A=await this.credentials.getText(Qj.jiraApiToken);if(!A)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:A,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,AB.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let A={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new Qv(A),agile:new Ej(A)},this.clients}async webhookApiRequest(e,t,A){let i,r=await this.requireCredentials(),n=Buffer.from(`${r.email}:${r.apiToken}`).toString("base64");try{i=await fetch(`${r.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===A?void 0:JSON.stringify(A),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(Sy(e,r.apiToken))}let a=await i.text();if(!i.ok){let e=a.trim().slice(0,300)||i.statusText;throw Object.assign(Error(Sy(`Jira rejected the webhook request with ${i.status}: ${e}`,r.apiToken)),{status:i.status})}if(!a.trim())return null;try{return JSON.parse(a)}catch{return null}}async currentAccountId(){let e=Sp(Sd((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 A=await aE();await A.$transaction(async A=>{await A.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await A.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,A){let i=await this.requireCredentials(),r=Date.now();try{await A(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-r})}catch(n){let A=Sy(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-r,statusCode:SE(n),error:A}),Error(A)}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: ${Sy(e,i.apiToken)}`)}}cacheKey(e,t,A){return(0,AB.createHash)("sha256").update(SC({siteUrl:e,operation:t,params:A})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),A=await aE(),i=this.cacheKey(t.siteUrl,e.operation,e.params),r=Date.now(),n=await A.jiraCacheEntry.findUnique({where:{cacheKey:i}}),a=null!==n&&Date.now()-n.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&a)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-r,itemCount:e.itemCount?.(Sf(n.responseJson))??null,sourceId:e.sourceId}),{value:Sf(n.responseJson),source:"CACHE",stale:!1,fetchedAt:n.fetchedAt,entryId:n.id};let s=this.inFlight.get(i);if(s){let t=await s;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-r,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let o=(async()=>{try{let t=await e.fetcher(),n=new Date,a=await A.jiraCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,AB.randomUUID)(),cacheKey:i,operation:e.operation,paramsJson:SC(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:SC(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-r,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:n,entryId:a.id}}catch(i){let A=null!==n&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-r,statusCode:SE(i),error:Sy(i,t.apiToken),servedStale:A,sourceId:e.sourceId}),A)return{value:Sf(n.responseJson),source:"ERROR",stale:!0,fetchedAt:n.fetchedAt,entryId:n.id};throw Error(Sy(i,t.apiToken))}})();this.inFlight.set(i,o);try{return await o}finally{this.inFlight.delete(i)}}async logCall(e){let t=await aE();await t.jiraApiCallLog.create({data:{id:(0,AB.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 A=t.trim();if(!A)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:A},requestSummary:`Validate JQL: ${A}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:A,maxResults:1,fields:["key"],failFast:!0})}}),{value:A,boardId:null};let i=function(e,t){let A=new URL(e.trim());if(A.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=A.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),r=A.searchParams.get("rapidView"),n=Number(i?.[1]??r);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:A.toString()}}(A,(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 A,i=[],r=[],n=[],a=!1;do{let s=Math.min(100,1e3-i.length),o=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:A??null,maxResults:s,fields:Sl},requestSummary:`JQL ${e.name}${A?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:A,maxResults:s,fields:Sl})},itemCount:e=>e.issues?.length??0});r.push(o);let l=o.value.issues??[];i.push(...l),n.push(...o.value.warningMessages??[]),"LIVE"===o.source&&await this.storeSummaries(o.entryId,l,o.fetchedAt),A=o.value.nextPageToken,i.length>=1e3&&A&&(a=!0)}while(A&&i.length<1e3)return this.buildBoardResult(i,r,n,a)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let A=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})}}),r=[A,i],n=[],a=[],s=!1;if("scrum"===(Sp(A.value.type)??"").toLowerCase()){let A=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=>Sh(e.values).length});r.push(A);let i=Sh(A.value.values).map(Sd);for(let A of(0===i.length&&a.push("This Scrum board has no active sprint."),i)){let i=Sg(A.id);if(!i||n.length>=1e3)continue;let o=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:Sl}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...o.issues),r.push(...o.results),a.push(...o.warnings),s||=o.truncated}}else{let A=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,A)=>({boardId:e.boardId,startAt:t,maxResults:A,fields:Sl}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...A.issues),r.push(...A.results),a.push(...A.warnings),s=A.truncated}let o=[...new Map(n.map(e=>[e.key??e.id,e])).values()],l=new Map;return Sh(Sd(i.value.columnConfig).columns).map(Sd).forEach((e,t)=>{Sh(e.statuses).map(Sd).forEach(e=>{let A=Sp(e.id);A&&l.set(A,t)})}),this.buildBoardResult(o,r,a,s,l)}async loadAgileIssues(e,t,A,i,r,n){let a=[],s=[],o=[],l=0,c=1/0,u=!1;for(;l<c&&a.length+n<1e3;){let u=i(l,Math.min(100,1e3-n-a.length)),d=await this.cachedCall({operation:e,params:u,requestSummary:`${e.replaceAll("_"," ")} from ${l}`,sourceId:t.id,force:A,fetcher:()=>r(u),itemCount:e=>e.issues?.length??0});s.push(d);let h=d.value.issues??[];if(a.push(...h),o.push(...d.value.warningMessages??[]),"LIVE"===d.source&&await this.storeSummaries(d.entryId,h,d.fetchedAt),c=d.value.total??a.length,0===h.length)break;l+=h.length}return a.length+n>=1e3&&l<c&&(u=!0),{issues:a,results:s,warnings:o,truncated:u}}buildBoardResult(e,t,A,i,r){let n=e.slice(0,1e3).map(SD),a=[...new Map(n.map(e=>[e.status,e])).values()];return a.sort((e,t)=>{let A=r?.get(e.statusId),i=r?.get(t.statusId);return void 0!==A||void 0!==i?(A??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):SR(e.statusCategory)-SR(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:a.map(e=>e.status),cache:SS(t),truncated:i,warnings:[...new Set(A)]}}async storeSummaries(e,t,A){let i=await aE();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:SQ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:A},update:{projectKey:SQ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:A}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let r=[...new Set(t.map(e=>e.key).filter(Boolean))];r.length>0&&await i.jiraCacheEntryIssue.createMany({data:r.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,A){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await aE();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:SQ(t),detailJson:JSON.stringify(t),detailFetchedAt:A},update:{projectKey:SQ(t),detailJson:JSON.stringify(t),detailFetchedAt:A}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,A,i){let r=await aE();await r.$transaction(async r=>{for(let n of(await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:A},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:A}}),i))await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,A,i,r){let n=SD(e),a=Sd(e.fields),s=Sd(e.names),o=Sd(e.schema),l=[];for(let e of Sh(a.issuelinks).map(Sd)){let t=Sd(e.type),A=Sb(e.outwardIssue,Sp(t.outward)??"relates to"),i=Sb(e.inwardIssue,Sp(t.inward)??"relates to");A&&l.push(A),i&&l.push(i)}let c=Sb(a.parent,"parent"),u=Sh(a.subtasks).map(e=>Sb(e,"subtask")).filter(e=>null!==e),d=Sh(a.sprint).map(Sd),h=Sh(a.closedSprints).map(Sd),p=d.filter(e=>{let t=Sp(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>Sp(e.name)).filter(e=>!!e),g=h.concat(d.filter(e=>Sp(e.state)?.toLowerCase()==="closed")).map(e=>Sp(e.name)).filter(e=>!!e),m=p.concat(g),f=t.map(Sd).map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),body:e.body??null,content:Sa(e.body??null,A),createdAt:Sp(e.created),updatedAt:Sp(e.updated)}));return{...n,jiraUrl:`${A}/browse/${n.key}`,description:a.description??null,descriptionContent:Sa(a.description??null,A),reporter:Sw(a.reporter),creator:Sw(a.creator),labels:Sh(a.labels).filter(e=>"string"==typeof e),components:SB(a.components),fixVersions:SB(a.fixVersions),affectedVersions:SB(a.versions),sprintNames:[...new Set(m)],activeSprintNames:[...new Set(p)],closedSprintNames:[...new Set(g)],parent:c,subtasks:u,issueLinks:l,attachments:Sh(a.attachment).map(Sd).map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),filename:Sp(e.filename)??"Attachment",contentUrl:Sp(e.content),mimeType:Sp(e.mimeType),size:Sg(e.size),author:Sw(e.author),createdAt:Sp(e.created)})),comments:f,createdAt:Sp(a.created),dueAt:Sp(a.duedate),resolvedAt:Sp(a.resolutiondate),timeTracking:a.timetracking??null,allFields:Object.entries(a).map(([e,t])=>{let i=Sd(o[e]),r="string"==typeof t||Su(t)&&"doc"===t.type?Sa(t,A):null;return{id:e,name:Sp(s[e])??e,schemaType:Sp(i.type),custom:!0===i.custom||e.startsWith("customfield_"),value:t??null,content:r}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:i,commentsCache:r}}cachedTicketView(e,t){let A=SD(Sd(Sf(e.detailJson)??Sf(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",r=[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:A.summary,status:"Unknown"===A.status?null:A.status,coverage:i,stale:r,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 aE();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let Sx="default",SO=/^[A-Z][A-Z0-9_]*-\d+$/,SN=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"]),SM={"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"},SG="/api/public/jira/webhook",S_="/rest/webhooks/1.0/webhook",SJ=new Set(["localhost","0.0.0.0","::1","[::1]",""]),SL=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class SP extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function SH(e){return"string"==typeof e&&e.trim()?e.trim():null}function SY(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function Sq(e){let t=Sj(e);if(!t)return null;let A=Array.isArray(t.items)?t.items:[];return{id:SY(t.id),items:A.map(Sj).filter(e=>null!==e).map(e=>({field:SH(e.field)??SH(e.fieldId)??"Field",fieldId:SH(e.fieldId),fieldType:SH(e.fieldtype)??SH(e.fieldType),from:SY(e.from),fromString:SY(e.fromString),to:SY(e.to),toString:SY(e.toString)}))}}function Sj(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function SK(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function SV(e){let t=Sj(e);return t?{accountId:SH(t.accountId),displayName:SH(t.displayName)}:null}class S${jira;credentials;workflowEvents;constructor(e,t,A){this.jira=e,this.credentials=t,this.workflowEvents=A}async webhooksEnabled(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(Qj.jiraWebhookSecret)}async getWebhookSettings(){let e=await aE(),[t,A,i]=await Promise.all([e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx},update:{}}),this.credentials.isConfigured(Qj.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&A,secretConfigured:A,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,AB.randomBytes)(32).toString("base64url");return await this.credentials.setText(Qj.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx,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 A=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(SJ.has(A)||A.endsWith(".local")||A.endsWith(".localhost")||/^127\./.test(A)||/^10\./.test(A)||/^192\.168\./.test(A)||/^172\.(1[6-9]|2\d|3[01])\./.test(A))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}${SG}`;if(i.endsWith(SG))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${SG}`)}(e.url),A=e.jql?.trim()||null,i=(0,AB.randomBytes)(32).toString("base64url"),r=await aE(),n=await r.jiraSettings.findUnique({where:{id:Sx},select:{webhookId:!0}}),a=await this.writeToJira({webhookId:n?.webhookId??null,url:t,jql:A,secret:i});return await this.credentials.setText(Qj.jiraWebhookSecret,i,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:a,webhookUrl:t,webhookJql:A},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:a,webhookUrl:t,webhookJql:A}})}),{settings:await this.getWebhookSettings(),secret:i}}async rotateSecret(){if(!await this.credentials.isConfigured(Qj.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},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 aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(Qj.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,A,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...SL],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${S_}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==SK(e))throw e}}let r=await this.jira.webhookApiRequest("POST",S_,i),n=(t=SH(r?.self),(A=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(A):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",`${S_}/${encodeURIComponent(e)}`)}catch(e){if(404!==SK(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 A=await this.webhooksEnabled();if(!A)return{enabled:A,items:[],total:0,limit:e,offset:t};let i=await aE(),[r,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:A,items:r.map(SW),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await aE();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await aE();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,A,i,r,n,a;let s,o,l=await this.credentials.getText(Qj.jiraWebhookSecret);if(!l)throw new SP("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new SP("Jira webhook signature is missing",401);if(t=`sha256=${(0,AB.createHmac)("sha256",l).update(e.body).digest("hex")}`,A=e.signature,s=Buffer.from(t),o=Buffer.from(A),!(s.length===o.length&&(0,AB.timingSafeEqual)(s,o)))throw new SP("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new SP("Jira delivery ID is missing",400);let c=await aE(),u=e.deliveryId.trim(),d=Number.parseInt(e.retryCount??"",10),h=Number.isInteger(d)?d:null;try{await c.jiraWebhookDelivery.create({data:{deliveryId:u,event:"unknown",outcome:"RECEIVED",retryCount:h}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await c.jiraWebhookDelivery.updateMany({where:{deliveryId:u,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:h,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 p=async(e,t=null)=>{let A=await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{outcome:e,error:t,processedAt:new Date}});aw.publish(aF,{jiraWebhookDeliveryChanged:SW(A)})};try{let t,A,s,o,l,d;try{let A=JSON.parse(Buffer.from(e.body).toString("utf8")),i=Sj(A);if(!i)throw Error("Payload is not an object");t=i}catch{throw new SP("Jira webhook payload is invalid JSON",400)}let g=SH(t.webhookEvent),m=(i=t,A=Sj(i.issue),(s=SH(A?.key)?.toUpperCase()??null)&&SO.test(s)?s:null),f=(r=t,o=Sj(r.issue),l=Sj(o?.fields),d=Sj(l?.project)??Sj(r.project),SH(d?.key)?.toUpperCase()??null),I=Sq(t.changelog);if(await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{event:g??"unknown",issueKey:m,projectKey:f,changelogJson:I?JSON.stringify(I):null}}),!g)return await p("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};if(!(SN.has(g)||"jira:issue_deleted"===g))return await p("IGNORED",`Unhandled Jira event ${g}`),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let C=m?[m]:[];if("issuelink_created"===g||"issuelink_deleted"===g){let e,A,i=(n=t,e=Sj(n.issueLink),[SY(e?.sourceIssueId),SY(e?.destinationIssueId)].filter((e,t,A)=>!!(e&&A.indexOf(e)===t)));if(0===i.length)return await p("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};f=(m=(C=await this.jira.resolveIssueKeys(i))[0]??null)?f??((A=(a=m).lastIndexOf("-"))>0?a.slice(0,A):null):f,await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{issueKey:m,projectKey:f}})}let E="sprint_started"===g||"sprint_closed"===g;if(!E&&!m)return await p("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let y=[];if("jira:issue_deleted"===g)await this.jira.deleteCachedTicket(m),y.push({key:m,projectKey:f});else if(E){let e=function(e){let t=SY(Sj(e.sprint)?.id);if(!t)return null;let A=Number(t);return Number.isSafeInteger(A)&&A>0?A:null}(t);if(!e)return await p("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let A=await this.jira.refreshSprintTickets(e);y.push(...A.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===g){let e=await this.jira.refreshCachedTicket(m,I);y.push({key:e.key,projectKey:e.projectKey})}else if(SN.has(g)){let e=await Promise.all(C.map(e=>this.jira.refreshCachedTicket(e)));y.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let Q=m?await this.recordWebhookTrigger({event:g,deliveryId:u,issueKey:m,projectKey:f,retries:h,payload:t}):0;for(let e of y)aw.publish(ax,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:g}});return await p("PROCESSED"),{outcome:"PROCESSED",event:g,issueKey:m,triggersRecorded:Q}}catch(t){let e=t instanceof Error?t.message:String(t);throw await p("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=SM[e.event];if(!t)return 0;let{payload:A}=e,i=Sj(A.issue),r=Sj(i?.fields),n=Sj(A.comment),a=Sj(A.attachment),s=Sj(A.issueLink),o=Sj(r?.status),l=Sq(A.changelog),c={ticket:{key:e.issueKey,title:SH(r?.summary),type:SH(Sj(r?.issuetype)?.name),status:SH(o?.name),statusId:SH(o?.id),statusCategory:SH(Sj(o?.statusCategory)?.key),assignee:SH(Sj(r?.assignee)?.displayName),assigneeAccountId:SH(Sj(r?.assignee)?.accountId),labels:Array.isArray(r?.labels)?r.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:SH(n.id),body:SH(n.body)??"",author:SV(n.author)}:null,attachment:a?{id:SH(a.id),filename:SH(a.filename),mimeType:SH(a.mimeType),author:SV(a.author)}:null,link:s?{id:SH(s.id),type:SH(Sj(s.issueLinkType)?.name),sourceIssueId:SH(s.sourceIssueId),destinationIssueId:SH(s.destinationIssueId)}:null,user:SV(A.user),changelog:l};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}}})}}function SW(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return Sq(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}}function SZ(e){if(e.agentId)throw Error("Agent credentials cannot perform control-plane operations")}function Sz(e,t,...A){if((A=A.filter(Boolean)).length>2){let t=A.pop();e+=`one of type ${A.join(", ")}, or ${t}.`}else 2===A.length?e+=`one of type ${A[0]} or ${A[1]}.`:e+=`of type ${A[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let SX=(e,t,...A)=>Sz(`Key for the ${e} algorithm must be `,t,...A);function S0(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),A=new Uint8Array(t.length);for(let e=0;e<t.length;e++)A[e]=t.charCodeAt(e);return A}class S1 extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class S4 extends S1{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class S8 extends S1{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class S2 extends S1{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class S6 extends S1{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}let S3=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},S5=e=>e?.[Symbol.toStringTag]==="KeyObject",S9=e=>S3(e)||S5(e),S7=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let A=0;A<e.byteLength;A++)if(e[A]!==t[A])return!1;return!0},De=e=>{let t=e.data[e.pos++];if(128&t){let A=127&t,i=0;for(let t=0;t<A;t++)i=i<<8|e.data[e.pos++];return i}return t},Dt=(e,t,A)=>{if(e.data[e.pos++]!==t)throw Error(A)},DA=(e,t)=>{let A=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,A},Di=async(e,t,A,i)=>{let r,n,a="spki"===e,s=()=>a?["verify"]:["sign"];switch(A){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${A.slice(-3)}`},n=s();break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${A.slice(-3)}`},n=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(A.slice(-3),10)||1}`},n=a?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":r={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[A]},n=s();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{let e=i.getNamedCurve(t);r="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new S4("Invalid or unsupported key format")}n=a?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":r={name:"Ed25519"},n=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":r={name:A},n=s();break;default:throw new S4('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,r,i?.extractable??!!a,n)};async function Dr(e,t,A){let i,r,n;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return i=/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,r=S0(e.replace(i,"")),n=A,t?.startsWith?.("ECDH-ES")&&((n||={}).getNamedCurve=e=>{let t,A={data:e,pos:0};return Dt(A,48,"Invalid PKCS#8 structure"),De(A),Dt(A,2,"Expected version field"),t=De(A),A.pos+=t,Dt(A,48,"Expected algorithm identifier"),De(A),A.pos,(e=>{let t,A=(Dt(e,6,"Expected algorithm OID"),t=De(e),DA(e,t));if(S7(A,[43,101,110]))return"X25519";if(!S7(A,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");Dt(e,6,"Expected curve OID");let i=De(e),r=DA(e,i);for(let{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(S7(r,t))return e;throw Error("Unsupported named curve")})(A)}),Di("pkcs8",r,t,n)}let Dn=new TextEncoder,Da=new TextDecoder;function Ds(e){let t=new Uint8Array(e.length);for(let A=0;A<e.length;A++){let i=e.charCodeAt(A);if(i>127)throw TypeError("non-ASCII string encountered in encode()");t[A]=i}return t}function Do(e){let t=e;return("string"==typeof t&&(t=Dn.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let A=0;A<e.length;A+=32768)t.push(String.fromCharCode.apply(null,e.subarray(A,A+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}let Dl=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Dc(e,t){if(parseInt(e.hash.name.slice(4),10)!==t)throw Dl(`SHA-${t}`,"algorithm.hash")}async function Du(e,t,A){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>Sz("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[A])}return!function(e,t,A){switch(t){case"HS256":case"HS384":case"HS512":if("HMAC"!==e.algorithm.name)throw Dl("HMAC");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==e.algorithm.name)throw Dl("RSASSA-PKCS1-v1_5");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==e.algorithm.name)throw Dl("RSA-PSS");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==e.algorithm.name)throw Dl("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let i;if(i=e.algorithm,i.name!==t)throw Dl(t);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==e.algorithm.name)throw Dl("ECDSA");let A=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==A)throw Dl(A,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(A&&!e.usages.includes(A))throw TypeError(`CryptoKey does not support this operation, its usages must include ${A}.`)}(t,e,A),t}async function Dd(e,t,A){let i=await Du(e,t,"sign");return!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:A}=t.algorithm;if("number"!=typeof A||A<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}(e,i),new Uint8Array(await crypto.subtle.sign(function(e,t){let A=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:A,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:A,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:A,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:A,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new S4(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm),i,A))}function Dh(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}let Dp=e=>Dh(e)&&"string"==typeof e.kty,Dg=e=>e?.[Symbol.toStringTag],Dm=(e,t,A)=>{if(void 0!==t.use){let e;switch(A){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let i;switch(!0){case"sign"===A||"verify"===A:case"dir"===e:case e.includes("CBC-HS"):i=A;break;case e.startsWith("PBES2"):i="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===A?"wrapKey":"unwrapKey":A;break;case"encrypt"===A&&e.startsWith("RSA"):i="wrapKey";break;case"decrypt"===A:i=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(i&&t.key_ops?.includes?.(i)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}return!0},Df='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function DI(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:A}=function(e){let t,A;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},A=e.priv?["sign"]:["verify"];break;default:throw new S4(Df)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},A=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},A=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},A=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new S4(Df)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[e.alg]},A=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},A=e.d?["deriveBits"]:[];break;default:throw new S4(Df)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},A=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},A=e.d?["deriveBits"]:[];break;default:throw new S4(Df)}break;default:throw new S4('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:A}}(e),i={...e};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,t,e.ext??(!e.d&&!e.priv),e.key_ops??A)}let DC="given KeyObject instance cannot be used for this algorithm",DE=async(e,A,i,r=!1)=>{let n=(t||=new WeakMap).get(e);if(n?.[i])return n[i];let a=await DI({...A,alg:i});return r&&Object.freeze(e),n?n[i]=a:t.set(e,{[i]:a}),a};async function Dy(e,A){if(e instanceof Uint8Array||S3(e))return e;if(S5(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,A)=>{let i,r=(t||=new WeakMap).get(e);if(r?.[A])return r[A];let n="public"===e.type,a=!!n;if("x25519"===e.asymmetricKeyType){switch(A){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(DC)}i=e.toCryptoKey(e.asymmetricKeyType,a,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==A&&"Ed25519"!==A)throw TypeError(DC);i=e.toCryptoKey(e.asymmetricKeyType,a,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(A!==e.asymmetricKeyType.toUpperCase())throw TypeError(DC);i=e.toCryptoKey(e.asymmetricKeyType,a,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(A){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError(DC)}if(A.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},a,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:A.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},a,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError(DC);let r={ES256:"P-256",ES384:"P-384",ES512:"P-521"};r[A]&&t===r[A]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:t},a,[n?"verify":"sign"])),A.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:t},a,n?[]:["deriveBits"]))}if(!i)throw TypeError(DC);return r?r[A]=i:t.set(e,{[A]:i}),i})(e,A)}catch(e){if(e instanceof TypeError)throw e}let i=e.export({format:"jwk"});return DE(e,i,A)}if(Dp(e)){if(e.k){var i=e.k;if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof i?i:Da.decode(i),{alphabet:"base64url"});let t=i;t instanceof Uint8Array&&(t=Da.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return S0(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}return DE(e,e,A,!0)}throw Error("unreachable")}function DQ(e,t){if(e)throw TypeError(`${t} can only be called once`)}Symbol();class Dw{#AM;#AG;#A_;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#AM=e}setProtectedHeader(e){return DQ(this.#AG,"setProtectedHeader"),this.#AG=e,this}setUnprotectedHeader(e){return DQ(this.#A_,"setUnprotectedHeader"),this.#A_=e,this}async sign(e,t){let A,i,r,n;if(!this.#AG&&!this.#A_)throw new S8("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!function(...e){let t,A=e.filter(Boolean);if(0===A.length||1===A.length)return!0;for(let e of A){let A=Object.keys(e);if(!t||0===t.size){t=new Set(A);continue}for(let e of A){if(t.has(e))return!1;t.add(e)}}return!0}(this.#AG,this.#A_))throw new S8("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...this.#AG,...this.#A_},s=function(e,t,A,i,r){let n;if(void 0!==r.crit&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let a of(n=void 0!==A?new Map([...Object.entries(A),...t.entries()]):t,i.crit)){if(!n.has(a))throw new S4(`Extension Header Parameter "${a}" is not recognized`);if(void 0===r[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(n.get(a)&&void 0===i[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(i.crit)}(S8,new Map([["b64",!0]]),t?.crit,this.#AG,a),o=!0;if(s.has("b64")&&"boolean"!=typeof(o=this.#AG.b64))throw new S8('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=a;if("string"!=typeof l||!l)throw new S8('JWS "alg" (Algorithm) Header Parameter missing or invalid');var c="sign";switch(l.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,A)=>{if(!(t instanceof Uint8Array)){if(Dp(t)){if("oct"===t.kty&&"string"==typeof t.k&&Dm(e,t,A))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!S9(t))throw TypeError(SX(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${Dg(t)} instances for symmetric algorithms must be of type "secret"`)}})(l,e,c);break;default:((e,t,A)=>{if(Dp(t))switch(A){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&Dm(e,t,A))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&Dm(e,t,A))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!S9(t))throw TypeError(SX(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${Dg(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(A){case"sign":throw TypeError(`${Dg(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${Dg(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(A){case"verify":throw TypeError(`${Dg(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${Dg(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(l,e,c)}o?i=Ds(A=Do(this.#AM)):(i=this.#AM,A=""),this.#AG?n=Ds(r=Do(JSON.stringify(this.#AG))):(r="",n=new Uint8Array);let u=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),A=0;for(let i of e)t.set(i,A),A+=i.length;return t}(n,Ds("."),i),d=await Dy(e,l),h={signature:Do(await Dd(l,d,u)),payload:A};return this.#A_&&(h.header=this.#A_),this.#AG&&(h.protected=r),h}}class DB{#AJ;constructor(e){this.#AJ=new Dw(e)}setProtectedHeader(e){return this.#AJ.setProtectedHeader(e),this}async sign(e,t){let A=await this.#AJ.sign(e,t);if(void 0===A.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${A.protected}.${A.payload}.${A.signature}`}}let Db=e=>Math.floor(e.getTime()/1e3),Dv=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Dk(e){let t,A=Dv.exec(e);if(!A||A[4]&&A[1])throw TypeError("Invalid time period format");let i=parseFloat(A[2]);switch(A[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(i);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*i);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*i);break;case"day":case"days":case"d":t=Math.round(86400*i);break;case"week":case"weeks":case"w":t=Math.round(604800*i);break;default:t=Math.round(0x1e187e0*i)}return"-"===A[1]||"ago"===A[4]?-t:t}function DS(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}class DD{#AM;constructor(e){if(!Dh(e))throw TypeError("JWT Claims Set MUST be an object");this.#AM=structuredClone(e)}data(){return Dn.encode(JSON.stringify(this.#AM))}get iss(){return this.#AM.iss}set iss(e){this.#AM.iss=e}get sub(){return this.#AM.sub}set sub(e){this.#AM.sub=e}get aud(){return this.#AM.aud}set aud(e){this.#AM.aud=e}set jti(e){this.#AM.jti=e}set nbf(e){"number"==typeof e?this.#AM.nbf=DS("setNotBefore",e):e instanceof Date?this.#AM.nbf=DS("setNotBefore",Db(e)):this.#AM.nbf=Db(new Date)+Dk(e)}set exp(e){"number"==typeof e?this.#AM.exp=DS("setExpirationTime",e):e instanceof Date?this.#AM.exp=DS("setExpirationTime",Db(e)):this.#AM.exp=Db(new Date)+Dk(e)}set iat(e){void 0===e?this.#AM.iat=Db(new Date):e instanceof Date?this.#AM.iat=DS("setIssuedAt",Db(e)):"string"==typeof e?this.#AM.iat=DS("setIssuedAt",Db(new Date)+Dk(e)):this.#AM.iat=DS("setIssuedAt",e)}}class DR{#AG;#AL;constructor(e={}){this.#AL=new DD(e)}setIssuer(e){return this.#AL.iss=e,this}setSubject(e){return this.#AL.sub=e,this}setAudience(e){return this.#AL.aud=e,this}setJti(e){return this.#AL.jti=e,this}setNotBefore(e){return this.#AL.nbf=e,this}setExpirationTime(e){return this.#AL.exp=e,this}setIssuedAt(e){return this.#AL.iat=e,this}setProtectedHeader(e){return this.#AG=e,this}async sign(e,t){let A=new DB(this.#AL.data());if(A.setProtectedHeader(this.#AG),Array.isArray(this.#AG?.crit)&&this.#AG.crit.includes("b64")&&!1===this.#AG.b64)throw new S2("JWTs MUST NOT use unencoded payload");return A.sign(e,t)}}function DU(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function DT(e){let t=DU(e.get("x-ratelimit-limit")),A=DU(e.get("x-ratelimit-remaining")),i=DU(e.get("x-ratelimit-used")),r=DU(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===A||null===i||null===r||!n)return null;let a=new Date(1e3*r);return Number.isFinite(a.getTime())?{limit:t,remaining:A,used:i,resetAt:a,resource:n}:null}async function DF(e,t){let A=DT(t.headers);if(!A)return null;try{let t=await aE(),i=`${e}:${A.resource}`,r=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:A.resource}},create:{id:i,authentication:e,observedAt:r,...A},update:{observedAt:r,...A}})}catch{}return A}async function Dx(){let e=await aE();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 DO="actions.cancelWorkflowRun",DN="actions.dispatchWorkflow",DM="actions.forceCancelWorkflowRun",DG="actions.getJobForWorkflowRun",D_="actions.getWorkflowRun",DJ="actions.getWorkflowRunAttempt",DL="actions.listJobsForWorkflowRun",DP="actions.listJobsForWorkflowRunAttempt",DH="actions.listRepoWorkflows",DY="actions.listWorkflowRuns",Dq="actions.listWorkflowRunsForRepo",Dj="actions.reRunJobForWorkflowRun",DK="actions.reRunWorkflow",DV="actions.reRunWorkflowFailedJobs",D$="apps.createInstallationAccessToken",DW="apps.getAuthenticated",DZ="apps.getInstallation",Dz="apps.updateWebhookConfigForApp",DX="repos.listPullRequestsAssociatedWithCommit",D0="users.listEmailsForAuthenticatedUser";class D1 extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,A=null,i=null,r=null){super(t),this.code=e,this.githubRequestId=A,this.statusCode=i,this.rateLimit=r,this.name="GitHubAppError"}}let D4=new Map,D8=new Map;function D2(e,t,A){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D1(A,`${t} must be a positive integer`);return i}function D6(e){let{privateKeyPkcs8:t,keyFingerprint:A}=function(e){try{let t=(0,AB.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==t.asymmetricKeyType)throw Error("The key is not RSA");let A=t.export({format:"pem",type:"pkcs8"}).toString(),i=(0,AB.createPublicKey)(t).export({format:"der",type:"spki"}),r=`SHA256:${(0,AB.createHash)("sha256").update(i).digest("base64url")}`;return{key:t,privateKeyPkcs8:A,keyFingerprint:r}}catch{throw new D1("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:D2(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:D2(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:t,keyFingerprint:A}}async function D3(e){try{let t=await Dr(e.privateKeyPkcs8,"RS256"),A=Math.floor(Date.now()/1e3);return await new DR({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(A-60).setExpirationTime(A+540).sign(t)}catch{throw new D1("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function D5(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function D9(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function D7(e,t,A,i,r){let n,a=Date.now(),s=(t.method??"GET").toUpperCase(),o=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:s,operation:A,requestSource:r,body:o,durationMs:Date.now()-a,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D1("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:s,operation:A,requestSource:r,body:o,durationMs:Date.now()-a,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:DT(n.headers)})).catch(()=>void 0),n}async function Re(e){try{return await e.json()}catch{return null}}function Rt(e){return e.headers.get("x-github-request-id")}function RA(e,t,A=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),A))t&&(i=i.split(t).join("[REDACTED]"));return i}async function Ri(e,t){let A=await D7(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:D9(`Bearer ${t}`)},DZ,e,"GITHUB_SETTINGS"),i=await Re(A),r=Rt(A);if(401===A.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",r);if(404===A.status)throw new D1("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",r);if(!A.ok||!i||"object"!=typeof i)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(i,A.status,[t,e.privateKey,e.privateKeyPkcs8]),r);if(String(i.app_id)!==e.appId)throw new D1("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",r);return i}async function Rr(e,t){let A=await D7(`${e.apiBaseUrl}/app`,{headers:D9(`Bearer ${t}`)},DW,e,"GITHUB_SETTINGS"),i=await Re(A),r=Rt(A);if(401===A.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",r);if(!A.ok||!i||"object"!=typeof i)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(i,A.status,[t,e.privateKey,e.privateKeyPkcs8]),r);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",r);return{details:i,githubRequestId:r}}async function Rn(e){let t=D6(e),A=await D3(t),i=await Rr(t,A);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function Ra(e,t,A){let i=A??await D3(e),r=await D7(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:D9(`Bearer ${i}`)},D$,e,t),n=await Re(r),a=Rt(r);if(401===r.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D1("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!n||"object"!=typeof n)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(n,r.status,[i,e.privateKey,e.privateKeyPkcs8]),a);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",a);if("write"!==(n.permissions?.actions??"none"))throw new D1("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",a);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function Rs(e,t){let A=D5(e),i=D4.get(A);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let r=D8.get(A);if(r)return r;let n=Ra(e,t).then(e=>(D4.set(A,e),e)).finally(()=>D8.delete(A));return D8.set(A,n),n}function Ro(){D4.clear(),D8.clear()}async function Rl(e,t,A){let i=D6(e),r=await Rs(i,A),n=await t(r.token);return 401===n.status&&(D4.delete(D5(i)),r=await Rs(i,A),n=await t(r.token)),{response:n,token:r.token}}async function Rc(e,t,A,i){let{response:r,token:n}=await Rl(e,r=>D7(e.graphqlUrl,{method:"POST",headers:{...D9(`Bearer ${r}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:A})},null,e,i),i),a=await Re(r),s=Rt(r),o=DT(r.headers);if(401===r.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",s,r.status,o);if(!r.ok||a?.errors?.length||!a?.data){let t=a?.errors?.map(e=>e.message).filter(Boolean).join("; ")||RA(a,r.status,[n]);throw new D1("GITHUB_APP_REQUEST_FAILED",RA({message:t},r.status,[n,e.privateKey]),s,r.status,o)}return{data:a.data,githubRequestId:s,statusCode:r.status,rateLimit:o}}async function Ru(e){let t=D6(e),A=await D3(t),[i,r]=await Promise.all([Ri(t,A),Rr(t,A)]),n=await Ra(t,"GITHUB_SETTINGS",A);D4.set(D5(t),n);let a=await Rc(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:r.details.slug,appOwnerLogin:r.details.owner.login,appOwnerType:r.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:a.data.viewer.login,verifiedAt:new Date,githubRequestId:a.githubRequestId}}async function Rd(e,t){let A=D6(e),i=await D3(A),r=await D7(`${A.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...D9(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},Dz,A,"GITHUB_SETTINGS"),n=Rt(r);if(404===r.status)return{configured:!1,githubRequestId:n};if(!r.ok)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(await Re(r),r.status,[i,t.secret,A.privateKey]),n);return{configured:!0,githubRequestId:n}}async function Rh(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:r}=await Rl(e,i=>D7(A,{method:"POST",headers:D9(`Bearer ${i}`)},DK,e,t.requestSource),t.requestSource),n=Rt(i);if(401===i.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await Re(i);throw new D1(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":RA(t,i.status,[r,e.privateKey]),n)}return{githubRequestId:n}}async function Rp(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:r}=await Rl(e,i=>D7(A,{method:"POST",headers:D9(`Bearer ${i}`)},DV,e,t.requestSource),t.requestSource),n=Rt(i);if(!i.ok){let t=await Re(i);throw new D1(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":RA(t,i.status,[r,e.privateKey]),n)}return{githubRequestId:n}}async function Rg(e,t){let A=t.force?"force-cancel":"cancel",i=t.force?DM:DO,r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${A}`,{response:n,token:a}=await Rl(e,A=>D7(r,{method:"POST",headers:D9(`Bearer ${A}`)},i,e,t.requestSource),t.requestSource),s=Rt(n);if(401===n.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",s);if(!n.ok){let t=await Re(n);throw new D1(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":RA(t,n.status,[a,e.privateKey]),s)}return{githubRequestId:s}}async function Rm(e,t){let A=[],i=1,r=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:a,token:s}=await Rl(e,A=>D7(n,{headers:D9(`Bearer ${A}`)},DL,e,t.requestSource),t.requestSource),o=Rt(a);if(401===a.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);let l=await Re(a);if(!a.ok||!l||"object"!=typeof l)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(l,a.status,[s,e.privateKey]),o);if(!Number.isInteger(l.total_count)||!Array.isArray(l.jobs))throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",o);r=l.total_count??0,A.push(...l.jobs),i+=1}while(A.length<r)return A}async function Rf(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${A}/actions/jobs/${encodeURIComponent(t.jobId)}`,r=await Rl(e,A=>D7(i,{headers:D9(`Bearer ${A}`)},DG,e,t.requestSource),t.requestSource),n=Rt(r.response);if(401===r.response.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let a=await Re(r.response);if(!r.response.ok||!a||"object"!=typeof a)throw new D1(404===r.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===r.response.status?"The GitHub Actions job is not available to this installation":RA(a,r.response.status,[r.token,e.privateKey]),n);if(String(a.run_id??"")!==t.workflowRunId)throw new D1("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(a.status?.toLowerCase()!=="completed")throw new D1("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let s=await Rl(e,A=>D7(`${i}/rerun`,{method:"POST",headers:D9(`Bearer ${A}`)},Dj,e,t.requestSource),t.requestSource),o=Rt(s.response);if(401===s.response.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!s.response.ok){let t=await Re(s.response);throw new D1(404===s.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===s.response.status?"The GitHub Actions job is not available to this installation":RA(t,s.response.status,[s.token,e.privateKey]),o)}return{githubRequestId:o}}let RI=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),RC=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),RE=["COMPLETED","EXHAUSTED","STOPPED"],Ry={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},RQ="server:github-auto-retry";function Rw(e){return e.toISOString()}function RB(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:Rw(e.updatedAt)})),createdAt:Rw(e.createdAt),updatedAt:Rw(e.updatedAt)}}class Rb{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,A=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:RQ,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),A&&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(RQ,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 aE()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(RQ,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(RQ,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 aE(),A=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...A?{codebaseRepositoryId:A}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(RB)}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 t=await aE(),A=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let i=await t.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(A=i?.branch??null))throw Error("The worktree does not have a branch")}let i=await t.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),r=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(i.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&r.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 n=e.id??(0,AB.randomUUID)(),a=await t.$transaction(async t=>(await t.gitHubAutoRetryRule.upsert({where:{id:n},create:{id:n,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 t.gitHubAutoRetryTarget.deleteMany({where:{ruleId:n}}),e.targets.length&&await t.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,AB.randomUUID)(),ruleId:n,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await t.gitHubAutoRetryExecution.deleteMany({where:{ruleId:n}}),t.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:n},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),RB(a)}async setEnabled(e,t){let A=await aE(),i=await A.$transaction(async A=>(t&&await A.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),A.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)),RB(i)}async delete(e){return(await (await aE()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,A=!1){if("WORKFLOW_RUN"!==e.scope){let i=RC.has(t.status);if(!A&&!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,t,A){return(await aE()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:t.id,targetKey:A}},create:{id:(0,AB.randomUUID)(),ruleId:e,workflowRunId:t.id,workflowId:t.workflowId,targetKey:A},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let A=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return A.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:A.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,A){await (await aE()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:A,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,A,i,r){let n=await aE();await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:A.runAttempt,observedAttempt:A.runAttempt,lastStatus:A.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,A.id,i,r,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let A=i instanceof Error?i.message:String(i);await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:A}}),await n.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A}})}}async reconcileExecution(e,t,A,i){var r;let n,a=await this.execution(e.id,t,A);if(null!=a.pendingFromAttempt)if(t.runAttempt>a.pendingFromAttempt)await (await aE()).gitHubAutoRetryExecution.update({where:{id:a.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-a.updatedAt.getTime()<12e4)return!1;let t=await aE(),A="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:a.id},data:{status:"ERROR",lastError:A}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:A}})}),!1}if(a.observedAttempt===t.runAttempt&&null==a.pendingFromAttempt)return!1;let s=i?.status??t.status,o=(n=null!=(r={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:a.automaticRetries,state:s}).retryLimit&&r.automaticRetries>=r.retryLimit,"COUNT"===r.mode?"SUCCESS"!==r.state?"STOP":n?"COMPLETE":"RETRY":"SUCCESS"===r.state?"COMPLETE":RI.has(r.state)?n?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===o?(await this.finishExecution(a.id,t,"COMPLETED"),!1):"EXHAUSTED"===o?(await this.finishExecution(a.id,t,"EXHAUSTED"),!1):"STOP"===o?(await this.finishExecution(a.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,a,t,i?"JOB":"ALL_JOBS",i?.id??null):await this.trigger(e,a,t,i?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",i?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await aE(),A=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=A.length;let i=new Map,r=A.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:A.map(e=>e.id)},status:{notIn:RE}},select:{ruleId:!0,workflowRunId:!0}}):[],n=new Map;for(let e of r){let t=n.get(e.ruleId)??new Set;t.add(e.workflowRunId),n.set(e.ruleId,t)}let a=new Map;for(let e of A){let A=i.get(e.codebaseRepositoryId);if(!A)try{A=await this.github.autoRetryRuns(e.codebaseRepositoryId),i.set(e.codebaseRepositoryId,A)}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}});continue}let r=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),s=n.get(e.id)??new Set;for(let i of new Set([...r,...s]))if(!A.some(e=>e.id===i))try{A.push(await this.github.autoRetryRun(e.codebaseRepositoryId,i,!1))}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}})}for(let t of A){if("WORKFLOW_RUN"===e.scope&&!r.has(t.id)||!this.matches(e,t,s.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let A=a.get(t.id);(!A||Ry[e.scope]>Ry[A.rule.scope])&&a.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:A}of a.values()){let i=this.targetKeys(e,A);if(RC.has(A.status)){await Promise.all(i.map(t=>this.execution(e.id,A,t)));continue}let r=A,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===r.id||e.workflowId===r.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,r,"workflow",null);continue}let a=await Promise.all(i.map(t=>this.execution(e.id,r,t)));if(!a.some(e=>e.observedAttempt!==r.runAttempt||null!=e.pendingFromAttempt&&r.runAttempt>e.pendingFromAttempt)){for(let t=0;t<a.length;t+=1)a[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,r,i[t],null);continue}try{r=await this.github.autoRetryRun(e.codebaseRepositoryId,r.id)}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=r.jobs.filter(e=>n.some(t=>t.jobName===e.name)),A=t.find(e=>RI.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];A?await this.reconcileExecution(e,r,"workflow",A):a[0]&&await this.finishExecution(a[0].id,r,"STOPPED");continue}let s=new Map(i.map((e,t)=>[e,a[t]]));for(let t of n){let A=r.jobs.find(e=>e.name===t.jobName);if(!A){let e=s.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,r,"STOPPED");continue}if(await this.reconcileExecution(e,r,`job:${A.name}`,A))break}}for(let e of A.filter(e=>"WORKFLOW_RUN"===e.scope)){let A=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});A.length>0&&A.every(e=>RE.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:A.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}let Rv={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},Rk=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),RS=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),RD=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function RR(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>Rk.has(e))?"FAILURE":e.some(e=>RS.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>RD.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function RU(e,t){let A=(t||e||"NONE").toUpperCase();return Rx(A)?A:"REQUESTED"===A||"WAITING"===A?"QUEUED":"NONE"}function RT(e){return RS.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function RF(e,t,A){let i=e.runAttempt??0,r=t.runAttempt??0;if(r!==i)return r>i;let n=e.githubUpdatedAt?.getTime()??0,a=t.githubUpdatedAt?.getTime()??0;if(a!==n)return a>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>A.getTime())return"MUTATION"===t.source;let s="MUTATION"===e.source?Rv.LEGACY:Rv[e.source],o=Rv[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let A=RT(e.status),i=RT(t.status);if(i!==A)return i>A}return o===s||o>s}function Rx(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 RO(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function RN(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function RM(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function RG(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function R_(e){return{id:e.githubPipelineId,name:e.name,status:Rx(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:RN(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function RJ(e,t){return{...R_(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function RL(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:RO(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(R_).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function RP(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 RH(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(RP).sort((e,t)=>e.localeCompare(t))})}class RY{lastPrunedAt=0;async snapshot(e){let t=await aE(),A=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return A?RL(A):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 A=await aE();return(await A.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(RL)}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 A=await aE();return(await A.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>RJ(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",A=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,A=i.get(e)??[];A.push(t),i.set(e,A)}let r=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,A=!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:A}})(e,t,A))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&r.set(t.workflowRunId,t);return r}async observeJobs(e,t,A,i="REST",r=null){let n=await aE(),a=await n.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let s=A.filter(e=>null==e.runAttempt||null==a.runAttempt||e.runAttempt===a.runAttempt);if(A.length>0&&0===s.length)return RJ({...a.snapshot,records:[a]},a);let o=RN(a.jobsJson),l=new Map(o.map(e=>[e.id,e])),c=s.map(e=>(function(e,t){if(!e)return t;let A=e.runAttempt??0,i=t.runAttempt??0;if(i!==A)return i>A?t:e;let r=RM(e.status),n=RM(t.status);return n<r?e:n===r&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(l.get(e.id),e)),u="WEBHOOK"===i?[...new Map([...o,...c].map(e=>[e.id,e])).values()]:c,d=Rx(a.status)?a.status:"NONE",h="REST"===i&&s.length>0?RR(s.map(e=>e.status),null):"NONE",p=("ERROR"===h||"FAILURE"===h||"SUCCESS"===h)&&a.snapshot.graphqlRollupStatus===h?h:d;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...R_(a),status:p,source:i,jobs:u,githubUpdatedAt:r??a.githubUpdatedAt,isCurrent:a.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,A){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},A)}async optimisticByWorkflowRun(e,t,A){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},A)}async optimisticJobByCheckSuite(e,t,A){let i=await aE(),r=await i.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!r)return null;let n=RN(r.jobsJson).map(e=>e.id===A?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:n})}async optimisticJobByWorkflowRun(e,t,A){let i=await aE(),r=await i.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!r)return null;let n=RN(r.jobsJson).map(e=>e.id===A?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:n})}async optimisticRecord(e,t){let A=await aE(),i=await A.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(!i)return null;let r=new Date;return(await this.observeSnapshot({repositoryGithubId:i.snapshot.repositoryGithubId,repositoryNameWithOwner:i.snapshot.repositoryNameWithOwner,repositoryUrl:i.snapshot.repositoryUrl,headSha:i.snapshot.headSha,pipelines:[{...R_(i),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:i.githubUpdatedAt,sourceFetchedAt:r,optimisticUntil:new Date(r.getTime()+12e4),isCurrent:i.isCurrent}]})).changedPipeline}async observeSnapshot(e){let t=e.repositoryGithubId.trim(),A=e.headSha.trim();if(!t||!A)throw Error("GitHub repository ID and head SHA are required");let i=new Date,r=e.sourceFetchedAt??i,n=await aE(),a=await n.$transaction(async n=>{let a=await n.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:t,headSha:A}},create:{id:(0,AB.randomUUID)(),repositoryGithubId:t,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:A,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:i},update:{lastObservedAt:i},include:{records:!0}}),s=RH(a),o=!!(e.completeGraphqlRollup&&(!a.lastGraphqlSyncAt||r.getTime()>=a.lastGraphqlSyncAt.getTime())),l=new Set,c=null;for(let t 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}`}(t),A=(await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id}})).filter(A=>A.identityKey===e||t.checkSuiteId&&A.checkSuiteId===t.checkSuiteId||t.workflowRunId&&A.workflowRunId===t.workflowRunId),s=A[0]??null;for(let e of A.slice(1))s&&RF({runAttempt:s.runAttempt,githubUpdatedAt:s.githubUpdatedAt,source:RG(s.source),optimisticUntil:s.optimisticUntil,status:Rx(s.status)?s.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:RG(e.source),status:Rx(e.status)?e.status:"NONE"},i)&&(s=e);for(let e of A)s&&e.id!==s.id&&(0===RN(s.jobsJson).length&&RN(e.jobsJson).length>0&&(s=await n.gitHubPipelineRecord.update({where:{id:s.id},data:{jobsJson:e.jobsJson}})),await n.gitHubPipelineRecord.delete({where:{id:e.id}}),c=s.id);let u=t.sourceFetchedAt??r,d=t.githubUpdatedAt??null,h=void 0===t.runAttempt?s?.runAttempt??null:t.runAttempt,p=void 0!==t.jobs?JSON.stringify(t.jobs):s&&(h??0)<=(s.runAttempt??0)?s.jobsJson:"[]",g=!!o||(!1===t.isCurrent?s?.isCurrent??!1:t.isCurrent??s?.isCurrent??!0);if(s){l.add(s.id);let A=RP(s),r=RF({runAttempt:s.runAttempt,githubUpdatedAt:s.githubUpdatedAt,source:RG(s.source),optimisticUntil:s.optimisticUntil,status:Rx(s.status)?s.status:"NONE"},{runAttempt:h,githubUpdatedAt:d,source:t.source,status:t.status},i),a=!!(!r&&"MUTATION"===s.source&&s.optimisticUntil&&s.optimisticUntil.getTime()>i.getTime()&&"MUTATION"!==t.source);A!==RP(s=await n.gitHubPipelineRecord.update({where:{id:s.id},data:r?{identityKey:e,githubPipelineId:t.id,name:t.name,status:t.status,url:void 0===t.url?s.url:t.url,checkSuiteId:void 0===t.checkSuiteId?s.checkSuiteId:t.checkSuiteId,workflowRunId:void 0===t.workflowRunId?s.workflowRunId:t.workflowRunId,workflowId:void 0===t.workflowId?s.workflowId:t.workflowId,runNumber:void 0===t.runNumber?s.runNumber:t.runNumber,runAttempt:h,canRetry:void 0===t.canRetry?s.canRetry:t.canRetry,retryUnavailableReason:void 0===t.retryUnavailableReason?s.retryUnavailableReason:t.retryUnavailableReason,jobsJson:p,source:t.source,githubUpdatedAt:d,sourceFetchedAt:u,lastObservedAt:i,optimisticUntil:void 0===t.optimisticUntil?s.optimisticUntil:t.optimisticUntil,isCurrent:g}:{lastObservedAt:i,...void 0!==t.jobs&&!a?{jobsJson:p}:{},...o?{isCurrent:!0}:{}}}))&&(c=s.id)}else c=(s=await n.gitHubPipelineRecord.create({data:{id:(0,AB.randomUUID)(),snapshotId:a.id,identityKey:e,githubPipelineId:t.id,name:t.name,status:t.status,url:t.url??null,checkSuiteId:t.checkSuiteId??null,workflowRunId:t.workflowRunId??null,workflowId:t.workflowId??null,runNumber:t.runNumber??null,runAttempt:h,canRetry:t.canRetry??!1,retryUnavailableReason:t.retryUnavailableReason??null,jobsJson:p,source:t.source,githubUpdatedAt:d,sourceFetchedAt:u,lastObservedAt:i,optimisticUntil:t.optimisticUntil??null,isCurrent:g}})).id;l.add(s.id)}if(o)for(let e of(await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id,isCurrent:!0}})))!l.has(e.id)&&e.sourceFetchedAt.getTime()<=r.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=i.getTime())&&(await n.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),c??=e.id);let u=await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id}}),d=o?e.graphqlRollupStatus??null:a.graphqlRollupStatus,h=RR(u.filter(e=>e.isCurrent).map(e=>Rx(e.status)?e.status:"NONE"),d&&RO(d)?d:null),p=s!==RH(a=await n.gitHubPipelineSnapshot.update({where:{id:a.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:h,graphqlRollupStatus:d,lastGraphqlSyncAt:o?r:a.lastGraphqlSyncAt,lastObservedAt:i},include:{records:!0}}))||null!==c;p&&(a=await n.gitHubPipelineSnapshot.update({where:{id:a.id},data:{revision:{increment:1}},include:{records:!0}}));let g=a,m=c?g.records.find(e=>e.id===c)??null:null;return{changed:p,change:{snapshot:RL(g),changedPipeline:m?RJ(g,m):null}}});return a.changed&&aw.publish(aT,{githubPipelineStatusChanged:a.change}),this.pruneIfNeeded().catch(()=>void 0),a.change}subscribe(){return aw.iterate(aT)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await aE();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}let Rq=/^[_A-Za-z][_0-9A-Za-z]*$/,Rj=new Map([["GitHubWorktreePullRequestStatuses",60]]),RK=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function RV(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(A=>[A,e(t[A])])):t}(e))}let R$=/(?:authorization|password|private.?key|secret|token)$/i;function RW(e,t=""){return R$.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>RW(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,RW(t,e)])):e}function RZ(e){try{return JSON.parse(e)}catch{return null}}function Rz(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 RX{inFlight=new Map;cacheWrites=new Set;cacheGeneration=0;lastPrunedAt=0;cacheKey(e){return(0,AB.createHash)("sha256").update(RV({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,A){return[A,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await aE();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await aE(),[A,i]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return A?.ttlSeconds??i}async query(e){let t=this.cacheGeneration,A=await aE(),i=this.cacheKey(e),r=this.inFlightKey(i,e,t),n=Date.now(),[a,s,o]=await Promise.all([A.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:i}}),this.effectiveTtlSeconds(e.operation),A.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(t!==this.cacheGeneration)return this.query(e);let l=null!==a&&Date.now()-a.fetchedAt.getTime()<1e3*s;if(!e.force&&l)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-n,pointCost:0,pointsAvoided:a.pointCost??0}).catch(()=>void 0),t!==this.cacheGeneration)?this.query(e):{data:RZ(a.responseJson),source:"CACHE",stale:!1,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};let c=this.inFlight.get(r);if(c){let A=await c;return t!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-n,pointCost:0,pointsAvoided:A.pointCost??0}).catch(()=>void 0),t!==this.cacheGeneration)?this.query(e):{...A,source:"CACHE"}}if(o?.remaining===0&&o.resetAt.getTime()>Date.now()){let A=`GitHub GraphQL rate limit is exhausted until ${o.resetAt.toISOString()}`,i=null!==a&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-n,error:A,servedStale:i,pointCost:0,pointsAvoided:i?a.pointCost??0:0,rateLimit:{limit:o.limit,remaining:o.remaining,used:o.used,resetAt:o.resetAt,resource:o.resource}}).catch(()=>void 0),t!==this.cacheGeneration)return this.query(e);if(i)return{data:RZ(a.responseJson),source:"ERROR",stale:!0,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};throw Error(A)}let u=(async()=>{try{let r=await e.fetcher(),a=new Date,s=null;if(t===this.cacheGeneration){let t=A.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,AB.randomUUID)(),cacheKey:i,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:RV(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:a,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:RV(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:a,pointCost:r.pointCost}});this.cacheWrites.add(t);try{s=await t}finally{this.cacheWrites.delete(t)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-n,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:a,entryId:t===this.cacheGeneration?s?.id??null:null,pointCost:r.pointCost}}catch(r){let A=Rz(r),i=t===this.cacheGeneration&&null!==a&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-n,statusCode:A.statusCode,error:r instanceof Error?r.message:String(r),servedStale:i,pointsAvoided:i?a?.pointCost??0:0,rateLimit:A.rateLimit}).catch(()=>void 0),t!==this.cacheGeneration)throw r;if(i)return{data:RZ(a.responseJson),source:"ERROR",stale:!0,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};throw r}})();this.inFlight.set(r,u);try{return await u}finally{this.inFlight.get(r)===u&&this.inFlight.delete(r)}}async mutation(e){let t,A=Date.now();try{t=await e.fetcher()}catch(i){let t=Rz(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-A,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()-A,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 A=await aE();return await A.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await aE();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:Rj.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await aE(),[t,A]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...Rj.keys(),...t.map(({operation:e})=>e),...A.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let A=e.trim();if(!Rq.test(A))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 i=await aE(),r=await i.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:A},create:{operation:A,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:r.operation,ttlSeconds:r.ttlSeconds,builtIn:Rj.has(r.operation),createdAt:r.createdAt.toISOString(),updatedAt:r.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(Rj.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let A=await aE();return(await A.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,A={};try{let i=new URL(e.endpoint);t=i.pathname,A={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{A={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:A,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 aE();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:A}=this.beginInvalidation();await Promise.allSettled(t);let i=await aE();return await i.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(A),await i.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await aE();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await aE();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let A=this.pagination(e,t),i=await aE(),[r,n,a,s]=await Promise.all([i.gitHubGraphqlCacheEntry.findMany({take:A.limit,skip:A.offset,orderBy:{fetchedAt:"desc"}}),i.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),i.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),o=new Map(s.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...A,total:n,items:r.map(e=>this.entryView(e,o.get(e.operation)??a))}}async entry(e){let t=await aE(),A=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!A)return null;let i=await this.effectiveTtlSeconds(A.operation);return{...this.entryView(A,i),query:A.query,variables:RZ(A.variablesJson),response:RZ(A.responseJson)}}async calls(e=50,t=0,A={}){let i=this.pagination(e,t);await this.pruneLogs();let r=await aE(),n={...A.apiType?{apiType:A.apiType}:{},...A.requestSource?{requestSource:A.requestSource}:{},...A.source?{source:A.source}:{}},[a,s]=await Promise.all([r.gitHubApiCallLog.findMany({where:n,take:i.limit,skip:i.offset,orderBy:{createdAt:"desc"}}),r.gitHubApiCallLog.count({where:n})]);return{...i,total:s,items:a.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:RZ(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 aE(),t=Date.now(),A=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-RK.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),i=RK.map(e=>this.metricWindow(e.window,A.filter(A=>A.createdAt.getTime()>=t-e.milliseconds)));return{windows:i,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.apiType===e&&A.createdAt.getTime()>=t-i.milliseconds)))})),operations:[...new Set(A.map(e=>e.operation))].sort().map(e=>({operation:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.operation===e&&A.createdAt.getTime()>=t-i.milliseconds)))})),requestSources:[...new Set(A.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.requestSource===e&&A.createdAt.getTime()>=t-i.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 A=t.length;return{window:e,total:A,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===A?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/A),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=RW(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 A=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${A.length>120?`${A.slice(0,117)}…`:A}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){await this.pruneLogs();let t=await aE();await t.gitHubApiCallLog.create({data:{id:(0,AB.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:RV(RW(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 aE();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let R0=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),R1=process.env.GITHUB_GRAPHQL_URL||`${R0}/graphql`,R4="_adeRateLimit";function R8(e){let t=(0,E.parse)(e),A=t.definitions.filter(e=>e.kind===H.Kind.OPERATION_DEFINITION);if(1!==A.length||!A[0])throw Error("GitHub GraphQL requests must contain one operation");let i=A[0],r=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,ea.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:r,normalizedQuery:n,liveQuery:n};let a={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:H.Kind.FIELD,alias:{kind:H.Kind.NAME,value:R4},name:{kind:H.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:H.Kind.SELECTION_SET,selections:[{kind:H.Kind.FIELD,name:{kind:H.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:r,normalizedQuery:n,liveQuery:(0,ea.print)(a)}}function R2(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[R4],A=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(R4 in e))return{data:e,pointCost:A};let i={...e};return delete i[R4],{data:i,pointCost:A}}let R6="default",R3="default",R5=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,R9=["workflow_run","workflow_job","check_run","check_suite","status"];function R7(e){return"read"===e||"write"===e}function Ue(e){let t=[];for(let A of(e.webhookConfigured||t.push("configure the signed webhook URL"),R7(e.actionsPermission)||t.push("grant Actions read permission"),R7(e.checksPermission)||t.push("grant Checks read permission"),R7(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),R9))e.webhookEvents.includes(A)||t.push(`subscribe to the ${A} event`);return t}function Ut(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class UA extends Error{statusCode;rateLimit;constructor(e,t,A){super(e),this.statusCode=t,this.rateLimit=A,this.name="GitHubRequestError"}}let Ui=`
|
|
11968
|
+
${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}]`}},Se=class{constructor(e){(0,wi.__publicField)(this,"mdToAdfEngine"),(0,wi.__publicField)(this,"adfToMdEngine"),(0,wi.__publicField)(this,"options"),(0,wi.__publicField)(this,"errorRecovery"),(0,wi.__publicField)(this,"remarkProcessor"),(0,wi.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new kv(this.options),this.adfToMdEngine=new k9(this.options),this.errorRecovery=new k7({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=wb().use(BZ).use(bK,["yaml"]).use(v1).use(ke,{strict:e?.strict||!1}).use(bx),this.registry=new ks,this.registerConverters()}catch(e){throw new kr("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new k9({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!A.success)throw A.error||Error("ADF to Markdown conversion failed");return A.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new kv({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!A.success)throw A.error||Error("Markdown to ADF conversion failed");return A.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let A=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!A.success)throw A.error||Error("Async Markdown to ADF conversion failed");return A.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 kA().validate(e)}validateMarkdown(e){return new ki().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new kk,new kS,new kD,new kR,new kU,new kT,new kF,new kx,new kO,new kN,new kM,new kG,new k_,new kJ,new kL,new kP,new kH,new kY,new kq,new kj,new kK,new kV,new k$,new kW,new kZ,new kz]),this.registry.registerMarks([new kX,new k0,new k1,new k4,new k8,new k2,new k6,new k3,new k5])}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 A of e)t++,A.content&&Array.isArray(A.content)&&(t+=this.countNodes(A.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},St=e.i(436057);let SA=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function Si(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function Sr(e,t){return St.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,A)=>t?`[${A}](${t}/browse/${A})`:`**${A}**`))}let Sn=new Se;function Sa(e,t){if(null==e)return null;let A=function(e){if(Si(e))return"ADF";let t="string"==typeof e?e:"";return SA.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),r="ADF"===A?function(e){try{return Sn.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"===A?Sr(i,t):i;return{format:A,raw:e,rawText:i,markdown:r,wikiMarkup:"JIRA_WIKI"===A?i:St.default.to_jira(r)}}function Ss(e){let t=e.value.trim(),A="JIRA_WIKI"===e.format?Sr(t):t,i=Sn.markdownToAdf(A);if(!Si(i))throw Error("The Jira text could not be converted to valid ADF");return i}let So="default",Sl=["summary","status","issuetype","priority","assignee","project","updated"],Sc=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function Su(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Sd(e){return Su(e)?e:{}}function Sh(e){return Array.isArray(e)?e:[]}function Sp(e){return"string"==typeof e&&e.length>0?e:null}function Sg(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Sm(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function Sf(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function SI(e){return Sh(Sf(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function SC(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):Su(t)?Object.fromEntries(Object.keys(t).sort().map(A=>[A,e(t[A])])):t}(e))}function SE(e){if(!Su(e))return null;let t=e.status??Sd(e.response).status;return"number"==typeof t?t:null}function Sy(e,t){let A=e instanceof Error?e.message:String(e);return(t?A.replaceAll(t,"[REDACTED]"):A).slice(0,1e3)}function SQ(e){return Sp(Sd(Sd(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function Sw(e){let t=Sd(e),A=Sp(t.displayName);if(!A)return null;let i=Sd(t.avatarUrls);return{accountId:Sp(t.accountId),displayName:A,avatarUrl:Sp(i["48x48"])??Sp(i["32x32"])??Sp(i["24x24"])}}function SB(e){return Sh(e).map(Sd).map(e=>({id:Sp(e.id),name:Sp(e.name)??"Unknown"}))}function Sb(e,t){let A=Sd(e),i=Sp(A.key);if(!i)return null;let r=Sd(A.fields);return{relationship:t,key:i,summary:Sp(r.summary)??i,status:Sp(Sd(r.status).name)}}function Sv(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function Sk(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function SS(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 SD(e){let t=Sd(e.fields),A=Sd(t.status),i=Sd(A.statusCategory),r=Sd(t.assignee),n=Sd(r.avatarUrls),a=Sd(t.project),s=e.key??"UNKNOWN";return{id:e.id??s,key:s,summary:Sp(t.summary)??s,statusId:Sp(A.id)??Sp(A.name)??"unknown",status:Sp(A.name)??"Unknown",statusCategory:Sp(i.key)??Sp(i.name)??"unknown",issueType:Sp(Sd(t.issuetype).name),priority:Sp(Sd(t.priority).name),assignee:Sp(r.displayName),assigneeAccountId:Sp(r.accountId),assigneeAvatarUrl:Sp(n["48x48"])??Sp(n["32x32"]),projectKey:Sp(a.key)??SQ(e),updatedAt:Sp(t.updated)}}function SR(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let SU=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function ST(e){return SU.has(e)?e:"ALL"}class SF{credentials;workflowEvents;recordCallLogs;inFlight;clients;lastPrunedAt;constructor(e=new Q8,t,A="true"!==process.env.JIRA_CACHE_LOGGING_DISABLED){this.credentials=e,this.workflowEvents=t,this.recordCallLogs=A,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let A=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:A?{id:A.id,body:A.content?.rawText??"",author:A.author}:null,...void 0!==t?{changelog:t}:{}},r=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,a=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",A?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",A?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&a.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()))),A=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&A.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&A.add("JIRA_LABEL"),e.has("assignee")&&A.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(A.add("JIRA_SPRINT_STARTED"),A.add("JIRA_SPRINT_ENDED")),a=a.filter(([e])=>A.has(e))}await Promise.allSettled(a.map(([t,A])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${r}`,payload:{...i,sessionData:i,cursorValue:A}})))}async getSettings(){let e=await aE(),t=await e.jiraSettings.upsert({where:{id:So},create:{id:So,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(Qj.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await aE(),A=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 r=await t.jiraSettings.findUnique({where:{id:So}}),n=e.apiToken?.trim()||null,a=!!(r?.siteUrl&&r.siteUrl!==A);if(a&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let s=r?.siteUrl!==A||r?.email!==i||!!n,o=async e=>{a&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),s&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:So},create:{id:So,siteUrl:A,email:i,cacheTtlSeconds:300},update:a?{siteUrl:A,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:A,email:i}})};return n?await this.credentials.setText(Qj.jiraApiToken,n,o):await t.$transaction(o),a&&await this.credentials.delete(Qj.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:So},select:{siteUrl:!0,email:!0,webhookId:!0}}),A=await this.credentials.isConfigured(Qj.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&A)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==SE(e))throw e}return await this.credentials.deleteMany([Qj.jiraApiToken,Qj.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:So},create:{id:So,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 aE();return await t.jiraSettings.upsert({where:{id:So},create:{id:So,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=Sd(e.value);return{accountId:Sp(t.accountId),displayName:Sp(t.displayName)??"Jira user",emailAddress:Sp(t.emailAddress),cache:Sk(e)}}async listProjects(){let e=await aE();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:ST(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:SI(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??we,sources:e.sources.map(Sv)}))}async projectStatuses(e){let t=await aE(),A=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!A)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:A.jiraId},requestSummary:`Statuses for project ${A.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(A.jiraId)}}),r=new Map;for(let e of Sh(i.value).map(Sd))for(let t of Sh(e.statuses).map(Sd)){let e=Sp(t.id),A=Sp(t.name);if(!e||!A||r.has(e))continue;let i=Sd(t.statusCategory);r.set(e,{id:e,name:A,category:Sp(i.key)??Sp(i.name)??"unknown"})}return[...r.values()].sort((e,t)=>SR(e.category)-SR(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!SU.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),A=await aE(),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 A.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 A=await aE(),i=await A.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let r=await wA(t,i.key);return await A.jiraProject.update({where:{id:e},data:{branchNamingScript:r}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let A=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=>Sh(Sd(e).values).length}),i=Sd(A.value),r=Sh(i.values).map(Sd);e.push(...r.flatMap(e=>{let t=Sp(e.id),A=Sp(e.key),i=Sp(e.name);if(!t||!A||!i)return[];let r=Sd(e.avatarUrls);return[{jiraId:t,key:A,name:i,avatarUrl:Sp(r["48x48"])??Sp(r["32x32"])}]}));let n=Sg(i.total)??e.length;if(0===r.length||e.length>=n)break;t+=r.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let A=Sd((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),i=Sp(A.key),r=Sp(A.name),n=Sp(A.id);if(!i||!r||!n)throw Error("Jira returned an incomplete project");let a=Sd(A.avatarUrls),s=await aE(),o=await s.jiraProject.aggregate({_max:{position:!0}});return await s.jiraProject.create({data:{id:(0,AB.randomUUID)(),jiraId:n,key:i,name:r,avatarUrl:Sp(a["48x48"])??Sp(a["32x32"]),position:(o._max.position??-1)+1,branchNamingScript:we}}),this.listProjects()}async removeProject(e){let t=await aE(),A=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{A.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:A}}}),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),A=this.validateSourceName(e.name),i=await aE();if(!await i.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let r=await i.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await i.jiraSource.create({data:{id:(0,AB.randomUUID)(),projectId:e.projectId,name:A,kind:e.kind,value:t.value,boardId:t.boardId,position:(r._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),A=this.validateSourceName(e.name),i=await aE();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:A,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await aE();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 A;let i,r,n,a=await aE(),s=await a.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!s)throw Error("Jira source not found");let o=await a.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),l=new Set(o?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===s.kind?await this.loadBoardSource(Sv(s),t):await this.loadJqlSource(Sv(s),t),u={ticketAssignmentFilter:ST(s.project.ticketAssignmentFilter),hideCompletedTickets:s.project.hideCompletedTickets,completedStatusIds:SI(s.project.completedStatusIdsJson)},d="ALL"===u.ticketAssignmentFilter?null:await this.currentAccountId(),h=(A={source:Sv(s),...c},i=u.hideCompletedTickets?new Set(u.completedStatusIds):new Set,r=new Set(A.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=A.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===u.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===u.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===d:null!==d&&e.assigneeAccountId===d&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...A,tickets:n,statusOrder:A.statusOrder.filter(e=>!r.has(e))});return this.workflowEvents&&o&&await Promise.allSettled(h.tickets.filter(({key:e})=>!l.has(e)).map(t=>{let A={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:{...A,sessionData:A,source:{id:e,name:s.name,kind:s.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,A){let i=Sm(e),r=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"===r.source&&await this.storeDetail(r.entryId,r.value,r.fetchedAt);let n=[],a=[],s=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:s,maxResults:100},requestSummary:`Comments for ${i} from ${s}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:s,maxResults:100,orderBy:"created"})},itemCount:e=>Sh(Sd(e).comments).length});n.push(e);let A=Sd(e.value),r=Sh(A.comments);a.push(...r);let o=Sg(A.total)??a.length;if(0===r.length||a.length>=o)break;s+=r.length}let o=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,a,o,n.map(e=>e.entryId));let l=await this.requireCredentials(),c=this.normalizeTicketDetail(r.value,a,l.siteUrl,Sk(r),SS(n));return await this.recordTicketWorkflowEvents(c,A),c}async assignableUsers(e,t=""){let A=Sm(e),i=t.trim().slice(0,100),r=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:A,query:i,maxResults:50},requestSummary:`Assignable users for ${A}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:A,query:i,maxResults:50,recommend:!0})},itemCount:e=>Sh(e).length});return await this.linkCacheEntryToIssue(A,r.entryId),Sh(r.value).map(Sw).filter(e=>null!==e)}async ticketTransitions(e){let t=Sm(e),A=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=>Sh(Sd(e).transitions).length});return await this.linkCacheEntryToIssue(t,A.entryId),Sh(Sd(A.value).transitions).map(Sd).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=Sp(e.id),A=Sp(e.name);if(!t||!A)return[];let i=Sd(e.to),r=Sd(i.statusCategory),n=Object.entries(Sd(e.fields)).filter(([,e])=>!0===Sd(e).required).map(([e,t])=>Sp(Sd(t).name)??e);return[{id:t,name:A,toStatusId:Sp(i.id),toStatus:Sp(i.name)??A,toStatusCategory:Sp(r.key)??Sp(r.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=Sm(e),A=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(Sd(Sd(e).fields)).length});return await this.linkCacheEntryToIssue(t,A.entryId),Object.entries(Sd(Sd(A.value).fields)).map(([e,t])=>{let A=Sd(t);return{id:e,name:Sp(A.name)??e,required:!0===A.required,schemaType:Sp(Sd(A.schema).type),allowedValues:Sh(A.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=Sd(e),A=Sp(t.name)??Sp(t.value)??Sp(t.displayName)??Sp(t.key);return A?[{id:Sp(t.id)??Sp(t.accountId)??Sp(t.value)??A,name:A}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,A=0){let i=Sm(e),r=this.validatePagination(t,A),n=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Changelog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>Sh(Sd(e).values).length});await this.linkCacheEntryToIssue(i,n.entryId);let a=Sg(Sd(n.value).total)??0,s=Math.min(r.limit,Math.max(0,a-r.offset)),o=Math.max(0,a-r.offset-s);if(0===s)return{...r,total:a,items:[],cache:Sk(n)};let l=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:i,startAt:o,maxResults:s},requestSummary:`Changelog for ${i} from ${o}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:i,startAt:o,maxResults:s})},itemCount:e=>Sh(Sd(e).values).length});await this.linkCacheEntryToIssue(i,l.entryId);let c=Sh(Sd(l.value).values).map(Sd).reverse().map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),createdAt:Sp(e.created),items:Sh(e.items).map(Sd).map(e=>({field:Sp(e.field)??"Field",fieldId:Sp(e.fieldId),from:Sp(e.fromString)??Sp(e.from),to:Sp(e.toString)??Sp(e.to)}))}));return{...r,total:a,items:c,cache:SS([n,l])}}async ticketWorklogs(e,t=50,A=0){let i=Sm(e),r=this.validatePagination(t,A),n=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:0,maxResults:1},requestSummary:`Worklog count for ${i}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:0,maxResults:1})},itemCount:e=>Sh(Sd(e).worklogs).length});await this.linkCacheEntryToIssue(i,n.entryId);let a=Sg(Sd(n.value).total)??0,s=Math.min(r.limit,Math.max(0,a-r.offset)),o=Math.max(0,a-r.offset-s);if(0===s)return{...r,total:a,items:[],cache:Sk(n)};let l=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:i,startAt:o,maxResults:s},requestSummary:`Worklogs for ${i} from ${o}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:i,startAt:o,maxResults:s})},itemCount:e=>Sh(Sd(e).worklogs).length});await this.linkCacheEntryToIssue(i,l.entryId);let c=await this.requireCredentials(),u=Sh(Sd(l.value).worklogs).map(Sd).reverse().map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),comment:Sa(e.comment??null,c.siteUrl),timeSpent:Sp(e.timeSpent),timeSpentSeconds:Sg(e.timeSpentSeconds),startedAt:Sp(e.started),createdAt:Sp(e.created),updatedAt:Sp(e.updated)})),d=u[0];if(this.workflowEvents&&d){let e={ticket:{key:i},worklog:{id:d.id,author:d.author,timeSpent:d.timeSpent,timeSpentSeconds:d.timeSpentSeconds,startedAt:d.startedAt,updatedAt:d.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:i,dedupeKey:`jira-worklog:${i}:${d.id}:${l.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:d.id}})}return{...r,total:a,items:u,cache:SS([n,l])}}async addComment(e,t){let A=Sm(e);if(!t.value.trim())throw Error("Comment text is required");let i=Ss(t);return this.mutateTicket(A,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:A,comment:i})})}async assignTicket(e,t){let A=Sm(e),i=t?.trim()||null;return this.mutateTicket(A,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:A,accountId:i})})}async transitionTicket(e,t){let A=Sm(e),i=(await this.ticketTransitions(A)).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(A,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:A,transition:{id:i.id}})})}async transitionTicketToConfiguredDone(e){let t=Sm(e),A=t.split("-")[0]??"",i=await aE(),r=await i.jiraProject.findUnique({where:{key:A},select:{doneStatusId:!0}});if(!r?.doneStatusId)throw Error(`Configure a done status for Jira project ${A} before using this option`);let n=await this.ticket(t);if(n.statusId===r.doneStatusId)return n;let a=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===r.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!a)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,a.id)}async updateTicket(e){let t=Sm(e.issueKey),A=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},r=e=>{let t=A.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")){r("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=r("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=Ss(e.description))}if(n("priorityId")){let t=r("priority"),A=e.priorityId?.trim()||null;if(!A&&t.required)throw Error("Priority is required");if(A&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===A))throw Error("The selected priority is not available");i.priority=A?{id:A}:null}n("labels")&&(r("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let a=(t,A)=>{if(!n(t))return;let a=r(A),s=[...new Set(e[t]??[])];if(a.allowedValues.length>0&&s.some(e=>!a.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${a.name} value is not available`);i[A]=s.map(e=>({id:e}))};if(a("componentIds","components"),a("fixVersionIds","fixVersions"),a("affectedVersionIds","versions"),n("dueDate")){let t=r("duedate"),A=e.dueDate?.trim()||null;if(A&&!/^\d{4}-\d{2}-\d{2}$/.test(A))throw Error("Due date must use YYYY-MM-DD");if(!A&&t.required)throw Error("Due date is required");i.duedate=A}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(),A=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!A||!i)throw Error("Project, issue type, and summary are required");let{version3:r}=await this.getClients(),n=await r.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:A},summary:i,...e.description?{description:Ss(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=Sm(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:A}=await this.getClients();return await A.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:Ss(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=Sm(e.inwardIssueKey),A=Sm(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:r}=await this.getClients();return await r.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:A}}),this.ticket(t,!0)}async branchTicket(e){let t=Sm(e),A=t.replace(/-\d+$/,""),i=await aE(),r=await i.jiraProject.findUnique({where:{key:A},select:{key:!0,branchNamingScript:!0}});if(!r)throw Error(`Jira project ${A} 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 a=Sd(n.value.fields);if((Sp(Sd(a.project).key)??SQ(n.value))!==r.key)throw Error(`Jira ticket ${t} does not belong to project ${r.key}`);return{ticketKey:n.value.key??t,ticketTitle:Sp(a.summary)??t,ticketType:Sp(Sd(a.issuetype).name),projectKey:r.key,branchNamingScript:r.branchNamingScript??we}}async clearCache(){let e=await aE();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await aE();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(Sm(e)),!0}async invalidateIssueCaches(e){let t=await aE(),A=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{A.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:A.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e,t){let A=await aE(),i=await A.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await A.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:A}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>A.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=Sp(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return Sm(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),A=[],i=0;for(;A.length<1e3;){let r=Math.min(100,1e3-A.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:r,fields:["key"]}),a=n.issues??[];A.push(...a.flatMap(e=>{let t=Sp(e.key);return t?[Sm(t)]:[]}));let s=void 0===n.total?a.length<r:i+a.length>=n.total;if(0===a.length||s)break;i+=a.length}let r=[],n=[...new Set(A)];for(let e=0;e<n.length;e+=5)r.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return r}async listCachedTickets(e=50,t=0){let A=this.validatePagination(e,t),i=await aE(),[r,n,a]=await Promise.all([i.jiraCachedTicket.findMany({take:A.limit,skip:A.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...A,total:n,items:r.map(e=>this.cachedTicketView(e,a.cacheTtlSeconds))}}async cachedTicket(e){let t=await aE(),[A,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return A?{...this.cachedTicketView(A,i.cacheTtlSeconds),summaryData:Sf(A.summaryJson),detailData:Sf(A.detailJson),commentsData:Sf(A.commentsJson),cacheEntries:A.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 A=this.validatePagination(e,t);await this.pruneLogs();let i=await aE(),[r,n]=await Promise.all([i.jiraApiCallLog.findMany({take:A.limit,skip:A.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...A,total:n,items:r.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 aE(),t=Date.now(),A=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-Sc.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:Sc.map(e=>this.metricWindow(e.window,A.filter(A=>A.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(A.map(e=>e.operation))].sort().map(e=>({operation:e,windows:Sc.map(i=>this.metricWindow(i.window,A.filter(A=>A.operation===e&&A.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:So}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let A=await this.credentials.getText(Qj.jiraApiToken);if(!A)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:A,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,AB.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let A={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new Qv(A),agile:new Ej(A)},this.clients}async webhookApiRequest(e,t,A){let i,r=await this.requireCredentials(),n=Buffer.from(`${r.email}:${r.apiToken}`).toString("base64");try{i=await fetch(`${r.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===A?void 0:JSON.stringify(A),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(Sy(e,r.apiToken))}let a=await i.text();if(!i.ok){let e=a.trim().slice(0,300)||i.statusText;throw Object.assign(Error(Sy(`Jira rejected the webhook request with ${i.status}: ${e}`,r.apiToken)),{status:i.status})}if(!a.trim())return null;try{return JSON.parse(a)}catch{return null}}async currentAccountId(){let e=Sp(Sd((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 A=await aE();await A.$transaction(async A=>{await A.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await A.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,A){let i=await this.requireCredentials(),r=Date.now();try{await A(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-r})}catch(n){let A=Sy(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-r,statusCode:SE(n),error:A}),Error(A)}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: ${Sy(e,i.apiToken)}`)}}cacheKey(e,t,A){return(0,AB.createHash)("sha256").update(SC({siteUrl:e,operation:t,params:A})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),A=await aE(),i=this.cacheKey(t.siteUrl,e.operation,e.params),r=Date.now(),n=await A.jiraCacheEntry.findUnique({where:{cacheKey:i}}),a=null!==n&&Date.now()-n.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&a)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-r,itemCount:e.itemCount?.(Sf(n.responseJson))??null,sourceId:e.sourceId}),{value:Sf(n.responseJson),source:"CACHE",stale:!1,fetchedAt:n.fetchedAt,entryId:n.id};let s=this.inFlight.get(i);if(s){let t=await s;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-r,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let o=(async()=>{try{let t=await e.fetcher(),n=new Date,a=await A.jiraCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,AB.randomUUID)(),cacheKey:i,operation:e.operation,paramsJson:SC(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:SC(e.params),responseJson:JSON.stringify(t),fetchedAt:n,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-r,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:n,entryId:a.id}}catch(i){let A=null!==n&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-r,statusCode:SE(i),error:Sy(i,t.apiToken),servedStale:A,sourceId:e.sourceId}),A)return{value:Sf(n.responseJson),source:"ERROR",stale:!0,fetchedAt:n.fetchedAt,entryId:n.id};throw Error(Sy(i,t.apiToken))}})();this.inFlight.set(i,o);try{return await o}finally{this.inFlight.delete(i)}}async logCall(e){if(!this.recordCallLogs)return;let t=await aE();await t.jiraApiCallLog.create({data:{id:(0,AB.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 A=t.trim();if(!A)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:A},requestSummary:`Validate JQL: ${A}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:A,maxResults:1,fields:["key"],failFast:!0})}}),{value:A,boardId:null};let i=function(e,t){let A=new URL(e.trim());if(A.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=A.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),r=A.searchParams.get("rapidView"),n=Number(i?.[1]??r);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:A.toString()}}(A,(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 A,i=[],r=[],n=[],a=!1;do{let s=Math.min(100,1e3-i.length),o=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:A??null,maxResults:s,fields:Sl},requestSummary:`JQL ${e.name}${A?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:A,maxResults:s,fields:Sl})},itemCount:e=>e.issues?.length??0});r.push(o);let l=o.value.issues??[];i.push(...l),n.push(...o.value.warningMessages??[]),"LIVE"===o.source&&await this.storeSummaries(o.entryId,l,o.fetchedAt),A=o.value.nextPageToken,i.length>=1e3&&A&&(a=!0)}while(A&&i.length<1e3)return this.buildBoardResult(i,r,n,a)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let A=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})}}),r=[A,i],n=[],a=[],s=!1;if("scrum"===(Sp(A.value.type)??"").toLowerCase()){let A=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=>Sh(e.values).length});r.push(A);let i=Sh(A.value.values).map(Sd);for(let A of(0===i.length&&a.push("This Scrum board has no active sprint."),i)){let i=Sg(A.id);if(!i||n.length>=1e3)continue;let o=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:Sl}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...o.issues),r.push(...o.results),a.push(...o.warnings),s||=o.truncated}}else{let A=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,A)=>({boardId:e.boardId,startAt:t,maxResults:A,fields:Sl}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...A.issues),r.push(...A.results),a.push(...A.warnings),s=A.truncated}let o=[...new Map(n.map(e=>[e.key??e.id,e])).values()],l=new Map;return Sh(Sd(i.value.columnConfig).columns).map(Sd).forEach((e,t)=>{Sh(e.statuses).map(Sd).forEach(e=>{let A=Sp(e.id);A&&l.set(A,t)})}),this.buildBoardResult(o,r,a,s,l)}async loadAgileIssues(e,t,A,i,r,n){let a=[],s=[],o=[],l=0,c=1/0,u=!1;for(;l<c&&a.length+n<1e3;){let u=i(l,Math.min(100,1e3-n-a.length)),d=await this.cachedCall({operation:e,params:u,requestSummary:`${e.replaceAll("_"," ")} from ${l}`,sourceId:t.id,force:A,fetcher:()=>r(u),itemCount:e=>e.issues?.length??0});s.push(d);let h=d.value.issues??[];if(a.push(...h),o.push(...d.value.warningMessages??[]),"LIVE"===d.source&&await this.storeSummaries(d.entryId,h,d.fetchedAt),c=d.value.total??a.length,0===h.length)break;l+=h.length}return a.length+n>=1e3&&l<c&&(u=!0),{issues:a,results:s,warnings:o,truncated:u}}buildBoardResult(e,t,A,i,r){let n=e.slice(0,1e3).map(SD),a=[...new Map(n.map(e=>[e.status,e])).values()];return a.sort((e,t)=>{let A=r?.get(e.statusId),i=r?.get(t.statusId);return void 0!==A||void 0!==i?(A??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):SR(e.statusCategory)-SR(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:a.map(e=>e.status),cache:SS(t),truncated:i,warnings:[...new Set(A)]}}async storeSummaries(e,t,A){let i=await aE();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:SQ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:A},update:{projectKey:SQ(e),summaryJson:JSON.stringify(e),summaryFetchedAt:A}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let r=[...new Set(t.map(e=>e.key).filter(Boolean))];r.length>0&&await i.jiraCacheEntryIssue.createMany({data:r.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,A){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await aE();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:SQ(t),detailJson:JSON.stringify(t),detailFetchedAt:A},update:{projectKey:SQ(t),detailJson:JSON.stringify(t),detailFetchedAt:A}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,A,i){let r=await aE();await r.$transaction(async r=>{for(let n of(await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:A},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:A}}),i))await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,A,i,r){let n=SD(e),a=Sd(e.fields),s=Sd(e.names),o=Sd(e.schema),l=[];for(let e of Sh(a.issuelinks).map(Sd)){let t=Sd(e.type),A=Sb(e.outwardIssue,Sp(t.outward)??"relates to"),i=Sb(e.inwardIssue,Sp(t.inward)??"relates to");A&&l.push(A),i&&l.push(i)}let c=Sb(a.parent,"parent"),u=Sh(a.subtasks).map(e=>Sb(e,"subtask")).filter(e=>null!==e),d=Sh(a.sprint).map(Sd),h=Sh(a.closedSprints).map(Sd),p=d.filter(e=>{let t=Sp(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>Sp(e.name)).filter(e=>!!e),g=h.concat(d.filter(e=>Sp(e.state)?.toLowerCase()==="closed")).map(e=>Sp(e.name)).filter(e=>!!e),m=p.concat(g),f=t.map(Sd).map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),author:Sw(e.author),body:e.body??null,content:Sa(e.body??null,A),createdAt:Sp(e.created),updatedAt:Sp(e.updated)}));return{...n,jiraUrl:`${A}/browse/${n.key}`,description:a.description??null,descriptionContent:Sa(a.description??null,A),reporter:Sw(a.reporter),creator:Sw(a.creator),labels:Sh(a.labels).filter(e=>"string"==typeof e),components:SB(a.components),fixVersions:SB(a.fixVersions),affectedVersions:SB(a.versions),sprintNames:[...new Set(m)],activeSprintNames:[...new Set(p)],closedSprintNames:[...new Set(g)],parent:c,subtasks:u,issueLinks:l,attachments:Sh(a.attachment).map(Sd).map(e=>({id:Sp(e.id)??(0,AB.randomUUID)(),filename:Sp(e.filename)??"Attachment",contentUrl:Sp(e.content),mimeType:Sp(e.mimeType),size:Sg(e.size),author:Sw(e.author),createdAt:Sp(e.created)})),comments:f,createdAt:Sp(a.created),dueAt:Sp(a.duedate),resolvedAt:Sp(a.resolutiondate),timeTracking:a.timetracking??null,allFields:Object.entries(a).map(([e,t])=>{let i=Sd(o[e]),r="string"==typeof t||Su(t)&&"doc"===t.type?Sa(t,A):null;return{id:e,name:Sp(s[e])??e,schemaType:Sp(i.type),custom:!0===i.custom||e.startsWith("customfield_"),value:t??null,content:r}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:i,commentsCache:r}}cachedTicketView(e,t){let A=SD(Sd(Sf(e.detailJson)??Sf(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",r=[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:A.summary,status:"Unknown"===A.status?null:A.status,coverage:i,stale:r,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 aE();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let Sx="default",SO=/^[A-Z][A-Z0-9_]*-\d+$/,SN=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"]),SM={"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"},SG="/api/public/jira/webhook",S_="/rest/webhooks/1.0/webhook",SJ=new Set(["localhost","0.0.0.0","::1","[::1]",""]),SL=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class SP extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function SH(e){return"string"==typeof e&&e.trim()?e.trim():null}function SY(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function Sq(e){let t=Sj(e);if(!t)return null;let A=Array.isArray(t.items)?t.items:[];return{id:SY(t.id),items:A.map(Sj).filter(e=>null!==e).map(e=>({field:SH(e.field)??SH(e.fieldId)??"Field",fieldId:SH(e.fieldId),fieldType:SH(e.fieldtype)??SH(e.fieldType),from:SY(e.from),fromString:SY(e.fromString),to:SY(e.to),toString:SY(e.toString)}))}}function Sj(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function SK(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function SV(e){let t=Sj(e);return t?{accountId:SH(t.accountId),displayName:SH(t.displayName)}:null}class S${jira;credentials;workflowEvents;constructor(e,t,A){this.jira=e,this.credentials=t,this.workflowEvents=A}async webhooksEnabled(){let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(Qj.jiraWebhookSecret)}async getWebhookSettings(){let e=await aE(),[t,A,i]=await Promise.all([e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx},update:{}}),this.credentials.isConfigured(Qj.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&A,secretConfigured:A,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,AB.randomBytes)(32).toString("base64url");return await this.credentials.setText(Qj.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx,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 A=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(SJ.has(A)||A.endsWith(".local")||A.endsWith(".localhost")||/^127\./.test(A)||/^10\./.test(A)||/^192\.168\./.test(A)||/^172\.(1[6-9]|2\d|3[01])\./.test(A))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}${SG}`;if(i.endsWith(SG))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${SG}`)}(e.url),A=e.jql?.trim()||null,i=(0,AB.randomBytes)(32).toString("base64url"),r=await aE(),n=await r.jiraSettings.findUnique({where:{id:Sx},select:{webhookId:!0}}),a=await this.writeToJira({webhookId:n?.webhookId??null,url:t,jql:A,secret:i});return await this.credentials.setText(Qj.jiraWebhookSecret,i,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:a,webhookUrl:t,webhookJql:A},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:a,webhookUrl:t,webhookJql:A}})}),{settings:await this.getWebhookSettings(),secret:i}}async rotateSecret(){if(!await this.credentials.isConfigured(Qj.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},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 aE(),t=await e.jiraSettings.findUnique({where:{id:Sx},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(Qj.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:Sx},create:{id:Sx},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,A,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...SL],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${S_}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==SK(e))throw e}}let r=await this.jira.webhookApiRequest("POST",S_,i),n=(t=SH(r?.self),(A=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(A):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",`${S_}/${encodeURIComponent(e)}`)}catch(e){if(404!==SK(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 A=await this.webhooksEnabled();if(!A)return{enabled:A,items:[],total:0,limit:e,offset:t};let i=await aE(),[r,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:A,items:r.map(SW),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await aE();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await aE();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,A,i,r,n,a;let s,o,l=await this.credentials.getText(Qj.jiraWebhookSecret);if(!l)throw new SP("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new SP("Jira webhook signature is missing",401);if(t=`sha256=${(0,AB.createHmac)("sha256",l).update(e.body).digest("hex")}`,A=e.signature,s=Buffer.from(t),o=Buffer.from(A),!(s.length===o.length&&(0,AB.timingSafeEqual)(s,o)))throw new SP("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new SP("Jira delivery ID is missing",400);let c=await aE(),u=e.deliveryId.trim(),d=Number.parseInt(e.retryCount??"",10),h=Number.isInteger(d)?d:null;try{await c.jiraWebhookDelivery.create({data:{deliveryId:u,event:"unknown",outcome:"RECEIVED",retryCount:h}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await c.jiraWebhookDelivery.updateMany({where:{deliveryId:u,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:h,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 p=async(e,t=null)=>{let A=await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{outcome:e,error:t,processedAt:new Date}});aw.publish(aF,{jiraWebhookDeliveryChanged:SW(A)})};try{let t,A,s,o,l,d;try{let A=JSON.parse(Buffer.from(e.body).toString("utf8")),i=Sj(A);if(!i)throw Error("Payload is not an object");t=i}catch{throw new SP("Jira webhook payload is invalid JSON",400)}let g=SH(t.webhookEvent),m=(i=t,A=Sj(i.issue),(s=SH(A?.key)?.toUpperCase()??null)&&SO.test(s)?s:null),f=(r=t,o=Sj(r.issue),l=Sj(o?.fields),d=Sj(l?.project)??Sj(r.project),SH(d?.key)?.toUpperCase()??null),I=Sq(t.changelog);if(await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{event:g??"unknown",issueKey:m,projectKey:f,changelogJson:I?JSON.stringify(I):null}}),!g)return await p("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};if(!(SN.has(g)||"jira:issue_deleted"===g))return await p("IGNORED",`Unhandled Jira event ${g}`),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let C=m?[m]:[];if("issuelink_created"===g||"issuelink_deleted"===g){let e,A,i=(n=t,e=Sj(n.issueLink),[SY(e?.sourceIssueId),SY(e?.destinationIssueId)].filter((e,t,A)=>!!(e&&A.indexOf(e)===t)));if(0===i.length)return await p("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};f=(m=(C=await this.jira.resolveIssueKeys(i))[0]??null)?f??((A=(a=m).lastIndexOf("-"))>0?a.slice(0,A):null):f,await c.jiraWebhookDelivery.update({where:{deliveryId:u},data:{issueKey:m,projectKey:f}})}let E="sprint_started"===g||"sprint_closed"===g;if(!E&&!m)return await p("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let y=[];if("jira:issue_deleted"===g)await this.jira.deleteCachedTicket(m),y.push({key:m,projectKey:f});else if(E){let e=function(e){let t=SY(Sj(e.sprint)?.id);if(!t)return null;let A=Number(t);return Number.isSafeInteger(A)&&A>0?A:null}(t);if(!e)return await p("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:g,issueKey:m,triggersRecorded:0};let A=await this.jira.refreshSprintTickets(e);y.push(...A.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===g){let e=await this.jira.refreshCachedTicket(m,I);y.push({key:e.key,projectKey:e.projectKey})}else if(SN.has(g)){let e=await Promise.all(C.map(e=>this.jira.refreshCachedTicket(e)));y.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let Q=m?await this.recordWebhookTrigger({event:g,deliveryId:u,issueKey:m,projectKey:f,retries:h,payload:t}):0;for(let e of y)aw.publish(ax,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:g}});return await p("PROCESSED"),{outcome:"PROCESSED",event:g,issueKey:m,triggersRecorded:Q}}catch(t){let e=t instanceof Error?t.message:String(t);throw await p("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=SM[e.event];if(!t)return 0;let{payload:A}=e,i=Sj(A.issue),r=Sj(i?.fields),n=Sj(A.comment),a=Sj(A.attachment),s=Sj(A.issueLink),o=Sj(r?.status),l=Sq(A.changelog),c={ticket:{key:e.issueKey,title:SH(r?.summary),type:SH(Sj(r?.issuetype)?.name),status:SH(o?.name),statusId:SH(o?.id),statusCategory:SH(Sj(o?.statusCategory)?.key),assignee:SH(Sj(r?.assignee)?.displayName),assigneeAccountId:SH(Sj(r?.assignee)?.accountId),labels:Array.isArray(r?.labels)?r.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:SH(n.id),body:SH(n.body)??"",author:SV(n.author)}:null,attachment:a?{id:SH(a.id),filename:SH(a.filename),mimeType:SH(a.mimeType),author:SV(a.author)}:null,link:s?{id:SH(s.id),type:SH(Sj(s.issueLinkType)?.name),sourceIssueId:SH(s.sourceIssueId),destinationIssueId:SH(s.destinationIssueId)}:null,user:SV(A.user),changelog:l};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}}})}}function SW(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return Sq(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}}function SZ(e){if(e.agentId)throw Error("Agent credentials cannot perform control-plane operations")}function Sz(e,t,...A){if((A=A.filter(Boolean)).length>2){let t=A.pop();e+=`one of type ${A.join(", ")}, or ${t}.`}else 2===A.length?e+=`one of type ${A[0]} or ${A[1]}.`:e+=`of type ${A[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let SX=(e,t,...A)=>Sz(`Key for the ${e} algorithm must be `,t,...A);function S0(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),A=new Uint8Array(t.length);for(let e=0;e<t.length;e++)A[e]=t.charCodeAt(e);return A}class S1 extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class S4 extends S1{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class S8 extends S1{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class S2 extends S1{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class S6 extends S1{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}let S3=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},S5=e=>e?.[Symbol.toStringTag]==="KeyObject",S9=e=>S3(e)||S5(e),S7=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let A=0;A<e.byteLength;A++)if(e[A]!==t[A])return!1;return!0},De=e=>{let t=e.data[e.pos++];if(128&t){let A=127&t,i=0;for(let t=0;t<A;t++)i=i<<8|e.data[e.pos++];return i}return t},Dt=(e,t,A)=>{if(e.data[e.pos++]!==t)throw Error(A)},DA=(e,t)=>{let A=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,A},Di=async(e,t,A,i)=>{let r,n,a="spki"===e,s=()=>a?["verify"]:["sign"];switch(A){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${A.slice(-3)}`},n=s();break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${A.slice(-3)}`},n=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(A.slice(-3),10)||1}`},n=a?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":r={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[A]},n=s();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{let e=i.getNamedCurve(t);r="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new S4("Invalid or unsupported key format")}n=a?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":r={name:"Ed25519"},n=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":r={name:A},n=s();break;default:throw new S4('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,r,i?.extractable??!!a,n)};async function Dr(e,t,A){let i,r,n;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return i=/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,r=S0(e.replace(i,"")),n=A,t?.startsWith?.("ECDH-ES")&&((n||={}).getNamedCurve=e=>{let t,A={data:e,pos:0};return Dt(A,48,"Invalid PKCS#8 structure"),De(A),Dt(A,2,"Expected version field"),t=De(A),A.pos+=t,Dt(A,48,"Expected algorithm identifier"),De(A),A.pos,(e=>{let t,A=(Dt(e,6,"Expected algorithm OID"),t=De(e),DA(e,t));if(S7(A,[43,101,110]))return"X25519";if(!S7(A,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");Dt(e,6,"Expected curve OID");let i=De(e),r=DA(e,i);for(let{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(S7(r,t))return e;throw Error("Unsupported named curve")})(A)}),Di("pkcs8",r,t,n)}let Dn=new TextEncoder,Da=new TextDecoder;function Ds(e){let t=new Uint8Array(e.length);for(let A=0;A<e.length;A++){let i=e.charCodeAt(A);if(i>127)throw TypeError("non-ASCII string encountered in encode()");t[A]=i}return t}function Do(e){let t=e;return("string"==typeof t&&(t=Dn.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let A=0;A<e.length;A+=32768)t.push(String.fromCharCode.apply(null,e.subarray(A,A+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}let Dl=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Dc(e,t){if(parseInt(e.hash.name.slice(4),10)!==t)throw Dl(`SHA-${t}`,"algorithm.hash")}async function Du(e,t,A){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>Sz("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[A])}return!function(e,t,A){switch(t){case"HS256":case"HS384":case"HS512":if("HMAC"!==e.algorithm.name)throw Dl("HMAC");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==e.algorithm.name)throw Dl("RSASSA-PKCS1-v1_5");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==e.algorithm.name)throw Dl("RSA-PSS");Dc(e.algorithm,parseInt(t.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==e.algorithm.name)throw Dl("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let i;if(i=e.algorithm,i.name!==t)throw Dl(t);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==e.algorithm.name)throw Dl("ECDSA");let A=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==A)throw Dl(A,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(A&&!e.usages.includes(A))throw TypeError(`CryptoKey does not support this operation, its usages must include ${A}.`)}(t,e,A),t}async function Dd(e,t,A){let i=await Du(e,t,"sign");return!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:A}=t.algorithm;if("number"!=typeof A||A<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}(e,i),new Uint8Array(await crypto.subtle.sign(function(e,t){let A=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:A,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:A,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:A,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:A,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new S4(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm),i,A))}function Dh(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}let Dp=e=>Dh(e)&&"string"==typeof e.kty,Dg=e=>e?.[Symbol.toStringTag],Dm=(e,t,A)=>{if(void 0!==t.use){let e;switch(A){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let i;switch(!0){case"sign"===A||"verify"===A:case"dir"===e:case e.includes("CBC-HS"):i=A;break;case e.startsWith("PBES2"):i="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===A?"wrapKey":"unwrapKey":A;break;case"encrypt"===A&&e.startsWith("RSA"):i="wrapKey";break;case"decrypt"===A:i=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(i&&t.key_ops?.includes?.(i)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${i}" when present`)}return!0},Df='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function DI(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:A}=function(e){let t,A;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},A=e.priv?["sign"]:["verify"];break;default:throw new S4(Df)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},A=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},A=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},A=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new S4(Df)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[e.alg]},A=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},A=e.d?["deriveBits"]:[];break;default:throw new S4(Df)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},A=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},A=e.d?["deriveBits"]:[];break;default:throw new S4(Df)}break;default:throw new S4('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:A}}(e),i={...e};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,t,e.ext??(!e.d&&!e.priv),e.key_ops??A)}let DC="given KeyObject instance cannot be used for this algorithm",DE=async(e,A,i,r=!1)=>{let n=(t||=new WeakMap).get(e);if(n?.[i])return n[i];let a=await DI({...A,alg:i});return r&&Object.freeze(e),n?n[i]=a:t.set(e,{[i]:a}),a};async function Dy(e,A){if(e instanceof Uint8Array||S3(e))return e;if(S5(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,A)=>{let i,r=(t||=new WeakMap).get(e);if(r?.[A])return r[A];let n="public"===e.type,a=!!n;if("x25519"===e.asymmetricKeyType){switch(A){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(DC)}i=e.toCryptoKey(e.asymmetricKeyType,a,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==A&&"Ed25519"!==A)throw TypeError(DC);i=e.toCryptoKey(e.asymmetricKeyType,a,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(A!==e.asymmetricKeyType.toUpperCase())throw TypeError(DC);i=e.toCryptoKey(e.asymmetricKeyType,a,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(A){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError(DC)}if(A.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},a,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:A.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},a,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError(DC);let r={ES256:"P-256",ES384:"P-384",ES512:"P-521"};r[A]&&t===r[A]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:t},a,[n?"verify":"sign"])),A.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:t},a,n?[]:["deriveBits"]))}if(!i)throw TypeError(DC);return r?r[A]=i:t.set(e,{[A]:i}),i})(e,A)}catch(e){if(e instanceof TypeError)throw e}let i=e.export({format:"jwk"});return DE(e,i,A)}if(Dp(e)){if(e.k){var i=e.k;if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof i?i:Da.decode(i),{alphabet:"base64url"});let t=i;t instanceof Uint8Array&&(t=Da.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return S0(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}return DE(e,e,A,!0)}throw Error("unreachable")}function DQ(e,t){if(e)throw TypeError(`${t} can only be called once`)}Symbol();class Dw{#AM;#AG;#A_;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#AM=e}setProtectedHeader(e){return DQ(this.#AG,"setProtectedHeader"),this.#AG=e,this}setUnprotectedHeader(e){return DQ(this.#A_,"setUnprotectedHeader"),this.#A_=e,this}async sign(e,t){let A,i,r,n;if(!this.#AG&&!this.#A_)throw new S8("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!function(...e){let t,A=e.filter(Boolean);if(0===A.length||1===A.length)return!0;for(let e of A){let A=Object.keys(e);if(!t||0===t.size){t=new Set(A);continue}for(let e of A){if(t.has(e))return!1;t.add(e)}}return!0}(this.#AG,this.#A_))throw new S8("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...this.#AG,...this.#A_},s=function(e,t,A,i,r){let n;if(void 0!==r.crit&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let a of(n=void 0!==A?new Map([...Object.entries(A),...t.entries()]):t,i.crit)){if(!n.has(a))throw new S4(`Extension Header Parameter "${a}" is not recognized`);if(void 0===r[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(n.get(a)&&void 0===i[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(i.crit)}(S8,new Map([["b64",!0]]),t?.crit,this.#AG,a),o=!0;if(s.has("b64")&&"boolean"!=typeof(o=this.#AG.b64))throw new S8('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=a;if("string"!=typeof l||!l)throw new S8('JWS "alg" (Algorithm) Header Parameter missing or invalid');var c="sign";switch(l.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,A)=>{if(!(t instanceof Uint8Array)){if(Dp(t)){if("oct"===t.kty&&"string"==typeof t.k&&Dm(e,t,A))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!S9(t))throw TypeError(SX(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${Dg(t)} instances for symmetric algorithms must be of type "secret"`)}})(l,e,c);break;default:((e,t,A)=>{if(Dp(t))switch(A){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&Dm(e,t,A))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&Dm(e,t,A))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!S9(t))throw TypeError(SX(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${Dg(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(A){case"sign":throw TypeError(`${Dg(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${Dg(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(A){case"verify":throw TypeError(`${Dg(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${Dg(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(l,e,c)}o?i=Ds(A=Do(this.#AM)):(i=this.#AM,A=""),this.#AG?n=Ds(r=Do(JSON.stringify(this.#AG))):(r="",n=new Uint8Array);let u=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),A=0;for(let i of e)t.set(i,A),A+=i.length;return t}(n,Ds("."),i),d=await Dy(e,l),h={signature:Do(await Dd(l,d,u)),payload:A};return this.#A_&&(h.header=this.#A_),this.#AG&&(h.protected=r),h}}class DB{#AJ;constructor(e){this.#AJ=new Dw(e)}setProtectedHeader(e){return this.#AJ.setProtectedHeader(e),this}async sign(e,t){let A=await this.#AJ.sign(e,t);if(void 0===A.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${A.protected}.${A.payload}.${A.signature}`}}let Db=e=>Math.floor(e.getTime()/1e3),Dv=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Dk(e){let t,A=Dv.exec(e);if(!A||A[4]&&A[1])throw TypeError("Invalid time period format");let i=parseFloat(A[2]);switch(A[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(i);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*i);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*i);break;case"day":case"days":case"d":t=Math.round(86400*i);break;case"week":case"weeks":case"w":t=Math.round(604800*i);break;default:t=Math.round(0x1e187e0*i)}return"-"===A[1]||"ago"===A[4]?-t:t}function DS(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}class DD{#AM;constructor(e){if(!Dh(e))throw TypeError("JWT Claims Set MUST be an object");this.#AM=structuredClone(e)}data(){return Dn.encode(JSON.stringify(this.#AM))}get iss(){return this.#AM.iss}set iss(e){this.#AM.iss=e}get sub(){return this.#AM.sub}set sub(e){this.#AM.sub=e}get aud(){return this.#AM.aud}set aud(e){this.#AM.aud=e}set jti(e){this.#AM.jti=e}set nbf(e){"number"==typeof e?this.#AM.nbf=DS("setNotBefore",e):e instanceof Date?this.#AM.nbf=DS("setNotBefore",Db(e)):this.#AM.nbf=Db(new Date)+Dk(e)}set exp(e){"number"==typeof e?this.#AM.exp=DS("setExpirationTime",e):e instanceof Date?this.#AM.exp=DS("setExpirationTime",Db(e)):this.#AM.exp=Db(new Date)+Dk(e)}set iat(e){void 0===e?this.#AM.iat=Db(new Date):e instanceof Date?this.#AM.iat=DS("setIssuedAt",Db(e)):"string"==typeof e?this.#AM.iat=DS("setIssuedAt",Db(new Date)+Dk(e)):this.#AM.iat=DS("setIssuedAt",e)}}class DR{#AG;#AL;constructor(e={}){this.#AL=new DD(e)}setIssuer(e){return this.#AL.iss=e,this}setSubject(e){return this.#AL.sub=e,this}setAudience(e){return this.#AL.aud=e,this}setJti(e){return this.#AL.jti=e,this}setNotBefore(e){return this.#AL.nbf=e,this}setExpirationTime(e){return this.#AL.exp=e,this}setIssuedAt(e){return this.#AL.iat=e,this}setProtectedHeader(e){return this.#AG=e,this}async sign(e,t){let A=new DB(this.#AL.data());if(A.setProtectedHeader(this.#AG),Array.isArray(this.#AG?.crit)&&this.#AG.crit.includes("b64")&&!1===this.#AG.b64)throw new S2("JWTs MUST NOT use unencoded payload");return A.sign(e,t)}}function DU(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function DT(e){let t=DU(e.get("x-ratelimit-limit")),A=DU(e.get("x-ratelimit-remaining")),i=DU(e.get("x-ratelimit-used")),r=DU(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===A||null===i||null===r||!n)return null;let a=new Date(1e3*r);return Number.isFinite(a.getTime())?{limit:t,remaining:A,used:i,resetAt:a,resource:n}:null}async function DF(e,t){let A=DT(t.headers);if(!A)return null;try{let t=await aE(),i=`${e}:${A.resource}`,r=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:A.resource}},create:{id:i,authentication:e,observedAt:r,...A},update:{observedAt:r,...A}})}catch{}return A}async function Dx(){let e=await aE();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 DO="actions.cancelWorkflowRun",DN="actions.dispatchWorkflow",DM="actions.forceCancelWorkflowRun",DG="actions.getJobForWorkflowRun",D_="actions.getWorkflowRun",DJ="actions.getWorkflowRunAttempt",DL="actions.listJobsForWorkflowRun",DP="actions.listJobsForWorkflowRunAttempt",DH="actions.listRepoWorkflows",DY="actions.listWorkflowRuns",Dq="actions.listWorkflowRunsForRepo",Dj="actions.reRunJobForWorkflowRun",DK="actions.reRunWorkflow",DV="actions.reRunWorkflowFailedJobs",D$="apps.createInstallationAccessToken",DW="apps.getAuthenticated",DZ="apps.getInstallation",Dz="apps.updateWebhookConfigForApp",DX="repos.listPullRequestsAssociatedWithCommit",D0="users.listEmailsForAuthenticatedUser";class D1 extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,A=null,i=null,r=null){super(t),this.code=e,this.githubRequestId=A,this.statusCode=i,this.rateLimit=r,this.name="GitHubAppError"}}let D4=new Map,D8=new Map;function D2(e,t,A){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D1(A,`${t} must be a positive integer`);return i}function D6(e){let{privateKeyPkcs8:t,keyFingerprint:A}=function(e){try{let t=(0,AB.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==t.asymmetricKeyType)throw Error("The key is not RSA");let A=t.export({format:"pem",type:"pkcs8"}).toString(),i=(0,AB.createPublicKey)(t).export({format:"der",type:"spki"}),r=`SHA256:${(0,AB.createHash)("sha256").update(i).digest("base64url")}`;return{key:t,privateKeyPkcs8:A,keyFingerprint:r}}catch{throw new D1("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:D2(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:D2(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:t,keyFingerprint:A}}async function D3(e){try{let t=await Dr(e.privateKeyPkcs8,"RS256"),A=Math.floor(Date.now()/1e3);return await new DR({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(A-60).setExpirationTime(A+540).sign(t)}catch{throw new D1("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function D5(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function D9(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function D7(e,t,A,i,r){let n,a=Date.now(),s=(t.method??"GET").toUpperCase(),o=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:s,operation:A,requestSource:r,body:o,durationMs:Date.now()-a,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D1("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:s,operation:A,requestSource:r,body:o,durationMs:Date.now()-a,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:DT(n.headers)})).catch(()=>void 0),n}async function Re(e){try{return await e.json()}catch{return null}}function Rt(e){return e.headers.get("x-github-request-id")}function RA(e,t,A=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),A))t&&(i=i.split(t).join("[REDACTED]"));return i}async function Ri(e,t){let A=await D7(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:D9(`Bearer ${t}`)},DZ,e,"GITHUB_SETTINGS"),i=await Re(A),r=Rt(A);if(401===A.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",r);if(404===A.status)throw new D1("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",r);if(!A.ok||!i||"object"!=typeof i)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(i,A.status,[t,e.privateKey,e.privateKeyPkcs8]),r);if(String(i.app_id)!==e.appId)throw new D1("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",r);return i}async function Rr(e,t){let A=await D7(`${e.apiBaseUrl}/app`,{headers:D9(`Bearer ${t}`)},DW,e,"GITHUB_SETTINGS"),i=await Re(A),r=Rt(A);if(401===A.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",r);if(!A.ok||!i||"object"!=typeof i)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(i,A.status,[t,e.privateKey,e.privateKeyPkcs8]),r);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",r);return{details:i,githubRequestId:r}}async function Rn(e){let t=D6(e),A=await D3(t),i=await Rr(t,A);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function Ra(e,t,A){let i=A??await D3(e),r=await D7(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:D9(`Bearer ${i}`)},D$,e,t),n=await Re(r),a=Rt(r);if(401===r.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D1("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!n||"object"!=typeof n)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(n,r.status,[i,e.privateKey,e.privateKeyPkcs8]),a);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",a);if("write"!==(n.permissions?.actions??"none"))throw new D1("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",a);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function Rs(e,t){let A=D5(e),i=D4.get(A);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let r=D8.get(A);if(r)return r;let n=Ra(e,t).then(e=>(D4.set(A,e),e)).finally(()=>D8.delete(A));return D8.set(A,n),n}function Ro(){D4.clear(),D8.clear()}async function Rl(e,t,A){let i=D6(e),r=await Rs(i,A),n=await t(r.token);return 401===n.status&&(D4.delete(D5(i)),r=await Rs(i,A),n=await t(r.token)),{response:n,token:r.token}}async function Rc(e,t,A,i){let{response:r,token:n}=await Rl(e,r=>D7(e.graphqlUrl,{method:"POST",headers:{...D9(`Bearer ${r}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:A})},null,e,i),i),a=await Re(r),s=Rt(r),o=DT(r.headers);if(401===r.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",s,r.status,o);if(!r.ok||a?.errors?.length||!a?.data){let t=a?.errors?.map(e=>e.message).filter(Boolean).join("; ")||RA(a,r.status,[n]);throw new D1("GITHUB_APP_REQUEST_FAILED",RA({message:t},r.status,[n,e.privateKey]),s,r.status,o)}return{data:a.data,githubRequestId:s,statusCode:r.status,rateLimit:o}}async function Ru(e){let t=D6(e),A=await D3(t),[i,r]=await Promise.all([Ri(t,A),Rr(t,A)]),n=await Ra(t,"GITHUB_SETTINGS",A);D4.set(D5(t),n);let a=await Rc(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:r.details.slug,appOwnerLogin:r.details.owner.login,appOwnerType:r.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:a.data.viewer.login,verifiedAt:new Date,githubRequestId:a.githubRequestId}}async function Rd(e,t){let A=D6(e),i=await D3(A),r=await D7(`${A.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...D9(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},Dz,A,"GITHUB_SETTINGS"),n=Rt(r);if(404===r.status)return{configured:!1,githubRequestId:n};if(!r.ok)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(await Re(r),r.status,[i,t.secret,A.privateKey]),n);return{configured:!0,githubRequestId:n}}async function Rh(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:r}=await Rl(e,i=>D7(A,{method:"POST",headers:D9(`Bearer ${i}`)},DK,e,t.requestSource),t.requestSource),n=Rt(i);if(401===i.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await Re(i);throw new D1(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":RA(t,i.status,[r,e.privateKey]),n)}return{githubRequestId:n}}async function Rp(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:r}=await Rl(e,i=>D7(A,{method:"POST",headers:D9(`Bearer ${i}`)},DV,e,t.requestSource),t.requestSource),n=Rt(i);if(!i.ok){let t=await Re(i);throw new D1(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":RA(t,i.status,[r,e.privateKey]),n)}return{githubRequestId:n}}async function Rg(e,t){let A=t.force?"force-cancel":"cancel",i=t.force?DM:DO,r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${A}`,{response:n,token:a}=await Rl(e,A=>D7(r,{method:"POST",headers:D9(`Bearer ${A}`)},i,e,t.requestSource),t.requestSource),s=Rt(n);if(401===n.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",s);if(!n.ok){let t=await Re(n);throw new D1(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":RA(t,n.status,[a,e.privateKey]),s)}return{githubRequestId:s}}async function Rm(e,t){let A=[],i=1,r=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:a,token:s}=await Rl(e,A=>D7(n,{headers:D9(`Bearer ${A}`)},DL,e,t.requestSource),t.requestSource),o=Rt(a);if(401===a.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);let l=await Re(a);if(!a.ok||!l||"object"!=typeof l)throw new D1("GITHUB_APP_REQUEST_FAILED",RA(l,a.status,[s,e.privateKey]),o);if(!Number.isInteger(l.total_count)||!Array.isArray(l.jobs))throw new D1("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",o);r=l.total_count??0,A.push(...l.jobs),i+=1}while(A.length<r)return A}async function Rf(e,t){let A=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${A}/actions/jobs/${encodeURIComponent(t.jobId)}`,r=await Rl(e,A=>D7(i,{headers:D9(`Bearer ${A}`)},DG,e,t.requestSource),t.requestSource),n=Rt(r.response);if(401===r.response.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let a=await Re(r.response);if(!r.response.ok||!a||"object"!=typeof a)throw new D1(404===r.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===r.response.status?"The GitHub Actions job is not available to this installation":RA(a,r.response.status,[r.token,e.privateKey]),n);if(String(a.run_id??"")!==t.workflowRunId)throw new D1("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(a.status?.toLowerCase()!=="completed")throw new D1("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let s=await Rl(e,A=>D7(`${i}/rerun`,{method:"POST",headers:D9(`Bearer ${A}`)},Dj,e,t.requestSource),t.requestSource),o=Rt(s.response);if(401===s.response.status)throw new D1("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!s.response.ok){let t=await Re(s.response);throw new D1(404===s.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===s.response.status?"The GitHub Actions job is not available to this installation":RA(t,s.response.status,[s.token,e.privateKey]),o)}return{githubRequestId:o}}let RI=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),RC=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),RE=["COMPLETED","EXHAUSTED","STOPPED"],Ry={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},RQ="server:github-auto-retry";function Rw(e){return e.toISOString()}function RB(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:Rw(e.updatedAt)})),createdAt:Rw(e.createdAt),updatedAt:Rw(e.updatedAt)}}class Rb{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,A=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:RQ,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),A&&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(RQ,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 aE()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(RQ,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(RQ,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 aE(),A=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...A?{codebaseRepositoryId:A}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(RB)}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 t=await aE(),A=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let i=await t.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(A=i?.branch??null))throw Error("The worktree does not have a branch")}let i=await t.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),r=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(i.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&r.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 n=e.id??(0,AB.randomUUID)(),a=await t.$transaction(async t=>(await t.gitHubAutoRetryRule.upsert({where:{id:n},create:{id:n,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 t.gitHubAutoRetryTarget.deleteMany({where:{ruleId:n}}),e.targets.length&&await t.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,AB.randomUUID)(),ruleId:n,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await t.gitHubAutoRetryExecution.deleteMany({where:{ruleId:n}}),t.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:n},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),RB(a)}async setEnabled(e,t){let A=await aE(),i=await A.$transaction(async A=>(t&&await A.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),A.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)),RB(i)}async delete(e){return(await (await aE()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,A=!1){if("WORKFLOW_RUN"!==e.scope){let i=RC.has(t.status);if(!A&&!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,t,A){return(await aE()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:t.id,targetKey:A}},create:{id:(0,AB.randomUUID)(),ruleId:e,workflowRunId:t.id,workflowId:t.workflowId,targetKey:A},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let A=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return A.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:A.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,A){await (await aE()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:A,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,A,i,r){let n=await aE();await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:A.runAttempt,observedAttempt:A.runAttempt,lastStatus:A.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,A.id,i,r,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let A=i instanceof Error?i.message:String(i);await n.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:A}}),await n.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A}})}}async reconcileExecution(e,t,A,i){var r;let n,a=await this.execution(e.id,t,A);if(null!=a.pendingFromAttempt)if(t.runAttempt>a.pendingFromAttempt)await (await aE()).gitHubAutoRetryExecution.update({where:{id:a.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-a.updatedAt.getTime()<12e4)return!1;let t=await aE(),A="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:a.id},data:{status:"ERROR",lastError:A}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:A}})}),!1}if(a.observedAttempt===t.runAttempt&&null==a.pendingFromAttempt)return!1;let s=i?.status??t.status,o=(n=null!=(r={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:a.automaticRetries,state:s}).retryLimit&&r.automaticRetries>=r.retryLimit,"COUNT"===r.mode?"SUCCESS"!==r.state?"STOP":n?"COMPLETE":"RETRY":"SUCCESS"===r.state?"COMPLETE":RI.has(r.state)?n?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===o?(await this.finishExecution(a.id,t,"COMPLETED"),!1):"EXHAUSTED"===o?(await this.finishExecution(a.id,t,"EXHAUSTED"),!1):"STOP"===o?(await this.finishExecution(a.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,a,t,i?"JOB":"ALL_JOBS",i?.id??null):await this.trigger(e,a,t,i?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",i?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await aE(),A=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=A.length;let i=new Map,r=A.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:A.map(e=>e.id)},status:{notIn:RE}},select:{ruleId:!0,workflowRunId:!0}}):[],n=new Map;for(let e of r){let t=n.get(e.ruleId)??new Set;t.add(e.workflowRunId),n.set(e.ruleId,t)}let a=new Map;for(let e of A){let A=i.get(e.codebaseRepositoryId);if(!A)try{A=await this.github.autoRetryRuns(e.codebaseRepositoryId),i.set(e.codebaseRepositoryId,A)}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}});continue}let r=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),s=n.get(e.id)??new Set;for(let i of new Set([...r,...s]))if(!A.some(e=>e.id===i))try{A.push(await this.github.autoRetryRun(e.codebaseRepositoryId,i,!1))}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}})}for(let t of A){if("WORKFLOW_RUN"===e.scope&&!r.has(t.id)||!this.matches(e,t,s.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let A=a.get(t.id);(!A||Ry[e.scope]>Ry[A.rule.scope])&&a.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:A}of a.values()){let i=this.targetKeys(e,A);if(RC.has(A.status)){await Promise.all(i.map(t=>this.execution(e.id,A,t)));continue}let r=A,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===r.id||e.workflowId===r.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,r,"workflow",null);continue}let a=await Promise.all(i.map(t=>this.execution(e.id,r,t)));if(!a.some(e=>e.observedAttempt!==r.runAttempt||null!=e.pendingFromAttempt&&r.runAttempt>e.pendingFromAttempt)){for(let t=0;t<a.length;t+=1)a[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,r,i[t],null);continue}try{r=await this.github.autoRetryRun(e.codebaseRepositoryId,r.id)}catch(A){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:A instanceof Error?A.message:String(A)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=r.jobs.filter(e=>n.some(t=>t.jobName===e.name)),A=t.find(e=>RI.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];A?await this.reconcileExecution(e,r,"workflow",A):a[0]&&await this.finishExecution(a[0].id,r,"STOPPED");continue}let s=new Map(i.map((e,t)=>[e,a[t]]));for(let t of n){let A=r.jobs.find(e=>e.name===t.jobName);if(!A){let e=s.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,r,"STOPPED");continue}if(await this.reconcileExecution(e,r,`job:${A.name}`,A))break}}for(let e of A.filter(e=>"WORKFLOW_RUN"===e.scope)){let A=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});A.length>0&&A.every(e=>RE.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:A.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}let Rv={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},Rk=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),RS=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),RD=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function RR(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>Rk.has(e))?"FAILURE":e.some(e=>RS.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>RD.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function RU(e,t){let A=(t||e||"NONE").toUpperCase();return Rx(A)?A:"REQUESTED"===A||"WAITING"===A?"QUEUED":"NONE"}function RT(e){return RS.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function RF(e,t,A){let i=e.runAttempt??0,r=t.runAttempt??0;if(r!==i)return r>i;let n=e.githubUpdatedAt?.getTime()??0,a=t.githubUpdatedAt?.getTime()??0;if(a!==n)return a>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>A.getTime())return"MUTATION"===t.source;let s="MUTATION"===e.source?Rv.LEGACY:Rv[e.source],o=Rv[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let A=RT(e.status),i=RT(t.status);if(i!==A)return i>A}return o===s||o>s}function Rx(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 RO(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function RN(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function RM(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function RG(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function R_(e){return{id:e.githubPipelineId,name:e.name,status:Rx(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:RN(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function RJ(e,t){return{...R_(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function RL(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:RO(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(R_).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function RP(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 RH(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(RP).sort((e,t)=>e.localeCompare(t))})}class RY{lastPrunedAt=0;async snapshot(e){let t=await aE(),A=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return A?RL(A):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 A=await aE();return(await A.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(RL)}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 A=await aE();return(await A.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>RJ(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",A=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,A=i.get(e)??[];A.push(t),i.set(e,A)}let r=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,A=!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:A}})(e,t,A))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&r.set(t.workflowRunId,t);return r}async observeJobs(e,t,A,i="REST",r=null){let n=await aE(),a=await n.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let s=A.filter(e=>null==e.runAttempt||null==a.runAttempt||e.runAttempt===a.runAttempt);if(A.length>0&&0===s.length)return RJ({...a.snapshot,records:[a]},a);let o=RN(a.jobsJson),l=new Map(o.map(e=>[e.id,e])),c=s.map(e=>(function(e,t){if(!e)return t;let A=e.runAttempt??0,i=t.runAttempt??0;if(i!==A)return i>A?t:e;let r=RM(e.status),n=RM(t.status);return n<r?e:n===r&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(l.get(e.id),e)),u="WEBHOOK"===i?[...new Map([...o,...c].map(e=>[e.id,e])).values()]:c,d=Rx(a.status)?a.status:"NONE",h="REST"===i&&s.length>0?RR(s.map(e=>e.status),null):"NONE",p=("ERROR"===h||"FAILURE"===h||"SUCCESS"===h)&&a.snapshot.graphqlRollupStatus===h?h:d;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...R_(a),status:p,source:i,jobs:u,githubUpdatedAt:r??a.githubUpdatedAt,isCurrent:a.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,A){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},A)}async optimisticByWorkflowRun(e,t,A){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},A)}async optimisticJobByCheckSuite(e,t,A){let i=await aE(),r=await i.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!r)return null;let n=RN(r.jobsJson).map(e=>e.id===A?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:n})}async optimisticJobByWorkflowRun(e,t,A){let i=await aE(),r=await i.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!r)return null;let n=RN(r.jobsJson).map(e=>e.id===A?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:n})}async optimisticRecord(e,t){let A=await aE(),i=await A.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(!i)return null;let r=new Date;return(await this.observeSnapshot({repositoryGithubId:i.snapshot.repositoryGithubId,repositoryNameWithOwner:i.snapshot.repositoryNameWithOwner,repositoryUrl:i.snapshot.repositoryUrl,headSha:i.snapshot.headSha,pipelines:[{...R_(i),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:i.githubUpdatedAt,sourceFetchedAt:r,optimisticUntil:new Date(r.getTime()+12e4),isCurrent:i.isCurrent}]})).changedPipeline}async observeSnapshot(e){let t=e.repositoryGithubId.trim(),A=e.headSha.trim();if(!t||!A)throw Error("GitHub repository ID and head SHA are required");let i=new Date,r=e.sourceFetchedAt??i,n=await aE(),a=await n.$transaction(async n=>{let a=await n.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:t,headSha:A}},create:{id:(0,AB.randomUUID)(),repositoryGithubId:t,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:A,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:i},update:{lastObservedAt:i},include:{records:!0}}),s=RH(a),o=!!(e.completeGraphqlRollup&&(!a.lastGraphqlSyncAt||r.getTime()>=a.lastGraphqlSyncAt.getTime())),l=new Set,c=null;for(let t 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}`}(t),A=(await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id}})).filter(A=>A.identityKey===e||t.checkSuiteId&&A.checkSuiteId===t.checkSuiteId||t.workflowRunId&&A.workflowRunId===t.workflowRunId),s=A[0]??null;for(let e of A.slice(1))s&&RF({runAttempt:s.runAttempt,githubUpdatedAt:s.githubUpdatedAt,source:RG(s.source),optimisticUntil:s.optimisticUntil,status:Rx(s.status)?s.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:RG(e.source),status:Rx(e.status)?e.status:"NONE"},i)&&(s=e);for(let e of A)s&&e.id!==s.id&&(0===RN(s.jobsJson).length&&RN(e.jobsJson).length>0&&(s=await n.gitHubPipelineRecord.update({where:{id:s.id},data:{jobsJson:e.jobsJson}})),await n.gitHubPipelineRecord.delete({where:{id:e.id}}),c=s.id);let u=t.sourceFetchedAt??r,d=t.githubUpdatedAt??null,h=void 0===t.runAttempt?s?.runAttempt??null:t.runAttempt,p=void 0!==t.jobs?JSON.stringify(t.jobs):s&&(h??0)<=(s.runAttempt??0)?s.jobsJson:"[]",g=!!o||(!1===t.isCurrent?s?.isCurrent??!1:t.isCurrent??s?.isCurrent??!0);if(s){l.add(s.id);let A=RP(s),r=RF({runAttempt:s.runAttempt,githubUpdatedAt:s.githubUpdatedAt,source:RG(s.source),optimisticUntil:s.optimisticUntil,status:Rx(s.status)?s.status:"NONE"},{runAttempt:h,githubUpdatedAt:d,source:t.source,status:t.status},i),a=!!(!r&&"MUTATION"===s.source&&s.optimisticUntil&&s.optimisticUntil.getTime()>i.getTime()&&"MUTATION"!==t.source);A!==RP(s=await n.gitHubPipelineRecord.update({where:{id:s.id},data:r?{identityKey:e,githubPipelineId:t.id,name:t.name,status:t.status,url:void 0===t.url?s.url:t.url,checkSuiteId:void 0===t.checkSuiteId?s.checkSuiteId:t.checkSuiteId,workflowRunId:void 0===t.workflowRunId?s.workflowRunId:t.workflowRunId,workflowId:void 0===t.workflowId?s.workflowId:t.workflowId,runNumber:void 0===t.runNumber?s.runNumber:t.runNumber,runAttempt:h,canRetry:void 0===t.canRetry?s.canRetry:t.canRetry,retryUnavailableReason:void 0===t.retryUnavailableReason?s.retryUnavailableReason:t.retryUnavailableReason,jobsJson:p,source:t.source,githubUpdatedAt:d,sourceFetchedAt:u,lastObservedAt:i,optimisticUntil:void 0===t.optimisticUntil?s.optimisticUntil:t.optimisticUntil,isCurrent:g}:{lastObservedAt:i,...void 0!==t.jobs&&!a?{jobsJson:p}:{},...o?{isCurrent:!0}:{}}}))&&(c=s.id)}else c=(s=await n.gitHubPipelineRecord.create({data:{id:(0,AB.randomUUID)(),snapshotId:a.id,identityKey:e,githubPipelineId:t.id,name:t.name,status:t.status,url:t.url??null,checkSuiteId:t.checkSuiteId??null,workflowRunId:t.workflowRunId??null,workflowId:t.workflowId??null,runNumber:t.runNumber??null,runAttempt:h,canRetry:t.canRetry??!1,retryUnavailableReason:t.retryUnavailableReason??null,jobsJson:p,source:t.source,githubUpdatedAt:d,sourceFetchedAt:u,lastObservedAt:i,optimisticUntil:t.optimisticUntil??null,isCurrent:g}})).id;l.add(s.id)}if(o)for(let e of(await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id,isCurrent:!0}})))!l.has(e.id)&&e.sourceFetchedAt.getTime()<=r.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=i.getTime())&&(await n.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),c??=e.id);let u=await n.gitHubPipelineRecord.findMany({where:{snapshotId:a.id}}),d=o?e.graphqlRollupStatus??null:a.graphqlRollupStatus,h=RR(u.filter(e=>e.isCurrent).map(e=>Rx(e.status)?e.status:"NONE"),d&&RO(d)?d:null),p=s!==RH(a=await n.gitHubPipelineSnapshot.update({where:{id:a.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:h,graphqlRollupStatus:d,lastGraphqlSyncAt:o?r:a.lastGraphqlSyncAt,lastObservedAt:i},include:{records:!0}}))||null!==c;p&&(a=await n.gitHubPipelineSnapshot.update({where:{id:a.id},data:{revision:{increment:1}},include:{records:!0}}));let g=a,m=c?g.records.find(e=>e.id===c)??null:null;return{changed:p,change:{snapshot:RL(g),changedPipeline:m?RJ(g,m):null}}});return a.changed&&aw.publish(aT,{githubPipelineStatusChanged:a.change}),this.pruneIfNeeded().catch(()=>void 0),a.change}subscribe(){return aw.iterate(aT)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await aE();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}let Rq=/^[_A-Za-z][_0-9A-Za-z]*$/,Rj=new Map([["GitHubWorktreePullRequestStatuses",60]]),RK=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function RV(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(A=>[A,e(t[A])])):t}(e))}let R$=/(?:authorization|password|private.?key|secret|token)$/i;function RW(e,t=""){return R$.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>RW(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,RW(t,e)])):e}function RZ(e){try{return JSON.parse(e)}catch{return null}}function Rz(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 RX{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,AB.createHash)("sha256").update(RV({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,A){return[A,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await aE();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await aE(),[A,i]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return A?.ttlSeconds??i}async query(e){let t=this.cacheGeneration,A=await aE(),i=this.cacheKey(e),r=this.inFlightKey(i,e,t),n=Date.now(),[a,s,o]=await Promise.all([A.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:i}}),this.effectiveTtlSeconds(e.operation),A.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(t!==this.cacheGeneration)return this.query(e);let l=null!==a&&Date.now()-a.fetchedAt.getTime()<1e3*s;if(!e.force&&l)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-n,pointCost:0,pointsAvoided:a.pointCost??0}).catch(()=>void 0),t!==this.cacheGeneration)?this.query(e):{data:RZ(a.responseJson),source:"CACHE",stale:!1,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};let c=this.inFlight.get(r);if(c){let A=await c;return t!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-n,pointCost:0,pointsAvoided:A.pointCost??0}).catch(()=>void 0),t!==this.cacheGeneration)?this.query(e):{...A,source:"CACHE"}}if(o?.remaining===0&&o.resetAt.getTime()>Date.now()){let A=`GitHub GraphQL rate limit is exhausted until ${o.resetAt.toISOString()}`,i=null!==a&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-n,error:A,servedStale:i,pointCost:0,pointsAvoided:i?a.pointCost??0:0,rateLimit:{limit:o.limit,remaining:o.remaining,used:o.used,resetAt:o.resetAt,resource:o.resource}}).catch(()=>void 0),t!==this.cacheGeneration)return this.query(e);if(i)return{data:RZ(a.responseJson),source:"ERROR",stale:!0,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};throw Error(A)}let u=(async()=>{try{let r=await e.fetcher(),a=new Date,s=null;if(t===this.cacheGeneration){let t=A.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:i},create:{id:(0,AB.randomUUID)(),cacheKey:i,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:RV(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:a,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:RV(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:a,pointCost:r.pointCost}});this.cacheWrites.add(t);try{s=await t}finally{this.cacheWrites.delete(t)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-n,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:a,entryId:t===this.cacheGeneration?s?.id??null:null,pointCost:r.pointCost}}catch(r){let A=Rz(r),i=t===this.cacheGeneration&&null!==a&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-n,statusCode:A.statusCode,error:r instanceof Error?r.message:String(r),servedStale:i,pointsAvoided:i?a?.pointCost??0:0,rateLimit:A.rateLimit}).catch(()=>void 0),t!==this.cacheGeneration)throw r;if(i)return{data:RZ(a.responseJson),source:"ERROR",stale:!0,fetchedAt:a.fetchedAt,entryId:a.id,pointCost:a.pointCost};throw r}})();this.inFlight.set(r,u);try{return await u}finally{this.inFlight.get(r)===u&&this.inFlight.delete(r)}}async mutation(e){let t,A=Date.now();try{t=await e.fetcher()}catch(i){let t=Rz(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-A,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()-A,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 A=await aE();return await A.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await aE();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:Rj.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await aE(),[t,A]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...Rj.keys(),...t.map(({operation:e})=>e),...A.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let A=e.trim();if(!Rq.test(A))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 i=await aE(),r=await i.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:A},create:{operation:A,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:r.operation,ttlSeconds:r.ttlSeconds,builtIn:Rj.has(r.operation),createdAt:r.createdAt.toISOString(),updatedAt:r.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(Rj.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let A=await aE();return(await A.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,A={};try{let i=new URL(e.endpoint);t=i.pathname,A={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{A={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:A,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 aE();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:A}=this.beginInvalidation();await Promise.allSettled(t);let i=await aE();return await i.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(A),await i.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await aE();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await aE();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let A=this.pagination(e,t),i=await aE(),[r,n,a,s]=await Promise.all([i.gitHubGraphqlCacheEntry.findMany({take:A.limit,skip:A.offset,orderBy:{fetchedAt:"desc"}}),i.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),i.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),o=new Map(s.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...A,total:n,items:r.map(e=>this.entryView(e,o.get(e.operation)??a))}}async entry(e){let t=await aE(),A=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!A)return null;let i=await this.effectiveTtlSeconds(A.operation);return{...this.entryView(A,i),query:A.query,variables:RZ(A.variablesJson),response:RZ(A.responseJson)}}async calls(e=50,t=0,A={}){let i=this.pagination(e,t);await this.pruneLogs();let r=await aE(),n={...A.apiType?{apiType:A.apiType}:{},...A.requestSource?{requestSource:A.requestSource}:{},...A.source?{source:A.source}:{}},[a,s]=await Promise.all([r.gitHubApiCallLog.findMany({where:n,take:i.limit,skip:i.offset,orderBy:{createdAt:"desc"}}),r.gitHubApiCallLog.count({where:n})]);return{...i,total:s,items:a.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:RZ(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 aE(),t=Date.now(),A=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-RK.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),i=RK.map(e=>this.metricWindow(e.window,A.filter(A=>A.createdAt.getTime()>=t-e.milliseconds)));return{windows:i,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.apiType===e&&A.createdAt.getTime()>=t-i.milliseconds)))})),operations:[...new Set(A.map(e=>e.operation))].sort().map(e=>({operation:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.operation===e&&A.createdAt.getTime()>=t-i.milliseconds)))})),requestSources:[...new Set(A.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:RK.map(i=>this.metricWindow(i.window,A.filter(A=>A.requestSource===e&&A.createdAt.getTime()>=t-i.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 A=t.length;return{window:e,total:A,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===A?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/A),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=RW(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 A=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${A.length>120?`${A.slice(0,117)}…`:A}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){if(!this.recordCallLogs)return;await this.pruneLogs();let t=await aE();await t.gitHubApiCallLog.create({data:{id:(0,AB.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:RV(RW(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 aE();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let R0=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),R1=process.env.GITHUB_GRAPHQL_URL||`${R0}/graphql`,R4="_adeRateLimit";function R8(e){let t=(0,E.parse)(e),A=t.definitions.filter(e=>e.kind===H.Kind.OPERATION_DEFINITION);if(1!==A.length||!A[0])throw Error("GitHub GraphQL requests must contain one operation");let i=A[0],r=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,ea.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:r,normalizedQuery:n,liveQuery:n};let a={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:H.Kind.FIELD,alias:{kind:H.Kind.NAME,value:R4},name:{kind:H.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:H.Kind.SELECTION_SET,selections:[{kind:H.Kind.FIELD,name:{kind:H.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:r,normalizedQuery:n,liveQuery:(0,ea.print)(a)}}function R2(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[R4],A=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(R4 in e))return{data:e,pointCost:A};let i={...e};return delete i[R4],{data:i,pointCost:A}}let R6="default",R3="default",R5=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,R9=["workflow_run","workflow_job","check_run","check_suite","status"];function R7(e){return"read"===e||"write"===e}function Ue(e){let t=[];for(let A of(e.webhookConfigured||t.push("configure the signed webhook URL"),R7(e.actionsPermission)||t.push("grant Actions read permission"),R7(e.checksPermission)||t.push("grant Checks read permission"),R7(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),R9))e.webhookEvents.includes(A)||t.push(`subscribe to the ${A} event`);return t}function Ut(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class UA extends Error{statusCode;rateLimit;constructor(e,t,A){super(e),this.statusCode=t,this.rateLimit=A,this.name="GitHubRequestError"}}let Ui=`
|
|
11969
11969
|
__typename
|
|
11970
11970
|
... on CheckRun {
|
|
11971
11971
|
id
|