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

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

import {EventEmitter} from '../../common/EventEmitter.js';
import {debugError} from '../../common/util.js';
import {
  bubble,
  inertIfDisposed,
  throwIfDisposed,
} from '../../util/decorators.js';
import {DisposableStack, disposeSymbol} from '../../util/disposable.js';

import {Browser} from './Browser.js';
import type {BidiEvents, Commands, Connection} from './Connection.js';

// TODO: Once Chrome supports session.status properly, uncomment this block.
// const MAX_RETRIES = 5;

/**
 * @internal
 */
export class Session
  extends EventEmitter<BidiEvents & {ended: {reason: string}}>
  implements Connection<BidiEvents & {ended: {reason: string}}>
{
  static async from(
    connection: Connection,
    capabilities: Bidi.Session.CapabilitiesRequest
  ): Promise<Session> {
    // Wait until the session is ready.
    //
    // TODO: Once Chrome supports session.status properly, uncomment this block
    // and remove `getBiDiConnection` in BrowserConnector.

    // let status = {message: '', ready: false};
    // for (let i = 0; i < MAX_RETRIES; ++i) {
    //   status = (await connection.send('session.status', {})).result;
    //   if (status.ready) {
    //     break;
    //   }
    //   // Backoff a little bit each time.
    //   await new Promise(resolve => {
    //     return setTimeout(resolve, (1 << i) * 100);
    //   });
    // }
    // if (!status.ready) {
    //   throw new Error(status.message);
    // }

    let result;
    try {
      result = (
        await connection.send('session.new', {
          capabilities,
        })
      ).result;
    } catch (err) {
      // Chrome does not support session.new.
      debugError(err);
      result = {
        sessionId: '',
        capabilities: {
          acceptInsecureCerts: false,
          browserName: '',
          browserVersion: '',
          platformName: '',
          setWindowRect: false,
          webSocketUrl: '',
          userAgent: '',
        },
      } satisfies Bidi.Session.NewResult;
    }

    const session = new Session(connection, result);
    await session.#initialize();
    return session;
  }

  #reason: string | undefined;
  readonly #disposables = new DisposableStack();
  readonly #info: Bidi.Session.NewResult;
  readonly browser!: Browser;
  @bubble()
  accessor connection: Connection;

  private constructor(connection: Connection, info: Bidi.Session.NewResult) {
    super();

    this.#info = info;
    this.connection = connection;
  }

  async #initialize(): Promise<void> {
    // SAFETY: We use `any` to allow assignment of the readonly property.
    (this as any).browser = await Browser.from(this);

    const browserEmitter = this.#disposables.use(this.browser);
    browserEmitter.once('closed', ({reason}) => {
      this.dispose(reason);
    });

    // TODO: Currently, some implementations do not emit navigationStarted event
    // for fragment navigations (as per spec) and some do. This could emits a
    // synthetic navigationStarted to work around this inconsistency.
    const seen = new WeakSet();
    this.on('browsingContext.fragmentNavigated', info => {
      if (seen.has(info)) {
        return;
      }
      seen.add(info);
      this.emit('browsingContext.navigationStarted', info);
      this.emit('browsingContext.fragmentNavigated', info);
    });
  }

  get capabilities(): Bidi.Session.NewResult['capabilities'] {
    return this.#info.capabilities;
  }
  get disposed(): boolean {
    return this.ended;
  }
  get ended(): boolean {
    return this.#reason !== undefined;
  }
  get id(): string {
    return this.#info.sessionId;
  }

  @inertIfDisposed
  private dispose(reason?: string): void {
    this.#reason = reason;
    this[disposeSymbol]();
  }

  /**
   * Currently, there is a 1:1 relationship between the session and the
   * session. In the future, we might support multiple sessions and in that
   * case we always needs to make sure that the session for the right session
   * object is used, so we implement this method here, although it's not defined
   * in the spec.
   */
  @throwIfDisposed<Session>(session => {
    // SAFETY: By definition of `disposed`, `#reason` is defined.
    return session.#reason!;
  })
  async send<T extends keyof Commands>(
    method: T,
    params: Commands[T]['params']
  ): Promise<{result: Commands[T]['returnType']}> {
    return await this.connection.send(method, params);
  }

  @throwIfDisposed<Session>(session => {
    // SAFETY: By definition of `disposed`, `#reason` is defined.
    return session.#reason!;
  })
  async subscribe(
    events: [string, ...string[]],
    contexts?: [string, ...string[]]
  ): Promise<void> {
    await this.send('session.subscribe', {
      events,
      contexts,
    });
  }

  @throwIfDisposed<Session>(session => {
    // SAFETY: By definition of `disposed`, `#reason` is defined.
    return session.#reason!;
  })
  async addIntercepts(
    events: [string, ...string[]],
    contexts?: [string, ...string[]]
  ): Promise<void> {
    await this.send('session.subscribe', {
      events,
      contexts,
    });
  }

  @throwIfDisposed<Session>(session => {
    // SAFETY: By definition of `disposed`, `#reason` is defined.
    return session.#reason!;
  })
  async end(): Promise<void> {
    try {
      await this.send('session.end', {});
    } finally {
      this.dispose(`Session already ended.`);
    }
  }

  [disposeSymbol](): void {
    this.#reason ??=
      'Session already destroyed, probably because the connection broke.';
    this.emit('ended', {reason: this.#reason});

    this.#disposables.dispose();
    super[disposeSymbol]();
  }
}