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";const i=`https://gitlab.com`,a=(e,t,n)=>{let r=process.env.GITLAB_CLIENT_ID,a=t||i;if(!r)throw Error(`GitLab Client ID is not configured`);let o=new URLSearchParams({client_id:r,redirect_uri:e,response_type:`code`,scope:`api read_repository`,state:`gitlab_oauth`});return n&&o.append(`login_hint`,n),`${a}/oauth/authorize?${o.toString()}`},o=async(t,n,r)=>{let a=process.env.GITLAB_CLIENT_ID,o=process.env.GITLAB_CLIENT_SECRET,s=r||i;if(!a||!o)throw Error(`GitLab OAuth credentials are not configured`);try{let e=await fetch(`${s}/oauth/token`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({client_id:a,client_secret:o,code:t,grant_type:`authorization_code`,redirect_uri:n})});if(!e.ok)throw Error(`GitLab token exchange failed: ${e.statusText}`);let r=await e.json();if(r.error)throw Error(`GitLab token error: ${r.error_description}`);return r.access_token}catch(t){throw e.error(`Error exchanging GitLab code for token:`,t),t}},s=async(t,n)=>{let r=n||i;try{let e=await fetch(`${r}/api/v4/projects?membership=true&order_by=last_activity_at&per_page=100`,{headers:{Authorization:`Bearer ${t}`,Accept:`application/json`}});if(!e.ok)throw Error(`Failed to fetch GitLab projects: ${e.statusText}`);return await e.json()}catch(t){throw e.error(`Error fetching GitLab projects:`,t),t}},c=async(t,r,a=`main`,o)=>{let s=o||i;try{let e=await fetch(`${s}/api/v4/projects/${r}/repository/tree?ref=${encodeURIComponent(a)}&recursive=true&per_page=10000`,{headers:{Authorization:`Bearer ${t}`,Accept:`application/json`}});if(!e.ok){if(e.status===404)return[];throw Error(`Failed to fetch repository tree: ${e.statusText}`)}return(await e.json()).filter(e=>e.type===`blob`?n.some(t=>e.path.endsWith(t)):!1).map(e=>e.path)}catch(t){return t.status===404||e.error(`Error checking intlayer configuration on GitLab:`,t),[]}},l=async(t,n,r,a=`main`,o)=>{let s=o||i;try{let e=encodeURIComponent(r),i=await fetch(`${s}/api/v4/projects/${n}/repository/files/${e}/raw?ref=${encodeURIComponent(a)}`,{headers:{Authorization:`Bearer ${t}`,Accept:`application/json`}});if(!i.ok){if(i.status===404)return null;throw Error(`Failed to fetch file contents: ${i.statusText}`)}return await i.text()}catch(t){if(t.status===404)return null;throw e.error(`Error fetching GitLab file contents:`,t),t}},u=async n=>{try{let e=t().db(),i=await e.collection(`account`).findOne({userId:n,providerId:`gitlab`});return!i&&r.isValid(n)&&(i=await e.collection(`account`).findOne({userId:new r(n),providerId:`gitlab`})),i||=await e.collection(`accounts`).findOne({userId:n,providerId:`gitlab`}),!i&&r.isValid(n)&&(i=await e.collection(`accounts`).findOne({userId:new r(n),providerId:`gitlab`})),i&&(i.accessToken||i.access_token)||null}catch(t){return e.error(`Error retrieving GitLab token from DB:`,t),null}},d=async(t,n,r=`.gitlab-ci.yml`,a=`main`,o)=>{let s=o||i;try{let e=encodeURIComponent(r),i=await fetch(`${s}/api/v4/projects/${n}/repository/files/${e}?ref=${encodeURIComponent(a)}`,{headers:{Authorization:`Bearer ${t}`,Accept:`application/json`}});if(i.status===404)return!1;if(!i.ok)throw Error(`Failed to check file existence: ${i.statusText}`);return!0}catch(t){if(t.status===404)return!1;throw e.error(`Error checking pipeline file existence:`,t),t}},f=async(t,n,r=`.gitlab-ci.yml`,a,o=`main`,s,c=`Add Intlayer CI pipeline`)=>{let l=s||i;try{let i=encodeURIComponent(r),s=Buffer.from(a,`utf-8`).toString(`base64`),u;try{let e=await fetch(`${l}/api/v4/projects/${n}/repository/files/${i}?ref=${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${t}`,Accept:`application/json`}});e.ok&&(u=(await e.json()).content_sha256)}catch(e){if(e.status!==404)throw e}let d={branch:o,content:s,commit_message:c,encoding:`base64`};u&&(d.last_commit_id=u);let f=await fetch(`${l}/api/v4/projects/${n}/repository/files/${i}`,{method:`PUT`,headers:{Authorization:`Bearer ${t}`,"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(d)});if(!f.ok){let e=await f.text();throw Error(`Failed to create/update pipeline file: ${e}`)}e.info(`Successfully ${u?`updated`:`created`} pipeline file ${r} for project ${n}`)}catch(t){throw e.error(`Error creating/updating pipeline file:`,t),t}};export{c as checkIntlayerConfig,d as checkPipelineFileExists,f as createPipelineFile,o as exchangeCodeForToken,a as getAuthorizationUrl,u as getGitLabTokenFromUser,l as getRepositoryFileContents,s as getUserProjects};
//# sourceMappingURL=gitlab.service.mjs.map