// @bun
import"./chunk-hggcmr0j.js";class A{userAgent="Buddy-Bot/1.0.0 (https://github.com/stacksjs/buddy)";async fetchPackageInfo(W,x,X){try{let Q=await this.fetchNpmPackageInfo(W),Z=[],B=[],Y;if(Q.repository?.url){let $=this.parseGitHubUrl(Q.repository.url);if($)Z=await this.fetchGitHubReleases($.owner,$.repo,x,X),Y=this.generateCompareUrl($.owner,$.repo,x,X),B=await this.fetchChangelog($.owner,$.repo)}return{packageInfo:Q,releaseNotes:Z,changelog:B,compareUrl:Y}}catch(Q){return console.warn(`Failed to fetch package info for ${W}:`,Q),{packageInfo:{name:W},releaseNotes:[],changelog:[]}}}async fetchNpmPackageInfo(W){try{let x=await fetch(`https://registry.npmjs.org/${encodeURIComponent(W)}`,{headers:{"User-Agent":this.userAgent}});if(!x.ok)throw new Error(`NPM registry responded with ${x.status}`);let X=await x.json(),Q=X["dist-tags"]?.latest,Z;try{let B=await fetch(`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(W)}`,{headers:{"User-Agent":this.userAgent}});if(B.ok)Z=(await B.json()).downloads}catch{}return{name:W,description:X.description,homepage:X.homepage,repository:X.repository,license:X.license,author:X.author,keywords:X.keywords,weeklyDownloads:Z,lastPublish:X.time?.[Q],maintainers:X.maintainers}}catch(x){return console.warn(`Failed to fetch npm info for ${W}:`,x),{name:W}}}parseGitHubUrl(W){try{let x=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),X=new URL(x);if(X.hostname!=="github.com")return null;let Q=X.pathname.split("/").filter(Boolean);if(Q.length>=2)return{owner:Q[0],repo:Q[1]};return null}catch{return null}}async fetchGitHubReleases(W,x,X,Q){try{let Z=await fetch(`https://api.github.com/repos/${W}/${x}/releases?per_page=50`,{headers:{"User-Agent":this.userAgent}});if(!Z.ok)return[];return(await Z.json()).filter((Y)=>{let $=Y.tag_name.replace(/^v/,"");return this.isVersionBetween($,X,Q)}).map((Y)=>({version:Y.tag_name,date:Y.published_at,title:Y.name||Y.tag_name,body:Y.body||"",htmlUrl:Y.html_url,compareUrl:this.generateCompareUrl(W,x,X,Y.tag_name),author:Y.author?.login,isPrerelease:Y.prerelease,assets:Y.assets?.map(($)=>({name:$.name,downloadUrl:$.browser_download_url,size:$.size,contentType:$.content_type}))||[]}))}catch(Z){return console.warn(`Failed to fetch GitHub releases for ${W}/${x}:`,Z),[]}}async fetchChangelog(W,x){let X=["CHANGELOG.md","CHANGELOG.rst","HISTORY.md","RELEASES.md"];for(let Q of X)try{let Z=await fetch(`https://api.github.com/repos/${W}/${x}/contents/${Q}`,{headers:{"User-Agent":this.userAgent}});if(Z.ok){let B=await Z.json();if(B.content){let Y=atob(B.content);return this.parseChangelog(Y)}}}catch{}return[]}parseChangelog(W){let x=[],X=W.split(`
`),Q=null,Z=null;for(let B of X){let Y=B.match(/^##\s*\[?([^\]]+)\]?\s*-?\s*(.*)/);if(Y){if(Q)x.push(Q);Q={version:Y[1],date:Y[2].trim(),changes:{}},Z=null;continue}let $=B.match(/^###\s*(.+)/);if($&&Q){Z=$[1].toLowerCase();continue}let G=B.match(/^[-*]\s*(.+)/);if(G&&Q&&Z){if(!Q.changes)Q.changes={};let T=Z;if(!Q.changes[T])Q.changes[T]=[];Q.changes[T].push(G[1])}}if(Q)x.push(Q);return x.slice(0,10)}generateCompareUrl(W,x,X,Q){let Z=X.startsWith("v")?X:`v${X}`,B=Q.startsWith("v")?Q:`v${Q}`;return`https://github.com/${W}/${x}/compare/${Z}...${B}`}isVersionBetween(W,x,X){let Q=W.replace(/^v/,""),Z=x.replace(/^v/,""),B=X.replace(/^v/,"");return Q===B||Q>Z}generatePackageBadges(W,x,X){let Q=encodeURIComponent(W.name),Z=this.normalizeVersionForBadges(x),B=this.normalizeVersionForBadges(X),Y=encodeURIComponent(Z),$=encodeURIComponent(B);return{age:`[![age](https://developer.mend.io/api/mc/badges/age/npm/${Q}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,adoption:`[![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/${Q}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,passing:`[![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/${Q}/${Y}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,confidence:`[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/${Q}/${Y}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`}}async fetchComposerPackageInfo(W){try{let x=await fetch(`https://packagist.org/packages/${encodeURIComponent(W)}.json`,{headers:{"User-Agent":this.userAgent}});if(!x.ok)throw new Error(`Packagist responded with ${x.status}`);let Q=(await x.json()).package;if(!Q)return{name:W};let Z=Object.keys(Q.versions||{}),B=Z.find(($)=>!$.includes("dev")&&!$.includes("alpha")&&!$.includes("beta"))||Z[0],Y=Q.versions[B]||{};return{name:Q.name,description:Y.description,homepage:Y.homepage,repository:Y.source?{type:"git",url:Y.source.url}:void 0,license:Y.license?.[0]||Y.license,author:Y.authors?.[0],keywords:Y.keywords,lastPublish:Y.time}}catch(x){return console.warn(`Failed to fetch Packagist info for ${W}:`,x),{name:W}}}generateComposerBadges(W,x,X){let Q=encodeURIComponent(W.name),Z=this.normalizeVersionForBadges(x),B=this.normalizeVersionForBadges(X),Y=encodeURIComponent(Z),$=encodeURIComponent(B);return{age:`[![age](https://developer.mend.io/api/mc/badges/age/packagist/${Q}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,adoption:`[![adoption](https://developer.mend.io/api/mc/badges/adoption/packagist/${Q}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,passing:`[![passing](https://developer.mend.io/api/mc/badges/compatibility/packagist/${Q}/${Y}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`,confidence:`[![confidence](https://developer.mend.io/api/mc/badges/confidence/packagist/${Q}/${Y}/${$}?slim=true)](https://docs.renovatebot.com/merge-confidence/)`}}normalizeVersionForBadges(W){let x=W.replace(/^v/,"");if(x.split(".").length===2)x=`${x}.0`;return x}}class q{releaseNotesFetcher=new A;async generatePullRequests(W){let x=[];for(let X of W){let Q=this.generateTitle(X),Z=await this.generateBody(X),B={number:0,title:Q,body:Z,head:`buddy/update-${X.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"buddy-bot",reviewers:[],assignees:[],labels:["dependencies","automated"],draft:!1};x.push(B)}return x}generateTitle(W){if(W.updates.length===1){let Q=W.updates[0];return`chore(deps): update dependency ${Q.name} to v${Q.newVersion}`}let x=W.updates.filter((Q)=>Q.updateType==="major").length,X=W.updates.filter((Q)=>Q.updateType==="minor").length;if(x>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(X>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){let x=`This PR contains the following updates:

`,X=W.updates.filter((H)=>H.file==="package.json"),Q=W.updates.filter((H)=>H.file.endsWith("composer.json")||H.file.endsWith("composer.lock")),Z=W.updates.filter((H)=>H.file.includes(".yaml")||H.file.includes(".yml")).filter((H)=>!H.file.includes(".github/workflows/")),B=W.updates.filter((H)=>H.file.includes(".github/workflows/")),Y=B.reduce((H,_)=>{if(!H.find((L)=>L.name===_.name&&L.currentVersion===_.currentVersion&&L.newVersion===_.newVersion)){let L=[...new Set(B.filter((K)=>K.name===_.name&&K.currentVersion===_.currentVersion&&K.newVersion===_.newVersion).map((K)=>K.file))];H.push({..._,file:L.join(", ")})}return H},[]),$=Q.reduce((H,_)=>{if(!H.find((L)=>L.name===_.name&&L.currentVersion===_.currentVersion&&L.newVersion===_.newVersion))H.push(_);return H},[]),G=new Map,T=new Map;if(X.length>0){x+=`### npm Dependencies

`,x+=`| Package | Change | Age | Adoption | Passing | Confidence |
`,x+=`|---|---|---|---|---|---|
`;for(let H of X)try{let _=H.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),j=await this.releaseNotesFetcher.fetchPackageInfo(_,H.currentVersion,H.newVersion);G.set(H.name,j)}catch(_){console.warn(`Failed to fetch info for ${H.name}:`,_)}for(let H of X){let j=G.get(H.name)?.packageInfo||{name:H.name},L=H.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),K;if(j.repository?.url){let J=this.getRepositorySourceUrl(j.repository.url,L),M=this.getRepositorySourceUrl(j.repository.url,L,"HEAD");K=`[${L}](${J}) ([source](${M}))`}else if(L.startsWith("@types/")){let J=L.replace("@types/",""),M=`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${J}`,F=`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/${J}`;K=`[${L}](${M}) ([source](${F}))`}else K=`[${L}](https://www.npmjs.com/package/${encodeURIComponent(L)})`;let S=`https://renovatebot.com/diffs/npm/${encodeURIComponent(L)}/${H.currentVersion}/${H.newVersion}`,R=`[\`${H.currentVersion}\` -> \`${H.newVersion}\`](${S})`,O=this.releaseNotesFetcher.generatePackageBadges({...j,name:L},H.currentVersion,H.newVersion);x+=`| ${K} | ${R} | ${O.age} | ${O.adoption} | ${O.passing} | ${O.confidence} |
`}x+=`
`}if($.length>0){for(let H of $)try{let _=await this.releaseNotesFetcher.fetchComposerPackageInfo(H.name);T.set(H.name,_)}catch(_){console.warn(`Failed to fetch Composer info for ${H.name}:`,_)}x+=`### PHP/Composer Dependencies

`,x+=`| Package | Change | Age | Adoption | Passing | Confidence | Type | Update |
`,x+=`|---|---|---|---|---|---|---|---|
`;for(let H of $){let _=T.get(H.name)||{name:H.name},j;if(_.homepage&&_.repository?.url){let M=this.getComposerRedirectSourceUrl(_.repository.url,H.name);j=`[${H.name}](${_.homepage}) ([source](${M}))`}else if(_.repository?.url){let M=this.getComposerRedirectSourceUrl(_.repository.url,H.name);j=`[${H.name}](${M})`}else j=`[${H.name}](https://packagist.org/packages/${encodeURIComponent(H.name)})`;let L=this.getConstraintStyleChange(H.currentVersion,H.newVersion),K=`https://renovatebot.com/diffs/packagist/${encodeURIComponent(H.name)}/${H.currentVersion}/${H.newVersion}`,S=`[\`${L}\`](${K})`,R=this.releaseNotesFetcher.generateComposerBadges(_,H.currentVersion,H.newVersion),O=H.dependencyType||"require",J=H.updateType||"minor";x+=`| ${j} | ${S} | ${R.age} | ${R.adoption} | ${R.passing} | ${R.confidence} | ${O} | ${J} |
`}x+=`
`}if(Z.length>0){x+=`### Launchpad/pkgx Dependencies

`,x+=`| Package | Change | File | Status |
`,x+=`|---|---|---|---|
`;for(let H of Z){let _=H.name==="bun.sh"?"bun.com":H.name,j=H.name==="bun.sh"?"https://bun.sh":`https://pkgx.com/pkg/${encodeURIComponent(H.name)}`,L=`[${_}](${j})`,K=`\`${H.currentVersion}\` -> \`${H.newVersion}\``,S=H.file.split("/").pop()||H.file,R="\u2705 Available";x+=`| ${L} | ${K} | ${S} | ${"\u2705 Available"} |
`}x+=`
`}if(Y.length>0){x+=`### GitHub Actions

`,x+=`| Action | Change | File | Status |
`,x+=`|---|---|---|---|
`;for(let H of Y){let _=`https://github.com/${H.name}`,j=`[${H.name}](${_})`,L=`\`${H.currentVersion}\` -> \`${H.newVersion}\``,K=H.file.includes(", ")?H.file.split(", ").map((R)=>{return`[${R.split("/").pop()||R}](../${R})`}).join(", "):(()=>{return`[${H.file.split("/").pop()||H.file}](../${H.file})`})(),S="\u2705 Available";x+=`| ${j} | ${L} | ${K} | ${"\u2705 Available"} |
`}x+=`
`}x+=`
---

`,x+=`### Release Notes

`;for(let H of X){let _=G.get(H.name),j=_?.packageInfo||{name:H.name},L=_?.releaseNotes||[],K=_?.compareUrl;x+=`<details>
`;let S,R=H.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,"");if(j.repository?.url)S=`${this.getRepositoryName(j.repository.url)} (${R})`;else S=R;if(x+=`<summary>${S}</summary>

`,L.length>0)for(let O of L.slice(0,3)){if(x+=`### [\`${O.version}\`](${O.htmlUrl})

`,K)x+=`[Compare Source](${K})

`;if(O.body){let J=this.cleanReleaseBody(O.body);x+=`${J}

`}if(O.author)x+=`*Released by [@${O.author}](https://github.com/${O.author}) on ${new Date(O.date).toLocaleDateString()}*

`}else{if(x+=`**${H.currentVersion} -> ${H.newVersion}**

`,K)x+=`[Compare Source](${K})

`;if(j.description)x+=`${j.description}

`;if(H.releaseNotesUrl)x+=`[Release Notes](${H.releaseNotesUrl})

`;if(H.changelogUrl)x+=`[Changelog](${H.changelogUrl})

`}x+=`</details>

`}let z=Z.filter((H)=>!X.some((_)=>_.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,"")===H.name));for(let H of z){let _=H.name==="bun.sh"?"bun.com":H.name;if(x+=`<details>
`,x+=`<summary>${_}</summary>

`,x+=`**${H.currentVersion} -> ${H.newVersion}**

`,H.name==="bun.sh")x+=`Visit [bun.sh](https://bun.sh) for more information about Bun releases.

`;else x+=`Visit [pkgx.com](https://pkgx.com/pkg/${encodeURIComponent(H.name)}) for more information.

`;x+=`</details>

`}for(let H of $)x+=`<details>
`,x+=`<summary>${H.name}</summary>

`,x+=`**${H.currentVersion} -> ${H.newVersion}**

`,x+=`Visit [${H.name}](https://packagist.org/packages/${encodeURIComponent(H.name)}) on Packagist for more information.

`,x+=`</details>

`;for(let H of Y)x+=`<details>
`,x+=`<summary>${H.name}</summary>

`,x+=`**${H.currentVersion} -> ${H.newVersion}**

`,x+=`Visit [${H.name}](https://github.com/${H.name}/releases) for release notes.

`,x+=`</details>

`;if(x+=`---

`,G.size>0||$.length>0||z.length>0||Y.length>0){x+=`### \uD83D\uDCCA Package Statistics

`;for(let H of X){let j=G.get(H.name)?.packageInfo;if(j?.weeklyDownloads)x+=`- **${H.name}**: ${j.weeklyDownloads.toLocaleString()} weekly downloads
`}for(let H of $)x+=`- **${H.name}**: PHP package available on Packagist
`;for(let H of z){let _=H.name==="bun.sh"?"bun.com":H.name;if(H.name==="bun.sh")x+=`- **${_}**: Popular JavaScript runtime and package manager
`;else x+=`- **${_}**: Available via pkgx package manager
`}for(let H of Y)x+=`- **${H.name}**: GitHub Action for workflow automation
`;x+=`
---

`}return x+=`### Configuration

`,x+=`\uD83D\uDCC5 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

`,x+=`\uD83D\uDEA6 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

`,x+=`\u267B **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

`,x+=`\uD83D\uDD15 **Ignore**: Close this PR and you won't be reminded about these updates again.

`,x+=`---

`,x+=` - [ ] <!-- rebase-check -->If you want to update/retry this PR, check this box

`,x+=`---

`,x+="This PR was generated by [Buddy](https://github.com/stacksjs/buddy-bot) \uD83E\uDD16",x}getRepositoryName(W){try{let x=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),Q=new URL(x).pathname.split("/").filter(Boolean);if(Q.length>=2)return`${Q[0]}/${Q[1]}`;return W}catch{return W}}getRepositorySourceUrl(W,x,X="master"){try{let Q=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),Z=new URL(Q);if(x.startsWith("@types/")&&Z.pathname.includes("DefinitelyTyped")){let B=x.replace("@types/","");return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/${X}/types/${B}`}if(Z.hostname==="github.com")return`${Q}/tree/${X}`;return Q}catch{return W}}getComposerSourceUrl(W,x){try{let X=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),Q=new URL(X);if(x.startsWith("@types/")&&Q.pathname.includes("DefinitelyTyped"))return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${x.replace("@types/","")}`;if(Q.hostname==="github.com")return`${X}/tree/master`;return X}catch{return W}}getConstraintStyleChange(W,x){let X=W.replace(/^v/,""),Q=x.replace(/^v/,""),Z=`^${X}`,B=`^${Q}`;return`${Z} -> ${B}`}getComposerRedirectSourceUrl(W,x){try{let X=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),Q=new URL(X);if(x.startsWith("@types/")&&Q.pathname.includes("DefinitelyTyped"))return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${x.replace("@types/","")}`;if(Q.hostname==="github.com"){let Z=Q.pathname.split("/").filter((B)=>B);if(Z.length>=2){let B=Z[0],Y=Z[1];return`https://redirect.github.com/${B}/${Y}`}}return X}catch{return W}}cleanReleaseBody(W){let x=W.replace(/\r\n/g,`
`).replace(/\n{3,}/g,`

`).trim();if(x.length>1000)x=`${x.substring(0,1000)}...

*[View full release notes]*`;return x}generateCustomTemplate(W,x,X={}){let Q=x,B={...{"{title}":this.generateTitle(W),"{package_count}":W.updates.length.toString(),"{update_type}":W.updateType,"{packages}":W.updates.map((Y)=>Y.name).join(", "),"{date}":new Date().toISOString().split("T")[0]},...X};for(let[Y,$]of Object.entries(B))Q=Q.replace(new RegExp(Y,"g"),$);return Q}}export{q as PullRequestGenerator};
export{A as g,q as h};
