Skip to content

Commit afb009e

Browse files
committed
feat: typed-ipc
1 parent 072e5c6 commit afb009e

File tree

12 files changed

+707
-5
lines changed

12 files changed

+707
-5
lines changed

.github/workflows/release-tag.yml

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ on:
55
- 'tsconfig*'
66
- 'preload*'
77
- 'eslint-config*'
8+
- 'typed-ipc*'
89

910
name: Create Release
1011

package.json

+7
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"lint": "eslint --ext .ts packages/*/src/**",
1212
"typecheck": "tsc --noEmit",
1313
"build:preload": "pnpm run -C packages/preload build",
14+
"build:ipc": "pnpm run -C packages/typed-ipc build",
1415
"build:utils": "pnpm run -C packages/utils build",
1516
"dev": "pnpm run -C packages/playground start"
1617
},
@@ -28,6 +29,9 @@
2829
]
2930
},
3031
"devDependencies": {
32+
"@rollup/plugin-commonjs": "^26.0.1",
33+
"@rollup/plugin-node-resolve": "^15.2.3",
34+
"@rollup/plugin-typescript": "^11.1.6",
3135
"@types/node": "^18.19.29",
3236
"@typescript-eslint/eslint-plugin": "^7.5.0",
3337
"@typescript-eslint/parser": "^7.5.0",
@@ -39,6 +43,9 @@
3943
"picocolors": "^1.0.0",
4044
"prettier": "^3.2.5",
4145
"rimraf": "^5.0.5",
46+
"rollup": "^4.21.0",
47+
"rollup-plugin-dts": "^6.1.1",
48+
"rollup-plugin-rm": "^1.0.2",
4249
"simple-git-hooks": "^2.11.1",
4350
"tslib": "^2.6.2",
4451
"typescript": "^5.4.3",

packages/typed-ipc/LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024-present, Alex.Wei
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

packages/typed-ipc/README.md

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# @electron-toolkit/typed-ipc
2+
3+
Type-safe Electron IPC, best practices in TypeScript.
4+
5+
Type checking and intellisense are available both in the main process and the renderer process. Both the listener parameters, handler parameters and return value types can be inspected and sensed, and you will not miss any modifications.
6+
7+
It provide a good development experience. Constrain the IPC registration of the main process and the calling of the renderer process, and avoid low-level errors. At the same time, it maintains the original writing method of IPC, which is more conducive to reading and understanding rather than over-encapsulating Electorn's IPC.
8+
9+
## Usage
10+
11+
### Install
12+
13+
```sh
14+
npm i @electron-toolkit/preload @electron-toolkit/typed-ipc
15+
```
16+
17+
### Get Started
18+
19+
1. Use [@electron-toolkit/preload](https://github.com/alex8088/electron-toolkit/tree/master/packages/preload) to expose Electron APIs.
20+
21+
You can expose it in the specified preload script:
22+
23+
```ts
24+
import { contextBridge } from 'electron'
25+
import { electronAPI } from '@electron-toolkit/preload'
26+
27+
if (process.contextIsolated) {
28+
try {
29+
contextBridge.exposeInMainWorld('electron', electronAPI)
30+
} catch (error) {
31+
console.error(error)
32+
}
33+
} else {
34+
window.electron = electronAPI
35+
}
36+
```
37+
38+
or
39+
40+
```ts
41+
import { exposeElectronAPI } from '@electron-toolkit/preload'
42+
43+
exposeElectronAPI()
44+
```
45+
46+
2. Add `*.d.ts` declaration file to define IPC event type constraints. And remember to include it in your tsconfig to make sure it takes effect.
47+
48+
```ts
49+
// Main process ipc events
50+
type IpcEvents =
51+
| {
52+
ping: [string] // listener event map
53+
}
54+
| {
55+
'say-hello': () => string // handler event map
56+
}
57+
58+
//Renderer ipc events
59+
type IpcRendererEvent = {
60+
ready: [boolean]
61+
}
62+
```
63+
64+
3. Register a listener or handler in the main process, or send a message to the renderer.
65+
66+
```ts
67+
import { IpcListenerIpcEmitter } from '@electron-toolkit/typed-ipc/main'
68+
69+
const ipc = new IpcListener<IpcEvents>()
70+
71+
const emitter = new IpcEmitter<IpcRendererEvent>()
72+
73+
ipc.on('ping', (e, arg) => {
74+
console.log(arg)
75+
emitter.send(e.sender, 'ready', true)
76+
})
77+
78+
ipc.handle('say-hello', () => {
79+
return 'hello'
80+
})
81+
```
82+
83+
4. Send a message from the render process to the main process, or listen for messages from the main process.
84+
85+
```ts
86+
import { IpcListenerIpcEmitter } from '@electron-toolkit/typed-ipc/renderer'
87+
88+
const ipc = new IpcListener<IpcRendererEvent>()
89+
90+
const emitter = new IpcEmitter<IpcEvents>()
91+
92+
ipc.on('ready', (e, arg) => {
93+
console.log(arg)
94+
})
95+
96+
emitter.send('ping', 'pong')
97+
98+
emitter.invoke('say-hello').then((str) => {
99+
console.log(str)
100+
})
101+
```
102+
103+
## License
104+
105+
[MIT](./LICENSE) © alex.wei

packages/typed-ipc/package.json

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "@electron-toolkit/typed-ipc",
3+
"version": "0.0.0",
4+
"description": "Type-safe Electron IPC, best practices in TypeScript.",
5+
"main": "dist/main.cjs",
6+
"module": "dist/main.mjs",
7+
"types": "dist/main.d.ts",
8+
"exports": {
9+
".": {
10+
"types": "./dist/main.d.ts",
11+
"import": "./dist/main.mjs",
12+
"require": "./dist/main.cjs"
13+
},
14+
"./main": {
15+
"types": "./dist/main.d.ts",
16+
"import": "./dist/main.mjs",
17+
"require": "./dist/main.cjs"
18+
},
19+
"./renderer": {
20+
"types": "./dist/renderer.d.ts",
21+
"import": "./dist/renderer.mjs"
22+
}
23+
},
24+
"files": [
25+
"dist"
26+
],
27+
"author": "Alex Wei<https://github.com/alex8088>",
28+
"license": "MIT",
29+
"repository": {
30+
"type": "git",
31+
"url": "git+https://github.com/alex8088/electron-toolkit.git",
32+
"directory": "packages/typed-ipc"
33+
},
34+
"bugs": {
35+
"url": "https://github.com/alex8088/electron-toolkit/issues"
36+
},
37+
"homepage": "https://github.com/alex8088/electron-toolkit/tree/master/packages/typed-ipc#readme",
38+
"keywords": [
39+
"electron",
40+
"toolkit",
41+
"ipc"
42+
],
43+
"scripts": {
44+
"build": "rollup -c rollup.config.ts --configPlugin typescript"
45+
},
46+
"peerDependencies": {
47+
"electron": ">=13.0.0",
48+
"@electron-toolkit/preload": ">=3.0.0"
49+
}
50+
}

packages/typed-ipc/rollup.config.ts

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/* eslint-disable @typescript-eslint/explicit-function-return-type */
2+
import { defineConfig } from 'rollup'
3+
import resolve from '@rollup/plugin-node-resolve'
4+
import commonjs from '@rollup/plugin-commonjs'
5+
import ts from '@rollup/plugin-typescript'
6+
import dts from 'rollup-plugin-dts'
7+
import rm from 'rollup-plugin-rm'
8+
9+
export default defineConfig([
10+
{
11+
input: ['src/main.ts'],
12+
output: [
13+
{
14+
entryFileNames: '[name].cjs',
15+
chunkFileNames: 'chunks/lib-[hash].cjs',
16+
format: 'cjs',
17+
dir: 'dist'
18+
},
19+
{
20+
entryFileNames: '[name].mjs',
21+
chunkFileNames: 'chunks/lib-[hash].mjs',
22+
format: 'es',
23+
dir: 'dist'
24+
}
25+
],
26+
external: ['electron'],
27+
plugins: [
28+
resolve(),
29+
commonjs(),
30+
ts({
31+
compilerOptions: {
32+
rootDir: 'src',
33+
declaration: true,
34+
outDir: 'dist/types'
35+
}
36+
}),
37+
rm('dist', 'buildStart')
38+
]
39+
},
40+
{
41+
input: ['src/renderer.ts'],
42+
output: [
43+
{ file: './dist/renderer.mjs', format: 'es' },
44+
{ name: 'renderer', file: './dist/renderer.js', format: 'iife' }
45+
],
46+
plugins: [
47+
ts({
48+
compilerOptions: {
49+
rootDir: 'src',
50+
declaration: true,
51+
outDir: 'dist/types'
52+
}
53+
})
54+
]
55+
},
56+
{
57+
input: ['dist/types/main.d.ts'],
58+
output: [{ file: './dist/main.d.ts', format: 'es' }],
59+
plugins: [dts()],
60+
external: ['electron']
61+
},
62+
{
63+
input: ['dist/types/renderer.d.ts'],
64+
output: [{ file: './dist/renderer.d.ts', format: 'es' }],
65+
plugins: [dts(), rm('dist/types', 'buildEnd')]
66+
}
67+
])

packages/typed-ipc/src/global.d.ts

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { ElectronAPI } from '@electron-toolkit/preload'
2+
3+
declare global {
4+
interface Window {
5+
electron: ElectronAPI
6+
}
7+
}

packages/typed-ipc/src/main.ts

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/* eslint-disable @typescript-eslint/no-explicit-any */
2+
import { ipcMain } from 'electron'
3+
import type { IpcEventMap, IpcListenEventMap, ExtractArgs, ExtractHandler } from './types'
4+
5+
export * from './types'
6+
7+
/**
8+
* Typed listener for Electron `ipcMain`.
9+
*/
10+
export class IpcListener<T extends IpcEventMap> {
11+
private listeners: string[] = []
12+
private handlers: string[] = []
13+
14+
/**
15+
* Listen to `channel`.
16+
*/
17+
on<E extends keyof ExtractArgs<T>>(
18+
channel: Extract<E, string>,
19+
listener: (e: Electron.IpcMainEvent, ...args: ExtractArgs<T>[E]) => void | Promise<void>
20+
): void {
21+
this.listeners.push(channel)
22+
ipcMain.on(channel, listener as (e: Electron.IpcMainEvent, ...args: any[]) => void)
23+
}
24+
25+
/**
26+
* Handle a renderer invoke request.
27+
*/
28+
handle<E extends keyof ExtractHandler<T>>(
29+
channel: Extract<E, string>,
30+
listener: (
31+
e: Electron.IpcMainInvokeEvent,
32+
...args: Parameters<ExtractHandler<T>[E]>
33+
) => ReturnType<ExtractHandler<T>[E]> | Promise<ReturnType<ExtractHandler<T>[E]>>
34+
): void {
35+
this.handlers.push(channel)
36+
ipcMain.handle(channel, listener as (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any)
37+
}
38+
39+
/**
40+
* Dispose all listeners and handlers.
41+
*/
42+
dispose(): void {
43+
this.listeners.forEach(c => ipcMain.removeAllListeners(c))
44+
this.listeners = []
45+
this.handlers.forEach(c => ipcMain.removeHandler(c))
46+
this.handlers = []
47+
}
48+
}
49+
50+
/**
51+
* Typed emitter for sending an asynchronous message to the renderer process.
52+
*/
53+
export class IpcEmitter<T extends IpcListenEventMap> {
54+
/**
55+
* Send an asynchronous message to the renderer process.
56+
*/
57+
send<E extends keyof T>(sender: Electron.WebContents, channel: Extract<E, string>, ...args: T[E]): void {
58+
sender.send(channel, ...args)
59+
}
60+
}

packages/typed-ipc/src/renderer.ts

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/* eslint-disable @typescript-eslint/no-explicit-any */
2+
import type { IpcEventMap, IpcListenEventMap, ExtractArgs, ExtractHandler } from './types'
3+
4+
export * from './types'
5+
6+
/**
7+
* Typed emitter for Electron `ipcRenderer`.
8+
*/
9+
export class IpcEmitter<T extends IpcEventMap> {
10+
send<E extends keyof ExtractArgs<T>>(channel: Extract<E, string>, ...args: ExtractArgs<T>[E]): void {
11+
window.electron.ipcRenderer.send(channel, ...args)
12+
}
13+
14+
invoke<E extends keyof ExtractHandler<T>>(
15+
channel: Extract<E, string>,
16+
...args: Parameters<ExtractHandler<T>[E]>
17+
): Promise<ReturnType<ExtractHandler<T>[E]>> {
18+
return window.electron.ipcRenderer.invoke(channel, ...args)
19+
}
20+
}
21+
22+
/**
23+
* Typed listener for Electron `ipcRenderer`.
24+
*/
25+
export class IpcListener<T extends IpcListenEventMap> {
26+
on<E extends keyof T>(
27+
channel: Extract<E, string>,
28+
listener: (e: Electron.IpcRendererEvent, ...args: T[E]) => void
29+
): void | Promise<void> {
30+
window.electron.ipcRenderer.on(channel, listener as (event: Electron.IpcRendererEvent, ...args: any[]) => void)
31+
}
32+
33+
once<E extends keyof T>(
34+
channel: Extract<E, string>,
35+
listener: (e: Electron.IpcRendererEvent, ...args: T[E]) => void | Promise<void>
36+
): () => void {
37+
return window.electron.ipcRenderer.once(
38+
channel,
39+
listener as (event: Electron.IpcRendererEvent, ...args: any[]) => void
40+
)
41+
}
42+
}

0 commit comments

Comments
 (0)