* Connect to the deployed Node Emulator instance.
()
| 57 | * Connect to the deployed Node Emulator instance. |
| 58 | */ |
| 59 | public async connect(): Promise<void> { |
| 60 | const { iframe, cdnUrl } = this.options; |
| 61 | |
| 62 | debug('[message-sender]: Connecting to node emulator...'); |
| 63 | |
| 64 | const connectionPromise = new DeferredPromise<void>(); |
| 65 | |
| 66 | if (!this.url) { |
| 67 | connectionPromise.reject( |
| 68 | new Error('Nodebox URL is missing. Did you forget to provide it when creating this Nodebox instance?') |
| 69 | ); |
| 70 | } |
| 71 | |
| 72 | invariant( |
| 73 | iframe.contentWindow, |
| 74 | 'Failed to create a MessageChannel with the Nodebox iframe: no content window found' |
| 75 | ); |
| 76 | |
| 77 | // Establish a message channel with the worker frame |
| 78 | // to communicate with the worker instance. |
| 79 | this.channel = new MessageSender(iframe.contentWindow); |
| 80 | |
| 81 | // Connect to the emulator. |
| 82 | const frameLoadPromise = new DeferredPromise<void>(); |
| 83 | iframe.setAttribute('src', this.url); |
| 84 | iframe.addEventListener( |
| 85 | 'load', |
| 86 | () => { |
| 87 | frameLoadPromise.resolve(); |
| 88 | }, |
| 89 | { once: true } |
| 90 | ); |
| 91 | iframe.addEventListener( |
| 92 | 'error', |
| 93 | (event) => { |
| 94 | frameLoadPromise.reject(event.error); |
| 95 | }, |
| 96 | { once: true } |
| 97 | ); |
| 98 | |
| 99 | // Wait until the Emulator iframe is ready |
| 100 | // before communicating with it. |
| 101 | await frameLoadPromise; |
| 102 | |
| 103 | debug('[message-sender]: IFrame loaded...'); |
| 104 | |
| 105 | // Await the worker frame to establish the receiver channel |
| 106 | // and confirm the functioning message port via handshake. |
| 107 | await this.channel.handshake(); |
| 108 | |
| 109 | debug('[message-sender]: Handshake completed...'); |
| 110 | |
| 111 | // Prompt a connection to the worker. |
| 112 | this.channel.send('connect', { |
| 113 | cdnUrl, |
| 114 | }); |
| 115 | |
| 116 | this.channel.on('runtime/ready', () => { |
no test coverage detected