UNPKG

@altostra/core

Version:

Core library for shared types and logic

1 lines • 16.7 kB
"use strict";var _GitlabGitHost_instances,_GitlabGitHost_axios,_GitlabGitHost_getIntegration,_GitlabGitHost_updateToken,_GitlabGitHost_integration,_GitlabGitHost_maxRetires,_GitlabGitHost_clientId,_GitlabGitHost_clientSecret,_GitlabGitHost_actionWrapper,_GitlabGitHost_getProjectPath,_GitlabGitHost_getApiEP,__awaiter=this&&this.__awaiter||function(t,e,i,a){return new(i||(i=Promise))((function(s,r){function o(t){try{_(a.next(t))}catch(t){r(t)}}function l(t){try{_(a.throw(t))}catch(t){r(t)}}function _(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,l)}_((a=a.apply(t,e||[])).next())}))},__classPrivateFieldSet=this&&this.__classPrivateFieldSet||function(t,e,i,a,s){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?s.call(t,i):s?s.value=i:e.set(t,i),i},__classPrivateFieldGet=this&&this.__classPrivateFieldGet||function(t,e,i,a){if("a"===i&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?a:"a"===i?a.call(t):a?a.value:e.get(t)},__importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GitlabGitHost=exports.GITLAB_REQUIRE_AUTHORIZATION_CODE=void 0;const path_1=require("path"),querystring_1=__importDefault(require("querystring")),Numerics_1=require("../../common/CustomTypes/Numerics"),Errors_1=require("../../common/Errors"),Axios_1=require("../../common/Utils/Axios"),Pagination_1=require("../../common/Utils/Pagination"),Url_1=require("../../common/Utils/Url"),concat_1=require("@reactivex/ix-es2015-cjs/iterable/concat"),filter_1=require("@reactivex/ix-es2015-cjs/iterable/operators/filter"),map_1=require("@reactivex/ix-es2015-cjs/iterable/operators/map"),axios_1=__importDefault(require("axios")),axios_retry_1=__importDefault(require("axios-retry")),Common_1=require("../Common"),GitLab_1=require("../git-utils/GitLab"),common_1=require("../git-utils/GitLab/common"),Types_1=require("./Types");exports.GITLAB_REQUIRE_AUTHORIZATION_CODE="gitlab.require-authorization";class GitlabGitHost extends GitLab_1.GitLabGitUtils{constructor(t,e,i,{axios:a,maxRetries:s=(0,Numerics_1.naturalNumber)(3),clientId:r,clientSecret:o}){super({groupName:t.groupName}),_GitlabGitHost_instances.add(this),_GitlabGitHost_axios.set(this,void 0),_GitlabGitHost_getIntegration.set(this,void 0),_GitlabGitHost_updateToken.set(this,void 0),_GitlabGitHost_integration.set(this,void 0),_GitlabGitHost_maxRetires.set(this,void 0),_GitlabGitHost_clientId.set(this,void 0),_GitlabGitHost_clientSecret.set(this,void 0),__classPrivateFieldSet(this,_GitlabGitHost_axios,null!=a?a:axios_1.default.create(),"f"),__classPrivateFieldGet(this,_GitlabGitHost_axios,"f").defaults.baseURL=common_1.GITLAB_BASE_URL,a||(0,axios_retry_1.default)(__classPrivateFieldGet(this,_GitlabGitHost_axios,"f"),{retries:s,retryDelay:axios_retry_1.default.exponentialDelay,retryCondition:t=>{const e=Number(t.code);return e>=400&&401!==e}}),__classPrivateFieldSet(this,_GitlabGitHost_maxRetires,s,"f"),__classPrivateFieldSet(this,_GitlabGitHost_getIntegration,e,"f"),__classPrivateFieldSet(this,_GitlabGitHost_updateToken,i,"f"),__classPrivateFieldSet(this,_GitlabGitHost_integration,t,"f"),__classPrivateFieldSet(this,_GitlabGitHost_clientId,r,"f"),__classPrivateFieldSet(this,_GitlabGitHost_clientSecret,o,"f")}get headers(){return{Authorization:"Bearer "+__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").token.accessToken}}getHeadSha(t,e){return __awaiter(this,void 0,void 0,(function*(){return null!=e||(e=yield this.getDefaultBranch(t)),yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"getHeadSha",()=>__awaiter(this,void 0,void 0,(function*(){const i=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,Url_1.asUrl`/repository/branches/${e}`)),{data:a}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(i,{headers:this.headers});return(0,Types_1.validateBranch)(a),a.commit.id})))}))}createRepository({name:t,privateRepo:e}){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"createRepository",()=>__awaiter(this,void 0,void 0,(function*(){const i=Object.assign({name:t,visibility:e?"private":"public",initialize_with_readme:!0},"group"===__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").type&&{namespace_id:__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").groupId}),{data:a}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,"projects"),i,{headers:this.headers});return(0,Types_1.validateRepoResponse)(a),{repoUrl:a.web_url}})))}))}commitFiles({commitMessage:t,filesToCommit:e,targetRepositoryName:i,targetBranch:a}){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"commitFiles",()=>__awaiter(this,void 0,void 0,(function*(){const s=this,r=null!=a?a:yield this.getDefaultBranch(i),o={},l=Object.keys(e).map(t=>function(t){return __awaiter(this,void 0,void 0,(function*(){try{const e=__classPrivateFieldGet(s,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(s,i,Url_1.asUrl`/repository/files/${t}?ref=${r}`);yield __classPrivateFieldGet(s,_GitlabGitHost_axios,"f").get(__classPrivateFieldGet(s,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(s,e),{headers:s.headers,maxContentLength:1/0,maxBodyLength:1/0}),o[t]="update"}catch(e){o[t]="create"}}))}(t));yield Promise.all(l);const _=Object.entries(e).map(([t,e])=>{var i;return{action:null!==(i=o[t])&&void 0!==i?i:"create",file_path:t,content:e.toString("base64"),encoding:"base64"}}),n={branch:r,commit_message:t,actions:_},c=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,i,"/repository/commits"),{data:G}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,c),n,{headers:this.headers,maxContentLength:1/0,maxBodyLength:1/0});return(0,Types_1.validateCommit)(G),G.id})))}))}listRepositories(t){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"listRepositories",()=>__awaiter(this,void 0,void 0,(function*(){const e=t?"?search="+t:"",{data:i}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,"projects",!0)+e,{headers:this.headers});return(0,Types_1.validateGetRepoResponse)(i),i.map(t=>t.path)})))}))}downloadFile(t,e){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"downloadFile",()=>__awaiter(this,void 0,void 0,(function*(){const i=yield this.getDefaultBranch(t),a=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,Url_1.asUrl`/repository/files/${e}?ref=${i}`),{data:s}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,a),{headers:this.headers});return(0,Types_1.validateFileResponse)(s),Buffer.from(s.content,"base64")})))}))}downloadRepo(t){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"downloadRepo",()=>__awaiter(this,void 0,void 0,(function*(){const e=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,"/repository/archive.zip"),{data:i}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,e),{headers:this.headers});return i})))}))}createBranch(t,e){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"createBranch",()=>__awaiter(this,void 0,void 0,(function*(){var i,a;const s=yield this.getDefaultBranch(t),r={branch:e,ref:s},o=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,"/repository/branches");try{yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,o),r,{headers:this.headers})}catch(t){if((0,Axios_1.isAxiosError)(t)&&"Branch already exists"===(null===(a=null===(i=t.response)||void 0===i?void 0:i.data)||void 0===a?void 0:a.message))return;throw t}})))}))}createPullRequest({repository:t,sourceBranch:e,title:i,content:a,targetBranch:s}){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"createPullRequest",()=>__awaiter(this,void 0,void 0,(function*(){var r,o;const l=Object.assign(Object.assign({title:i,source_branch:e},a&&{description:a}),{target_branch:null!=s?s:yield this.getDefaultBranch(t)}),_=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,"/merge_requests");try{const{data:t}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,_),l,{headers:this.headers});return(0,Types_1.validateMergeRequestResponse)(t),t.web_url}catch(t){if((0,Axios_1.isAxiosError)(t)&&Array.isArray(null===(o=null===(r=t.response)||void 0===r?void 0:r.data)||void 0===o?void 0:o.message)&&t.response.data.message.some(t=>"string"==typeof t&&t.startsWith("Another open merge request already exists for this source branch")))throw Errors_1.AltoError.wrapError(Errors_1.UserFacingError.wrapError(t,{category:"user-fault",message:t.response.data.message.join("\n")}),{data:{noRetry:!0},forceWrap:!0});throw t}})))}))}getDefaultBranch(t){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"getDefaultBranch",()=>__awaiter(this,void 0,void 0,(function*(){const e=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t),{data:i}=yield __classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,e),{headers:this.headers});if((0,Types_1.validateRepoResponse)(i),null===i.default_branch)throw Errors_1.AltoError.create("Repository doesn't has default branch",{data:{repository:i}});return i.default_branch})))}))}static tryRefreshToken(t,e,i,a){var s,r,o;return __awaiter(this,void 0,void 0,(function*(){const l={grant_type:"refresh_token",refresh_token:t.token.refreshToken,client_id:e,client_secret:i};let _;try{_=yield a.post("/oauth/token",querystring_1.default.stringify(l),{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}catch(t){if((0,Axios_1.isAxiosError)(t)&&400===(null===(s=t.response)||void 0===s?void 0:s.status))return;throw Errors_1.UserFacingError.wrapError(t,{category:"server-fault",type:"gitlab-server-error",message:"It appears that GitLab is unavailable.\nThis might be a temporary error, please try again or contact support.",data:{status:null===(r=t.response)||void 0===r?void 0:r.status,message:null===(o=t.response)||void 0===o?void 0:o.statusText}})}(0,Types_1.validateCreateAccessTokenResponse)(_.data);const{access_token:n,refresh_token:c}=_.data;return{accessToken:n,refreshToken:c}}))}static runWithRetries({operationName:t,getIntegrationFn:e,fn:i,tryRefreshTokenFn:a,updateTokenFn:s,retriesCount:r=(0,Numerics_1.naturalNumber)(3),retryAttemptCount:o=0,lastError:l}){var _,n,c,G;return __awaiter(this,void 0,void 0,(function*(){if(o>=r)throw Errors_1.UserFacingError.wrapError(Errors_1.AltoError.wrapError(l,{message:"Retries exhausted for gitlab "+t,code:exports.GITLAB_REQUIRE_AUTHORIZATION_CODE,data:{retires:r,action:t}}),{message:"Retries exhausted for gitlab "+t,category:"server-fault",type:exports.GITLAB_REQUIRE_AUTHORIZATION_CODE});const d=yield e();try{return yield i(d)}catch(l){if((0,Axios_1.isAxiosError)(l)&&401===(null===(_=l.response)||void 0===_?void 0:_.status)){const _=yield a();return _&&(yield s(_)),yield GitlabGitHost.runWithRetries({operationName:t,getIntegrationFn:e,fn:i,tryRefreshTokenFn:a,updateTokenFn:s,retriesCount:r,retryAttemptCount:o+1,lastError:l})}throw l instanceof Errors_1.AltoError&&(null===(n=l.data)||void 0===n?void 0:n.noRetry)?l:Errors_1.UserFacingError.wrapError(l,{category:"server-fault",type:"gitlab-server-error",message:"It appears that GitLab is unavailable.\nThis might be a temporary error, please try again or contact support.",data:{status:null===(c=l.response)||void 0===c?void 0:c.status,message:null===(G=l.response)||void 0===G?void 0:G.statusText,action:t}})}}))}listFiles(t,{path:e,extFilter:i}={}){return __classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_actionWrapper).call(this,"listFiles",()=>__awaiter(this,void 0,void 0,(function*(){const a=__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getApiEP).call(this,__classPrivateFieldGet(this,_GitlabGitHost_instances,"m",_GitlabGitHost_getProjectPath).call(this,t,"/repository/tree"))+"?path="+(e||"/");let s=(yield(0,Pagination_1.getAllPages)({getPage:t=>__classPrivateFieldGet(this,_GitlabGitHost_axios,"f").get(a+"&page="+(t||1),{headers:this.headers}),getCursor:t=>t.headers["x-next-page"],hasNext:t=>!!t,appendPage:(t,e)=>{const{data:i}=e;return(0,Types_1.validateContentResponse)(i),(0,concat_1.concat)(null!=t?t:[],i)}})).pipe((0,filter_1.filter)(t=>"blob"===t.type),(0,map_1.map)(t=>t.name));if((i=(0,Common_1.normalizeExtFilter)(i)).length>0){const t=new Set(i);s=s.pipe((0,filter_1.filter)(e=>t.has((0,path_1.extname)(e).toLowerCase())))}return[...s]})))}getGitUtilsInitialization(){return{type:"gitlab",groupName:__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").groupName}}validateAuthentication(){return __awaiter(this,void 0,void 0,(function*(){}))}}exports.GitlabGitHost=GitlabGitHost,_GitlabGitHost_axios=new WeakMap,_GitlabGitHost_getIntegration=new WeakMap,_GitlabGitHost_updateToken=new WeakMap,_GitlabGitHost_integration=new WeakMap,_GitlabGitHost_maxRetires=new WeakMap,_GitlabGitHost_clientId=new WeakMap,_GitlabGitHost_clientSecret=new WeakMap,_GitlabGitHost_instances=new WeakSet,_GitlabGitHost_actionWrapper=function(t,e){var i,a;return __awaiter(this,void 0,void 0,(function*(){const s=t=>(__classPrivateFieldSet(this,_GitlabGitHost_integration,t,"f"),e()),r=()=>__awaiter(this,void 0,void 0,(function*(){return yield GitlabGitHost.tryRefreshToken(__classPrivateFieldGet(this,_GitlabGitHost_integration,"f"),__classPrivateFieldGet(this,_GitlabGitHost_clientId,"f"),__classPrivateFieldGet(this,_GitlabGitHost_clientSecret,"f"),__classPrivateFieldGet(this,_GitlabGitHost_axios,"f"))}));try{return yield GitlabGitHost.runWithRetries({operationName:t,getIntegrationFn:__classPrivateFieldGet(this,_GitlabGitHost_getIntegration,"f"),fn:s,tryRefreshTokenFn:r,updateTokenFn:__classPrivateFieldGet(this,_GitlabGitHost_updateToken,"f"),retriesCount:__classPrivateFieldGet(this,_GitlabGitHost_maxRetires,"f")})}catch(t){throw t instanceof Errors_1.AltoError&&(null===(i=t.data)||void 0===i?void 0:i.noRetry)&&null!==(a=t.inner)&&void 0!==a?a:t}}))},_GitlabGitHost_getProjectPath=function(t,e=""){const i=__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").groupName+"/"+t;return Url_1.asUrl`projects/${i}`+e},_GitlabGitHost_getApiEP=function(t,e=!1){let i=t;if(e){i=`${"group"===__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").type?"groups":"users"}/${__classPrivateFieldGet(this,_GitlabGitHost_integration,"f").groupId}/${t}`}return"/api/v4/"+i};