VaKeR CYBER ARMY
Logo of a company Server : Apache/2.4.41 (Ubuntu)
System : Linux absol.cf 5.4.0-198-generic #218-Ubuntu SMP Fri Sep 27 20:18:53 UTC 2024 x86_64
User : www-data ( 33)
PHP Version : 7.4.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Directory :  /var/www/html/keeview_app/html/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/html/keeview_app/html/jsthread.js
class JSThreadPromise extends Promise {
    constructor (executor) {
        return super((resolve, reject) => {
            Thread.execFunc(executor, [resolve, reject]);
        });
    }

    then (onFulfilled, onRejected) {
        if ((onRejected === undefined) || (!EncodingClass.type.isFunction(onRejected))) {
            this.traceError = new Error("Promise onRejected");
            return super.then(function (...args) {
                var r;
                if (EncodingClass.type.isFunction(onFulfilled)) {
                    return Thread.execFunc(onFulfilled, args);
                }
                if (args.length == 1) {
                    return args[0];
                }
                else if (args.length == 0) {
                    return undefined;
                }
                else {
                    return args;
                }
            }, onRejected);
        }
        return super.then(
            function (...args) {
                var r;
                if (EncodingClass.type.isFunction(onFulfilled)) {
                    return Thread.execFunc(onFulfilled, args);
                }
                if (args.length == 1) {
                    return args[0];
                }
                else if (args.length == 0) {
                    return undefined;
                }
                else {
                    return args;
                }
            },
            function (...args) {
                return Thread.execFunc(onRejected, args);
            }
        );
    }
}

Promise = JSThreadPromise;

