-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.ts
92 lines (78 loc) · 2.76 KB
/
index.ts
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { TRPCClientError, TRPCLink } from '@trpc/client';
import type { AnyRouter } from '@trpc/server';
import { observable } from '@trpc/server/observable';
import type { TRPCChromeRequest, TRPCChromeResponse } from '../types';
export type ChromeLinkOptions = {
port: chrome.runtime.Port;
};
export const chromeLink = <TRouter extends AnyRouter>(
opts: ChromeLinkOptions,
): TRPCLink<TRouter> => {
return (runtime) => {
const { port } = opts;
return ({ op }) => {
return observable((observer) => {
const listeners: (() => void)[] = [];
const { id, type, path } = op;
try {
const input = runtime.transformer.serialize(op.input);
const onDisconnect = () => {
observer.error(new TRPCClientError('Port disconnected prematurely'));
};
port.onDisconnect.addListener(onDisconnect);
listeners.push(() => port.onDisconnect.removeListener(onDisconnect));
const onMessage = (message: TRPCChromeResponse) => {
if (!('trpc' in message)) return;
const { trpc } = message;
if (!trpc) return;
if (!('id' in trpc) || trpc.id === null || trpc.id === undefined) return;
if (id !== trpc.id) return;
if ('error' in trpc) {
const error = runtime.transformer.deserialize(trpc.error);
observer.error(TRPCClientError.from({ ...trpc, error }));
return;
}
observer.next({
result: {
...trpc.result,
...((!trpc.result.type || trpc.result.type === 'data') && {
type: 'data',
data: runtime.transformer.deserialize(trpc.result.data),
}),
} as any,
});
if (type !== 'subscription' || trpc.result.type === 'stopped') {
observer.complete();
}
};
port.onMessage.addListener(onMessage);
listeners.push(() => port.onMessage.removeListener(onMessage));
port.postMessage({
trpc: {
id,
jsonrpc: undefined,
method: type,
params: { path, input },
},
} as TRPCChromeRequest);
} catch (cause) {
observer.error(
new TRPCClientError(cause instanceof Error ? cause.message : 'Unknown error'),
);
}
return () => {
listeners.forEach((unsub) => unsub());
if (type === 'subscription') {
port.postMessage({
trpc: {
id,
jsonrpc: undefined,
method: 'subscription.stop',
},
} as TRPCChromeRequest);
}
};
});
};
};
};