# All files / src utils.ts

57.25% Statements 75/131
54.65% Branches 47/86
81.25% Functions 13/16
56.69% Lines 72/127

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
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    3471x
    1x

    1x

    1x
    8x

    1x
    8x

    1x
    5x

    1x

    1x
    26x
    1x

    26x

    78x
    78x

    26x
    123x

    123x
    2x

    24x

    1x
    21x
    21x

    21x
    651x
    651x
    651x

    1x
    32x
    32x
    32x

    31x
    31x

    31x

    31x

    1x

    1x
    33x

    33x
    1x

    32x
    32x

    1x

    29x
    29x
    29x
    29x
    29x
    1x

    28x

    28x
    28x

    1x

    9x

    9x
    9x
    9x
    9x

    9x
    9x
    9x
    9x

    1x

    9x

    9x
    9x
    3x
    6x

    6x

    6x
    6x

     import { Logger } from './logger'
    import {
      BadPathError,
      ConflictError,
      DoesNotExist,
      GaiaHubErrorResponse,
      NotEnoughProofError,
      PayloadTooLargeError,
      ValidationError
    } from './errors'

    /**
     *  @ignore
     */
    export const BLOCKSTACK_HANDLER = 'blockstack'

    /**
     * Time
     * @private
     * @ignore
     */
    export function nextYear() {
      return new Date(
        new Date().setFullYear(
          new Date().getFullYear() + 1
        )
      )
    }

    /**
     * Time
     * @private
     * @ignore
     */
    export function nextMonth() {
      return new Date(
        new Date().setMonth(
          new Date().getMonth() + 1
        )
      )
    }

    /**
     * Time
     * @private
     * @ignore
     */
    export function nextHour() {
      return new Date(
        new Date().setHours(
          new Date().getHours() + 1
        )
      )
    }

    /**
     * Query Strings
     * @private
     * @ignore
     */

    export function updateQueryStringParameter(uri: string, key: string, value: string) {
      const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i')
      const separator = uri.indexOf('?') !== -1 ? '&' : '?'
      if (uri.match(re)) {
        return uri.replace(re, `$1${key}=${value}$2`)
      } else {
        return `${uri}${separator}${key}=${value}`
      }
    }

    /**
     * Versioning
     * @param {string} v1 - the left half of the version inequality
     * @param {string} v2 - right half of the version inequality
     * @returns {bool} iff v1 >= v2
     * @private
     * @ignore
     */

    export function isLaterVersion(v1: string, v2: string) {
      if (v1 === undefined) {
        v1 = '0.0.0'
      }

      Iif (v2 === undefined) {
        v2 = '0.0.0'
      }

      const v1tuple = v1.split('.').map(x => parseInt(x, 10))
      const v2tuple = v2.split('.').map(x => parseInt(x, 10))

      for (let index = 0; index < v2.length; index++) {
        Iif (index >= v1.length) {
          v2tuple.push(0)
        }
        if (v1tuple[index] < v2tuple[index]) {
          return false
        }
      }
      return true
    }

    /**
     * UUIDs
     * @private
     * @ignore
     */
    export function makeUUID4() {
      let d = new Date().getTime()
      Iif (typeof performance !== 'undefined' && typeof performance.now === 'function') {
        d += performance.now() // use high-precision timer if available
      }
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
      })
    }

    /**
     * Checks if both urls pass the same origin check & are absolute
     * @param  {[type]}  uri1 first uri to check
     * @param  {[type]}  uri2 second uri to check
     * @return {Boolean} true if they pass the same origin check
     * @private
     * @ignore
     */
    export function isSameOriginAbsoluteUrl(uri1: string, uri2: string) {
      try {
        const parsedUri1 = new URL(uri1)
        const parsedUri2 = new URL(uri2)

        const port1 = parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80)
        const port2 = parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80)

        const match = {
          scheme: parsedUri1.protocol === parsedUri2.protocol,
          hostname: parsedUri1.hostname === parsedUri2.hostname,
          port: port1 === port2,
          absolute: (uri1.includes('http://') || uri1.includes('https://'))
          && (uri2.includes('http://') || uri2.includes('https://'))
        }

        return match.scheme && match.hostname && match.port && match.absolute
      } catch (error) {
        // Parse error
        return false
      }
    }

    /**
     * Returns the global scope `Window`, `WorkerGlobalScope`, or `NodeJS.Global` if available in the
     * currently executing environment.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
     * @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self
     * @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
     *
     * This could be switched to `globalThis` once it is standardized and widely available.
     * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
     * @ignore
     */
    export function getGlobalScope(): Window {
      Iif (typeof self !== 'undefined') {
        return self
      }
      if (typeof window !== 'undefined') {
        return window
      }
      // This function is meant to be called when accessing APIs that are typically only available in
      // web-browser/DOM environments, but we also want to support situations where running in Node.js
      // environment, and a polyfill was added to the Node.js `global` object scope without adding the
      // `window` global object as well.
      Eif (typeof global !== 'undefined') {
        return (global as unknown) as Window
      }
      throw new Error('Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available')
    }

    function getAPIUsageErrorMessage(
      scopeObject: unknown,
      apiName: string,
      usageDesc?: string
    ): string {
      if (usageDesc) {
        return `Use of '${usageDesc}' requires \`${apiName}\` which is unavailable on the '${scopeObject}' object within the currently executing environment.`
      } else {
        return `\`${apiName}\` is unavailable on the '${scopeObject}' object within the currently executing environment.`
      }
    }

    interface GetGlobalObjectOptions {
      /**
       * Throw an error if the object is not found.
       * @default false
       */
      throwIfUnavailable?: boolean;
      /**
       * Additional information to include in an error if thrown.
       */
      usageDesc?: string;
      /**
       * If the object is not found, return an new empty object instead of undefined.
       * Requires [[throwIfUnavailable]] to be falsey.
       * @default false
       */
      returnEmptyObject?: boolean;
    }

    /**
     * Returns an object from the global scope (`Window` or `WorkerGlobalScope`) if it
     * is available within the currently executing environment.
     * When executing within the Node.js runtime these APIs are unavailable and will be
     * `undefined` unless the API is provided via polyfill.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
     * @ignore
     */
    export function getGlobalObject<K extends Extract<keyof Window, string>>(
      name: K,
      { throwIfUnavailable, usageDesc, returnEmptyObject }: GetGlobalObjectOptions = { }
    ): Window[K] {
      let globalScope: Window
      try {
        globalScope = getGlobalScope()
        Eif (globalScope) {
          const obj = globalScope[name]
          if (obj) {
            return obj
          }
        }
      } catch (error) {
        Logger.error(`Error getting object '${name}' from global scope '${globalScope}': ${error}`)
      }
      Iif (throwIfUnavailable) {
        const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc)
        Logger.error(errMsg)
        throw new Error(errMsg)
      }
      Eif (returnEmptyObject) {
        return {} as any
      }
      return undefined
    }

    /**
     * Returns a specified subset of objects from the global scope (`Window` or `WorkerGlobalScope`)
     * if they are available within the currently executing environment.
     * When executing within the Node.js runtime these APIs are unavailable will be `undefined`
     * unless the API is provided via polyfill.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
     * @ignore
     */
    export function getGlobalObjects<K extends Extract<keyof Window, string>>(
      names: K[],
      { throwIfUnavailable, usageDesc, returnEmptyObject }: GetGlobalObjectOptions = {}
    ): Pick<Window, K> {
      let globalScope: Window
      try {
        globalScope = getGlobalScope()
      } catch (error) {
        Logger.error(`Error getting global scope: ${error}`)
        if (throwIfUnavailable) {
          const errMsg = getAPIUsageErrorMessage(globalScope, names[0].toString(), usageDesc)
          Logger.error(errMsg)
          throw errMsg
        } else if (returnEmptyObject) {
          globalScope = {} as any
        }
      }

      const result: Pick<Window, K> = {} as any
      for (let i = 0; i < names.length; i++) {
        const name = names[i]
        try {
          if (globalScope) {
            const obj = globalScope[name]
            if (obj) {
              result[name] = obj
            } else if (throwIfUnavailable) {
              const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc)
              Logger.error(errMsg)
              throw new Error(errMsg)
            } else if (returnEmptyObject) {
              result[name] = {} as any
            }
          }
        } catch (error) {
          if (throwIfUnavailable) {
            const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc)
            Logger.error(errMsg)
            throw new Error(errMsg)
          }
        }
      }
      return result
    }

    async function getGaiaErrorResponse(response: Response): Promise<GaiaHubErrorResponse> {
      let responseMsg = ''
      let responseJson: any | undefined
      try {
        responseMsg = await response.text()
        try {
          responseJson = JSON.parse(responseMsg)
        } catch (error) {
          // Use text instead
        }
      } catch (error) {
        Logger.debug(`Error getting bad http response text: ${error}`)
      }
      const status = response.status
      const statusText = response.statusText
      const body = responseJson || responseMsg
      return { status, statusText, body }
    }

    /**
     * Returns a BlockstackError correlating to the given HTTP response,
     * with the provided errorMsg. Throws if the HTTP response is 'ok'.
     */
    export async function getBlockstackErrorFromResponse(
      response: Response,
      errorMsg: string
    ): Promise<Error> {
      Iif (response.ok) {
        throw new Error('Cannot get a BlockstackError from a valid response.')
      }
      const gaiaResponse = await getGaiaErrorResponse(response)
      if (gaiaResponse.status === 401) {
        return new ValidationError(errorMsg, gaiaResponse)
      } else Iif (gaiaResponse.status === 402) {
        return new NotEnoughProofError(errorMsg, gaiaResponse)
      } else Iif (gaiaResponse.status === 403) {
        return new BadPathError(errorMsg, gaiaResponse)
      } else Eif (gaiaResponse.status === 404) {
        throw new DoesNotExist(errorMsg, gaiaResponse)
      } else if (gaiaResponse.status === 409) {
        return new ConflictError(errorMsg, gaiaResponse)
      } else if (gaiaResponse.status === 413) {
        return new PayloadTooLargeError(errorMsg, gaiaResponse)
      } else {
        return new Error(errorMsg)
      }
    }