import{logger as e}from"../logger/index.mjs";import{getDBClient as t}from"../utils/mongoDB/connectDB.mjs";import{configurationFilesCandidates as n}from"@intlayer/config/node";import{ObjectId as r}from"mongodb";import{Octokit as i}from"@octokit/rest";const a=(e,t)=>{let n=process.env.GITHUB_CLIENT_ID;if(!n)throw Error(`GitHub Client ID is not configured`);let r=new URLSearchParams({client_id:n,scope:`repo`,state:`github_oauth`,redirect_uri:e});return t&&r.append(`login`,t),`https://github.com/login/oauth/authorize?${r.toString()}`},o=async t=>{let n=process.env.GITHUB_CLIENT_ID,r=process.env.GITHUB_CLIENT_SECRET;if(!n||!r)throw Error(`GitHub OAuth credentials are not configured`);try{let e=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({client_id:n,client_secret:r,code:t})});if(!e.ok)throw Error(`GitHub token exchange failed: ${e.statusText}`);let i=await e.json();if(i.error)throw Error(`GitHub token error: ${i.error_description}`);return i.access_token}catch(t){throw e.error(`Error exchanging GitHub code for token:`,t),t}},s=async t=>{try{let{data:e}=await new i({auth:t}).rest.repos.listForAuthenticatedUser({sort:`updated`,per_page:100,visibility:`all`});return e}catch(t){throw e.error(`Error fetching GitHub repositories:`,t),t}},c=async(t,r,a,o=`main`)=>{try{let{data:e}=await new i({auth:t}).rest.git.getTree({owner:r,repo:a,tree_sha:o,recursive:`true`});return!e.tree||!Array.isArray(e.tree)?[]:e.tree.filter(e=>e.type!==`blob`||!e.path?!1:n.some(t=>e.path?.endsWith(t))).map(e=>e.path)}catch(t){return t.status===404||t.status===409||e.error(`Error checking intlayer configuration:`,t),[]}},l=async(t,n,r,a,o=`main`)=>{try{let{data:e}=await new i({auth:t}).rest.repos.getContent({owner:n,repo:r,path:a,ref:o});if(Array.isArray(e)||!(`content`in e))throw Error(`Path points to a directory, not a file`);return Buffer.from(e.content,`base64`).toString(`utf-8`)}catch(t){if(t.status===404)return null;throw e.error(`Error fetching repository file contents:`,t),t}},u=async n=>{try{let e=t().db(),i=await e.collection(`account`).findOne({userId:n,providerId:`github`});return!i&&r.isValid(n)&&(i=await e.collection(`account`).findOne({userId:new r(n),providerId:`github`})),i||=await e.collection(`accounts`).findOne({userId:n,providerId:`github`}),!i&&r.isValid(n)&&(i=await e.collection(`accounts`).findOne({userId:new r(n),providerId:`github`})),i&&(i.accessToken||i.access_token)||null}catch(t){return e.error(`Error retrieving GitHub token from DB:`,t),null}},d=async({project:t,eventType:n=`intlayer_cms_update`,payload:r={}})=>{let{repository:i,oAuth2Access:a}=t;if(!i||i.provider!==`github`)throw Error(`Project is not connected to a GitHub repository.`);let o=(a?.[0])?.accessToken?.[0];if(!o)throw Error(`No valid OAuth2 access token found for GitHub.`);let{owner:s,repository:c}=i,l=`https://api.github.com/repos/${s}/${c}/dispatches`;try{let i=await fetch(l,{method:`POST`,headers:{Authorization:`Bearer ${o}`,Accept:`application/vnd.github+json`,"Content-Type":`application/json`},body:JSON.stringify({event_type:n,client_payload:{...r,projectId:t.id,timestamp:Date.now()}})});if(!i.ok){let e=await i.text();throw Error(`GitHub API Error: ${i.status} - ${e}`)}return e.info(`Successfully triggered GitHub Action '${n}' for ${s}/${c}`),!0}catch(t){throw e.error(t),t}},f=async(t,n,r,a,o=`main`)=>{try{return await new i({auth:t}).rest.repos.getContent({owner:n,repo:r,path:a,ref:o}),!0}catch(t){if(t.status===404)return!1;throw e.error(`Error checking workflow file existence:`,t),t}},p=async(t,n,r,a,o,s=`main`,c=`Add Intlayer CI workflow`)=>{try{let l=new i({auth:t}),u;try{let{data:e}=await l.rest.repos.getContent({owner:n,repo:r,path:a,ref:s});if(Array.isArray(e)||!(`sha`in e))throw Error(`Path points to a directory, not a file`);u=e.sha}catch(e){if(e.status!==404)throw e}let d=Buffer.from(o,`utf-8`).toString(`base64`);await l.rest.repos.createOrUpdateFileContents({owner:n,repo:r,path:a,message:c,content:d,branch:s,...u&&{sha:u}}),e.info(`Successfully ${u?`updated`:`created`} workflow file ${a} for ${n}/${r}`)}catch(t){throw e.error(`Error creating/updating workflow file:`,t),t}};export{c as checkIntlayerConfig,f as checkWorkflowFileExists,p as createWorkflowFile,o as exchangeCodeForToken,a as getAuthorizationUrl,u as getGitHubTokenFromUser,l as getRepositoryFileContents,s as getUserRepos,d as triggerGithubDispatch};
//# sourceMappingURL=github.service.mjs.map