summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/packages/puppeteer-core/src/bidi/ExposedFunction.ts
blob: f6e1304a550e518cb70bcff8320f04c46fa15473 (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
/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import * as Bidi from 'chromium-bidi/lib/cjs/protocol/protocol.js';

import {EventEmitter} from '../common/EventEmitter.js';
import type {Awaitable, FlattenHandle} from '../common/types.js';
import {debugError} from '../common/util.js';
import {DisposableStack} from '../util/disposable.js';
import {interpolateFunction, stringifyFunction} from '../util/Function.js';

import type {Connection} from './core/Connection.js';
import {BidiElementHandle} from './ElementHandle.js';
import type {BidiFrame} from './Frame.js';
import {BidiJSHandle} from './JSHandle.js';

type CallbackChannel<Args, Ret> = (
  value: [
    resolve: (ret: FlattenHandle<Awaited<Ret>>) => void,
    reject: (error: unknown) => void,
    args: Args,
  ]
) => void;

/**
 * @internal
 */
export class ExposeableFunction<Args extends unknown[], Ret> {
  static async from<Args extends unknown[], Ret>(
    frame: BidiFrame,
    name: string,
    apply: (...args: Args) => Awaitable<Ret>,
    isolate = false
  ): Promise<ExposeableFunction<Args, Ret>> {
    const func = new ExposeableFunction(frame, name, apply, isolate);
    await func.#initialize();
    return func;
  }

  readonly #frame;

  readonly name;
  readonly #apply;
  readonly #isolate;

  readonly #channel;

  #scripts: Array<[BidiFrame, Bidi.Script.PreloadScript]> = [];
  #disposables = new DisposableStack();

  constructor(
    frame: BidiFrame,
    name: string,
    apply: (...args: Args) => Awaitable<Ret>,
    isolate = false
  ) {
    this.#frame = frame;
    this.name = name;
    this.#apply = apply;
    this.#isolate = isolate;

    this.#channel = `__puppeteer__${this.#frame._id}_page_exposeFunction_${this.name}`;
  }

  async #initialize() {
    const connection = this.#connection;
    const channel = {
      type: 'channel' as const,
      value: {
        channel: this.#channel,
        ownership: Bidi.Script.ResultOwnership.Root,
      },
    };

    const connectionEmitter = this.#disposables.use(
      new EventEmitter(connection)
    );
    connectionEmitter.on(
      Bidi.ChromiumBidi.Script.EventNames.Message,
      this.#handleMessage
    );

    const functionDeclaration = stringifyFunction(
      interpolateFunction(
        (callback: CallbackChannel<Args, Ret>) => {
          Object.assign(globalThis, {
            [PLACEHOLDER('name') as string]: function (...args: Args) {
              return new Promise<FlattenHandle<Awaited<Ret>>>(
                (resolve, reject) => {
                  callback([resolve, reject, args]);
                }
              );
            },
          });
        },
        {name: JSON.stringify(this.name)}
      )
    );

    const frames = [this.#frame];
    for (const frame of frames) {
      frames.push(...frame.childFrames());
    }

    await Promise.all(
      frames.map(async frame => {
        const realm = this.#isolate ? frame.isolatedRealm() : frame.mainRealm();
        try {
          const [script] = await Promise.all([
            frame.browsingContext.addPreloadScript(functionDeclaration, {
              arguments: [channel],
              sandbox: realm.sandbox,
            }),
            realm.realm.callFunction(functionDeclaration, false, {
              arguments: [channel],
            }),
          ]);
          this.#scripts.push([frame, script]);
        } catch (error) {
          // If it errors, the frame probably doesn't support call function. We
          // fail gracefully.
          debugError(error);
        }
      })
    );
  }

  get #connection(): Connection {
    return this.#frame.page().browser().connection;
  }

  #handleMessage = async (params: Bidi.Script.MessageParameters) => {
    if (params.channel !== this.#channel) {
      return;
    }
    const realm = this.#getRealm(params.source);
    if (!realm) {
      // Unrelated message.
      return;
    }

    using dataHandle = BidiJSHandle.from<
      [
        resolve: (ret: FlattenHandle<Awaited<Ret>>) => void,
        reject: (error: unknown) => void,
        args: Args,
      ]
    >(params.data, realm);

    using argsHandle = await dataHandle.evaluateHandle(([, , args]) => {
      return args;
    });

    using stack = new DisposableStack();
    const args = [];
    for (const [index, handle] of await argsHandle.getProperties()) {
      stack.use(handle);

      // Element handles are passed as is.
      if (handle instanceof BidiElementHandle) {
        args[+index] = handle;
        stack.use(handle);
        continue;
      }

      // Everything else is passed as the JS value.
      args[+index] = handle.jsonValue();
    }

    let result;
    try {
      result = await this.#apply(...((await Promise.all(args)) as Args));
    } catch (error) {
      try {
        if (error instanceof Error) {
          await dataHandle.evaluate(
            ([, reject], name, message, stack) => {
              const error = new Error(message);
              error.name = name;
              if (stack) {
                error.stack = stack;
              }
              reject(error);
            },
            error.name,
            error.message,
            error.stack
          );
        } else {
          await dataHandle.evaluate(([, reject], error) => {
            reject(error);
          }, error);
        }
      } catch (error) {
        debugError(error);
      }
      return;
    }

    try {
      await dataHandle.evaluate(([resolve], result) => {
        resolve(result);
      }, result);
    } catch (error) {
      debugError(error);
    }
  };

  #getRealm(source: Bidi.Script.Source) {
    const frame = this.#findFrame(source.context as string);
    if (!frame) {
      // Unrelated message.
      return;
    }
    return frame.realm(source.realm);
  }

  #findFrame(id: string) {
    const frames = [this.#frame];
    for (const frame of frames) {
      if (frame._id === id) {
        return frame;
      }
      frames.push(...frame.childFrames());
    }
    return;
  }

  [Symbol.dispose](): void {
    void this[Symbol.asyncDispose]().catch(debugError);
  }

  async [Symbol.asyncDispose](): Promise<void> {
    this.#disposables.dispose();
    await Promise.all(
      this.#scripts.map(async ([frame, script]) => {
        const realm = this.#isolate ? frame.isolatedRealm() : frame.mainRealm();
        try {
          await Promise.all([
            realm.evaluate(name => {
              delete (globalThis as any)[name];
            }, this.name),
            frame.browsingContext.removePreloadScript(script),
          ]);
        } catch (error) {
          debugError(error);
        }
      })
    );
  }
}