summaryrefslogtreecommitdiff
path: root/chromium/third_party/devtools-frontend/src/node_modules/mocha/lib/plugin-loader.js
blob: 075ad91b49a22ceb0694cf0d55355f03860b78e7 (plain)
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
/**
 * Provides a way to load "plugins" as provided by the user.
 *
 * Currently supports:
 *
 * - Root hooks
 * - Global fixtures (setup/teardown)
 * @private
 * @module plugin
 */

'use strict';

const debug = require('debug')('mocha:plugin-loader');
const {
  createInvalidPluginDefinitionError,
  createInvalidPluginImplementationError
} = require('./errors');
const {castArray} = require('./utils');

/**
 * Built-in plugin definitions.
 */
const MochaPlugins = [
  /**
   * Root hook plugin definition
   * @type {PluginDefinition}
   */
  {
    exportName: 'mochaHooks',
    optionName: 'rootHooks',
    validate(value) {
      if (
        Array.isArray(value) ||
        (typeof value !== 'function' && typeof value !== 'object')
      ) {
        throw createInvalidPluginImplementationError(
          `mochaHooks must be an object or a function returning (or fulfilling with) an object`
        );
      }
    },
    async finalize(rootHooks) {
      if (rootHooks.length) {
        const rootHookObjects = await Promise.all(
          rootHooks.map(async hook =>
            typeof hook === 'function' ? hook() : hook
          )
        );

        return rootHookObjects.reduce(
          (acc, hook) => {
            hook = {
              beforeAll: [],
              beforeEach: [],
              afterAll: [],
              afterEach: [],
              ...hook
            };
            return {
              beforeAll: [...acc.beforeAll, ...castArray(hook.beforeAll)],
              beforeEach: [...acc.beforeEach, ...castArray(hook.beforeEach)],
              afterAll: [...acc.afterAll, ...castArray(hook.afterAll)],
              afterEach: [...acc.afterEach, ...castArray(hook.afterEach)]
            };
          },
          {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
        );
      }
    }
  },
  /**
   * Global setup fixture plugin definition
   * @type {PluginDefinition}
   */
  {
    exportName: 'mochaGlobalSetup',
    optionName: 'globalSetup',
    validate(value) {
      let isValid = true;
      if (Array.isArray(value)) {
        if (value.some(item => typeof item !== 'function')) {
          isValid = false;
        }
      } else if (typeof value !== 'function') {
        isValid = false;
      }
      if (!isValid) {
        throw createInvalidPluginImplementationError(
          `mochaGlobalSetup must be a function or an array of functions`,
          {pluginDef: this, pluginImpl: value}
        );
      }
    }
  },
  /**
   * Global teardown fixture plugin definition
   * @type {PluginDefinition}
   */
  {
    exportName: 'mochaGlobalTeardown',
    optionName: 'globalTeardown',
    validate(value) {
      let isValid = true;
      if (Array.isArray(value)) {
        if (value.some(item => typeof item !== 'function')) {
          isValid = false;
        }
      } else if (typeof value !== 'function') {
        isValid = false;
      }
      if (!isValid) {
        throw createInvalidPluginImplementationError(
          `mochaGlobalTeardown must be a function or an array of functions`,
          {pluginDef: this, pluginImpl: value}
        );
      }
    }
  }
];

/**
 * Contains a registry of [plugin definitions]{@link PluginDefinition} and discovers plugin implementations in user-supplied code.
 *
 * - [load()]{@link #load} should be called for all required modules
 * - The result of [finalize()]{@link #finalize} should be merged into the options for the [Mocha]{@link Mocha} constructor.
 * @private
 */
class PluginLoader {
  /**
   * Initializes plugin names, plugin map, etc.
   * @param {PluginLoaderOptions} [opts] - Options
   */
  constructor({pluginDefs = MochaPlugins, ignore = []} = {}) {
    /**
     * Map of registered plugin defs
     * @type {Map<string,PluginDefinition>}
     */
    this.registered = new Map();

    /**
     * Cache of known `optionName` values for checking conflicts
     * @type {Set<string>}
     */
    this.knownOptionNames = new Set();

    /**
     * Cache of known `exportName` values for checking conflicts
     * @type {Set<string>}
     */
    this.knownExportNames = new Set();

    /**
     * Map of user-supplied plugin implementations
     * @type {Map<string,Array<*>>}
     */
    this.loaded = new Map();

    /**
     * Set of ignored plugins by export name
     * @type {Set<string>}
     */
    this.ignoredExportNames = new Set(castArray(ignore));

    castArray(pluginDefs).forEach(pluginDef => {
      this.register(pluginDef);
    });

    debug(
      'registered %d plugin defs (%d ignored)',
      this.registered.size,
      this.ignoredExportNames.size
    );
  }

  /**
   * Register a plugin
   * @param {PluginDefinition} pluginDef - Plugin definition
   */
  register(pluginDef) {
    if (!pluginDef || typeof pluginDef !== 'object') {
      throw createInvalidPluginDefinitionError(
        'pluginDef is non-object or falsy',
        pluginDef
      );
    }
    if (!pluginDef.exportName) {
      throw createInvalidPluginDefinitionError(
        `exportName is expected to be a non-empty string`,
        pluginDef
      );
    }
    let {exportName} = pluginDef;
    if (this.ignoredExportNames.has(exportName)) {
      debug(
        'refusing to register ignored plugin with export name "%s"',
        exportName
      );
      return;
    }
    exportName = String(exportName);
    pluginDef.optionName = String(pluginDef.optionName || exportName);
    if (this.knownExportNames.has(exportName)) {
      throw createInvalidPluginDefinitionError(
        `Plugin definition conflict: ${exportName}; exportName must be unique`,
        pluginDef
      );
    }
    this.loaded.set(exportName, []);
    this.registered.set(exportName, pluginDef);
    this.knownExportNames.add(exportName);
    this.knownOptionNames.add(pluginDef.optionName);
    debug('registered plugin def "%s"', exportName);
  }

  /**
   * Inspects a module's exports for known plugins and keeps them in memory.
   *
   * @param {*} requiredModule - The exports of a module loaded via `--require`
   * @returns {boolean} If one or more plugins was found, return `true`.
   */
  load(requiredModule) {
    // we should explicitly NOT fail if other stuff is exported.
    // we only care about the plugins we know about.
    if (requiredModule && typeof requiredModule === 'object') {
      return Array.from(this.knownExportNames).reduce(
        (pluginImplFound, pluginName) => {
          const pluginImpl = requiredModule[pluginName];
          if (pluginImpl) {
            const plugin = this.registered.get(pluginName);
            if (typeof plugin.validate === 'function') {
              plugin.validate(pluginImpl);
            }
            this.loaded.set(pluginName, [
              ...this.loaded.get(pluginName),
              ...castArray(pluginImpl)
            ]);
            return true;
          }
          return pluginImplFound;
        },
        false
      );
    }
    return false;
  }

  /**
   * Call the `finalize()` function of each known plugin definition on the plugins found by [load()]{@link PluginLoader#load}.
   *
   * Output suitable for passing as input into {@link Mocha} constructor.
   * @returns {Promise<object>} Object having keys corresponding to registered plugin definitions' `optionName` prop (or `exportName`, if none), and the values are the implementations as provided by a user.
   */
  async finalize() {
    const finalizedPlugins = Object.create(null);

    for await (const [exportName, pluginImpls] of this.loaded.entries()) {
      if (pluginImpls.length) {
        const plugin = this.registered.get(exportName);
        finalizedPlugins[plugin.optionName] =
          typeof plugin.finalize === 'function'
            ? await plugin.finalize(pluginImpls)
            : pluginImpls;
      }
    }

    debug('finalized plugins: %O', finalizedPlugins);
    return finalizedPlugins;
  }

  /**
   * Constructs a {@link PluginLoader}
   * @param {PluginLoaderOptions} [opts] - Plugin loader options
   */
  static create({pluginDefs = MochaPlugins, ignore = []} = {}) {
    return new PluginLoader({pluginDefs, ignore});
  }
}

module.exports = PluginLoader;

/**
 * Options for {@link PluginLoader}
 * @typedef {Object} PluginLoaderOptions
 * @property {PluginDefinition[]} [pluginDefs] - Plugin definitions
 * @property {string[]} [ignore] - A list of plugins to ignore when loading
 */