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

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

import type {ElementHandle} from '../api/ElementHandle.js';
import {JSHandle} from '../api/JSHandle.js';
import {UnsupportedOperation} from '../common/Errors.js';

import {BidiDeserializer} from './Deserializer.js';
import type {BidiRealm} from './Realm.js';
import type {Sandbox} from './Sandbox.js';
import {releaseReference} from './util.js';

/**
 * @internal
 */
export class BidiJSHandle<T = unknown> extends JSHandle<T> {
  #disposed = false;
  readonly #sandbox: Sandbox;
  readonly #remoteValue: Bidi.Script.RemoteValue;

  constructor(sandbox: Sandbox, remoteValue: Bidi.Script.RemoteValue) {
    super();
    this.#sandbox = sandbox;
    this.#remoteValue = remoteValue;
  }

  context(): BidiRealm {
    return this.realm.environment.context();
  }

  override get realm(): Sandbox {
    return this.#sandbox;
  }

  override get disposed(): boolean {
    return this.#disposed;
  }

  override async jsonValue(): Promise<T> {
    return await this.evaluate(value => {
      return value;
    });
  }

  override asElement(): ElementHandle<Node> | null {
    return null;
  }

  override async dispose(): Promise<void> {
    if (this.#disposed) {
      return;
    }
    this.#disposed = true;
    if ('handle' in this.#remoteValue) {
      await releaseReference(
        this.context(),
        this.#remoteValue as Bidi.Script.RemoteReference
      );
    }
  }

  get isPrimitiveValue(): boolean {
    switch (this.#remoteValue.type) {
      case 'string':
      case 'number':
      case 'bigint':
      case 'boolean':
      case 'undefined':
      case 'null':
        return true;

      default:
        return false;
    }
  }

  override toString(): string {
    if (this.isPrimitiveValue) {
      return 'JSHandle:' + BidiDeserializer.deserialize(this.#remoteValue);
    }

    return 'JSHandle@' + this.#remoteValue.type;
  }

  override get id(): string | undefined {
    return 'handle' in this.#remoteValue ? this.#remoteValue.handle : undefined;
  }

  remoteValue(): Bidi.Script.RemoteValue {
    return this.#remoteValue;
  }

  override remoteObject(): never {
    throw new UnsupportedOperation('Not available in WebDriver BiDi');
  }
}