All files / src Client.ts

93.84% Statements 61/65
92.64% Branches 63/68
80% Functions 8/10
96.82% Lines 61/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 3166x   6x 6x   6x 6x                                   50x 50x 50x 50x 1x 1x 1x   49x 49x 49x     50x 50x 50x 50x 50x 50x                                                                                         55x 1x       54x 1x       53x 1x       52x 1x       51x 1x         50x   50x 1x 1x 49x 6x   43x   50x                           80x                                           91x 1x       90x                               6x 5x 5x 3x   3x 2x           1x             3x 3x                                     4x                                                                                                   4x 4x                     4x 4x                                         8x 8x               8x 8x    
import axios from "axios";
import { ClientConfig } from "./interfaces/Config";
import { findExpiryTime } from "./utils";
import { API_DOMAIN, TOKEN_GENERATION_API, PAT_TOKEN_EXCHANGE_API, CLIENT_SOURCE_EXCEL, CLIENT_SOURCE_SDK } from "./Constants";
 
export class Client {
  private static instance: Client | null = null;
 
  private token: string;
  private readonly apiKey: string;
  private readonly patToken: string;
  private readonly clientId: string;
  private readonly orgId: string;
  private expiresAt: number;
  private readonly domain: string;
  private readonly tokenDomain: string;
  private readonly isUserProvidedToken: boolean;
  private readonly clientSource: string;
 
  private constructor(
    token: string,
    config: ClientConfig,
    isUserProvidedToken = false
  ) {
    const { apiKey="", patToken="", clientId, orgId="", host, authUrl, isExcelAddIn=false } = config;
    this.token = token;
    this.clientId = clientId;
    if (isUserProvidedToken) {
      this.apiKey = "";
      this.patToken = "";
      this.orgId = "";
    } else {
      this.apiKey = apiKey;
      this.patToken = patToken;
      this.orgId = orgId;
    }
 
    const exp = findExpiryTime(token);
    this.expiresAt = exp;
    this.domain = host ?? API_DOMAIN;
    this.tokenDomain = authUrl ?? (patToken ? PAT_TOKEN_EXCHANGE_API : TOKEN_GENERATION_API);
    this.isUserProvidedToken = isUserProvidedToken;
    this.clientSource = isExcelAddIn === true ? CLIENT_SOURCE_EXCEL : CLIENT_SOURCE_SDK;
  }
 
/**
 * Initializes and returns a Client instance with the provided configuration.
 *
 * @static
 * @param {ClientConfig} config - The client configuration object
 * @return {Promise<void>} A promise that resolves when the client is initialized
 * @throws {Error} Throws an error if:
 *  - custom "host" is provided without "authUrl"
 *  - token is provided without "clientId"
 *  - apiKey is provided without "clientId" or "orgId"
 *  - patToken is provided without "clientId" or with "orgId"
 *
 * @example
 * // Initialize with authentication URL
 * await Client.getClient({
 *   host: 'https://api.example.com',
 *   authUrl: 'https://auth.example.com',
 *   clientId: 'client123',
 *   orgId: 'org456'
 * });
 *
 * // Initialize with existing token
 * await Client.getClient({
 *   token: 'existing-jwt-token',
 *   clientId: 'client123'
 * });
 *
 * // Initialize with API key
 * await Client.getClient({
 *   apiKey: 'your-api-key',
 *   clientId: 'client123',
 *   orgId: 'org456'
 * });
 *
 * // Initialize with PAT token
 * await Client.getClient({
 *   patToken: 'your-personal-access-token',
 *   clientId: 'client123'
 * });
 */
 
  public static async getClient(config: ClientConfig): Promise<void> {
    if (config.host && !config.authUrl) {
      throw new Error(
        'If custom "host" is provided, "authUrl" must also be provided.'
      );
    }
    if (config.token && !config.clientId) {
      throw new Error(
        'If token is provided directly, "clientId" must also be provided.'
      );
    }
    if(config.apiKey && (!config.orgId || !config.clientId)){
      throw new Error(
        'If apiKey is provided , "clientId" and "OrgId" must also be provided.'
      );
    }
    if(config.patToken && !config.clientId){
      throw new Error(
        'If patToken is provided, "clientId" must also be provided.'
      );
    }
    if(config.patToken && config.orgId){
      throw new Error(
        'orgId should not be provided when using patToken.'
      );
    }
    let token: string;
    let isUserProvidedToken = false;
 
    if (config.token && config.clientId) {
      token = config.token;
      isUserProvidedToken = true;
    } else if (config.patToken && config.clientId) {
      token = await Client.requestTokenFromPAT(config);
    } else {
      token = await Client.requestToken(config);
    }
    Client.instance = new Client(token, config, isUserProvidedToken);
  }
 
  /**
   * Returns the domain URL configured for the client.
   * 
   * @return {string} The domain URL string
   * 
   * @example
   * const client = Client.getInstance();
   * const apiDomain = client.getDomain();
   * console.log(apiDomain); // e.g., 'https://api.example.com'
   */
  public getDomain(): string {
    return this.domain;
  }
 
