All files / src/onboarding/webview vscode-api.ts

0% Statements 0/12
100% Branches 1/1
100% Functions 1/1
0% Lines 0/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                               
/**
 * Thin typed wrapper around the VS Code webview API.
 *
 * The webview runs in a sandboxed browser context where `acquireVsCodeApi`
 * is injected by the host. We grab it once and expose strict typed `post()`
 * and `onMessage()` helpers backed by the shared discriminated-union types.
 */
 
import type { ExtensionToWebview, WebviewToExtension } from "../messages";
 
interface VsCodeWebviewApi {
    postMessage(message: unknown): void;
    setState(state: unknown): void;
    getState(): unknown;
}
 
declare function acquireVsCodeApi(): VsCodeWebviewApi;
 
const api = acquireVsCodeApi();
 
export const vscode = {
    post(message: WebviewToExtension): void {
        api.postMessage(message);
    },
    onMessage(handler: (message: ExtensionToWebview) => void): () => void {
        const listener = (event: MessageEvent<ExtensionToWebview>) =>
            handler(event.data);
        window.addEventListener("message", listener);
        return () => window.removeEventListener("message", listener);
    },
};