|
| 1 | +/** |
| 2 | + * Copyright (c) Microsoft Corporation. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { debugLogger } from '@utils/debugLogger'; |
| 18 | +import { createHttpServer } from '@utils/network'; |
| 19 | + |
| 20 | +import type { IncomingMessage, Server, ServerResponse } from 'http'; |
| 21 | + |
| 22 | +export type DialogRequest = { |
| 23 | + type: 'alert' | 'confirm' | 'prompt'; |
| 24 | + message: string; |
| 25 | + defaultValue: string; |
| 26 | +}; |
| 27 | + |
| 28 | +export type DialogResult = { |
| 29 | + accept: boolean; |
| 30 | + promptText?: string; |
| 31 | +}; |
| 32 | + |
| 33 | +type DialogHandler = (req: DialogRequest) => Promise<DialogResult>; |
| 34 | + |
| 35 | +export class DialogBridge { |
| 36 | + private readonly _server: Server; |
| 37 | + private readonly _baseUrl: string; |
| 38 | + private readonly _handlers = new Map<string, DialogHandler>(); |
| 39 | + |
| 40 | + static async start(): Promise<DialogBridge> { |
| 41 | + const server = createHttpServer(); |
| 42 | + await new Promise<void>((resolve, reject) => { |
| 43 | + server.once('error', reject); |
| 44 | + server.listen(0, '127.0.0.1', () => { |
| 45 | + server.removeListener('error', reject); |
| 46 | + resolve(); |
| 47 | + }); |
| 48 | + }); |
| 49 | + const address = server.address(); |
| 50 | + if (!address || typeof address === 'string') |
| 51 | + throw new Error('DialogBridge: failed to bind HTTP server'); |
| 52 | + return new DialogBridge(server, `http://127.0.0.1:${address.port}`); |
| 53 | + } |
| 54 | + |
| 55 | + private constructor(server: Server, baseUrl: string) { |
| 56 | + this._server = server; |
| 57 | + this._baseUrl = baseUrl; |
| 58 | + this._server.on('request', (req, res) => this._handleRequest(req, res)); |
| 59 | + } |
| 60 | + |
| 61 | + endpointFor(pageId: string): string { |
| 62 | + return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`; |
| 63 | + } |
| 64 | + |
| 65 | + registerTab(pageId: string, handler: DialogHandler): void { |
| 66 | + this._handlers.set(pageId, handler); |
| 67 | + } |
| 68 | + |
| 69 | + unregisterTab(pageId: string): void { |
| 70 | + this._handlers.delete(pageId); |
| 71 | + } |
| 72 | + |
| 73 | + async close(): Promise<void> { |
| 74 | + this._handlers.clear(); |
| 75 | + await new Promise<void>(resolve => this._server.close(() => resolve())); |
| 76 | + } |
| 77 | + |
| 78 | + private _writeCorsHeaders(res: ServerResponse): void { |
| 79 | + res.setHeader('Access-Control-Allow-Origin', '*'); |
| 80 | + res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); |
| 81 | + res.setHeader('Access-Control-Allow-Headers', 'content-type'); |
| 82 | + } |
| 83 | + |
| 84 | + private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> { |
| 85 | + this._writeCorsHeaders(res); |
| 86 | + |
| 87 | + if (req.method === 'OPTIONS') { |
| 88 | + res.statusCode = 204; |
| 89 | + res.end(); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + const url = new URL(req.url || '/', this._baseUrl); |
| 94 | + if (!(req.method === 'POST' && url.pathname === '/dialog')) { |
| 95 | + res.statusCode = 404; |
| 96 | + res.end(); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + const tab = url.searchParams.get('tab') || ''; |
| 101 | + const handler = this._handlers.get(tab); |
| 102 | + if (!handler) { |
| 103 | + // Either the tab is gone or the page raced ahead of registerTab. Reply |
| 104 | + // 404 so the page-side override silently falls through. |
| 105 | + res.statusCode = 404; |
| 106 | + res.end(); |
| 107 | + return; |
| 108 | + } |
| 109 | + |
| 110 | + let body = ''; |
| 111 | + req.setEncoding('utf8'); |
| 112 | + req.on('data', chunk => { body += chunk; }); |
| 113 | + req.on('end', async () => { |
| 114 | + let parsed: DialogRequest; |
| 115 | + try { |
| 116 | + const json = JSON.parse(body); |
| 117 | + if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt') |
| 118 | + throw new Error(`Invalid dialog type: ${json.type}`); |
| 119 | + parsed = { |
| 120 | + type: json.type, |
| 121 | + message: typeof json.message === 'string' ? json.message : '', |
| 122 | + defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '', |
| 123 | + }; |
| 124 | + } catch (e) { |
| 125 | + debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`); |
| 126 | + res.statusCode = 400; |
| 127 | + res.end(); |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + try { |
| 132 | + const result = await handler(parsed); |
| 133 | + res.statusCode = 200; |
| 134 | + res.setHeader('Content-Type', 'application/json'); |
| 135 | + res.end(JSON.stringify({ |
| 136 | + accept: !!result.accept, |
| 137 | + promptText: result.promptText, |
| 138 | + })); |
| 139 | + } catch (e) { |
| 140 | + debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`); |
| 141 | + res.statusCode = 500; |
| 142 | + res.end(); |
| 143 | + } |
| 144 | + }); |
| 145 | + } |
| 146 | +} |
0 commit comments