# All files index.js

96.66% Statements 232/240
90.08% Branches 109/121
100% Functions 30/30
96.56% Lines 225/233

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
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507

    62x
    62x

    1x
    6x
    3x

    3x

    1x
    12x
    6x

    6x

    1x
    27x
    27x
    27x
    27x

    27x
    3x

    24x
    24x
    33x
    27x
    27x
    27x
    27x
    27x

    27x
    27x
    27x
    19x

    19x

    27x
    27x
    27x

    27x

    9x
    3x
    3x

    6x

    6x
    6x

    2x

    2x

    16x

    16x
    3x

    1x
    4x
    4x

    4x
    4x

    1x
    27x
    27x

    27x
    27x
    6x

    27x
    1x

    1x

    26x
    41x
    41x
    41x
    41x
    41x
    40x
    40x
    40x

    41x
    1x
    1x
    1x

    41x
    41x
    41x

    41x
    24x
    12x

    12x

    41x
    14x
    8x
    8x
    8x
    1x
    7x

    6x

    5x

    5x

    6x

    27x

    1x

    26x
    26x
    26x
    26x
    3x
    23x

    18x

    7x
    2x
    2x

    5x
    5x

    19x
    2x
    2x

    26x
    11x

    15x

    1x
    5x
    5x

    5x
    6x
    6x
    2x

    5x

    1x
    2x
    2x
    2x

    2x

    2x

    2x

    1x

    17x
    17x
    17x

    7x
    2x
    2x

    5x

    12x
    10x

    9x

    7x

    1x
    2x

    2x
    2x
    4x
    6x

    4x
    1x
    1x

    3x

    2x
    2x
    4x
    6x

    4x
    1x
    1x

    3x

    2x

    1x
    2x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    51x
    43x
    43x
    8x
    1x

    51x
    51x

    51x
    1x

    50x
    2x

    48x

    50x

    1x
    60x

    60x
    52x
    52x
    52x

    60x
    1x

    59x
    2x

    57x

    59x
    59x

    1x
    1x
    1x
    1x
    1x

    1x

    1x
    4x

    4x
    6x
    6x

    4x
    5x

    4x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x

    61x

    41x
    2x

    39x

    1x
     'use strict';

    /**
     * Create a new instance
     */
    function Kareem() {
      this._pres = new Map();
      this._posts = new Map();
    }

    Kareem.skipWrappedFunction = function skipWrappedFunction() {
      if (!(this instanceof Kareem.skipWrappedFunction)) {
        return new Kareem.skipWrappedFunction(...arguments);
      }

      this.args = [...arguments];
    };

    Kareem.overwriteResult = function overwriteResult() {
      if (!(this instanceof Kareem.overwriteResult)) {
        return new Kareem.overwriteResult(...arguments);
      }

      this.args = [...arguments];
    };

    /**
     * Execute all "pre" hooks for "name"
     * @param {String} name The hook name to execute
     * @param {*} context Overwrite the "this" for the hook
     * @param {Array|Function} args arguments passed to the pre hooks
     * @returns {void}
     */
    Kareem.prototype.execPre = async function execPre(name, context, args) {
      const pres = this._pres.get(name) || [];
      const numPres = pres.length;
      const $args = args;
      let skipWrappedFunction = null;

      if (!numPres) {
        return;
      }

      const asyncPrePromises = [];
      for (const pre of pres) {
        if (pre.fn.length > 0) {
          let resolve = null;
          let reject = null;
          const cbPromise = new Promise((_resolve, _reject) => {
            resolve = _resolve;
            reject = _reject;
          });
          const args = [(err) => err ? reject(err) : resolve()];
          const _args = [null].concat($args);
          for (let i = 1; i < _args.length; ++i) {
            Iif (i === _args.length - 1 && typeof _args[i] === 'function') {
              continue; // skip callbacks to avoid accidentally calling the callback from a hook
            }
            args.push(_args[i]);
          }

          try {
            const maybePromiseLike = pre.fn.apply(context, args);
            Iif (isPromiseLike(maybePromiseLike)) {
              await maybePromiseLike;
            } else {
              await cbPromise;
            }
          } catch (error) {
            if (error instanceof Kareem.skipWrappedFunction) {
              skipWrappedFunction = error;
              continue;
            }
            throw error;
          }
        } else {
          try {
            await pre.fn.call(context);
          } catch (error) {
            Iif (error instanceof Kareem.skipWrappedFunction) {
              skipWrappedFunction = error;
              continue;
            }
            throw error;
          }
        }
      }

      await Promise.all(asyncPrePromises);

      if (skipWrappedFunction) {
        throw skipWrappedFunction;
      }
    };

    /**
     * Execute all "pre" hooks for "name" synchronously
     * @param {String} name The hook name to execute
     * @param {*} context Overwrite the "this" for the hook
     * @param {Array} [args] Apply custom arguments to the hook
     * @returns {void}
     */
    Kareem.prototype.execPreSync = function(name, context, args) {
      const pres = this._pres.get(name) || [];
      const numPres = pres.length;

      for (let i = 0; i < numPres; ++i) {
        pres[i].fn.apply(context, args || []);
      }
    };

    /**
     * Execute all "post" hooks for "name"
     * @param {String} name The hook name to execute
     * @param {*} context Overwrite the "this" for the hook
     * @param {Array|Function} args Apply custom arguments to the hook
     * @param {*} options Optional options or directly the callback
     * @returns {void}
     */
    Kareem.prototype.execPost = async function execPost(name, context, args, options) {
      const posts = this._posts.get(name) || [];
      const numPosts = posts.length;

      let firstError = null;
      if (options && options.error) {
        firstError = options.error;
      }

      if (!numPosts) {
        Iif (firstError != null) {
          throw firstError;
        }
        return args;
      }

      for (const currentPost of posts) {
        const post = currentPost.fn;
        let numArgs = 0;
        const newArgs = [];
        const argLength = args.length;
        for (let i = 0; i < argLength; ++i) {
          Eif (!args[i] || !args[i]._kareemIgnore) {
            numArgs += 1;
            newArgs.push(args[i]);
          }
        }
        // If numCallbackParams set, fill in the rest with null to enforce consistent number of args
        if (options?.numCallbackParams != null) {
          numArgs = options.numCallbackParams;
          for (let i = newArgs.length; i < numArgs; ++i) {
            newArgs.push(null);
          }
        }

        let resolve;
        let reject;
        const cbPromise = new Promise((_resolve, _reject) => {
          resolve = _resolve;
          reject = _reject;
        });
        newArgs.push(function nextCallback(err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });

        if (firstError) {
          if (isErrorHandlingMiddleware(currentPost, numArgs)) {
            try {
              const res = post.apply(context, [firstError].concat(newArgs));
              if (isPromiseLike(res)) {
                await res;
              } else if (post.length === numArgs + 2) {
                // `numArgs + 2` because we added the error and the callback
                await cbPromise;
              }
            } catch (error) {
              Iif (error instanceof Kareem.overwriteResult) {
                args = error.args;
                continue;
              }
              firstError = error;
            }
          } else {
            continue;
          }
        } else {
          if (isErrorHandlingMiddleware(currentPost, numArgs)) {
            // Skip error handlers if no error
            continue;
          } else {
            let res = null;
            try {
              res = post.apply(context, newArgs);
              if (isPromiseLike(res)) {
                res = await res;
              } else if (post.length === numArgs + 1) {
                // If post function takes a callback, wait for the post function to call the callback
                res = await cbPromise;
              }
            } catch (error) {
              if (error instanceof Kareem.overwriteResult) {
                args = error.args;
                continue;
              }
              firstError = error;
              continue;
            }

            if (res instanceof Kareem.overwriteResult) {
              args = res.args;
              continue;
            }
          }
        }
      }

      if (firstError != null) {
        throw firstError;
      }

      return args;
    };

    /**
     * Execute all "post" hooks for "name" synchronously
     * @param {String} name The hook name to execute
     * @param {*} context Overwrite the "this" for the hook
     * @param {Array|Function} args Apply custom arguments to the hook
     * @returns {Array} The used arguments
     */
    Kareem.prototype.execPostSync = function(name, context, args) {
      const posts = this._posts.get(name) || [];
      const numPosts = posts.length;

      for (let i = 0; i < numPosts; ++i) {
        const res = posts[i].fn.apply(context, args || []);
        if (res instanceof Kareem.overwriteResult) {
          args = res.args;
        }
      }

      return args;
    };

    /**
     * Create a synchronous wrapper for "fn"
     * @param {String} name The name of the hook
     * @param {Function} fn The function to wrap
     * @returns {Function} The wrapped function
     */
    Kareem.prototype.createWrapperSync = function(name, fn) {
      const _this = this;
      return function syncWrapper() {
        _this.execPreSync(name, this, arguments);

        const toReturn = fn.apply(this, arguments);

        const result = _this.execPostSync(name, this, [toReturn]);

        return result[0];
      };
    };

    /**
     * Executes pre hooks, followed by the wrapped function, followed by post hooks.
     * @param {String} name The name of the hook
     * @param {Function} fn The function for the hook
     * @param {*} context Overwrite the "this" for the hook
     * @param {Array} args Apply custom arguments to the hook
     * @param {Object} options Additional options for the hook
     * @returns {void}
     */
    Kareem.prototype.wrap = async function wrap(name, fn, context, args, options) {
      let ret;
      let skipWrappedFunction = false;
      try {
        await this.execPre(name, context, args);
      } catch (error) {
        if (error instanceof Kareem.skipWrappedFunction) {
          ret = error.args;
          skipWrappedFunction = true;
        } else {
          await this.execPost(name, context, args, { ...options, error });
        }
      }

      if (!skipWrappedFunction) {
        ret = await fn.apply(context, args);
      }

      ret = await this.execPost(name, context, [ret], options);

      return ret[0];
    };

    /**
     * Filter current instance for something specific and return the filtered clone
     * @param {Function} fn The filter function
     * @returns {Kareem} The cloned and filtered instance
     */
    Kareem.prototype.filter = function(fn) {
      const clone = this.clone();

      const pres = Array.from(clone._pres.keys());
      for (const name of pres) {
        const hooks = this._pres.get(name).
          map(h => Object.assign({}, h, { name: name })).
          filter(fn);

        if (hooks.length === 0) {
          clone._pres.delete(name);
          continue;
        }

        clone._pres.set(name, hooks);
      }

      const posts = Array.from(clone._posts.keys());
      for (const name of posts) {
        const hooks = this._posts.get(name).
          map(h => Object.assign({}, h, { name: name })).
          filter(fn);

        if (hooks.length === 0) {
          clone._posts.delete(name);
          continue;
        }

        clone._posts.set(name, hooks);
      }

      return clone;
    };

    /**
     * Check for a "name" to exist either in pre or post hooks
     * @param {String} name The name of the hook
     * @returns {Boolean} "true" if found, "false" otherwise
     */
    Kareem.prototype.hasHooks = function(name) {
      return this._pres.has(name) || this._posts.has(name);
    };

    /**
     * Create a Wrapper for "fn" on "name" and return the wrapped function
     * @param {String} name The name of the hook
     * @param {Function} fn The function to wrap
     * @param {*} context Overwrite the "this" for the hook
     * @param {Object} [options]
     * @returns {Function} The wrapped function
     */
    Kareem.prototype.createWrapper = function(name, fn, context, options) {
      const _this = this;
      Iif (!this.hasHooks(name)) {
        // Fast path: if there's no hooks for this function, just return the function
        return fn;
      }
      return function kareemWrappedFunction() {
        const _context = context || this;
        return _this.wrap(name, fn, _context, Array.from(arguments), options);
      };
    };

    /**
     * Register a new hook for "pre"
     * @param {String} name The name of the hook
     * @param {Object} [options]
     * @param {Function} fn The function to register for "name"
     * @param {never} error Unused
     * @param {Boolean} [unshift] Wheter to "push" or to "unshift" the new hook
     * @returns {Kareem}
     */
    Kareem.prototype.pre = function(name, options, fn, error, unshift) {
      if (typeof options === 'function') {
        fn = options;
        options = {};
      } else if (options == null) {
        options = {};
      }

      const pres = this._pres.get(name) || [];
      this._pres.set(name, pres);

      if (typeof fn !== 'function') {
        throw new Error('pre() requires a function, got "' + typeof fn + '"');
      }

      if (unshift) {
        pres.unshift(Object.assign({}, options, { fn: fn }));
      } else {
        pres.push(Object.assign({}, options, { fn: fn }));
      }

      return this;
    };

    /**
     * Register a new hook for "post"
     * @param {String} name The name of the hook
     * @param {Object} [options]
     * @param {Boolean} [options.errorHandler] Whether this is an error handler
     * @param {Function} fn The function to register for "name"
     * @param {Boolean} [unshift] Wheter to "push" or to "unshift" the new hook
     * @returns {Kareem}
     */
    Kareem.prototype.post = function(name, options, fn, unshift) {
      const posts = this._posts.get(name) || [];

      if (typeof options === 'function') {
        unshift = !!fn;
        fn = options;
        options = {};
      }

      if (typeof fn !== 'function') {
        throw new Error('post() requires a function, got "' + typeof fn + '"');
      }

      if (unshift) {
        posts.unshift(Object.assign({}, options, { fn: fn }));
      } else {
        posts.push(Object.assign({}, options, { fn: fn }));
      }
      this._posts.set(name, posts);
      return this;
    };

    /**
     * Register a new error handler for "name"
     * @param {String} name The name of the hook
     * @param {Object} [options]
     * @param {Function} fn The function to register for "name"
     * @param {Boolean} [unshift] Wheter to "push" or to "unshift" the new hook
     * @returns {Kareem}
     */

    Kareem.prototype.postError = function postError(name, options, fn, unshift) {
      Eif (typeof options === 'function') {
        unshift = !!fn;
        fn = options;
        options = {};
      }
      return this.post(name, { ...options, errorHandler: true }, fn, unshift);
    };

    /**
     * Clone the current instance
     * @returns {Kareem} The cloned instance
     */
    Kareem.prototype.clone = function() {
      const n = new Kareem();

      for (const key of this._pres.keys()) {
        const clone = this._pres.get(key).slice();
        n._pres.set(key, clone);
      }
      for (const key of this._posts.keys()) {
        n._posts.set(key, this._posts.get(key).slice());
      }

      return n;
    };

    /**
     * Merge "other" into self or "clone"
     * @param {Kareem} other The instance to merge with
     * @param {Kareem} [clone] The instance to merge onto (if not defined, using "this")
     * @returns {Kareem} The merged instance
     */
    Kareem.prototype.merge = function(other, clone) {
      clone = arguments.length === 1 ? true : clone;
      const ret = clone ? this.clone() : this;

      for (const key of other._pres.keys()) {
        const sourcePres = ret._pres.get(key) || [];
        const deduplicated = other._pres.get(key).
          // Deduplicate based on `fn`
          filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1);
        const combined = sourcePres.concat(deduplicated);
        ret._pres.set(key, combined);
      }
      for (const key of other._posts.keys()) {
        const sourcePosts = ret._posts.get(key) || [];
        const deduplicated = other._posts.get(key).
          filter(p => sourcePosts.indexOf(p) === -1);
        ret._posts.set(key, sourcePosts.concat(deduplicated));
      }

      return ret;
    };

    function isPromiseLike(v) {
      return (typeof v === 'object' && v !== null && typeof v.then === 'function');
    }

    function isErrorHandlingMiddleware(post, numArgs) {
      if (post.errorHandler) {
        return true;
      }
      return post.fn.length === numArgs + 2;
    }

    module.exports = Kareem;