Skip to content

Commit

Permalink
Improve IPC types; throw if ipc not enabled (#64)
Browse files Browse the repository at this point in the history
Improve the event types so that the IPC message types work as expected for `webview.on("ipc", { message }, ...`

If listening to IPC but IPC isn't enabled throw an error. I may downgrade this later to a warning.
zephraph authored Sep 26, 2024
1 parent 34af1e2 commit a6c4723
Showing 2 changed files with 23 additions and 8 deletions.
1 change: 0 additions & 1 deletion examples/ipc.ts
Original file line number Diff line number Diff line change
@@ -7,7 +7,6 @@ using webview = await createWebView({
ipc: true,
});

// @ts-expect-error event emitter types still need to be corrected
webview.on("ipc", ({ message }) => {
console.log(message);
});
30 changes: 23 additions & 7 deletions src/lib.ts
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ import {
WebViewResponse,
} from "./schemas.ts";
import { monotonicUlid as ulid } from "jsr:@std/ulid";
import type { Except } from "npm:type-fest";
import type { Except, Simplify } from "npm:type-fest";
import { join } from "jsr:@std/path";
import { ensureDir, exists } from "jsr:@std/fs";

@@ -210,6 +210,7 @@ export class WebView implements Disposable {
#internalEvent = new EventEmitter();
#externalEvent = new EventEmitter();
#messageLoop: Promise<void>;
#options: WebViewOptions;

/**
* Creates a new webview window.
@@ -218,6 +219,7 @@ export class WebView implements Disposable {
* @param webviewBinaryPath - The path to the webview binary.
*/
constructor(options: WebViewOptions, webviewBinaryPath: string) {
this.#options = options;
this.#process = new Deno.Command(webviewBinaryPath, {
args: [JSON.stringify(options)],
stdin: "piped",
@@ -328,20 +330,34 @@ export class WebView implements Disposable {
/**
* Listens for events emitted by the webview.
*/
on(
event: WebViewNotification["$type"],
callback: (event: WebViewNotification) => void,
on<E extends WebViewNotification["$type"]>(
event: E,
callback: (
event: Simplify<
Omit<Extract<WebViewNotification, { $type: E }>, "$type">
>,
) => void,
) {
if (event === "ipc" && !this.#options.ipc) {
throw new Error("IPC is not enabled for this webview");
}
this.#externalEvent.on(event, callback);
}

/**
* Listens for a single event emitted by the webview.
*/
once(
event: WebViewNotification["$type"],
callback: (event: WebViewNotification) => void,
once<E extends WebViewNotification["$type"]>(
event: E,
callback: (
event: Simplify<
Omit<Extract<WebViewNotification, { $type: E }>, "$type">
>,
) => void,
) {
if (event === "ipc" && !this.#options.ipc) {
throw new Error("IPC is not enabled for this webview");
}
this.#externalEvent.once(event, callback);
}

0 comments on commit a6c4723

Please sign in to comment.