| 26 | import {isTypedArrayBrowser} from './is_typed_array_browser'; |
| 27 | |
| 28 | export class PlatformBrowser implements Platform { |
| 29 | // According to the spec, the built-in encoder can do only UTF-8 encoding. |
| 30 | // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder |
| 31 | private textEncoder: TextEncoder; |
| 32 | |
| 33 | // For setTimeoutCustom |
| 34 | private readonly messageName = 'setTimeoutCustom'; |
| 35 | private functionRefs: Function[] = []; |
| 36 | private handledMessageCount = 0; |
| 37 | private hasEventListener = false; |
| 38 | |
| 39 | fetch(path: string, init?: RequestInit): Promise<Response> { |
| 40 | return fetch(path, init); |
| 41 | } |
| 42 | |
| 43 | now(): number { |
| 44 | return performance.now(); |
| 45 | } |
| 46 | |
| 47 | encode(text: string, encoding: string): Uint8Array { |
| 48 | if (encoding !== 'utf-8' && encoding !== 'utf8') { |
| 49 | throw new Error( |
| 50 | `Browser's encoder only supports utf-8, but got ${encoding}`); |
| 51 | } |
| 52 | if (this.textEncoder == null) { |
| 53 | this.textEncoder = new TextEncoder(); |
| 54 | } |
| 55 | return this.textEncoder.encode(text); |
| 56 | } |
| 57 | decode(bytes: Uint8Array, encoding: string): string { |
| 58 | return new TextDecoder(encoding).decode(bytes); |
| 59 | } |
| 60 | |
| 61 | // If the setTimeout nesting level is greater than 5 and timeout is less |
| 62 | // than 4ms, timeout will be clamped to 4ms, which hurts the perf. |
| 63 | // Interleaving window.postMessage and setTimeout will trick the browser and |
| 64 | // avoid the clamp. |
| 65 | setTimeoutCustom(functionRef: Function, delay: number): void { |
| 66 | if (typeof window === 'undefined' || |
| 67 | !env().getBool('USE_SETTIMEOUTCUSTOM')) { |
| 68 | setTimeout(functionRef, delay); |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | this.functionRefs.push(functionRef); |
| 73 | setTimeout(() => { |
| 74 | window.postMessage( |
| 75 | {name: this.messageName, index: this.functionRefs.length - 1}, '*'); |
| 76 | }, delay); |
| 77 | |
| 78 | if (!this.hasEventListener) { |
| 79 | this.hasEventListener = true; |
| 80 | window.addEventListener('message', (event: MessageEvent) => { |
| 81 | if (event.source === window && event.data.name === this.messageName) { |
| 82 | event.stopPropagation(); |
| 83 | const functionRef = this.functionRefs[event.data.index]; |
| 84 | functionRef(); |
| 85 | this.handledMessageCount++; |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…