const Thread = Object.freeze(function () {
    var thread_retval = {};
    var core = {
        rawSetTimeout: function (oldfunc) {
            return function (func, ...args) {
                return oldfunc(func, ...args);
            }
        } (window.setTimeout),
        queue: [],
        activeThreadCount: 0,
        hookList: []
    };

    thread_retval.generateBlob = function (params) {
        var xurl = window.URL || window.webkitURL;
        var st = [];
        if (typeof(Worker) === "undefined") return null;
        if (!window.Worker) return null;
        if ((params.func === undefined) &&  (params.afunc === undefined)) return null;
        if (params.extcode !== undefined) st.push(params.extcode + "\n");
        if (params.modules !== undefined) {
            keys = Object.keys(params.modules);
            for (i = 0; i < keys.length; i++) {
                st.push("\r\nvar " + keys[i] + " = " + EncodingClass.string.exportVariable(params.modules[keys[i]]) + ";\r\n");
            }
        }
        if (params.func !== undefined) {
            st.push("var ThreadFunction = " + params.func.toString() + ";\r\n");
        }
        if (params.afunc !== undefined) {
            st.push("var callbackfunc = function (retval, transferList) {if (transferList !== undefined) postMessage(retval, transferList); else postMessage(retval);};\r\n");
            st.push("var AThreadFunction = " + params.afunc.toString() + ";\r\n");
        }
        st.push("var main = {}; transferList = null;\r\n");
        st.push("onmessage = function(e) {var r; if (e.data.type == 'sync') ");
        st.push("{r = ThreadFunction(e.data.params); if (transferList !== null) {postMessage(r, transferList); transferList = null;} else postMessage(r);} else {AThreadFunction(e.data.params, callbackfunc);} };\r\n");
        st = EncodingClass.string.merge(st);
        return xurl.createObjectURL(new Blob([ st ], { type: "text/javascript" }));
    };

    core.execCall = function () {
        var c, x;
        while ((core.queue.length > 0) && (core.activeThreadCount < navigator.hardwareConcurrency)) {
            c = core.queue.shift();
            try {
                if (c.transferList !== undefined) {
                    c.instance.postMessage(c.params, c.transferList);
                }
                else {
                    c.instance.postMessage(c.params);
                }
                core.activeThreadCount++;
            }
            catch (e) {
                Thread.setTimeout({ func: core.execCall });
                if (c.stack != "") {
                    x = e.message + "\r\n=================\r\n" + c.stack;
                    x = new Error(x);
                    throw x;
                }
                else {
                    throw e;
                }
            }
        }
    };

    core.insertCall = function (workerInstance, params, stack, transferList) {
        var nParams = EncodingClass.string.duplicateObject(params);
        var nTransferList = [];
        var i;
        if (transferList !== undefined) {
            for (i = 0; i < transferList.length; i++) {
                nTransferList.push(transferList[i]);
            }
            core.queue.push({
                instance: workerInstance,
                params: nParams,
                transferList: nTransferList,
                stack: stack
            });
        }
        else {
            core.queue.push({
                instance: workerInstance,
                params: nParams,
                stack: stack
            });
        }
        core.execCall();
    };

    thread_retval.createFromBlob = function (params) {
        var rv = [], n;
        var r, i;
        params = EncodingClass.string.duplicateObject(params);
        if (params.n !== undefined) {
            n = params.n;
        }
        else {
            n = 1;
        }
        if (n < 1) n = 1;
        for (i = 0; i < n; i++) {
            r = {};
            if (params.options !== undefined) {
                r.w = new Worker (params.blobURL, params.options);
            }
            else {
                r.w = new Worker (params.blobURL);
            }
            if (r.w == null) return null;
            r.call = function (r) {
                return function (params, transferList, excluded) {
                    var e;
                    if (excluded === true) {
                        r.excluded = true;
                        r.w.postMessage({
                            type: "sync",
                            params: params
                        }, transferList);
                    }
                    else {
                        e = new Error();
                        e = e.stack || "";
                        core.insertCall(r.w, {
                            type: "sync",
                            params: params,
                        }, e, transferList);
                    }
                };
            } (r);
            r.acall = function (r) {
                return function (params, transferList, excluded) {
                    var e;
                    if (excluded === true) {
                        r.excluded = true;
                        r.w.postMessage({
                            type: "async",
                            params: params
                        }, transferList);
                    }
                    else {
                        e = new Error();
                        e = e.stack || "";
                        core.insertCall(r.w, {
                            type: "async",
                            params: params
                        }, e, transferList);
                    }
                };
            }(r);
            r.terminate = function (r) {
                return function () {
                    thread_retval.close(r);
                };
            }(r);
            if (params.callbackfunc !== undefined) {
                r.w.onmessage = function(r) {
                    return function (e) {
                        thread_retval.setTimeout({
                            func: params.callbackfunc,
                            args: [e.data]
                        });
                        if (r.excluded) {
                            delete r.excluded;
                        }
                        else {
                            core.activeThreadCount--;
                            core.execCall();
                        }
                    }
                } (r);
                r.w.onerror = function(r, errorFunc) {
                    return function (e) {
                        if (errorFunc !== undefined) {
                            thread_retval.setTimeout({
                                func: params.errorFunc,
                                args: [e]
                            });
                        }
                        if (r.excluded) {
                            delete r.excluded;
                        }
                        else {
                            core.activeThreadCount--;
                            core.execCall();
                        }
                    }
                } (r, params.errorFunc);
            }
            rv.push(r);
        }
        return rv;
    };

    var voidBlob = thread_retval.generateBlob({
        func: function (params) {
            return null;
        }
    });

    var voidWorker = null;
    var voidQueue = [];
    var voidExpired = 0;

    var voidThread = function () {
        var t;
        if (voidQueue.length > 0) {
            if (voidWorker === null) {
                voidWorker = thread_retval.createFromBlob({
                    blobURL: voidBlob,
                    callbackfunc: function () {
                        voidExpired = (new Date()).getTime() + 1000;
                        core.rawSetTimeout(voidThread, 1);
                    },
                    n: 1
                }) [0];
            }
            t = voidQueue.shift();
            voidWorker.call({data: t}, [t.buffer], true);
            return;
        }
        if (voidWorker !== null) {
            if ((new Date()).getTime() > voidExpired) {
                thread_retval.close(voidWorker);
                voidWorker = null;
            }
        }
        core.rawSetTimeout(voidThread, 1);
    }

    core.rawSetTimeout(voidThread, 1);

    thread_retval.delete = function (data) {
        var ok = false;
        if (data === undefined) return;
        if (data === null) return;
        if ((typeof(data)).toLowerCase() != "object") return;
        if (data.buffer === undefined) return;
        if ((typeof(data.buffer)).toLowerCase() != "object") return;
        if (data instanceof Int8Array) ok = true;
        if (data instanceof Uint8Array) ok = true;
        if (data instanceof Int16Array) ok = true;
        if (data instanceof Uint16Array) ok = true;
        if (data instanceof Int32Array) ok = true;
        if (data instanceof Uint32Array) ok = true;
        if (data instanceof Float32Array) ok = true;
        if (data instanceof Float64Array) ok = true;
        if (window.BigUint64Array && (data instanceof BigUint64Array)) ok = true;
        if (window.BigInt64Array && (data instanceof BigInt64Array)) ok = true;
        if (ok) voidQueue.push(data);
    }

    thread_retval.createWorkerPool = function (params) {
        var host = {
            maxThread: params.maxThread,
            queue: [],
            pool: [],
            threadCount: 0,
            terminateRequest: false
        };
        var retval = {};
        var modules, extcode, keys, i;
        if (host.maxThread === undefined) host.maxThread = navigator.hardwareConcurrency;
        if (EncodingClass.type.isString(host.maxThread)) host.maxThread = parseInt(host.maxThread);
        if (!EncodingClass.type.isNumber(host.maxThread)) host.maxThread = navigator.hardwareConcurrency;

        if (params.extcode !== undefined) {
            extcode = params.extcode;
        }
        else {
            extcode = "";
        }
        if (params.modules !== undefined) {
            modules = params.modules;
        }
        else {
            modules = {};
        }
        host.blob = thread_retval.generateBlob({
            extcode: extcode,
            modules: modules,
            func: params.func,
            afunc: params.afunc
        });

        if (params.func !== undefined) {
            retval.call = function (params) {
                host.queue.push({
                    type: "sync",
                    params: params.params,
                    excluded: params.excluded,
                    callbackfunc: params.callbackfunc,
                    transferList: params.transferList
                });
            };
            retval.promiseCall = function (params) {
                var thost = {};
                host.queue.push({
                    type: "sync",
                    params: params.params,
                    excluded: params.excluded,
                    transferList: params.transferList,
                    callbackfunc: function (retval) {
                        thost.resolve(retval);
                    }
                });
                return new Promise(function(resolve, reject) {
                    thost.resolve = resolve;
                    thost.reject = reject;
                });
            }
        }

        if (params.afunc !== undefined) {
            retval.acall = function (params) {
                host.queue.push({
                    type: "async",
                    params: params.params,
                    excluded: params.excluded,
                    callbackfunc: params.callbackfunc,
                    transferList: params.transferList
                });
            };
            retval.promiseACall = function (params) {
                var thost = {};
                host.queue.push({
                    type: "async",
                    params: params.params,
                    excluded: params.excluded,
                    transferList: params.transferList,
                    callbackfunc: function (retval) {
                        thost.resolve(retval);
                    }
                });
                return new Promise(function(resolve, reject) {
                    thost.resolve = resolve;
                    thost.reject = reject;
                });
            }
        }

        retval.close = function (me) {
            return function () {
                var keys, i;
                host.terminateRequest = true;
                delete me.maxThread;
                delete me.threadCount;
                keys = Object.keys(me);
                for (i = 0; i < keys.length; i++) {
                    delete me[keys[i]];
                }
            }
        } (retval);

        Object.defineProperty(retval, "maxThread", {
            configurable: true,
            get: function (host) {
                return function () {
                    return host.maxThread;
                }
            } (host),
            set: function (host) {
                return function (value) {
                    if (value === undefined) return;
                    if (!EncodingClass.type.isNumber(value)) return;
                    if (value < 1) return;
                    host.maxThread = value;
                }
            } (host)
        });

        Object.defineProperty(retval, "threadCount", {
            configurable: true,
            get: function (host) {
                return function () {
                    return host.threadCount;
                }
            } (host)
        });

        host.thread = function () {
            var instance, etime;
            var stime = (new Date()).getTime();
            var ttime;
            while ((host.queue.length > 0) && (host.threadCount < host.maxThread)) {
                if (host.pool.length == 0) {
                    instance = {};
                    instance.thread = thread_retval.createFromBlob({
                        blobURL: host.blob,
                        callbackfunc: function (me) {
                            return function (retval) {
                                me.callbackfunc(retval);
                            }
                        } (instance)
                    })[0];
                    instance.exec = function (me) {
                        return function () {
                            var task = host.queue.shift();
                            me.task = task.callbackfunc;
                            if (task.type == "sync") {
                                me.thread.call(task.params, task.transferList, task.excluded);
                            }
                            else {
                                me.thread.acall(task.params, task.transferList, task.excluded);
                            }
                        }
                    } (instance);
                }
                else {
                    instance = host.pool.shift().instance;
                }
                instance.callbackfunc = function (me) {
                    return function (retval) {
                        thread_retval.setTimeout({
                            func: me.task,
                            args: [retval]
                        });
                        if (host.queue.length > 0) {
                            me.exec();
                        }
                        else {
                            host.pool.push({
                                instance: me,
                                time: (new Date()).getTime()
                            });
                            host.threadCount--;
                        }
                    }
                } (instance);
                instance.exec();
                host.threadCount++;
                ttime = (new Date()).getTime();
                if (ttime - stime > 40) break;
            }
            if ((host.queue.length > 0) && (host.threadCount < host.maxThread)) {
                thread_retval.setTimeout({func: host.thread});
                return;
            }
            etime = (new Date()).getTime() - 5000;
            while (host.pool.length > 0) {
                if (host.pool[0].time > etime) break;
                host.pool.shift().instance.thread.terminate();
            }
            if ((host.queue.length == 0) && (host.threadCount == 0) && (host.terminateRequest === true)) {
                var xurl = window.URL || window.webkitURL;
                var keys, i;
                while (host.pool.length > 0) {
                    host.pool.shift().instance.thread.terminate();
                }
                thread_retval.setTimeout({
                    func: xurl.revokeObjectURL,
                    args: [host.blob],
                    time: 5000
                });
                keys = Object.keys(host);
                for (i = 0; i < keys.length; i++) {
                    delete host[keys[i]];
                }
                return;
            }
            thread_retval.setTimeout({
                func: host.thread,
                time: 5
            });
        }
        host.thread();

        return Object.freeze(retval);
    };

    thread_retval.create = function (params) {
        var blobURL = thread_retval.generateBlob(params);
        if (blobURL == null) return null;
        var x = thread_retval.createFromBlob({
            blobURL: blobURL,
            callbackfunc: params.callbackfunc
        });
        if (EncodingClass.type.isArray(x)) return x[0];
        return null;
    };

    thread_retval.close = function (r) {
        r.w.terminate();
        delete r.w;
        delete r.call;
        delete r.acall;
        delete r.terminate;
    };

    thread_retval.hookError = function (f) {
        var i;
        if (!EncodingClass.type.isFunction(f)) return false;
        for (i = 0; i < core.hookList.length; i++) {
            if (core.hookList[i] === f) return false;
        }
        core.hookList.push(f);
        return true;
    }

    thread_retval.reportError = function (message) {
        var index = 0;
        var callstack, isCallstackPopulated = false;
        var r;
        if (core.hookList.length == 0) return;
        try {
            callstack.error = "this is error";
        }
        catch (e) {
            callstack = [];
            if (e.stack) { //Firefox
                var lines = e.stack.split('\n');
                for (var i = 0, len = lines.length; i < len; i++) {
                    if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                        callstack.push(lines[i]);
                    }
                }
                //Remove call to printStackTrace()
                callstack.shift();
                isCallstackPopulated = true;
            }
            else if (window.opera && e.message) { //Opera
                var lines = e.message.split('\n');
                for (var i = 0, len = lines.length; i < len; i++) {
                    if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                        var entry = lines[i];
                        //Append next line also since it has the file info
                        if (lines[i+1]) {
                            entry += " at " + lines[i+1];
                            i++;
                        }
                        callstack.push(entry);
                    }
                }
                //Remove call to printStackTrace()
                callstack.shift();
                isCallstackPopulated = true;
            }
        }
        if (!isCallstackPopulated) { //IE and Safari
            var currentFunction = arguments.callee.caller;
            callstack = [];
            while (currentFunction) {
                var fn = currentFunction.toString();
                var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous';
                callstack.push(fname);
                currentFunction = currentFunction.caller;
            }
        }
        if ((message === undefined) || (message === null)) message = "";
        r = {
            message: message,
            callstack: callstack
        };
        if (core.hookList.length > 1) {
            thread_retval.exec(
                function () {
                    if (index >= core.hookList.length) return true;
                    try {
                        core.hookList[index++](EncodingClass.string.duplicateObject(r));
                    }
                    catch (e) {
                    }
                    return false;
                }
            );
        }
        else {
            try {
                core.hookList[0](r);
            }
            catch (e) {
            }
        }
        throw new Error(r.message);
    };

    var errorHandlerList = [];

    thread_retval.addErrorHandler = function (handler) {
        var i;
        if (!EncodingClass.type.isFunction(handler)) return;
        for (i = 0; i < errorHandlerList.length; i++) {
            if (handler === errorHandlerList[i]) return;
        }
        errorHandlerList.push(handler);
    }

    var oldbrowser = false;

    var meH = function (event) {
        var i, nevent = EncodingClass.string.duplicateObject(event);
        var error, perror;
        var sindex, sx, sr, sc;
        if (event.promise !== undefined) {
            perror = event.promise.traceError;
        }
        error = event.error || event.reason || perror;
        if (error === undefined) {
            oldbrowser = true;
        }
        else if (error.stack === undefined) {
            oldbrowser = true;
        }
        else {
            nevent = {
                isTrusted: true,
                error: error,
                message: error.message + "\n" + error.stack,
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno,
                timeStamp: event.timeStamp,
                type: event.type,
                target: event.target,
                srcElement: event.srcElement,
                currentTarget: event.currentTarget,
                defaultPrevented: false
            }
            if (nevent.message === undefined) nevent.message = "";
            if (nevent.filename === undefined) nevent.filename = "";
            if (nevent.lineno === undefined) nevent.lineno = 0;
            if (nevent.colno === undefined) nevent.colno = 0;
            if ((nevent.filename == "") && (nevent.lineno == 0) && (nevent.colno == 0) && (error.stack !== undefined)) {
                sindex = error.stack.indexOf(" at ");
                if (sindex >= 0) {
                    sx = error.stack.substr(sindex + 4);
                    sindex = sx.indexOf("\n");
                    if (sindex >= 0) {
                        sx = sx.substr(0, sindex);
                        sindex = sx.lastIndexOf(":");
                        if (sindex >= 0) {
                            sc = parseInt(sx.substr(sindex + 1));
                            sx = sx.substr(0, sindex);
                            sindex = sx.lastIndexOf(":");
                            if (sindex >= 0) {
                                sr = parseInt(sx.substr(sindex + 1));
                                nevent.filename = sx.substr(0, sindex);
                                nevent.lineno = sr;
                                nevent.colno = sc;
                            }
                        }
                    }
                }
            }
        }
        for (i = 0; i < errorHandlerList.length; i++) {
            try {
                errorHandlerList[i](nevent);
            }
            catch (e) {
            }
        }
        if (nevent.defaultPrevented === true) event.defaultPrevented = true;
    }

    thread_retval.sendError = function (filename, message, stack) {
        try {
            meH({
                isTrusted: true,
                error: {
                    message: message,
                    stack: stack
                },
                message: message + "\n" + stack,
                filename: filename,
                lineno: 0,
                colno: 0,
                timeStamp: (new Date()).getTime(),
                type: "Error",
                target: window,
                srcElement: document.body,
                currentTarget: window
            });
        }
        catch (e) {
        }
    }

    window.addEventListener("error", meH);
    window.addEventListener("unhandledrejection", meH);

    var debugMode = false;

    Object.defineProperty(thread_retval, 'debugMode', {
        get: function () {
            return debugMode;
        },
        set: function (value) {
            if ((value === true) || (value === false)) debugMode = value;
        }
    });

    core.execFunc = function (func, params) {
        var r, ne;
        var t = (new Date()).getTime();
        var i;
        if ((errorHandlerList.length > 0) && (oldbrowser)) {
            try {
                r = func(...params);
                t = (new Date()).getTime() - t;
            }
            catch (e) {
                t = (new Date()).getTime() - t;
                ne = new Error(e);
                ne.error = e;
                if (e.stack !== undefined) {
                    ne.message = e.message + "\r\n" + e.stack;
                }
                meH(ne);
            }
        }
        else {
            r = func(...params);
            t = (new Date()).getTime() - t;
        }
        if (t > 150) {
            if (func.name !== undefined) {
                console.log("slow function call (" + t + "), ", func.name, {func: func});
            }
            else {
                console.log("slow function call (" + t + "), ", {func: func});
            }
        }
        return r;
    }

    thread_retval.execFunc = function (func, params) {
        return core.execFunc(func, params);
    }

    /*
    Promise.prototype.constructor = function (oldfunc) {
        return function (f) {
            return oldfunc.apply(this, function (resolve, reject) {
                return core.execFunc(f, [resolve, reject]);
            });
        }
    } (Promise.prototype.constructor);

    Promise.prototype.then = function (oldfunc) {
        return function (onFulfilled, onRejected) {
            return oldfunc.apply(this,
                [function (...args) {
                    if (EncodingClass.type.isFunction(onFulfilled)) {
                        return core.execFunc(onFulfilled, args);
                    }
                    else if (args.length == 1) {
                        return args[0];
                    }
                    else {
                        return args;
                    }
                },
                function (...args) {
                    if (EncodingClass.type.isFunction(onRejected)) {
                        return core.execFunc(onRejected, args);
                    }
                    else if (args.length == 1) {
                        throw args[0];
                    }
                    else {
                        throw args;
                    }
                }]
            );
        }
    } (Promise.prototype.then);
    */

    var threadQueue = [], threadPrepareQueue = [], inexec = false;

    var threadCallExec = function (host) {
        if (host.handler !== undefined) {
            try {
                core.execFunc(host.func, host.args);
            }
            catch (e) {
                core.execFunc(host.handler, [{
                    type: "run-time",
                    message: "run-time error",
                    content: e
                }]);
            }
            delete host.handler;
        }
        else {
            core.execFunc(host.func, host.args);
        }
        delete host.func;
        delete host.args;
    }

    var timecmp = function (a, b) {
        if (a.time < b.time) return -1;
        if (a.time > b.time) return 1;
        if (a.index < b.index) return -1;
        if (a.index > b.index) return 1;
        return 0;
    }

    var pushThreadQueue = function (pr, data) {
        var index, hindex, t;
        if (threadQueue[pr] === undefined) threadQueue[pr] = [];
        index = threadQueue[pr].length;
        threadQueue[pr].push(data);
        while (index > 0) {
            hindex = ((index + 1) >> 1) - 1;
            if (timecmp(threadQueue[pr][hindex], threadQueue[pr][index]) <= 0) break;
            t = threadQueue[pr][index];
            threadQueue[pr][index] = threadQueue[pr][hindex];
            threadQueue[pr][hindex] = t;
            index = hindex;
        }
    }

    var popThreadQueue = function (pr) {
        var r, index, index1, index2, t;
        var index, index1, index2;
        if (threadQueue[pr].length == 1) return threadQueue[pr].pop();
        r = threadQueue[pr][0];
        threadQueue[pr][0] = threadQueue[pr].pop();
        index = 0;
        while (true) {
            index2 = (index << 1) + 2;
            index1 = index2 - 1;
            if (index1 >= threadQueue[pr].length) break;
            if (index2 < threadQueue[pr].length) {
                if (timecmp(threadQueue[pr][index2], threadQueue[pr][index1]) < 0) index1 = index2;
            }
            if (timecmp(threadQueue[pr][index], threadQueue[pr][index1]) <= 0) break;
            t = threadQueue[pr][index];
            threadQueue[pr][index] = threadQueue[pr][index1];
            threadQueue[pr][index1] = t;
            index = index1;
        }
        return r;
    }

    var removeThreadQueue = function (pr, index) {
        var hindex, index1, index2, t, mode;
        if (index >= threadQueue[pr].length) return;
        if (index == threadQueue[pr].length - 1) {
            threadQueue[pr].pop();
            return;
        }
        threadQueue[pr][index] = threadQueue[pr].pop();
        if (index == 0) {
            mode = 1;
        }
        else {
            hindex = ((index + 1) >> 1) - 1;
            if (timecmp(threadQueue[pr][hindex], threadQueue[pr][index]) <= 0) {
                mode = 1;
            }
            else {
                mode = 0;
            }
        }
        if (mode == 0) {
            while (index > 0) {
                hindex = ((index + 1) >> 1) - 1;
                if (timecmp(threadQueue[pr][hindex], threadQueue[pr][index]) <= 0) break;
                t = threadQueue[pr][index];
                threadQueue[pr][index] = threadQueue[pr][hindex];
                threadQueue[pr][hindex] = t;
                index = hindex;
            }
        }
        else {
            while (true) {
                index2 = (index << 1) + 2;
                index1 = index2 - 1;
                if (index1 >= threadQueue[pr].length) break;
                if (index2 < threadQueue[pr].length) {
                    if (timecmp(threadQueue[pr][index2], threadQueue[pr][index1]) < 0) index1 = index2;
                }
                if (timecmp(threadQueue[pr][index], threadQueue[pr][index1]) <= 0) break;
                t = threadQueue[pr][index];
                threadQueue[pr][index] = threadQueue[pr][index1];
                threadQueue[pr][index1] = t;
                index = index1;
            }
        }
    }

    var lastnow = 0, lastnowindex = 0, lasttimeoutid = 0;

    var addPrepareQueue = function () {
        var i, pr;
        var now = (new Date()).getTime() + 1;
        for (i = 0; i < threadPrepareQueue.length; i++) {
            pr = threadPrepareQueue[i].pr;
            pushThreadQueue(pr, {
                id: threadPrepareQueue[i].id,
                func: threadPrepareQueue[i].func,
                args: threadPrepareQueue[i].args,
                handler: threadPrepareQueue[i].handler,
                time: now + threadPrepareQueue[i].time,
                index: threadPrepareQueue[i].index
            });
        }
        threadPrepareQueue = [];
    }

    var threadQueueExec = function () {
        var now = (new Date()).getTime();
        var i, pr, pList, ftime, fpr, ok = false;
        inexec = true;
        pList = Object.keys(threadQueue);
        for (i = 0; i < pList.length; i++) {
            pList[i] = parseInt(pList[i]);
        }
        pList.sort((a, b) => (b - a));
        core.rawSetTimeout(threadQueueExec, 1);
        addPrepareQueue();
        for (i = 0; i < pList.length; i++) {
            pr = pList[i];
            while (threadQueue[pr].length > 0) {
                if (((threadQueue[pr][0].time <= now) && (!ok)) || (threadQueue[pr][0].time < now)) {
                    threadCallExec(popThreadQueue(pr));
                    ok = true;
                }
                else {
                    break;
                }
            }
        }
        inexec = false;
        addPrepareQueue();
    }

    threadQueueExec();
    //setInterval(threadQueueExec, 2);

    window.setTimeout = function (func, time, ...args) {
        return Thread.setTimeout({
            func: func,
            args: args,
            time: time
        });
    }

    window.clearTimeout = function (oldfunc) {
        return function (timeoutID) {
            var i, j, pr;
            pList = Object.keys(threadQueue);
            for (i = 0; i < pList.length; i++) {
                pr = parseInt(pList[i]);
                for (j = 0; j < threadQueue[pr].length; j++) {
                    if (threadQueue[pr][j].id === timeoutID) {
                        removeThreadQueue(pr, j);
                        return;
                    }
                }
            }
            oldfunc(timeoutID);
        }
    } (window.clearTimeout);

    thread_retval.setTimeout = function (params) {
        var time, args, handler, priority, func, r;
        var now = (new Date()).getTime();
        if ((params.func === undefined) || (params.func === null) || ((!EncodingClass.type.isFunction(params.func)) && (!EncodingClass.type.isString(params.func))) ) {
            if (params.handler === undefined) {
                console.trace();
                console.error("Invalid function", params.func);
            }
            else {
                core.execFunc(params.handler, [{
                    type: "invalid",
                    message: "Invalid function",
                    content: {
                        func: params.func
                    }
                }]);
            }
            return;
        }
        if (now != lastnow) {
            lastnow = now;
            lastnowindex = 0;
        }
        time = params.time;
        args = params.args;
        handler = params.handler;
        priority = params.priority;
        func = params.func;
        if (EncodingClass.type.isString(func)) func = new Function(func);
        if (time === undefined) time = 0;
        if (!EncodingClass.type.isNumber(time)) time = 0;
        if (args === undefined) args = [];
        if (priority === undefined) priority = 0;
        if (!EncodingClass.type.isNumber(priority)) priority = 0;
        if (++lasttimeoutid >= 100000000000000) lasttimeoutid = 1;
        r = lasttimeoutid;
        threadPrepareQueue.push({
            pr: priority,
            id: r,
            func: func,
            args: args,
            handler: handler,
            time: time,
            index: lastnowindex++
        });
        if (!inexec) addPrepareQueue();
        return r;
    };

    thread_retval.wait = function (waitFunc, callbackfunc, errorHandler) {
        var host = {
            waitFunc: waitFunc,
            callbackfunc: callbackfunc,
            errorHandler: errorHandler
        };
        host.waitThread = function (host) {
            return function () {
                try {
                    if (host.waitFunc()) {
                        thread_retval.setTimeout({
                            func: host.callbackfunc,
                            time: 0,
                            args: [],
                            handler: host.errorHandler
                        });
                        delete host.waitFunc;
                        delete host.callbackfunc;
                        delete host.errorHandler;
                        delete host.waitThread;
                        return;
                    }
                }
                catch (e) {
                    if (host.errorHandler !== undefined) {
                        core.rawSetTimeout(function (func, e) {
                            return function () {
                                func(e);
                            }
                        } (host.errorHandler, e), 0);
                    }
                    else {
                        console.log("waitFunc error", e);
                    }
                }
                thread_retval.setTimeout({
                    func: host.waitThread,
                    time: 2
                });
            }
        } (host);
        thread_retval.setTimeout({
            func: host.waitThread
        });
    };

    thread_retval.exec = function (func, callbackfunc) {
        var host = {
            func: func,
            callbackfunc: callbackfunc,
            imax: 1
        };
        host.execThread = function (host) {
            return function () {
                var stime = (new Date()).getTime();
                var xtime = stime, ttime;
                var i, inloop = true;
                while (inloop) {
                    for (i = 0; i < host.imax; i++) {
                        if (host.func() === true) {
                            inloop = false;
                            break;
                        }
                    }
                    ttime = (new Date()).getTime();
                    if (ttime - xtime < 5) {
                        host.imax = ~~(host.imax * 1.1);
                    }
                    else {
                        i = ~~(host.imax * 0.9);
                        if (i < host.imax) {
                            host.imax = i;
                        }
                        else {
                            host.imax--;
                        }
                        if (host.imax < 1) host.imax = 1;
                    }
                    if (ttime - stime > 40) break;
                    xtime = ttime;
                }
                if (inloop) {
                    thread_retval.setTimeout({ func: host.execThread });
                }
                else {
                    if (host.callbackfunc !== undefined) {
                        if (EncodingClass.type.isFunction(host.callbackfunc)) thread_retval.setTimeout({ func: host.callbackfunc });
                    }
                    delete host.func;
                    delete host.callbackfunc;
                    delete host.imax;
                    delete host.execThread;
                }
            }
        } (host);
        thread_retval.setTimeout({ func: host.execThread });
    };

    thread_retval.waitPromise = function (waitFunc) {
        var host = {
            waitFunc: waitFunc
        };
        r = new Promise(function (host) {
            return function(resolve, reject) {
                host.resolve = resolve;
                host.reject = reject;
            }
        } (host));
        var wf2 = function (host) {
            return function () {
                if (host.resolve === undefined) return false;
                return host.waitFunc();
            }
        } (host);
        thread_retval.wait(
            wf2,
            function (host) {
                return function () {
                    host.resolve();
                }
            } (host),
            function (host) {
                return function () {
                    host.reject();
                }
            } (host)
        );
        return r;
    };

    thread_retval.serializeThread = function (host) {
        var t;
        if (host.terminateRequest) {
            host.status = "terminated";
            return;
        }
        if (EncodingClass.type.isFunction(host.content[host.step].condition)) {
            t = host.content[host.step].condition(host.lastRetval, host);
        }
        else if (EncodingClass.type.isNumber) {
            t = host.content[host.step].condition != 0;
        }
        else {
            t = host.content[host.step].condition;
        }
        if ((t === true) && (!host.terminateRequest)) {
            host.status = "running";
            host.lastRetval = host.content[host.step].task(host.lastRetval, host);
            host.status = "idle";
            host.step++;
        }
        if (host.step < host.content.length) {
            core.rawSetTimeout(function (host) {
                thread_retval.serializeThread(host);
            } (host), 0);
        }
        else {
            host.status = "finished";
        }
    };

    thread_retval.serialize = function (params) {
        var retval = {params: params.params};
        var temp = {
            step: 0,
            terminateRequest: false,
            status: "idle",
            lastRetval: null,
            content: []
        };
        var i, t;
        if (!EncodingClass.type.isArray(params)) return thread_retval.serialize([params]);
        for (i = 0; i < params.length; i++) {
            t = {};
            if (params[i].condition === undefined) {
                t.condition = true;
            }
            else {
                t.condition = params[i].condition;
            }
            if (params[i].task === undefined) break;
            if (!EncodingClass.type.isFunction(params[i].task)) break;
            temp.content.push(t);
        }
        if (temp.content.length == 0) {
            Object.defineProperty(retval, 'step', {get: function () { return 0; }});
            Object.defineProperty(retval, 'length', {get: function () { return 0; }});
            Object.defineProperty(retval, 'status', {get: function () { return "finished"; }});
            retval.terminate = function () {};
        }
        else {
            Object.defineProperty(retval, 'step', {
                get: function (host) {
                    return function () {
                        return host.step;
                    }
                } (temp)
            });
            Object.defineProperty(retval, 'length', {
                get: function (host) {
                    return function () {
                        return host.content.length;
                    }
                } (temp)
            });
            Object.defineProperty(retval, 'status', {
                get: function (host) {
                    return function () {
                        return host.status;
                    }
                } (temp)
            });
            retval.terminate = function (host) {
                return function () {
                    host.terminateRequest = true;
                }
            } (temp);
            thread_retval.setTimeout({
                func: thread_retval.serializeThread,
                args: [temp],
                time: 5
            });
        }
        return retval;
    };

    thread_retval.testErrorBlob = function () {
        var blob = thread_retval.generateBlob({
            modules: {
                test: function () {
                    if (asdf) console.log("this is error");
                }
            },
            func: function (params) {
                test();
            }
        });
        var instance = thread_retval.createFromBlob({
            blobURL: blob,
            n: 1,
            callbackfunc: function () {
                console.log("error blob test finished");
            }
        }) [0];
        instance.call({});
    }

    return thread_retval;
} ());

VaKeR 2022