📄 src/models/worker/libs/threadWorker.ts
D-OPEN SOVEREIGN
1
2/*
3 * Copyright (c) 2026 DataPond D-Library Pty Ltd. ("The Sanctuary")
4 * Non-Profit Public Library — The World Library
5 * 
6 * D-SAFE Certification issued by POND Enterprise.
7 * Published under the D-Open Code Sovereign Licence v1.0 framework
8 * DataPond D-Library All exclusive Right reserved on modifiying the code - CC Attribution to data pond, Non modifiable, Non Commercial.
9 * https://registry.world.bibliotech.com/licence
10 * Source code donated to DataPond D-Library by it's author: data pond.
11 * 
12 * Technical Guardian ("The Shield"): Pond Enterprise Pty Ltd. (ACN 694 747 987)
13 * All liability claims about D-SAFE certification issues coming from the published D-Safe direction must be addressed with Pond Enterprise Pty Ltd.
14 * Code Modification automatically voids the certified liability protection provided by Pond Enterprise.
15 */
16import {WorkerEvent, } from "../../enums.ts";
17
18
19
20export class ThreadWorker {
21    constructor() {
22        self.onmessage = e => this._onMessage(e.data);
23
24        self.addEventListener('error', (e) => {
25            console.log('worker error', e)
26        })
27
28        this.onCreate();
29    }
30    onCreate() {}
31
32    _onMessage(e:any) {
33        const { id, data } = e;
34        this.onRequest(id, data);
35    }
36
37    // abstract
38    onRequest(id:string, payload:any) {}
39
40    _sendResponse(id:string, data:any, opts={}) {
41        const defaults = {
42            transferables: [],
43            error: undefined,
44        };
45        const actual = Object.assign({}, defaults, opts);
46        const error = actual.error;
47        // @ts-ignore
48        self.postMessage({
49            id: id,
50            result: { data, error },
51            // @ts-ignore
52        }, actual.transferables.length > 0 ? actual.transferables : undefined);
53    }
54    postEvent(eventName: WorkerEvent, payload: any) {
55        self.postMessage({
56            eventName,
57            payload,
58        })
59    }
60    sendResponse(id:string, payload=undefined, transferables=[]) {
61        this._sendResponse(id, payload, { transferables });
62    }
63    sendError(id:string, error: Error) {
64        console.trace(error)
65        console.error(`[worker] sendError(): id: ${id}, error: ${error.message}`)
66        this._sendResponse(id, undefined, { error });
67    }
68}