-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
371 lines (327 loc) · 11 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
interface TransformedObject {
_IS_TRANSFORMED_: true;
type: 'fn' | 'fn_str';
id: string | number;
code?: string;
}
function isTransformedObject(obj: any): obj is TransformedObject {
return obj && obj._IS_TRANSFORMED_ === true;
}
const transformData = (obj: any, cache = new Map(), idGen = (function* () {
let id = 0;
while (true) {
yield id++;
}
})()) => {
if (cache.has(obj)) return cache.get(obj);
if (typeof obj !== 'object' && typeof obj !== 'function') {
return obj;
}
if (obj === null) return obj;
if (isTransformedObject(obj)) return obj;
if (typeof obj === 'function') {
const transformed = {
id: idGen.next().value,
type: 'fn_str' as const,
code: obj.toString(),
_IS_TRANSFORMED_: true
};
cache.set(obj, transformed);
return transformed;
}
const newObj = Array.isArray(obj) ? new Array(obj.length) : {};
cache.set(obj, newObj); // Set cache early to handle circular references
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
// @ts-ignore
newObj[key] = transformData(obj[key], cache, idGen);
}
}
return newObj;
}
const createRequest = (event: RuntimeEvent, name: string, args: any, transfer: Transferable[] = [], timeout = 5000) => {
const reqid = generateUniqueId(event);
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
event.promises.delete(reqid);
reject(new Error('Request timed out'));
}, timeout);
event.promises.set(reqid, {
resolve: (value: any) => {
clearTimeout(timeoutId);
resolve(value);
},
reject: (error: any) => {
clearTimeout(timeoutId);
reject(error);
}
});
const transferMap = new Map(transfer.map(v => [v, v]));
const transformedArgs = transformData(args, transferMap);
event.thread.postMessage({
__IS_TYPED_WORKER__: true,
isRequest: true,
reqid,
name,
args: transformedArgs,
}, { transfer });
}).finally(() => {
event.promises.delete(reqid);
});
};
const generateUniqueId = (event: RuntimeEvent): string => {
let reqid: string;
do {
reqid = Math.random().toString(36).slice(2);
} while (event.promises.has(reqid));
return reqid;
};
const restoreMessage = (event: RuntimeEvent, root: MessageEvent, obj = root.data.data, cache = new Map()) => {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
return new Proxy(obj, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
if (typeof value !== 'object' || value === null) {
return value;
}
if (isTransformedObject(value)) {
switch (value.type) {
case 'fn': {
if (cache.has(value.id)) {
return cache.get(value.id);
}
const fn = function (...args: any[]) {
// @ts-ignore
return createRequest(event, value.id as string, args, fn.transfer, fn.timeout);
};
// @ts-ignore
fn.transfer = [];
fn.timeout = 5000;
cache.set(value.id, fn);
return fn;
}
case 'fn_str': {
if (!cache.has(value.id)) {
cache.set(value.id, new Function('return ' + value.code)());
}
return cache.get(value.id);
}
}
}
return restoreMessage(event, root, value, cache);
}
});
}
type CommRequest = {
__IS_TYPED_WORKER__: true;
isRequest: true;
reqid: string;
name: string;
args: unknown[];
};
type CommResult = {
__IS_TYPED_WORKER__: true;
isRequest: false;
reqid: string;
isReject?: boolean;
data: unknown;
};
type RuntimeEvent = {
thread: Worker | Window,
handlers: Map<string, Function>
promises: Map<string, { resolve: Function; reject: Function; }>
cg: WeakMap<Function, number>
}
const TEMP_FUNCTION_CG = 30 * 1000;
export const TEMP_NAME_PREFIX = 'temp_fn_';
const createRuntime = (thread: Worker | Window): RuntimeEvent => ({
thread,
handlers: new Map(),
promises: new Map(),
cg: new WeakMap(),
});
const messageHandler = (event: RuntimeEvent) => {
const { thread, handlers, promises, cg } = event;
let cgCleanupId = 0;
const cleanupTempHandlers = () => {
const now = Date.now();
for (const [name, fn] of handlers) {
if (!name.startsWith(TEMP_NAME_PREFIX)) continue;
if (!cg.has(fn)) {
cg.set(fn, now);
continue;
}
if (now - cg.get(fn)! > TEMP_FUNCTION_CG) {
handlers.delete(name);
cg.delete(fn);
}
}
};
return async (m: MessageEvent<CommRequest | CommResult>) => {
const data = m.data;
if (!data?.__IS_TYPED_WORKER__) return;
try {
if (data.isRequest) {
const fn = handlers.get(data.name);
if (!fn) {
throw new Error(`Function "${data.name}" not found`);
}
cg.has(fn) && cg.set(fn, Date.now());
const args = restoreMessage(event, m, data.args);
const result = await fn(...args);
thread.postMessage({
__IS_TYPED_WORKER__: true,
isRequest: false,
reqid: data.reqid,
data: transformData(result),
});
} else {
const promise = promises.get(data.reqid);
if (promise) {
const res = data.data;
const unpacked = (typeof res === 'object' && res !== null)
? restoreMessage(event, m)
: res;
data.isReject ? promise.reject(unpacked) : promise.resolve(unpacked);
}
}
} catch (error) {
console.error('Worker message handling error:', error);
if (data.isRequest) {
thread.postMessage({
__IS_TYPED_WORKER__: true,
isRequest: false,
reqid: data.reqid,
isReject: true,
data: transformData(error instanceof Error ? error.message : String(error)),
});
} else {
promises.get(data.reqid)?.reject(error);
}
}
cgCleanupId && clearTimeout(cgCleanupId);
cgCleanupId = setTimeout(cleanupTempHandlers, TEMP_FUNCTION_CG);
};
};
/**
* Define message handlers for a Web Worker
*
* @param e - Object containing handler functions to be registered
* @returns A function that returns a WorkerEvent object
*
* @example
* ```ts
* // worker.ts
* import { defineReceive } from 'typed-worker';
*
* export default defineReceive({
* add: (a: number, b: number) => a + b,
* getData: async () => {
* const response = await fetch('https://api.example.com/data');
* return response.json();
* }
* });
* ```
*/
export const defineReceive = <T extends Record<string, (...args: any[]) => any>>(e: T) => {
const event = createRuntime(self);
Object.entries(e).forEach(([name, fn]) => {
event.handlers.set(name, fn);
});
self.onmessage = messageHandler(event);
return null as unknown as () => WorkerEvent<T>;
}
export type WorkerCallBack<T> = (T extends (...args: any[]) => any ? (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> : never) & {
transfer: Transferable[];
timeout: number;
};
type WorkerEvent<T extends Record<string, (...args: any[]) => any>> = {
worker: Worker;
event: RuntimeEvent
cb: <F extends Function>(e: F, name?: string) => WorkerCallBack<F>;
methods: { [K in keyof T]: WorkerCallBack<T[K]>; } & { timeout: number; }
}
/**
* Create a typed interface for communicating with a Web Worker
*
* @param worker - Web Worker instance to communicate with
* @returns WorkerEvent object containing typed methods matching the worker's handlers
*
* @example
* ```ts
* // main.ts
* import { useWorker } from 'typed-worker';
*
* const worker = new Worker('worker.js');
*
* interface WorkerAPI {
* add(a: number, b: number): number;
* getData(): Promise<any>;
* }
*
* const { methods } = useWorker<WorkerAPI>(worker);
*
* // Type-safe worker calls
* const sum = await methods.add(1, 2); // Returns: 3
* const data = await methods.getData(); // Returns API data
*
* // Configure timeout for all methods
* methods.timeout = 10000; // 10 seconds
*
* // Configure transferable objects
* const { getData } = methods;
* const buffer = new ArrayBuffer(1024);
* getData.transfer = [buffer];
* ```
*/
export const useWorker = <T extends Record<string, (...args: any[]) => any>>(worker: Worker): WorkerEvent<T> => {
const event = createRuntime(worker);
const cleanup = () => {
event.handlers.clear();
event.promises.forEach(p => p.reject(new Error('Worker connection terminated')));
event.promises.clear();
};
worker.addEventListener('error', (e) => {
console.error('Worker error:', e);
cleanup();
});
worker.addEventListener('messageerror', (e) => {
console.error('Worker message error:', e);
cleanup();
});
worker.addEventListener('message', messageHandler(event));
// @ts-ignore
return {
worker,
event,
cb: (e, name) => {
let id = name || generateUniqueId(event);
while (!name && event.handlers.has(id)) {
id = TEMP_NAME_PREFIX + Math.random().toString(36).slice(2);
}
event.handlers.set(id, e);
return {
_IS_TRANSFORMED_: true,
type: 'fn',
id, // Use the same id for both handler and transformed object
}
},
methods: new Proxy({
timeout: 5000,
}, {
get(_target, name) {
if (Reflect.has(_target, name)) return Reflect.get(_target, name);
const fn = function (...args: any[]) {
// @ts-ignore
return createRequest(event, name as string, args, fn.transfer, fn.timeout);
}
// @ts-ignore
fn.transfer = [];
fn.timeout = Reflect.get(_target, 'timeout');
return fn;
}
})
} as WorkerEvent<T>
};