UNPKG

@altostra/core

Version:

Core library for shared types and logic

1 lines • 40.8 kB
"use strict";var _GitHubGitHost_instances,_a,_GitHubGitHost_headers,_GitHubGitHost_githubApis,_GitHubGitHost_axios,_GitHubGitHost_auth,_GitHubGitHost_refreshTokenFn,_GitHubGitHost_maxRetries,_GitHubGitHost_accessTokenLastUpdate,_GitHubGitHost_logger,_GitHubGitHost_retryConditionOverride,_GitHubGitHost_installation,_GitHubGitHost_loggingTokenMetadata,_GitHubGitHost_getGitTree,_GitHubGitHost_getGithubAccountName,_GitHubGitHost_getRepoUrl,_GitHubGitHost_createInitialBranch,_GitHubGitHost_setAuthorizationHeader,_GitHubGitHost_hasValidToken,_GitHubGitHost_createJwtToken,_GitHubGitHost_createOrganizationAccessToken,_GitHubGitHost_getHeadCommitRefSHA,_GitHubGitHost_createBlobFiles,_GitHubGitHost_isRepoNameValid,_GitHubGitHost_createNewTree,_GitHubGitHost_createNewCommit,_GitHubGitHost_updateHeadBySHA,_GitHubGitHost_createAccessTokenUsingInstallationId,_GitHubGitHost_createRepoToUser,_GitHubGitHost_createRepoToOrganization,_GitHubGitHost_withRetryConditionOverride,__awaiter=this&&this.__awaiter||function(t,i,e,s){return new(e||(e=Promise))((function(a,r){function o(t){try{n(s.next(t))}catch(t){r(t)}}function _(t){try{n(s.throw(t))}catch(t){r(t)}}function n(t){var i;t.done?a(t.value):(i=t.value,i instanceof e?i:new e((function(t){t(i)}))).then(o,_)}n((s=s.apply(t,i||[])).next())}))},__classPrivateFieldSet=this&&this.__classPrivateFieldSet||function(t,i,e,s,a){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof i?t!==i||!a:!i.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?a.call(t,e):a?a.value=e:i.set(t,e),e},__classPrivateFieldGet=this&&this.__classPrivateFieldGet||function(t,i,e,s){if("a"===e&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof i?t!==i||!s:!i.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===e?s:"a"===e?s.call(t):s?s.value:i.get(t)},__importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GitHubGitHost=exports.MAX_RETRY_TIMES=void 0;const https_1=require("https"),path_1=require("path"),Types_1=require("../../bizops/GitHubAppInstallation/Types"),NonEmptyString_1=require("../../common/CustomTypes/NonEmptyString"),Numerics_1=require("../../common/CustomTypes/Numerics"),Errors_1=require("../../common/Errors"),AltoError_1=require("../../common/Errors/AltoError"),Logging_1=require("../../common/Logging"),Axios_1=require("../../common/Utils/Axios"),Object_1=require("../../common/Utils/Object"),Url_1=require("../../common/Utils/Url"),JwtGenerator_1=require("../../jwt/JwtGenerator"),type_validations_1=require("@altostra/type-validations"),from_1=require("@reactivex/ix-es2015-cjs/iterable/from"),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"),GitHub_1=require("../git-utils/GitHub"),RetryConditionOverride_1=require("./RetryConditionOverride"),Types_2=require("./Types"),GITHUB_API_URL="https://api.github.com";exports.MAX_RETRY_TIMES=3;const EMPTY_GIT_REPO_RESPONSE_CODE=409,UNPROCESSED_ENTITY_RESPONSE_CODE=422,FORBIDDEN_RESPONSE_CODE=403,BRANCH_IS_PROTECTED_DOCS_URL="https://docs.github.com/articles/about-protected-branches",USA_TRADE_CONTROLS_POLICY_DOCS_URL_RX=/^https:\/\/docs\.github\.com\/[^/]+\/github\/site-policy\/github-and-trade-controls(?:[?#].*)?$/,IP_NOT_IN_ALLOW_LIST_ERROR_MESSAGE_RX=/^Although you appear to have the correct authorization credentials, the `[^`]+` organization has an IP allow list enabled, and [0-9.]{7,15} is not permitted to access this resource.$/,createRepoResponseAssertion=(0,type_validations_1.assertBy)((0,type_validations_1.objectOf)({html_url:NonEmptyString_1.isNonEmptyString}),(t,i)=>AltoError_1.AltoError.create("Unexpected response from GitHub API when creating a repository.",{data:{data:t,rejections:i}}));class GitHubGitHost extends GitHub_1.GitHubGitUtils{constructor(t,{logger:i=(0,Logging_1.nullLogger)(),maxRetries:e=(0,Numerics_1.naturalNumber)(3),axios:s,auth:a,refreshTokenFn:r}={}){super({accountName:t.accountName}),_GitHubGitHost_instances.add(this),_GitHubGitHost_headers.set(this,{"Content-Type":"application/json",Accept:"application/vnd.github.v3+json"}),_GitHubGitHost_githubApis.set(this,{repos:GITHUB_API_URL+"/repos"}),_GitHubGitHost_axios.set(this,void 0),_GitHubGitHost_auth.set(this,void 0),_GitHubGitHost_refreshTokenFn.set(this,void 0),_GitHubGitHost_maxRetries.set(this,void 0),_GitHubGitHost_accessTokenLastUpdate.set(this,void 0),_GitHubGitHost_logger.set(this,void 0),_GitHubGitHost_retryConditionOverride.set(this,void 0),_GitHubGitHost_installation.set(this,void 0),__classPrivateFieldSet(this,_GitHubGitHost_installation,t,"f"),__classPrivateFieldSet(this,_GitHubGitHost_logger,i,"f"),__classPrivateFieldSet(this,_GitHubGitHost_maxRetries,e,"f"),__classPrivateFieldSet(this,_GitHubGitHost_axios,null!=s?s:axios_1.default.create(),"f"),__classPrivateFieldSet(this,_GitHubGitHost_retryConditionOverride,new RetryConditionOverride_1.OverridableRetryCondition(t=>{var i;const e=null===(i=t.response)||void 0===i?void 0:i.status,s=!e||e>=400&&401!==e;return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Request-retry: Got error response from GitHub.",{code:e,shouldRetry:s,status:t.message,error:t}),s}),"f"),s||(0,axios_retry_1.default)(__classPrivateFieldGet(this,_GitHubGitHost_axios,"f"),{retries:__classPrivateFieldGet(this,_GitHubGitHost_maxRetries,"f"),retryCondition:__classPrivateFieldGet(this,_GitHubGitHost_retryConditionOverride,"f").retryCondition,retryDelay:(t,i)=>{const e=axios_retry_1.default.exponentialDelay(t);return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Request-retry: Delaying request retrial by ${e} ms`,{delay:e,error:i}),e}}),__classPrivateFieldSet(this,_GitHubGitHost_auth,a,"f"),__classPrivateFieldSet(this,_GitHubGitHost_refreshTokenFn,r,"f"),__classPrivateFieldGet(this,_GitHubGitHost_axios,"f").defaults.httpsAgent=new https_1.Agent({keepAlive:!0}),__classPrivateFieldGet(this,_GitHubGitHost_axios,"f").interceptors.response.use(void 0,(0,Common_1.createErrorHandler)({provider:"GitHub",hostErrorMapping:githubHostError,userErrorMapping:githubUserError,logger:__classPrivateFieldGet(this,_GitHubGitHost_logger,"f")}))}static removeInstallation(t,i,e,s=(0,Logging_1.nullLogger)()){return __awaiter(this,void 0,void 0,(function*(){const a=axios_1.default.create(),r=__classPrivateFieldGet(GitHubGitHost,_a,"m",_GitHubGitHost_createJwtToken).call(GitHubGitHost,i,e);s.verbose("Removing GitHub installation",{installationId:t,appId:i}),yield a.delete(Url_1.asUrl`https://api.github.com/app/installations/${t}`,{headers:{Accept:"application/vnd.github.v3+json",Authorization:"Bearer "+r}}),s.verbose("GitHub installation removed successfully",{installationId:t,appId:i})}))}getHeadSha(t,i){return __awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getHeadCommitRefSHA).call(this,t,null!=i?i:yield this.getDefaultBranch(t))}))}createRepository({name:t,privateRepo:i}){return __awaiter(this,void 0,void 0,(function*(){if("anonymous"===__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType)throw AltoError_1.AltoError.create("Unsupported installation type for method "+__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createRepoToUser));if(!__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_isRepoNameValid).call(this,t))throw AltoError_1.AltoError.create(`Invalid repository name[${t}],\nRepository name can only contain letters and dashes`);try{const e=yield"user"===__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType?__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createRepoToUser).call(this,t,i):__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createRepoToOrganization).call(this,__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountName,t,i);return createRepoResponseAssertion(e),{repoUrl:e.html_url}}catch(t){throw AltoError_1.AltoError.wrapError(t,{message:"Failed to create GitHub repository",data:{accountName:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountName}})}}))}commitFiles({commitMessage:t,filesToCommit:i,targetRepositoryName:e,targetBranch:s}){return __awaiter(this,void 0,void 0,(function*(){try{yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this);const a=null!=s?s:yield this.getDefaultBranch(e);let r="";try{r=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getHeadCommitRefSHA).call(this,e,a)}catch(t){if(!isEmptyGitRepoError(t))throw __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").warn("The last github error does not indicate an empty repository",Object.assign({targetRepositoryName:e,targetBranch:s},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),t;r=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createInitialBranch).call(this,e,a)}const o=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createBlobFiles).call(this,e,i),_=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createNewTree).call(this,e,o,r),n=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createNewCommit).call(this,e,t,r,_);return yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_updateHeadBySHA).call(this,e,n,a),n}catch(t){throw AltoError_1.AltoError.wrapError(t,{message:"Error occurred while trying to commit files"})}}))}listRepositories(t){return __awaiter(this,void 0,void 0,(function*(){const i=this;yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this);const e=t?Url_1.asUrl`${t}+in:name+`+o():o(),s=`${GITHUB_API_URL}/search/repositories?per_page=100&q=${e}`,a=[];let r=1/0;for(let t=1;a.length<r;t++){const i=`${s}&page=${t}`,e=yield _(i);(0,Types_2.validateGithubRepositoriesSearchResult)(e);const{items:o,total_count:n}=e;r=n,a.push(...o.map(t=>t.name))}return a;function o(){const t=__classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_getGithubAccountName).call(i,__classPrivateFieldGet(i,_GitHubGitHost_installation,"f")),{accountType:e}=__classPrivateFieldGet(i,_GitHubGitHost_installation,"f");switch(e){case"anonymous":case"organization":return"fork:true+org:"+t;case"user":return"fork:true+user:"+t;default:throw AltoError_1.AltoError.create(`Unknown github account type [${e}]`,{data:{account:__classPrivateFieldGet(i,_GitHubGitHost_installation,"f")}})}}function _(e){return __awaiter(this,void 0,void 0,(function*(){try{__classPrivateFieldGet(i,_GitHubGitHost_logger,"f").verbose("Listing repositories",Object.assign({filter:null!=t?t:null},__classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(i)));const{data:s}=yield __classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_withRetryConditionOverride).call(i,{action:()=>__awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(i,_GitHubGitHost_axios,"f").get(e,{headers:yield __classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(i)})})),override:t=>{if(n(t))return!1}});return __classPrivateFieldGet(i,_GitHubGitHost_logger,"f").verbose("Repositories listed successfully",Object.assign({filter:null!=t?t:null,url:e},__classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(i))),s}catch(s){if(n(s))return __classPrivateFieldGet(i,_GitHubGitHost_logger,"f").verbose("The user has no repositories",Object.assign({filter:null!=t?t:null,url:e},__classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(i))),{items:[],total_count:0,incomplete_results:!1};throw __classPrivateFieldGet(i,_GitHubGitHost_logger,"f").verbose("Listing repositories has failed",Object.assign(Object.assign({filter:null!=t?t:null,url:e},__classPrivateFieldGet(i,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(i)),{error:s})),s}}))}function n(t){var i;return t instanceof AltoError_1.AltoError?n(t.inner):(0,Axios_1.isAxiosError)(t)&&422===(null===(i=t.response)||void 0===i?void 0:i.status)}}))}downloadFile(t,i){return __awaiter(this,void 0,void 0,(function*(){const e=`${__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)}/contents/${i}`;__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Downloading file",Object.assign({repository:t,path:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const{data:s}=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").get(e,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)});if(Array.isArray(s))throw __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").warn("Tried to downloading a file, but got a directory",Object.assign({repository:t,path:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),AltoError_1.AltoError.create({message:"Cannot download directory.",data:{repository:t,path:i}});__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("File downloaded successfully",Object.assign({repository:t,path:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const a=s.content;return Buffer.from(a.replace("\n",""),"base64")}))}downloadRepo(t){return __awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Downloading full repository",Object.assign({repository:t},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const i=__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/zipball",{data:e}=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").get(i,{maxContentLength:10485760,responseType:"stream",headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Full repository downloaded successfully",Object.assign({repository:t},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),e}))}createBranch(t,i){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.getDefaultBranch(t),s=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getHeadCommitRefSHA).call(this,t,e),a=__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/git/refs",r={ref:"refs/heads/"+i,sha:s};try{__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Creating a new branch",Object.assign({repository:t,branch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_withRetryConditionOverride).call(this,{action:()=>__awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(a,r,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)})})),override:t=>{if(o(t))return!1}}),__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("A new branch created successfully",Object.assign({repository:t,branch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)))}catch(e){if(o(e))return void __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("A new branch was not created because it is already exist",Object.assign({repository:t,branch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));throw __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").warn("Branch creation failed.",Object.assign({repository:t,branch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),e}function o(t){var i;return t instanceof AltoError_1.AltoError?o(t.inner):(0,Axios_1.isAxiosError)(t)&&422===(null===(i=t.response)||void 0===i?void 0:i.status)}}))}createPullRequest({repository:t,sourceBranch:i,targetBranch:e,title:s,content:a}){return __awaiter(this,void 0,void 0,(function*(){const r=__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/pulls",o={title:s,head:i,base:null!=e?e:yield this.getDefaultBranch(t),body:a};__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Creating pull request",Object.assign({repository:t,sourceBranch:i,targetBranch:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const{data:_}=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(r,o,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)});return(0,Types_2.validateCreatePullRequestResponse)(_),__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Pull request created successfully",Object.assign({repository:t,sourceBranch:i,targetBranch:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),_.html_url}))}getDefaultBranch(t){return __awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Getting default branch of "+t,Object.assign({repository:t},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const{data:i}=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t),{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)});return(0,Types_2.validateGithubRepository)(i),__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Successfully got default branch of "+t,Object.assign({repository:t},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),(0,NonEmptyString_1.nonEmptyString)(i.default_branch)}))}listFiles(t,{path:i,extFilter:e}={}){return __awaiter(this,void 0,void 0,(function*(){const s=this,a=yield function(){return __awaiter(this,void 0,void 0,(function*(){let e=yield __classPrivateFieldGet(s,_GitHubGitHost_instances,"m",_GitHubGitHost_getGitTree).call(s,t,"HEAD");const a=[];if(i)for(const r of i.split("/")){if(a.push(r),!r||"."===r||".."===r)throw Errors_1.UserFacingError.create("Invalid path.\nPath must not contain empty file-names, nor '.' file, nor '..' file.",{category:"user-fault",type:"invalid-path",data:{repository:t,path:i,currentPath:a.join("/")}});const o=e[r];if(!o)throw Errors_1.UserFacingError.create("Path does not exist in the repository.",{category:"user-fault",type:"path-not-exist",data:{repository:t,path:i,currentPath:a.join("/")}});if("tree"!==o.type)throw Errors_1.UserFacingError.create("Invalid path.\nThe path leads to file rather than directory.",{category:"user-fault",type:"path-is-file",data:{repository:t,path:i,currentPath:a.join("/")}});e=yield __classPrivateFieldGet(s,_GitHubGitHost_instances,"m",_GitHubGitHost_getGitTree).call(s,t,o.sha)}return e}))}();let r=(0,from_1.from)(Object.values(a)).pipe((0,map_1.map)(t=>t.path));if((e=(0,Common_1.normalizeExtFilter)(e)).length>0){const t=new Set(e);r=r.pipe((0,filter_1.filter)(i=>t.has((0,path_1.extname)(i).toLowerCase())))}return[...r]}))}getGitUtilsInitialization(){return{type:"github",accountName:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountName}}validateAuthentication(){return __awaiter(this,void 0,void 0,(function*(){yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)}))}}function githubHostError(t){var i,e,s;return Errors_1.UserFacingError.wrapError(t,{category:"server-fault",type:"github-server-error",message:"It appears that GitHub is unavailable.\nThis might be a temporary error, please try again or contact support.",data:{status:null===(i=t.response)||void 0===i?void 0:i.status,message:null===(e=t.response)||void 0===e?void 0:e.statusText,data:null===(s=t.response)||void 0===s?void 0:s.data}})}function githubUserError(t){var i,e,s,a;if(404===(null===(i=t.response)||void 0===i?void 0:i.status)&&isRepoUrl(t.config.url))return Errors_1.UserFacingError.wrapError(t,{type:"insufficient-access",category:"user-fault",message:"Unable to access GitHub repository.\nEither the repository does not exist or Altostra does not have permission to access it.\n\nRead how to give Altostra permissions to access the repository:\nhttps://docs.altostra.com/errors-and-solutions/import-project-troubleshooting.html",code:404});if(!(null===(e=t.response)||void 0===e?void 0:e.data))return t;let r=tryParseAsJSON(null===(s=t.response)||void 0===s?void 0:s.data);if(!(0,Object_1.isObject)(r))return t;if((0,NonEmptyString_1.isNonEmptyString)(r.message)&&"string"==typeof r.documentation_url)switch(null===(a=t.response)||void 0===a?void 0:a.status){case 422:if(USA_TRADE_CONTROLS_POLICY_DOCS_URL_RX.test(r.documentation_url))return Errors_1.UserFacingError.wrapError(t,{message:r.message,category:"user-fault",type:"usa-trade-controls-restrictions",data:r});if(r.documentation_url===BRANCH_IS_PROTECTED_DOCS_URL)return Errors_1.UserFacingError.wrapError(t,{message:"The default branch in the repository is protected.\n\t\tPlease use Altostra extension for vscode to edit your project locally and commit the changes to your preferred branch.",category:"user-fault",type:"branch-protection-violation",data:r});break;case 403:if(IP_NOT_IN_ALLOW_LIST_ERROR_MESSAGE_RX.test(r.message))return Errors_1.UserFacingError.wrapError(t,{message:"Your IP allow list blocks Altostra's IP address.\n\tTo fix this, follow this link to let installed apps update the list.\n\thttps://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps",category:"user-fault",type:"github-IP-not-allowed",data:r})}return Array.isArray(r.errors)&&1===r.errors.length&&(r=r.errors[0]),AltoError_1.AltoError.wrapError(t,{message:r.message,data:r,code:t.response.status})}exports.GitHubGitHost=GitHubGitHost,_a=GitHubGitHost,_GitHubGitHost_headers=new WeakMap,_GitHubGitHost_githubApis=new WeakMap,_GitHubGitHost_axios=new WeakMap,_GitHubGitHost_auth=new WeakMap,_GitHubGitHost_refreshTokenFn=new WeakMap,_GitHubGitHost_maxRetries=new WeakMap,_GitHubGitHost_accessTokenLastUpdate=new WeakMap,_GitHubGitHost_logger=new WeakMap,_GitHubGitHost_retryConditionOverride=new WeakMap,_GitHubGitHost_installation=new WeakMap,_GitHubGitHost_instances=new WeakSet,_GitHubGitHost_loggingTokenMetadata=function(){const t=__classPrivateFieldGet(this,_GitHubGitHost_installation,"f");return Object.assign({accountType:t.accountType,accountName:t.accountName},"anonymous"!==t.accountType?{createdAt:t.createdAt}:{})},_GitHubGitHost_getGitTree=function(t,i){return __awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Getting a git tree from [${t}]`,Object.assign({repository:t,treeish:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const{data:e}=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").get(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+Url_1.asUrl`/git/trees/${i}`,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)});return(0,Types_2.validateGetTreeResponse)(e),__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Successfully got a git tree from [${t}]`,Object.assign({repository:t,treeish:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),(0,Object_1.fromEntries)(e.tree.map(t=>[t.path,t]))}))},_GitHubGitHost_getGithubAccountName=function(t){return t.accountName},_GitHubGitHost_getRepoUrl=function(t){const i=__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getGithubAccountName).call(this,__classPrivateFieldGet(this,_GitHubGitHost_installation,"f"));return __classPrivateFieldGet(this,_GitHubGitHost_githubApis,"f").repos+Url_1.asUrl`/${i}/${t}`},_GitHubGitHost_createInitialBranch=function(t,i){return __awaiter(this,void 0,void 0,(function*(){const e={branch:i,message:"Initial commit",content:""};__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Creating initial branch for repo [${t}]`,Object.assign({repository:t,targetBranch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const s=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").put(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/contents/README.md",e,{headers:__classPrivateFieldGet(this,_GitHubGitHost_headers,"f")});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Successfully created initial branch for repo [${t}]`,Object.assign({repository:t,targetBranch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),s.data.commit.sha}))},_GitHubGitHost_setAuthorizationHeader=function({useUserAccessToken:t}={}){return __awaiter(this,void 0,void 0,(function*(){let i=void 0;if("anonymous"===__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType){if(!__classPrivateFieldGet(this,_GitHubGitHost_auth,"f"))throw AltoError_1.AltoError.create("No auth parameters presented on anonymous installation type");const t=Buffer.from(`${__classPrivateFieldGet(this,_GitHubGitHost_auth,"f").appId}:${__classPrivateFieldGet(this,_GitHubGitHost_auth,"f").secret}`,"utf8").toString("base64");return Object.assign(Object.assign({},__classPrivateFieldGet(this,_GitHubGitHost_headers,"f")),{Authorization:"Basic "+t})}return t&&(0,Types_1.isUserGithubIntegration)(__classPrivateFieldGet(this,_GitHubGitHost_installation,"f"))?Object.assign(Object.assign({},__classPrivateFieldGet(this,_GitHubGitHost_headers,"f")),{Authorization:`${__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").token.type} ${__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").token.token}`}):(__classPrivateFieldGet(this,_GitHubGitHost_auth,"f")&&!__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_hasValidToken).call(this)&&(i=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createOrganizationAccessToken).call(this,__classPrivateFieldGet(this,_GitHubGitHost_auth,"f").appId,__classPrivateFieldGet(this,_GitHubGitHost_auth,"f").secret,__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").id)),i&&(__classPrivateFieldGet(this,_GitHubGitHost_headers,"f").Authorization=`${i.type} ${i.token}`),__classPrivateFieldGet(this,_GitHubGitHost_headers,"f"))}))},_GitHubGitHost_hasValidToken=function(){return __classPrivateFieldGet(this,_GitHubGitHost_accessTokenLastUpdate,"f")&&Date.now()-__classPrivateFieldGet(this,_GitHubGitHost_accessTokenLastUpdate,"f").getTime()<=54e4},_GitHubGitHost_createJwtToken=function(t,i){const e=Math.floor(Date.now()/1e3)-30,s={iat:e,exp:e+600,iss:t};return(0,JwtGenerator_1.jwtGenerator)(s,i,{algorithm:"RS256"})},_GitHubGitHost_createOrganizationAccessToken=function(t,i,e){return __awaiter(this,void 0,void 0,(function*(){const s=__classPrivateFieldGet(GitHubGitHost,_a,"m",_GitHubGitHost_createJwtToken).call(GitHubGitHost,t,i);return yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_createAccessTokenUsingInstallationId).call(this,s,e)}))},_GitHubGitHost_getHeadCommitRefSHA=function(t,i){return __awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Getting HEAD of branch [${i}] in repo [${t}]`,Object.assign({repository:t,targetBranch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const e=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_withRetryConditionOverride).call(this,{action:()=>__awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").get(`${__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)}/git/ref/heads/${i}`,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)})})),override:t=>{if(isEmptyGitRepoError(t))return!1}});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Successfully got HEAD of branch [${i}] in repo [${t}]`,Object.assign({repository:t,targetBranch:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),e.data.object.sha}))},_GitHubGitHost_createBlobFiles=function(t,i){return __awaiter(this,void 0,void 0,(function*(){const e=(0,from_1.from)(Object.entries(i)).pipe((0,filter_1.filter)(([,t])=>void 0!==t),(0,map_1.map)(([t,i])=>({fileName:t,content:i.toString("base64")}))).pipe((0,map_1.map)(({fileName:i,content:e})=>__awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Loading file blob to repo",Object.assign({repository:t,fileName:i,size:e.length},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const s=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/git/blobs",{content:e,encoding:"base64"},{headers:__classPrivateFieldGet(this,_GitHubGitHost_headers,"f"),maxContentLength:1/0,maxBodyLength:1/0});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Successfully loaded file blob to repo",Object.assign({repository:t,fileName:i,size:e.length},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),[i,s]}))));return(0,Object_1.fromEntries)((0,from_1.from)(yield Promise.all(e)).pipe((0,map_1.map)(([t,i])=>[t,i.data.sha])))}))},_GitHubGitHost_isRepoNameValid=function(t){return/^[a-zA-z0-9-]*$/gi.test(t)},_GitHubGitHost_createNewTree=function(t,i,e){return __awaiter(this,void 0,void 0,(function*(){const s={base_tree:e,tree:[]};for(const[t,e]of Object.entries(i)){if(void 0===e)throw new AltoError_1.AltoError(`Could not create blob file from path: ${t}, file's SHA is missing`);s.tree.push({path:t,mode:"100644",type:"blob",sha:e})}__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Creating new git-tree in repo [${t}]`,Object.assign({repository:t,baseTree:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const a=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/git/trees",s,{headers:__classPrivateFieldGet(this,_GitHubGitHost_headers,"f")});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`New git-tree created successfully in repo [${t}]`,Object.assign({repository:t,baseTree:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),a.data.sha}))},_GitHubGitHost_createNewCommit=function(t,i,e,s){return __awaiter(this,void 0,void 0,(function*(){const a={message:i,parents:[e],tree:s};__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Creating a new commit in [${t}]`,Object.assign({repository:t,parentSHA:e,newTreeSha:s},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const r=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+"/git/commits",a,{headers:__classPrivateFieldGet(this,_GitHubGitHost_headers,"f"),maxContentLength:1/0,maxBodyLength:1/0});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`A new commit created successfully in [${t}]`,Object.assign({repository:t,parentSHA:e,newTreeSha:s},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),r.data.sha}))},_GitHubGitHost_updateHeadBySHA=function(t,i,e){return __awaiter(this,void 0,void 0,(function*(){const s={sha:i,force:!0};__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Updating branch HEAD",Object.assign({repository:t,targetBranch:e,targetSHA:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").patch(__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_getRepoUrl).call(this,t)+Url_1.asUrl`/git/refs/heads/${e}`,s,{headers:__classPrivateFieldGet(this,_GitHubGitHost_headers,"f")}),__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Branch HEAD updated successfully",Object.assign({repository:t,targetBranch:e,targetSHA:i},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)))}))},_GitHubGitHost_createAccessTokenUsingInstallationId=function t(i,e,s=0){return __awaiter(this,void 0,void 0,(function*(){if(s>=exports.MAX_RETRY_TIMES)throw AltoError_1.AltoError.create({message:"Failed to generate an access token",data:{installationId:e,retryCount:s}});try{__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Getting access token for [${e}]`,Object.assign({retryCount:s},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const t=yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(`https://api.github.com/app/installations/${e}/access_tokens`,{},{headers:{"User-Agent":"Altostra",Authorization:"Bearer "+i,Accept:"application/vnd.github.machine-man-preview+json"}});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose(`Got access token successfully for [${e}]`,Object.assign({retryCount:s},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),__classPrivateFieldSet(this,_GitHubGitHost_accessTokenLastUpdate,new Date(t.data.expires_at),"f"),{token:t.data.token,type:"token"}}catch(a){if(a instanceof AltoError_1.AltoError&&401===a.code)return yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",t).call(this,i,e,++s);throw a}}))},_GitHubGitHost_createRepoToUser=function t(i,e,s=0,a){return __awaiter(this,void 0,void 0,(function*(){if("anonymous"===__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType)throw AltoError_1.AltoError.create("Unsupported installation type}");if(s>=__classPrivateFieldGet(this,_GitHubGitHost_maxRetries,"f"))throw Errors_1.UserFacingError.wrapError(AltoError_1.AltoError.wrapError(a,{message:"Retries exhausted for github _createRepoToUser",code:Types_1.GITHUB_REQUIRE_AUTHORIZATION_CODE,data:{retires:s,action:"_createRepoToUser"}}),{message:"Failed to create repository",category:"server-fault",type:Types_1.GITHUB_REQUIRE_AUTHORIZATION_CODE});if(!(0,Types_1.isUserGithubIntegration)(__classPrivateFieldGet(this,_GitHubGitHost_installation,"f"))||!__classPrivateFieldGet(this,_GitHubGitHost_refreshTokenFn,"f"))throw AltoError_1.AltoError.create("Repository creation for User GitHub account requires both a refresh token function and user installation",{data:{installation:{accountName:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountName,accountType:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType,createdAt:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").createdAt,id:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").id},refreshTokenFnExists:!!__classPrivateFieldGet(this,_GitHubGitHost_refreshTokenFn,"f")}});try{const t={name:i,private:e};__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Creating repository in user account",Object.assign({repoName:i,isPrivate:e,currentRetries:s,lastError:null!=a?a:null},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const r=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_withRetryConditionOverride).call(this,{action:()=>__awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post("https://api.github.com/user/repos",t,{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this,{useUserAccessToken:!0})})})),override:t=>{if(isRepoAlreadyExistsError(t))return!1}});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Successfully created repository in user account",Object.assign({repoName:i,isPrivate:e,currentRetries:s,lastError:null!=a?a:null},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),r.data}catch(a){if(401===Number(a.code))return __classPrivateFieldGet(this,_GitHubGitHost_installation,"f").token=yield __classPrivateFieldGet(this,_GitHubGitHost_refreshTokenFn,"f").call(this),yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",t).call(this,i,e,s+1,a);throw AltoError_1.AltoError.wrapError(a,{message:"Failed to create repository for user",data:{installation:{accountName:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountName,accountType:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").accountType,createdAt:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").createdAt,id:__classPrivateFieldGet(this,_GitHubGitHost_installation,"f").id}}})}}))},_GitHubGitHost_createRepoToOrganization=function(t,i,e){return __awaiter(this,void 0,void 0,(function*(){__classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Creating repository in organization account",Object.assign({repoName:i,isPrivate:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this)));const s=yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_withRetryConditionOverride).call(this,{action:()=>__awaiter(this,void 0,void 0,(function*(){return yield __classPrivateFieldGet(this,_GitHubGitHost_axios,"f").post(Url_1.asUrl`https://api.github.com/orgs/${t}/repos`,{name:i,private:e},{headers:yield __classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_setAuthorizationHeader).call(this)})})),override:t=>{if(isRepoAlreadyExistsError(t))return!1}});return __classPrivateFieldGet(this,_GitHubGitHost_logger,"f").verbose("Successfully created repository in organization account",Object.assign({repoName:i,isPrivate:e},__classPrivateFieldGet(this,_GitHubGitHost_instances,"m",_GitHubGitHost_loggingTokenMetadata).call(this))),s.data}))},_GitHubGitHost_withRetryConditionOverride=function(t){return __classPrivateFieldGet(this,_GitHubGitHost_retryConditionOverride,"f").withOverride(t)};const repoUrlRX=/^https:\/\/api\.github\.com\/repos\/[^/]+\/[^/]+/i;function isRepoUrl(t){return"string"==typeof t&&repoUrlRX.test(t)}function isEmptyGitRepoError(t){var i;return t instanceof AltoError_1.AltoError?isEmptyGitRepoError(t.inner):(0,Axios_1.isAxiosError)(t)&&409===(null===(i=t.response)||void 0===i?void 0:i.status)}function tryParseAsJSON(t){let i=t;try{"string"===t&&(i=JSON.parse(t))}catch(e){i=t}return i}function isRepoAlreadyExistsError(t){var i;return t instanceof AltoError_1.AltoError?isRepoAlreadyExistsError(t.inner):(0,Axios_1.isAxiosError)(t)&&422===(null===(i=t.response)||void 0===i?void 0:i.status)}