summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/packages/puppeteer-core/src/common/ScriptInjector.ts
blob: cb0c0395308157053618c534465ca07adaad6282 (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
import {source as injectedSource} from '../generated/injected.js';

class ScriptInjector {
  #updated = false;
  #amendments = new Set<string>();

  // Appends a statement of the form `(PuppeteerUtil) => {...}`.
  append(statement: string): void {
    this.#update(() => {
      this.#amendments.add(statement);
    });
  }

  pop(statement: string): void {
    this.#update(() => {
      this.#amendments.delete(statement);
    });
  }

  inject(inject: (script: string) => void, force = false) {
    if (this.#updated || force) {
      inject(this.#get());
    }
    this.#updated = false;
  }

  #update(callback: () => void): void {
    callback();
    this.#updated = true;
  }

  #get(): string {
    return `(() => {
      const module = {};
      ${injectedSource}
      ${[...this.#amendments]
        .map(statement => {
          return `(${statement})(module.exports.default);`;
        })
        .join('')}
      return module.exports.default;
    })()`;
  }
}

/**
 * @internal
 */
export const scriptInjector = new ScriptInjector();