import { JSONSchema } from '@apidevtools/json-schema-ref-parser' ; import { isNull } from 'lodash' ; import camelCase from 'lodash/camelCase' ; import isArray from 'lodash/isArray' ; import isObject from 'lodash/isObject' ; import isUndefined from 'lodash/isUndefined' ; import { AHStats , APIKey , APIKeyCode , AuthorizerAction , ChangeLog , ChartTemplatesData , CheckAvailabilityProps , Error , ErrorKind , EventKind , LogoImage , Member , OptOutItem , Organization , OrganizationPolicy , Package , PackageStars , PackageViewsStats , Profile , RegoPlaygroundPolicy , RegoPlaygroundResult , Repository , SearchQuery , SearchResults , SecurityReport , SecurityReportResult , Stats , Subscription , TestWebhook , TsQuery , TwoFactorAuth , User , UserFullName , UserLogin , Webhook , } from '../types' ; import { TS_QUERY } from '../utils/data' ; import { getURLSearchParams , prepareAPIQueryString } from '../utils/prepareQueryString' ; import renameKeysInObject from '../utils/renameKeysInObject' ; interface PackageRequest { packageName : string ; repositoryKind : string ; repositoryName : string ; version ? : string ; } interface TransferRepositoryRequest { repositoryName : string ; toOrgName ? : string ; fromOrgName ? : string ; } interface Result { [ key ] : any ; } interface FetchOptions { method : 'POST' | 'GET' | 'PUT' | 'DELETE' | 'HEAD' ; headers ? : { [ key ] : string ; } ; body ? : any ; } interface APIFetchProps { url : string ; opts ? : FetchOptions ; skipCamelConversion ? : boolean ; checkApprovedSession ? : boolean ; headers ? : string [ ] ; } type SecurityReportRaw = { [ key ] : { Results : SecurityReportResult [ ] ; } | SecurityReportResult [ ] ; } ; class API_CLASS { private EXCEPTIONS = [ 'policies' , 'rules' , 'policyData' , 'roles' , 'crds' , 'crdsExamples' , 'crds_examples' ] ; private HEADERS = { csrf : 'X-Csrf-Token' , sessionApproved : 'X-Session-Approved' , pagination : 'Pagination-Total-Count' , } ; private csrfToken : string | null = null ; private API_BASE_URL = '/api/v1' ; private toCamelCase ( r ) { if ( isArray ( r ) ) { return r . map ( ( v ) => this . toCamelCase ( v ) ) ; } else if ( isObject ( r ) ) { return Object . keys ( r ) . reduce ( ( result , key ) => { return { ... result , [ camelCase ( key ) ] : this . EXCEPTIONS . includes ( key ) ? ( r as Result ) [ key ] : this . toCamelCase ( ( r as Result ) [ key ] ) , } ; } , { } ) ; } return r ; } private async handleErrors ( res ) { if ( ! res . ok ) { let error ; switch ( res . status ) { case 401 : try { let text = await res . json ( ) ; error = { kind : ErrorKind . Unauthorized , message : text . message !== '' ? text . message : undefined , } ; } catch { error = { kind : ErrorKind . Unauthorized , } ; } break ; case 404 : error = { kind : ErrorKind . NotFound , } ; break ; case 403 : try { const er = await res . text ( ) ; if ( er . includes ( 'CSRF token invalid' ) ) { this . csrfToken = null ; error = { kind : ErrorKind . InvalidCSRF , } ; } else { error = { kind : ErrorKind . Forbidden , } ; } } catch { error = { kind : ErrorKind . Forbidden , } ; } break ; case 410 : error = { kind : ErrorKind . Gone , } ; break ; default : try { let text = await res . json ( ) ; error = { kind : ErrorKind . Other , message : text . message !== '' ? text . message : undefined , } ; } catch { error = { kind : ErrorKind . Other , } ; } } throw error ; } return res ; } private checkIfApprovedSession ( res ) { if ( res . headers . has ( this . HEADERS . sessionApproved ) ) { const isApproved = res . headers . get ( this . HEADERS . sessionApproved ) ; if ( isApproved === 'false' ) { const err = { kind : ErrorKind . NotApprovedSession , } ; throw err ; } else { return res ; } } else { return res ; } } private getHeadersValue ( res , params ? ) { if ( ! isUndefined ( params ) && params . length > 0 ) { let headers = { } ; params . forEach ( ( param ) => { if ( res . headers . has ( param ) ) { headers [ param ] = res . headers . get ( param ) ; } } ) ; return headers ; } return null ; } private async handleContent ( res , skipCamelConversion ? , checkApprovedSession ? , headers ? ) { let response = res ; if ( ! isUndefined ( checkApprovedSession ) && checkApprovedSession ) { response = this . checkIfApprovedSession ( res ) ; } switch ( response . headers . get ( 'Content-Type' ) ) { case 'text/plain; charset=utf-8' : case 'text/markdown' : case 'application/yaml' : const text = await response . text ( ) ; return text ; case 'application/json' : let json = await response . json ( ) ; const tmpHeaders = this . getHeadersValue ( res , headers ) ; if ( ! isNull ( tmpHeaders ) ) { if ( isArray ( json ) ) { json = { items : json } ; } json = { ... json , ... tmpHeaders } ; } return skipCamelConversion ? json : this . toCamelCase ( json ) ; default : return response ; } } private async processFetchOptions ( opts ? ) { let options = opts || { } ; if ( opts && [ 'DELETE' , 'POST' , 'PUT' ] . includes ( opts . method ) ) { if ( isNull ( this . csrfToken ) ) { this . csrfToken = await this . getCSRFToken ( ) ; if ( isNull ( this . csrfToken ) ) { const error = { kind : ErrorKind . Other } ; throw error ; } } return { ... options , headers : { ... options . headers , [ this . HEADERS . csrf ] : this . csrfToken , } , } ; } return options ; } private async apiFetch ( props ) { const csrfRetry = ( func ) => { return func ( ) . catch ( ( error ) => { if ( error . kind === ErrorKind . InvalidCSRF ) { return func ( ) . catch ( ( error ) => Promise . reject ( error ) ) ; } else { return Promise . reject ( error ) ; } } ) ; } ; return csrfRetry ( async ( ) => { let options = await this . processFetchOptions ( props . opts ) ; return fetch ( props . url , options ) . then ( this . handleErrors ) . then ( ( res ) => this . handleContent ( res , props . skipCamelConversion , props . checkApprovedSession , props . headers ) ) . catch ( ( error ) => Promise . reject ( error ) ) ; } ) ; } private getUrlContext ( fromOrgName ? ) { let context = '/user' ; if ( ! isUndefined ( fromOrgName ) ) { context = `/org/${ fromOrgName }` ; } return context ; } public getPackage ( request ) { let url = `${ this . API_BASE_URL }/packages/${ request . repositoryKind }/${ request . repositoryName }/${ request . packageName }` ; if ( ! isUndefined ( request . version ) ) { url += `/${ request . version }` ; } return this . apiFetch ( { url : url } ) ; } public toggleStar ( packageId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/stars` , opts : { method : 'PUT' , } , } ) ; } public getStars ( packageId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/stars` } ) ; } public searchPackages ( query , facets = true ) { const q = getURLSearchParams ( query ) ; q . set ( 'facets' , facets ? 'true' : 'false' ) ; if ( ! isUndefined ( query . tsQuery ) ) { let values = [ ] ; query . tsQuery . forEach ( ( value ) => { if ( value !== '' ) { const activeTsQuery = TS_QUERY . find ( ( ts ) => ts . label === value ) ; if ( ! isUndefined ( activeTsQuery ) ) { values . push ( activeTsQuery . value ) ; } } } ) ; if ( values . length > 0 ) { q . set ( 'ts_query' , values . join ( ' | ' ) ) ; } } q . set ( 'sort' , query . sort || 'relevance' ) ; q . set ( 'limit' , query . limit . toString ( ) ) ; q . set ( 'offset' , query . offset . toString ( ) ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/search?${ q . toString ( ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public getStats ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/stats` } ) ; } public getRandomPackages ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/random` } ) ; } public getCSRFToken ( ) { const tokenError = { kind : ErrorKind . Other } ; return fetch ( `${ this . API_BASE_URL }/csrf` ) . then ( ( res ) => { if ( ! res . ok ) { throw tokenError ; } else { if ( res . headers . has ( this . HEADERS . csrf ) ) { const token = res . headers . get ( this . HEADERS . csrf ) ; return token === '' ? null : token ; } else { throw tokenError ; } } } ) ; } public register ( user ) { const newUser = renameKeysInObject ( user , { firstName : 'first_name' , lastName : 'last_name' } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/users` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( newUser ) , } , } ) ; } public verifyEmail ( code ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/verify-email` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { code : code , } ) , } , } ) ; } public login ( user ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/login` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { email : user . email , password : user . password , } ) , } , checkApprovedSession : true , } ) ; } public logout ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/logout` } ) ; } public getUserProfile ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/profile` } ) ; } public checkPasswordStrength ( pwd ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/check-password-strength` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { password : pwd , } ) , } , } ) ; } public searchRepositories ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories/search${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public addRepository ( repository , fromOrgName ? ) { const repo = renameKeysInObject ( repository , { displayName : 'display_name' , authUser : 'auth_user' , authPass : 'auth_pass' , scannerDisabled : 'scanner_disabled' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories${ this . getUrlContext ( fromOrgName ) }` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( repo ) , } , } ) ; } public deleteRepository ( repositoryName , fromOrgName ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories${ this . getUrlContext ( fromOrgName ) }/${ repositoryName }` , opts : { method : 'DELETE' , } , } ) ; } public updateRepository ( repository , fromOrgName ? ) { const repo = renameKeysInObject ( repository , { displayName : 'display_name' , authUser : 'auth_user' , authPass : 'auth_pass' , scannerDisabled : 'scanner_disabled' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories${ this . getUrlContext ( fromOrgName ) }/${ repository . name }` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( repo ) , } , } ) ; } public transferRepository ( params ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories${ this . getUrlContext ( params . fromOrgName ) }/${ params . repositoryName }/transfer${ isUndefined ( params . toOrgName ) ? '' : `?org=${ params . toOrgName }` }` , opts : { method : 'PUT' , } , } ) ; } public claimRepositoryOwnership ( repo , toOrgName ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/repositories${ this . getUrlContext ( repo . organizationName || undefined ) }/${ repo . name }/claim-ownership${ isUndefined ( toOrgName ) ? '' : `?org=${ toOrgName }` }` , opts : { method : 'PUT' , } , } ) ; } public async checkAvailability ( props ) { return fetch ( `${ this . API_BASE_URL }/check-availability/${ props . resourceKind }?v=${ encodeURIComponent ( props . value ) }` , { method : 'HEAD' , } ) . then ( ( res ) => { switch ( res . status ) { case 404 : return Promise . resolve ( false ) ; default : return Promise . resolve ( true ) ; } } ) . catch ( ( ) => { return Promise . resolve ( true ) ; } ) ; } public getUserOrganizations ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/user${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public getOrganization ( organizationName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ organizationName }` } ) ; } public addOrganization ( organization ) { const org = renameKeysInObject ( organization , { displayName : 'display_name' , logoImageId : 'logo_image_id' , homeUrl : 'home_url' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( org ) , } , } ) ; } public updateOrganization ( organization , name ) { const org = renameKeysInObject ( organization , { displayName : 'display_name' , logoImageId : 'logo_image_id' , homeUrl : 'home_url' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ name }` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( org ) , } , } ) ; } public deleteOrganization ( orgName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ orgName }` , opts : { method : 'DELETE' , } , } ) ; } public getOrganizationMembers ( query , organizationName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ organizationName }/members${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public addOrganizationMember ( organizationName , alias ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ organizationName }/member/${ encodeURI ( alias ) }` , opts : { method : 'POST' , } , } ) ; } public deleteOrganizationMember ( organizationName , alias ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ organizationName }/member/${ encodeURI ( alias ) }` , opts : { method : 'DELETE' , } , } ) ; } public confirmOrganizationMembership ( organizationName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ organizationName }/accept-invitation` } ) ; } public getStarredByUser ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/starred${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public updateUserProfile ( profile ) { const updatedProfile = renameKeysInObject ( profile , { firstName : 'first_name' , lastName : 'last_name' , profileImageId : 'profile_image_id' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/profile` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( updatedProfile ) , } , } ) ; } public updatePassword ( oldPassword , newPassword ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/password` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { old : oldPassword , new : newPassword , } ) , } , } ) ; } public saveImage ( data ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/images` , opts : { method : 'POST' , body : data , } , } ) ; } public getPackageSubscriptions ( packageId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions/${ packageId }` } ) ; } public addSubscription ( packageId , eventKind ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { package_id : packageId , event_kind : eventKind , } ) , } , } ) ; } public deleteSubscription ( packageId , eventKind ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions?package_id=${ packageId }&event_kind=${ eventKind }` , opts : { method : 'DELETE' , } , } ) ; } public getUserSubscriptions ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public getWebhooks ( query , fromOrgName ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks${ this . getUrlContext ( fromOrgName ) }${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public getWebhook ( webhookId , fromOrgName ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks${ this . getUrlContext ( fromOrgName ) }/${ webhookId }` } ) ; } public addWebhook ( webhook , fromOrgName ? ) { const formattedWebhook = renameKeysInObject ( webhook , { contentType : 'content_type' , eventKinds : 'event_kinds' } ) ; const formattedPackages = webhook . packages . map ( ( packageItem ) => ( { package_id : packageItem . packageId , } ) ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks${ this . getUrlContext ( fromOrgName ) }` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { ... formattedWebhook , packages : formattedPackages , } ) , } , } ) ; } public deleteWebhook ( webhookId , fromOrgName ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks${ this . getUrlContext ( fromOrgName ) }/${ webhookId }` , opts : { method : 'DELETE' , } , } ) ; } public updateWebhook ( webhook , fromOrgName ? ) { const formattedWebhook = renameKeysInObject ( webhook , { contentType : 'content_type' , eventKinds : 'event_kinds' } ) ; const formattedPackages = webhook . packages . map ( ( packageItem ) => ( { package_id : packageItem . packageId , } ) ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks${ this . getUrlContext ( fromOrgName ) }/${ webhook . webhookId }` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { ... formattedWebhook , packages : formattedPackages } ) , } , } ) ; } public triggerWebhookTest ( webhook ) { const formattedWebhook = renameKeysInObject ( webhook , { contentType : 'content_type' , eventKinds : 'event_kinds' } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/webhooks/test` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( formattedWebhook ) , } , } ) ; } public getAPIKeys ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/api-keys${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public getAPIKey ( apiKeyId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/api-keys/${ apiKeyId }` } ) ; } public addAPIKey ( name ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/api-keys` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { name : name , } ) , } , } ) ; } public updateAPIKey ( apiKeyId , name ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/api-keys/${ apiKeyId }` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { name : name } ) , } , } ) ; } public deleteAPIKey ( apiKeyId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/api-keys/${ apiKeyId }` , opts : { method : 'DELETE' , } , } ) ; } public getOptOutList ( query ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions/opt-out${ prepareAPIQueryString ( query ) }` , headers : [ this . HEADERS . pagination ] , } ) ; } public addOptOut ( repositoryId , eventKind ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions/opt-out` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { repository_id : repositoryId , event_kind : eventKind , } ) , } , } ) ; } public deleteOptOut ( optOutId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/subscriptions/opt-out/${ optOutId }` , opts : { method : 'DELETE' , } , } ) ; } public getAuthorizationPolicy ( orgName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ orgName }/authorization-policy` } ) ; } public updateAuthorizationPolicy ( orgName , policy ) { const formattedPolicy = renameKeysInObject ( { ... policy } , { authorizationEnabled : 'authorization_enabled' , predefinedPolicy : 'predefined_policy' , customPolicy : 'custom_policy' , policyData : 'policy_data' , } ) ; return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ orgName }/authorization-policy` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( formattedPolicy ) , } , } ) ; } public getUserAllowedActions ( orgName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/orgs/${ orgName }/user-allowed-actions` } ) ; } public getSnapshotSecurityReport ( packageId , version , eventId ? ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/${ version }/security-report${ ! isUndefined ( eventId ) ? `?event-id=${ eventId }` : '' }` , skipCamelConversion : true , } ) . then ( ( report ) => { const newFormatReport = { } ; Object . keys ( report ) . forEach ( ( item ) => { if ( isArray ( report [ item ] ) ) { newFormatReport [ item ] = { Results : report [ item ] as SecurityReportResult [ ] , } ; } else if ( isObject ( report [ item ] ) && report [ item ] . hasOwnProperty ( 'Results' ) ) { newFormatReport [ item ] = report [ item ] as { Results : SecurityReportResult [ ] ; } ; } } ) ; return newFormatReport ; } ) ; } public getChartValues ( packageId , version ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/${ version }/values` , } ) ; } public getValuesSchema ( packageId , version ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/${ version }/values-schema` , skipCamelConversion : true , } ) ; } public trackView ( packageId , version ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/${ version }/views` , opts : { method : 'POST' , } , } ) ; } public getViews ( packageId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/views` , skipCamelConversion : true } ) ; } public getChangelog ( packageId ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/changelog` } ) ; } public getChangelogMD ( request ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ request . repositoryKind }/${ request . repositoryName }/${ request . packageName }/changelog.md` , } ) ; } public getChartTemplates ( packageId , version ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ packageId }/${ version }/templates` , skipCamelConversion : true , } ) ; } public requestPasswordResetCode ( email ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/password-reset-code` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { email : email , } ) , } , } ) ; } public verifyPasswordResetCode ( code ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/verify-password-reset-code` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { code : code , } ) , } , } ) ; } public resetPassword ( code , password ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/reset-password` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { code : code , password : password , } ) , } , } ) ; } public getAHStats ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/stats` } ) ; } public setUpTFA ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/tfa` , opts : { method : 'POST' } } ) ; } public enableTFA ( passcode ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/tfa/enable` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { passcode : passcode , } ) , } , } ) ; } public disableTFA ( passcode ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/tfa/disable` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { passcode : passcode , } ) , } , } ) ; } public approveSession ( passcode ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/approve-session` , opts : { method : 'PUT' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { passcode : passcode , } ) , } , } ) ; } public registerDeleteUserCode ( ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users/delete-user-code` , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , } , } ) ; } public deleteUser ( code ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/users` , opts : { method : 'DELETE' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { code : code , } ) , } , } ) ; } public getAllUserOrganizations ( ) { return this . getAllItems ( `${ this . API_BASE_URL }/orgs/user` ) as Promise < Organization [ ] > ; } public getAllOrganizationMembers ( organizationName ) { return this . getAllItems ( `${ this . API_BASE_URL }/orgs/${ organizationName }/members` ) as Promise < Member [ ] > ; } private getAllItems ( url ) { const MAX_LIMIT = 60 ; let formattedUrl = `${ url }?limit=${ MAX_LIMIT }` ; return this . apiFetch ( { url : `${ formattedUrl }&offset=0` , headers : [ this . HEADERS . pagination ] } ) . then ( async ( result ) => { const paginationTotalCount = parseInt ( result . paginationTotalCount ) ; let items = result . items ; if ( paginationTotalCount > MAX_LIMIT ) { const totalPages = Math . ceil ( paginationTotalCount / MAX_LIMIT ) ; const pagesList = Array . from ( Array ( totalPages - 1 ) , ( _ , i ) => i + 1 ) ; await Promise . all ( [ ... pagesList . map ( ( page ) => this . apiFetch ( { url : `${ formattedUrl }&offset=${ page * MAX_LIMIT }` } ) ) , ] ) . then ( ( res ) => res . forEach ( ( list ) => ( items = [ ... items , ... list ] ) ) ) ; return items ; } else { return items ; } } ) ; } public getProductionUsage ( request ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ request . repositoryKind }/${ request . repositoryName }/${ request . packageName }/production-usage` , } ) ; } public addProductionUsage ( request , orgName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ request . repositoryKind }/${ request . repositoryName }/${ request . packageName }/production-usage/${ orgName }` , opts : { method : 'POST' , } , } ) ; } public deleteProductionUsage ( request , orgName ) { return this . apiFetch ( { url : `${ this . API_BASE_URL }/packages/${ request . repositoryKind }/${ request . repositoryName }/${ request . packageName }/production-usage/${ orgName }` , opts : { method : 'DELETE' , } , } ) ; } public triggerTestInRegoPlayground ( data ) { return this . apiFetch ( { url : 'https://play.openpolicyagent.org/v1/share' , opts : { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( data ) , } , } ) ; } public getPublicSignKey ( url ) { return this . apiFetch ( { url : url , } ) ; } } const API = new API_CLASS ( ) ; export default API ;