decap-cms-backend-github 3.1.0-beta.0 → 3.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,17 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.1.0-beta.1](https://github.com/decaporg/decap-cms/compare/decap-cms-backend-github@3.1.0-beta.0...decap-cms-backend-github@3.1.0-beta.1) (2023-11-15)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * used merge-upstream to sync fork & upstream ([#6504](https://github.com/decaporg/decap-cms/issues/6504)) ([931399d](https://github.com/decaporg/decap-cms/commit/931399dd6eb675e06d59ac57ecfefc1b82467271))
12
+
13
+
14
+
15
+
16
+
6
17
  # [3.1.0-beta.0](https://github.com/decaporg/decap-cms/compare/decap-cms-backend-github@3.1.0...decap-cms-backend-github@3.1.0-beta.0) (2023-10-20)
7
18
 
8
19
 
@@ -300,7 +300,7 @@
300
300
  }
301
301
  }
302
302
  ${Fo}
303
- `;function ca(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function la(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ca(Object(r),!0).forEach((function(t){ha(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ca(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function ha(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const fa="no-cache",pa="cache-first",da=new Xn({introspectionQueryResultData:ki()});function ma(e){return la(la({},e),{},{labels:e.labels.nodes,head:{ref:e.headRefName,sha:e.headRefOid,repo:{fork:e.repository.isFork}},base:{ref:e.baseRefName,sha:e.baseRefOid}})}class ya extends ht{constructor(e){super(e),ha(this,"client",void 0),this.client=this.getApolloClient()}getApolloClient(){const e=(r=(e,{headers:t})=>({headers:la(la({"Content-Type":"application/json; charset=utf-8"},t),{},{authorization:this.token?`token ${this.token}`:""})}),new $r((function(e,t){var n=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,[]);return new Tr((function(i){var o;return Promise.resolve(n).then((function(t){return r(t,e.getContext())})).then(e.setContext).then((function(){o=t(e).subscribe({next:i.next.bind(i),error:i.error.bind(i),complete:i.complete.bind(i)})})).catch(i.error.bind(i)),function(){o&&o.unsubscribe()}}))}))),t=Oi({uri:`${this.apiRoot}/graphql`});var r;return new cn({link:e.concat(t),cache:new mi({fragmentMatcher:da}),defaultOptions:{watchQuery:{fetchPolicy:fa,errorPolicy:"ignore"},query:{fetchPolicy:fa,errorPolicy:"all"}}})}reset(){return this.client.resetStore()}async getRepository(e,t){const{data:r}=await this.query({query:Go,variables:{owner:e,name:t},fetchPolicy:pa});return r.repository}query(e){return this.client.query(e).catch((e=>{throw new S.APIError(e.message,500,"GitHub")}))}async mutate(e){try{return await this.client.mutate(e)}catch(u){const c=u.graphQLErrors;if(Array.isArray(c)&&c.some((e=>"Ref cannot be created."===e.message))){var t,r;const n=(null==e||null===(t=e.variables)||void 0===t||null===(r=t.createRefInput)||void 0===r?void 0:r.name)||"",i=s()(n,"refs/heads/");i&&await(0,S.throwOnConflictingBranches)(i,(e=>this.getBranch(e)),it)}else if(Array.isArray(c)&&c.some((e=>new RegExp(`A ref named "refs/heads/${S.CMS_BRANCH_PREFIX}/.+?" already exists in the repository.`).test(e.message)))){var n,i,o,a;const t=(null==e||null===(n=e.variables)||void 0===n||null===(i=n.createRefInput)||void 0===i?void 0:i.name)||"",r=(null==e||null===(o=e.variables)||void 0===o||null===(a=o.createRefInput)||void 0===a?void 0:a.oid)||"",u=s()(t,"refs/heads/");if(u&&u.startsWith(`${S.CMS_BRANCH_PREFIX}/`)&&r)try{return await this.backupBranch(u),await this.deleteBranch(u),await this.client.mutate(e)}catch(e){console.log(e)}}throw new S.APIError(u.message,500,"GitHub")}}async hasWriteAccess(){const{repoOwner:e,repoName:t}=this;try{const{data:r}=await this.query({query:Bo,variables:{owner:e,name:t},fetchPolicy:pa}),{viewerPermission:n}=r.repository;return["ADMIN","MAINTAIN","WRITE"].includes(n)}catch(e){throw console.error("Problem fetching repo data from GitHub"),e}}async user(){const{data:e}=await this.query({query:Lo,fetchPolicy:pa});return e.viewer}async retrieveBlobObject(e,t,r,n={}){const{data:i}=await this.query(la({query:Mo,variables:{owner:e,name:t,expression:r}},n));if(i.repository.object){const{is_binary:e,text:t}=i.repository.object;return{isNull:!1,isBinary:e,text:t}}return{isNull:!0}}getOwnerAndNameFromRepoUrl(e){let{repoOwner:t,repoName:r}=this;return e===this.originRepoURL&&({originRepoOwner:t,originRepoName:r}=this),{owner:t,name:r}}async readFile(e,t,{branch:r=this.branch,repoURL:n=this.repoURL,parseText:i=!0}={}){return t||(t=await this.getFileSha(e,{repoURL:n,branch:r})),await(0,S.readFile)(t,(()=>this.fetchBlobContent({sha:t,repoURL:n,parseText:i})),S.localForage,i)}async fetchBlobContent({sha:e,repoURL:t,parseText:r}){if(!r)return super.fetchBlobContent({sha:e,repoURL:t,parseText:r});const{owner:n,name:i}=this.getOwnerAndNameFromRepoUrl(t),{isNull:o,isBinary:a,text:s}=await this.retrieveBlobObject(n,i,e,{fetchPolicy:pa});if(o)throw new S.APIError("Not Found",404,"GitHub");return a?super.fetchBlobContent({sha:e,repoURL:t,parseText:r}):s}async getPullRequestAuthor(e){const t=e.user;return(null==t?void 0:t.name)||(null==t?void 0:t.login)}async getPullRequests(e,t,r){const{originRepoOwner:n,originRepoName:i}=this;let o;o=t===st.Open?["OPEN"]:t===st.Closed?["CLOSED","MERGED"]:["OPEN","CLOSED","MERGED"];const{data:a}=await this.query({query:Ho,variables:la(la({owner:n,name:i},e?{head:e}:{}),{},{states:o})}),{pullRequests:s}=a.repository;return s.nodes.map(ma).filter((e=>e.head.ref.startsWith(`${S.CMS_BRANCH_PREFIX}/`)&&r(e)))}async getOpenAuthoringBranches(){const{repoOwner:e,repoName:t}=this,{data:r}=await this.query({query:zo,variables:{owner:e,name:t,refPrefix:`refs/heads/cms/${this.repo}/`}});return r.repository.refs.nodes.map((({name:e,prefix:t})=>({ref:`${t}${e}`})))}async getStatuses(e,t){const r=this.generateContentKey(e,t),n=(0,S.branchFromContentKey)(r),i=(await this.getBranchPullRequest(n)).head.sha,{originRepoOwner:o,originRepoName:a}=this,{data:s}=await this.query({query:Uo,variables:{owner:o,name:a,sha:i}});if(s.repository.object){const{status:e}=s.repository.object,{contexts:t}=e||{contexts:[]};return t}return[]}getAllFiles(e,t){return e.reduce(((e,r)=>{if("tree"===r.type){var n;const i=(null===(n=r.object)||void 0===n?void 0:n.entries)||[];return[...e,...this.getAllFiles(i,`${t}/${r.name}`)]}return"blob"===r.type?[...e,{name:r.name,type:r.type,id:r.sha,path:`${t}/${r.name}`,size:r.blob?r.blob.size:0}]:e}),[])}async listFiles(e,{repoURL:t=this.repoURL,branch:r=this.branch,depth:n=1}={}){const{owner:i,name:o}=this.getOwnerAndNameFromRepoUrl(t),a=ae()(e,"/"),{data:s}=await this.query({query:$o(n),variables:{owner:i,name:o,expression:`${r}:${a}`}});return s.repository.object?this.getAllFiles(s.repository.object.entries,a):[]}getBranchQualifiedName(e){return`refs/heads/${e}`}getBranchQuery(e,t,r){return{query:Vo,variables:{owner:t,name:r,qualifiedName:this.getBranchQualifiedName(e)}}}async getDefaultBranch(){const{data:e}=await this.query(la({},this.getBranchQuery(this.branch,this.originRepoOwner,this.originRepoName)));return e.repository.branch}async getBranch(e){const{data:t}=await this.query(la(la({},this.getBranchQuery(e,this.repoOwner,this.repoName)),{},{fetchPolicy:pa}));if(!t.repository.branch)throw new S.APIError("Branch not found",404,it);return t.repository.branch}async patchRef(e,t,r,n={}){if("heads"!==e)return super.patchRef(e,t,r,n);const i=n.force||!1,o=await this.getBranch(t),{data:a}=await this.mutate({mutation:Xo,variables:{input:{oid:r,refId:o.id,force:i}}});return a.updateRef.branch}async deleteBranch(e){const t=await this.getBranch(e),{data:r}=await this.mutate({mutation:ea,variables:{deleteRefInput:{refId:t.id}},update:e=>e.data.delete(fi(t))});return r.deleteRef}getPullRequestQuery(e){const{originRepoOwner:t,originRepoName:r}=this;return{query:Wo,variables:{owner:t,name:r,number:e}}}async getPullRequest(e){const{data:t}=await this.query(la(la({},this.getPullRequestQuery(e)),{},{fetchPolicy:pa})),r="OPEN"===t.repository.pullRequest.state?st.Open:st.Closed;return la(la({},t.repository.pullRequest),{},{state:r})}getPullRequestAndBranchQuery(e,t){const{repoOwner:r,repoName:n}=this,{originRepoOwner:i,originRepoName:o}=this;return{query:Jo,variables:{owner:r,name:n,originRepoOwner:i,originRepoName:o,number:t,qualifiedName:this.getBranchQualifiedName(e)}}}async getPullRequestAndBranch(e,t){const{data:r}=await this.query(la(la({},this.getPullRequestAndBranchQuery(e,t)),{},{fetchPolicy:pa})),{repository:n,origin:i}=r;return{branch:n.branch,pullRequest:i.pullRequest}}async openPR(e){const t=await this.getPullRequest(e),{data:r}=await this.mutate({mutation:ua,variables:{reopenPullRequestInput:{pullRequestId:t.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.reopenPullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}});return r.reopenPullRequest}async closePR(e){const t=await this.getPullRequest(e),{data:r}=await this.mutate({mutation:ra,variables:{closePullRequestInput:{pullRequestId:t.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.closePullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}});return r.closePullRequest}async deleteUnpublishedEntry(e,t){try{const r=this.generateContentKey(e,t),n=(0,S.branchFromContentKey)(r),i=await this.getBranchPullRequest(n);if(i.number!==ot){const{branch:e,pullRequest:t}=await this.getPullRequestAndBranch(n,i.number),{data:r}=await this.mutate({mutation:na,variables:{deleteRefInput:{refId:e.id},closePullRequestInput:{pullRequestId:t.id}},update:r=>{r.data.delete(fi(e)),r.data.delete(fi(t))}});return r.closePullRequest}return await this.deleteBranch(n)}catch(e){const{graphQLErrors:t}=e;if(t&&t.length>0){const e=t.some((e=>"NOT_FOUND"===e.type));if(e)return}throw e}}async createPR(e,t){const[r,n]=await Promise.all([this.getRepository(this.originRepoOwner,this.originRepoName),this.useOpenAuthoring?`${(await this.user()).login}:${t}`:t]),{data:i}=await this.mutate({mutation:oa,variables:{createPullRequestInput:{baseRefName:this.branch,body:S.DEFAULT_PR_BODY,title:e,headRefName:n,repositoryId:r.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.createPullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}}),{pullRequest:o}=i.createPullRequest;return la(la({},o),{},{head:{sha:o.headRefOid}})}async createBranch(e,t){const r=this.repoOwner,n=this.repoName,i=await this.getRepository(r,n),{data:o}=await this.mutate({mutation:aa,variables:{createRefInput:{name:this.getBranchQualifiedName(e),oid:t,repositoryId:i.id}},update:(t,{data:i})=>{const{branch:o}=i.createRef,a={repository:la(la({},o.repository),{},{branch:o})};t.writeQuery(la(la({},this.getBranchQuery(e,r,n)),{},{data:a}))}}),{branch:a}=o.createRef;return la(la({},a),{},{ref:`${a.prefix}${a.name}`})}async createBranchAndPullRequest(e,t,r){const n=this.originRepoOwner,i=this.originRepoName,o=await this.getRepository(n,i),{data:a}=await this.mutate({mutation:sa,variables:{createRefInput:{name:this.getBranchQualifiedName(e),oid:t,repositoryId:o.id},createPullRequestInput:{baseRefName:this.branch,body:S.DEFAULT_PR_BODY,title:r,headRefName:e,repositoryId:o.id}},update:(t,{data:r})=>{const{branch:o}=r.createRef,{pullRequest:a}=r.createPullRequest,s={repository:la(la({},o.repository),{},{branch:o})},u={repository:la(la({},a.repository),{},{branch:o}),origin:la(la({},a.repository),{},{pullRequest:a})};t.writeQuery(la(la({},this.getBranchQuery(e,n,i)),{},{data:s})),t.writeQuery(la(la({},this.getPullRequestAndBranchQuery(e,a.number)),{},{data:u}))}}),{pullRequest:s}=a.createPullRequest;return ma(s)}async getFileSha(e,{repoURL:t=this.repoURL,branch:r=this.branch}={}){const{owner:n,name:i}=this.getOwnerAndNameFromRepoUrl(t),{data:o}=await this.query({query:Yo,variables:{owner:n,name:i,expression:`${r}:${e}`}});if(o.repository.file)return o.repository.file.sha;throw new S.APIError("Not Found",404,it)}}function va(){return va=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},va.apply(this,arguments)}function ga(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ba(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ga(Object(r),!0).forEach((function(t){wa(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ga(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function wa(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const{fetchWithTimeout:Ra}=S.unsentRequest,Ea="https://www.githubstatus.com",Oa=`${Ea}/api/v2/components.json`,Sa=["API Requests","Issues, Pull Requests, Projects"],ka={GitHubBackend:class{constructor(e,t={}){var r;if(wa(this,"lock",void 0),wa(this,"api",void 0),wa(this,"options",void 0),wa(this,"originRepo",void 0),wa(this,"repo",void 0),wa(this,"openAuthoringEnabled",void 0),wa(this,"useOpenAuthoring",void 0),wa(this,"alwaysForkEnabled",void 0),wa(this,"branch",void 0),wa(this,"apiRoot",void 0),wa(this,"mediaFolder",void 0),wa(this,"previewContext",void 0),wa(this,"token",void 0),wa(this,"squashMerges",void 0),wa(this,"cmsLabelPrefix",void 0),wa(this,"useGraphql",void 0),wa(this,"_currentUserPromise",void 0),wa(this,"_userIsOriginMaintainerPromises",void 0),wa(this,"_mediaDisplayURLSem",void 0),wa(this,"getCursorAndFiles",((e,t)=>{const r=e.length,n=Math.ceil(e.length/20),i=[];return t>1&&(i.push("prev"),i.push("first")),t<n&&(i.push("next"),i.push("last")),{cursor:S.Cursor.create({actions:i,meta:{page:t,count:r,pageSize:20,pageCount:n},data:{files:e}}),files:e.slice(20*(t-1),20*t)}})),this.options=ba({proxied:!1,API:null,initialWorkflowStatus:""},t),!this.options.proxied&&(null===e.backend.repo||void 0===e.backend.repo))throw new Error('The GitHub backend needs a "repo" in the backend configuration.');if(this.api=this.options.API||null,this.openAuthoringEnabled=e.backend.open_authoring||!1,this.openAuthoringEnabled){if(!this.options.useWorkflow)throw new Error("backend.open_authoring is true but publish_mode is not set to editorial_workflow.");this.originRepo=e.backend.repo||""}else this.repo=this.originRepo=e.backend.repo||"";this.alwaysForkEnabled=e.backend.always_fork||!1,this.branch=(null===(r=e.backend.branch)||void 0===r?void 0:r.trim())||"master",this.apiRoot=e.backend.api_root||"https://api.github.com",this.token="",this.squashMerges=e.backend.squash_merges||!1,this.cmsLabelPrefix=e.backend.cms_label_prefix||"",this.useGraphql=e.backend.use_graphql||!1,this.mediaFolder=e.media_folder,this.previewContext=e.backend.preview_context||"",this.lock=(0,S.asyncLock)()}isGitBackend(){return!0}async status(){const e=await Ra(Oa).then((e=>e.json())).then((e=>e.components.filter((e=>Sa.includes(e.name))).every((e=>"operational"===e.status)))).catch((e=>(console.warn("Failed getting GitHub status",e),!0)));let t=!1;var r;return e&&(t=await(null===(r=this.api)||void 0===r?void 0:r.getUser().then((e=>!!e)).catch((e=>(console.warn("Failed getting GitHub user",e),!1))))||!1),{auth:{status:t},api:{status:e,statusPage:Ea}}}authComponent(){const e=e=>(0,P.jsx)(ie,va({},e,{backend:this}));return e.displayName="AuthenticationPage",e}restoreUser(e){return this.openAuthoringEnabled?this.authenticateWithFork({userData:e,getPermissionToFork:()=>!0}).then((()=>this.authenticate(e))):this.authenticate(e)}async pollUntilForkExists({repo:e,token:t}){let r=!1;for(;!r;)r=await Ra(`${this.apiRoot}/repos/${e}`,{headers:{Authorization:`token ${t}`}}).then((()=>!0)).catch((e=>e&&404===e.status?(console.log("This 404 was expected and handled appropriately."),!1):Promise.reject(e))),r||await new Promise((e=>setTimeout(e,250)));return Promise.resolve()}async currentUser({token:e}){return this._currentUserPromise||(this._currentUserPromise=Ra(`${this.apiRoot}/user`,{headers:{Authorization:`token ${e}`}}).then((e=>e.json()))),this._currentUserPromise}async userIsOriginMaintainer({username:e,token:t}){const r=e||(await this.currentUser({token:t})).login;return this._userIsOriginMaintainerPromises=this._userIsOriginMaintainerPromises||{},this._userIsOriginMaintainerPromises[r]||(this._userIsOriginMaintainerPromises[r]=Ra(`${this.apiRoot}/repos/${this.originRepo}/collaborators/${r}/permission`,{headers:{Authorization:`token ${t}`}}).then((e=>e.json())).then((({permission:e})=>"admin"===e||"write"===e))),this._userIsOriginMaintainerPromises[r]}async forkExists({token:e}){try{const t=await this.currentUser({token:e}),r=this.originRepo.split("/")[1],n=await Ra(`${this.apiRoot}/repos/${t.login}/${r}`,{method:"GET",headers:{Authorization:`token ${e}`}}).then((e=>e.json()));return!0===n.fork&&n.parent&&n.parent.full_name.toLowerCase()===this.originRepo.toLowerCase()}catch{return!1}}async authenticateWithFork({userData:e,getPermissionToFork:t}){if(!this.openAuthoringEnabled)throw new Error("Cannot authenticate with fork; Open Authoring is turned off.");const r=e.token;if(!this.alwaysForkEnabled&&await this.userIsOriginMaintainer({token:r}))return this.repo=this.originRepo,this.useOpenAuthoring=!1,Promise.resolve();await this.forkExists({token:r})||await t();const n=await Ra(`${this.apiRoot}/repos/${this.originRepo}/forks`,{method:"POST",headers:{Authorization:`token ${r}`}}).then((e=>e.json()));return this.useOpenAuthoring=!0,this.repo=n.full_name,this.pollUntilForkExists({repo:n.full_name,token:r})}async authenticate(e){this.token=e.token;const t=this.useGraphql?ya:ht;this.api=new t({token:this.token,branch:this.branch,repo:this.repo,originRepo:this.originRepo,apiRoot:this.apiRoot,squashMerges:this.squashMerges,cmsLabelPrefix:this.cmsLabelPrefix,useOpenAuthoring:this.useOpenAuthoring,initialWorkflowStatus:this.options.initialWorkflowStatus});const r=await this.api.user();if(!await this.api.hasWriteAccess().catch((e=>{throw e.message=O`
303
+ `;function ca(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function la(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ca(Object(r),!0).forEach((function(t){ha(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ca(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function ha(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const fa="no-cache",pa="cache-first",da=new Xn({introspectionQueryResultData:ki()});function ma(e){return la(la({},e),{},{labels:e.labels.nodes,head:{ref:e.headRefName,sha:e.headRefOid,repo:{fork:e.repository.isFork}},base:{ref:e.baseRefName,sha:e.baseRefOid}})}class ya extends ht{constructor(e){super(e),ha(this,"client",void 0),this.client=this.getApolloClient()}getApolloClient(){const e=(r=(e,{headers:t})=>({headers:la(la({"Content-Type":"application/json; charset=utf-8"},t),{},{authorization:this.token?`token ${this.token}`:""})}),new $r((function(e,t){var n=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,[]);return new Tr((function(i){var o;return Promise.resolve(n).then((function(t){return r(t,e.getContext())})).then(e.setContext).then((function(){o=t(e).subscribe({next:i.next.bind(i),error:i.error.bind(i),complete:i.complete.bind(i)})})).catch(i.error.bind(i)),function(){o&&o.unsubscribe()}}))}))),t=Oi({uri:`${this.apiRoot}/graphql`});var r;return new cn({link:e.concat(t),cache:new mi({fragmentMatcher:da}),defaultOptions:{watchQuery:{fetchPolicy:fa,errorPolicy:"ignore"},query:{fetchPolicy:fa,errorPolicy:"all"}}})}reset(){return this.client.resetStore()}async getRepository(e,t){const{data:r}=await this.query({query:Go,variables:{owner:e,name:t},fetchPolicy:pa});return r.repository}query(e){return this.client.query(e).catch((e=>{throw new S.APIError(e.message,500,"GitHub")}))}async mutate(e){try{return await this.client.mutate(e)}catch(u){const c=u.graphQLErrors;if(Array.isArray(c)&&c.some((e=>"Ref cannot be created."===e.message))){var t,r;const n=(null==e||null===(t=e.variables)||void 0===t||null===(r=t.createRefInput)||void 0===r?void 0:r.name)||"",i=s()(n,"refs/heads/");i&&await(0,S.throwOnConflictingBranches)(i,(e=>this.getBranch(e)),it)}else if(Array.isArray(c)&&c.some((e=>new RegExp(`A ref named "refs/heads/${S.CMS_BRANCH_PREFIX}/.+?" already exists in the repository.`).test(e.message)))){var n,i,o,a;const t=(null==e||null===(n=e.variables)||void 0===n||null===(i=n.createRefInput)||void 0===i?void 0:i.name)||"",r=(null==e||null===(o=e.variables)||void 0===o||null===(a=o.createRefInput)||void 0===a?void 0:a.oid)||"",u=s()(t,"refs/heads/");if(u&&u.startsWith(`${S.CMS_BRANCH_PREFIX}/`)&&r)try{return await this.backupBranch(u),await this.deleteBranch(u),await this.client.mutate(e)}catch(e){console.log(e)}}throw new S.APIError(u.message,500,"GitHub")}}async hasWriteAccess(){const{repoOwner:e,repoName:t}=this;try{const{data:r}=await this.query({query:Bo,variables:{owner:e,name:t},fetchPolicy:pa}),{viewerPermission:n}=r.repository;return["ADMIN","MAINTAIN","WRITE"].includes(n)}catch(e){throw console.error("Problem fetching repo data from GitHub"),e}}async user(){const{data:e}=await this.query({query:Lo,fetchPolicy:pa});return e.viewer}async retrieveBlobObject(e,t,r,n={}){const{data:i}=await this.query(la({query:Mo,variables:{owner:e,name:t,expression:r}},n));if(i.repository.object){const{is_binary:e,text:t}=i.repository.object;return{isNull:!1,isBinary:e,text:t}}return{isNull:!0}}getOwnerAndNameFromRepoUrl(e){let{repoOwner:t,repoName:r}=this;return e===this.originRepoURL&&({originRepoOwner:t,originRepoName:r}=this),{owner:t,name:r}}async readFile(e,t,{branch:r=this.branch,repoURL:n=this.repoURL,parseText:i=!0}={}){return t||(t=await this.getFileSha(e,{repoURL:n,branch:r})),await(0,S.readFile)(t,(()=>this.fetchBlobContent({sha:t,repoURL:n,parseText:i})),S.localForage,i)}async fetchBlobContent({sha:e,repoURL:t,parseText:r}){if(!r)return super.fetchBlobContent({sha:e,repoURL:t,parseText:r});const{owner:n,name:i}=this.getOwnerAndNameFromRepoUrl(t),{isNull:o,isBinary:a,text:s}=await this.retrieveBlobObject(n,i,e,{fetchPolicy:pa});if(o)throw new S.APIError("Not Found",404,"GitHub");return a?super.fetchBlobContent({sha:e,repoURL:t,parseText:r}):s}async getPullRequestAuthor(e){const t=e.user;return(null==t?void 0:t.name)||(null==t?void 0:t.login)}async getPullRequests(e,t,r){const{originRepoOwner:n,originRepoName:i}=this;let o;o=t===st.Open?["OPEN"]:t===st.Closed?["CLOSED","MERGED"]:["OPEN","CLOSED","MERGED"];const{data:a}=await this.query({query:Ho,variables:la(la({owner:n,name:i},e?{head:e}:{}),{},{states:o})}),{pullRequests:s}=a.repository;return s.nodes.map(ma).filter((e=>e.head.ref.startsWith(`${S.CMS_BRANCH_PREFIX}/`)&&r(e)))}async getOpenAuthoringBranches(){const{repoOwner:e,repoName:t}=this,{data:r}=await this.query({query:zo,variables:{owner:e,name:t,refPrefix:`refs/heads/cms/${this.repo}/`}});return r.repository.refs.nodes.map((({name:e,prefix:t})=>({ref:`${t}${e}`})))}async getStatuses(e,t){const r=this.generateContentKey(e,t),n=(0,S.branchFromContentKey)(r),i=(await this.getBranchPullRequest(n)).head.sha,{originRepoOwner:o,originRepoName:a}=this,{data:s}=await this.query({query:Uo,variables:{owner:o,name:a,sha:i}});if(s.repository.object){const{status:e}=s.repository.object,{contexts:t}=e||{contexts:[]};return t}return[]}getAllFiles(e,t){return e.reduce(((e,r)=>{if("tree"===r.type){var n;const i=(null===(n=r.object)||void 0===n?void 0:n.entries)||[];return[...e,...this.getAllFiles(i,`${t}/${r.name}`)]}return"blob"===r.type?[...e,{name:r.name,type:r.type,id:r.sha,path:`${t}/${r.name}`,size:r.blob?r.blob.size:0}]:e}),[])}async listFiles(e,{repoURL:t=this.repoURL,branch:r=this.branch,depth:n=1}={}){const{owner:i,name:o}=this.getOwnerAndNameFromRepoUrl(t),a=ae()(e,"/"),{data:s}=await this.query({query:$o(n),variables:{owner:i,name:o,expression:`${r}:${a}`}});return s.repository.object?this.getAllFiles(s.repository.object.entries,a):[]}getBranchQualifiedName(e){return`refs/heads/${e}`}getBranchQuery(e,t,r){return{query:Vo,variables:{owner:t,name:r,qualifiedName:this.getBranchQualifiedName(e)}}}async getDefaultBranch(){const{data:e}=await this.query(la({},this.getBranchQuery(this.branch,this.originRepoOwner,this.originRepoName)));return e.repository.branch}async getBranch(e){const{data:t}=await this.query(la(la({},this.getBranchQuery(e,this.repoOwner,this.repoName)),{},{fetchPolicy:pa}));if(!t.repository.branch)throw new S.APIError("Branch not found",404,it);return t.repository.branch}async patchRef(e,t,r,n={}){if("heads"!==e)return super.patchRef(e,t,r,n);const i=n.force||!1,o=await this.getBranch(t),{data:a}=await this.mutate({mutation:Xo,variables:{input:{oid:r,refId:o.id,force:i}}});return a.updateRef.branch}async deleteBranch(e){const t=await this.getBranch(e),{data:r}=await this.mutate({mutation:ea,variables:{deleteRefInput:{refId:t.id}},update:e=>e.data.delete(fi(t))});return r.deleteRef}getPullRequestQuery(e){const{originRepoOwner:t,originRepoName:r}=this;return{query:Wo,variables:{owner:t,name:r,number:e}}}async getPullRequest(e){const{data:t}=await this.query(la(la({},this.getPullRequestQuery(e)),{},{fetchPolicy:pa})),r="OPEN"===t.repository.pullRequest.state?st.Open:st.Closed;return la(la({},t.repository.pullRequest),{},{state:r})}getPullRequestAndBranchQuery(e,t){const{repoOwner:r,repoName:n}=this,{originRepoOwner:i,originRepoName:o}=this;return{query:Jo,variables:{owner:r,name:n,originRepoOwner:i,originRepoName:o,number:t,qualifiedName:this.getBranchQualifiedName(e)}}}async getPullRequestAndBranch(e,t){const{data:r}=await this.query(la(la({},this.getPullRequestAndBranchQuery(e,t)),{},{fetchPolicy:pa})),{repository:n,origin:i}=r;return{branch:n.branch,pullRequest:i.pullRequest}}async openPR(e){const t=await this.getPullRequest(e),{data:r}=await this.mutate({mutation:ua,variables:{reopenPullRequestInput:{pullRequestId:t.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.reopenPullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}});return r.reopenPullRequest}async closePR(e){const t=await this.getPullRequest(e),{data:r}=await this.mutate({mutation:ra,variables:{closePullRequestInput:{pullRequestId:t.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.closePullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}});return r.closePullRequest}async deleteUnpublishedEntry(e,t){try{const r=this.generateContentKey(e,t),n=(0,S.branchFromContentKey)(r),i=await this.getBranchPullRequest(n);if(i.number!==ot){const{branch:e,pullRequest:t}=await this.getPullRequestAndBranch(n,i.number),{data:r}=await this.mutate({mutation:na,variables:{deleteRefInput:{refId:e.id},closePullRequestInput:{pullRequestId:t.id}},update:r=>{r.data.delete(fi(e)),r.data.delete(fi(t))}});return r.closePullRequest}return await this.deleteBranch(n)}catch(e){const{graphQLErrors:t}=e;if(t&&t.length>0){const e=t.some((e=>"NOT_FOUND"===e.type));if(e)return}throw e}}async createPR(e,t){const[r,n]=await Promise.all([this.getRepository(this.originRepoOwner,this.originRepoName),this.useOpenAuthoring?`${(await this.user()).login}:${t}`:t]),{data:i}=await this.mutate({mutation:oa,variables:{createPullRequestInput:{baseRefName:this.branch,body:S.DEFAULT_PR_BODY,title:e,headRefName:n,repositoryId:r.id}},update:(e,{data:t})=>{const{pullRequest:r}=t.createPullRequest,n={repository:la(la({},r.repository),{},{pullRequest:r})};e.writeQuery(la(la({},this.getPullRequestQuery(r.number)),{},{data:n}))}}),{pullRequest:o}=i.createPullRequest;return la(la({},o),{},{head:{sha:o.headRefOid}})}async createBranch(e,t){const r=this.repoOwner,n=this.repoName,i=await this.getRepository(r,n),{data:o}=await this.mutate({mutation:aa,variables:{createRefInput:{name:this.getBranchQualifiedName(e),oid:t,repositoryId:i.id}},update:(t,{data:i})=>{const{branch:o}=i.createRef,a={repository:la(la({},o.repository),{},{branch:o})};t.writeQuery(la(la({},this.getBranchQuery(e,r,n)),{},{data:a}))}}),{branch:a}=o.createRef;return la(la({},a),{},{ref:`${a.prefix}${a.name}`})}async createBranchAndPullRequest(e,t,r){const n=this.originRepoOwner,i=this.originRepoName,o=await this.getRepository(n,i),{data:a}=await this.mutate({mutation:sa,variables:{createRefInput:{name:this.getBranchQualifiedName(e),oid:t,repositoryId:o.id},createPullRequestInput:{baseRefName:this.branch,body:S.DEFAULT_PR_BODY,title:r,headRefName:e,repositoryId:o.id}},update:(t,{data:r})=>{const{branch:o}=r.createRef,{pullRequest:a}=r.createPullRequest,s={repository:la(la({},o.repository),{},{branch:o})},u={repository:la(la({},a.repository),{},{branch:o}),origin:la(la({},a.repository),{},{pullRequest:a})};t.writeQuery(la(la({},this.getBranchQuery(e,n,i)),{},{data:s})),t.writeQuery(la(la({},this.getPullRequestAndBranchQuery(e,a.number)),{},{data:u}))}}),{pullRequest:s}=a.createPullRequest;return ma(s)}async getFileSha(e,{repoURL:t=this.repoURL,branch:r=this.branch}={}){const{owner:n,name:i}=this.getOwnerAndNameFromRepoUrl(t),{data:o}=await this.query({query:Yo,variables:{owner:n,name:i,expression:`${r}:${e}`}});if(o.repository.file)return o.repository.file.sha;throw new S.APIError("Not Found",404,it)}}function va(){return va=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},va.apply(this,arguments)}function ga(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ba(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ga(Object(r),!0).forEach((function(t){wa(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ga(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function wa(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const{fetchWithTimeout:Ra}=S.unsentRequest,Ea="https://www.githubstatus.com",Oa=`${Ea}/api/v2/components.json`,Sa=["API Requests","Issues, Pull Requests, Projects"],ka={GitHubBackend:class{constructor(e,t={}){var r;if(wa(this,"lock",void 0),wa(this,"api",void 0),wa(this,"options",void 0),wa(this,"originRepo",void 0),wa(this,"repo",void 0),wa(this,"openAuthoringEnabled",void 0),wa(this,"useOpenAuthoring",void 0),wa(this,"alwaysForkEnabled",void 0),wa(this,"branch",void 0),wa(this,"apiRoot",void 0),wa(this,"mediaFolder",void 0),wa(this,"previewContext",void 0),wa(this,"token",void 0),wa(this,"squashMerges",void 0),wa(this,"cmsLabelPrefix",void 0),wa(this,"useGraphql",void 0),wa(this,"_currentUserPromise",void 0),wa(this,"_userIsOriginMaintainerPromises",void 0),wa(this,"_mediaDisplayURLSem",void 0),wa(this,"getCursorAndFiles",((e,t)=>{const r=e.length,n=Math.ceil(e.length/20),i=[];return t>1&&(i.push("prev"),i.push("first")),t<n&&(i.push("next"),i.push("last")),{cursor:S.Cursor.create({actions:i,meta:{page:t,count:r,pageSize:20,pageCount:n},data:{files:e}}),files:e.slice(20*(t-1),20*t)}})),this.options=ba({proxied:!1,API:null,initialWorkflowStatus:""},t),!this.options.proxied&&(null===e.backend.repo||void 0===e.backend.repo))throw new Error('The GitHub backend needs a "repo" in the backend configuration.');if(this.api=this.options.API||null,this.openAuthoringEnabled=e.backend.open_authoring||!1,this.openAuthoringEnabled){if(!this.options.useWorkflow)throw new Error("backend.open_authoring is true but publish_mode is not set to editorial_workflow.");this.originRepo=e.backend.repo||""}else this.repo=this.originRepo=e.backend.repo||"";this.alwaysForkEnabled=e.backend.always_fork||!1,this.branch=(null===(r=e.backend.branch)||void 0===r?void 0:r.trim())||"master",this.apiRoot=e.backend.api_root||"https://api.github.com",this.token="",this.squashMerges=e.backend.squash_merges||!1,this.cmsLabelPrefix=e.backend.cms_label_prefix||"",this.useGraphql=e.backend.use_graphql||!1,this.mediaFolder=e.media_folder,this.previewContext=e.backend.preview_context||"",this.lock=(0,S.asyncLock)()}isGitBackend(){return!0}async status(){const e=await Ra(Oa).then((e=>e.json())).then((e=>e.components.filter((e=>Sa.includes(e.name))).every((e=>"operational"===e.status)))).catch((e=>(console.warn("Failed getting GitHub status",e),!0)));let t=!1;var r;return e&&(t=await(null===(r=this.api)||void 0===r?void 0:r.getUser().then((e=>!!e)).catch((e=>(console.warn("Failed getting GitHub user",e),!1))))||!1),{auth:{status:t},api:{status:e,statusPage:Ea}}}authComponent(){const e=e=>(0,P.jsx)(ie,va({},e,{backend:this}));return e.displayName="AuthenticationPage",e}restoreUser(e){return this.openAuthoringEnabled?this.authenticateWithFork({userData:e,getPermissionToFork:()=>!0}).then((()=>this.authenticate(e))):this.authenticate(e)}async pollUntilForkExists({repo:e,token:t}){let r=!1;for(;!r;)r=await Ra(`${this.apiRoot}/repos/${e}`,{headers:{Authorization:`token ${t}`}}).then((()=>!0)).catch((e=>e&&404===e.status?(console.log("This 404 was expected and handled appropriately."),!1):Promise.reject(e))),r||await new Promise((e=>setTimeout(e,250)));return Promise.resolve()}async currentUser({token:e}){return this._currentUserPromise||(this._currentUserPromise=Ra(`${this.apiRoot}/user`,{headers:{Authorization:`token ${e}`}}).then((e=>e.json()))),this._currentUserPromise}async userIsOriginMaintainer({username:e,token:t}){const r=e||(await this.currentUser({token:t})).login;return this._userIsOriginMaintainerPromises=this._userIsOriginMaintainerPromises||{},this._userIsOriginMaintainerPromises[r]||(this._userIsOriginMaintainerPromises[r]=Ra(`${this.apiRoot}/repos/${this.originRepo}/collaborators/${r}/permission`,{headers:{Authorization:`token ${t}`}}).then((e=>e.json())).then((({permission:e})=>"admin"===e||"write"===e))),this._userIsOriginMaintainerPromises[r]}async forkExists({token:e}){try{const t=await this.currentUser({token:e}),r=this.originRepo.split("/")[1],n=await Ra(`${this.apiRoot}/repos/${t.login}/${r}`,{method:"GET",headers:{Authorization:`token ${e}`}}).then((e=>e.json()));return!0===n.fork&&n.parent&&n.parent.full_name.toLowerCase()===this.originRepo.toLowerCase()}catch{return!1}}async authenticateWithFork({userData:e,getPermissionToFork:t}){if(!this.openAuthoringEnabled)throw new Error("Cannot authenticate with fork; Open Authoring is turned off.");const r=e.token;if(!this.alwaysForkEnabled&&await this.userIsOriginMaintainer({token:r}))return this.repo=this.originRepo,this.useOpenAuthoring=!1,Promise.resolve();const n=await this.currentUser({token:r}),i=this.originRepo.split("/")[1];if(this.repo=`${n.login}/${i}`,this.useOpenAuthoring=!0,await this.forkExists({token:r}))return Ra(`${this.apiRoot}/repos/${this.repo}/merge-upstream`,{method:"POST",headers:{Authorization:`token ${r}`},body:JSON.stringify({branch:this.branch})});{await t();const e=await Ra(`${this.apiRoot}/repos/${this.originRepo}/forks`,{method:"POST",headers:{Authorization:`token ${r}`}}).then((e=>e.json()));return this.pollUntilForkExists({repo:e.full_name,token:r})}}async authenticate(e){this.token=e.token;const t=this.useGraphql?ya:ht;this.api=new t({token:this.token,branch:this.branch,repo:this.repo,originRepo:this.originRepo,apiRoot:this.apiRoot,squashMerges:this.squashMerges,cmsLabelPrefix:this.cmsLabelPrefix,useOpenAuthoring:this.useOpenAuthoring,initialWorkflowStatus:this.options.initialWorkflowStatus});const r=await this.api.user();if(!await this.api.hasWriteAccess().catch((e=>{throw e.message=O`
304
304
  Repo "${this.repo}" not found.
305
305
 
306
306
  Please ensure the repo information is spelled correctly.