示例工程 09-typed-ipc-contracts
09-typed-ipc-contracts/app/preload/index.ts
import { contextBridge, ipcRenderer } from "electron";
import {
CH,
type CaseReport,
type CreateNoteReq,
type Envelope,
type ListNotesReq,
type ListNotesRes,
type Note,
} from "../shared/ipc";
const api = {
createNote: (req: CreateNoteReq): Promise<Envelope<Note>> =>
ipcRenderer.invoke(CH.create, req) as Promise<Envelope<Note>>,
// 只用于演示:页面可以绕过 TS 发送任意值,主进程仍会校验。
createNoteRaw: (value: unknown): Promise<Envelope<Note>> =>
ipcRenderer.invoke(CH.create, value) as Promise<Envelope<Note>>,
listNotes: (req: ListNotesReq): Promise<Envelope<ListNotesRes>> =>
ipcRenderer.invoke(CH.list, req) as Promise<Envelope<ListNotesRes>>,
runCases: (): Promise<Envelope<CaseReport>> =>
ipcRenderer.invoke(CH.cases) as Promise<Envelope<CaseReport>>,
// 仅用于 smoke/shots 的确定性:清空内存中的笔记。
resetNotes: (): Promise<Envelope<{ cleared: boolean }>> =>
ipcRenderer.invoke(CH.reset) as Promise<Envelope<{ cleared: boolean }>>,
};
contextBridge.exposeInMainWorld("api", api);
export type Api = typeof api;