  /**
   * Returns the singleton instance of the Client.
   * 
   * @static
   * @return {Client} The singleton Client instance
   * @throws {Error} Throws an error if the Client has not been initialized with getClient()
   * 
   * @example
   * // First initialize the client
   * await Client.getClient({
   *   clientId: 'client123',
   *   orgId: 'org456'
   * });
   * 
   * // Then get the instance
   * const client = Client.getInstance();
   * // Use the client...
   */
  public static getInstance(): Client {
    if (!Client.instance) {
      throw new Error(
        "Client is not initialized. Call Client.getClient() first."
      );
    }
    return Client.instance;
  }
 
  /**
   * Refreshes the authentication token if it's about to expire.
   * Only refreshes if the token was not provided by the user and is expiring within 60 seconds.
   * 
   * @return {Promise<void>} A promise that resolves when the token refresh is complete
   * 
   * @example
   * const client = Client.getInstance();
   * // Ensure token is fresh before making API requests
   * await client.refreshToken();
   * // Proceed with API requests...
   */
  public async refreshToken(): Promise<void> {
    if (!this.isUserProvidedToken) {
      const now = Math.floor(Date.now() / 1000);
      if (this.expiresAt - now < 60) {
        console.log("[SDK] Refreshing token...");
        let token: string;
        if (this.patToken) {
          token = await Client.requestTokenFromPAT({
            patToken: this.patToken,
            clientId: this.clientId,
            authUrl: this.tokenDomain,
          });
        } else {
          token = await Client.requestToken({
            apiKey: this.apiKey,
            clientId: this.clientId,
            orgId: this.orgId,
            authUrl: this.tokenDomain,
          });
        }
        this.token = token;
        this.expiresAt = findExpiryTime(token);
      }
    }
  }
 
  /**
   * Returns the authorization header object with the Bearer token.
   * 
   * @return {Record<string, string>} An object containing the Authorization header with the Bearer token
   * 
   * @example
   * const client = Client.getInstance();
   * const headers = {
   *   'Content-Type': 'application/json',
   *   ...client.getAuthHeader()
   * };
   * // headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer token...' }
   */
  public getAuthHeader(): Record<string, string> {
    return { Authorization: `Bearer ${this.token}` };
  }
  
  /**
   * Returns the client ID configured for this client instance.
   * 
   * @return {string} The client ID string
   * 
   * @example
   * const client = Client.getInstance();
   * const clientId = client.getClientId();
   * console.log(clientId); // e.g., 'client123'
   */
  public getClientId(): string {
    return this.clientId;
  }
 
  /**
   * Returns the client source identifier for this client instance.
   * 
   * @return {string} The client source string
   * 
   * @example
   * const client = Client.getInstance();
   * const source = client.getClientSource();
   * console.log(source); // e.g., 'web', 'mobile', 'sdk'
   */
  public getClientSource() : string {
    return this.clientSource;
  }
 
  /**
   * Requests an authentication token from the token generation API.
   * 
   * @private
   * @static
   * @param {ClientConfig} config - The client configuration containing authentication details
   * @return {Promise<string>} A promise that resolves to the authentication token string
   * @throws {Error} Throws an error if the token response is empty
   * 
   * @example
   * // Internal usage within the Client class
   * const token = await Client.requestToken({
   *   apiKey: 'your-api-key',
   *   clientId: 'client123',
   *   orgId: 'org456',
   *   authUrl: 'https://custom-auth.example.com/token'
   * });
   */
  private static async requestToken(config: ClientConfig): Promise<string> {
    const tokenUrl = config.authUrl ?? TOKEN_GENERATION_API;
    const res = await axios.get(tokenUrl, {
      headers: {
        "X-Api-Key": config.apiKey,
        "X-IBM-Client-Id": `saascore-${config.clientId}`,
        accept: "application/json",
      },
      params: {
        orgId: config.orgId
      }
    });
 
    Iif (!res.data) throw new Error("Token response is empty");
    return String(res.data).trim();
  }
 
  /**
   * Requests an authentication token by exchanging a Personal Access Token (PAT).
   *
   * @private
   * @static
   * @param {ClientConfig} config - The client configuration containing PAT and client details
   * @return {Promise<string>} A promise that resolves to the authentication token string
   * @throws {Error} Throws an error if the token response is empty
   *
   * @example
   * // Internal usage within the Client class
   * const token = await Client.requestTokenFromPAT({
   *   patToken: 'your-personal-access-token',
   *   clientId: 'client123',
   *   authUrl: 'https://custom-auth.example.com/exchange'
   * });
   */
  private static async requestTokenFromPAT(config: ClientConfig): Promise<string> {
    const tokenUrl = config.authUrl ?? PAT_TOKEN_EXCHANGE_API;
    const res = await axios.post(tokenUrl, null, {
      headers: {
        "X-IBM-Client-Id": `saascore-${config.clientId}`,
        "X-IBM-Envizi-Pat": config.patToken,
        accept: "application/json",
      }
    });
 
    Iif (!res.data) throw new Error("Token response is empty");
    return String(res.data).trim();
  }
}