You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.3 KiB
68 lines
2.3 KiB
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import type { ElectronTRPCBridge } from 'electron-trpc/shared'
|
|
const mocks = vi.hoisted(() => ({
|
|
expose: vi.fn(),
|
|
send: vi.fn(),
|
|
on: vi.fn(),
|
|
off: vi.fn()
|
|
}))
|
|
vi.mock('electron', () => ({
|
|
contextBridge: { exposeInMainWorld: mocks.expose },
|
|
ipcRenderer: { send: mocks.send, on: mocks.on, off: mocks.off }
|
|
}))
|
|
import { exposeElectronTRPC } from 'electron-trpc/preload'
|
|
|
|
let bridge: ElectronTRPCBridge
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
exposeElectronTRPC()
|
|
bridge = mocks.expose.mock.calls[0]![1] as ElectronTRPCBridge
|
|
})
|
|
describe('sandboxed electron-trpc bridge', () => {
|
|
it('accepts only the declared envelope on its fixed channel', () => {
|
|
bridge.sendMessage({
|
|
method: 'request',
|
|
operation: { id: 1, path: 'notes.list', type: 'query' }
|
|
})
|
|
expect(mocks.send).toHaveBeenCalledWith(
|
|
'electron-trpc',
|
|
expect.objectContaining({ method: 'request' })
|
|
)
|
|
expect(() => bridge.sendMessage({ method: 'execute', channel: 'arbitrary' } as never)).toThrow()
|
|
expect(() =>
|
|
bridge.sendMessage({
|
|
method: 'request',
|
|
operation: {
|
|
id: 2,
|
|
path: 'notes.add',
|
|
type: 'mutation',
|
|
input: 'x'.repeat(300001)
|
|
}
|
|
})
|
|
).toThrow('Request too large')
|
|
expect(mocks.send).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('uses one native listener and releases it when the last observer leaves', () => {
|
|
const stops = Array.from({ length: 25 }, () => bridge.onMessage(vi.fn()))
|
|
expect(mocks.on).toHaveBeenCalledTimes(1)
|
|
for (const stop of stops.slice(0, -1)) stop()
|
|
expect(mocks.off).not.toHaveBeenCalled()
|
|
stops.at(-1)!()
|
|
expect(mocks.off).toHaveBeenCalledWith('electron-trpc', mocks.on.mock.calls[0]![1])
|
|
})
|
|
|
|
it('does not pass Electron event objects and isolates throwing callbacks', () => {
|
|
bridge.onMessage(() => {
|
|
throw new Error('renderer callback')
|
|
})
|
|
const listener = vi.fn()
|
|
bridge.onMessage(listener)
|
|
const receive = mocks.on.mock.calls[0]![1] as (event: object, raw: unknown) => void
|
|
const response = { id: 1, result: { type: 'data', data: 'hello' } }
|
|
receive({ privileged: true }, response)
|
|
expect(listener).toHaveBeenCalledExactlyOnceWith(response)
|
|
receive({}, null)
|
|
expect(listener).toHaveBeenCalledTimes(1)
|
|
})
|
|
})
|
|
|